JohnEhlersFourierTransformLibrary "JohnEhlersFourierTransform"
Fourier Transform for Traders By John Ehlers, slightly modified to allow to inspect other than the 8-50 frequency spectrum.
reference:
www.mesasoftware.com
high_pass_filter(source) Detrended version of the data by High Pass Filtering with a 40 Period cutoff
Parameters:
source : float, data source.
Returns: float.
transformed_dft(source, start_frequency, end_frequency) DFT by John Elhers.
Parameters:
source : float, data source.
start_frequency : int, lower bound of the frequency window, must be a positive number >= 0, window must be less than or 30.
end_frequency : int, upper bound of the frequency window, must be a positive number >= 0, window must be less than or 30.
Returns: tuple with float, float array.
db_to_rgb(db, transparency) converts the frequency decibels to rgb.
Parameters:
db : float, decibels value.
transparency : float, transparency value.
Returns: color.
Arrays
harmonicpatterns1Library "harmonicpatterns1"
harmonicpatterns: methods required for calculation of harmonic patterns. Correction for library (missing export in line 303)
isGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isGartleyPattern: Checks for harmonic pattern Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Gartley. False otherwise.
isBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isBatPattern: Checks for harmonic pattern Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Bat. False otherwise.
isButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isButterflyPattern: Checks for harmonic pattern Butterfly
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Butterfly. False otherwise.
isCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isCrabPattern: Checks for harmonic pattern Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Crab. False otherwise.
isDeepCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isDeepCrabPattern: Checks for harmonic pattern DeepCrab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is DeepCrab. False otherwise.
isCypherPattern(xabRatio, axcRatio, xadRatio, err_min, err_max) isCypherPattern: Checks for harmonic pattern Cypher
Parameters:
xabRatio : AB/XA
axcRatio : XC/AX
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Cypher. False otherwise.
isSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isSharkPattern: Checks for harmonic pattern Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Shark. False otherwise.
isNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNenStarPattern: Checks for harmonic pattern Nenstar
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Nenstar. False otherwise.
isAntiNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiNenStarPattern: Checks for harmonic pattern Anti NenStar
Parameters:
xabRatio : - AB/XA
abcRatio : - BC/AB
bcdRatio : - CD/BC
xadRatio : - AD/XA
err_min : - Minumum error threshold
err_max : - Maximum error threshold
Returns: True if the pattern is Anti NenStar. False otherwise.
isAntiSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiSharkPattern: Checks for harmonic pattern Anti Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Shark. False otherwise.
isAntiCypherPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCypherPattern: Checks for harmonic pattern Anti Cypher
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Cypher. False otherwise.
isAntiCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCrabPattern: Checks for harmonic pattern Anti Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Crab. False otherwise.
isAntiButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiButterflyPattern: Checks for harmonic pattern Anti Butterfly
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Butterfly. False otherwise.
isAntiBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiBatPattern: Checks for harmonic pattern Anti Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Bat. False otherwise.
isAntiGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiGartleyPattern: Checks for harmonic pattern Anti Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Gartley. False otherwise.
isNavarro200Pattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNavarro200Pattern: Checks for harmonic pattern Navarro200
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Navarro200. False otherwise.
isHarmonicPattern(x, a, c, c, d, flags, errorPercent) isHarmonicPattern: Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
FunctionCosineSimilarityLibrary "FunctionCosineSimilarity"
Cosine Similarity method.
function(sample_a, sample_b) Measure the similarity of 2 vectors.
Parameters:
sample_a : float array, values.
sample_b : float array, values.
Returns: float.
diss(cosim) Dissimilarity helper function.
Parameters:
cosim : float, cosine similarity value (0 > 1)
Returns: float
ArrayOperationsLibrary "ArrayOperations"
Array element wise basic operations.
add(sample_a, sample_b) Adds sample_b to sample_a and returns a new array.
Parameters:
sample_a : values to be added to.
sample_b : values to add.
Returns: array with added results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
subtract(sample_a, sample_b) Subtracts sample_b from sample_a and returns a new array.
sample_a : values to be subtracted from.
sample_b : values to subtract.
Returns: array with subtracted results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
multiply(sample_a, sample_b) multiply sample_a by sample_b and returns a new array.
sample_a : values to multiply.
sample_b : values to multiply with.
Returns: array with multiplied results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
divide(sample_a, sample_b) Divide sample_a by sample_b and returns a new array.
sample_a : values to divide.
sample_b : values to divide with.
Returns: array with divided results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
power(sample_a, sample_b) power sample_a by sample_b and returns a new array.
sample_a : values to power.
sample_b : values to power with.
Returns: float array with power results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
remainder(sample_a, sample_b) Remainder sample_a by sample_b and returns a new array.
sample_a : values to remainder.
sample_b : values to remainder with.
Returns: array with remainder results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
equal(sample_a, sample_b) Check element wise sample_a equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
not_equal(sample_a, sample_b) Check element wise sample_a not equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
over_or_equal(sample_a, sample_b) Check element wise sample_a over or equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
under_or_equal(sample_a, sample_b) Check element wise sample_a under or equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
over(sample_a, sample_b) Check element wise sample_a over sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
under(sample_a, sample_b) Check element wise sample_a under sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
and_(sample_a, sample_b) Check element wise sample_a and sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
or_(sample_a, sample_b) Check element wise sample_a or sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
all(sample) Check element wise if all numeric samples are true (!= 0).
sample : values to check.
Returns: int.
any(sample) Check element wise if any numeric samples are true (!= 0).
sample : values to check.
Returns: int.
WIPNNetworkLibrary "WIPNNetwork"
this is a work in progress (WIP) and prone to have some errors, so use at your own risk...
let me know if you find any issues..
Method for a generalized Neural Network.
network(x) Generalized Neural Network Method.
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
FunctionPatternDecompositionLibrary "FunctionPatternDecomposition"
Methods for decomposing price into common grid/matrix patterns.
series_to_array(source, length) Helper for converting series to array.
Parameters:
source : float, data series.
length : int, size.
Returns: float array.
smooth_data_2d(data, rate) Smooth data sample into 2d points.
Parameters:
data : float array, source data.
rate : float, default=0.25, the rate of smoothness to apply.
Returns: tuple with 2 float arrays.
thin_points(data_x, data_y, rate) Thin the number of points.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
rate : float, default=2.0, minimum threshold rate of sample stdev to accept points.
Returns: tuple with 2 float arrays.
extract_point_direction(data_x, data_y) Extract the direction each point faces.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
Returns: float array.
find_corners(data_x, data_y, rate) ...
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
rate : float, minimum threshold rate of data y stdev.
Returns: tuple with 2 float arrays.
grid_coordinates(data_x, data_y, m_size) transforms points data to a constrained sized matrix format.
Parameters:
data_x : float array, points x value.
data_y : float array, points y value.
m_size : int, default=10, size of the matrix.
Returns: flat 2d pseudo matrix.
FunctionBlackScholesLibrary "FunctionBlackScholes"
Some methods for the Black Scholes Options Model, which demonstrates several approaches to the valuation of a European call.
// reference:
// people.math.sc.edu
// people.math.sc.edu
asset_path(s0, mu, sigma, t1, n) Simulates the behavior of an asset price over time.
Parameters:
s0 : float, asset price at time 0.
mu : float, growth rate.
sigma : float, volatility.
t1 : float, time to expiry date.
n : int, time steps to expiry date.
Returns: option values at each equal timed step (0 -> t1)
binomial(s0, e, r, sigma, t1, m) Uses the binomial method for a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: option value at time 0.
bsf(s0, t0, e, r, sigma, t1) Evaluates the Black-Scholes formula for a European call.
Parameters:
s0 : float, asset price at time 0.
t0 : float, time at which the price is known.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
Returns: option value at time 0.
forward(e, r, sigma, t1, nx, nt, smax) Forward difference method to value a European call option.
Parameters:
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
nx : int, number of space steps in interval (0, L).
nt : int, number of time steps.
smax : float, maximum value of S to consider.
Returns: option values for the european call, float array of size ((nx-1) * (nt+1)).
mc(s0, e, r, sigma, t1, m) Uses Monte Carlo valuation on a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: confidence interval for the estimated range of valuation.
ArrayExtLibrary "ArrayExt"
Array extensions
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
get(a, idx) Get element from the array at index, or na if index not found
Parameters:
a : The array
idx : The array index to get
Returns: The array item if exists or na
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
set(a, idx, val) Set array item at index, if array has no index at the specified index, the array is filled with na
Parameters:
a : The array
idx : The array index to set
val : The value to be set
FunctionMinkowskiDistanceLibrary "FunctionMinkowskiDistance"
Method for Minkowski Distance,
The Minkowski distance or Minkowski metric is a metric in a normed vector space
which can be considered as a generalization of both the Euclidean distance and
the Manhattan distance.
It is named after the German mathematician Hermann Minkowski.
reference: en.wikipedia.org
double(point_ax, point_ay, point_bx, point_by, p_value) Minkowsky Distance for single points.
Parameters:
point_ax : float, x value of point a.
point_ay : float, y value of point a.
point_bx : float, x value of point b.
point_by : float, y value of point b.
p_value : float, p value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
Returns: float
ndim(point_x, point_y, p_value) Minkowsky Distance for N dimensions.
Parameters:
point_x : float array, point x dimension attributes.
point_y : float array, point y dimension attributes.
p_value : float, p value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
Returns: float
globalCurrently in PineScript you cannot modify global variables in functions because of scope limitations.
One way to work around that is to use arrays.
This Library simplifies the use of arrays as global variables to make your code look cleaner.
If you're coming from other programming languages, I'm sure you will come across this issue in your PineScript journey at some point.
------------------------------------
The code below will throw an error that says: Cannot modify global variable 'price' in function.
var price = 0.0
function() =>
price := 5.5
------------------------------------
To work around that you can do:
var price = array.new_float(1, 0.0)
function() =>
array.set(price, 0, 5.5)
But that code does not spark joy.
------------------------------------
So I bring to you the global library:
import marspumpkin/global/1
var price = global.init(0.0)
function() =>
global.set(price, 5.5)
FunctionGenerateRandomPointsInShapeLibrary "FunctionGenerateRandomPointsInShape"
Generate random vector points in geometric shape (parallelogram, triangle)
random_parallelogram(vector_a, vector_b) Generate random vector point in a parallelogram shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
random_triangle(vector_a, vector_b) Generate random vector point in a triangle shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
FunctionArrayNextPreviousLibrary "FunctionArrayNextPrevious"
Methods to iterate through a array by a fixed anchor point.
array_next(array, start_index) retrieves the next value of the internal pointer index.
Parameters:
array : (any array type), array to iterate.
start_index : int, anchor index to start indexing.
array_previous(array, start_index) retrieves the previous value of the internal pointer index.
Parameters:
array : (any array type), array to iterate.
start_index : int, anchor index to start indexing.
note: regrettably is not possible to have global reference index without juggling it in the parameters and tracking it externally to switch between next/previous
FunctionNNLayerLibrary "FunctionNNLayer"
Generalized Neural Network Layer method.
function(inputs, weights, n_nodes, activation_function, bias, alpha, scale) Generalized Layer.
Parameters:
inputs : float array, input values.
weights : float array, weight values.
n_nodes : int, number of nodes in layer.
activation_function : string, default='sigmoid', name of the activation function used.
bias : float, default=1.0, bias to pass into activation function.
alpha : float, default=na, if required to pass into activation function.
scale : float, default=na, if required to pass into activation function.
Returns: float
FunctionNNPerceptronLibrary "FunctionNNPerceptron"
Perceptron Function for Neural networks.
function(inputs, weights, bias, activation_function, alpha, scale) generalized perceptron node for Neural Networks.
Parameters:
inputs : float array, the inputs of the perceptron.
weights : float array, the weights for inputs.
bias : float, default=1.0, the default bias of the perceptron.
activation_function : string, default='sigmoid', activation function applied to the output.
alpha : float, default=na, if required for activation.
scale : float, default=na, if required for activation.
@outputs float
MLActivationFunctionsLibrary "MLActivationFunctions"
Activation functions for Neural networks.
binary_step(value) Basic threshold output classifier to activate/deactivate neuron.
Parameters:
value : float, value to process.
Returns: float
linear(value) Input is the same as output.
Parameters:
value : float, value to process.
Returns: float
sigmoid(value) Sigmoid or logistic function.
Parameters:
value : float, value to process.
Returns: float
sigmoid_derivative(value) Derivative of sigmoid function.
Parameters:
value : float, value to process.
Returns: float
tanh(value) Hyperbolic tangent function.
Parameters:
value : float, value to process.
Returns: float
tanh_derivative(value) Hyperbolic tangent function derivative.
Parameters:
value : float, value to process.
Returns: float
relu(value) Rectified linear unit (RELU) function.
Parameters:
value : float, value to process.
Returns: float
relu_derivative(value) RELU function derivative.
Parameters:
value : float, value to process.
Returns: float
leaky_relu(value) Leaky RELU function.
Parameters:
value : float, value to process.
Returns: float
leaky_relu_derivative(value) Leaky RELU function derivative.
Parameters:
value : float, value to process.
Returns: float
relu6(value) RELU-6 function.
Parameters:
value : float, value to process.
Returns: float
softmax(value) Softmax function.
Parameters:
value : float array, values to process.
Returns: float
softplus(value) Softplus function.
Parameters:
value : float, value to process.
Returns: float
softsign(value) Softsign function.
Parameters:
value : float, value to process.
Returns: float
elu(value, alpha) Exponential Linear Unit (ELU) function.
Parameters:
value : float, value to process.
alpha : float, default=1.0, predefined constant, controls the value to which an ELU saturates for negative net inputs. .
Returns: float
selu(value, alpha, scale) Scaled Exponential Linear Unit (SELU) function.
Parameters:
value : float, value to process.
alpha : float, default=1.67326324, predefined constant, controls the value to which an SELU saturates for negative net inputs. .
scale : float, default=1.05070098, predefined constant.
Returns: float
exponential(value) Pointer to math.exp() function.
Parameters:
value : float, value to process.
Returns: float
function(name, value, alpha, scale) Activation function.
Parameters:
name : string, name of activation function.
value : float, value to process.
alpha : float, default=na, if required.
scale : float, default=na, if required.
Returns: float
derivative(name, value, alpha, scale) Derivative Activation function.
Parameters:
name : string, name of activation function.
value : float, value to process.
alpha : float, default=na, if required.
scale : float, default=na, if required.
Returns: float
MLLossFunctionsLibrary "MLLossFunctions"
Methods for Loss functions.
mse(expects, predicts) Mean Squared Error (MSE) " MSE = 1/N * sum ((y - y')^2) ".
Parameters:
expects : float array, expected values.
predicts : float array, prediction values.
Returns: float
binary_cross_entropy(expects, predicts) Binary Cross-Entropy Loss (log).
Parameters:
expects : float array, expected values.
predicts : float array, prediction values.
Returns: float
PointsLibrary "Points"
Provides functions for simplifying operations with collections of x+y coordinates. Where x is typically a bar index or time (millisecond) value.
new(size) Creates two arrays. One for X (int ) and another for Y (float ).
Parameters:
size : The initial size of the arrays.
size(xA, yA) Checks the size of the arrays and if they're equal returns the size.
Parameters:
xA : The X array.
yA : The Y array.
get(xA, yA, index) Gets the X and Y values of the arrays at the index.
Parameters:
xA : The X array.
yA : The Y array.
index : The index.
Returns:
set(xA, yA, index, x, y) Sets the X and Y values of the arrays at the index.
Parameters:
xA : The X array.
yA : The Y array.
index : The index.
x : The x value.
y : The y value.
Returns:
push(xA, yA, x, y) Adds X and Y values to the end of the arrays (as the last element).
Parameters:
xA : The X array.
yA : The Y array.
x : The x value.
y : The y value.
Returns:
unshift(xA, yA, x, y) Adds X and Y values to the beginning of the arrays (as the first element).
Parameters:
xA : The X array.
yA : The Y array.
x : The x value.
y : The y value.
Returns:
insert(xA, yA, index, x, y) Inserts X and Y values to the arrays at the index.
Parameters:
xA : The X array.
yA : The Y array.
index : The index to insert at.
x : The x value.
y : The y value.
Returns:
pop(xA, yA) Removes the last element from the arrays and returns their value.
Parameters:
xA : The X array.
yA : The Y array.
Returns:
shift(xA, yA) Removes the first element from the arrays and returns their value.
Parameters:
xA : The X array.
yA : The Y array.
Returns:
remove(xA, yA) Removes the element from the arrays at the index and returns their value.
Parameters:
xA : The X array.
yA : The Y array.
Returns:
first(xA, yA) Gets the X and Y values of the first element.
Parameters:
xA : The X array.
yA : The Y array.
Returns:
last(xA, yA) Gets the X and Y values of the last element.
Parameters:
xA : The X array.
yA : The Y array.
Returns:
allIndexesBetween(xA, lo, hi, start, ordered) Gets the indexes that have values at or above the low value and below the high value.
Parameters:
xA : The X array.
lo : The inclusive low value.
hi : The excluded hi value.
start : The optional index to start the backwards search.
ordered : If true, the search ends when the first value is found that is less than the low.
lastIndexBetween(xA, lo, hi, start, ordered) Gets the first found from the end that has a value at or above the low value and below the high value.
Parameters:
xA : The X array.
lo : The inclusive low value.
hi : The excluded hi value.
start : The optional index to start the backwards search.
ordered : If true, the search ends when the first value is found that is less than the low.
lastIndexBelow(xA, hi, start) Gets the first found from the end that has a value below the high value.
Parameters:
xA : The X array.
hi : The excluded hi value.
start : The optional index to start the backwards search.
eHarmonicpatternsLibrary "eHarmonicpatterns"
Library provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations
scan_xab(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : AB/XA ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) Checks if abc or axc ratio is in range of any harmonic pattern
Parameters:
abcRatio : BC/AB ratio
axcRatio : XC/AX ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_bcd(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : CD/BC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray) Checks if xad or xcd ratio is in range of any harmonic pattern
Parameters:
xadRatio : AD/XA ratio
xcdRatio : CD/XC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
isHarmonicPattern(x, a, c, c, d, flags, errorPercent) Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, c, c, flags, errorPercent) Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
hashmapsA simple hashmap implementation for pinescript.
It gets your string array and transforms it into a hashmap.
Before using it you need to initialize your array with the size you need for your specific case since the size is not dynamic.
To use it, first you need to import it the following way:
> import marspumpkin/hashmaps/1
Then, initialize your array with the size needed for your specific case:
> hashmap = array.new_string(10000)
After that you can call:
> hashmaps.put() and hashmaps.get()
Passing in the array(hashmap), key and value.
I hope this helps you in your pinescript journey.
Dictionary/Object LibraryThis Library is aimed to mitigate the limitation of Pinescript having only one structured data type which is only arrays.
It lacks data types like Dictionaries(in Python) or Object (in JS) that are standard for other languages. Tuples do exist, but it hardly solves any problem.
Working only with Arrays could be overwhelming if your codebase is large. I looked for alternatives to arrays but couldn't find any library.
So I coded it myself and it's been working good for me. So I wanted to share it with you all.
What does it do:
==================
If you are familiar with Python or Javascript, this library tries to immimate Object/Dictonary like structure with Key Value Pairs.
For Example:
object= {name:"John Doe", age: 28 , org: "PineCoders"}
And then it also tries to immitate the Array of Objects (I call it Stack)
like this:
stack= Array({name:"John Doe", age: 28 , org: "PineCoders"},
{name:"Adam Smith", age: 32 , org: "PineCoders"},
{name:"Paragjyoti Deka", age: 25 , org: "PineCoders"})
So there are basically two ideas: Objects and Stacks.
But it looks whole different in Pinescript for obvious reasons.
Limitation:
The major limitation I couldn't overcome was that, for all of the values: both input and return values for properties will be of string type.
This is due to the limiation of Pinecsript that there is no way to return a value on a if-else statement dynamically with different data types.
And as the input data type must be explicitly defined when exporting the library functions, only string inputs are allowed.
Now that doesn't mean you won't be able to use integer, float or boolens, you just need to pass the string value for it using str.tostring() method.
And the output for the getter functions will be in strings as well. But I have added some type conversion methods that you could use from this library itself.
From String to Float, String To Integer and String to Boolean: these three methods are included in this library.
So basically the whole library is based on a manipulatiion of Array of strings under the hood.
///////////////
Usage
///////////////
Import the library using this statement:
import paragjyoti2012/STR_Dict_Lib/4 as DictLib
Objects
First define an object using this method:
for eample:
object1= DictLib.init("name=John,age=26,org=")
This is similar to
object1= {name:"John",age:"26", org:""} in JS or Python
Just like we did here in for "org", you can set initital value to "". But remember to pass string values, even for a numerical properties, like here in "age".
You can use "age="+str.tostring(age). If you find it tedious, you can always add properties later on using .set() method.
So it could also be initiated like this
object= DictLib.init("name=John")
and later on
DictLib.set(object1,"age", str.toString(age))
DictLib.set(object1,"org", "PineCoders")
The getter function looks like this
age= DictLib.get(object1,"age")
name=DictLib.get(object1,"name")
The first argument for all methods .get, .set, and .remove is the pointer (name of the object).
///////////////////////////
Array Of Objects (Stacks)
///////////////////////////
As I mentioned earlier, I call the array of objects as Stack.
Here's how to initialize a Stack.
stack= DictLib.initStack(object1)
The .initStack() method takes an object pointer as argument. It simply converts the array into a string and pushes it into the newly created stack.
Rest of all the methods for Stacks, takes the stack pointer as it's first arument.
For example:
DictLib.pushStack(stack,object2)
The second argument here is the object pointer. It adds the object to it's stack. Although it might feel like a two dimentional array, it's actually an one dimentional array with string values.
Under the hood, it looks like this
////////////////////
Methods
////////////////////
For Objects
-------------------
init() : Initializes the object.
params: (string) e.g
returns: The object ( )
example:
object1=DictLib.init("name=John,age=26,org=")
...................
get() : Returns the value for given property
params: (string object_pointer, string property)
returns: string
example:
age= DictLib.get(object1,"age")
.......................
set() : Adds a new property or updates an existing property
params: (string object_pointer, string property, string value)
returns: void
example:
DictLib.set(object1,"age", str.tostring(29))
........................
remove() : Removes a property from the object
params : (string object_pointer, string property)
returns: void
example:
DictLib.set(object1,"org")
........................
For Array Of Objects (Stacks)
-------------------------------
initStack() : Initializes the stack.
params: (string object_pointer) e.g
returns: The Stack
example:
stack= DictLib.initStack(object1)
...................
pushToStack() : Adds an object at at last index of the stack
params: (string stack_pointer, string object_pointer)
returns: void
example:
DictLib.pushToStack(stack,object2)
.......................
popFromStack() : Removes the last object from the stack
params: (string stack_pointer)
returns: void
example:
DictLib.popFromStack(stack)
.......................
insertToStack() : Adds an object at at the given index of the stack
params: (string stack_pointer, string object_pointer, int index)
returns: void
example:
DictLib.insertToStack(stack,object3,1)
.......................
removeFromStack() : Removes the object from the given index of the stack
params: (string stack_pointer, int index)
returns: void
example:
DictLib.removeFromStack(stack,2)
.......................
getElement () : Returns the value for given property from an object in the stack (index must be given)
params: (string stack_pointer, int index, string property)
returns: string
example:
ageFromObject1= DictLib.getElement(stack,0,"age")
.......................
setElement() : Updates an existing property of an object in the stack (index must be given)
params: (string stack_pointer, int index, string property, string value)
returns: void
example:
DictLib.setElement(stack,0,"age", str.tostring(32))
........................
includesElement() : Checks if any object exists in the stack with the given property-value pair
params : (string stack_pointer, string property, string value)
returns : Boolean
example:
doesExist= DictLib.includesElement(stack,"org","PineCoders")
........................
searchStack() : Search for a property-value pair in the stack and returns it's index
params: (stringp stack_pointer, string property, string value)
returns: int (-1 if doesn't exist)
example:
index= DictLib.searchElement(stack,"org","PineCoders")
///////////////////////
Type Conversion Methods
///////////////////////
strToFloat() : Converts String value to Float
params: (string value)
returns: float
example:
floatVal= DictLib.strToFloat("57.96")
.............................
strToInt() : Converts String value to Integer
params: (string value)
returns: int
example:
intVal= DictLib.strToFloat("45")
.............................
strToBool() : Converts String value to Boolean
params: (string value)
returns: boolean
example:
boolVal= DictLib.strToBool("true")
.............................
Points to remember
...............
1. Always pass string values as arguments.
2. The return values will be of type string, so convert them before to avoid typecasting conflict.
3. Horses can't vomit.
More Informations
====================
Yes, You can store this objects and stacks for persisting through the iterations of a script across successive bars.
You just need to set the variable using "var" keyword. Remember this objects and stacks are just arrays,
so any methods and properties an array have it pinescript, would be applicable for objects and stacks.
It can also be used in security functions without any issues for MTF Analysis.
If you have any suggestions or feedback, please comment on the thread, I would surely be happy to help.
FunctionPeakDetectionLibrary "FunctionPeakDetection"
Method used for peak detection, similar to MATLAB peakdet method
function(sample_x, sample_y, delta) Method for detecting peaks.
Parameters:
sample_x : float array, sample with indices.
sample_y : float array, sample with data.
delta : float, positive threshold value for detecting a peak.
Returns: tuple with found max/min peak indices.
AveragesLibrary "Averages"
Contains utilities for generating averages from arrays. Useful for manipulated or cleaned data.
triangular(src, startingWeight) Calculates the triangular weighted average of a set of values where the last value has the highest weight.
Parameters:
src : The array to derive the average from.
startingWeight : The weight to begin with when calculating the average. Higher numbers will decrease the bias.
weighted(src, weights, weightDefault) Calculates the weighted average of a set of values.
Parameters:
src : The array to derive the average from.
weights : The array containing the weights for the source.
weightDefault : The default value to use when a weight is NA.
triangularWeighted(src, weights, startingWeight) Calculates the weighted average of a set of values where the last value has the highest triangular multiple.
Parameters:
src : The array to derive the average from.
weights : The array containing the weights for the source.
startingWeight : The multiple to begin with when calculating the average. Higher numbers will decrease the bias.
exponential(src) Calculates the exponential average of a set of values where the last value has the highest weight.
Parameters:
src : The array to derive the average from.
arrayFrom(src, len, omitNA) Creates an array from the provided series (oldest to newest).
Parameters:
src : The array to derive from.
len : The target length of the array.
omitNA : If true, NA values will not be added to the array and the resultant array may be shorter than the target length.
arrayutilsLibrary "_arrayutils"
Library contains utility functions using arrays.
delete(arr, index)
remove an item from array at specific index. Also deletes the item
Parameters:
arr : - array from which the item needs to be deleted
index : - index of item to be deleted
Returns: void
pop(arr)
remove the last item from array. Also deletes the item
Parameters:
arr : - array from which the last item needs to be removed and deleted
Returns: void
shift(arr)
remove an item from array at index 0. Also deletes the item
Parameters:
arr : - array from which the first item needs to be removed and deleted
Returns: void
unshift(arr, val, maxItems)
add an item to the beginning of an array with max items cap
Parameters:
arr : - array to which the item needs to be added at the beginning
val : - value of item which needs to be added
maxItems : - max items array can hold. After that, items are removed from the other end
Returns: resulting array
clear(arr)
remove and delete all items in an array
Parameters:
arr : - array which needs to be cleared
Returns: void
push(arr, val, maxItems)
add an item to the end of an array with max items cap
Parameters:
arr : - array to which the item needs to be added at the beginning
val : - value of item which needs to be added
maxItems : - max items array can hold. After that, items are removed from the starting index
Returns: resulting array
check_overflow(pivots, barArray, dir)
finds difference between two timestamps
Parameters:
pivots : pivots array
barArray : pivot bar array
dir : direction for which overflow need to be checked
Returns: bool overflow
get_trend_series(pivots, length, highLow, trend)
finds series of pivots in particular trend
Parameters:
pivots : pivots array
length : length for which trend series need to be checked
highLow : filter pivot high or low
trend : Uptrend or Downtrend
Returns: int trendIndexes
get_trend_series(pivots, firstIndex, lastIndex)
finds series of pivots in particular trend
Parameters:
pivots : pivots array
firstIndex : First index of the series
lastIndex : Last index of the series
Returns: int trendIndexes
sma(source)
calculates sma for elements in array
Parameters:
source : source array
Returns: float sma
ema(source, length)
calculates ema for elements in array
Parameters:
source : source array
length : ema length
Returns: float ema
rma(source, length)
calculates rma for elements in array
Parameters:
source : source array
length : rma length
Returns: float rma
wma(source, length)
calculates wma for elements in array
Parameters:
source : source array
length : wma length
Returns: float wma
hma(source, length)
calculates hma for elements in array
Parameters:
source : source array
length : hma length
Returns: float hma
ma(source, matype, length)
wrapper for all moving averages based on array
Parameters:
source : source array
matype : moving average type. Valud values are: sma, ema, rma, wma and hma
length : moving average length length
Returns: float moving average
getFibSeries(numberOfFibs, start)
gets fib series in array
Parameters:
numberOfFibs : number of fibs
start : starting number
Returns: float fibArray