Adaptive SuperTrend Oscillator [AlgoAlpha]Adaptive SuperTrend Oscillator 🤖📈
Introducing the Adaptive SuperTrend Oscillator , an innovative blend of volatility clustering and SuperTrend logic designed to identify market trends with precision! 🚀 This indicator uses K-Means clustering to dynamically adjust volatility levels, helping traders spot bullish and bearish trends. The oscillator smoothly tracks price movements, adapting to market conditions for reliable signals. Whether you're scalping or riding long-term trends, this tool has got you covered! 💹✨
🔑 Key Features:
📊 Volatility Clustering with K-Means: Segments volatility into three levels (high, medium, low) using a K-Means algorithm for precise trend detection.
📈 Normalized Oscillator : Allows for customizable smoothing and normalization, ensuring the oscillator remains within a fixed range for easy interpretation.
🔄 Heiken Ashi Candles : Optionally visualize smoothed trends with Heiken Ashi-style candlesticks to better capture market momentum.
🔔 Alert System : Get notified when key conditions like trend shifts or volatility changes occur.
🎨 Customizable Appearance : Fully customizable colors for bullish/bearish signals, along with adjustable smoothing methods and lengths.
📚 How to Use:
⭐ Add the indicator to favorites by pressing the star icon. Customize settings to your preference:
👀 Watch the chart for trend signals and reversals. The oscillator will change color when trends shift, offering visual confirmation.
🔔 Enable alerts to be notified of critical trend changes or volatility conditions
⚙️ How It Works:
This script integrates SuperTrend with volatility clustering by analyzing ATR (Average True Range) to dynamically identify high, medium, and low volatility clusters using a K-Means algorithm . The SuperTrend logic adjusts based on the assigned volatility level, creating adaptive trend signals. These signals are then smoothed and optionally normalized for clearer visual interpretation. The Heiken Ashi transformation adds an additional layer of smoothing, helping traders better identify the market's true momentum. Alerts are set to notify users of key trend shifts and volatility changes, allowing traders to react promptly.
Kmeans
Correlation Clusters [LuxAlgo]The Correlation Clusters is a machine learning tool that allows traders to group sets of tickers with a similar correlation coefficient to a user-set reference ticker.
The tool calculates the correlation coefficients between 10 user-set tickers and a user-set reference ticker, with the possibility of forming up to 10 clusters.
🔶 USAGE
Applying clustering methods to correlation analysis allows traders to quickly identify which set of tickers are correlated with a reference ticker, rather than having to look at them one by one or using a more tedious approach such as correlation matrices.
Tickers belonging to a cluster may also be more likely to have a higher mutual correlation. The image above shows the detailed parts of the Correlation Clusters tool.
The correlation coefficient between two assets allows traders to see how these assets behave in relation to each other. It can take values between +1.0 and -1.0 with the following meaning
Value near +1.0: Both assets behave in a similar way, moving up or down at the same time
Value close to 0.0: No correlation, both assets behave independently
Value near -1.0: Both assets have opposite behavior when one moves up the other moves down, and vice versa
There is a wide range of trading strategies that make use of correlation coefficients between assets, some examples are:
Pair Trading: Traders may wish to take advantage of divergences in the price movements of highly positively correlated assets; even highly positively correlated assets do not always move in the same direction; when assets with a correlation close to +1.0 diverge in their behavior, traders may see this as an opportunity to buy one and sell the other in the expectation that the assets will return to the likely same price behavior.
Sector rotation: Traders may want to favor some sectors that are expected to perform in the next cycle, tracking the correlation between different sectors and between the sector and the overall market.
Diversification: Traders can aim to have a diversified portfolio of uncorrelated assets. From a risk management perspective, it is useful to know the correlation between the assets in your portfolio, if you hold equal positions in positively correlated assets, your risk is tilted in the same direction, so if the assets move against you, your risk is doubled. You can avoid this increased risk by choosing uncorrelated assets so that they move independently.
Hedging: Traders may want to hedge positions with correlated assets, from a hedging perspective, if you are long an asset, you can hedge going long a negatively correlated asset or going short a positively correlated asset.
Grouping different assets with similar behavior can be very helpful to traders to avoid over-exposure to those assets, traders may have multiple long positions on different assets as a way of minimizing overall risk when in reality if those assets are part of the same cluster traders are maximizing their risk by taking positions on assets with the same behavior.
As a rule of thumb, a trader can minimize risk via diversification by taking positions on assets with no correlations, the proposed tool can effectively show a set of uncorrelated candidates from the reference ticker if one or more clusters centroids are located near 0.
🔶 DETAILS
K-means clustering is a popular machine-learning algorithm that finds observations in a data set that are similar to each other and places them in a group.
The process starts by randomly assigning each data point to an initial group and calculating the centroid for each. A centroid is the center of the group. K-means clustering forms the groups in such a way that the variances between the data points and the centroid of the cluster are minimized.
It's an unsupervised method because it starts without labels and then forms and labels groups itself.
🔹 Execution Window
In the image above we can see how different execution windows provide different correlation coefficients, informing traders of the different behavior of the same assets over different time periods.
Users can filter the data used to calculate correlations by number of bars, by time, or not at all, using all available data. For example, if the chart timeframe is 15m, traders may want to know how different assets behave over the last 7 days (one week), or for an hourly chart set an execution window of one month, or one year for a daily chart. The default setting is to use data from the last 50 bars.
🔹 Clusters
On this graph, we can see different clusters for the same data. The clusters are identified by different colors and the dotted lines show the centroids of each cluster.
Traders can select up to 10 clusters, however, do note that selecting 10 clusters can lead to only 4 or 5 returned clusters, this is caused by the machine learning algorithm not detecting any more data points deviating from already detected clusters.
Traders can fine-tune the algorithm by changing the 'Cluster Threshold' and 'Max Iterations' settings, but if you are not familiar with them we advise you not to change these settings, the defaults can work fine for the application of this tool.
🔹 Correlations
Different correlations mean different behaviors respecting the same asset, as we can see in the chart above.
All correlations are found against the same asset, traders can use the chart ticker or manually set one of their choices from the settings panel. Then they can select the 10 tickers to be used to find the correlation coefficients, which can be useful to analyze how different types of assets behave against the same asset.
🔶 SETTINGS
Execution Window Mode: Choose how the tool collects data, filter data by number of bars, time, or no filtering at all, using all available data.
Execute on Last X Bars: Number of bars for data collection when the 'Bars' execution window mode is active.
Execute on Last: Time window for data collection when the `Time` execution window mode is active. These are full periods, so `Day` means the last 24 hours, `Week` means the last 7 days, and so on.
🔹 Clusters
Number of Clusters: Number of clusters to detect up to 10. Only clusters with data points are displayed.
Cluster Threshold: Number used to compare a new centroid within the same cluster. The lower the number, the more accurate the centroid will be.
Max Iterations: Maximum number of calculations to detect a cluster. A high value may lead to a timeout runtime error (loop takes too long).
🔹 Ticker of Reference
Use Chart Ticker as Reference: Enable/disable the use of the current chart ticker to get the correlation against all other tickers selected by the user.
Custom Ticker: Custom ticker to get the correlation against all the other tickers selected by the user.
🔹 Correlation Tickers
Select the 10 tickers for which you wish to obtain the correlation against the reference ticker.
🔹 Style
Text Size: Select the size of the text to be displayed.
Display Size: Select the size of the correlation chart to be displayed, up to 500 bars.
Box Height: Select the height of the boxes to be displayed. A high height will cause overlapping if the boxes are close together.
Clusters Colors: Choose a custom colour for each cluster.
Machine Learning Adaptive SuperTrend [AlgoAlpha]📈🤖 Machine Learning Adaptive SuperTrend - Take Your Trading to the Next Level! 🚀✨
Introducing the Machine Learning Adaptive SuperTrend , an advanced trading indicator designed to adapt to market volatility dynamically using machine learning techniques. This indicator employs k-means clustering to categorize market volatility into high, medium, and low levels, enhancing the traditional SuperTrend strategy. Perfect for traders who want an edge in identifying trend shifts and market conditions.
What is K-Means Clustering and How It Works
K-means clustering is a machine learning algorithm that partitions data into distinct groups based on similarity. In this indicator, the algorithm analyzes ATR (Average True Range) values to classify volatility into three clusters: high, medium, and low. The algorithm iterates to optimize the centroids of these clusters, ensuring accurate volatility classification.
Key Features
🎨 Customizable Appearance: Adjust colors for bullish and bearish trends.
🔧 Flexible Settings: Configure ATR length, SuperTrend factor, and initial volatility guesses.
📊 Volatility Classification: Uses k-means clustering to adapt to market conditions.
📈 Dynamic SuperTrend Calculation: Applies the classified volatility level to the SuperTrend calculation.
🔔 Alerts: Set alerts for trend shifts and volatility changes.
📋 Data Table Display: View cluster details and current volatility on the chart.
Quick Guide to Using the Machine Learning Adaptive SuperTrend Indicator
🛠 Add the Indicator: Add the indicator to favorites by pressing the star icon. Customize settings like ATR length, SuperTrend factor, and volatility percentiles to fit your trading style.
📊 Market Analysis: Observe the color changes and SuperTrend line for trend reversals. Use the data table to monitor volatility clusters.
🔔 Alerts: Enable notifications for trend shifts and volatility changes to seize trading opportunities without constant chart monitoring.
How It Works
The indicator begins by calculating the ATR values over a specified training period to assess market volatility. Initial guesses for high, medium, and low volatility percentiles are inputted. The k-means clustering algorithm then iterates to classify the ATR values into three clusters. This classification helps in determining the appropriate volatility level to apply to the SuperTrend calculation. As the market evolves, the indicator dynamically adjusts, providing real-time trend and volatility insights. The indicator also incorporates a data table displaying cluster centroids, sizes, and the current volatility level, aiding traders in making informed decisions.
Add the Machine Learning Adaptive SuperTrend to your TradingView charts today and experience a smarter way to trade! 🌟📊
RSI K-Means Clustering [UAlgo]The "RSI K-Means Clustering " indicator is a technical analysis tool that combines the Relative Strength Index (RSI) with K-means clustering techniques. This approach aims to provide more nuanced insights into market conditions by categorizing RSI values into overbought, neutral, and oversold clusters.
The indicator adjusts these clusters dynamically based on historical RSI data, allowing for more adaptive and responsive thresholds compared to traditional fixed levels. By leveraging K-means clustering, the indicator identifies patterns in RSI behavior, which can help traders make more informed decisions regarding market trends and potential reversals.
🔶 Key Features
K-means Clustering: The indicator employs K-means clustering, an unsupervised machine learning technique, to dynamically determine overbought, neutral, and oversold levels based on historical RSI data.
User-Defined Inputs: You can customize various aspects of the indicator's behavior, including:
RSI Source: Select the data source used for RSI calculation (e.g., closing price).
RSI Length: Define the period length for RSI calculation.
Training Data Size: Specify the number of historical RSI values used for K-means clustering.
Number of K-means Iterations: Set the number of iterations performed by the K-means algorithm to refine cluster centers.
Overbought/Neutral/Oversold Levels: You can define initial values for these levels, which will be further optimized through K-means clustering.
Alerts: The indicator can generate alerts for various events, including:
Trend Crossovers: Alerts for when the RSI crosses above/below the neutral zone, signaling potential trend changes.
Overbought/Oversold: Alerts when the RSI reaches the dynamically determined overbought or oversold thresholds.
Reversals: Alerts for potential trend reversals based on RSI crossing above/below the calculated overbought/oversold levels.
RSI Classification: Alerts based on the current RSI classification (ranging, uptrend, downtrend).
🔶 Interpreting Indicator
Adjusted RSI Value: The primary plot represents the adjusted RSI value, calculated based on the relative position of the current RSI compared to dynamically adjusted overbought and oversold levels. This value provides an intuitive measure of the market's momentum. The final overbought, neutral, and oversold levels are determined by K-means clustering and are displayed as horizontal lines. These levels serve as dynamic support and resistance points, indicating potential reversal zones.
Classification Symbols : The "RSI K-Means Clustering " indicator uses specific symbols to classify the current market condition based on the position of the RSI value relative to dynamically determined clusters. These symbols provide a quick visual reference to help traders understand the prevailing market sentiment. Here's a detailed explanation of each classification symbol:
Ranging Classification ("R")
This symbol appears when the RSI value is closest to the neutral threshold compared to the overbought or oversold thresholds. It indicates a ranging market, where the price is moving sideways without a clear trend direction. In this state, neither buyers nor sellers are in control, suggesting a period of consolidation or indecision. This is often seen as a time to wait for a breakout or reversal signal before taking a position.
Up-Trend Classification ("↑")
The up-trend symbol, represented by an upward arrow, is displayed when the RSI value is closer to the overbought threshold than to the neutral or oversold thresholds. This classification suggests that the market is in a bullish phase, with buying pressure outweighing selling pressure. Traders may consider this as a signal to enter or hold long positions, as the price is likely to continue rising until the market reaches an overbought condition.
Down-Trend Classification ("↓")
The down-trend symbol, depicted by a downward arrow, appears when the RSI value is nearest to the oversold threshold. This indicates a bearish market condition, where selling pressure dominates. The market is likely experiencing a downward movement, and traders might view this as an opportunity to enter or hold short positions. This symbol serves as a warning of potential further declines, especially if the RSI continues to move toward the oversold level.
Bullish Reversal ("▲")
This signal occurs when the RSI value crosses above the oversold threshold. It indicates a potential shift from a downtrend to an uptrend, suggesting that the market may start to move higher. Traders might use this signal as an opportunity to enter long positions.
Bearish Reversal ("▼")
This signal appears when the RSI value crosses below the overbought threshold. It suggests a possible transition from an uptrend to a downtrend, indicating that the market may begin to decline. This signal can alert traders to consider entering short positions or taking profits on long positions.
These classification symbols are plotted near the adjusted RSI line, with their positions adjusted based on the standard deviation and a distance multiplier. This placement helps in visualizing the classification's strength and ensuring clarity in the indicator's presentation. By monitoring these symbols, traders can quickly assess the market's state and make more informed trading decisions.
🔶 Disclaimer
Use with Caution: This indicator is provided for educational and informational purposes only and should not be considered as financial advice. Users should exercise caution and perform their own analysis before making trading decisions based on the indicator's signals.
Not Financial Advice: The information provided by this indicator does not constitute financial advice, and the creator (UAlgo) shall not be held responsible for any trading losses incurred as a result of using this indicator.
Backtesting Recommended: Traders are encouraged to backtest the indicator thoroughly on historical data before using it in live trading to assess its performance and suitability for their trading strategies.
Risk Management: Trading involves inherent risks, and users should implement proper risk management strategies, including but not limited to stop-loss orders and position sizing, to mitigate potential losses.
No Guarantees: The accuracy and reliability of the indicator's signals cannot be guaranteed, as they are based on historical price data and past performance may not be indicative of future results.
Support/Resistance v2 (ML) KmeanKmean with Standard Deviation Channel
1. Description of Kmean
Kmean (or K-means) is a popular clustering algorithm used to divide data into K groups based on their similarity. In the context of financial markets, Kmean can be applied to find the average price values over a specific period, allowing the identification of major trends and levels of support and resistance.
2. Application in Trading
In trading, Kmean is used to smooth out the price series and determine long-term trends. This helps traders make more informed decisions by avoiding noise and short-term fluctuations. Kmean can serve as a baseline around which other analytical tools, such as channels and bands, are constructed.
3. Description of Standard Deviation (stdev)
Standard deviation (stdev) is a statistical measure that indicates how much the values of data deviate from their mean value. In finance, standard deviation is often used to assess price volatility. A high standard deviation indicates strong price fluctuations, while a low standard deviation indicates stable movements.
4. Combining Kmean and Standard Deviation to Predict Short-Term Price Behavior
Combining Kmean and standard deviation creates a powerful tool for analyzing market conditions. Kmean shows the average price trend, while the standard deviation channels demonstrate the boundaries within which the price can fluctuate. This combination helps traders to:
Identify support and resistance levels.
Predict potential price reversals.
Assess risks and set stop-losses and take-profits.
Should you have any questions about code, please reach me at Tradingview directly.
Hope you find this script helpful!
AI Channels (Clustering) [LuxAlgo]The AI Channels indicator is constructed based on rolling K-means clustering, a common machine learning method used for clustering analysis. These channels allow users to determine the direction of the underlying trends in the price.
We also included an option to display the indicator as a trailing stop from within the settings.
🔶 USAGE
Each channel extremity allows users to determine the current trend direction. Price breaking over the upper extremity suggesting an uptrend, and price breaking below the lower extremity suggesting a downtrend. Using a higher Window Size value will return longer-term indications.
The "Clusters" setting allows users to control how easy it is for the price to break an extremity, with higher values returning extremities further away from the price.
The "Denoise Channels" is enabled by default and allows to see less noisy extremities that are more coherent with the detected trend.
Users who wish to have more focus on a detected trend can display the indicator as a trailing stop.
🔹 Centroid Dispersion Areas
Each extremity is made of one area. The width of each area indicates how spread values within a cluster are around their centroids. A wider area would suggest that prices within a cluster are more spread out around their centroid, as such one could say that it is indicative of the volatility of a cluster.
Wider areas around a specific extremity can indicate a larger and more spread-out amount of prices within the associated cluster. In practice price entering an area has a higher chance to break an associated extremity.
🔶 DETAILS
The indicator performs K-means clustering over the most recent Window Size prices, finding a number of user-specified clusters. See here to find more information on cluster detection.
The channel extremities are returned as the centroid of the lowest, average, and highest price clusters.
K-means clustering can be computationally expensive and as such we allow users to determine the maximum number of iterations used to find the centroids as well as the number of most historical bars to perform the indicator calculation. Do note that increasing the calculation window of the indicator as well as the number of clusters will return slower results.
🔶 SETTINGS
Window Size: Amount of most recent prices to use for the calculation of the indicator.
Clusters": Amount of clusters detected for the calculation of the indicator.
Denoise Channels: When enabled, return less noisy channels extremities, disabling this setting will return the exact centroids at each time but will produce less regular extremities.
As Trailing Stop: Display the indicator as a trailing stop.
🔹 Optimization
This group of settings affects the runtime performance of the script.
Maximum Iteration Steps: Maximum number of iterations allowed for finding centroids. Excessively low values can return a better script load time but poor clustering.
Historical Bars Calculation: Calculation window of the script (in bars).
Support & Resistance AI (K means/median) [ThinkLogicAI]█ OVERVIEW
K-means is a clustering algorithm commonly used in machine learning to group data points into distinct clusters based on their similarities. While K-means is not typically used directly for identifying support and resistance levels in financial markets, it can serve as a tool in a broader analysis approach.
Support and resistance levels are price levels in financial markets where the price tends to react or reverse. Support is a level where the price tends to stop falling and might start to rise, while resistance is a level where the price tends to stop rising and might start to fall. Traders and analysts often look for these levels as they can provide insights into potential price movements and trading opportunities.
█ BACKGROUND
The K-means algorithm has been around since the late 1950s, making it more than six decades old. The algorithm was introduced by Stuart Lloyd in his 1957 research paper "Least squares quantization in PCM" for telecommunications applications. However, it wasn't widely known or recognized until James MacQueen's 1967 paper "Some Methods for Classification and Analysis of Multivariate Observations," where he formalized the algorithm and referred to it as the "K-means" clustering method.
So, while K-means has been around for a considerable amount of time, it continues to be a widely used and influential algorithm in the fields of machine learning, data analysis, and pattern recognition due to its simplicity and effectiveness in clustering tasks.
█ COMPARE AND CONTRAST SUPPORT AND RESISTANCE METHODS
1) K-means Approach:
Cluster Formation: After applying the K-means algorithm to historical price change data and visualizing the resulting clusters, traders can identify distinct regions on the price chart where clusters are formed. Each cluster represents a group of similar price change patterns.
Cluster Analysis: Analyze the clusters to identify areas where clusters tend to form. These areas might correspond to regions of price behavior that repeat over time and could be indicative of support and resistance levels.
Potential Support and Resistance Levels: Based on the identified areas of cluster formation, traders can consider these regions as potential support and resistance levels. A cluster forming at a specific price level could suggest that this level has been historically significant, causing similar price behavior in the past.
Cluster Standard Deviation: In addition to looking at the means (centroids) of the clusters, traders can also calculate the standard deviation of price changes within each cluster. Standard deviation is a measure of the dispersion or volatility of data points around the mean. A higher standard deviation indicates greater price volatility within a cluster.
Low Standard Deviation: If a cluster has a low standard deviation, it suggests that prices within that cluster are relatively stable and less likely to exhibit sudden and large price movements. Traders might consider placing tighter stop-loss orders for trades within these clusters.
High Standard Deviation: Conversely, if a cluster has a high standard deviation, it indicates greater price volatility within that cluster. Traders might opt for wider stop-loss orders to allow for potential price fluctuations without getting stopped out prematurely.
Cluster Density: Each data point is assigned to a cluster so a cluster that is more dense will act more like gravity and
2) Traditional Approach:
Trendlines: Draw trendlines connecting significant highs or lows on a price chart to identify potential support and resistance levels.
Chart Patterns: Identify chart patterns like double tops, double bottoms, head and shoulders, and triangles that often indicate potential reversal points.
Moving Averages: Use moving averages to identify levels where the price might find support or resistance based on the average price over a specific period.
Psychological Levels: Identify round numbers or levels that traders often pay attention to, which can act as support and resistance.
Previous Highs and Lows: Identify significant previous price highs and lows that might act as support or resistance.
The key difference lies in the approach and the foundation of these methods. Traditional methods are based on well-established principles of technical analysis and market psychology, while the K-means approach involves clustering price behavior without necessarily incorporating market sentiment or specific price patterns.
It's important to note that while the K-means approach might provide an interesting way to analyze price data, it should be used cautiously and in conjunction with other traditional methods. Financial markets are influenced by a wide range of factors beyond just price behavior, and the effectiveness of any method for identifying support and resistance levels should be thoroughly tested and validated. Additionally, developments in trading strategies and analysis techniques could have occurred since my last update.
█ K MEANS ALGORITHM
The algorithm for K means is as follows:
Initialize cluster centers
assign data to clusters based on minimum distance
calculate cluster center by taking the average or median of the clusters
repeat steps 1-3 until cluster centers stop moving
█ LIMITATIONS OF K MEANS
There are 3 main limitations of this algorithm:
Sensitive to Initializations: K-means is sensitive to the initial placement of centroids. Different initializations can lead to different cluster assignments and final results.
Assumption of Equal Sizes and Variances: K-means assumes that clusters have roughly equal sizes and spherical shapes. This may not hold true for all types of data. It can struggle with identifying clusters with uneven densities, sizes, or shapes.
Impact of Outliers: K-means is sensitive to outliers, as a single outlier can significantly affect the position of cluster centroids. Outliers can lead to the creation of spurious clusters or distortion of the true cluster structure.
█ LIMITATIONS IN APPLICATION OF K MEANS IN TRADING
Trading data often exhibits characteristics that can pose challenges when applying indicators and analysis techniques. Here's how the limitations of outliers, varying scales, and unequal variance can impact the use of indicators in trading:
Outliers are data points that significantly deviate from the rest of the dataset. In trading, outliers can represent extreme price movements caused by rare events, news, or market anomalies. Outliers can have a significant impact on trading indicators and analyses:
Indicator Distortion: Outliers can skew the calculations of indicators, leading to misleading signals. For instance, a single extreme price spike could cause indicators like moving averages or RSI (Relative Strength Index) to give false signals.
Risk Management: Outliers can lead to overly aggressive trading decisions if not properly accounted for. Ignoring outliers might result in unexpected losses or missed opportunities to adjust trading strategies.
Different Scales: Trading data often includes multiple indicators with varying units and scales. For example, prices are typically in dollars, volume in units traded, and oscillators have their own scale. Mixing indicators with different scales can complicate analysis:
Normalization: Indicators on different scales need to be normalized or standardized to ensure they contribute equally to the analysis. Failure to do so can lead to one indicator dominating the analysis due to its larger magnitude.
Comparability: Without normalization, it's challenging to directly compare the significance of indicators. Some indicators might have a larger numerical range and could overshadow others.
Unequal Variance: Unequal variance in trading data refers to the fact that some indicators might exhibit higher volatility than others. This can impact the interpretation of signals and the performance of trading strategies:
Volatility Adjustment: When combining indicators with varying volatility, it's essential to adjust for their relative volatilities. Failure to do so might lead to overemphasizing or underestimating the importance of certain indicators in the trading strategy.
Risk Assessment: Unequal variance can impact risk assessment. Indicators with higher volatility might lead to riskier trading decisions if not properly taken into account.
█ APPLICATION OF THIS INDICATOR
This indicator can be used in 2 ways:
1) Make a directional trade:
If a trader thinks price will go higher or lower and price is within a cluster zone, The trader can take a position and place a stop on the 1 sd band around the cluster. As one can see below, the trader can go long the green arrow and place a stop on the one standard deviation mark for that cluster below it at the red arrow. using this we can calculate a risk to reward ratio.
Calculating risk to reward: targeting a risk reward ratio of 2:1, the trader could clearly make that given that the next resistance area above that in the orange cluster exceeds this risk reward ratio.
2) Take a reversal Trade:
We can use cluster centers (support and resistance levels) to go in the opposite direction that price is currently moving in hopes of price forming a pivot and reversing off this level.
Similar to the directional trade, we can use the standard deviation of the cluster to place a stop just in case we are wrong.
In this example below we can see that shorting on the red arrow and placing a stop at the one standard deviation above this cluster would give us a profitable trade with minimal risk.
Using the cluster density table in the upper right informs the trader just how dense the cluster is. Higher density clusters will give a higher likelihood of a pivot forming at these levels and price being rejected and switching direction with a larger move.
█ FEATURES & SETTINGS
General Settings:
Number of clusters: The user can select from 3 to five clusters. A good rule of thumb is that if you are trading intraday, less is more (Think 3 rather than 5). For daily 4 to 5 clusters is good.
Cluster Method: To get around the outlier limitation of k means clustering, The median was added. This gives the user the ability to choose either k means or k median clustering. K means is the preferred method if the user things there are no large outliers, and if there appears to be large outliers or it is assumed there are then K medians is preferred.
Bars back To train on: This will be the amount of bars to include in the clustering. This number is important so that the user includes bars that are recent but not so far back that they are out of the scope of where price can be. For example the last 2 years we have been in a range on the sp500 so 505 days in this setting would be more relevant than say looking back 5 years ago because price would have to move far to get there.
Show SD Bands: Select this to show the 1 standard deviation bands around the support and resistance level or unselect this to just show the support and resistance level by itself.
Features:
Besides the support and resistance levels and standard deviation bands, this indicator gives a table in the upper right hand corner to show the density of each cluster (support and resistance level) and is color coded to the cluster line on the chart. Higher density clusters mean price has been there previously more than lower density clusters and could mean a higher likelihood of a reversal when price reaches these areas.
█ WORKS CITED
Victor Sim, "Using K-means Clustering to Create Support and Resistance", 2020, towardsdatascience.com
Chris Piech, "K means", stanford.edu
█ ACKNOLWEDGMENTS
@jdehorty- Thanks for the publish template. It made organizing my thoughts and work alot easier.
SignalProcessingClusteringKMeansLibrary "SignalProcessingClusteringKMeans"
K-Means Clustering Method.
nearest(point_x, point_y, centers_x, centers_y) finds the nearest center to a point and returns its distance and center index.
Parameters:
point_x : float, x coordinate of point.
point_y : float, y coordinate of point.
centers_x : float array, x coordinates of cluster centers.
centers_y : float array, y coordinates of cluster centers.
@ returns tuple of int, float.
bisection_search(samples, value) Bissection Search
Parameters:
samples : float array, weights to compare.
value : float array, weights to compare.
Returns: int.
label_points(points_x, points_y, centers_x, centers_y) labels each point index with cluster index and distance.
Parameters:
points_x : float array, x coordinates of points.
points_y : float array, y coordinates of points.
centers_x : float array, x coordinates of points.
centers_y : float array, y coordinates of points.
Returns: tuple with int array, float array.
kpp(points_x, points_y, n_clusters) K-Means++ Clustering adapted from Andy Allinger.
Parameters:
points_x : float array, x coordinates of the points.
points_y : float array, y coordinates of the points.
n_clusters : int, number of clusters.
Returns: tuple with 2 arrays, float array, int array.
Function K-Means ClusteringDescription:
A Function that returns cluster centers for given data (X,Y) vector points.
Inputs:
_X: Array containing x data points.¹
_Y: Array containing y data points.¹
_number_of_clusters: number of clusters.
Note:
¹: _X and _Y size must match.
Outputs:
_centers_x: Array containing x data points.
_centers_y: Array containing y data points.
Resources:
rosettacode.org
en.wikipedia.org