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!
Optimal
Machine Learning: Optimal Length [YinYangAlgorithms]This Indicator aims to solve an issue that most others face; static lengths. This Indicator will scan lengths from the Min to Max setting (1 - 400 by default) to calculate which is the most Optimal Length in the current market condition. Almost every Indicator uses a length in some part of their calculation, and this length is usually adjustable via the Settings; however it is generally a static fixed length. Static non changing lengths may not always produce optimal results. As market conditions change generally the optimal length will too. For this reason we have created this indicator.
This Indicator will create a Neutral (Min - Max Length), Fast (Min - Mid Length ((Max - Min) / 2)) and Slow (Mid Length ((Max - Min) / 2) - Max Length). This allows you to understand which the Optimal Fast, Slow and Neutral lengths are within the given Mix and Max length settings.
This Indicator then plots these Optimal Lengths as an Oscillator which can then be used within ANOTHER Indicator as a Source within its Settings. Stand alone this Indicator may not prove all that useful, however when its Lengths are inputted into another Indicator it may prove very useful. This allows other Indicators to use the Optimal Length within its calculations from the Settings rather than relying on simply a fixed length. Unfortunately this results in users needing to manually plug the Optimal Length plots into the second Indicator; but it also allows for endless possibilities with applying Machine Learning Optimal Lengths within both Traditional and Non-Traditional Indicators and may give other Pine Coders an easy and effective way to add Machine Learning auto adjustable lengths within their already created Indicators.
The beautiful part about this Indicator is that aside from inputting the Optimal Length Plot into another Indicator, there is no manual updating needed. When the Optimal Length changes, the change will automatically reflect in the other Indicator without the need for you to manually adjust its length. This may be very useful with both time preservation, as well as if there is an automated strategy based upon said Indicator that now won’t need manual intervention.
Tutorial:
By default this is what the Machine Learning: Optimal Length Indicator looks like. It is simply a way of both Displaying and Plotting our current Optimal Length so that we may then use it as a source within ANOTHER Indicator. This will allow the automation of an Optimal Length to be updated, rather than needing any manual input from yourself (aside from set up).
For instance if you set the start length to 1 and the end length to 400 (default settings), it will scan to find the optimal Length setting between 1 and 400. This features 3 types of lengths:
Fast (Green Line): 1-199 (from start length to half way of total)
Slow (Red Line): 200 - 400 (mid way to end length)
Neutral (Blue Line): 1 - 400 (start to end length)
By breaking down the Optimal Length detection into these 3 different types, we can see how the Optimal Length compares and changes based on the lengths allotted to them and how performance changes.
For instance, you may notice that both the Fast and Slow Optimal Length didn’t change much in the example above; however the Neutral Optimal Length changed quite a bit. This is due to the fact that the Neutral is inclusive of all lengths available and may be considered the more accurate due to that. However, this doesn’t mean the Fast and Slow lengths aren’t important and should be used. They may be useful for seeing how something fairs in a Fast and Slow standpoint.
If you change your TimeFrame from 15 minute to 1 Day, you’ll notice that the Optimal Lengths gravitate towards their upper bounds:
199 is max for Fast, it’s at 195
400 is max for Slow, its at 393
400 is max for Neutral, its at 399
The Optimal Length may move up to its upper bounds on Higher Time Frames because there is a lot of price action and long term data being displayed. This may lead to higher lengths performing better in a profitability standpoint since its data is based on so far back and such drastic price movements.
Below we’re going to go through a few examples, including the code so you may reproduce the example and have an understanding of how versatile Inputting an Optimal Length as a source may be within Traditional Indicators.
Adding the Machine Learning: Optimal Length to another Indicator:
You may add the Optimal Length to another Indicator as shown in the example above. In the example we are adding the ‘Machine Learning: Optimal Length - Neutral’ to our Neutral Length within the Settings. The external Indicator needs to have the ability to input the Optimal Length as a Source, this way it can automatically change within the external Indicator when the Optimal Length Indicator changes its Optimal Length.
Please note you may get an error within an external Indicator that accepts the Length as a Source if you don’t select the Machine Learning: Optimal Length. For instance, if you use ‘Close’ within BTC/USDT the length used would be ~36,000. This length is too long and will throw an error.
For this reason, we will ensure the Max Length that may be used is 1000.
Please note, on lower Time Frames you may need to adjust the Max Length. For instance if 20k bar data is used, the Max Length ‘may’ fail to load when going by default Min: 1 and Max: 400. Generally with most pairs it will load if your TradingView subscription is Premium or greater; however if it is less there is a chance it may fail. If it fails for you too often please lower the Max Length Amount; or send us a message we can look into a fix for this.
*** If it fails to load, please try removing the external Indicator and re-adding it and adding the Lengths back as a Source within the Settings. Sometimes it fails, but re-adding may fix it. If it keeps failing afterwards, reduce the Max Length Amount as mentioned above. ***
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 is the code for the example Indicator shown above. This example shows how you may use the Optimal Length as a Source and then use that Optimal Length and plot it as a Simple Moving Average:
//@version=5
indicator("Optimal Length - Backtesting - MA", overlay=true, max_bars_back=5000)
outputType = input.string("All", "Output Type", options= )
lengthSource = input.source(close, "Neutral Length")
lengthSource_fast = input.source(close, "Fast Length")
lengthSource_slow = input.source(close, "Slow Length")
showNeutral = outputType == "Neutral" or outputType == "Fast + Neutral" or outputType == "Slow + Neutral" or outputType == "All"
showFast = outputType == "Fast" or outputType == "Fast + Neutral" or outputType == "Fast + Slow" or outputType == "All"
showSlow = outputType == "Slow" or outputType == "Slow + Neutral" or outputType == "Fast + Slow" or outputType == "All"
//Neutral
optimalLength = math.min(math.max(math.round(lengthSource), 1), 1000)
optimalMA = ta.sma(close, optimalLength)
//Fast
optimalLength_fast = math.min(math.max(math.round(lengthSource_fast), 1), 1000)
optimalMA_fast = ta.sma(close, optimalLength_fast)
//Slow
optimalLength_slow = math.min(math.max(math.round(lengthSource_slow), 1), 1000)
optimalMA_slow = ta.sma(close, optimalLength_slow)
plot(showNeutral ? optimalMA : na, color=color.blue)
plot(showFast ? optimalMA_fast : na, color=color.green)
plot(showSlow ? optimalMA_slow : na, color=color.red)
Bollinger Bands:
In the two examples above for Bollinger Bands we have first the 15 Minute Time Frame and then the 1 Day Time Frame. As described above in ‘Adding the Machine Learning: Optimal Length to another Indicator’ sometimes it may fail to load, for this reason in the 15 Minute it was reduced to a max of 300 Length.
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 than 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.
Below is the code for the Bollinger Bands example above:
//@version=5
indicator("Optimal Length - Backtesting - Bollinger Bands", overlay=true, max_bars_back=5000)
outputType = input.string("All", "Output Type", options= )
lengthSource = input.source(close, "Neutral Length")
lengthSource_fast = input.source(close, "Fast Length")
lengthSource_slow = input.source(close, "Slow Length")
showNeutral = outputType == "Neutral" or outputType == "Fast + Neutral" or outputType == "Slow + Neutral" or outputType == "All"
showFast = outputType == "Fast" or outputType == "Fast + Neutral" or outputType == "Fast + Slow" or outputType == "All"
showSlow = outputType == "Slow" or outputType == "Slow + Neutral" or outputType == "Fast + Slow" or outputType == "All"
mult = 2.0
src = close
neutralColor = color.blue
slowColor = color.red
fastColor = color.green
//Neutral
optimalLength = math.min(math.max(math.round(lengthSource), 1), 1000)
optimalMA = ta.sma(close, optimalLength)
//Fast
optimalLength_fast = math.min(math.max(math.round(lengthSource_fast), 1), 1000)
optimalMA_fast = ta.sma(close, optimalLength_fast)
//Slow
optimalLength_slow = math.min(math.max(math.round(lengthSource_slow), 1), 1000)
optimalMA_slow = ta.sma(close, optimalLength_slow)
//Neutral Bollinger Bands
dev = mult * ta.stdev(src, math.round(optimalLength))
upper = optimalMA + dev
lower = optimalMA - dev
plot(showNeutral ? optimalMA : na, "Neutral Basis", color=color.new(neutralColor, 0))
p1 = plot(showNeutral ? upper : na, "Neutral Upper", color=color.new(neutralColor, 50))
p2 = plot(showNeutral ? lower : na, "Neutral Lower", color=color.new(neutralColor, 50))
fill(p1, p2, title = "Neutral Background", color=color.new(neutralColor, 96))
//Slow Bollinger Bands
dev_slow = mult * ta.stdev(src, math.round(optimalLength_slow))
upper_slow = optimalMA_slow + dev_slow
lower_slow = optimalMA_slow - dev_slow
plot(showFast ? optimalMA_slow : na, "Slow Basis", color=color.new(slowColor, 0))
p1_slow = plot(showFast ? upper_slow : na, "Slow Upper", color=color.new(slowColor, 50))
p2_slow = plot(showFast ? lower_slow : na, "Slow Lower", color=color.new(slowColor, 50))
fill(p1_slow, p2_slow, title = "Slow Background", color=color.new(slowColor, 96))
//Fast Bollinger Bands
dev_fast = mult * ta.stdev(src, math.round(optimalLength_fast))
upper_fast = optimalMA_fast + dev_fast
lower_fast = optimalMA_fast - dev_fast
plot(showSlow ? optimalMA_fast : na, "Fast Basis", color=color.new(fastColor, 0))
p1_fast = plot(showSlow ? upper_fast : na, "Fast Upper", color=color.new(fastColor, 50))
p2_fast = plot(showSlow ? lower_fast : na, "Fast Lower", color=color.new(fastColor, 50))
fill(p1_fast, p2_fast, title = "Fast Background", color=color.new(fastColor, 96))
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 our 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.
The code to reproduce these Donchian Channels as displayed above is so:
//@version=5
indicator("Optimal Length - Backtesting - Donchian Channels", overlay=true, max_bars_back=5000)
outputType = input.string("All", "Output Type", options= )
lengthSource = input.source(close, "Neutral Length")
lengthSource_fast = input.source(close, "Fast Length")
lengthSource_slow = input.source(close, "Slow Length")
showNeutral = outputType == "Neutral" or outputType == "Fast + Neutral" or outputType == "Slow + Neutral" or outputType == "All"
showFast = outputType == "Fast" or outputType == "Fast + Neutral" or outputType == "Fast + Slow" or outputType == "All"
showSlow = outputType == "Slow" or outputType == "Slow + Neutral" or outputType == "Fast + Slow" or outputType == "All"
mult = 2.0
src = close
neutralColor = color.blue
slowColor = color.red
fastColor = color.green
//Neutral
optimalLength = math.min(math.max(math.round(lengthSource), 1), 1000)
optimalMA = ta.sma(close, optimalLength)
//Fast
optimalLength_fast = math.min(math.max(math.round(lengthSource_fast), 1), 1000)
optimalMA_fast = ta.sma(close, optimalLength_fast)
//Slow
optimalLength_slow = math.min(math.max(math.round(lengthSource_slow), 1), 1000)
optimalMA_slow = ta.sma(close, optimalLength_slow)
//Neutral Donchian Channels
lower_dc = ta.lowest(optimalLength)
upper_dc = ta.highest(optimalLength)
basis_dc = math.avg(upper_dc, lower_dc)
plot(showNeutral ? basis_dc : na, "Donchain Channel - Neutral Basis", color=color.new(neutralColor, 0))
u = plot(showNeutral ? upper_dc : na, "Donchain Channel - Neutral Upper", color=color.new(neutralColor, 50))
l = plot(showNeutral ? lower_dc : na, "Donchain Channel - Neutral Lower", color=color.new(neutralColor, 50))
fill(u, l, color=color.new(neutralColor, 96), title = "Donchain Channel - Neutral Background")
//Fast Donchian Channels
lower_dc_fast = ta.lowest(optimalLength_fast)
upper_dc_fast = ta.highest(optimalLength_fast)
basis_dc_fast = math.avg(upper_dc_fast, lower_dc_fast)
plot(showFast ? basis_dc_fast : na, "Donchain Channel - Fast Neutral Basis", color=color.new(fastColor, 0))
u_fast = plot(showFast ? upper_dc_fast : na, "Donchain Channel - Fast Upper", color=color.new(fastColor, 50))
l_fast = plot(showFast ? lower_dc_fast : na, "Donchain Channel - Fast Lower", color=color.new(fastColor, 50))
fill(u_fast, l_fast, color=color.new(fastColor, 96), title = "Donchain Channel - Fast Background")
//Slow Donchian Channels
lower_dc_slow = ta.lowest(optimalLength_slow)
upper_dc_slow = ta.highest(optimalLength_slow)
basis_dc_slow = math.avg(upper_dc_slow, lower_dc_slow)
plot(showSlow ? basis_dc_slow : na, "Donchain Channel - Slow Neutral Basis", color=color.new(slowColor, 0))
u_slow = plot(showSlow ? upper_dc_slow : na, "Donchain Channel - Slow Upper", color=color.new(slowColor, 50))
l_slow = plot(showSlow ? lower_dc_slow : na, "Donchain Channel - Slow Lower", color=color.new(slowColor, 50))
fill(u_slow, l_slow, color=color.new(slowColor, 96), title = "Donchain Channel - Slow Background")
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 our 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 out 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.
The code used to reproduce the example above is as follows:
//@version=5
indicator("Optimal Length - Backtesting - Envelopes", overlay=true, max_bars_back=5000)
outputType = input.string("All", "Output Type", options= )
displayType = input.string("Envelope Adjusted", "Display Type", options= )
lengthSource = input.source(close, "Neutral Length")
lengthSource_fast = input.source(close, "Fast Length")
lengthSource_slow = input.source(close, "Slow Length")
showNeutral = outputType == "Neutral" or outputType == "Fast + Neutral" or outputType == "Slow + Neutral" or outputType == "All"
showFast = outputType == "Fast" or outputType == "Fast + Neutral" or outputType == "Fast + Slow" or outputType == "All"
showSlow = outputType == "Slow" or outputType == "Slow + Neutral" or outputType == "Fast + Slow" or outputType == "All"
mult = 2.0
src = close
neutralColor = color.blue
slowColor = color.red
fastColor = color.green
//Neutral
optimalLength = math.min(math.max(math.round(lengthSource), 1), 1000)
optimalMA = ta.sma(close, optimalLength)
//Fast
optimalLength_fast = math.min(math.max(math.round(lengthSource_fast), 1), 1000)
optimalMA_fast = ta.sma(close, optimalLength_fast)
//Slow
optimalLength_slow = math.min(math.max(math.round(lengthSource_slow), 1), 1000)
optimalMA_slow = ta.sma(close, optimalLength_slow)
percent = 10.0
maxAmount = math.max(optimalLength, optimalLength_fast, optimalLength_slow)
//Neutral
k = displayType == "Envelope" ? percent/100.0 : (percent/100.0) / (optimalLength / maxAmount)
upper_env = optimalMA * (1 + k)
lower_env = optimalMA * (1 - k)
plot(showNeutral ? optimalMA : na, "Envelope - Neutral Basis", color=color.new(neutralColor, 0))
u_env = plot(showNeutral ? upper_env : na, "Envelope - Neutral Upper", color=color.new(neutralColor, 50))
l_env = plot(showNeutral ? lower_env : na, "Envelope - Neutral Lower", color=color.new(neutralColor, 50))
fill(u_env, l_env, color=color.new(neutralColor, 96), title = "Envelope - Neutral Background")
//Fast
k_fast = displayType == "Envelope" ? percent/100.0 : (percent/100.0) / (optimalLength_fast / maxAmount)
upper_env_fast = optimalMA_fast * (1 + k_fast)
lower_env_fast = optimalMA_fast * (1 - k_fast)
plot(showFast ? optimalMA_fast : na, "Envelope - Fast Basis", color=color.new(fastColor, 0))
u_env_fast = plot(showFast ? upper_env_fast : na, "Envelope - Fast Upper", color=color.new(fastColor, 50))
l_env_fast = plot(showFast ? lower_env_fast : na, "Envelope - Fast Lower", color=color.new(fastColor, 50))
fill(u_env_fast, l_env_fast, color=color.new(fastColor, 96), title = "Envelope - Fast Background")
//Slow
k_slow = displayType == "Envelope" ? percent/100.0 : (percent/100.0) / (optimalLength_slow / maxAmount)
upper_env_slow = optimalMA_slow * (1 + k_slow)
lower_env_slow = optimalMA_slow * (1 - k_slow)
plot(showSlow ? optimalMA_slow : na, "Envelope - Slow Basis", color=color.new(slowColor, 0))
u_env_slow = plot(showSlow ? upper_env_slow : na, "Envelope - Slow Upper", color=color.new(slowColor, 50))
l_env_slow = plot(showSlow ? lower_env_slow : na, "Envelope - Slow Lower", color=color.new(slowColor, 50))
fill(u_env_slow, l_env_slow, color=color.new(slowColor, 96), title = "Envelope - Slow Background")
Hopefully these examples, including reproducing code, have given you some insight as to how useful this Machine Learning: Optimal Length may be and how another Indicator may easily modify their existing code to incorporate the usage of such Machine Learning: Optimal Length. We likewise will publish a Backtesting Indicator which incorporates all of the concepts we’ve gone over within here; in case you wish to take advantage of the Traditional Indicators mentioned above that allow the input of Machine Learning: Optimal Length and don’t wish to code them.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
Machine Learning: Optimal RSI [YinYangAlgorithms]This Indicator, will rate multiple different lengths of RSIs to determine which RSI to RSI MA cross produced the highest profit within the lookback span. This ‘Optimal RSI’ is then passed back, and if toggled will then be thrown into a Machine Learning calculation. You have the option to Filter RSI and RSI MA’s within the Machine Learning calculation. What this does is, only other Optimal RSI’s which are in the same bullish or bearish direction (is the RSI above or below the RSI MA) will be added to the calculation.
You can either (by default) use a Simple Average; which is essentially just a Mean of all the Optimal RSI’s with a length of Machine Learning. Or, you can opt to use a k-Nearest Neighbour (KNN) calculation which takes a Fast and Slow Speed. We essentially turn the Optimal RSI into a MA with different lengths and then compare the distance between the two within our KNN Function.
RSI may very well be one of the most used Indicators for identifying crucial Overbought and Oversold locations. Not only that but when it crosses its Moving Average (MA) line it may also indicate good locations to Buy and Sell. Many traders simply use the RSI with the standard length (14), however, does that mean this is the best length?
By using the length of the top performing RSI and then applying some Machine Learning logic to it, we hope to create what may be a more accurate, smooth, optimal, RSI.
Tutorial:
This is a pretty zoomed out Perspective of what the Indicator looks like with its default settings (except with Bollinger Bands and Signals disabled). If you look at the Tables above, you’ll notice, currently the Top Performing RSI Length is 13 with an Optimal Profit % of: 1.00054973. On its default settings, what it does is Scan X amount of RSI Lengths and checks for when the RSI and RSI MA cross each other. It then records the profitability of each cross to identify which length produced the overall highest crossing profitability. Whichever length produces the highest profit is then the RSI length that is used in the plots, until another length takes its place. This may result in what we deem to be the ‘Optimal RSI’ as it is an adaptive RSI which changes based on performance.
In our next example, we changed the ‘Optimal RSI Type’ from ‘All Crossings’ to ‘Extremity Crossings’. If you compare the last two examples to each other, you’ll notice some similarities, but overall they’re quite different. The reason why is, the Optimal RSI is calculated differently. When using ‘All Crossings’ everytime the RSI and RSI MA cross, we evaluate it for profit (short and long). However, with ‘Extremity Crossings’, we only evaluate it when the RSI crosses over the RSI MA and RSI <= 40 or RSI crosses under the RSI MA and RSI >= 60. We conclude the crossing when it crosses back on its opposite of the extremity, and that is how it finds its Optimal RSI.
The way we determine the Optimal RSI is crucial to calculating which length is currently optimal.
In this next example we have zoomed in a bit, and have the full default settings on. Now we have signals (which you can set alerts for), for when the RSI and RSI MA cross (green is bullish and red is bearish). We also have our Optimal RSI Bollinger Bands enabled here too. These bands allow you to see where there may be Support and Resistance within the RSI at levels that aren’t static; such as 30 and 70. The length the RSI Bollinger Bands use is the Optimal RSI Length, allowing it to likewise change in correlation to the Optimal RSI.
In the example above, we’ve zoomed out as far as the Optimal RSI Bollinger Bands go. You’ll notice, the Bollinger Bands may act as Support and Resistance locations within and outside of the RSI Mid zone (30-70). In the next example we will highlight these areas so they may be easier to see.
Circled above, you may see how many times the Optimal RSI faced Support and Resistance locations on the Bollinger Bands. These Bollinger Bands may give a second location for Support and Resistance. The key Support and Resistance may still be the 30/50/70, however the Bollinger Bands allows us to have a more adaptive, moving form of Support and Resistance. This helps to show where it may ‘bounce’ if it surpasses any of the static levels (30/50/70).
Due to the fact that this Indicator may take a long time to execute and it can throw errors for such, we have added a Setting called: Adjust Optimal RSI Lookback and RSI Count. This settings will automatically modify the Optimal RSI Lookback Length and the RSI Count based on the Time Frame you are on and the Bar Indexes that are within. For instance, if we switch to the 1 Hour Time Frame, it will adjust the length from 200->90 and RSI Count from 30->20. If this wasn’t adjusted, the Indicator would Timeout.
You may however, change the Setting ‘Adjust Optimal RSI Lookback and RSI Count’ to ‘Manual’ from ‘Auto’. This will give you control over the ‘Optimal RSI Lookback Length’ and ‘RSI Count’ within the Settings. Please note, it will likely take some “fine tuning” to find working settings without the Indicator timing out, but there are definitely times you can find better settings than our ‘Auto’ will create; especially on higher Time Frames. The Minimum our ‘Auto’ will create is:
Optimal RSI Lookback Length: 90
RSI Count: 20
The Maximum it will create is:
Optimal RSI Lookback Length: 200
RSI Count: 30
If there isn’t much bar index history, for instance, if you’re on the 1 Day and the pair is BTC/USDT you’ll get < 4000 Bar Indexes worth of data. For this reason it is possible to manually increase the settings to say:
Optimal RSI Lookback Length: 500
RSI Count: 50
But, please note, if you make it too high, it may also lead to inaccuracies.
We will conclude our Tutorial here, hopefully this has given you some insight as to how calculating our Optimal RSI and then using it within Machine Learning may create a more adaptive RSI.
Settings:
Optimal RSI:
Show Crossing Signals: Display signals where the RSI and RSI Cross.
Show Tables: Display Information Tables to show information like, Optimal RSI Length, Best Profit, New Optimal RSI Lookback Length and New RSI Count.
Show Bollinger Bands: Show RSI Bollinger Bands. These bands work like the TDI Indicator, except its length changes as it uses the current RSI Optimal Length.
Optimal RSI Type: This is how we calculate our Optimal RSI. Do we use all RSI and RSI MA Crossings or just when it crosses within the Extremities.
Adjust Optimal RSI Lookback and RSI Count: Auto means the script will automatically adjust the Optimal RSI Lookback Length and RSI Count based on the current Time Frame and Bar Index's on chart. This will attempt to stop the script from 'Taking too long to Execute'. Manual means you have full control of the Optimal RSI Lookback Length and RSI Count.
Optimal RSI Lookback Length: How far back are we looking to see which RSI length is optimal? Please note the more bars the lower this needs to be. For instance with BTC/USDT you can use 500 here on 1D but only 200 for 15 Minutes; otherwise it will timeout.
RSI Count: How many lengths are we checking? For instance, if our 'RSI Minimum Length' is 4 and this is 30, the valid RSI lengths we check is 4-34.
RSI Minimum Length: What is the RSI length we start our scans at? We are capped with RSI Count otherwise it will cause the Indicator to timeout, so we don't want to waste any processing power on irrelevant lengths.
RSI MA Length: What length are we using to calculate the optimal RSI cross' and likewise plot our RSI MA with?
Extremity Crossings RSI Backup Length: When there is no Optimal RSI (if using Extremity Crossings), which RSI should we use instead?
Machine Learning:
Use Rational Quadratics: Rationalizing our Close may be beneficial for usage within ML calculations.
Filter RSI and RSI MA: Should we filter the RSI's before usage in ML calculations? Essentially should we only use RSI data that are of the same type as our Optimal RSI? For instance if our Optimal RSI is Bullish (RSI > RSI MA), should we only use ML RSI's that are likewise bullish?
Machine Learning Type: Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?
KNN Distance Type: We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.
Machine Learning Length: How far back is our Machine Learning going to keep data for.
k-Nearest Neighbour (KNN) Length: How many k-Nearest Neighbours will we account for?
Fast ML Data Length: What is our Fast ML Length? This is used with our Slow Length to create our KNN Distance.
Slow ML Data Length: What is our Slow ML Length? This is used with our Fast Length to create our KNN Distance.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
Optimal Weighted Moving AverageThe Optimal Weighted Moving Average was created by Thomas Hutchinson and Peter G. Zhang, Ph.D. (Stocks & Commodities V. 11:12 (500-505)) and it is very similar to a classic weighted moving average but it uses the correlation between the input and the optimal weighted moving average output to use as the weights. Buy when the line turns green and sell when it turns red.
Let me know if you would like to see me publish any other scripts or if you want something custom done!
Self-Adjusting Parabolic SARWhat is this tool?
This is an implementation of the well-known Parabolic SAR indicator that can adjust parameters on the fly to achieve a better profitability.
The algorithm was borrowed from Profitable Parabolic SAR and connected to the basic Parabolic SAR implementation. So, now it will switch parameters automatically without any manual work required.
Profitable Parabolic SAR indicator can be found here:
Parabolic SAR indicator can be found here:
EQma - Adaptive Smoothing Based On Optimal Markets DetectionIntroduction
"You don’t put sunscreen when there is no sun, you don’t use an umbrella when there is no rain, you don’t use a kite when there is no wind, so why would you use a trend following strategy when there is no trend ?"
This is how i start my 4th paper "A New Technical Indicator For Optimal Markets Detection" where i present two new technical indicators. We talked about the first one, running equity, which aim to detect the best moment to enter trades, based on this new metric i made an adaptive moving average.
You can see the full paper here figshare.com
The Indicator
The moving average is based on exponential averaging and use a smoothing variable alpha based on the running equity metric, in order to calculate alpha the running equity is divided by the optimal equity which show the best returns possible for the conditions used. Basically the indicator work as follow :
When the running equity is close to the optimal equity it means that the price need no/little filtering since it does not contain information that need to be filtered, therefore alpha is high, however when the running equity is far from the optimal equity this mean that the price posses malign information that need to be removed.
This is why the indicator will be closer to the price when length is high :
See the full paper for an explanation on how this work.
I added various options for the indicator, one will reduce the lag by squaring alpha, thus giving for length = 14 :
The efficient option will make use of recursion to provide a more efficient indicator :
In green the efficient version, note how this option can allow a better fit with the price.
Conclusion
This is an indicator but at its core its rather a framework, if you have read the paper you'll see that the conditions are just 1 and -1 that changes with time, basically its like making a strategy with :
Condition = if buy then 1 else if sell then -1 else Precedent value of condition.
So those two indicators allow to give useful and usable information about your strategy. I hope it can be of use for anyone here, if so don't hesitate to send me what you made using the proposed indicator (and with all my indicators in general). If you are writing a paper and you think this indicator could fit in your work then let me know so i can be aware of it :)
Thanks for reading !
Acknowledgement
My papers are quite ridiculous but they still manage to get some views, some researchers don't even reach those number in so little time which is quite unfortunate but also really motivating for me, so thanks to those who take time to read them and give me some feedback :)
Self-Adjusting SuperTrendWhat is this tool?
This is an implementation of the well-known SuperTrend indicator that can adjust parameters on the fly to achieve a better profitability.
The algorithm was borrowed from Profitable SuperTrend and connected to the basic SuperTrend implementation. So, now it will switch parameters automatically without any manual work required.
Alerts
The same alerts as for the basic SuperTrend + special alert to notify user about parameters switching.
Profitable SuperTrend indicator can be found here:
SuperTrend indicator can be found here:
Good luck!
Profitable MAMA & FAMA CrossoverIntroduction
The MESA Adaptive Moving Average (MAMA) was originally presented by John F. Ehlers. By design, it is a special kind of Exponential Moving Average with self-adjusting alpha. Its adaptation is based on the rate change of phase as measured by the Homodyne Discriminator and the alpha parameter is allowed to range between a maximum and minimum value (Fast Limit and Slow Limit).
Key Point: Ehlers suggested the maximum value to be 0.5 and the minimum to be 0.05 .
The variable alpha is computed as the Fast Limit divided by the phase rate of change. If the phase rate of change is large, the variable alpha is bounded at the SlowLimit. Then, this alpha is used to compute MAMA and FAMA (Following Adaptive Moving Average).
Should we rely on Ehlers' suggestions if we want to achieve the best result with MAMA & FAMA crossover system?
Well, he is a good specialist and widely recognized author, I respect him, but the answer is no and you can see results on the chart.
What is our goal?
We want to find the best configuration for MAMA & FAMA Crossover. To achieve that we need to analyze the MAMA's alpha parameter or, more specific, the bounds for this parameter, Fast and Slow Limits.
What is this tool?
This tool is a performance optimizer that uses decision tree-based algorithm under the hood to find the most profitable settings for the MAMA & FAMA Crossover. It analyzes a bunch of different Fast Limits (between 0.01 to 0.8 with step of 0.1 ) and Slow Limits (between 0.01 to 0.6 with step of 0.1 ) and backtests each combination across the entire history of an instrument. If the more profitable parameters were found, the indicator will switch its values to the found ones immediately.
So, instead of manually selecting and testing parameters just apply this indicator to your chart and
relax - the algorithm will find the best parameters for you
Alerts
It has a special alert that notifies when the more profitable settings were detected.
NOTE: It does not change what has already been plotted.
NOTE 2: This is not a strategy, but an algorithmic optimizer.
Reference: www.mesasoftware.com
MAMA & FAMA Crossover can be found here:
Optimal 4H Moving Average Ribbon for ETH
Stolen from Madrid Moving Average Ribbon : 2.0 : MMAR
madridjourneyonws.blogspot.com
Adapted for 4H optimal EMAs
This plots a moving average ribbon, please use the exponential not the standard.
It is based on a constant calculation of the most profitable EMAs to trade on the 4H time frame for Ethereum!
Thus the values will be updated with time as they change.
As an example trading the EMA 167 will return ~17742% (15.8.2019)on initial investment starting March 2016, compared to holding giving ~1225%.
It is a simple price breaks above EMAs to go long and break below to go short strategy but I recomened waiting for the full twist.
Lime : Uptrend. Long trading
Green : Reentry (buy the dip) or downtrend reversal warning
Red : Downtrend. Short trading
Maroon : Short Reentry (sell the peak) or uptrend reversal warning
Optimal 4H Moving Average Ribbon//
// Stolen from Madrid Moving Average Ribbon : 2.0 : MMAR
// madridjourneyonws.blogspot.com
// Adapted for 4H optimal EMAs
//
// This plots a moving average ribbon, please use the exponential not the standard.
// It is based on a constant calculation of the most profitable EMAs to trade on the 4H time frame for Ethereum!
// Thus the values will be updated with time as they change.
// As an example trading the EMA 167 will return ~17742% (15.8.2019)on initial investment starting March 2016, compared to holding giving ~1225%.
// It is a simple price breaks above EMAs to go long and break below to go short strategy but I recomened waiting for the full twist.
//
//
// Lime : Uptrend. Long trading
// Green : Reentry (buy the dip) or downtrend reversal warning
// Red : Downtrend. Short trading
// Maroon : Short Reentry (sell the peak) or uptrend reversal warning
//
Profitable Jurik RSXIntroduction
As you know the Jurik RSX is a "noise free" smoothed version of RSI (Relative Strength Index), with no added lag.
It was originally developed by Mark Jurik and is used the same way as RSI. To learn more about this indicator see www.jurikres.com
The most basic and common strategy is to use the crossovers between Jurik RSX and its overbought/oversold levels as trade signals:
when RSX crosses above 30, go Long
when RSX crosses below 70, go Short
exit when a crossover occurs in the opposite direction
What is this tool?
This tool is a performance scanner that uses a decision tree-based algorithm under the hood to find the most profitable settings for Jurik RSX. It analyzes the range of periods between 2 to 100 and backtests the Jurik RSX for each period (using the strategy mentioned above) across the entire history of an instrument. If the more profitable parameter was found, the indicator will switch its value to the found one immediately.
So, instead of manually selecting parameters just apply it to your chart and relax - the algorithm will do it for you, everywhere you want.
The algorithm can work in two modes: Basic and Early Switch. The Early Switch algorithm makes some assumptions and activates a set of optimizations to find a better setting DURING the trades, not after they were actually closed.
The difference is illustrated on the screenshot below
But two modes can show identical values depending on timeframe
Additionally you can set up a backtest window through indicator's settings (the optimizers which were published before will get this feature soon).
Alerts
It has a special alert that notifies when a more profitable period was detected.
NOTE: It does not change what has already been plotted.
NOTE 2: This is not a strategy, but an algorithmic optimizer.
Profitable RSI (Relative Strength Index)Introduction
As you know the Relative Strength Index (RSI) was originally developed by J. Welles Wilder and was described in his book "New Concepts in Technical Trading Systems" (1978). It is intended to measure the strength or weakness of an instrument for the specified period.
The most basic strategy is to use the crossovers as trade signals:
when RSI crosses above 30, go Long
when RSI crosses below 70, go Short
Exit when a crossover occurs in the opposite direction
What is this tool?
This tool is a performance scanner that uses a decision tree-based algorithm under the hood to find the most profitable settings for RSI. It analyzes the range of periods between 2 to 100 and backtests the RSI for each period using the strategy mentioned above across the entire history of an instrument. If the more profitable parameter was found, the indicator will switch its value to the found one immediately.
So, instead of manually selecting parameters just apply it to your chart and relax - the algorithm will do it for you.
The algorithm can work in two modes: Basic and Advanced "Early Switch" . The Early Switch algorithm makes some assumptions and activates a set of optimizations to find the better setting DURING the trades, not after they were closed.
The difference is illustrated on the screenshot below:
Additionally you can set up a backtest window through indicator's settings (the optimizers which were published before will get this feature soon).
Alerts
It has a special alert that notifies when a more profitable period was detected.
NOTE: It does not change what has already been plotted.
NOTE 2: This is not a strategy, but an algorithmic optimizer.
Day after day. Night after night.
I've been waiting to program again.
Day after day. Night by to night.
Trading is waiting inside your heart.
Ehlers Modified Optimum Elliptic FilterThis indicator was originally developed by John F. Ehlers (Stocks & Commodities, V.18:7 (July, 2000): "Optimal Detrending").
Mr. Ehlers didn't stop and improved his Optimum Elliptic Filter. To reduce the effects of lag he added the one day momentum of the price to the price value.
This modification produce a better response.
Ehlers Optimum Elliptic FilterThis indicator was originally developed by John F. Ehlers (Stocks & Commodities, V.18:7 (July, 2000): "Optimal Detrending").
Mr. Ehlers worked on the smoother that could have no more than a one-bar lag. An elliptic filter provides the maximum amount of smoothing under the constraint of a given lag.
Profitable Parabolic SARIntroduction
As you know, Parabolic Stop and Reverse (SAR, PSAR) was originally developed by J. Welles Wilder and was described in his book "New Concepts in Technical Trading Systems" (1978). It derives its name from the fact that when charted, the pattern formed by the points resembles a parabola.
Mr. Wilder described it as "one of my favorite systems because it squeezes more profit out of an intermediate move than any method I know" .
Interpretation
PSAR follows price and can be considered a trend following indicator. Once a downtrend reverses and starts up, PSAR follows prices like a trailing stop. Same is true for the opposite direction.
Due to its nature, PSAR continuosly protects on long and short positions.
Parameters
One of the key components of PSAR is the Acceleration Factor (AF). The AF is one of a progression of numbers beginning at 0.02 and ending at 0.2 . The AF is increased by the increment of 0.02 each time that a new high is made until a value of 0.2 is reached.
Mr. Wilder used the next parameters
Start: 0.02
Increment: 0.02
Maximum: 0.2
and they are default for the built-in PSAR indicator and its strategy.
But are these params really profitable? Mr. Wilder noticed that "I have tried many different acceleration factors on this system and have found that a consistent increase of 0.02 works best overall...the range for the incremental increase is between 0.018 and 0.021 " .
That was then, in 1978. Other times have come. Is our grandpa still right in his recommendations?
I made this tool to figure it out.
What is this tool?
This tool is a performance scanner that uses a decision tree-based algorithm under the hood to find the most profitable settings for PSAR. It analyzes a bunch of different Start (between 0.001 to 0.02 ) and Increment (between 0.001 to 0.03 ) parameters and backtests each combination across the entire history of an instrument. If the more profitable parameters were found, the indicator will switch its values to the found ones immediately.
Instead of manually selecting parameters, just relax - the algorithm will do it for you.
It doesn't touch the last parameter, Maximum , for two reasons.
First, as Mr. Wilder noticed in his book, "...the number of increases it takes to reach at least 0.2 , but do not exceed 0.22 " . That is, the parameter sits in a very narrow range.
Second, I tested different maximums and I came to the conclusion that this parameter has a minimal impact on net profit, compared with the more significant parameters of start and increment.
Alerts
It has an alert that notifies when the more profitable settings were detected.
NOTE : It does not change what has already been plotted.
Good luck!
Profitable SMA CrossoverWhat is this tool?
This tool is a performance scanner of the crossover trading system that is based on the two simple moving averages (SMA). It uses a decision tree-based algorithm under the hood to find and plot the most profitable periods of the SMA combination.
It analyzes the range of periods between 4 to 45 and backtests each combination across the entire history of an instrument. If the more profitable periods were detected the indicator will switch periods of the moving averages immediately.
This is an add-on for the Ingenious SMA Crossover but can be used standalone.
Alerts
It has an alert that notifies when the more profitable periods were detected.
NOTE : It does not change what has already been plotted.
Good luck!
Ingenious SMA CrossoverIntroduction
A popular use for moving averages is to develop simple trading systems based on moving average crossovers. A trading system using two moving averages would give a buy signal when the shorter (faster) moving average advances above the longer (slower) moving average. A sell signal would be given when the shorter moving average crosses below the longer moving average. The speed of the systems and the number of signals generated will depend on the period of the moving averages.
What is this tool?
This tool is a crossover system of two simple moving averages. I called it "Ingenious" because it uses a decision tree-based algorithm under the hood to find and plot the most profitable SMA combination.
It analyzes the range of periods between 4 to 45 and backtests each combination across the entire history of an instrument. If the more profitable periods were detected the indicator will switch periods of the moving averages to the found ones immediately.
NOTE : It does not change what has already been plotted.
Good luck!