Optimal Length BackTester [YinYangAlgorithms]This Indicator allows for a ‘Optimal Length’ to be inputted within the Settings as a Source. Unlike most Indicators and/or Strategies that rely on either Static Lengths or Internal calculations for the length, this Indicator relies on the Length being derived from an external Indicator in the form of a Source Input.
This may not sound like much, but this application may allows limitless implementations of such an idea. By allowing the input of a Length within a Source Setting you may have an ‘Optimal Length’ that adjusts automatically without the need for manual intervention. This may allow for Traditional and Non-Traditional Indicators and/or Strategies to allow modifications within their settings as well to accommodate the idea of this ‘Optimal Length’ model to create an Indicator and/or Strategy that adjusts its length based on the top performing Length within the current Market Conditions.
This specific Indicator aims to allow backtesting with an ‘Optimal Length’ inputted as a ‘Source’ within the Settings.
This ‘Optimal Length’ may be used to display and potentially optimize multiple different Traditional Indicators within this BackTester. The following Traditional Indicators are included and available to be backtested with an ‘Optimal Length’ inputted as a Source in the Settings:
Moving Average; expressed as either a: Simple Moving Average, Exponential Moving Average or Volume Weighted Moving Average
Bollinger Bands; expressed based on the Moving Average Type
Donchian Channels; expressed based on the Moving Average Type
Envelopes; expressed based on the Moving Average Type
Envelopes Adjusted; expressed based on the Moving Average Type
All of these Traditional Indicators likewise may be displayed with multiple ‘Optimal Lengths’. They have the ability for multiple different ‘Optimal Lengths’ to be inputted and displayed, such as:
Fast Optimal Length
Slow Optimal Length
Neutral Optimal Length
By allowing for the input of multiple different ‘Optimal Lengths’ we may express the ‘Optimal Movement’ of such an expressed Indicator based on different Time Frames and potentially also movement based on Fast, Slow and Neutral (Inclusive) Lengths.
This in general is a simple Indicator that simply allows for the input of multiple different varieties of ‘Optimal Lengths’ to be displayed in different ways using Tradition Indicators. However, the idea and model of accepting a Length as a Source is unique and may be adopted in many different forms and endless ideas.
Tutorial:
You may add an ‘Optimal Length’ within the Settings as a ‘Source’ as followed in the example above. This Indicator allows for the input of a:
Neutral ‘Optimal Length’
Fast ‘Optimal Length’
Slow ‘Optimal Length’
It is important to account for all three as they generally encompass different min/max length values and therefore result in varying ‘Optimal Length’s’.
For instance, say you’re calculating the ‘Optimal Length’ and you use:
Min: 1
Max: 400
This would therefore be scanning for 400 (inclusive) lengths.
As a general way of calculating you may assume the following for which lengths are being used within an ‘Optimal Length’ calculation:
Fast: 1 - 199
Slow: 200 - 400
Neutral: 1 - 400
This allows for the calculation of a Fast and Slow length within the predetermined lengths allotted. However, it likewise allows for a Neutral length which is inclusive to all lengths alloted and may be deemed the ‘Most Accurate’ for these reasons. However, just because the Neutral is inclusive to all lengths, doesn’t mean the Fast and Slow lengths are irrelevant. The Fast and Slow length inputs may be useful for seeing how specifically zoned lengths may fair, and likewise when they cross over and/or under the Neutral ‘Optimal Length’.
This Indicator features the ability to display multiple different types of Traditional Indicators within the ‘Display Type’.
We will go over all of the different ‘Display Types’ with examples on how using a Fast, Slow and Neutral length would impact it:
Simple Moving Average:
In this example above have the Fast, Slow and Neutral Optimal Length formatted as a Slow Moving Average. The first example is on the 15 minute Time Frame and the second is on the 1 Day Time Frame, demonstrating how the length changes based on the Time Frame and the effects it may have.
Here we can see that by inputting ‘Optimal Lengths’ as a Simple Moving Average we may see moving averages that change over time with their ‘Optimal Lengths’. These lengths may help identify Support and/or Resistance locations. By using an 'Optimal Length' rather than a static length, we may create a Moving Average which may be more accurate as it attempts to be adaptive to current Market Conditions.
Bollinger Bands:
Bollinger Bands are a way to see a Simple Moving Average (SMA) that then uses Standard Deviation to identify how much deviation has occurred. This Deviation is then Added and Subtracted from the SMA to create the Bollinger Bands which help Identify possible movement zones that are ‘within range’. This may mean that the price may face Support / Resistance when it reaches the Outer / Inner bounds of the Bollinger Bands. Likewise, it may mean the Price is ‘Overbought’ when outside and above or ‘Underbought’ when outside and below the Bollinger Bands.
By applying All 3 different types of Optimal Lengths towards a Traditional Bollinger Band calculation we may hope to see different ranges of Bollinger Bands and how different lookback lengths may imply possible movement ranges on both a Short Term, Long Term and Neutral perspective. By seeing these possible ranges you may have the ability to identify more levels of Support and Resistance over different lengths and Trading Styles.
Donchian Channels:
Above you’ll see two examples of Machine Learning: Optimal Length applied to Donchian Channels. These are displayed with both the 15 Minute Time Frame and the 1 Day Time Frame.
Donchian Channels are a way of seeing potential Support and Resistance within a given lookback length. They are a way of withholding the High’s and Low’s of a specific lookback length and looking for deviation within this length. By applying a Fast, Slow and Neutral Machine Learning: Optimal Length to these Donchian Channels way may hope to achieve a viable range of High’s and Low’s that one may use to Identify Support and Resistance locations for different ranges of Optimal Lengths and likewise potentially different Trading Strategies.
Envelopes / Envelopes Adjusted:
Envelopes are an interesting one in the sense that they both may be perceived as useful; however we deem that with the use of an ‘Optimal Length’ that the ‘Envelopes Adjusted’ may work best. We will start with examples of the Traditional Envelope then showcase the Adjusted version.
Envelopes:
As you may see, a Traditional form of Envelopes even produced with a Machine Learning: Optimal Length may not produce optimal results. Unfortunately this may occur with some Traditional Indicators and they may need some adjustments as you’ll notice with the ‘Envelopes Adjusted’ version. However, even without the adjustments, these Envelopes may be useful for seeing ‘Overbought’ and ‘Oversold’ locations within a Machine Learning: Optimal Length standpoint.
Envelopes Adjusted:
By adding an adjustment to these Envelopes, we may hope to better reflect our Optimal Length within it. This is caused by adding a ratio reflection towards the current length of the Optimal Length and the max Length used. This allows for the Fast and Neutral (and potentially Slow if Neutral is greater) to achieve a potentially more accurate result.
Envelopes, much like Bollinger Bands are a way of seeing potential movement zones along with potential Support and Resistance. However, unlike Bollinger Bands which are based on Standard Deviation, Envelopes are based on percentages +/- from the Simple Moving Average.
We will conclude our Tutorial here. Hopefully this has given you some insight into how useful adding a ‘Optimal Length’ within an external (secondary) Indicator as a Source within the Settings may be. Likewise, how useful it may be for automation sake in the sense that when the ‘Optimal Length’ changes, it doesn’t rely on an alert where you need to manually update it yourself; instead it will update Automatically and you may reap the benefits of such with little manual input needed (aside from the initial setup).
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
Envelopes
Nadaraya-Watson: Envelope (Non-Repainting)Due to popular request, this is an envelope implementation of my non-repainting Nadaraya-Watson indicator using the Rational Quadratic Kernel. For more information on this implementation, please refer to the original indicator located here:
What is an Envelope?
In technical analysis, an "envelope" typically refers to a pair of upper and lower bounds that surrounds price action to help characterize extreme overbought and oversold conditions. Envelopes are often derived from a simple moving average (SMA) and are placed at a predefined distance above and below the SMA from which they were generated. However, envelopes do not necessarily need to be derived from a moving average; they can be derived from any estimator, including a kernel estimator such as Nadaraya-Watson.
How to use this indicator?
Overall, this indicator offers a high degree of flexibility, and the location of the envelope's bands can be adjusted by (1) tweaking the parameters for the Rational Quadratic Kernel and (2) adjusting the lookback window for the custom ATR calculation. In a trending market, it is often helpful to use the Nadaraya-Watson estimate line as a floating SR and/or reversal zone. In a ranging market, it is often more convenient to use the two Upper Bands and two Lower Bands as reversal zones.
How are the Upper and Lower bounds calculated?
In this indicator, the Rational Quadratic (RQ) Kernel estimates the price value at each bar in a user-defined lookback window. From this estimation, the upper and lower bounds of the envelope are calculated based on a custom ATR calculated from the kernel estimations for the high, low, and close series, respectively. These calculations are then scaled against a user-defined multiplier, which can be used to further customize the Upper and Lower bounds for a given chart.
How to use Kernel Estimations like this for other indicators?
Kernel Functions are highly underrated, and when calibrated correctly, they have the potential to provide more value than any mundane moving average. For those interested in using non-repainting Kernel Estimations for technical analysis, I have written a Kernel Functions library that makes it easy to access various well-known kernel functions quickly. The Rational Quadratic Kernel is used in this implementation, but one can conveniently swap out other kernels from the library by modifying only a single line of code. For more details and usage examples, please refer to the Kernel Functions library located here:
ENVELOPE RSI - Buy Sell SignalsThis indicator is mainly based on Overbought and Oversold . Indicator for short-term trading. This way you can get small but acceptable signals.
The main basis of the indicator is as follows:
To buy, the indicator is waiting for the instrument to be oversold from the RSI point of view. Then, if the chart crosses the bottom line of the Envelope indicator from the bottom to the top, a buy signal is issued.
For sell, the indicator waits for the instrument to be overbought from the RSI perspective. Then, if the chart crosses the top line of the Envelope indicator from top to bottom, a sell signal is issued.
The general basis is the consonance of the price and the RSI indicator .
The best settings I came up with myself:
Time frame: 15 minutes
Overbought: 80
Oversell: 25
RSI Length: 8
It can be done on different instruments. But always set your profit and loss limits.
(Profit to loss ratio in this indicator can be 1: 1.)
Disclaimer : This information and trading indicators and tools provided neither is, nor should be construed, as an offer, or a solicitation of an offer, to buy or sell securities. You shall be fully responsible for any investment decision you make, and such decisions will be based solely on your evaluation of your financial circumstances, investment objectives, risk tolerance, and liquidity needs.
I am not liable for any profit, financial improvement, losses or damages, monetary or other that may result from the application of information contained within this indicator. Individual traders must use their own due diligence in analyzing featured trading indicators, other trading tools, webinars and other educational materials to determine if they represent suitable and useable features and capabilities for the individual trader.
multiple_ma_envelope
Description:
Moving Average is a well-known though simple technical analysis tool, that can be applied in most trading journeys. By adding an envelope (a certain amount above and below the moving averages, cited from Investopedia), the indicator aligned its aim to identify the reversal area i.e. when the price reaches the envelopes, the price tends to have a reverse. In this indicator, the improvement is by adding multiple envelopes at once, thus can identify the further phase of the reverse area when the price apparently continues current direction.
Upper Band = MA * (1 + %envelope)
Lower Band = MA * (1 - %envelope)
Notes:
1). In this indicator, the default value of the moving average utilized is set to 10, 20, 50, 100 respectively
2). The band initial value is set to 0.2, and increases by 0.2 for each increasing MA Length
Feature:
1). Multiple Moving Average Envelope
2). Information Table as displayed Rolling Deviation, Rolling Maximum Drawdown, and Value-at-Risk
HatiKO EnvelopesPublished source code is subject to the terms of the GNU Affero General Public License v3.0
This script describes and provides backtesting functionality to internal strategy of algorithmic crypto trading software "HatiKO bot".
Suitable for backtesting any Cryptocurrency Pair on any Exchange/Platform, any Timeframe.
Core Mechanics of this strategy are based on theory of price always returning to Moving Average + Envelopes indicator (Moving_average_envelope from Wiki)
Developement of this script and trading software is inspired by:
"Essential Technical Analysis: Tools and Techniques to Spot Market Trends" by Leigh Stevens (published on 12th of April 2002)
"Moving Average Envelopes" by ChartSchool, StockCharts platform (published on 13th of April 2015 or earlier)
"Коля Колеснік" from Crypto Times channel ("Метод сетка", published on 19th of August 2018)
"3 ways to use Moving Average Envelopes" by Rich Fitton, published on Trader's Nest (published on 28st of November 2018 or earlier)
noro's "Robot WhiteBox ShiftMA" strategy v1 script, published on TradingView platform (published on 29th of August 2018)
"Moving Average Envelopes: A Popular Trading Tool" Investopedia article (published 25th of June 2019)
and KROOL1980's blogpost on Argolabs ("Гридерство или Сетка как источник прибыли на форекс", published on 27th of February 2015)
Core Features:
1) Up to 4 Envelopes in each direction (Long/Short)
2) Use any of 6 different basis MAs, optionally use different MAs for Opening and Closure
3) Use different Timeframes for MA calculation, without any repainting and lookahead bias.
4) Fixed order size, not Martingale strategy
5) Close open position earlier by using Deviation parameter
6) PineScript v4 code
Options description:
Lot - % from your initial balance to use for order size calculation
Timeframe Short - Timeframe to use for Short Opening MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Short - Type of MA to use for Short Opening MA calculation, can be chosen from dropdown list, default is SMA
Data Short - Source of Price for Short Opening MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Short - Period used for Short Opening MA calculation, should be >=1, default is 3
MA offset Short - Offset for MA value used for Short Envelopes calculation, should be >= 0, default is 0
Timeframe Long - Timeframe to use for Long Opening MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Long - Type of MA to use for Long Opening MA calculation, can be chosen from dropdown list, default is SMA
Data Long - Source of Price for Long Opening MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Long - Period used for Long Opening MA calculation, should be >=1, default is 3
MA offset Long - Offset for MA value used for Long Envelopes calculation, should be >= 0, default is 0
Mode close MA Short - Enable different MA for Short position Closure, default is "false". If false, Closure MA = Opening MA
Timeframe Short Close - Timeframe to use for Short Position Closure MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Close Short - Type of MA to use for Short Position Closure MA calculation, can be chosen from dropdown list, default is SMA
Data Short Close - Source of Price for Short Closure MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Short Close - Period used for Short Opening MA calculation, should be >=1, default is 3
Short Deviation - % to move from MA value, used to close position above or beyond MA, can be negative, default is 0
MA offset Short Close - Offset for MA value used for Short Position Closure calculation, should be >= 0, default is 0
Mode close MA Long - Enable different MA for Long position Closure, default is "false". If false, Closure MA = Opening MA
Timeframe Long Close - Timeframe to use for Long Position Closure MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Close Long - Type of MA to use for Long Position Closure MA calculation, can be chosen from dropdown list, default is SMA
Data Long Close - Source of Price for Long Closure MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Long Close - Period used for Long Opening MA calculation, should be >=1, default is 3
Long Deviation - % to move from MA value, used to close position above or beyond MA, can be negative, default is 0
MA offset Long Close - Offset for MA value used for Long Position Closure calculation, should be >= 0, default is 0
Short Shift 1..4 - % from MA value to put Envelopes at, for Shorts numbers should be positive, the higher is number, the higher should be Shift position, example: "Shift 1 = 1, shift 2 = 2, etc."
Long Shift 1..4 - % from MA value to put Envelopes at, for Longs numbers should be negative, the lower is number, the lower should be Shift position, example: "Shift 1 = -1, shift 2 = -2, etc."
From Year 20XX - Backtesting Starting Year number, only 20xx supported as script is cryptocurrency-oriented.
To Year 20XX - Backtesting Final Year number, only 20xx supported as script is cryptocurrency-oriented.
From Month - Years starting Month, optional tweaking, changing not recommended
To Month - Years ending Month, optional tweaking, changing not recommended
From day - Months starting day, optional tweaking, changing not recommended
To day - Months ending day, optional tweaking, changing not recommended
Graph notes:
Green lines - Long Envelopes.
Red lines - Short Envelopes.
Orange line - MA for closing of Short positions.
Lime line - MA for closing of Long positions.
**************************************************************************************************************************************************************************************************************
Опубликованный исходный код регулируется Условиями Стандартной Общественной Лицензии GNU Affero v3.0
Этот скрипт описывает и предоставляет функции бектеста для внутренней стратегии алгоритмического программного обеспечения "HatiKO bot".
Подходит для тестирования любой криптовалютной пары на любой бирже/платформе, на любом таймфрейме.
Кор-механика этой стратегии основана на теории всегда возвращающейся к значению МА цены с использованием индикатора Envelopes (Moving_average_envelope from Wiki)
Разработка этого скрипта и программного обеспечения для торговли вдохновлена следующими источниками:
Книга "Essential Technical Analysis: Tools and Techniques to Spot Market Trends" Ли Стивенса (опубликовано 12 апреля 2002 года)
«Moving Average Envelopes» от ChartSchool, платформа StockCharts (опубликовано 13 апреля 2015 года или раньше)
«Коля Колеснік» с канала Crypto Times («Метод сетка», опубликовано 19 августа 2018 года)
«3 ways to use Moving Average Envelopes» Рича Фиттона, опубликованные в «Trader's Nest» (опубликовано 28 ноября 2018 года или раньше)
Скрипт стратегии noro "Robot WhiteBox ShiftMA" v1, опубликованный на платформе TradingView(опубликовано 29 августа 2018 года)
«Moving Average Envelopes: A Popular Trading Tool», статья Investopedia (опубликовано 25 июня 2019 года)
Блог KROOL1980 из Argolabs («Гридерство или Сетка как источник прибыли на форекс», опубликовано 27 февраля 2015 года)
Основные особенности:
1) До 4-х Ордеров в каждом из направлении (Лонг / Шорт)
2) Выбор из 6-ти разных базовых МА, опционально используйте разные МА для открытия и закрытия.
3) Используйте разные таймфреймы для расчета MA, без перерисовки и "эффекта стеклянного шара".
4) Фиксированный размер ордера, а не стратегия Мартингейла
5) Возможность закрытия открытой позиции заблаговременно, используя параметр Deviation
6) Код реализован на PineScript v4
Описание параметров:
Lot - % от вашего первоначального баланса, используется при расчете размера Ордера
Timeframe Short - таймфрейм, используемый для расчета МА Открытия Шорт позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Short - тип MA, используемый для расчета МА Открытия Шорт позиций, может быть выбран из списка, по умолчанию SMA
Data Short - источник цены для расчета МА Открытия Шорт позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Short - период, используемый для расчета МА Открытия Шорт позиций, должен быть >= 1, по умолчанию 3
MA Offset Short - смещение значения MA, используемого для расчета Шорт Ордеров, должно быть >= 0, по умолчанию 0
Timeframe Long - таймфрейм, используемый для расчета МА Открытия Лонг позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Long - тип MA, используемый для расчета МА Открытия Лонг позиций, может быть выбран из списка, по умолчанию SMA
Data Long - источник цены для расчета МА Открытия Лонг позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Long - период, используемый для расчета МА Открытия Лонг позиций, должен быть >= 1, по умолчанию 3
MA Offset Long - смещение значения MA, используемого для расчета Лонг Ордеров, должно быть >= 0, по умолчанию 0
Mode close MA Short - Включает отдельное MA для закрытия Шорт позиции, по умолчанию «false». Если false, MA Закрытия = MA Открытия
Timeframe Short Close - таймфрейм, используемый для расчета МА Закрытия Шорт позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Close Short - тип MA, используемый при расчете МА Закрытия Шорт позиции. Mожно выбрать из списка, по умолчанию SMA
Data Short Close - источник цены для расчета МА Закрытия Шорт позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Short Close - период, используемый для расчета МА Закрытия Шорт позиции, должен быть >= 1, по умолчанию 3
Short Deviation - % отклонения от значения MA, используется для закрытия позиции выше или ниже рассчитанного значения MA, может быть отрицательным, по умолчанию 0
MA Offset Short Close - смещение значения MA, используемого для расчета закрытия Шорт позиции, должно быть >= 0, по умолчанию 0
Mode close MA Long - Включает разные MA для закрытия Лонг позиции, по умолчанию «false». Если false, MA Закрытия = MA Открытия
Timeframe Long Close - таймфрейм, используемый для расчета МА Закрытия Лонг позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Close Long - тип MA, используемый при расчете МА Закрытия Лонг позиции. Mожно выбрать из списка, по умолчанию SMA
Data Long Close - источник цены для расчета МА Закрытия Лонг позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Long Close - период, используемый для расчета МА Закрытия Лонг позиции, должен быть >= 1, по умолчанию 3
Long Deviation -% для перехода от значения MA, используется для закрытия позиции выше или ниже рассчитанного значения MA, может быть отрицательным, по умолчанию 0
MA Offset Long Close - смещение значения MA, используемого для расчета закрытия Лонг позиции, должно быть >= 0, по умолчанию 0
Short Shift 1..4 - % от значения MA для размещения Ордеров, для Шорт Ордеров должен быть положительным, чем выше номер, тем выше должна располагаться позиция Shift, например: «Shift 1 = 1, Shift 2 = 2 и т.д. "
Long Shift 1..4 - % от значения MA для размещения Ордеров, для Лонг Ордеров должно быть отрицательным, чем ниже число, тем ниже должна располагаться позиция Shift, например: «Shift 1 = -1, Shift 2 = -2, и т.д."
From Year 20XX - Год начала тестирования, из-за ориентированности на криптовалюты поддерживаются только значения формата 20хх.
To Year 20XX - Год окончания тестирования, из-за ориентированности на криптовалюты поддерживаются только значения формата 20хх.
From Month - Начальный месяц, опционально, менять не рекомендуется
To Month - Конечный месяц, опционально, менять не рекомендуется
From day - Начальный день месяца, опционально, менять не рекомендуется
To day - Конечный день месяца, опционально, менять не рекомендуется
Пояснения к графику:
Зеленые линии - Лонг Ордера.
Красные линии - Шорт Ордера.
Оранжевая линия - MA Закрытия Шорт позиций.
Лаймовая линия - MA Закрытия Лонг позиций.
G-Channels - Efficient Calculation Of Upper/Lower ExtremitiesIntroduction
Channels indicators are widely used in technical analysis, they provide lot of information. In general, technical indicators giving upper/lower extremities are calculated by adding/subtracting a volatility component to a central tendency estimator. This is the case with Bollinger bands, using the rolling standard deviation as volatility estimator and the simple moving average as central tendency estimator, or the Keltner channels using the exponential moving average and the average true range.
Lots and lots and lots (i can go on) of those indicators have been made, they only really need a central tendency estimator, which can be obtained from pretty much any filter, however i find interesting to focus on the efficiency of those indicators, therefore i propose a super efficient channel indicator using recursion. The average resulting from the upper/lower extremity of the indicator provide a new efficient filter similar to the average highest/lowest.
The calculation - How Does It Works
Efficiency is often associated to recursion, this would allow us to use past output values as input, so how does the indicator is calculated? Lets look at the upper band calculation :
a := max(src,nz(a(1))) - nz(a(1) - b(1))/length
src is the closing price, a is upper extremity, b is the lower one. Here we only need 3 values, the previous values of a and b and the closing price. Basically a := max(src,nz(a(1))) mean :
if the closing price is greater than the precedent value of a then output the closing price, else output the precedent value of a
therefore a will never be inferior to its precedent value, this is useful for getting the maximum price value in our dataset however its not useful to make an upper band, therefore we subtract this to a correction factor defined as the difference between a and b , this force the upper band to have lower values thus acting like a band without loosing its "upper" property, a similar process is done with the lower band.
Of course we could only use 2 values for making the indicator, thus ending with :
a := max(src,nz(a(1))) - nz(abs(close - a(1))/length
In fact this implementation is the same as the one proposed in my paper "Recursive Bands - A New Indicator For Technical Analysis", its also what i used for making the indicator "Adaptive Trailing Stop", this would be more efficient but i used the difference between the upper and lower extremities for a reason.
The Central tendency Estimator
This is the reason why i didn't implemented a more efficient version. Basically this central tendency estimator is just the average between the upper and lower extremities, it behave like the average of the highest/lowest over length period, its central plot in the Donchian channel indicator. Below is a comparison of both with length = 100 :
But why is our average so "boxy"? The extremities are not boxy, so why the average is sometimes equal to its previous value? Explain!
Its super easy to understand, imagine two lines, if their absolute change is the same and they follow an opposite direction, then their average is constant.
the average of the green and red line is the orange line. If both lines follow the same direction then their average will also follow this direction.
When both extremities follow the same direction, the average will also do the same, when both follow an opposite direction then the average will be equal to its precedent value, this is also due to the fact that both extremities are based on the same correction factor (a-b) , else the average wouldn't act that way, now you understand why i made this choice.
Conclusion
I proposed an efficient implementation of a channel indicator that provide an interesting central tendency estimator. This simple implementation would allow for tons of interesting concepts, some of my indicators use a similar approach and allow for great outputs, you'll see them soon enough. I hope this indicator find its use in the community, remember to ask before using this indicator in a script you want to publish.
Thanks for reading !
If you want to discuss about anime stuff send me a pm but don't do it in the commend section.
Periodic ChannelThis indicator try to create a channel by summing a re-scaled and readapted sinusoidal wave form to the price mean.
The length parameter control the speed of the sinusoidal wave form, this parameter is not converted to a sine wave period for allowing a better estimation, higher length's work better but feel free to try shorter periods.
The invert parameter invert the sinusoidal wave.
Each bands represent possible return points, the higher the band the higher the probability.
Inverted sin wave exemple
The performance of the indicator is subjective to the main estimation (blue line), select the parameter that best fit the blue line to the price.
Best ragards
Moving Average Envelopes Backtest Moving Average Envelopes are percentage-based envelopes set above and
below a moving average. The moving average, which forms the base for
this indicator, can be a simple or exponential moving average. Each
envelope is then set the same percentage above or below the moving average.
This creates parallel bands that follow price action. With a moving average
as the base, Moving Average Envelopes can be used as a trend following indicator.
However, this indicator is not limited to just trend following. The envelopes
can also be used to identify overbought and oversold levels when the trend is
relatively flat.
You can change long to short in the Input Settings
WARNING:
- For purpose educate only
- This script to change bars colors.
Moving Average Envelopes Moving Average Envelopes are percentage-based envelopes set above and
below a moving average. The moving average, which forms the base for
this indicator, can be a simple or exponential moving average. Each
envelope is then set the same percentage above or below the moving average.
This creates parallel bands that follow price action. With a moving average
as the base, Moving Average Envelopes can be used as a trend following indicator.
However, this indicator is not limited to just trend following. The envelopes
can also be used to identify overbought and oversold levels when the trend is
relatively flat.
WARNING:
- This script to change bars colors.
Moving Average Envelopes Moving Average Envelopes are percentage-based envelopes set above and
below a moving average. The moving average, which forms the base for
this indicator, can be a simple or exponential moving average. Each
envelope is then set the same percentage above or below the moving average.
This creates parallel bands that follow price action. With a moving average
as the base, Moving Average Envelopes can be used as a trend following indicator.
However, this indicator is not limited to just trend following. The envelopes
can also be used to identify overbought and oversold levels when the trend is
relatively flat.