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!
Fractales
@tk · fractal emas█ OVERVIEW
This script is an indicator that plots short, medium and long moving averages for multiple fractals. This script was based on sharks EMAs by rlvs indicator, that plots multiple rays for each fractals into the chart. The main feature of this indicator is the customizability. The calculation itself is simple as moving average.
█ MOTIVATION
The trader can customize all aspects of the plotted data. The text size, extended line length, the moving average type — exponential, simple, etc... — the length of fractal rays, line style, line width and visibility. To keep minimalist, this indicator simplifies the logic of line colors based on the purpose of each moving averages. To prevent overnoise the chart with multiple lines with multiple colors for each fractal timefraes, the trader needs to keep in mind that the all lines with the "short" moving average color for example, will represents the short moving averages lines for all fractals. This logic is applied for medium and long moving averages either.
█ CONCEPT
The trading concept to use this indicator is to make entries on uptrend or downtrend pullbacks when the asset price reaches the short, medium or long moving averages price levels. But this strategy don't works alone. It needs to be aligned together with others indicators like RSI, Chart Patterns, Support and Resistance, and so on... Even more confluences that you have, bigger are your chances to increase the probability for a successful trade. So, don't use this indicator alone. Compose a trading strategy and use it to improve your analysis.
█ CUSTOMIZATION
This indicator allows the trader to customize the following settings:
GENERAL
Text size
Changes the font size of the labels to improve accessibility.
Type: string
Options: `tiny`, `small`, `normal`, `large`.
Default: `small`
SHORT
Type
Select the Short Moving Average calculation type.
Type: string
Options: `EMA`, `SMA`, `HMA`, `VWMA`, `WMA`.
Default: `EMA`
Length
Changes the base length for the Short Moving Average calculation.
Type: int
Default: 12
Source
Changes the base source for the Short Moving Average calculation.
Type: float
Default: close
Color
The base color that will represent the Short Moving Average.
Type: color
Default: color.rgb(255, 235, 59) (yellow)
Fractal Style
The fractal ray line style.
Type: string
Options: `dotted`, `dashed`, `solid`.
Default: `dotted`
Fractal Width
The fractal ray line width.
Type: string
Options: `1px`, `2px`, `3px`, `4px`.
Default: `1px`
Fractal Ray Length
The fractal ray line length.
Type: int
Default: 12
MEDIUM
Type
Select the Medium Moving Average calculation type.
Type: string
Options: `EMA`, `SMA`, `HMA`, `VWMA`, `WMA`.
Default: `EMA`
Length
Changes the base length for the Medium Moving Average calculation.
Type: int
Default: 26
Source
Changes the base source for the Medium Moving Average calculation.
Type: float
Default: close
Color
The base color that will represent the Short Moving Average.
Type: color
Default: color.rgb(0, 230, 118) (lime)
Fractal Style
The fractal ray line style.
Type: string
Options: `dotted`, `dashed`, `solid`.
Default: `dotted`
Fractal Width
The fractal ray line width.
Type: string
Options: `1px`, `2px`, `3px`, `4px`.
Default: `1px`
Fractal Ray Length
The fractal ray line length.
Type: int
Default: 12
LONG
Type
Select the Long Moving Average calculation type.
Type: string
Options: `EMA`, `SMA`, `HMA`, `VWMA`, `WMA`.
Default: `EMA`
Length
Changes the base length for the Long Moving Average calculation.
Type: int
Default: 200
Source
Changes the base source for the Long Moving Average calculation.
Type: float
Default: close
Color
The base color that will represent the Short Moving Average.
Type: color
Default: color.rgb(255, 82, 82) (red)
Fractal Style
The fractal ray line style.
Type: string
Options: `dotted`, `dashed`, `solid`.
Default: `dotted`
Fractal Width
The fractal ray line width.
Type: string
Options: `1px`, `2px`, `3px`, `4px`.
Default: `1px`
Fractal Ray Length
The fractal ray line length.
Type: int
Default: 12
VISIBILITY
Show Fractal Rays · (Short)
Shows short moving average fractal rays.
Type: bool
Default: true
Show Fractal Rays · (Medium)
Shows short moving average fractal rays.
Type: bool
Default: true
Show Fractal Rays · (Long)
Shows short moving average fractal rays.
Type: bool
Default: true
█ FUNCTIONS
The script contains the following functions:
`fn_labelizeTimeFrame`
Labelize timeframe period in minutes and hours.
Parameters:
tf: (string) Timeframe period to be labelized.
Returns: (string) Labelized timeframe string.
`fn_builtInLineStyle`
Converts simple string to built-in line style variable value.
Parameters:
lineStyle: (string) The line style simple string.
Returns: (string) Built-in line style string value.
`fn_builtInLineWidth`
Converts simple pixel string to line width number value.
Parameters:
lineWidth: (string) The line width pixel simple string.
Returns: (string) Built-in line width number value.
`fn_requestFractal`
Requests fractal data based on `period` given an expression.
Parameters:
period: (string) The period timeframe of fractal.
expression: (series float) The expression to retrieve data from fractal.
Returns: (mixed) A result determined by `expression`.
`fn_plotRay`
Plots line after chart bars.
Parameters:
y: (float) Y axis line position.
label: (string) Label to be ploted after line.
color: (color) Line and label color.
length: (int) Line length.
show: (bool) Flag to display the line. (default: `true`)
lineStyle: (string) Line style to be applied. (default: `line.style_dotted`)
lineWidth: (int) Line width. (default: `1`)
Returns: void
`fn_plotEmaRay`
Plots moving average line for a specific period.
Parameters:
period: (simple string) Period of fractal to retrieve
expression: (series float) The expression to retrieve data from fractal.
color: (color) Line and label color.
length: (int) Line length. (default: `12`)
show: (bool) Flag to display the line. (default: `true`)
lineStyle: (string) Line style to be applied. (default: `line.style_dotted`)
lineWidth: (string) Line width. (default: `1px`)
Returns: void
`fn_plotExtendedEmaRay`
Draws extended line for current timeframe moving average.
Parameters:
coordY: (float) Extended line Y axis position.
textValue: (simple string) Extended line label text.
textColor: (color) Extended line text color.
length: (int) Extended length. (default: `5`)
Returns: void
@tk · fractal rsi levels█ OVERVIEW
This script is an indicator that helps traders to identify the RSI Levels for multiple fractals wherever the current timeframe is. This script was based on RSI Levels, 20-30 & 70-80 by abdomi indicator, that calculates the Relative Strenght Index levels based on the asset's price and plots it into the chart, creating a "wave" style indicator. The core feature of this indicator is the fractal rays, so trader can visualize each of the oversold and overbought levels of multiple timeframe on the current timeframe that he is on. The indicator will plots multiple rays after the chart bars. indicating where is the oversold and overbought levels for others fractals.
█ MOTIVATION
Since the RSI Levels, 20-30 & 70-80 by abdomi indicator helps a lot to identify the possible price levels when the asset is oversold or overbought, I saw myself drawing multiple horizontal lines on these levels in lower timeframes so, in an uptrend or downtrend, I can try to get a pullback of these trends when the asset reaches oversold or overboght levels. So, I get the idea to make those lines visible in multiple timeframes so I don't need to draw it myself manually anymore.
█ CONCEPT
The trading concept to use this indicator is the concept to make entries on uptrend or downtrend pullbacks when the asset price reaches oversold or overbought levels. But this strategy don't works alone. It needs to be aligned together with others indicators like Exponential Moving Averages, Chart Patterns, Support and Resistance, and so on... Even more confluences that you have, bigger are your chances to increase the probability for a successful trade. So, don't use this indicator alone. Compose a trading strategy and use it to improve your analysis.
█ CUSTOMIZATION
This indicator allows the trader to customize the following settings:
GENERAL
Text size
Changes the font size of the labels to improve accessibility.
Type: string
Options: `tiny`, `small`, `normal`, `large`.
Default: `small`
RSI LEVELS · SETTINGS
Pre-oversold Level
Changes the RSI Level to calculate the "pre-oversold" price level on the chart.
Type: int
Min: 1
Max: 49
Default: 33
Pre-overbought Level
Changes the RSI Level to calculate the "pre-overbought" price level on the chart.
Type: int
Min: 51
Max: 100
Default: 67
Show "Pre-over" Levels
Enables / Disables the pre-oversold and pre-overbought levels on the chart.
Type: bool
Default: true
FRACTAL RAYS · SETTINGS
Length
Changes the base length for the RSI calculation.
Type: int
Min: 1
Default: 14
Source
Changes the base source for the RSI calculation.
Type: float
Default: close
FRACTAL RAYS · STYLE
Ray Color
Changes the color of all fractal rays and its label.
Type: color
Default: color.rgb(187, 74, 207)
Ray Style
Changes the style of all fractal rays.
Type: string
Options: `line.style_solid`, `line.style_dashed`, `line.style_dotted`
Default: line.style_dotted
Ray Length
Changes the length of all fractal rays.
Type: int
Default: 15
FRACTAL RAYS · OVERSOLD
Oversold Level
Changes the base RSI Level for fractal rays calculation.
Type: int
Min: 1
Default: 30
Oversold Prefix
Customizes the fractal ray label with a prefix text.
Type: string
Default: 🚀
Oversold Suffix
Customizes the fractal ray label with a suffix text.
Type: string
Default: (empty)
FRACTAL RAYS · OVERBOUGHT
Overbought Level
Changes the base RSI Level for fractal rays calculation.
Type: int
Min: 1
Default: 70
Overbought Prefix
Customizes the fractal ray label with a prefix text.
Type: string
Default: 🐻
Overbought Suffix
Customizes the fractal ray label with a suffix text.
Type: string
Default: (empty)
FRACTAL RAYS · VISIBILITY RULES
These rules are applied for each of fractal rays so, the traders can choose what timeframes they wants to show the fractal rays for each of it. The rule will be applied as the following condition: `if timeframe != CURRENT_TIMEFRAME and timeframe <= CHOSEN_OPTION`. Actually, the fractal rays are on the chart but, isn't visible because it was applied a transparent color, so it is visually not on the chart to prevent chart's over polution.
LABELS
Show Labels on Price Scale
Shows labels on price scale.
Type: bool
Default: false
Show Price on Fractal Rays
Shows the RSI Level price on each of fractal rays respectively.
Type: bool
Default: false
█ EXTERNAL LIBRARIES
This script uses the `tk` library to calculate RSI Levels. It is a library that contains various functions that helps pine script developers to calculate RSI Levels.
█ FUNCTIONS
The library contains the following functions:
fn_fractalVisibilityRule(string visibilityRule)
Converts the fractal rays timeframe visibility rule label to timestamp int.
Parameters:
visibilityRule: (string) Fractal ray visibility rule label.
Returns: (int) Fractal ray visibility rule timestamp.
fn_requestFractal(string period, expression)
Converts the fractal rays timeframe visibility rule label to timestamp int.
Parameters:
period: (string) Timeframe period for the desired fractal.
expression: (mixed) Security expression that will be applied for calculation.
Returns: (mixed) A result determined by expression.
fn_plotRay(float y, string label, color color, int length)
Plots ray after chart bars for the current time.
Parameters:
period: (string) Timeframe period for the desired fractal.
expression: (mixed) Security expression that will be applied for calculation.
Returns: (void) This function only plots the elements into the chart
fn_plotRsiLevelRay(simple string period, simple int level, color color)
Plots RSI Levels ray after chart bars for the current time.
Parameters:
period: (simple string) Timeframe period.
level: (simple int) Relative Strength Index level.
color: (color) The color of both, ray and label text.
Returns: (void) This function only plots the elements into the chart
[-_-] 2D FractalsThe sole purpose of this script is to demonstrate what's possible to make with Pinescript, namely to display images (2D Fractals in this case).
The script consists of two functions: one that generates the values of a fractal and one that displays them (utilising table) with each cell being used as a "pixel". We can control the "resolution" of image, as well as choose one of three fractal types.
PivotThis library was designed to create three different datasets using Bill Williams fractals. The goal is to spot trends in reversal data and ultimately use these datasets to help predict future price reversals.
First, the pivot() function is used to initialize and populate three separate arrays (high pivot , low pivot , all pivots ). Since each high/low price depends on the bar_index, the bar_index, pivot direction(high/low), and high/low values are compressed into a string to maintain the data's integrity ("__"). Once each string array is populated and organized by bar_index, all three are returned inside a tuple. The return value must be deconstructed H,L,A =pivot() for each array's values to be accessed using getPivot() . This boilerplate allows for data to be accessed more efficiently in a recursive environment. getPivot() was designed to be used inside of a for or while block to populate matrices for further analyses. Again, getPivot() return values must be exposed through deconstruction. x,d,y =getPivot(). See code for more details.
pivot(int XLR) initializes and populates arrays
Parameters
XLR - number of bars to the left and right that must be lower for a high to be considered a pivotHigh, or vice versa. This number will drastically change the size and scope of the returned datasets. smaller values will produce much larger datasets, which might model short term price activity well. In contrast, larger values will produce smaller datasets which might model longer term price activity well.
Returns - tuple [string ]
getPivot(string arrayID, int index) accesses array data
Parameters
arrayID - the variable name for one of the three arrays returned by pivot().
index - the index of the provided array, with 0 being the most recent pivot point. can be set to " i " in a loop to access values recursively
Returns - tuple