Linear Regression Forecast Tool [Daveatt]Hello traders,
Navigating through the financial markets requires a blend of analysis, insight, and a touch of foresight.
My Linear Regression Forecast Tool is here to add that touch of foresight to your analysis toolkit on TradingView!
Linear Regression is the heart of this tool, a statistical method that explores the relationship between a dependent variable and one (or more) independent variable(s).
In simpler terms, it finds a straight line that best fits a set of data points.
This "line of best fit" then becomes a visual representation of the relationship in the data, providing a basis for making predictions.
Here's what the Linear Regression Forecast Tool brings to your trading table:
Multiple Indicator Choices: Select from various market indicators like Simple Moving Averages, Bollinger Bands, or the Volume Weighted Average Price as the basis for your linear regression analysis.
Customizable Forecast Periods: Define how many periods ahead you want to forecast, adjusting to your analysis needs, whether that's looking 5, 7, or 10 periods into the future.
On-Chart Forecast Points: The tool plots the forecasted points on your chart, providing a straightforward visual representation of potential future values based on past data.
In this script:
1. We first calculate the indicator using the specified period.
2. We then use the ta.linreg function to calculate a linear regression curve fitted to the indicator over the last Period bars.
3. We calculate the slope of the linear regression curve using the last two points on the curve.
We use this slope to extrapolate the linear regression curve to forecast the next X points of the indicator.
4/ Finally, we use the plot function to plot the original indicator and the forecasted points on the chart, using the offset parameter to shift the forecasted points to the right (into the future).
This method assumes that the trend represented by the linear regression curve will continue, which may not always be the case, especially in volatile or changing market conditions.
Examples:
Works with a moving average
Works with a Bollinger band
The code can be adapted to work with any other indicator (imagine RSI, MACD, other Moving Average Type, PSAR, Supertrend, etc...)
Conclusion
The Linear Regression Forecast Tool doesn't promise to tell the future but provides a structured way to visualize possible future price trends based on historical data. I
Remember, no tool can predict market conditions with certainty.
It's always advisable to corroborate findings with other analysis methods and stay updated with market news and events.
Happy trading!
Forecasting
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!
Purchasing Managers Index (PMI)The Purchasing Managers Index (PMI) is a widely recognized economic indicator that provides crucial insights into the health and performance of an economy's manufacturing and services sectors. This index is a vital tool for anticipating economic developments and trends, offering an early warning system for changes in these sectors.
The PMI is calculated based on surveys conducted among purchasing managers in various businesses and organizations. These managers are asked about their perceptions of current business conditions and their expectations for future economic activity within their sectors. The responses are then compiled and used to calculate the PMI value.
A PMI value above 50 typically indicates that the manufacturing or services sector is expanding, suggesting a positive economic outlook. Conversely, a PMI value below 50 suggests contraction, which may be an early indication of economic challenges or a potential recession.
In summary, the Purchasing Managers Index (PMI) is an essential economic indicator that assesses the health of manufacturing and services sectors by surveying purchasing managers' opinions. It serves as an early warning system for changes in economic activity and is a valuable tool for forecasting economic trends and potential crises.
This code combines the Purchasing Managers Index (PMI) data with two Simple Moving Averages (SMA) and some visual elements.
Let's break down how this indicator works:
1. Loading PMI Data:
The indicator loads data for the "USBCOI" symbol, which represents the PMI data. It fetches the monthly closing prices of this symbol.
2. Calculating Moving Averages:
Two Simple Moving Averages (SMAs) are calculated based on the PMI data. The first SMA, sma_usbcoi, has a length defined by the input parameter (default: 2). The second SMA, sma2_usbcoi, has a different length defined by the second input parameter (default: 14).
3. Color Coding and Thresholds:
The line color of the PMI plot is determined based on the value of the PMI. If the PMI is above 52, the color is teal; if it's below 48, the color is red; otherwise, it's gray. These threshold values are often used to identify specific conditions in the PMI data.
4. Crossing Indicator:
A key feature of this indicator is to determine if the PMI crosses the first SMA (sma_usbcoi) from top to bottom while also being above the value of 52. This is indicated by the crossedUp variable. This condition suggests a specific situation where the PMI crosses a short-term moving average while indicating strength (above 52).
5. Visual Elements:
A "💀" skull emoji is defined as skullEmoji.
The PMI is plotted on the chart with color coding based on its value, as described earlier.
The two SMAs are also plotted on the chart.
When the crossedUp condition is met (PMI crosses the first SMA from top to bottom while above 52), a skull emoji (indicating potential danger) is plotted at the top of the indicator window.
US Composite Leading Indicator (CLI)The US Composite Leading Indicator (CLI), normalized for the United States, closely mirrors the Conference Board "Leading Economic Index" (LEI). It offers unique insights into economic and financial dynamics.
The Composite Leading Indicator (CLI) is an economic tool designed to anticipate economic developments. It is created by aggregating and normalizing a wide range of economic and financial data from various sources.
The normalized data is then aggregated, and a composite indicator is calculated by taking a weighted average of individual indicators.
The CLI is used to provide early insights into the state of the economy and to anticipate future economic trends. It is particularly valuable for predicting economic downturns, including recessions.
The CLI is an essential tool for economists, governments, businesses, and investors seeking to understand economic trends and make informed decisions.
Key Features:
1. Early Warning: Just like its counterpart, the CLI indicator excels at offering early warnings about significant economic events, particularly economic crises. This makes it an indispensable asset for analysts and investors.
2. Recession Indicators: The moving average serves as an early warning system for potential economic recessions. When it crosses the indicator line from the bottom to the top while surpassing a predefined threshold (e.g., 101), it signals a potential crisis.
3. Market Impact: The CLI indicator provides valuable insights into the performance of financial markets, offering cues about indices such as the S&P 500, Nasdaq, Dow Jones, and more.
Why It Matters:
Understanding the US Composite Leading Indicator (CLI) indicator, normalized for the United States, is crucial for anticipating economic shifts and preparing for changes in financial markets. By analyzing a diverse array of economic factors, it provides a holistic view of economic well-being. Whether you're an investor or economist, this indicator can be an invaluable resource for staying informed about market trends and major economic developments.
Source:
www.data.oecd.org
Supertrend Multiasset Correlation - vanAmsen Hello traders!
I am elated to introduce the "Supertrend Multiasset Correlation" , a groundbreaking fusion of the trusted Supertrend with multi-asset correlation insights. This approach offers traders a nuanced, multi-layered perspective of the market.
The Underlying Concept:
Ever pondered over the term Multiasset Correlation?
In the intricate tapestry of financial markets, assets do not operate in silos. Their movements are frequently intertwined, sometimes palpably so, and at other times more covertly. Understanding these correlations can unlock deeper insights into overarching market narratives and directional trends.
By melding the Supertrend with multi-asset correlations, we craft a holistic narrative. This allows traders to fathom not merely the trend of a lone asset but to appreciate its dynamics within a broader market tableau.
Strategy Insights:
At the core of this indicator is its strategic approach. For every asset, a signal is generated based on the Supertrend parameters you've configured. Subsequently, the correlation of daily price changes is assessed. The ultimate signal on the selected asset emerges from the average of the squared correlations, factoring in their direction. This indicator not only accounts for the asset under scrutiny (hence a correlation of 1) but also integrates 12 additional assets. By default, these span U.S. growth ETFs, value ETFs, sector ETFs, bonds, and gold.
Indicator Highlights:
The "Supertrend Multiasset Correlation" isn't your run-of-the-mill Supertrend adaptation. It's a bespoke concoction, tailored to arm traders with an all-encompassing view of market intricacies, fortified with robust correlation metrics.
Key Features:
- Supertrend Line : A crystal-clear visual depiction of the prevailing market trajectory.
- Multiasset Correlation : Delve into the intricate interplay of various assets and their correlation with your primary instrument.
- Interactive Correlation Table : Nestled at the top right, this table offers a succinct overview of correlation metrics.
- Predictive Insights : Leveraging correlations to proffer predictive pointers, adding another layer of conviction to your trades.
Usage Nuances:
- The bullish Supertrend line radiates in a rejuvenating green hue, indicative of potential upward swings.
- On the flip side, the bearish trajectory stands out in a striking red, signaling possible downtrends.
- A rich suite of customization tools ensures that the chart resonates with your trading ethos.
Parting Words:
While the "Supertrend Multiasset Correlation" bestows traders with a rejuvenated perspective, it's paramount to embed it within a comprehensive trading blueprint. This would include blending it with other technical tools and adhering to stringent risk management practices. And remember, before plunging into live trades, always backtest to fine-tune your strategies.
Supertrend Forecast - vanAmsenHello everyone!
I am thrilled to present the "vanAmsen - Supertrend Forecast", an advanced tool that marries the simplicity of the Supertrend with comprehensive statistical insights.
Before we dive into the functionalities of this indicator, it's essential to understand its foundation and theory.
The Theory:
What exactly is the Supertrend?
The Supertrend, at its core, is a momentum oscillator. It's a tool that provides buy and sell signals based on the prevailing market trend. The underlying principle is straightforward: by analyzing average price data and volatility over a period, the Supertrend gives us a line that represents the trend direction.
However, trading isn't just about identifying trends; it's about understanding their strength, potential profitability, and historical accuracy. This is where statistics come into play. By incorporating statistical analysis into the Supertrend, we can gain deeper insights into the market's behavior.
Description:
The "vanAmsen - Supertrend Forecast" isn't just another Supertrend indicator. It's a comprehensive tool designed to offer traders a holistic view of market trends, backed by robust statistical analysis.
Key Features:
- Supertrend Line: A visual representation of the current market direction.
- Win Rate & Expected Return: Delve into the historical accuracy and profitability of the prevailing trend.
- Average Percentage Change: Understand the average price fluctuation for both winning and losing trends.
- Forecast Lines: Project future price movements based on historical data, providing a roadmap for potential scenarios.
- Interactive Table: A concise table in the top right, offering a snapshot of all vital metrics at a glance.
Usage:
- The bullish Supertrend line adopts an Aqua hue, indicating potential upward momentum.
- In contrast, the bearish line is painted in Orange, suggesting potential downtrends.
- Customize your chart by toggling labels, tables, and lines according to preference.
Recommendation:
The "vanAmsen - Supertrend Forecast" is undoubtedly a powerful tool in a trader's arsenal. However, it's imperative to combine it with other technical analysis tools and sound risk management practices. It's always prudent to backtest strategies with historical data before embarking on live trading.
Strong Pullback Indicator [Rami_LB]Strong Pullback Indicator
Description:
The Strong Pullback Indicator is designed to identify potential pullbacks or even trend reversals by utilizing a specific candlestick pattern in conjunction with the Relative Strength Index (RSI). It is advised to employ this indicator in chart intervals of 15 minutes or higher, as intervals below 15 minutes may generate excessive false signals.
Working Mechanism:
Upon detecting the designated candlestick pattern, the indicator examines whether any of the last five candles exhibit RSI values below 30 or above 70 across at least four distinct time intervals, depending on whether the pattern is bullish or bearish. The RSI calculations incorporate eight different intervals: 1 minute (1m), 5 minutes (5m), 15 minutes (15m), 30 minutes (30m), 1 hour (1h), 2 hours (2h), 4 hours (4h), and 1 day (1d). An arrow is rendered above or below the current candle only when these conditions are met.
Users have the option to adjust the number of overbought or oversold intervals, as well as the general settings for the RSI.
SL/TP Lines:
The indicator can also serve as a trade signal to initiate trades in the opposite direction. To evaluate the potential success of a trade in a backtesting scenario, SL (Stop Loss) and TP (Take Profit) lines can be displayed on the chart. The SL is calculated by taking the distance from the close of the current candle to the high/low of the previous candle and multiplying it by 2.
In the settings, you can alter the Risk Reward Ratio (RRR) of the trade. Given the pullback nature of this indicator, a RRR of 1:1 is deemed logical, thus set as the default value.
Bullish vs. Bearish Candle Counter:
An additional feature of this indicator is its ability to analyze the last 100 candles to ascertain the ratio of bullish to bearish candles. When a 60% threshold is reached, the chart background color alters accordingly. This feature was conceived after a thorough analysis of over 50,000 candles of a currency pair revealed nearly identical counts of bullish and bearish candles, suggesting a market tendency to maintain this balance.
Within the settings, you have the flexibility to modify the number of candles to be analyzed and the percentage threshold for each candle type.
Should you have any ideas on how to enhance the accuracy of this indicator, or suggestions for other indicators that could improve the signals, feel free to leave a comment.
Open, Open +/- EMA ATR Lines with LabelsThis indicator provides traders with a clear visualization of the opening price and its potential movement range for a specific timeframe, based on the Exponential Moving Average (EMA) of the Average True Range (ATR).
Features:
Opening Price Line: A green line representing the opening price for the chosen timeframe.
EMA ATR Lines:
An upper blue line, calculated as the opening price plus the EMA of the ATR.
A lower blue line, calculated as the opening price minus the EMA of the ATR.
Labels: Each line comes with a label on its right side, displaying the price level and, for the EMA ATR lines, the distance in pips from the opening price.
Custom Timeframes: Users can select their desired timeframe for calculations, making this tool versatile for different trading strategies.
Usage:
The EMA-smoothed ATR provides a measure of volatility. By plotting this value above and below the opening price, traders get a sense of potential price movement for the selected timeframe. This can be particularly useful for setting stop losses, take profit levels, or identifying breakout points.
For instance, if the price breaks above the upper EMA ATR line, it might indicate a potential upward move, especially if other market conditions align.
Customization:
Timeframe: Choose from various timeframes like 1-minute, 5-minutes, daily, weekly, and more.
ATR Length: Adjust the length of the ATR for more or less sensitivity.
This indicator is designed to offer traders a quick way to gauge potential price movement for their chosen timeframe. By combining the principles of the opening price and volatility measured by the EMA-smoothed ATR, it provides a straightforward yet powerful tool for various trading scenarios.
Machine Learning: SuperTrend Strategy TP/SL [YinYangAlgorithms]The SuperTrend is a very useful Indicator to display when trends have shifted based on the Average True Range (ATR). Its underlying ideology is to calculate the ATR using a fixed length and then multiply it by a factor to calculate the SuperTrend +/-. When the close crosses the SuperTrend it changes direction.
This Strategy features the Traditional SuperTrend Calculations with Machine Learning (ML) and Take Profit / Stop Loss applied to it. Using ML on the SuperTrend allows for the ability to sort data from previous SuperTrend calculations. We can filter the data so only previous SuperTrends that follow the same direction and are within the distance bounds of our k-Nearest Neighbour (KNN) will be added and then averaged. This average can either be achieved using a Mean or with an Exponential calculation which puts added weight on the initial source. Take Profits and Stop Losses are then added to the ML SuperTrend so it may capitalize on Momentum changes meanwhile remaining in the Trend during consolidation.
By applying Machine Learning logic and adding a Take Profit and Stop Loss to the Traditional SuperTrend, we may enhance its underlying calculations with potential to withhold the trend better. The main purpose of this Strategy is to minimize losses and false trend changes while maximizing gains. This may be achieved by quick reversals of trends where strategic small losses are taken before a large trend occurs with hopes of potentially occurring large gain. Due to this logic, the Win/Loss ratio of this Strategy may be quite poor as it may take many small marginal losses where there is consolidation. However, it may also take large gains and capitalize on strong momentum movements.
Tutorial:
In this example above, we can get an idea of what the default settings may achieve when there is momentum. It focuses on attempting to hit the Trailing Take Profit which moves in accord with the SuperTrend just with a multiplier added. When momentum occurs it helps push the SuperTrend within it, which on its own may act as a smaller Trailing Take Profit of its own accord.
We’ve highlighted some key points from the last example to better emphasize how it works. As you can see, the White Circle is where profit was taken from the ML SuperTrend simply from it attempting to switch to a Bullish (Buy) Trend. However, that was rejected almost immediately and we went back to our Bearish (Sell) Trend that ended up resulting in our Take Profit being hit (Yellow Circle). This Strategy aims to not only capitalize on the small profits from SuperTrend to SuperTrend but to also capitalize when the Momentum is so strong that the price moves X% away from the SuperTrend and is able to hit the Take Profit location. This Take Profit addition to this Strategy is crucial as momentum may change state shortly after such drastic price movements; and if we were to simply wait for it to come back to the SuperTrend, we may lose out on lots of potential profit.
If you refer to the Yellow Circle in this example, you’ll notice what was talked about in the Summary/Overview above. During periods of consolidation when there is little momentum and price movement and we don’t have any Stop Loss activated, you may see ‘Signal Flashing’. Signal Flashing is when there are Buy and Sell signals that keep switching back and forth. During this time you may be taking small losses. This is a normal part of this Strategy. When a signal has finally been confirmed by Momentum, is when this Strategy shines and may produce the profit you desire.
You may be wondering, what causes these jagged like patterns in the SuperTrend? It's due to the ML logic, and it may be a little confusing, but essentially what is happening is the Fast Moving SuperTrend and the Slow Moving SuperTrend are creating KNN Min and Max distances that are extreme due to (usually) parabolic movement. This causes fewer values to be added to and averaged within the ML and causes less smooth and more exponential drastic movements. This is completely normal, and one of the perks of using k-Nearest Neighbor for ML calculations. If you don’t know, the Min and Max Distance allowed is derived from the most recent(0 index of data array) to KNN Length. So only SuperTrend values that exhibit distances within these Min/Max will be allowed into the average.
Since the KNN ML logic can cause these exponential movements in the SuperTrend, they likewise affect its Take Profit. The Take Profit may benefit from this movement like displayed in the example above which helped it claim profit before then exhibiting upwards movement.
By default our Stop Loss Multiplier is kept quite low at 0.0000025. Keeping it low may help to reduce some Signal Flashing while not taking extra losses more so than not using it at all. However, if we increase it even more to say 0.005 like is shown in the example above. It can really help the trend keep momentum. Please note, although previous results don’t imply future results, at 0.0000025 Stop Loss we are currently exhibiting 69.27% profit while at 0.005 Stop Loss we are exhibiting 33.54% profit. This just goes to show that although there may be less Signal Flashing, it may not result in more profit.
We will conclude our Tutorial here. Hopefully this has given you some insight as to how Machine Learning, combined with Trailing Take Profit and Stop Loss may have positive effects on the SuperTrend when turned into a Strategy.
Settings:
SuperTrend:
ATR Length: ATR Length used to create the Original Supertrend.
Factor: Multiplier used to create the Original Supertrend.
Stop Loss Multiplier: 0 = Don't use Stop Loss. Stop loss can be useful for helping to prevent false signals but also may result in more loss when hit and less profit when switching trends.
Take Profit Multiplier: Take Profits can be useful within the Supertrend Strategy to stop the price reverting all the way to the Stop Loss once it's been profitable.
Machine Learning:
Only Factor Same Trend Direction: Very useful for ensuring that data used in KNN is not manipulated by different SuperTrend Directional data. Please note, it doesn't affect KNN Exponential.
Rationalized Source Type: Should we Rationalize only a specific source, All or None?
Machine Learning Type: Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?
Machine Learning Smoothing Type: How should we smooth our Fast and Slow ML Datas to be used in our KNN Distance calculation? SMA, EMA or VWMA?
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!
Euclidean Distance Predictive Candles [SS]Finally releasing this, its been in the works for the past 2 weeks and has undergone many iterations.
I am not sure if I am 100% happy with it yet, but I guess its best to release and get feedback to make improvements.
So this is the Euclidean distance predictive candle indicator and what it does is exactly what it sounds like, it uses Euclidean distance to identify similar candles and then plot the candles and range that immediately proceeded like candles.
While this is using a general machine learning/data science approach (Euclidean distance), I do not employ the KNN (Nearest Neighbors) algo into this. The reason being is it simply offered no predictive advantage than isolating for the last case. I tried it, I didn't like it, the results were not improve and, at times, acutally hindered so I ditched it. Perhaps it was my approach but using some other KNN indicators, I just don't really find them all that more advantageous to simply relying on the Law of Large Numbers and collecting more data rather than less data (which we will get into later in this explanation).
So using this indicator:
There is a lot of customizability here. And the reason is, not all settings are going to work the same for all tickers. To help you narrow down your parameters, I have included various backtest results that show you how the model is performing. You see in the AMZN chart above, with the current settings, it is performing optimally, with a cumulative range pass of 99% (meaning that, of all the cases, the indicator accurately predicted the next day high OR low range 99% of the time), and the ability to predict the candle slightly over 52%.
The recommended settings, from me, are as follows:
So these are generally my recommended settings.
Euclidian Tolerance: This will determine the parameters to look for similar candles. In general, the lower the tolerance, the greater the precision. I recommend keeping it between 0.5, for tickers with larger prices (like ES1! futures or NQ1!) or 0.05 for tickers with lower TPs, like SPY or QQQ.
If the ED Tolerance is too extreme that the indicator cannot find identical setups, it will alert you:
But in general, the more precise you can get it, the better.
Anchor Type: You will see the option to anchor by "Predicted Open" or by "Previous Close". I suggest sticking with anchoring by predicted open. All this means is, it is going to anchor your range, candle, high and low targets by the predicted open price. Anchoring by previous close will anchor by the close of yesterday. Both work okay, but in general the results from anchoring to predicted open have higher pass rates and more accurately depict the candle.
Euclidean Distance Measurement Type: You can choose to measure by candle body or from high to low wicks. I haven't played around with measuring from high to low wicks all that much, because candle body tends to do the job. But remember, ED is a neutral measurement. Which means, its not going to distinguish between a red or green candle, just the formation of the candle. Thus, I tend to recommend, pragmatically, not to necessarily rely on the candle being red or green, but one the formation of the candle (where are the wicks going, are there more bearish wicks or bullish wicks) etc. Examples will follow.
Range Prediction Type: You can filter the range prediction type by last instance (in which, it will pull the previous identical candle and plot the next candle that followed it, adjusted for the current ranges) or "Average of All Cases". So this is where we need to talk a little bit about the law of large numbers.
In general, in statistics, when you have a huge amount of random data, the law of large numbers stipulates that, within this randomness should be repeated events. This is why sometimes chart patterns work, sometimes they don't. When we filter by the average of all cases, we are relying on the law of large numbers. In general, if you are getting good Backtest readings from Last Instance, then you don't need to use this function. But it provides an alternative insight into potential candle formations next day. Its not a bad idea to compare between the two and look for similarities and differences.
So now that we have covered the boring details, let's get into how to use the indicator and some examples.
So the indicator is plotting the range and candle for the next day. As such, we are not looking at the current candle being plotted, but we are looking at the previous candle (see image below for example):
The green arrow shows the prediction for Friday, along with the corresponding result. The purple arrow shows the prediction for Monday which we have yet to realize.
So remember when you are using this, you need to look at the previous candle, and not the candle that it is currently plotting with realtime data, because it is plotting for the next candle.
If you are plotting by last instance, the indicator will tell you which day it is pulling its data from if you have opted to toggle on the demographic data:
You can see the green arrow pointing to the date where it is pulling from. This data serves as the example candle with the candle proceeding this date being the anchored candle (or the predicted candle).
Price Targets and Probability:
In the chart, you can see the green arrow pointing to the green portion of the table. In this table, it will give you the current TPs. These represent the current time target price, which means, the TPs shown here are for Friday. On Monday, the table will update with the TPs for Monday, etc. If you want to view the TPs in advance, you can view them from the actual candle itself.
Below the TPs, you see a bullish 7:6. It means, in a total of 13 cases, the next candle was bullish 7 times and bearish 6 times. Where do we see the number of cases? In the demographic table as well:
Auxiliary functions
Because you are using the previous candle, if you want to avoid confusion, you can have the indicator plot the price targets over the predicted candle, to anchor your attention so to speak. Simply select "Label" in the "Show Price Targets" section, which will look like this:
You can also ask the indicator to plot the demographic data of Higher High, Low, etc. information. What this does is simply looks at all the cases and plots how many times higher highs, lows, lower lows, highs etc. were made:
This will just count all of the cases identified and plot the number of times higher highs, lows, etc. were made.
Concluding Remarks
This is a kind of complex indicator and I can appreciate it may take some getting used to.
I will try to post a tutorial video at some point next week for it, so stay tuned for that.
But this isn't designed to make your life more complicated, just to help give you insights into potential outcomes for the next day or hour or 5 minute (it can be used on all timeframes).
If you find it helpful, great! If not, that's okay, too :-).
Please be aware, this is not my forte of indicators. I am not a data scientist or programmer. My background is in Epi and we don't use these types of data science approaches, so if you have any suggestions or critiques, feel free to share them below.
Otherwise, I hope you enjoy!
Take care everyone and safe trades!
Bullish vs. Bearish Candle CounterFollowing an exhaustive analysis of the most recent 50,000 candles within a given currency pair, a notable equilibrium between bearish and bullish candles has emerged as a persistent market phenomenon. This equilibrium, indicative of the market's continuous endeavor to establish parity, has spurred the development of the following indicator.
The indicator meticulously scrutinizes the preceding 100 candles, promptly triggering an on-chart marker when either bullish or bearish candle counts surpass the threshold of 60%. This marker serves as an invaluable tool, providing traders with a potential signal for the initiation of a trend reversal.
As such, this indicator serves as a valuable asset in a trader's toolkit, offering insights into shifts in market sentiment and the prospect of emerging trends.
Key Features:
- Customizable Candle Count: Traders can set the number of candlesticks to be analyzed in the input parameters, allowing flexibility in their analysis.
- Bullish and Bearish Percentage: Users can define their desired percentage for both bullish and bearish candles in the indicator's settings. The indicator calculates the percentage of each candle type within the specified range.
- Arrow Signals: The indicator plots arrows above or below the current candle, indicating bullish or bearish conditions based on the defined percentage thresholds. A green arrow signifies bullish sentiment, while a red arrow denotes bearish sentiment.
How to Use:
- Adjust Parameters: In the indicator settings, users can customize the number of candlesticks to be analyzed, as well as set their preferred percentages for both bullish and bearish conditions.
- Interpret Arrows: The indicator generates arrows above or below the current candle, reflecting the prevailing market sentiment. A green arrow suggests a bullish bias, while a red arrow indicates a bearish bias.
- Trade with Confidence: Traders can use this indicator as a tool to gauge market sentiment and make informed trading decisions. It helps identify potential entry and exit points based on the chosen percentage thresholds.
Multiperiod Volume Pressure Indicator
Description:
The Volume Pressure Indicator is a powerful tool designed to assess market sentiment based on a combination of price and volume data. By analyzing buy and sell pressure within specific lookback periods, this indicator provides valuable insights into the intensity of market buying and selling activities. Traders can use this information to make informed decisions, especially during periods of price consolidation or trend reversal.
Key Features:
- **Multi-Period Analysis:** Utilizes multiple lookback periods (1, 2, and 4) to calculate buy and sell pressures, offering a nuanced view of market dynamics over different timeframes.
- **Pressure Calculation:** Computes buy and sell pressures based on price range and closing values, providing a comprehensive understanding of market participant behavior.
- **Color-Coded Bars:** Visualizes market sentiment by coloring bars according to the number of positive (buy pressure > sell pressure) periods observed within the specified lookback periods.
How to Use:
- **Color Coding:** Green bars represent periods where buy pressure dominates, indicating potential buying interest. Yellow bars suggest a balance between buy and sell pressures. Red bars signal periods dominated by sell pressure, indicating potential selling interest.
- **Lookback Periods:** Shorter lookback periods (e.g., 1) offer insights into immediate market sentiment, while longer periods (e.g., 4) provide a broader perspective. Analyzing multiple periods can help traders confirm trends and anticipate reversals.
Customization:
- **Lookback Periods:** Adjust the length of the lookback periods (1, 2, and 4) to match your trading style and timeframe preferences.
Disclaimer:
Trading involves risk, and past performance is not indicative of future results. Always conduct thorough analysis and apply proper risk management techniques before making trading decisions.
Usage Scenarios:
- **Trend Confirmation:** Use the indicator to confirm the strength of an ongoing trend. Consistent green bars can validate a bullish trend, while red bars may confirm a bearish trend.
- **Reversal Signals:** Look for transitions in bar colors to identify potential trend reversals. A shift from green to yellow/red or vice versa can indicate changing market sentiment.
- **Divergence Analysis:** Compare price movements with the indicator's bar colors. Divergence between price trends and bar colors may signal upcoming price movements.
Machine Learning using Neural Networks | EducationalThe script provided is a comprehensive illustration of how to implement and execute a simplistic Neural Network (NN) on TradingView using PineScript.
It encompasses the entire workflow from data input, weight initialization, implicit neuron calculation, feedforward computation, backpropagation for weight adjustments, generating predictions, to visualizing the Mean Squared Error (MSE) Loss Curve for monitoring the training phase.
In the visual example above, you can see that the prediction is not aligned with the actual value. This is intentional for demonstrative purposes, and by incrementing the Epochs or Learning Rate, you will see these two values converge as the accuracy increases.
Hyperparameters:
Learning Rate, Epochs, and the choice between Simple Backpropagation and a verbose version are declared as script inputs, allowing users to tailor the training process.
Initialization:
Random initialization of weight matrices (w1, w2) is performed to ensure asymmetry, promoting effective gradient updates. A seed is added for reproducibility.
Utility Functions:
Functions for matrix randomization, sigmoid activation, MSE loss calculation, data normalization, and standardization are defined to streamline the computation process.
Neural Network Computation:
The feedforward function computes the hidden and output layer values given the input.
Two variants of the backpropagation function are provided for weight adjustment, with one offering a more verbose step-by-step computation of gradients.
A wrapper train_nn function iterates through epochs, performing feedforward, loss computation, and backpropagation in each epoch while logging and collecting loss values.
Training Invocation:
The input data is prepared by normalizing it to a value between 0 and 1 using the maximum standardized value, and the training process is invoked only on the last confirmed bar to preserve computational resources.
Output Forecasting and Visualization:
Post training, the NN's output (predicted price) is computed, standardized and visualized alongside the actual price on the chart.
The MSE loss between the predicted and actual prices is visualized, providing insight into the prediction accuracy.
Optionally, the MSE Loss Curve is plotted on the chart, illustrating the loss trajectory through epochs, assisting in understanding the training performance.
Customizable Visualization:
Various inputs control visualization aspects like Chart Scaling, Chart Horizontal Offset, and Chart Vertical Offset, allowing users to adapt the visualization to their preference.
-------------------------------------------------------
The following is this Neural Network structure, consisting of one hidden layer, with two hidden neurons.
Through understanding the steps outlined in my code, one should be able to scale the NN in any way they like, such as changing the input / output data and layers to fit their strategy ideas.
Additionally, one could forgo the backpropagation function, and load their own trained weights into the w1 and w2 matrices, to have this code run purely for inference.
-------------------------------------------------------
While this demonstration does create a “prediction”, it is on historical data. The purpose here is educational, rather than providing a ready tool for non-programmer consumers.
Normally in Machine Learning projects, the training process would be split into two segments, the Training and the Validation parts. For the purpose of conveying the core concept in a concise and non-repetitive way, I have foregone the Validation part. However, it is merely the application of your trained network on new data (feedforward), and monitoring the loss curve.
Essentially, checking the accuracy on “unseen” data, while training it on “seen” data.
-------------------------------------------------------
I hope that this code will help developers create interesting machine learning applications within the Tradingview ecosystem.
@tk · spectral█ OVERVIEW
This script is an indicator that helps traders to identify the price difference between spot and futures of the current crypto plotted into the chart. It works in both types of markets, when the chart is plotting the crypto in spot market, it will compare with its respective futures ticker and vice-versa. If the current asset isn't a crypt ticker, the indicator will not be plotted into the chart.
█ MOTIVATION
Since crypto's derivative market is based on spot market asset's price, to calculate the arbitrage mechanisms that attempts to balance the asset price, this indicator can help traders to identify some spot and futures price divergence that can create an anomaly of funding rate and can push it to an extreme negative — or positive — rate. So, easing to track the price difference between both markets will bring more evidences to identify an artificial price move, specially in crypto assets with low market cap.
█ CONCEPT
The trading concept to use this indicator is the concept of the arbitrage machamism created by exchanges that calculates the funding rate based on spot and futures price difference that will vary from exchange to exchange. 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 price difference table to improve accessibility.
Type: string
Options: `tiny`, `small`, `normal`, `large`.
Default: `small`
Position
Changes the position of price difference table.
Type: string
Options: `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`.
Default: `bottom_right`
Pair Quote
The ticker quote symbol that will be used to base the ticker comparison from spot to futures (e.g. BTCUSDT which `USDT` is the quote. ETHBTC which `BTC` is the quote).
Type: string
Default: USDT
Spectrum Color
The color of the spectrum candles. Spectrum candles are the candles of the opposite market. If the current ticker is in the spot market, the spectrum candles will be the price of the futures market.
Type: color
Default: #434651
█ FUNCTIONS
The indicator contains the following functions:
stripStarts(src, str)
Strips a defined pattern from a string.
Parameters:
src: (string) Source string
str: (string) String pattern to be stripped from start of source string.
Returns: (string) Stripped string with matched regex pattern.
Golden Level Predictions v1.0Golden Level Predictions (GLP) Trading Indicator
This script introduces a custom trading indicator named "GLP" tailored for the TradingView platform. It offers various price levels derived from Fibonacci calculations and other mathematical models, assisting traders in pinpointing potential overpriced and discounted price levels.
Key Features:
User Inputs : Users have the flexibility to select their desired timeframe, with options ranging from Weekly, Daily, Monthly, and more. Additionally, they can opt to showcase Fibonacci lines and the associated prices within these levels.
Price Level Calculations :
- Employs constants such as the Golden Ratio (PHI) and Pi (PI) to extract various multipliers and factors.
- Assesses if the current asset is a cryptocurrency and tweaks calculations accordingly.
- Determines overpriced and discounted price levels, drawing from the current open price and past data.
Fibonacci Levels :
- For each overpriced and discounted level, the script computes intermediary Fibonacci levels, including 23.6%, 38.2%, 50%, 61.8%, and 78.6% (the 3rd level is excluded due to plot limitations).
- These levels are illustrated on the chart, granting traders a more detailed view of price targets.
Visual Elements :
- Projects horizontal lines to the subsequent selected indicator interval for every calculated price level.
- Exhibits potential percentage gains or losses at each tier, indicating the prospective price alteration upon reaching that level.
- Differentiates overpriced (green) and discounted (red) levels using color codes. A neutral price is depicted in yellow.
Anticipated Close Calculation : Offers a projected closing price for the current timeframe, based on a myriad of factors.
This indicator is particularly effective with cryptocurrencies due to their inherent volatility. It's also compatible with stocks and is most efficient with tickers that provide volume data.
Highlight BarHighlight bars in the past. I use this to show the start of moving average calculations - very helpful to anticipate the change in slope of moving averages. You can change color as well as how far back in time to highlight. The defaults are 20, 50 and 200.
I learned of the idea from Brian Shannon - thanks!
Seasonality and Presidential cycleAn incredibly useful indicator that shows seasonality and presidential cycles by indices, stocks and industries. Just type in a ticker and trade according to seasonal patterns
Blue line - seasonality excluding presidential cycles
Green line - seasonality taking into account presidential cycles
*Seasonal patterns over the last 10 years
This indicator uses the request.seed() function.
Requests data from a GitHub repository maintained by our team and returns it as a series.
Pine Seeds is a service to import custom data and access it via TradingView.
Use TradingView as frontend and use a GitHub repository as backend.
github.com
...
Rus: Невероятно полезный индикатор, который показывает сезонность и президентские циклы по индексам, акциям и отраслям. Просто вбейте тикер и торгуйте согласно сезонным паттернам
Синяя линия - сезонность без учета президентских циклов
Зеленая линия - сезонность с учетом президентских циклов
*Сезонные паттерны за последние 10 лет
Machine Learning: Gaussian Process Regression [LuxAlgo]We provide an implementation of the Gaussian Process Regression (GPR), a popular machine-learning method capable of estimating underlying trends in prices as well as forecasting them.
While this implementation is adapted to real-time usage, do remember that forecasting trends in the market is challenging, do not use this tool as a standalone for your trading decisions.
🔶 USAGE
The main goal of our implementation of GPR is to forecast trends. The method is applied to a subset of the most recent prices, with the Training Window determining the size of this subset.
Two user settings controlling the trend estimate are available, Smooth and Sigma . Smooth determines the smoothness of our estimate, with higher values returning smoother results suitable for longer-term trend estimates.
Sigma controls the amplitude of the forecast, with values closer to 0 returning results with a higher amplitude. Do note that due to the calculation of the method, lower values of sigma can return errors with higher values of the training window.
🔹 Updating Mechanisms
The script includes three methods to update a forecast. By default a forecast will not update for new bars (Lock Forecast).
The forecast can be re-estimated once the price reaches the end of the forecasting window when using the "Update Once Reached" method.
Finally "Continuously Update" will update the whole forecast on any new bar.
🔹 Estimating Trends
Gaussian Process Regression can be used to estimate past underlying local trends in the price, allowing for a noise-free interpretation of trends.
This can be useful for performing descriptive analysis, such as highlighting patterns more easily.
🔶 SETTINGS
Training Window: Number of most recent price observations used to fit the model
Forecasting Length: Forecasting horizon, determines how many bars in the future are forecasted.
Smooth: Controls the degree of smoothness of the model fit.
Sigma: Noise variance. Controls the amplitude of the forecast, lower values will make it more sensitive to outliers.
Update: Determines when the forecast is updated, by default the forecast is not updated for new bars.
Intraday Volatility Bands [Honestcowboy]The Intraday Volatility Bands aims to provide a better alternative to ATR in the calculation of targets or reversal points.
How are they different from ATR based bands?
While ATR and other measures of volatility base their calculations on the previous bars on the chart (for example bars 1954 to 1968). The volatility used in these bands measure expected volatility during that time of the day.
Why would you take this approach?
Markets behave different during certain times of the day, also called sessions.
Here are a couple examples.
Asian Session (generally low volatility)
London Session (bigger volatility starts)
New York Session (overlap of New York with London creates huge volatility)
Generally when using bands or channel type indicators intraday they do not account for the upcoming sessions. On London open price will quickly spike through a bollinger band and it will take some time for the bands to adjust to new volatility.
This script will show expected volatility targets at the start of each new bar and will not adjust during the bar. It already knows what price is expected to do at this time of day.
Script also plots arrows when price breaches either the top or bottom of the bands. You can also set alerts for when this occurs. These are non repainting as the script knows the level at start of the bar and does not change.
🔷 CALCULATION
Think of this script like an ATR but instead it uses past days data instead of previous bars data. Charts below should visualise this more clearly:
The scripts measure of volatility is based on a simple high-low.
The script also counts the number of bars that exist in a day on your current timeframe chart. After knowing that number it creates the matrix used in it's calculations and data storage.
See how it works perfectly on a lower timeframe chart below:
Getting this right was the hardest part, check the coding if you are interested in this type of stuff. I commented every step in the coding process.
🔷 SETTINGS
Every setting of the script has a tooltip but I provided a breakdown here:
Some more examples of different charts:
Machine Learning: Trend Lines [YinYangAlgorithms]Trend lines have always been a key indicator that may help predict many different types of price movements. They have been well known to create different types of formations such as: Pennants, Channels, Flags and Wedges. The type of formation they create is based on how the formation was created and the angle it was created. For instance, if there was a strong price increase and then there is a Wedge where both end points meet, this is considered a Bull Pennant. The formations Trend Lines create may be powerful tools that can help predict current Support and Resistance and also Future Momentum changes. However, not all Trend Lines will create formations, and alone they may stand as strong Support and Resistance locations on the Vertical.
The purpose of this Indicator is to apply Machine Learning logic to a Traditional Trend Line Calculation, and therefore allowing a new approach to a modern indicator of high usage. The results of such are quite interesting and goes to show the impacts a simple KNN Machine Learning model can have on Traditional Indicators.
Tutorial:
There are a few different settings within this Indicator. Many will greatly impact the results and if any are changed, lots will need ‘Fine Tuning’. So let's discuss the main toggles that have great effects and what they do before discussing the lengths. Currently in this example above we have the Indicator at its Default Settings. In this example, you can see how the Trend Lines act as key Support and Resistance locations. Due note, Support and Resistance are a relative term, as is their color. What starts off as Support or Resistance may change when the price crosses over / under them.
In the example above we have zoomed in and circled locations that exhibited markers of Support and Resistance along the Trend Lines. These Trend Lines are all created using the Default Settings. As you can see from the example above; just because it is a Green Upwards Trend Line, doesn’t mean it’s a Support Line. Support and Resistance is always shifting on Trend Lines based on the prices location relative to them.
We won’t go through all the Formations Trend Lines make, but the example above, we can see the Trend Lines formed a Downward Channel. Channels are when there are two parallel downwards Trend Lines that are at a relatively similar angle. This means that they won’t ever meet. What may happen when the price is within these channels, is it may bounce between the upper and lower bounds. These Channels may drive the price upwards or downwards, depending on if it is in an Upwards or Downwards Channel.
If you refer to the example above, you’ll notice that the Trend Lines are formed like traditional Trend Lines. They don’t stem from current Highs and Lows but rather Machine Learning Highs and Lows. More often than not, the Machine Learning approach to Trend Lines cause their start point and angle to be quite different than a Traditional Trend Line. Due to this, it may help predict Support and Resistance locations at are more uncommon and therefore can be quite useful.
In the example above we have turned off the toggle in Settings ‘Use Exponential Data Average’. This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN. By Default it is enabled, but as you can see when it is disabled it may create some pretty strong lasting Trend Lines. This is why we advise you ZOOM OUT AS FAR AS YOU CAN. Trend Lines are only displayed when you’ve zoomed out far enough that their Start Point is visible.
As you can see in this example above, there were 3 major Upward Trend Lines created in 2020 that have had a major impact on Support and Resistance Locations within the last year. Lets zoom in and get a closer look.
We have zoomed in for this example above, and circled some of the major Support and Resistance locations that these Upward Trend Lines may have had a major impact on.
Please note, these Machine Learning Trend Lines aren’t a ‘One Size Fits All’ kind of thing. They are completely customizable within the Settings, so that you can get a tailored experience based on what Pair and Time Frame you are trading on.
When any values are changed within the Settings, you’ll likely need to ‘Fine Tune’ the rest of the settings until your desired result is met. By default the modifiable lengths within the Settings are:
Machine Learning Length: 50
KNN Length:5
Fast ML Data Length: 5
Slow ML Data Length: 30
For example, let's toggle ‘Use Exponential Data Averages’ back on and change ‘Fast ML Data Length’ from 5 to 20 and ‘Slow ML Data Length’ from 30 to 50.
As you can in the example above, all of the lines have changed. Although there are still some strong Support Locations created by the Upwards Trend Lines.
We will conclude our Tutorial here. Hopefully you’ve learned how to use Machine Learning Trend Lines and will be able to now see some more unorthodox Support and Resistance locations on the Vertical.
Settings:
Use Machine Learning Sources: If disabled Traditional Trend line sources (High and Low) will be used rather than Rational Quadratics.
Use KNN Distance Sorting: You can disable this if you wish to not have the Machine Learning Data sorted using KNN. If disabled trend line logic will be Traditional.
Use Exponential Data Average: This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN.
Machine Learning Length: How strong is our Machine Learning Memory? Please note, when this value is too high the data is almost 'too' much and can lead to poor results.
K-Nearest Neighbour (KNN) Length: How many K-Nearest Neighbours are allowed with our Distance Clustering? Please note, too high or too low may lead to poor results.
Fast ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 3/5/7 all seem to work well for Fast.
Slow ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 20 - 50 all seem to work well for Slow.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
RVI_HTFThe "RVI_HTF" indicator is a tool designed to assist traders in analyzing market trends using the Relative Vigor Index (RVI) across different timeframes. It enables users to customize various aspects of the indicator's appearance and behavior. By monitoring the RVI on different timeframes, tracking its relationship with the moving average, and paying attention to extreme arrows above the 80 or below the 20 line, traders can anticipate potential reversals, trends, or changes in market momentum.
Above 80 Line: When the RVI moves above the 80 line, it suggests that the market may be overbought. Extreme upward arrows (indicating potential sell signals) can be a sign that a bullish trend might be reaching an exhaustion point. Traders may anticipate a possible trend reversal or pullback.
Below 20 Line: When the RVI dips below the 20 line, it implies that the market might be oversold. Extreme downward arrows (indicating potential buy signals) can be an early signal of a potential bullish reversal. Traders may anticipate an upcoming uptrend or bounce.
Crossing Above Moving Average: When the RVI crosses above its moving average on the selected timeframe, it can serve as an early indication of potential bullish strength in the market. This suggests that buying pressure may be increasing.
Crossing Below Moving Average: Conversely, when the RVI crosses below its moving average, it can signal potential bearish momentum. This indicates that selling pressure may be gaining strength.
Variables:
Timeframe (TF) Selection:
The indicator allows you to select the timeframe for the RVI calculation. You can choose from various options such as 1 minute (1), 5 minutes (5), 15 minutes (15), 30 minutes (30), 60 minutes (60), 240 minutes (240), Daily (D), Weekly (W), Monthly (M), or use "Auto" to automatically select a higher timeframe based on your current chart's timeframe.
Moving Average Type (MA_Type):
Function: Allows users to select the type of moving average used in RVI calculations.
Options: You can select from various moving average types, including:
SMA (Simple Moving Average)
EMA (Exponential Moving Average)
SMMA (Smoothed Moving Average, also known as RMA)
WMA (Weighted Moving Average)
VWMA (Volume Weighted Moving Average)
DEMA (Double Exponential Moving Average)
Moving Average Length (MA_Length):
Function: Permits users to set the number of periods for the selected moving average type.
Purpose: Controls the sensitivity of the RVI indicator. Longer lengths provide smoother results, while shorter lengths react more quickly to price changes.
Up Arrow Color (upArrowColor):
Function: Enables users to customize the color of arrows that indicate potential Overbought areas. (Only shown when the TF is same as or lower than the chart TF)
Down Arrow Color (downArrowColor):
Function: Allows users to specify the color of downward-pointing arrows signaling potential Oversold areas. (Only shown when the TF is same as or lower than the chart TF)
RVI Up Color (firstColor):
Function: Defines the color of the RVI line when it indicates a bullish condition on the higher timeframe.
RVI Down Color (secondColor):
Function: Specifies the color of the RVI line when it suggests a bearish condition on the higher timeframe.
RVI-Based Moving Average Up Color (firstColorMA):
Function: Customizes the color of the RVI-based moving average line when it indicates a bullish condition.
RVI-Based Moving Average Down Color (secondColorMA):
Function: Defines the color of the RVI-based moving average line when it suggests a bearish condition.
Double AI Super Trend Trading - Strategy [PresentTrading]█ Introduction and How It is Different
The Double AI Super Trend Trading Strategy is a cutting-edge approach that leverages the power of not one, but two AI algorithms, in tandem with the SuperTrend technical indicator. The strategy aims to provide traders with enhanced precision in market entry and exit points. It is designed to adapt to market conditions dynamically, offering the flexibility to trade in both bullish and bearish markets.
*The KNN part is mainly referred from @Zeiierman.
BTCUSD 8hr performance
ETHUSD 8hr performance
█ Strategy, How It Works: Detailed Explanation
1. SuperTrend Calculation
The SuperTrend is a popular indicator that captures market trends through a combination of the Volume-Weighted Moving Average (VWMA) and the Average True Range (ATR). This strategy utilizes two sets of SuperTrend calculations with varying lengths and factors to capture both short-term and long-term market trends.
2. KNN Algorithm
The strategy employs k-Nearest Neighbors (KNN) algorithms, which are supervised machine learning models. Two sets of KNN algorithms are used, each focused on different lengths of historical data and number of neighbors. The KNN algorithms classify the current SuperTrend data point as bullish or bearish based on the weighted sum of the labels of the k closest historical data points.
3. Signal Generation
Based on the KNN classifications and the SuperTrend indicator, the strategy generates signals for the start of a new trend and the continuation of an existing trend.
4. Trading Logic
The strategy uses these signals to enter long or short positions. It also incorporates dynamic trailing stops for exit conditions.
Local picture
█ Trade Direction
The strategy allows traders to specify their trading direction: long, short, or both. This enables the strategy to be versatile and adapt to various market conditions.
█ Usage
ToolTips: Comprehensive tooltips are provided for each parameter to guide the user through the customization process.
Inputs: Traders can customize numerous parameters including the number of neighbors in KNN, ATR multiplier, and types of moving averages.
Plotting: The strategy also provides visual cues on the chart to indicate bullish or bearish trends.
Order Execution: Based on the generated signals, the strategy will execute buy or sell orders automatically.
█ Default Settings
The default settings are configured to offer a balanced approach suitable for most scenarios:
Initial Capital: $10,000
Default Quantity Type: 10% of equity
Commission: 0.1%
Slippage: 1
Currency: USD
These settings can be modified to suit various trading styles and asset classes.
Recession Indicator (Unemployment Rate)Unemployment rate
percentage of unemployed individuals in an economy among individuals currently in the labour force. It is calcuated as Unemployed IndividualsTotal Labour Force × 100 where unemployed individuals are those who are currently not working but are actively seeking work.
The unemployment rate is one of the primary economic indicators used to measure the health of an economy. It tends to fluctuate with the business cycle, increasing during recessions and decreasing during expansions. It is among the indicators most commonly watched by policy makers, investors, and the general public.
Policy makers and central banks consider how much the unemployment rate has increased during a particular recession to gauge the recession’s impact on the economy and to decide how to tailor fiscal and monetary policies to mitigate its adverse effects. In addition, central banks carefully try to predict the future trend of the unemployment rate to devise long-term strategies to lower it.
This indicator is a representation of yearly rate of change of Unemployment rate. Historically (not always) when ROC(Yearly) of Unemployment rate crossover zero line was a signal of recession or economic contraction.