KNN ATR Dual Range Predictions [SS]Excited to release this indicator!
I wanted to do a machine learning, ATR based indicator for a while, but I first had to learn about machine learning algos haha.
Now that I have created a KNN based regression methodology (shared in a previous indicator), I can finally do it!
So this is a Nearest Known Neighbor or KNN regression based indicator that uses ATR (average ranges) to predict future ranges.
It operates by calculating the move from High to Open and Open to Low and performing KNN regression to look for other, similar instances of similar movements and what followed those movements.
It provides for 2 methods of KNN regression, the traditional Cluster method (where it identifies a number of clusters within a tolerance range and averages them out), or the method of last instance (where it finds the most recent identical instance and plots the result from that).
You can toggle the parameters as you wish, including the:
a) Type of Regression
b) Number of Clusters
c) Tolerance for Clusters
Others functions:
The indicator provides for the ability to view 2 different timeframe targets. The default calculation is the current timeframe you are on. So if you are on the 1 minute, 5 minute or 1 hour, it will automatically default the primary range to this timeframe. This cannot be changed.
But it permits for a second prediction to be calculated for a timeframe you can specify. The example in the chart above is the 1 hour overlaid on the 5 minute chart.
You can see how the model is performing in the statistics table. The statistics table can be removed as well if you don't want it overlaid on your chart.
You can also toggle off and on the various ranges. IF you only want to visualize 1 hour levels on a 5 minute chart, you can toggle off the bands and just view the higher tf data. Inversely, if you only want the current timeframe data and not the higher tf data, you can toggle the higher tf data off as well.
General Use Tips:
Some general use tips include:
🎯The default settings are appropriate for most common tickers. Because this is performing an autoregression on itself, the parameters tend to be more tight vs. performing dual correlation between two separate tickers which are sizably different in scale (which would require a higher tolerance).
Here is an example of YM1!, which is a sizably larger ticker, however it is performing well with the current settings.
🎯 If you get not great results from your ranges or an error in the correlation table, something like this:
It means the parameters are too tight for what you want to do and it is having trouble identifying other, similar cases (in this case, the lookback length was significantly shortened). The first step is to:
a) Expand your lookback range (up to 500 is usually sufficient). This should resolve most issues in most cases. If not:
b) If you are using the Cluster method, try broadening your cluster tolerance by 0.5 increments.
Between those two implementations, you should get a functional model. And it actually honestly hasn't happened to me in general use, I had to force that example by significantly shortening the lookback period.
Concluding Remarks
And that's pretty much the indicator.
I hope you enjoy it! I was really excited to be finally able to do it, like I said I attempted to do this for a while but needed to research the whole KNN process and how its performed.
Enjoy and leave your comments and questions below!
Forecasting
Data from dataThe "Data from Data" indicator, developed by OmegaTools, is a sophisticated and versatile tool designed to offer a nuanced analysis of various market dynamics, catering to traders and investors seeking a comprehensive understanding of price movements considering a large amount of data and variables.
The uses of this indicator are nonconventional. You can use the indicator as a stand-alone tool on the chart, hiding the current symbol price data, to be able to analyze the price action with the Semaphore visualization method, you can also hide the indicator and choose from your favorite indicators and oscillator one of the data output as a source to have additional insight on the asset.
The last use of this indicator, which depends on the X Value that you set in the settings, is to have a possible scenario for the future outcomes of the markets. Remember that there is no tool that can really predict what the market will do in the future, this tool applies a large amount of formulas to use past prices as an indication that aims to be as close as possible to the future prices. The X Value not only changes the lookback of the formulas but also changes the number of future scenarios that the indicator will plot on the chart.
Key Features:
1. Rate of Change Analysis:
The indicator evaluates the rate of change variations in closing prices, providing insights into the current rate of change and expected rate of change variation.
2. Momentum Analysis:
Momentum is analyzed through calculations involving simple moving averages, offering expected values derived from momentum and momentum variation.
3. High/Low Variation:
The expected market behavior is assessed based on the average variation between high and low prices, contributing to a more holistic analysis.
4. Liquidity Targets:
Liquidity targets can be found by analyzing the highs and lows in the direction of the current fair price.
5. Regression Sequence:
Linear regression analysis is applied to closing prices, assessing momentum and providing expected values based on regression sequences.
6. Volume Presence:
The indicator evaluates the Rate of Change (ROC) by volume presence, offering insights into price movements influenced by trading volume.
7. Liquidity Grabs:
Expected market behavior is determined based on liquidity grabs, considering both current and historical price levels.
8. Fair Value Analysis:
Expected values are derived from fair value closes and fair value highs and lows, contributing to a more nuanced analysis of market conditions.
9. STT (Sequential Trend Test):
The Sequential Trend Test is employed to analyze market trends, providing expected values for a more informed decision-making process.
Visualization:
The indicator shows a "Semaphore" on the chart, visually representing all of the data extrapolated from the script. The visualization can be more minimalistic or more complex, to let the user decide that, in the settings, it's possible to decide if to show all of the data or only the average.
Additionally, the user can choose to display bars on the chart, that visualize the standard high and low of the price data, with the difference between the expected forecasted value and the actual closing price.
My suggestion is to try to change the colors of the data to fit best your eye and the data that you find more useful, and also to try to change some parameters from circle to line as a visualization method to catch with more ease some price patterns.
Error Analysis:
The indicator provides a detailed error analysis, including historical error, average error, and present error. This information is presented in a user-friendly table for quick reference. This table can be used to analyze the margin of error of the expected future price.
Backtest Strategy Optimizer Adapter - Supertrend ExampleSample Code
This is a sample code for my Backtest Strategy Optimizer Adapter library.
You can find the library at:
Backtest Strategy Optimizer Tester
With this indicator, you will be able to run one or multiple backtests with different variables (combinations). For example, you can run dozens of backtests of Supertrend at once with an increment factor of 0.1, or whatever you prefer. This way, you can easily grab the most profitable settings and use them in your strategy. The chart above shows different color plots, each indicating a profit backtest equal to tradingview backtesting system. This code uses my backtest library, available in my profile.
Below the code you should edit yourself
You can use ChatGPT or write a python script to autogenerate code for you.
// #################################################################
// # ENTRIES AND EXITS
// #################################################################
// You can use the link and code in the description to create
// your code for the desired number of entries / exits.
// #################################################################
// AUTO GENERATED CODE
// ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
= ti.supertrend(10, 0.1)
= ti.supertrend(10, 0.2)
= ti.supertrend(10, 0.3)
= ti.supertrend(10, 0.4)
// 005 etc...
pnl_001 = backtest.profit(date_start, date_end, entry_001, exit_001)
pnl_002 = backtest.profit(date_start, date_end, entry_002, exit_002)
pnl_003 = backtest.profit(date_start, date_end, entry_003, exit_003)
pnl_004 = backtest.profit(date_start, date_end, entry_004, exit_004)
plot(pnl_001, title='0.1', color=backtest.color(001))
plot(pnl_002, title='0.2', color=backtest.color(002))
plot(pnl_003, title='0.3', color=backtest.color(003))
plot(pnl_004, title='0.4', color=backtest.color(004))
// Make sure you set the correct array size.
// The amount of tests + 1 (e.g. 4 tests you set it to 5)
var results_list = array.new_string(5)
if (ta.change(pnl_001))
array.set(results_list, 0, str.tostring(pnl_001) + '|0.1')
if (ta.change(pnl_002))
array.set(results_list, 1, str.tostring(pnl_002) + '|0.2')
if (ta.change(pnl_003))
array.set(results_list, 2, str.tostring(pnl_003) + '|0.3')
if (ta.change(pnl_004))
array.set(results_list, 3, str.tostring(pnl_004) + '|0.4')
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// AUTO GENERATED CODE
// #################################################################
ADR % RangesThis indicator is designed to visually represent percentage lines from the open of the day. The % amount is determined by X amount of the last days to create an average...or Average Daily Range (ADR).
1. ADR Percentage Lines: The core function of the script is to apply lines to the chart that represent specific percentage changes from the daily open. It first calculates the average over X amount of days and then displays two lines that are 1/3rd of that average. One line goes above the other line goes below. The other two lines are the full "range" of the average. These lines can act as boundaries or targets to know how an asset has moved recently. *Past performance is not indicative of current or future results.
The calculation for ADR is:
Step 1. Calculate Today's Range = DailyHigh - DailyLow
Step 2. Store this average after the day has completed
Step 3. Sum all day's ranges
Step 4. Divide by total number of days
Step 5. Draw on chart
2. Customizable Inputs: Users have the flexibility to customize the script through various inputs. This includes the option to display lines only for the current trading day (`todayonly`), and to select which lines are displayed. The user can also opt to show a table the displays the total range of previous days and the average range of those previous days.
3. No Secondary Timeframe: The ADR is computed based on whatever timeframe the chart is and does not reference secondary periods. Therefore the script cannot be used on charts greater than daily.
This script is can be used by all traders for any market. The trader might have to adjust the "X" number of days back to compute a historical average. Maybe they only want to know the average over the past week (5 days) or maybe the past month (20 days).
[KVA]Body Percentage Counter This indicator presents a comprehensive view of the historical candle data within user-defined body percentage ranges. Each column represents a specific body size percentage threshold, starting from as low as 0.01% and extending up to 20%.
The rows categorize candles by their closing and opening price differences, effectively sorting them into green (bullish) and red (bearish) candles based on whether they closed higher or lower than their opening prices.
First Row of the table is the bu
For developers, this table can be immensely useful in determining stop-loss ranges. By analyzing the frequency of candles that fall within certain body percentage ranges, developers can better understand where to set stop-loss orders. For instance, if a developer notices a high frequency of candles with body sizes within a specific percentage range, they may choose to set their stop-loss orders outside of this range to avoid being stopped out by normal market fluctuations.
Moreover, the indicator can be used to:
Volatility Assessment : The indicator can be used to gauge market volatility. Smaller bodies may indicate consolidation periods, while larger bodies might suggest more volatile market conditions.
Optimize Trading Strategies : Adjust entry and exit points based on the prevalence of certain candle sizes.
Risk Management : Determine the commonality of price movements within a certain range to better manage risks.
Backtesting : Use historical data to backtest how different stop-loss ranges would have performed in the past.
Comparative Analysis : Traders can compare the frequency of different body sizes over a selected period, providing insights into how the market is evolving.
Educational Use : For new traders, the indicator can serve as an educational tool to understand the implications of candlestick sizes and their relationship with market dynamics
The data provided in this output can guide developers to make more informed decisions about where to place stop-loss orders, potentially increasing the effectiveness of their trading algorithms or manual trading strategies.
The output of the " Body Percentage Counter" indicator is organized into a table format, which can be broken down as follows:
Header (First Row) : This row lists the body percentage thresholds used to categorize the candles. It starts from 0.01% and increases incrementally to 20%. These thresholds are likely set by the user and represent the range of candle body sizes as a percentage of the total candle size.
Green Candle Count (Second Row) : This row displays the count of green candles—candles where the close price is higher than the open price—that fall within each body percentage threshold. For example, under the column "0.01", the number 25 indicates there are 25 green candles whose body size is 0.01% of the total candle size.
Red Candle Count (Third Row) : This row shows the count of red candles—candles where the close price is lower than the open price—for each body percentage threshold. The numbers in this row reflect the number of red candles that match the body percentage criteria in the corresponding column.
Total Candle Count (Fourth Row) : This row sums the counts of both green and red candles for each body percentage threshold, providing a total count of candles that have a body size within the specific range. For instance, if under "0.01" the green count is 25 and the red count is 26, then the total would be 51.
This organized data representation allows users to quickly assess the distribution of candle body sizes over a historical period, which is especially useful for determining the frequency of price movements that are significant enough to consider for stop-loss settings or other trade management decisions.
Time-itTime-it = Time based indicator
The Time-it indicator parses data by the day of week. Every tradeable instrument has its own personality. Some are more volatile on Mondays, and some are more bullish / bearish on Fridays or any day in between. The key metrics Time-it parses is range, open, high, low, close and +volume-.
The Time-it parsed data is printed in a table format. The table, position, size & color and text color & size can be changed to your preference. Each column parsed data is the last 10 which is numbered 0-9 which refers to the number of the selected day bars ago. For example: if Monday is chosen, 0 is the last closed Monday bar and 9 is the last closed Monday 9 Monday bars ago.
Range = measures the range between high and low for the day.
Open = is the opening price for the day.
High = is the high price for the day.
Low = is the low price for the day.
Close = is the closing price for the day.
+volume- = is the positive or negative volume for the day.
Default settings:
*Represents a how to use tooltip*
Source = ohlc4
* The source used for MA
MA length = 20
* The moving average used
Day bar color on / off
* checked on / unchecked off
Monday = blue
Tuesday = yellow
Wednesday = purple
Thursday = orange
Friday = white
Saturday = red
Sunday = green
Day M, T, W, TH, F, ST, SN.
* Parsed data for the day of week tables
Table, position, size & color:
Top, middle, bottom, left, center, right
* Table position on the chart.
Frame width & border width = 1
Text color and text size
Border color and frame color
Decimal place = 0
* example: use 0 for a round number, use 4 for Forex
*** The Time-it indicator uses parts and/or pieces of code from "Tradingview Up/Down Volume" and "Tradingview Financials on Chart".
Trend Line XrossTrend Line Xross (TLX) Uses User Input Points to draw trendlines and displays the exact intersection point of those trendlines.
This is the public indicator of the practical application for this intersection method included in my entry for Pinefest #1.
To determine the exact intersection point I am using the y-intercept method as seen below.
The code is notated for more information on the technical workings.
One difference to note between this version and the pinefest version is that I had to change the line drawings to use bar_index values so that I can use line.get_price() to grab the current value of the line to make alerts from.
Additionally, there are alerts built-in to this version for every type of cross on all of the visible lines.
Enjoy!
Intersection PointThis publication focusses at the intersection of 2 lines, and a trend estimation derived from a comparison of Intersection Point value against current price value.
The formula to calculate the Intersection Point (IP) is:
change1 = ta.change (valueLine1)
change2 = ta.change (valueLine2)
sf = (valueLine2 - valueLine1 ) / (change1 - change2)
I = valueLine1 + change1 * sf
🔶 USAGE
🔹 Future / Past Intersection
The position where 2 lines would intersect in the future is shown here by extending both lines and a yellow small line to indicate its location:
Of course this can change easily when price changes.
If "Back" is enabled, the IP in history can be seen:
The yellow line which indicates the IP is only visible when it is not further located then +/- 500 bars from current bar.
If this point is further away, lines towards the IP still will be visible (max 500 bars further) without the IP.
🔹 Trend
The calculated intersection price is compared with the latest close and used for estimating the trend direction.
When close is above the intersection price (I), this is an indication the market is trending up, if close is below I, this would indicate the market is trending down.
The included bands can be useful for entry/SL/TP,...
🔶 DETAILS
🔹 Map.new()
All values are put in a map.new() with the function value()
The latest Intersection is also placed in this map with the function addLastIntersectValue() and retrieved at the last bar (right top)
🔹 Intersection Point Line
The intersection price can be made visible by enabling "Intersection Price" in SETTINGS -> STYLE. To ensure lines aren't drawn all over the place, this value is limited to maximum high + 200 days-ATR and minimum low - 200 days-ATR.
🔶 SETTINGS
🔹 Choose the value for both lines :
Type : choose between
• open, high, low, close,
• SMA, EMA, HullMA, WMA, VWMA, DEMA, TEMA
• The Length setting sets 1 of these Moving Averages when chosen
• src 1 -> You can pick an external source here
🔹 Length Intersection Line : Max length of line:
Intersection Line will update untillthe amount of bars reach the "Length Intersection Line"
💜 PURPLE BARS 😈
• Since TradingView has chosen to give away our precious Purple coloured Wizard Badge, bars are coloured purple 😊😉
Ultimate Seasonality Indicator [SS]Hello everyone,
This is my seasonality indicator. I have been working on it for like 2 months, so hope you like it!
What it does?
The Ultimate Seasonality indicator is designed to provide you, the trader, an in-depth look at seasonality. The indicator gives you the ability to do the following functions:
View the most bearish and bullish months over a user defined amount of years back.
View the average daily change for each respective months over a user defined amount of years back.
See the most closely correlated month to the current month to give potential insights of likely trend.
Plot out areas of High and Low Seasonality.
Create a manual seasonal forecast model by selecting the desired month you would like to model the current month data after.
Have the indicator develop an autoregressive seasonal model based on seasonally lagged variables, using principles of machine learning.
I will go over these functions 1 by 1, its a whopper of an indicator so I will try to be as clear and concise as possible.
Viewing Bullish vs Bearish Months, Average Daily Change & Correlation to Current Month
The indicator will break down the average change, as well as the number of bullish and bearish days by month. See the image below as an example:
In the table to the right, you will see a breakdown of each month over the past 3 years.
In the first column, you will see the average daily change. A negative value, means it was a particularly bearish month, a positive value means it was a particularly bullish month.
The next column over shows the correlation to the current dataset. How this works is the indicator takes the size of the monthly data for each month, and compares it to the last X number of days up until the last trading day. It will then perform a correlation assessment to see how closely similar the past X number of trading days are to the various monthly data.
The last 2 columns break down the number of Bullish and Bearish days, so you can see how many red vs green candles happened in each respective month over your set timeframe. In the example above, it is over the pats 3 years.
Plot areas of High and Low Seasonality
In the chart above, you will see red and green highlighted zones.
Red represents areas of HIGH Seasonality .
Green represents areas of LOW Seasonality .
For this function, seasonality is measured by the autocorrelation function at various lags (12 lags). When there is an average autocorrelation of greater than 0.85 across all seasonal lags, it is considered likely the result of high seasonality/trend.
If the lag is less than or equal to 0.05, it is indicative of very low seasonality, as there is no predominate trend that can be found by the autocorrelation functions over the seasonally lagged variables.
Create Manual Seasonal Forecasts
If you find a month that has a particularly high correlation to the current month, you can have the indicator create a seasonal model from this month, and fit it onto the current dataset (past X days of trading).
If we look at the example below:
We can see that the most similar month to the current data is September. So, we can ask the indicator to create a seasonal forecast model from only September data and fit it to our current month. This is the result:
You will see, using September data, our most likely close price for this month is 450 and our model is y= 1.4305x + -171.67.
We can accept the 450 value but we can use the equation to model the data ourselves manually.
For example, say we have a target price on the month of 455 based on our own analysis. We can calculate the likely close price, should this target be reached, by substituting this target for x. So y = 1.4305x + -171.67 becomes
y = 1.4305(455) +- 171.67
y = 479.20
So the likely close price would be 479.20. No likely, and thus its not likely we are to see 455.
HOWEVER, in this current example, the model is far too statistically insignificant to be used. We can see the correlation is only 0.21 and the R squared is 0.04. Not a model you would want to use!
You want to see a correlation of at least 0.5 or higher and an R2 of 0.5 or higher.
We can improve the accuracy by reducing the number of years we look back. This is what happens when we reduce the lookback years to 1:
You can see reducing to 1 year gives December as the most similar month. However, our R2 value is still far too low to really rely on this data whole-heartedly. But it is a good reference point.
Automatic Autoregressive Model
So this is my first attempt at using some machine learning principles to guide statistical analysis.
In the main chart above, you will see the indicator making an autoregressive model of seasonally lagged variables. It does this in steps. The steps include:
1) Differencing the data over 12, seasonally lagged variables.
2) Determining stationarity using DF test.
3) Determining the highest, autocorrelated lags that fall within a significant stationary result.
4) Creating a quadratic model of the two identified lags that best represents a stationary model with a high autocorrelation.
What are seasonally lagged variables?
Seasonally lagged variables are variables that represent trading months. So a lag of 25 would be 1 month, 50, 2 months, 75, 3 months, etc.
When it displays this model, it will show us what the results of the t-statistic are for the DF test, whether the data is stationary, and the result of the autocorrelation assessment.
It will then display the model detail in the tip table, which includes the equation, the current lags being used, the R2 and the correlation value.
Concluding Remarks
That's the indicator in a nutshell!
Hope you like it!
One final thing, you MUST have your chart set to daily, otherwise you will get a runtime error. This can ONLY be used on the daily timeframe!
Feel free to leave your questions, comments and suggestions below.
Note:
My "ultimate" indicators are made to give the functionality of multiple indicators in one. If you like this one, you may like some of my others:
Ultimate P&L Indicator
Ultimate Customizable EMA/SMA
Thanks for checking out the indicator!
K`s Extreme DurationExtreme duration uses a special combination of the RSI and its relative position to deliver a reversal signal.
The following are the conditions to generate signals:
* Bullish signal: The current 8-period RSI is below 50 and above 35 while the previous 5 RSI's are below 35.
* Bearish signal: The current 8-period RSI is above 50 and below 65 while the previous 5 RSI's are above 65.
Machine Learning: Anchored Gaussian Process Regression [LuxAlgo]Machine Learning: Anchored Gaussian Process Regression is an anchored version of Machine Learning: Gaussian Process Regression .
It implements Gaussian Process Regression (GPR), a popular machine-learning method capable of estimating underlying trends in prices as well as forecasting them. Users can set a Training Window by choosing 2 points. GPR will be calculated for the data between these 2 points.
Do remember that forecasting trends in the market is challenging, do not use this tool as a standalone for your trading decisions.
🔶 USAGE
When adding the indicator to the chart, users will be prompted to select a starting and ending point for the calculations, click on your chart to select those points.
Start & end point are named 'Anchor 1' & 'Anchor 2', the Training Window is located between these 2 points. Once both points are positioned, the Training Window is set, whereafter the Gaussian Process Regression (GPR) is calculated using data between both Anchors .
The blue line is the GPR fit, the red line is the GPR prediction, derived from data between the Training Window .
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.
One of the advantages of the anchoring process is the ability for the user to evaluate the accuracy of forecasts and further understand how settings affect their accuracy.
The publication also shows the mean average (faint silver line), which indicates the average of the prices within the calculation window (between the anchors). This can be used as a reference point for the forecast, seeing how it deviates from the training window average.
🔶 DETAILS
🔹 Limited Training Window
The Training Window is limited due to matrix.new() limitations in size.
When the 2 points are too far from each other (as in the latter example), the line will end at the maximum limit, without giving a size error.
The red forecasted line is always given priority.
🔹 Positioning Anchors
Typically Anchor 1 is located further in history than Anchor 2 , however, placing Anchor 2 before Anchor 1 is perfectly possibly, and won't give issues.
🔶 SETTINGS
Anchor 1 / Anchor 2: both points will form the Training Window .
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.
Multi-TF AI SuperTrend with ADX - Strategy [PresentTrading]
## █ Introduction and How it is Different
The trading strategy in question is an enhanced version of the SuperTrend indicator, combined with AI elements and an ADX filter. It's a multi-timeframe strategy that incorporates two SuperTrends from different timeframes and utilizes a k-nearest neighbors (KNN) algorithm for trend prediction. It's different from traditional SuperTrend indicators because of its AI-based predictive capabilities and the addition of the ADX filter for trend strength.
BTC 8hr Performance
ETH 8hr Performance
## █ Strategy, How it Works: Detailed Explanation (Revised)
### Multi-Timeframe Approach
The strategy leverages the power of multiple timeframes by incorporating two SuperTrend indicators, each calculated on a different timeframe. This multi-timeframe approach provides a holistic view of the market's trend. For example, a 8-hour timeframe might capture the medium-term trend, while a daily timeframe could capture the longer-term trend. When both SuperTrends align, the strategy confirms a more robust trend.
### K-Nearest Neighbors (KNN)
The KNN algorithm is used to classify the direction of the trend based on historical SuperTrend values. It uses weighted voting of the 'k' nearest data points. For each point, it looks at its 'k' closest neighbors and takes a weighted average of their labels to predict the current label. The KNN algorithm is applied separately to each timeframe's SuperTrend data.
### SuperTrend Indicators
Two SuperTrend indicators are used, each from a different timeframe. They are calculated using different moving averages and ATR lengths as per user settings. The SuperTrend values are then smoothed to make them suitable for KNN-based prediction.
### ADX and DMI Filters
The ADX filter is used to eliminate weak trends. Only when the ADX is above 20 and the directional movement index (DMI) confirms the trend direction, does the strategy signal a buy or sell.
### Combining Elements
A trade signal is generated only when both SuperTrends and the ADX filter confirm the trend direction. This multi-timeframe, multi-indicator approach reduces false positives and increases the robustness of the strategy.
By considering multiple timeframes and using machine learning for trend classification, the strategy aims to provide more accurate and reliable trade signals.
BTC 8hr Performance (Zoom-in)
## █ Trade Direction
The strategy allows users to specify the trade direction as 'Long', 'Short', or 'Both'. This is useful for traders who have a specific market bias. For instance, in a bullish market, one might choose to only take 'Long' trades.
## █ Usage
Parameters: Adjust the number of neighbors, data points, and moving averages according to the asset and market conditions.
Trade Direction: Choose your preferred trading direction based on your market outlook.
ADX Filter: Optionally, enable the ADX filter to avoid trading in a sideways market.
Risk Management: Use the trailing stop-loss feature to manage risks.
## █ Default Settings
Neighbors (K): 3
Data points for KNN: 12
SuperTrend Length: 10 and 5 for the two different SuperTrends
ATR Multiplier: 3.0 for both
ADX Length: 21
ADX Time Frame: 240
Default trading direction: Both
By customizing these settings, traders can tailor the strategy to fit various trading styles and assets.
Expected Move by Option's Implied Volatility Symbols: EAT - GBDC
This script plots boxes to reflect weekly, monthly and yearly expected moves based on "At The Money" put and call option's implied volatility.
Symbols in range: This script will display Expected Move data for Symbols within the range of EAT-GDBC in alphabetical order.
Weekly Updates: Each weekend, the script is updated with fresh expected move data, a job that takes place every Saturday following the close of the markets on Friday.
In the provided script, several boxes are created and plotted on a price chart to represent the expected price moves for various timeframes.
These boxes serve as visual indicators to help traders and analysts understand the expected price volatility.
Definition of Expected Move: Expected Move refers to the anticipated range within which the price of an underlying asset is expected to move over a specific time frame, based on the current implied volatility of its options. Calculation: Expected Move is typically calculated by taking the current stock price and applying a multiple of the implied volatility. The most commonly used multiple is the one-standard-deviation move, which encompasses approximately 68% of potential price outcomes.
Example: Suppose a stock is trading at $100, and the implied volatility of its options is 20%. The one-standard-deviation expected move would be $100 * 0.20 = $20.
This suggests that there is a 68% probability that the stock's price will stay within a range of $80 to $120 over the specified time frame. Usage: Traders and investors use the expected move as a guideline for setting trading strategies and managing risk. It helps them gauge the potential price swings and make informed decisions about buying or selling options. There is a 68% chance that the underlying asset stock or ETF price will be within the boxed area at option expiry. The data on this script is updating weekly at the close of Friday, calculating the implied volatility for the week/month/year based on the "at the money" put and call options with the relevant expiry.
In summary, implied volatility reflects market expectations about future price volatility, especially in the context of options. Expected Move is a practical application of implied volatility, helping traders estimate the likely price range for an asset over a given period. Both concepts play a vital role in assessing risk and devising trading strategies in the options and stock markets.
Expected Move by Option's Implied Volatility Symbols: CLFD-EARN This script plots boxes to reflect weekly, monthly and yearly expected moves based on "At The Money" put and call option's implied volatility.
Symbols in range: This script will display Expected Move data for Symbols within the range of CLFD - EARN in alphabetical order.
Weekly Updates: Each weekend, the script is updated with fresh expected move data, a job that takes place every Saturday following the close of the markets on Friday.
In the provided script, several boxes are created and plotted on a price chart to represent the expected price moves for various timeframes.
These boxes serve as visual indicators to help traders and analysts understand the expected price volatility.
Definition of Expected Move: Expected Move refers to the anticipated range within which the price of an underlying asset is expected to move over a specific time frame, based on the current implied volatility of its options. Calculation: Expected Move is typically calculated by taking the current stock price and applying a multiple of the implied volatility. The most commonly used multiple is the one-standard-deviation move, which encompasses approximately 68% of potential price outcomes.
Example: Suppose a stock is trading at $100, and the implied volatility of its options is 20%. The one-standard-deviation expected move would be $100 * 0.20 = $20.
This suggests that there is a 68% probability that the stock's price will stay within a range of $80 to $120 over the specified time frame. Usage: Traders and investors use the expected move as a guideline for setting trading strategies and managing risk. It helps them gauge the potential price swings and make informed decisions about buying or selling options. There is a 68% chance that the underlying asset stock or ETF price will be within the boxed area at option expiry. The data on this script is updating weekly at the close of Friday, calculating the implied volatility for the week/month/year based on the "at the money" put and call options with the relevant expiry.
In summary, implied volatility reflects market expectations about future price volatility, especially in the context of options. Expected Move is a practical application of implied volatility, helping traders estimate the likely price range for an asset over a given period. Both concepts play a vital role in assessing risk and devising trading strategies in the options and stock markets.
Expected Move by Option's Implied Volatility Symbols: B - CLF
This script plots boxes to reflect weekly, monthly and yearly expected moves based on "At The Money" put and call option's implied volatility.
Symbols in range: This script will display Expected Move data for Symbols within the range of B - CLF in alphabetical order.
Weekly Updates: Each weekend, the script is updated with fresh expected move data, a job that takes place every Saturday following the close of the markets on Friday.
In the provided script, several boxes are created and plotted on a price chart to represent the expected price moves for various timeframes.
These boxes serve as visual indicators to help traders and analysts understand the expected price volatility.
Definition of Expected Move: Expected Move refers to the anticipated range within which the price of an underlying asset is expected to move over a specific time frame, based on the current implied volatility of its options. Calculation: Expected Move is typically calculated by taking the current stock price and applying a multiple of the implied volatility. The most commonly used multiple is the one-standard-deviation move, which encompasses approximately 68% of potential price outcomes.
Example: Suppose a stock is trading at $100, and the implied volatility of its options is 20%. The one-standard-deviation expected move would be $100 * 0.20 = $20.
This suggests that there is a 68% probability that the stock's price will stay within a range of $80 to $120 over the specified time frame. Usage: Traders and investors use the expected move as a guideline for setting trading strategies and managing risk. It helps them gauge the potential price swings and make informed decisions about buying or selling options. There is a 68% chance that the underlying asset stock or ETF price will be within the boxed area at option expiry. The data on this script is updating weekly at the close of Friday, calculating the implied volatility for the week/month/year based on the "at the money" put and call options with the relevant expiry.
In summary, implied volatility reflects market expectations about future price volatility, especially in the context of options. Expected Move is a practical application of implied volatility, helping traders estimate the likely price range for an asset over a given period. Both concepts play a vital role in assessing risk and devising trading strategies in the options and stock markets.
Cycle OscillatorThe Cycle Oscillator is a tool developed to help traders analyze market cycles thanks to a simplified version of the Hurst theory and the easy visualization provided by the detrended cycle.
This indicator has two functions:
- The first one is the plotting of a line that oscillates above and below the zero line, which can be used to find the cycle direction and momentum
- The second feature is the next-cycle bottom forecaster, useful for estimating the timing of the future pivot low based on the pivot low of the oscillator.
This last feature shows graphically the period in which the next low will probably happen, using as a calculation method the timing of the previous indicator's lows.
Additionally, the user can choose to modify the cycle length to analyze bigger or smaller price movements.
This indicator can be greatly used in combination with other Cycle Indicators to gain more confluence in the plotted time areas.
Cycle IndicatorThe Cycle Indicator is a tool developed to help traders analyze market cycles thanks to a simplified version of the Hurst theory.
This indicator has two functions:
- The first one is the plotting of a line that can be used to find the cycle direction and momentum
- The second feature is the next-cycle bottom forecaster, useful for estimating the timing of the future pivot low.
This last feature shows graphically the period in which the next low will probably happen, using as a calculation method the timing of the previous lows.
Additionally, the user can choose to extend this time zone or to limit them to the range between the last pivot high and low.
Expected Move by Option's Implied Volatility Symbols: A - AZZ
This script plots boxes to reflect weekly, monthly and yearly expected moves based on "At The Money" put and call option's implied volatility.
Symbols in range: This script will display Expected Move data for Symbols within the range of A - AZZ in alphabetical order.
Weekly Updates: Each weekend, the script is updated with fresh expected move data, a job that takes place every Saturday following the close of the markets on Friday.
In the provided script, several boxes are created and plotted on a price chart to represent the expected price moves for various timeframes.
These boxes serve as visual indicators to help traders and analysts understand the expected price volatility.
Definition of Expected Move: Expected Move refers to the anticipated range within which the price of an underlying asset is expected to move over a specific time frame, based on the current implied volatility of its options. Calculation: Expected Move is typically calculated by taking the current stock price and applying a multiple of the implied volatility. The most commonly used multiple is the one-standard-deviation move, which encompasses approximately 68% of potential price outcomes.
Example: Suppose a stock is trading at $100, and the implied volatility of its options is 20%. The one-standard-deviation expected move would be $100 * 0.20 = $20.
This suggests that there is a 68% probability that the stock's price will stay within a range of $80 to $120 over the specified time frame. Usage: Traders and investors use the expected move as a guideline for setting trading strategies and managing risk. It helps them gauge the potential price swings and make informed decisions about buying or selling options. There is a 68% chance that the underlying asset stock or ETF price will be within the boxed area at option expiry. The data on this script is updating weekly at the close of Friday, calculating the implied volatility for the week/month/year based on the "at the money" put and call options with the relevant expiry.
In summary, implied volatility reflects market expectations about future price volatility, especially in the context of options. Expected Move is a practical application of implied volatility, helping traders estimate the likely price range for an asset over a given period. Both concepts play a vital role in assessing risk and devising trading strategies in the options and stock markets.
Machine Learning: VWAP [YinYangAlgorithms]Machine Learning: VWAP aims to use Machine Learning to Identify the best location to Anchor the VWAP at. Rather than using a traditional fixed length or simply adjusting based on a Date / Time; by applying Machine Learning we may hope to identify crucial areas which make sense to reset the VWAP and start anew. VWAP’s may act similar to a Bollinger Band in the sense that they help to identify both Overbought and Oversold Price locations based on previous movements and help to identify how far the price may move within the current Trend. However, unlike Bollinger Bands, VWAPs have the ability to parabolically get quite spaced out and also reset. For this reason, the price may never actually go from the Lower to the Upper and vice versa (when very spaced out; when the Upper and Lower zones are narrow, it may bounce between the two). The reason for this is due to how the anchor location is calculated and in this specific Indicator, how it changes anchors based on price movement calculated within Machine Learning.
This Indicator changes the anchor if the Low < Lowest Low of a length of X and likewise if the High > Highest High of a length of X. This logic is applied within a Machine Learning standpoint that likewise amplifies this Lookback Length by adding a Machine Learning Length to it and increasing the lookback length even further.
Due to how the anchor for this VWAP changes, you may notice that the Basis Line (Orange) may act as a Trend Identifier. When the Price is above the basis line, it may represent a bullish trend; and likewise it may represent a bearish trend when below it. You may also notice what may happen is when the trend occurs, it may push all the way to the Upper or Lower levels of this VWAP. It may then proceed to move horizontally until the VWAP expands more and it may gain more movement; or it may correct back to the Basis Line. If it corrects back to the basis line, what may happen is it either uses the Basis Line as a Support and continues in its current direction, or it will change the VWAP anchor and start anew.
Tutorial:
If we zoom in on the most recent VWAP we can see how it expands. Expansion may be caused by time but generally it may be caused by price movement and volume. Exponential Price movement causes the VWAP to expand, even if there are corrections to it. However, please note Volume adds a large weighted factor to the calculation; hence Volume Weighted Average Price (VWAP).
If you refer to the white circle in the example above; you’ll be able to see that the VWAP expanded even while the price was correcting to the Basis line. This happens due to exponential movement which holds high volume. If you look at the volume below the white circle, you’ll notice it was very large; however even though there was exponential price movement after the white circle, since the volume was low, the VWAP didn’t expand much more than it already had.
There may be times where both Volume and Price movement isn’t significant enough to cause much of an expansion. During this time it may be considered to be in a state of consolidation. While looking at this example, you may also notice the color switch from red to green to red. The color of the VWAP is related to the movement of the Basis line (Orange middle line). When the current basis is > the basis of the previous bar the color of the VWAP is green, and when the current basis is < the basis of the previous bar, the color of the VWAP is red. The color may help you gauge the current directional movement the price is facing within the VWAP.
You may have noticed there are signals within this Indicator. These signals are composed of Green and Red Triangles which represent potential Bullish and Bearish momentum changes. The Momentum changes happen when the Signal Type:
The High/Low or Close (You pick in settings)
Crosses one of the locations within the VWAP.
Bullish Momentum change signals occur when :
Signal Type crosses OVER the Basis
Signal Type crosses OVER the lower level
Bearish Momentum change signals occur when:
Signal Type crosses UNDER the Basis
Signal Type Crosses UNDER the upper level
These signals may represent locations where momentum may occur in the direction of these signals. For these reasons there are also alerts available to be set up for them.
If you refer to the two circles within the example above, you may see that when the close goes above the basis line, how it mat represents bullish momentum. Likewise if it corrects back to the basis and the basis acts as a support, it may continue its bullish momentum back to the upper levels again. However, if you refer to the red circle, you’ll see if the basis fails to act as a support, it may then start to correct all the way to the lower levels, or depending on how expanded the VWAP is, it may just reset its anchor due to such drastic movement.
You also have the ability to disable Machine Learning by setting ‘Machine Learning Type’ to ‘None’. If this is done, it will go off whether you have it set to:
Bullish
Bearish
Neutral
For the type of VWAP you want to see. In this example above we have it set to ‘Bullish’. Non Machine Learning VWAP are still calculated using the same logic of if low < lowest low over length of X and if high > highest high over length of X.
Non Machine Learning VWAP’s change much quicker but may also allow the price to correct from one side to the other without changing VWAP Anchor. They may be useful for breaking up a trend into smaller pieces after momentum may have changed.
Above is an example of how the Non Machine Learning VWAP looks like when in Bearish. As you can see based on if it is Bullish or Bearish is how it favors the trend to be and may likewise dictate when it changes the Anchor.
When set to neutral however, the Anchor may change quite quickly. This results in a still useful VWAP to help dictate possible zones that the price may move within, but they’re also much tighter zones that may not expand the same way.
We will conclude this Tutorial here, hopefully this gives you some insight as to why and how Machine Learning VWAPs may be useful; as well as how to use them.
Settings:
VWAP:
VWAP Type: Type of VWAP. You can favor specific direction changes or let it be Neutral where there is even weight to both. Please note, these do not apply to the Machine Learning VWAP.
Source: VWAP Source. By default VWAP usually uses HLC3; however OHLC4 may help by providing more data.
Lookback Length: The Length of this VWAP when it comes to seeing if the current High > Highest of this length; or if the current Low is < Lowest of this length.
Standard VWAP Multiplier: This multiplier is applied only to the Standard VWMA. This is when 'Machine Learning Type' is set to 'None'.
Machine Learning:
Use Rational Quadratics: Rationalizing our source may be beneficial for usage within ML calculations.
Signal Type: Bullish and Bearish Signals are when the price crosses over/under the basis, as well as the Upper and Lower levels. These may act as indicators to where price movement may occur.
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!
Choose Symbol, candle and Trend modeThis Pine Script code is designed for technical analysis and visualization of price movements on the TradingView platform. It serves as a tool for traders and investors to:
Price Chart Analysis: The code plots the price chart of a selected symbol and utilizes Heikin-Ashi candlesticks to visualize price movements. This aids in better understanding price trends, support and resistance levels, retracements, and other price actions.
Trend Identification: The code also employs the Exponential Moving Average (EMA) to identify the price trend. EMA is commonly used to determine the strength and direction of a trend. Traders and investors can use this information to track trends and develop trading strategies.
Buy and Sell Signals: The code generates buy and sell signals based on EMA. These signals provide information on when to consider buying or selling a specific symbol. This is particularly useful for traders when making trading decisions.
Timeframe Customization: Users can adapt the code to different timeframes. This flexibility is valuable for those looking to develop strategies for both short-term and long-term trading.
Customization: The code allows users to customize various parameters, including the symbol, timeframe, Heikin-Ashi mode, and others. This enables it to be tailored to different assets and trading styles.
Please note that this code is provided for educational and informational purposes only. It does not constitute financial advice or recommendations for specific trading actions. Any trading decisions made using this code should be based on individual research, analysis, and a clear understanding of the associated risks.
AR Forecast Scatterplot [SS]This is a showcase indicator of my recently released SPTS library (the partner of the SPTS indicator).
This is just to show some of the practical applications of the boring statistical functions contained within the library/SPTS indicator :-).
This is an autoregressive (AR), scatter plot forecaster. What this means is it tags a lag of 1, performs an autoregressive assessment over the desired training time, then uses what it learns over that training time to forecast the likely outcome.
Its not a machine learning (I am in the process of creating one like this, but it is taking quite some time to complete), but the model needs to learn to plan the statistical coefficients that will best mimic the current trend.
As of its current state, this actually surpassed my own expectations. I can show you some QQQ examples:
Example #1:
Prediction:
Actual:
Example #2:
Prediction:
Actual:
Pretty nuts, eh?
Statistics, I'm telling you, its the answer haha.
So how do we determine the train time?
Because this is not using machine learning to control for over/under representation of datasize (again, I am making a version that does this, but its a slow process), some quick tips at determine appropriate train time is to use the Tradingview Regression tool:
When you set the parameters to align with the current, strongest trend, it is more reliable.
You will see, that it acutally is forecasting a move back to the exact top of this trend, that is because it is using the same processes as the linear regression trend on Tradingview.
You can use a bar counter indicator ( such as mine available here ) to calculate the number or bars back for your model training.
You can verify that these parameters are appropriate by looking at the Model Data table (which can be toggled on and off). You want to see both a high correlation and a high R2 value.
Quick note on colour:
Green = represents the upper confidence predictions (best case scenario)
Blue = represents the most likely result
red = represents that lower confidence (not as best case scenario)
Hope you enjoy!
Safe trades everyone!
WU Sahm Recession Indicator The Sahm Recession Indicator devised by Economist Claudia Sahm is a rather insightful tool that captures the onset of recessions by utilizing unemployment data, which can provide more real-time insights compared to quarterly GDP reports. If the three-month simple moving average (SMA) of the unemployment rate exceeds the minimum unemployment rate of the previous 12 months by 0.5 percentage points, it indicates a high likelihood of a recession.
This script allows you to visualize this indicator and set up alerts for when this criterion indicates that a recession could be coming.
Asiri Colored CandleNote: To use this code, you must choose Hollow candle
This code color the candle based the relationship current volume to previous volume, according these features:
1- White candle when the current volume greater than the previous one, and all of them greater than moving average for 20 periods of volume
2- Green candle color when the current volume greater than the previous one, and all of them lower than moving average for 20 periods of volume
3- Blue candle it means (Bullish Candle) purchasing candles, with change 3% or higher
4- Yellow candle it means (Bearish Candle) with change 3% or higher
5- The number upper the candle means how much does the volume represent relative to the volume moving average
6- The number lower candle means value of MFI indicator value
كود برمجي يقوم بإعطاء لون للشموع بناء على الحجم
لطي تتمكن من استخدام هذا الكود يجب أن يكون نمط الشموع الذي على الشارت شموع مفرغة
من خصائصه التالي
1- إذا الحجم السفلي الحالي أكبر من الحجم السابق وكلاهما فوق متوسط 20 للحجم والسعر الحالي ارتفع عن السعر السابق يقوم بتلوين الشمعة بيضاء
2- إذا الحجم السفلي الحالي أكبر من الحجم السابق وكلاهما أسفل متوسط 20 للحجم والسعر الحالي ارتفع عن السعر السابق يقوم بتلوين الشمعة خضراء
3- إذا الحجم الحالي أقل من السابق ولكن تكونت شمعة شرائية ارتفعت الشمعة بـ 3% أو تغيرها كان 3% فأعلى يكون لونها أزرق
4- إذا تكونت شمعة بيعية انخفاضها أو تغيرها كان 3% بأعلى يكون لونها أصفر
5- الأرقام أعلى الشموع تبين كم أن الحجم المقابل للشمعة ضعف الحجم لمتوسط حجم 20 فترة سابقة للحجم يعني إذا كان أعلى الشمعة 3 فهذا يعني أن الحجم لهذه الشمعة ارتفع بـ 3 أضعاف متوسط 20 فترة سابقة للحجم ، كما أن هذا الرقم يظهر أعلى شمعة الدوجي التي إغلاقها مساوي لافتتاحها
6- الرقم أسفل الشمعة يبين قيمة مؤشر التدفق النقدي MFI
أخيرا تستطيع التعديل على الكود حسب ما تراه و إخفاء الأرقام أعلى أو أسفل الشموع
لا تنسوني من دعائكم