Reverse Ehler Instantaneous Trendline - TraderHalaiThis script uses a reverse function of the famous Ehler Instantaneous Trendline to calculate the source price required in order to change from Bullish to bearish
From my analysis, the reverse price does appear to be rather choppy, though it is 100% accurate. This is because Ehler's Instantaneous Trendline tends to remain trending for longer periods of time with above average hold periods.
The main suitability for this would be higher level timeframes, such as Weekly, 5 daily, 3 daily. From my findings Smoothed Heikin Ashi Trend, tends to provide better risk-adjusted returns across most timeframes (Higher return to drawdown ratio)
As I have spent a bit of time getting the reverse function mathematics to work, I decided to publish this as open source for the benefit, scrutiny and for further development by the TradingView community anyways.
Enjoy!
Function
FunctionDynamicTimeWarpingLibrary "FunctionDynamicTimeWarping"
"In time series analysis, dynamic time warping (DTW) is an algorithm for
measuring similarity between two temporal sequences, which may vary in
speed. For instance, similarities in walking could be detected using DTW,
even if one person was walking faster than the other, or if there were
accelerations and decelerations during the course of an observation.
DTW has been applied to temporal sequences of video, audio, and graphics
data — indeed, any data that can be turned into a linear sequence can be
analyzed with DTW. A well-known application has been automatic speech
recognition, to cope with different speaking speeds. Other applications
include speaker recognition and online signature recognition.
It can also be used in partial shape matching applications."
"Dynamic time warping is used in finance and econometrics to assess the
quality of the prediction versus real-world data."
~~ wikipedia
reference:
en.wikipedia.org
towardsdatascience.com
github.com
cost_matrix(a, b, w)
Dynamic Time Warping procedure.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: matrix optimum match matrix.
traceback(M)
perform a backtrace on the cost matrix and retrieve optimal paths and cost between arrays.
Parameters:
M : matrix, cost matrix.
Returns: tuple:
array aligned 1st array of indices.
array aligned 2nd array of indices.
float final cost.
reference:
github.com
report(a, b, w)
report ordered arrays, cost and cost matrix.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: string report.
FunctionKellyCriterionLibrary "FunctionKellyCriterion"
Kelly criterion methods.
the kelly criterion helps with the decision of how much one should invest in
a asset as long as you know the odds and expected return of said asset.
simplified(win_p, rr)
simplified version of the kelly criterion formula.
Parameters:
win_p : float, probability of winning.
rr : float, reward to risk rate.
Returns: float, optimal fraction to risk.
usage:
simplified(0.55, 1.0)
partial(win_p, loss_p, win_rr, loss_rr)
general form of the kelly criterion formula.
Parameters:
win_p : float, probability of the investment returns a positive outcome.
loss_p : float, probability of the investment returns a negative outcome.
win_rr : float, reward on a positive outcome.
loss_rr : float, reward on a negative outcome.
Returns: float, optimal fraction to risk.
usage:
partial(0.6, 0.4, 0.6, 0.1)
from_returns(returns)
Calculate the fraction to invest from a array of returns.
Parameters:
returns : array trade/asset/strategy returns.
Returns: float, optimal fraction to risk.
usage:
from_returns(array.from(0.1,0.2,0.1,-0.1,-0.05,0.05))
final_f(fraction, max_expected_loss)
Final fraction, eg. if fraction is 0.2 and expected max loss is 10%
then you should size your position as 0.2/0.1=2 (leverage, 200% position size).
Parameters:
fraction : float, aproximate percent fraction invested.
max_expected_loss : float, maximum expected percent on a loss (ex 10% = 0.1).
Returns: float, final fraction to invest.
usage:
final_f(0.2, 0.5)
hpr(fraction, trade, biggest_loss)
Holding Period Return function
Parameters:
fraction : float, aproximate percent fraction invested.
trade : float, profit or loss in a trade.
biggest_loss : float, value of the biggest loss on record.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
hpr(fraction=0.05, trade=0.1, biggest_loss=-0.2)
twr(returns, rr, eps)
Terminal Wealth Relative, returns a multiplier that can be applied
to the initial capital that leadds to the final balance.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, optimal fraction to invest.
usage:
twr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
ghpr(returns, rr, eps)
Geometric mean Holding Period Return, represents the average multiple made on the stake.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
ghpr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
run_coin_simulation(fraction, initial_capital, n_series, n_periods)
run multiple coin flipping (binary outcome) simulations.
Parameters:
fraction : float, fraction of capital to bet.
initial_capital : float, capital at the start of simulation.
n_series : int , number of simulation series.
n_periods : int , number of periods in each simulation series.
Returns: matrix(n_series, n_periods), matrix with simulation results per row.
usage:
run_coin_simulation(fraction=0.1)
run_asset_simulation(returns, fraction, initial_capital)
run a simulation over provided returns.
Parameters:
returns : array, trade, asset or strategy percent returns.
fraction : float , fraction of capital to bet.
initial_capital : float , capital at the start of simulation.
Returns: array, array with simulation results.
usage:
run_asset_simulation(returns=array.from(0.1,-0.2,0.-3,0.4), fraction=0.1)
strategy_win_probability()
calculate strategy() current probability of positive outcome in a trade.
strategy_avg_won()
calculate strategy() current average won on a trade with positive outcome.
strategy_avg_loss()
calculate strategy() current average lost on a trade with negative outcome.
FunctionArrayUniqueLibrary "FunctionArrayUnique"
Method for retrieving the unique elements in a array.
for example would retrieve a array with ,
the elements retrieved will be sorted by its first seen index in
parent array.
note: float values have no precision option.
unique(source)
method for retrieving the unique elements in a array.
Parameters:
source : array source array to extract elements.
Returns: array unique elements in the source array.
unique(source)
method for retrieving the unique elements in a array.
Parameters:
source : array source array to extract elements.
Returns: array unique elements in the source array.
unique(source)
method for retrieving the unique elements in a array.
Parameters:
source : array source array to extract elements.
Returns: array unique elements in the source array.
functionStringToMatrixLibrary "functionStringToMatrix"
Provides unbound methods (no error checking) to parse a string into a float or int matrix.
to_matrix_float(str, interval_sep, start_tk, end_tk)
Parse a string into a float matrix.
Parameters:
str : , string, the formated string to parse.
interval_sep : , string, cell interval separator token.
start_tk : , string, row start token.
end_tk : , string, row end token.
Returns: matrix, parsed float matrix.
to_matrix_int(str, interval_sep, start_tk, end_tk)
Parse a string into a int matrix.
Parameters:
str : , string, the formated string to parse.
interval_sep : , string, cell interval separator token.
start_tk : , string, row start token.
end_tk : , string, row end token.
Returns: matrix, parsed int matrix.
"Swap" - Bool/Position/Value : Array / Matrix / Var AutoswapLibrary "swap"
Side / Boundary Based All Types Swapper
- three automagical types for Arrays, Matrixes, and Variables
-- no signal : Long/ Short position autoswap
-- true / false : Boolean based side choice
-- Src / Thresh : if source is above or below the threshold
- two operating modes for variables, Holding mode only for arrays/matrixes
-- with two items, will automatically change between the two caveat is it does not delete table/box/line(fill VAR items automatically)
-- with three items, a neutral is available for NA input or neutral
- one function name for all of them. One import name that's easy to type/remember
-- make life easy for your conditional items.
side(source, thresh, _a, _b, _c)
side Change outputs based on position or a crossing level
Parameters:
source : (float) OPTIONAL value input
thresh : (float) OPTIONAL boundary line to cross
_a : (any) if Long/True/Above
_b : (any) if Short/False/Below
_c : (any) OPTIONAL NOT FOR MTX OR ARR... Neutral Item, if var/varip on a/b it will leave behind, ie, a table or box or line will not erase , if it's a varip you're sending in.
Returns: first, second, or third items based on input conditions
Please notify if bugs found.
Thanks.
Price Displacement - Candlestick (OHLC) CalculationsA Magical little helper friend for Candle Math.
When composing scripts, it is often necessary to manipulate the math around the OHLC. At times, you want a scalar (absolute) value others you want a vector (+/-). Sometimes you want the open - close and sometimes you want just the positive number of the body size. You might want it in ticks or you might want it in points or you might want in percentages. And every time you try to put it together you waste precious time and brain power trying to think about how to properly structure what you're looking for. Not to mention it's normally not that aesthetically pleasing to look at in the code.
So, this fixes all of that.
Using this library. A function like 'pd.pt(_exp)' can call any kind of candlestick math you need. The function returns the candlestick math you define using particular expressions.
Candle Math Functions Include:
Points:
pt(_exp) Absolute Point Displacement. Point quantity of given size parameters according to _exp.
vpt(_exp) Vector Point Displacement. Point quantity of given size parameters according to _exp.
Ticks:
tick(_exp) Absolute Tick Displacement. Tick quantity of given size parameters according to _exp.
vtick(_exp) Vector Tick Displacement. Tick quantity of given size parameters according to _exp.
Percentages:
pct(_exp, _prec) Absolute Percent Displacement. (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
vpct(_exp, _prec) Vector Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
Expressions You Can Use with Formulas:
The expressions are simple (simple strings that is) and I did my best to make them sensible, generally using just the ohlc abreviations. I also included uw, lw, bd, and rg for when you're just trying to pull a candle component out. That way you don't have to think about which of the ohlc you're trying to get just use pd.tick("uw") and now the variable is assigned the length of the upper wick, absolute value, in ticks. If you wanted the vector in pts its pd.vpt("uw"). It also makes changing things easy too as I write it out.
Expression List:
Combinations
"oh" = open - high
"ol" = open - low
"oc" = open - close
"ho" = high - open
"hl" = high - low
"hc" = high - close
"lo" = low - open
"lh" = low - high
"lc" = low - close
"co" = close - open
"ch" = close - high
"cl" = close - low
Candle Components
"uw" = Upper Wick
"bd" = Body
"lw" = Lower Wick
"rg" = Range
Pct() Only
"scp" = Scalar Close Position
"sop" = Scalar Open Position
"vcp" = Vector Close Position
"vop" = Vector Open Position
The attributes are going to be available in the pop up dialogue when you mouse over the function, so you don't really have to remember them. I tried to make that look as efficient as possible. You'll notice it follows the OHLC pattern. Thus, "oh" precedes "ho" (heyo) because "O" would be first in the OHLC. Its a way to help find the expression you're looking for quickly. Like looking through an alphabetized list for traders.
There is a copy/paste console friendly helper list in the script itself.
Additional Notes on the Pct() Only functions:
This is the original reason I started writing this. These concepts place a rating/value on the bar based on candle attributes in one number. These formulas put a open or close value in a percentile of the bar relative to another aspect of the bar.
Scalar - Non-directional. Absolute Value.
Scalar Position: The position of the price attribute relative to the scale of the bar range (high - low)
Example: high = 100. low = 0. close = 25.
(A) Measure price distance C-L. How high above the low did the candle close (e.g. close - low = 25)
(B) Divide by bar range (high - low). 25 / (100 - 0) = .25
Explaination: The candle closed at the 25th percentile of the bar range given the bar range low = 0 and bar range high = 100.
Formula: scp = (close - low) / (high - low)
Vector = Directional.
Vector Position: The position of the price attribute relative to the scale of the bar midpoint (Vector Position at hl2 = 0)
Example: high = 100. low = 0. close = 25.
(A) Measure Price distance C-L: How high above the low did the candle close (e.g. close - low = 25)
(B) Measure Price distance H-C: How far below the high did the candle close (e.g. high - close = 75)
(C) Take Difference: A - B = C = -50
(D) Divide by bar range (high - low). -50 / (100 - 0) = -0.50
Explaination: Candle close at the midpoint between hl2 and the low.
Formula: vcp = { / (high - low) }
Thank you for checking this out. I hope no one else has already done this (because it took half the day) and I hope you find value in it. Be well. Trade well.
Library "PD"
Price Displacement
pt(_exp) Absolute Point Displacement. Point quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Point size of given expression as an absolute value.
vpt(_exp) Vector Point Displacement. Point quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Point size of given expression as a vector.
tick(_exp) Absolute Tick Displacement. Tick quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Tick size of given expression as an absolute value.
vtick(_exp) Vector Tick Displacement. Tick quantity of given size parameters according to _exp.
Parameters:
_exp : (string) Price Parameter
Returns: Tick size of given expression as a vector.
pct(_exp, _prec) Absolute Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
Parameters:
_exp : (string) Expression
_prec : (int) Overload - Place value precision definition
Returns: Percent size of given expression as decimal.
vpct(_exp, _prec) Vector Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
Parameters:
_exp : (string) Expression
_prec : (int) Overload - Place value precision definition
Returns: Percent size of given expression as decimal.
FunctionIntrabarCrossValueLibrary "FunctionIntrabarCrossValue"
intrabar_cross_value(a, b, step) Find the minimum difference of a intrabar cross and return its median value.
Parameters:
a : float, series a.
b : float, series b.
step : float, step to iterate x axis, default=0.01
Returns: float
MathProbabilityDistributionLibrary "MathProbabilityDistribution"
Probability Distribution Functions.
name(idx) Indexed names helper function.
Parameters:
idx : int, position in the range (0, 6).
Returns: string, distribution name.
usage:
.name(1)
Notes:
(0) => 'StdNormal'
(1) => 'Normal'
(2) => 'Skew Normal'
(3) => 'Student T'
(4) => 'Skew Student T'
(5) => 'GED'
(6) => 'Skew GED'
zscore(position, mean, deviation) Z-score helper function for x calculation.
Parameters:
position : float, position.
mean : float, mean.
deviation : float, standard deviation.
Returns: float, z-score.
usage:
.zscore(1.5, 2.0, 1.0)
std_normal(position) Standard Normal Distribution.
Parameters:
position : float, position.
Returns: float, probability density.
usage:
.std_normal(0.6)
normal(position, mean, scale) Normal Distribution.
Parameters:
position : float, position in the distribution.
mean : float, mean of the distribution, default=0.0 for standard distribution.
scale : float, scale of the distribution, default=1.0 for standard distribution.
Returns: float, probability density.
usage:
.normal(0.6)
skew_normal(position, skew, mean, scale) Skew Normal Distribution.
Parameters:
position : float, position in the distribution.
skew : float, skewness of the distribution.
mean : float, mean of the distribution, default=0.0 for standard distribution.
scale : float, scale of the distribution, default=1.0 for standard distribution.
Returns: float, probability density.
usage:
.skew_normal(0.8, -2.0)
ged(position, shape, mean, scale) Generalized Error Distribution.
Parameters:
position : float, position.
shape : float, shape.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.ged(0.8, -2.0)
skew_ged(position, shape, skew, mean, scale) Skew Generalized Error Distribution.
Parameters:
position : float, position.
shape : float, shape.
skew : float, skew.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.skew_ged(0.8, 2.0, 1.0)
student_t(position, shape, mean, scale) Student-T Distribution.
Parameters:
position : float, position.
shape : float, shape.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.student_t(0.8, 2.0, 1.0)
skew_student_t(position, shape, skew, mean, scale) Skew Student-T Distribution.
Parameters:
position : float, position.
shape : float, shape.
skew : float, skew.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.skew_student_t(0.8, 2.0, 1.0)
select(distribution, position, mean, scale, shape, skew, log) Conditional Distribution.
Parameters:
distribution : string, distribution name.
position : float, position.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
shape : float, shape.
skew : float, skew.
log : bool, if true apply log() to the result.
Returns: float, probability.
usage:
.select('StdNormal', __CYCLE4F__, log=true)
How To Identify Argument Type Of Number Using OverloadsExample overload functions accept loading of _value for types float, int, or string, then positively identifies the actual argument type of that specific loaded _value.
How To Identify Type Of NumberExample function accepts loading of _value for types float, int, or string, then identifies whether the loaded _value is a string number, string, or number.
How To Count DecimalsCustom f_nDecimals() function returns precision of decimal numbers of the following forms:
const, input, simple, and series of the following types: float, integer, and string.
Error checking is performed for valid numbers and invalid values return NaN.
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!
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
Vertical LinesThis script plots vertical lines on charts or indicators. Unfortunately pinescript is lacking a vertical line plotting function. Vertical lines are useful to mark events, such as crossover of levels, indicators signals or as a time marker.
After searching the internet for a long time and trying different scripts, this script is the simplest and visually the best. You would think that plotting a vertical line would be relatively easy, it is not! I thank the unknow author for sharing this solution and now I will share it on tradingview to make it readily available to anybody that needs it.
RSI crossover signals are used as an example in this script. When the RSI crosses over 70 or below 30, the script plots a red or green vertical line.
The script plots a vertical line as a histogram bar. The histogram bar must have a height.
Setting the height near infinity like 1e20 will cover all the ranges from top to bottom in most charts, but doesn't work all the time. If the chart range is small in values, the line is not plotted or the chart is visually compressed because the top of the bar is also a data point in the chart. Another solution is to find the highest point in the chart and multiply it by a number from 2 to 10 to set the top of the histogram bar. But this solution doesn't work if the line is drawn in the indicator window. additionally if the chart or indicator includes negative values, a histogram bar with a negative height must be concatenated to the histogram bar with a positive height to cover the positive and negative range.
It would seem intuitive to include a vertical plot function since it is very useful and pinescript already has a horizontal line plot function called Hline. But pinescript is becoming less intuitive, and redundant. A case in point is Version 4 variable declaration and naming, it less intuitive and more redundant than previous versions. I beg Tradingview to adopt a more refined scripting language such as Matlab or Python for charting purposes. These languages can be easily ported to other analysis programs for AI or statistical analysis.
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
FunctionZigZagMultipleMethodsLibrary "FunctionZigZagMultipleMethods"
ZigZag Multiple Methods.
method(idx) Helper methods enumeration.
Parameters:
idx : int, index of method, range 0 to 4.
Returns: string
function(method, value_x, value_y) Multiple method ZigZag.
Parameters:
method : string, default='(MANUAL) Percent price move over X * Y', method for zigzag.
value_x : float, x value in method.
value_y : float, y value in method.
Returns: tuple with:
zigzag float
direction
reverse_line float
realtimeofpivot int
Double_Triple_EMALibrary "Double_Triple_EMA"
Provides the functions to calculate Double and Triple Exponentional Moving Averages (DEMA & TEMA).
dema(_source, _length) Calculates Double Exponentional Moving Averages (DEMA)
Parameters:
_source : -> Open, Close, High, Low, etc ('close' is used if no argument is supplied)
_length : -> DEMA length
Returns: Double Exponential Moving Average (DEMA) of an input source at the specified input length
tema(_source, _length) Calculates Triple Exponentional Moving Averages (TEMA)
Parameters:
_source : -> Open, Close, High, Low, etc ('close' is used if no argument is supplied)
_length : -> TEMA length
Returns: Triple Exponential Moving Average (TEMA) of an input source at the specified input length
[FN] Strategy - Store Level on ConditionThis is a function that you can use in strategies. Not a strategy in and of itself.
Example thumbnail is showing the function applied to a strategy.
Oftentimes, I am asked a question regarding how to hold a variable at a specific, constant level over a conditional period of time. This question is always asked in a very long convoluted way like "I want the strategy to know what the high of the last pivot was while I'm in a long." or some other variation of wanting a script to remember something from prior bars.
This function is designed to store a price or some numeric level on the bar that your conditional (bool) statements determine that it should be stored. In this construct, you would set conditional statement(s) to flip the 'hold condition' to be true on the next bar, then hold that value until either the "hold condition" is no longer true or the initial conditions trigger again, causing an update to the level that you want to capture.
You still have to come up with the logic for the start condition and hold condition on your own, but I've provided an example that should give you an idea of how to accomplish this and customize/deploy the function for your purposes.
The function will return 'na' when neither the start condition nor hold condition are true. There's multiple ways to implement this and variations on how the level is chosen. I've written extensive notes in the script to guide you through the logic behind the function. My hope is that it will be useful to those trying to build strategies or anyone attempting to get their script to remember a level under given conditions.
In the thumbnail example, the take profit level is defined at the beginning of the trade and held until the take profit order executes. The order execution is a separate matter. However, storing the take-profit level at a static value is key to telling the strategy.exit() function what price to execute a limit exit order at.
Example: strategy.exit("Exit Long", from_entry = "long", qty_percent = 100, limit = stored_value)
Let me know how it works out for you and if I can be of any assistance.
Note: Strategy results are mainly derived from the fact that the strategy is long-only, the NQ only goes up, and there is no stop loss in place. So don't ask for the specific strategy, because unless you're trading a single contract with a $500,000 account, you'll probably get liquidated using this strategy as it is presented.
Linear Regression & RSI Multi-Function Screener with Table-LabelHi fellow traders..
Happy to share a Linear Regression & RSI Multi-Function Custom Screener with Table-Labels...
The Screener scans for Linear Regression 2-SD Breakouts and RSI OB/OS levels for the coded tickers and gives Summary alerts
Uses Tables (dynamica resizing) for the scanner output instead of standard labels!
This Screener cum indicator collection has two distinct objectives..
1. Attempt re-entry into trending trades.
2. Attempt Counter trend trades using linear regression , RSI and Zigzag.
Briefly about the Screener functions..
a. It uses TABLES as Labels a FIRST for any Screener on TV.
b. Tables dynamically resize based on criteria..
c. Alerts for breakouts of the UPPER and the LOWER regression channels.(2 SD)
d. In addition to LinReg it also Screens RSI for OB/OS levels so a multifunction Screener.
e. Of course has the standard summary Alerts and programmable format for Custom functions.
f. Uses only the inbuilt Auto Fib and Lin Reg code for the screener.(No proprietary stuff)
g. The auto Zigzag code is derived(Auto fib).
Question what are all these doing in a single screener ??
ZigZag is very useful in determining Trend Up or Down from one Pivot to another.
So Once you have a firm view of the Current Trend for your chosen timeframe and ticker…
We can consider few possible trading scenarios..
a. Re-entry in an Up Trend - Combination of OS Rsi And a Lower Channel breach followed by a re-entry back into the regression channel CAN be used as an effective re-entry.
b. Similarily one can join a Down Trend on OB Rsi and Upper Channel line breach followed by re-entry into the regression channel.
If ZigZag signals a range-bound market, bound within channel lines then the Upper breakout can be used to Sell and vice-versa!
In short many possibilities for using these functions together with Scanner and Alerts.
This facilitates timely PROFITABLE Trending and Counter trend opportunities across multiple tickers.
You must give a thorough READ to the various available tutorials on ZigZag / Regression and Fib retracements before attempting counter trend trades using these tools!!
A small TIP – Markets are sideways or consolidating 70% of the time!!
Acknowledgements: - Thanks a lot DGTRD for the Auto ZigZag code and also for the eagerness to help wherever possible..Respect!!
Disclaimer: The Alerts and Screener are just few tools among many and not any kind of Buy/Sell recommendations. Unless you have sufficient trading experience please consult a Financial advisor before investing real money.
*The alerts are set for crossovers however for viewing tickers trading above or below the channel use code in line 343 and 344 after setting up the Alerts!
** RSI alerts are disabled by default to avoid clutter, but if needed one can activate code lines 441,442,444 and 445
Wish you all, Happy Profitable Trading!