Nasy -- Daily, Weekly, Monthly MADaily High Low, Daily Open Close, Weekly High Low, Weekly Open Close, Monthly High Low, Monthly Open Close
Statistics
Variety Distribution Probability Cone [Loxx]Variety Distribution Probability Cone forecasts price within a range of confidence using Geometric Brownian Motion (GBM) calculated using selected probability distribution, volatility, and drift. Below is detailed explanation of the inner workings of the indicator and the math involved. While normally this indicator would be used by options traders, this can also be used by regular directional traders who wish to observe a forecast of the confidence interval of possible prices over time.
What is a Random Walk
A random walk is a path which consists of a set of random steps. The starting point is zero and following movement may be one step to the left or to the right with equal probability. In the random walk process, there is no observable trend or pattern which are followed by the objects that is the movements are completely random. That is why the prices of a stock as it moves up and down can be modeled by random a walk process.
Stock Prices and Geometric Brownian Motion
Brownian motion, as first conceived by the botanist Robert Brown (1827), is a mathematical model used to describe random movements of small particles in a fluid or gas. These random movements are observed in the stock markets where the prices move up and down, randomly; hence, Brownian motion is considered as a mathematical model for stock prices.
P(exp(lnS0 + (mu + 1/2*sigma^2)t - z(0.05)*sigma*t^0.5) <= St <= exp(lnS0 + (mu + 1/2*sigma^2)t + z(0.05)*sigma*t^0.5)) = 0.95
Probability Distributions
Typically the normal distribution is used, but for our purposes here we extend this to Student t-distribution, Cauchy, Gaussian KDE, and Laplace
Student's t-Distribution
The probability density function of the Student’s t distribution is given by
g(x) = (L(v+1)/2) / L(v/2) * 1 / L(sqrt(v)) * (1 + x^2/v) ^ (-(v+1)/2)
with v degrees of freedom and v >= 0, denoted by X ~ t(v). The mean is 0 and the variance is v/(v-2). It is known that as v tends to infinity, the Student’s t-distribution tends to a standard normal probability density function, which has a variance of one. Blattberg and Gonedes were the first to propose that stock returns could be modeled by this distribution. (Blattberg and Gonedes, 1974) Platen and Sidorowicz later reaffirmed these findings.(Platen and Rendek, 2007) Finally, Cassidy, Hamp, and Ouyed used these findings to derive the Gosset formula, which is the Student t version of the Black-Scholes model.(Cassidy et al., 2010) They found that v = 2.65 provides the best fit when looking at the past 100 years of returns. They realized that as markets become more turbulent, the degrees of freedom should be adjusted to a smaller value.(Cassidy et al., 2010)
Cauchy Distribution
The probability density function of the Cauchy distribution is given by
f(x) = 1 / (theta*pi*(1 + ((x-n)/v)))
where n is the location parameter and theta is the scale parameter, for -infinity < x < infinity and is denoted by X ~ CAU(L,v). This model is similar to the normal distribution in that it is symmetric about zero, but the tails are fatter. This would mean that the probability of an extreme event occurring lies far out in the distributions tail. Using a crude example, if the normal distribution gave a probability of an extreme event occurring of 0.05% and the “best case” scenario of this event occurring 300 years, then using the Cauchy distribution one would find that the probability of occurring would be around 5% and now the “best case” scenario might have been reduced to only 63 years. Thus giving extreme events more of a likelihood of occurring. The mean, variance, and higher order moments are not defined (they are infinite); this implies that n and theta cannot be related to a mean and standard deviation. The Cauchy distribution is related to the Student’s t distribution T ~ CAU(1,0) when v = 1. In 1963, Benoit Mandelbrot was the first to suggest that stock returns follow a stable distribution, in particular, the Cauchy distribution.(Mandelbrot, 1963) His work was validated by Eugene Fama in 1965.(Fama, 1965) Recent research by Nassim Taleb came to the same conclusion as Mandelbrot, saying that stock returns follow a Cauchy distribution, as reported in his New York Times best-seller book “The Black Swan”.(Taleb, 2010)
Laplace Distribution
In probability theory and statistics, the Laplace distribution is a continuous probability distribution named after Pierre-Simon Laplace. It is also sometimes called the double exponential distribution, because it can be thought of as two exponential distributions (with an additional location parameter) spliced together along the abscissa, although the term is also sometimes used to refer to the Gumbel distribution. The difference between two independent identically distributed exponential random variables is governed by a Laplace distribution, as is a Brownian motion evaluated at an exponentially distributed random time. Increments of Laplace motion or a variance gamma process evaluated over the time scale also have a Laplace distribution.
The probability density function of the Cauchy distribution is given by
f(x) = 1/2b * exp(-|x-µ|/b)
Here, µ is a location parameter and b > 0, which is sometimes referred to as the "diversity", is a scale parameter. If µ = 0 and b=1, the positive half-line is exactly an exponential distribution scaled by 1/2.
The probability density function of the Laplace distribution is also reminiscent of the normal distribution; however, whereas the normal distribution is expressed in terms of the squared difference from the mean µ, the Laplace density is expressed in terms of the absolute difference from the mean. Consequently, the Laplace distribution has fatter tails than the normal distribution.
Gaussian Kernel Density Estimation
In statistics, kernel density estimation (KDE) is the application of kernel smoothing for probability density estimation, i.e., a non-parametric method to estimate the probability density function of a random variable based on kernels as weights. KDE is a fundamental data smoothing problem where inferences about the population are made, based on a finite data sample. In some fields such as signal processing and econometrics it is also termed the Parzen–Rosenblatt window method, after Emanuel Parzen and Murray Rosenblatt, who are usually credited with independently creating it in its current form. One of the famous applications of kernel density estimation is in estimating the class-conditional marginal densities of data when using a naive Bayes classifier, which can improve its prediction accuracy.
Let (x1, x2, ..., xn) be independent and identically distributed samples drawn from some univariate distribution with an unknown density f at any given point x. We are interested in estimating the shape of this function f. Its kernel density estimator is:
f(x) = 1/nh * sum(k(x-xi)/h, n)
where K is the kernel—a non-negative function—and h > 0 is a smoothing parameter called the bandwidth. A kernel with subscript h is called the scaled kernel and defined as Kh(x) = 1/h K(x/h). Intuitively one wants to choose h as small as the data will allow; however, there is always a trade-off between the bias of the estimator and its variance.
The probability density function of Gaussian Kernel Density Estimation is given by
f(x) = 1 / (v * 2*pi)^0.5 * exp(-(x - m)^2 / (2 * v))
where v is the bandwidth component h squared
KDE Bandwidth Estimation
Bandwidth selection strongly influences the estimate obtained from the KDE (much more so than the actual shape of the kernel). Bandwidth selection can be done by a "rule of thumb", by cross-validation, by "plug-in methods" or by other means. The default is Scott's Rule.
Scott's Rule
n ^ (-1/(d+4))
with n the number of data points and d the number of dimensions.
In the case of unequally weighted points, this becomes
neff^(-1/(d+4))
with neff the effective number of datapoints.
Silverman's Rule
(n * (d + 2) / 4)^(-1 / (d + 4))
or in the case of unequally weighted points:
(neff * (d + 2) / 4)^(-1 / (d + 4))
With a set of weighted samples, the effective number of datapoints neff
is defined by:
neff = sum(weights)^2 / sum(weights^2)
Manual input
You can provide your own bandwidth input. This is useful for those who wish to run external to TradingView Grid Search Machine Learning algorithms to solve for the bandwidth per ticker.
Inverse CDF of KDE Calculation
1. Create an array of random normalized numbers, using an inverse CDF of a normal distribution of mean of zero
and standard deviation one
2. Create a line space range of values -3 to 3
3. Create a Gaussian Kernel Density Estimate CDF by iterating over the line space array created in step 2. For each line space item, find the mean difference between the line space and the random variable divided by the bandwidth.
4. Derive test statistics from the resulting KDE inverse CDF, we use cubic spline interpolation to solve for line space value for a given alpha computed using the user selected probability percent value in the settings.
Volatility
Close-to-Close
Close-to-Close volatility is a classic and most commonly used volatility measure, sometimes referred to as historical volatility.
Volatility is an indicator of the speed of a stock price change. A stock with high volatility is one where the price changes rapidly and with a bigger amplitude. The more volatile a stock is, the riskier it is.
Close-to-close historical volatility calculated using only stock's closing prices. It is the simplest volatility estimator. But in many cases, it is not precise enough. Stock prices could jump considerably during a trading session, and return to the open value at the end. That means that a big amount of price information is not taken into account by close-to-close volatility.
Despite its drawbacks, Close-to-Close volatility is still useful in cases where the instrument doesn't have intraday prices. For example, mutual funds calculate their net asset values daily or weekly, and thus their prices are not suitable for more sophisticated volatility estimators.
Parkinson
Parkinson volatility is a volatility measure that uses the stock’s high and low price of the day.
The main difference between regular volatility and Parkinson volatility is that the latter uses high and low prices for a day, rather than only the closing price. That is useful as close to close prices could show little difference while large price movements could have happened during the day. Thus Parkinson's volatility is considered to be more precise and requires less data for calculation than the close-close volatility.
One drawback of this estimator is that it doesn't take into account price movements after market close. Hence it systematically undervalues volatility. That drawback is taken into account in the Garman-Klass's volatility estimator.
Garman-Klass
Garman Klass is a volatility estimator that incorporates open, low, high, and close prices of a security.
Garman-Klass volatility extends Parkinson's volatility by taking into account the opening and closing price. As markets are most active during the opening and closing of a trading session, it makes volatility estimation more accurate.
Garman and Klass also assumed that the process of price change is a process of continuous diffusion (geometric Brownian motion). However, this assumption has several drawbacks. The method is not robust for opening jumps in price and trend movements.
Despite its drawbacks, the Garman-Klass estimator is still more effective than the basic formula since it takes into account not only the price at the beginning and end of the time interval but also intraday price extremums.
Researchers Rogers and Satchel have proposed a more efficient method for assessing historical volatility that takes into account price trends. See Rogers-Satchell Volatility for more detail.
Rogers-Satchell
Rogers-Satchell is an estimator for measuring the volatility of securities with an average return not equal to zero.
Unlike Parkinson and Garman-Klass estimators, Rogers-Satchell incorporates drift term (mean return not equal to zero). As a result, it provides a better volatility estimation when the underlying is trending.
The main disadvantage of this method is that it does not take into account price movements between trading sessions. It means an underestimation of volatility since price jumps periodically occur in the market precisely at the moments between sessions.
A more comprehensive estimator that also considers the gaps between sessions was developed based on the Rogers-Satchel formula in the 2000s by Yang-Zhang. See Yang Zhang Volatility for more detail.
Yang-Zhang
Yang Zhang is a historical volatility estimator that handles both opening jumps and the drift and has a minimum estimation error.
We can think of the Yang-Zhang volatility as the combination of the overnight (close-to-open volatility) and a weighted average of the Rogers-Satchell volatility and the day’s open-to-close volatility. It considered being 14 times more efficient than the close-to-close estimator.
Garman-Klass-Yang-Zhang
Garman Klass is a volatility estimator that incorporates open, low, high, and close prices of a security.
Garman-Klass volatility extends Parkinson's volatility by taking into account the opening and closing price. As markets are most active during the opening and closing of a trading session, it makes volatility estimation more accurate.
Garman and Klass also assumed that the process of price change is a process of continuous diffusion (geometric Brownian motion). However, this assumption has several drawbacks. The method is not robust for opening jumps in price and trend movements.
Despite its drawbacks, the Garman-Klass estimator is still more effective than the basic formula since it takes into account not only the price at the beginning and end of the time interval but also intraday price extremums.
Researchers Rogers and Satchel have proposed a more efficient method for assessing historical volatility that takes into account price trends. See Rogers-Satchell Volatility for more detail.
Exponential Weighted Moving Average
The Exponentially Weighted Moving Average (EWMA) is a quantitative or statistical measure used to model or describe a time series. The EWMA is widely used in finance, the main applications being technical analysis and volatility modeling.
The moving average is designed as such that older observations are given lower weights. The weights fall exponentially as the data point gets older – hence the name exponentially weighted.
The only decision a user of the EWMA must make is the parameter lambda. The parameter decides how important the current observation is in the calculation of the EWMA. The higher the value of lambda, the more closely the EWMA tracks the original time series.
Standard Deviation of Log Returns
This is the simplest calculation of volatility. It's the standard deviation of ln(close/close(1))
Pseudo GARCH(2,2)
This is calculated using a short- and long-run mean of variance multiplied by θ.
θavg(var ;M) + (1 − θ)avg(var ;N) = 2θvar/(M+1-(M-1)L) + 2(1-θ)var/(M+1-(M-1)L)
Solving for θ can be done by minimizing the mean squared error of estimation; that is, regressing L^-1var - avg(var; N) against avg(var; M) - avg(var; N) and using the resulting beta estimate as θ.
Manual
User input % value
Drift
Cost of Equity / Required Rate of Return (CAPM)
Standard Capital Asset Pricing Model used to solve for Cost of Equity of Required Rate of Return. Due to the processor overhead required to compute CAPM, the user must plug in values for beta, alpha, and expected market return using Loxx's CAPM indicator series. Used for stocks.
Mean of Log Returns
Average of the log returns for the underlying ticker over the user selected period of evaluation. General purpose use.
Risk-free Rate (r)
10, 20, or 30 year bond yields for the user selected currency. Under equilibrium the drift of the empirical GBM must be the risk-free rate. If the price process is a GBM under the empirical measure, then a consequence of viability is that it is also a GBM under an equivalent (risk-neutral) measure.
Risk-free Rate adjusted for Dividends (r-q)
This is the Risk-free Rate minus the Dividend Yield.
Forex (r-rf)
This is derived from the Garman and Kohlhagen (1983) modified Black-Scholes model can be used to price European currency options. This is simply the diffeence between Risk-free Rate of the Forex currency in question. This is used for Forex pricing.
Martingale (0)
When the drift parameter is 0, geometric Brownian motion is a martingale. In probability theory, a martingale is a sequence of random variables (i.e., a stochastic process) for which, at a particular time, the conditional expectation of the next value in the sequence is equal to the present value, regardless of all prior values. Typically used for futures or margined futures.
Manual
User input % value
Additional notes
Indicator can be used on any timeframe. The T (time) variable used to annualize volatility and inside the GBM formula is automatically calculated based on the timeframe of the chart.
Confidence interval of volatility is calculated using an inverse CDF of a Chi-Squared Distribution. You change the volatility input used to create the probability cones from from realized volatility to upper or lower confidence levels of volatility to better visualize extremes of range. Generally, you'd stick with realized volatility.
Days per year should be 252 for everything but Cryptocurrency. These are days trader per year. Maximum future forecast bars is 365. Forecast bars are limited to the maximum of selected days per year.
Includes the ability to overlay option expiration dates by bars to see the range of prices for that date at that bar
You can select confidence % you wish for both the cone in general and the volatility. There are three levels for the cones, this will show on the three different levels up and down on the chart.
The table on the right displays important calculated values so you don't have to remember what they are or what settings you selected
All values are annualized no matter the timeframe.
Additional distributions and measures of volatility and drift will be added in future releases.
LibIndicadoresUteisLibrary "LibIndicadoresUteis"
Collection of useful indicators. This collection does not do any type of plotting on the graph, as the methods implemented can and should be used to get the return of mathematical formulas, in a way that speeds up the development of new scripts. The current version contains methods for stochastic return, slow stochastic, IFR, leverage calculation for B3 futures market, leverage calculation for B3 stock market, bollinger bands and the range of change.
estocastico(PeriodoEstocastico)
Returns the value of stochastic
Parameters:
PeriodoEstocastico : Period for calculation basis
Returns: Float with the stochastic value of the period
estocasticoLento(PeriodoEstocastico, PeriodoMedia)
Returns the value of slow stochastic
Parameters:
PeriodoEstocastico : Stochastic period for calculation basis
PeriodoMedia : Average period for calculation basis
Returns: Float with the value of the slow stochastic of the period
ifrInvenenado(PeriodoIFR, OrigemIFR)
Returns the value of the RSI/IFR Poisoned of Guima
Parameters:
PeriodoIFR : RSI/IFR period for calculation basis
OrigemIFR : Source of RSI/IFR for calculation basis
Returns: Float with the RSI/IFR value for the period
calculoAlavancagemFuturos(margem, alavancagemMaxima)
Returns the number of contracts to work based on margin
Parameters:
margem : Margin for contract unit
alavancagemMaxima : Maximum number of contracts to work
Returns: Integer with the number of contracts suggested for trading
calculoAlavancagemAcoes(alavancagemMaxima)
Returns the number of batches to work based on the margin
Parameters:
alavancagemMaxima : Maximum number of batches to work
Returns: Integer with the amount of lots suggested for trading
bandasBollinger(periodoBB, origemBB, desvioPadrao)
Returns the value of bollinger bands
Parameters:
periodoBB : Period of bollinger bands for calculation basis
origemBB : Origin of bollinger bands for calculation basis
desvioPadrao : Standard Deviation of bollinger bands for calculation basis
Returns: Two-position array with upper and lower band values respectively
theRoc(periodoROC, origemROC)
Returns the value of Rate Of Change
Parameters:
periodoROC : Period for calculation basis
origemROC : Source of calculation basis
Returns: Float with the value of Rate Of Change
BpaLibrary "Bpa"
TODO: library of Brooks Price Action concepts
isBreakoutBar(atr, high, low, close, open, tail, size)
TODO: check if the bar is a breakout based on the specified conditions
Parameters:
atr : TODO: atr value
high : TODO: high price
low : TODO: low price
close : TODO: close price
open : TODO: open price
tail : TODO: decimal value for a percent that represent the size of the tail of the bar that cant be preceeded to be considered strong close
size : TODO: decimal value for a percent that represents by how much the breakout bar should be bigger than others to be considered one
Returns: TODO: boolean value, true if breakout bar, false otherwise
Fed Net Liquidity Indicator (24-Oct-2022 update)This indicator is an implementation of the USD Liquidity Index originally proposed by Arthur Hayes based on the initial implementation of jlb05013, kudos to him!
I have incorporated subsequent additions (Standing Repo Facility and Central Bank Liquidity Swaps lines) and dealt with some recent changes in reporting units from TradingView.
This is a macro indicator that aims at tracking how much USD liquidity is available to chase financial assets:
- When the FED is expanding liquidity, financial asset prices tend to increase
- When the FED is contracting liquidity, financial asset prices tend to decrease
Here is the current calculation:
Net Liquidity =
(+) The Fed’s Balance Sheet (FRED:WALCL)
(-) NY Fed Total Amount of Accepted Reverse Repo Bids (FRED:RRPONTTLD)
(-) US Treasury General Account Balance Held at NY Fed (FRED:WTREGEN)
(+) NY Fed - Standing Repo Facility (FRED:RPONTSYD)
(+) NY Fed - Central Bank Liquidity Swaps (FRED:SWPT)
ILM COT Financial Table - CFTCUse this indicator on Daily Timeframe
Please refer to the below link for CFTC Financials
www.cftc.gov
This script shows the Financial COT for the respective instrument by deriving the CFTC code.
Option is provided to override the CFTC code
User can also configure the historical CFTC data view
The script calculates the Long% vs Short% for various categories (Dealers/Asset Managers/Leveraged Funds/Other Reportables) and color codes the column appropriately.
The goal of this script is to show all the financial CFTC data on a single page to digest the data better in a tabular form
Fixed the default TradingView Library which has some errors with CFTC code mapping.
For example, SPX CFTC Code #13874+ which is the most important one where big players take positions is not there in the default Library.
LibraryCOTLibrary "LibraryCOT"
This library provides tools to help Pine programmers fetch Commitment of Traders (COT) data for futures.
rootToCFTCCode(root)
Accepts a futures root and returns the relevant CFTC code.
Parameters:
root : Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
Returns: The part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
currencyToCFTCCode(curr)
Converts a currency string to its corresponding CFTC code.
Parameters:
curr : Currency code, e.g., "USD" for US Dollar.
Returns: The corresponding to the currency, if one exists.
optionsToTicker(includeOptions)
Returns the part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
Parameters:
includeOptions : A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
Returns: The part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
metricNameAndDirectionToTicker(metricName, metricDirection)
Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
Parameters:
metricName : One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
metricDirection : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Valid values vary with metrics. Invalid values will cause a runtime error.
Returns: The part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction", or "TC_L" for "Traders Commercial" and "Long".
typeToTicker(metricType)
Converts a metric type into one component required to build a valid COT ticker ID. See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
Parameters:
metricType : Metric type. Accepted values are: "All", "Old", "Other".
Returns: The part of a COT ticker.
convertRootToCOTCode(mode, convertToCOT)
Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`. Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
Parameters:
mode : A string determining how the function will work. Valid values are:
"Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
"Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
"Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
"Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
convertToCOT : "bool" value that, when `true`, causes the function to return a CFTC code. Otherwise, the root or currency information is returned. Optional. The default is `true`.
Returns: If `convertToCOT` is `true`, the part of a COT ticker ID string. If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
COTTickerid(COTType, CTFCCode, includeOptions, metricName, metricDirection, metricType)
Returns a valid TradingView ticker for the COT symbol with specified parameters.
Parameters:
COTType : A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
CTFCCode : The for the asset, e.g., wheat futures (root "ZW") have the code "001602".
includeOptions : A boolean value. 'true' if the symbol should include options and 'false' otherwise.
metricName : One of the metric names listed in this library's chart.
metricDirection : Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction".
metricType : Type of the metric. Possible values: "All", "Old", and "Other".
Returns: A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
Original Strategy - Backtest & Alerts [AlgoRider]█ OVERVIEW
This indicator simulates an efficient trading strategy developed by our team in a simple and effective way, the primary objective when designing it was to make its reading and use as simple as possible for TradingView users. The Backtesting feature has been designed to keep only the most essential information to obtain clear and precise results directly on the graph. The settings interface has also been designed for ergonomic and simplified use. The user is free to customize the parameters as he wishes and according to his trading profile by having the choice, for example, of using options to reduce the risk of loss, to increase the win rate, to optimize profits. Automation is made possible and facilitated thanks to preconfigured alert conditions.
█ CONCEPTS
How the strategy works :
When the price is close to its equilibrium (represented by an exponential moving average - EMA) and it starts to take an upward or downward direction the script will issue Long or Short entry orders. If the price turns and goes to the opposite direction, the script quickly cuts the position by issuing a Stop Loss order. When the price takes a real clear direction, this is where the script will be able to accumulate profits.
What makes this script unique is :
• That it is entirely developed by us, inspired by a strategy that is little known and little used in the trading world, in particular because it often involves a greater number of losing trades than winning trades.
• Its ease of reading and use. The backtesting feature was designed to clearly display the most important information in a data table directly on the chart. The user is not lost with dozens of superfluous data and can directly access the most essential information to see how the strategy has performed in the past.
• Its ease of configuration and customization. Once in the configuration window, again the user is not lost, because there is only one main parameter to modify, it is the length of the EMA, which will influence the timing of entries and exits trades. Then there are a few other non-mandatory parameters to fine-tune risk management and maximize profits. (Detailed description of the settings further down the page)
• Strategy automation made easy and fast thanks to several types of alerts which are differentiated for entries, for auto-exits and for Custom TP and SL. These alerts can be configured to send the messages by email or via Webhooks.
• The indicator has several custom options allowing its user to go further than the basic strategy. Several confirmations for entries are available as well as the possibility of adding or not a personalized TP and/or SL.
• There is no repaint, once an entry/exit symbol or drawing is displayed it doesn't change anymore. The Short, Long and auto-Exit signals appear only at the open of the candles, just after the signal was confirmed at the close of the previous candle. The custom TP and custom SL signals can appear when a candle is not yet finished, but once displayed they don't change.
█ HOW TO PROCEED
1 — Once the script is applied to your chart, it already works with its default settings. You can already see the performance of the strategy in the data table directly on the chart (in the top right corner by default).
2 — You can customize the strategy and influence the results/performance by modifying its parameters. 3 types of parameters are present and can be modified.
3 — This strategy is designed for the cryptocurrency market in priority, but you can also try it on other types of assets. It works on Futures but you can also try it on Spot market mainly for LONG trades.
4 — You can apply the script in every timeframe. We do not recommend using it below m30 because in most cases the statistics are unfavorable largely because of the fees. (This is not a financial advice but only for the use of the indicator)
█ FEATURES
Screenshot on BYBIT:EGLDUSDT Bybit Futures, H1, with default parameters, from 2022-01-01 to 2022-09-27, to show the settings window
• Settings For Backtesting
- Strategy : Choose from a drop-down list if the strategy should execute only Long trades or only Short trades or both. Default Both.
- Invest. : Choose the amount you want to invest in the simulation. Default 10000.
- Position : Choose the amount of the position (Size order) that will be used during the simulation. This will be the $ amount staked/involved for each trade entry.
Ex: If you put 20000 in position and 10000 in Invest. We consider that you use at least a leverage x2. Default 10000.
- Slipp. TP : Choose the amount in percentage of average slippage for Take Profits. This parameter makes it possible to predict a potential gap between the theoretical exit price for each TP (On the graph) and the real exit price on an exchange when implementing the strategy for real (slippage may be due to a time lag of a few seconds from execution time of the order on the exchange and/or due to the execution of a market order).
Ex: If a TP exit order of a Long trade, with entry $19000 (on BTCUSDT), is carried out in theory on the chart at $20000, in practice on the exchange the script have indeed sent an exit order at 20000 , but if the true exit price is 20050, the TP slippage is then +0.25%. Default 0.
- Slipp. SL : Choose the amount in percentage of average slippage for Stop Losses. This parameter makes it possible to predict a potential gap between the theoretical exit price for each SL (On the graph) and the real exit price on an exchange when implementing the strategy for real.
Ex: If an SL exit order of a Long trade, entry $19000 (on BTCUSDT), is carried out in theory on the chart at $18000, in practice on the exchange the script have indeed sent an exit order at 18000 $, but if the true exit price is 17950, the slippage SL is then +0.278% . Default 0.
- Fees % : Choose the percentage amount of fees applied to each trade to simulate the application of the strategy on the exchange of your choice. Applies to the entry and exit of each trade. Ex: For Binance Futures: 0.04; For Bybit futures: 0.06; For Ftx Futures: 0.075. Default 0.
- Cumulate Trades : If you check this, the Backtest will use 100% of the balance as Order Size (Position) for All or in the next X consecutive trades. Default not checked.
⚠️ Be Careful please, this option is available to show the full extent and possibilities of the algorithm when pushed to its limits thanks to the accumulation of profits (cumulative earnings), but it is a strategy that involves great risk. If a bad trade suffers a -50% loss, 50% of the account balance is lost, if the position is liquidated, the entire account balance is lost.
- All : If you check this All trades will be accumulated. Default not checked.
- Consecutive Trades : Choose the number of trades to accumulate. After X consecutive trades, the algorithm reassigns the initial order size to the current one and starts again for X consecutive trades. Minimum Value 2, Default 2.
• Settings To Optimize Performances and Risk Management
- (Main Parameter) EMA Length : Choose the length of the EMA. This value will determine the exponential moving average plot (blue line) that represents the equilibrium in this strategy. Depending on the positioning of the price around this equilibrium, the algorithm will decide to trigger Long or Short entry alerts, and exit alerts. Default 200.
- 1 - Confirm (After X Bar(s)) : If you check this, when the algorithm will detect an entry, it will wait for the number of bars you have entered to actually trigger the entry alert. Default not checked.
- Nb Bar : Enter here the number of bar you want, will be taken into account only if you check (1) Confirm (After X Bar(s)). Default 2.
- 2 - Confirm (Trend) : If you check this, when the algorithm will detect an entry, it will check that the trend is similar to the direction of the trade, if not, it will wait that the trade goes in the same direction as the trend to actually trigger the entry alert. Default not checked.
- OR/AND : This choice is taken into account only if you tick both confirmations. If you choose OR: The first of the 2 confirmations to be validated will trigger the entry alert. If you choose AND : once confirmation (1) is validated, the algorithm waits for confirmation (2) to be validated to actually trigger the entry alert. Default OR.
- Use TP / Use SL : If you check these, the algorithm will trigger personalized trade exit alerts when the price evolution has reached the amounts indicated since the trade entry. Default not Checked.
- % TP - SL : Indicate here the personalized amount in percentage that you want for your Take Profit and Stop Loss of each trade. Default 15-5.
• Settings For Appearances
- Small-size Data Table : If you check this, the data table will become smaller to free up more space on the chart to make it visually more pleasing. Default not checked.
Hide Table /
- Hide Labels / : You can check these to get a cleaner chart and focus only on what interests you in the indicator. Default not checked.
Hide Risk-Reward Areas
█ MAIN PARAMETERS TO USE
• In the default settings none of the box settings are checked. Basic strategy is made to be applied this way.
• The main parameter (the length of the EMA) is by default 200 because it is a known value that many traders rely on in many trading strategies. Moreover in this strategy it works in many cases and on different timeframes.
• To go further the user of the indicator is free to modify the parameters of the category "Leading Parameters - Risk Management" to reduce risks and to optimize profits.
• You can find below our recommendations for the EMA length value corresponding to the main timeframes.
m30 — EMA Length = 400 | 800
H1 — EMA Length = 200 | 400
H2 — EMA Length = 200 | 250
H4 — EMA Length = 100 | 200
D — EMA Length = 20 | 40
⚠️ We have chosen to recommend these settings because they will work in most cases, on most cryptoassets, but of course they will not work 100% of the time on all assets and will not always give positive results in the backtest, and they are not the most optimized parameters either. The user of the indicator is free to optimize the asset on which he wants to trade in his own way. Just as we do not give financial advice, we do not encourage to trade any asset in particular.
█ STATISTICS
The statistics presented below are an example of the results that the strategy can provide. (Reminder: These statistics are made over a past period and there is no guarantee that the same performance will reproduce in the future) .
For the demonstration we chose to apply the strategy on the Top 5 marketcap cryptos in September 2022. They are not the most favorable coins for this strategy but at least this way we don't take the most suitable assets to show wonderful and biased results. Likewise for the parameters used which are the default ones and which are not the most optimized parameters, much better results are possible. We chose Binance because it has the highest volumes and liquidity and the most historical data. We chose H1 because it is one of the most used timeframes.
BTC
Screenshot on BINANCE:BTCUSDTPERP Binance Futures, H1, with default parameters (EMA : 400), from 2022-01-01 to 2022-09-27
ETH
Screenshot on BINANCE:ETHUSDTPERP Binance Futures, H1, with default parameters (EMA : 400), from 2022-01-01 to 2022-09-27
BNB
Screenshot on BINANCE:BNBUSDTPERP Binance Futures, H1, with default parameters (EMA : 400), from 2022-01-01 to 2022-09-27
XRP
Screenshot on BINANCE:XRPUSDTPERP Binance Futures, H1, with default parameters (EMA : 200), from 2022-01-01 to 2022-09-27
ADA
Screenshot on BINANCE:ADAUSDTPERP Binance Futures, H1, with default parameters (EMA : 400), from 2022-01-01 to 2022-09-27
To show the potential of the indicator and push it to its limits, here is an example of the strategy applied for about 2 years (Up to the maximum of historical data available).
⚠️ It must be taken into account that during the period of this backtest the last Bullrun took place and it was a very favorable period for the strategy and for this altcoin (FTM), nothing ensures that it will happen again. ⚠️
FTM
Screenshot on BINANCE:FTMUSDTPERP Binance Futures, H4, with default parameters ( without cumulative earnings) and EMA : 400, start on 2020/12/03 to 2022/09/27
✅ All of the above statistics are verifiable by anyone using the indicator's backtesting system.
█ LIMITATIONS
• Despite the fact that we can see good performances when we backtest the strategy, we must take into account the fact that these are results performed in the past and that in no case does this guarantee that these same performances will be repeated again in the future.
• The automation of this strategy is made possible and is facilitated by alerts, but you must be aware of the fact that if you decide to put this strategy into practice in real life, you are solely responsible for the results that you will be able to obtain and you must be aware of the possibility at all times of partial or even total losses of your invested capital.
• Keep in mind that generating profits in trading is difficult. A strategy can perform very well at one time in the past during a period that is favorable to it, then from one day to the next it can give really bad results for several months or years.
• When backtesting a strategy, there are many factors to consider, not just trade entries to which you add a Take Profit and sometimes a Stop Loss. You must at least take into account the size of the position in relation to the capital you want to invest, the trading fees, the slippages (which can be really important depending on the exchange on which you are trading and depending on the asset you are trading), trading frequency, risk management, momentum, volumes and even more.
• This indicator has been optimized for crypto, you can try to use it on other type of assets but again, at your own risk.
The information published here on TradingView is not prohibited, doesn't constitute investment advice, and isn't created solely for qualified investors.
═════════════════════════════════════════════════════════════════════════
Important to note : our indicators with the same backtesting system are published in separate publications, because putting them together in a single script would considerably slow down the execution of the script. In addition each indicator, even when it is based on a simple technical indicator, has several options, parameters and entry/exit conditions specific to the underlying technical indicator. Finally, we want to keep the simplicity of use, configuration and understanding of our indicator by not mixing strategies that have nothing to do with each other.
MACD Strategy - Backtest [AlgoRider]█ OVERVIEW
Hello dear Tradingviewers !
We are excited to share with you this new indicator which simulates a trading strategy based solely on the well-known technical indicator MACD . We designed it for the sole educational and analytical purposes of showing novice traders and new investors that basing a trading strategy only on one such technical indicator is not necessarily a good thing to do. We do not recommend to apply this strategy for real.
Thanks to this indicator redesigned in our own way by incorporating our simple and easy-to-use Backtest functionality, you will be able to see and report on the performance and results that such a strategy has produced in the past.
The configuration window has also been designed to be easily readable and simple to use. Our goal is to make parameter customization as easy as possible.
█ HOW THE STRATEGY WORKS
• The script will simply trigger Long entries when bullish MACD crossings appear (the Macd line crosses the Signal line upwards) and Short entries when bearish MACD crossings appear (the Macd line crosses below the signal line).
• A Short signal ends a Long trade, a Long signal ends a Short trade.
• The script also allows setting up custom TP and SL.
• An option allows you to trigger early crossings, which will influence entries and exits.
• There is no repaint, once an entry/exit symbol or drawing is displayed it doesn't change anymore. The Short and Long signals appear at the open of the candles, just after the signal was confirmed at the close of the previous candle. The custom TP and custom SL signals can appear when a candle is not yet finished, but once displayed they don't change.
█ HOW TO PROCEED
1 — Once the script is applied to your chart, it already works with its default settings. You can already see the performance of the strategy in the data table directly on the chart (in the top right corner by default).
2 — You can customize the strategy and influence the results/performance by modifying its parameters. 3 types of parameters are present and can be modified.
3 — You can use this indicator in all types of markets.
4 — You can apply the script in every timeframe.
█ PARAMETERS
• Settings For Backtesting
- Strategy : Choose from a drop-down list if the strategy should execute only Long trades or only Short trades or both. Default Both.
- Invest. : Choose the amount you want to invest in the simulation. Default 10000.
- Position : Choose the amount of the position (Size order) that will be used during the simulation. This will be the $ amount staked/involved for each trade entry.
Ex: If you put 20000 in position and 10000 in Invest. We consider that you use at least a leverage x2. Default 10000.
- Slipp. TP : Choose the amount in percentage of average slippage for Take Profits. This parameter makes it possible to predict a potential gap between the theoretical exit price for each TP (On the graph) and the real exit price on an exchange when implementing the strategy for real (slippage may be due to a time lag of a few seconds from execution time of the order on the exchange and/or due to the execution of a market order).
Ex: If a TP exit order of a Long trade, with entry $19000 (on BTCUSDT ), is carried out in theory on the chart at $20000, in practice on the exchange the script have indeed sent an exit order at 20000 , but if the true exit price is 20050, the TP slippage is then +0.25%. Default 0.
- Slipp. SL : Choose the amount in percentage of average slippage for Stop Losses. This parameter makes it possible to predict a potential gap between the theoretical exit price for each SL (On the graph) and the real exit price on an exchange when implementing the strategy for real.
Ex: If an SL exit order of a Long trade, entry $19000 (on BTCUSDT ), is carried out in theory on the chart at $18000, in practice on the exchange the script have indeed sent an exit order at 18000 $, but if the true exit price is 17950, the slippage SL is then +0.278%. Default 0.
- Fees % : Choose the percentage amount of fees applied to each trade to simulate the application of the strategy on the exchange of your choice. Applies to the entry and exit of each trade. Ex: For Binance Futures: 0.04; For Bybit futures: 0.06; For Ftx Futures: 0.075. Default 0.
- Cumulate Trades : If you check this, the Backtest will use 100% of the balance as Order Size (Position) for All or in the next X consecutive trades. Default not checked.
⚠️ Be Careful please, this option is available to show the full extent and possibilities of the algorithm when pushed to its limits thanks to the accumulation of profits (cumulative earnings ), but it is a strategy that involves great risk. If a bad trade suffers a -50% loss, 50% of the account balance is lost, if the position is liquidated, the entire account balance is lost.
- All : If you check this All trades will be accumulated. Default not checked.
- Consecutive Trades : Choose the number of trades to accumulate. After X consecutive trades, the algorithm reassigns the initial order size to the current one and starts again for X consecutive trades. Minimum Value 2, Default 2.
• Settings To Optimize Performances and Risk Management
- Fast_MA : Choose the length of the Fast Moving Average. Default 12.
- Slow_MA : Choose the length of the Slow Moving Average. Default 26.
- Enable Early Crossings : If you check this, when the algorithm will detect an early crossing wethere bullish or bearish , it will trigger the Long or Short entries. Default not checked.
- Oscillator MA Type : Choose if the Macd line should be an Exponential Moving Average or a Simple Moving Average . Default Expo.
- Signal Line MA Type : Choose if the Signal line should be an Exponential Moving Average or a Simple Moving Average . Default Expo.
- Use TP / Use SL : If you check these, the algorithm will trigger personalized trade exit signals when the price evolution has reached the amounts indicated since the trade entry. Default not Checked.
- % TP - SL : Indicate here the personalized amount in percentage that you want for your Take Profit and Stop Loss of each trade. Default 15-5.
• Settings For Appearances
- Small-size Data Table : If you check this, the data table will become smaller to free up more space on the chart to make it visually more pleasing. Default not checked.
Hide Table /
- Hide Labels / : You can check these to get a cleaner chart and focus only on what interests you in the indicator. Default not checked.
Hide Risk-Reward Areas
█ LIMITATIONS
• ⚠️ We repeat it once again, this strategy is not intended to be reproduced in real conditions, we have designed it for educational and analytical purposes only.
• Even if you see good performances when you backtest the strategy, you must take into account that these results are performed in the past and that in no case does this guarantee that these same performances will be repeated again in the future.
• When you run for real a trading strategy you must be aware of the fact that you are solely responsible for the results that you will be able to obtain and you must be aware of the possibility at all times of partial or even total losses of your invested capital.
• Keep in mind that generating profits in trading is difficult. A strategy can perform very well at one time in the past during a period that is favorable to it, then from one day to the next it can give really bad results for several months or years.
• When backtesting a trading strategy, there are many factors to consider, not just trade entries to which you add a Take Profit and sometimes a Stop Loss. You must at least take into account the size of the position in relation to the capital you want to invest, the trading fees, the slippages (which can be really important depending on the exchange on which you are trading and depending on the asset you are trading), trading frequency, risk management, momentum, volumes and even more.
The information published here on TradingView is not prohibited, doesn't constitute investment advice, and isn't created solely for qualified investors.
═════════════════════════════════════════════════════════════════════════
Important to note : our indicators with the same backtesting system are published in separate publications, because putting them together in a single script would considerably slow down the execution of the script. In addition each indicator, even when it is based on a simple technical indicator, has several options, parameters and entry/exit conditions specific to the underlying technical indicator. Finally, we want to keep the simplicity of use, configuration and understanding of our indicator by not mixing strategies that have nothing to do with each other.
RSI Strategy - Backtest [AlgoRider]█ OVERVIEW
Hello dear Tradingviewers !
We share with you this new indicator which simulates a trading strategy based solely on the well-known technical indicator RSI . We designed it for the sole educational and analytical purposes of showing novice traders and new investors that basing a trading strategy only on one such technical indicator is not necessarily a good thing to do. We do not recommend to apply this strategy for real.
Thanks to this indicator redesigned in our own way by incorporating our simple and easy-to-use Backtest functionality, you will be able to see and report on the performance and results that such a strategy has produced in the past.
The configuration window has also been designed to be easily readable and simple to use. Our goal is to make parameter customization as easy as possible.
█ HOW THE STRATEGY WORKS
• The script will trigger Long entries when the price crosses upwards the Oversold zone (Default 38.2) and Short entries when the price crosses downward the Overbought zone (Default 61.8).
• A Short signal ends a Long trade, a Long signal ends a Short trade.
• The script also allows setting up custom TP and SL.
• Several options allow you to reverse entry and exit conditions of trades. You can choose to reverse entries or/and exits (Ex: when the script detects a Long Entry, it will actually trigger a Short trade).
• You can also change the entry conditions of the strategy. Instead of entering oversold/overbought zone conditions, it will trigger entries when the Rsi changes direction and reverses (Ex: when the rsi has been going down for 5 candles, and the rsi starts going up) , regardless of the area in which the RSI is located.
• There is no repaint, once an entry/exit symbol or drawing is displayed it doesn't change anymore. The Short and Long signals appear at the open of the candles, just after the signal was confirmed at the close of the previous candle. The custom TP and custom SL signals can appear when a candle is not yet finished, but once displayed they don't change.
█ HOW TO PROCEED
1 — Once the script is applied to your chart, it already works with its default settings. You can already see the performance of the strategy in the data table directly on the chart (in the top right corner by default).
2 — You can customize the strategy and influence the results/performance by modifying its parameters. 4 types of parameters are present and can be modified.
3 — You can use this indicator in all types of markets.
4 — You can apply the script in every timeframe.
█ PARAMETERS
• Settings For Backtesting
- Strategy : Choose from a drop-down list if the strategy should execute only Long trades or only Short trades or both. Default Both.
- Invest. : Choose the amount you want to invest in the simulation. Default 10000.
- Position : Choose the amount of the position (Size order) that will be used during the simulation. This will be the $ amount staked/involved for each trade entry.
Ex: If you put 20000 in position and 10000 in Invest. We consider that you use at least a leverage x2. Default 10000.
- Slipp. TP : Choose the amount in percentage of average slippage for Take Profits. This parameter makes it possible to predict a potential gap between the theoretical exit price for each TP (On the graph) and the real exit price on an exchange when implementing the strategy for real (slippage may be due to a time lag of a few seconds from execution time of the order on the exchange and/or due to the execution of a market order).
Ex: If a TP exit order of a Long trade, with entry $19000 (on BTCUSDT ), is carried out in theory on the chart at $20000, in practice on the exchange the script have indeed sent an exit order at 20000 , but if the true exit price is 20050, the TP slippage is then +0.25%. Default 0.
- Slipp. SL : Choose the amount in percentage of average slippage for Stop Losses. This parameter makes it possible to predict a potential gap between the theoretical exit price for each SL (On the graph) and the real exit price on an exchange when implementing the strategy for real.
Ex: If an SL exit order of a Long trade, entry $19000 (on BTCUSDT ), is carried out in theory on the chart at $18000, in practice on the exchange the script have indeed sent an exit order at 18000 $, but if the true exit price is 17950, the slippage SL is then +0.278%. Default 0.
- Fees % : Choose the percentage amount of fees applied to each trade to simulate the application of the strategy on the exchange of your choice. Applies to the entry and exit of each trade. Ex: For Binance Futures: 0.04; For Bybit futures: 0.06; For Ftx Futures: 0.075. Default 0.
- Cumulate Trades : If you check this, the Backtest will use 100% of the balance as Order Size (Position) for All or in the next X consecutive trades. Default not checked.
⚠️ Be Careful please, this option is available to show the full extent and possibilities of the algorithm when pushed to its limits thanks to the accumulation of profits (cumulative earnings ), but it is a strategy that involves great risk. If a bad trade suffers a -50% loss, 50% of the account balance is lost, if the position is liquidated, the entire account balance is lost.
- All : If you check this All trades will be accumulated. Default not checked.
- Consecutive Trades : Choose the number of trades to accumulate. After X consecutive trades, the algorithm reassigns the initial order size to the current one and starts again for X consecutive trades. Minimum Value 2, Default 2.
• Change Entry & Exit conditions
- Rsi Turns Up/Down : Enable this option to change conditions for trade entries. For Long entries : It will start a Long trade when RSI turns up and the RSI was falling on the last X bar(s). For Short entries : It will start a Short trade when RSI turns down and the RSI was rising on the last X bar(s). Default not checked.
- After Falling/Rising Bars(s) : Choose the number of bars/candles since which the price was falling/rising. Default 5.
- Reverse Entries : Enable this option to reverse conditions for trade entries. When a Short signal appears, it will actually start a Long trade. When a Long signal appears, it will actually start a Short trade. Default not checked.
- Reverse Exits : Enable this option to reverse conditions for trade exits. Default not checked.
- Safety Stop Loss : Enable this option to quickly cut the trade when the price turns quickly. For a Long trade : if the price returns to the oversold zone, it ends the trade. For a Short trade : if the price returns to the overbought zone, it ends the trade. Mainly useful for basic strategy (overbought/oversold conditions). Default not checked.
• Settings To Optimize Performances and Risk Management
- Len RSI : The length of RSI . Default 14.
- Overbuy : You can change the limit value of the overbought zone of the RSI . Default 61.8.
- Oversell : You can change the limit value of the oversell zone of the RSI . Default 38.2.
- Use TP / Use SL : If you check these, the algorithm will trigger personalized trade exit signals when the price evolution has reached the amounts indicated since the trade entry. Default not Checked.
- % TP - SL : Indicate here the personalized amount in percentage that you want for your Take Profit and Stop Loss of each trade. Default 15-5.
• Settings For Appearances
- Small-size Data Table : If you check this, the data table will become smaller to free up more space on the chart to make it visually more pleasing. Default not checked.
Hide Table /
- Hide Labels / : You can check these to get a cleaner chart and focus only on what interests you in the indicator. Default not checked.
Hide Risk-Reward Areas
█ LIMITATIONS
• ⚠️ We repeat it once again, this strategy is not intended to be reproduced in real conditions, we have designed it for educational and analytical purposes only.
• Even if you see good performances when you backtest the strategy, you must take into account that these results are performed in the past and that in no case does this guarantee that these same performances will be repeated again in the future.
• When you run for real a trading strategy you must be aware of the fact that you are solely responsible for the results that you will be able to obtain and you must be aware of the possibility at all times of partial or even total losses of your invested capital.
• Keep in mind that generating profits in trading is difficult. A strategy can perform very well at one time in the past during a period that is favorable to it, then from one day to the next it can give really bad results for several months or years.
• When backtesting a trading strategy, there are many factors to consider, not just trade entries to which you add a Take Profit and sometimes a Stop Loss. You must at least take into account the size of the position in relation to the capital you want to invest, the trading fees, the slippages (which can be really important depending on the exchange on which you are trading and depending on the asset you are trading), trading frequency, risk management, momentum, volumes and even more.
The information published here on TradingView is not prohibited, doesn't constitute investment advice, and isn't created solely for qualified investors.
═════════════════════════════════════════════════════════════════════════
Important to note : our indicators with the same backtesting system are published in separate publications, because putting them together in a single script would considerably slow down the execution of the script. In addition each indicator, even when it is based on a simple technical indicator, has several options, parameters and entry/exit conditions specific to the underlying technical indicator. Finally, we want to keep the simplicity of use, configuration and understanding of our indicator by not mixing strategies that have nothing to do with each other.
Position size in dollar cost average strategySTATIC DCA
Using the tradingview.com, an algorithm was generated that simulates the behavior of the DCA methodology. This algorithm simulates the purchase of 1000 USD on the 15th of each month, regardless of the bitcoin price. It is considered a static DCA, since the amount to be invested remains always fixed.
The inputs to the function are, the day number of the month in which the purchase is to be made, the start date of the simulation and the capital to be invested month by month. What the function does is to receive the value of the investment, and if the day entered in the function coincides with the current day, it will divide the invested capital by the price of the asset, obtaining a position size that accumulates in each purchase. With this data we can obtain the total invested capital, the net profit, as well as the average buying price.
DYNAMIC DCA
The dynamic DCA, bases its operation on the use of moving averages and standard deviations, in order to find the zones where the price has a lower value than the deviation under the mean. This condition can be considered as an accumulation zone.
The data were obtained in a one-week time window, using the security request method. Since purchases are made one every month, the daily time window generates many false signals, while the one-month time window generates few signals. The analysis is performed on data from 52 weeks equivalent to one year.
Subsequently we created an algorithm based on the ATR, for the selection of the position size, the fundamental characteristic of this development is that the algorithm will not invest the total of the capital destined to month to month. The amount of money to be invested will vary between 0 and 100%, in discrete values defined by the mean and standard deviation in the ATR calculation. Uninvested money will accumulate until the asset price enters the accumulation zone, where this capital will be released and used to accumulate as much of the asset as possible.
The function developed for the dynamic DCA receives the same inputs as the previous function, plus an extra condition and the variable resulting from the calculation of the position size.
---
ANALYSIS
In the analysis, we will consider ratios, such as cumulative position size, percentage net profit, invested amount and average buying price. The simulation of the results starts on 12/18/2017. For the analysis in all charts, the red line will represent the static DCA ratios, while the blue line will represent the dynamic DCA ratios.
Amount invested
At the end of this backtesting, the quantity invested is the same for each of the cases, however, the way the money enters the market is different. Money enters steadily and in the same amount in the static DCA, while in the dynamic DCA, there are months in which no purchases are made, or partial purchases are made. The remaining capital that accumulates and flows into the market, when bitcoin reaches its lowest price and enters accumulation zones.
Accumulated position size
It can be noted that the dynamic DCA strategy obtains a better result, accumulating a total of 6.62 bitcoins, 18% higher than the static DCA strategy.
Percentage net profit
The static DCA strategy in the last rally was approximately 40% lower in percentage return on invested capital than the dynamic DCA strategy.
Average buying price
In the initial part of the simulation the average buying price of bitcoin using the static DCA strategy was lower, however, as time went on, the dynamic DCA strategy obtained a better average buying price, with 15% cheaper.
---
CONCLUSIONS
The dynamic DCA strategy was more efficient in the use of investment resources.
- One of the main advantages of the dynamic DCA strategy is that it will allow us to enter the spot market even after it has passed its parabolic growth cycle. We will be able to accumulate bitcoin in the bearish regime, having our largest purchases in the accumulation zone.
- Due to these characteristics, the time in which we stay in negative returns is going to be shorter than with a DCA strategy.
- This algorithm can be tested on different assets, extrapolated to Python and by connecting via API, you can configure the automatic purchase of cryptocurrencies, which generates an accumulation of assets based on back testing, relatively superior to what several wallets and exchanges offer.
- The parameters for configuring the dynamic DCA strategy are quite basic and do not require professional knowledge, and the optimal configuration can be obtained by visualizing the results.
TradingWolfLibaryLibrary "TradingWolfLibary"
getMA(int, string)
Gets a Moving Average based on type
Parameters:
int : length The MA period
string : maType The type of MA
Returns: A moving average with the given parameters
minStop(float, simple, float, string)
Calculates and returns Minimum stop loss
Parameters:
float : entry price (Close if calculating on the entry candle)
simple : int Calculate how many bars back to look at swings
float : Minimum Stop Loss allowed (Should be x 0.01) if input
string : Direciton of trade either "Long" or "Short"
Returns: Stop Loss Value
Correlation ZonesThis indicator highlights zones with strong, weak and negative correlation. Unlike standard coefficient indicator it will help to filter out noise when analyzing dependencies between two assets.
With default input setting Correlation_Threshold=0.5:
- Zones with correlation above 0.5, will be colored in green (strong correlation)
- Zones with correlation from -0.5 to 0.5 will be colored grey (weak correlation)
- Zones with correlation below -0.5 will be colore red (strong negative correlation)
Input parameter "Correlation_Threshold" can be modified in settings.
Provided example demonstrates BTCUSD correlation with NASDAQ Composite . I advice to use weekly timeframe and set length to 26 week for this study
Kendall Rank Correlation Coefficient (alt)This is a non-parametric correlation statistical test, which is less sensitive to magnitude and more to direction, hence why some people call this a "concordance test".
This indicator was originally created by Alex Orekhov (everget), if you like this one, please show the original author some love:
This version is extended by tartigradia (2022) to make it more readily useable:
* Update to pinescript v5
* Default compare to current symbol (instead of only fixed symbols)
* Add 1.0, 0.0 and -1.0 correlation levels lines.
This indicator plots both the Kendall correlation in orange, and the more classical parametric Pearson correlation in purple for comparison. Either can be disabled in the Style tab.
Quantitative mean reversion v4The code uses the concept of mean reversion. Mean reversion suggests that price over a period of time reverts back to its statistical mean. In simple terms, it means if a price has drifted apart from the statistical mean, after a certain amount of time, it will revert back to its statistical mean. This drift is measured via z-score. When the z-score value is high, the price is expected to revert. Besides, the higher the time frame you use, the lesser the drift is, so reduce the z-score in the tabs if you use higher time frames, else, vice-versa.
Based on the parameters, the code will provide a trade signal - both long and short, and entry and exit. You can use notifications for alerts. Please use the parameters in the options to find the best combinations for your stocks.
In the properties, you can use your own brokers commission, capital, to see if the strategy is profitable for your ticker in the long run or not. This code has been tested for profits for various assets in both crypto - Bitcoin futures , Ethereum futures -, and stocks - AMD , Apple , MSFT , etc.
This is not get rich quick scheme, and you have to be patient with it for the long run.
If you have any query, please feel free to ask in the comments sections.
If you want some new changes, please feel free to suggest
Currently, I am optimising the maximum time for holding a trade. Till that's completed, use this and please feel free to leave a feedback to make it better
Three Linear Regression ChannelsPlot three linear regression channels using alexgrover 's Computing The Linear Regression Using The WMA And SMA indicator for the linear regression calculations.
Settings
Length : Number of inputs to be used
Source : Source input of the indicator
Midline Colour : The colour of the midline
Channel One, Two, and Three Multiplicative Factor : Multiplication factor for the RMSE, determine the distance between the upper and lower level
Channel One, Two, and Three Colour : The channel's lines colour
Usage
For usage details, please refer to alexgrover 's Computing The Linear Regression Using The WMA And SMA indicator.