OPEN-SOURCE SCRIPT
Updated Machine Learning | Adaptive Trend Signals [Bitwardex]

⚙️🧠Machine Learning | Adaptive Trend Signals [Bitwardex]
🔷Overview
Machine Learning | Adaptive Trend Signals is a Pine Script™ v6 indicator designed to visualize market trends and generate signals through a combination of volatility clustering, Gaussian smoothing, and adaptive trend calculations. Built as an overlay indicator, it integrates advanced techniques inspired by machine learning concepts, such as K-Means clustering, to adapt to changing market conditions. The script is highly customizable, includes a backtesting module, and supports alert conditions, making it suitable for traders exploring trend-based strategies and developers studying volatility-driven indicator design.
🔷Functionality
The indicator performs the following core functions:
• Volatility Clustering: Uses K-Means clustering to categorize market volatility into high, medium, and low states, adjusting trend sensitivity accordingly.
• Trend Calculation: Computes adaptive trend lines (SmartTrend) based on volatility-adjusted standard deviation, smoothed RSI, and ADX filters.
• Signal Generation: Identifies potential buy and sell points through trend line crossovers and directional confirmation.
• Backtesting Module: Tracks trade outcomes based on the SmartTrend3 value, displaying win rate and total trades.
• Visualization: Plots trend lines with gradient colors and optional signal markers (bullish 🐮 and bearish 🐻).
• Alerts: Provides configurable alerts for trend shifts and volatility state changes.
🔷Technical Methodology
Volatility Clustering with K-Means
The indicator employs a K-Means clustering algorithm to classify market volatility, measured via the Average True Range (ATR), into three distinct clusters:
• Data Collection: Gathers ATR values over a user-defined training period (default: 100 bars).
• Centroid Initialization: Sets initial centroids at the highest, lowest, and midpoint ATR values within the training period.
• Iterative Clustering: Assigns ATR data points to the nearest centroid, recalculates centroid means, and repeats until convergence.
• Dynamic Adjustment: Assigns a volatility state (high, medium, or low) based on the closest centroid, adjusting the trend factor (e.g., tighter for high volatility, wider for low volatility).
🔷Gaussian Smoothing
To enhance signal clarity and reduce noise, the indicator applies Gaussian kernel smoothing to:
• RSI: Smooths the Relative Strength Index (calculated from OHLC4) to filter short-term fluctuations.
• SmartTrend: Smooths the primary trend line for a more stable output.
🔷SmartTrend Calculation
The pineSmartTrend function is the core of the indicator, producing three trend lines:
• SmartTrend: The primary trend line, calculated using a volatility-adjusted standard deviation, smoothed RSI, and ADX conditions.
• SmartTrend2: A secondary trend line with a wider factor (base factor * 1.382) for signal confirmation.
* SmartTrend3: The average of SmartTrend and SmartTrend2, used for plotting and backtesting.
Key components of the calculation include:
• Dynamic Standard Deviation: Scales based on ATR relative to its 50-period smoothed average, with multipliers (1.0 to 1.4) applied according to volatility thresholds.
• RSI and ADX Filters: Requires RSI > 50 for bullish trends or < 50 for bearish trends, alongside ADX > 15 and rising to confirm trend strength.
* Volatility-Adjusted Bands: Constructs upper and lower bands around price action, adjusted by the volatility cluster’s dynamic factor.
🔷Signal Generation
The generate_signals function generates signals as follows:
• Buy Signal: Triggered when SmartTrend crosses above SmartTrend2 and the price is above SmartTrend, with directional confirmation.
• Sell Signal: Triggered when SmartTrend crosses below SmartTrend2 and the price is below SmartTrend, with directional confirmation.
* Directional Logic: Tracks trend direction to filter out conflicting signals, ensuring alignment with the broader market context.
🔷Backtesting
The get_backtest function evaluates signal outcomes using the SmartTrend3 value (rather than closing prices) to align with the trend-based methodology.
It tracks:
• Total Trades: Counts completed long and short trades.
• Win Rate: Calculates the percentage of trades where SmartTrend3 moves favorably (higher for longs, lower for shorts).
* Position Management: Closes opposite positions before opening new ones, simulating a single-position trading system.
🔷Visualization and Alerts
• Trend Lines: SmartTrend3 is plotted with gradient colors reflecting trend direction and volatility cluster, accompanied by a secondary line for visual clarity.
• Signal Markers: Optional buy/sell signals are plotted as small circles with customizable colors.
• Alerts: Supports alerts for:
• Bullish and bearish trend shifts (confirmed on bar close).
* Transitions to high, medium, or low volatility states.
🔷Input Parameters
• ATR Length (default: 14): Period for ATR calculation, used in volatility clustering.
• Period (default: 21): Common period for RSI, ADX, and standard deviation calculations.
• Base SmartTrend Factor (default: 2.0): Base multiplier for volatility-adjusted bands.
• SmartTrend Smoothing Length (default: 10): Length for Gaussian smoothing of the trend line.
• Show Buy/Sell Signals? (default: true): Enables/disables signal markers.
• Bullish/Bearish Color: Customizable colors for trend lines and signals.
🔷Usage Instructions
• Apply to Chart: Add the indicator to any TradingView chart.
• Configure Inputs: Adjust parameters to align with your trading style or market conditions (e.g., shorter ATR length for faster markets).
• Interpret Output:
• Trend Lines: Use SmartTrend3’s direction and color to gauge market bias.
• Signals: Monitor bullish (🐮) and bearish (🐻) markers for potential entry/exit points.
• Backtest Table: Review win rate and total trades to understand the indicator’s behavior in historical data.
• Set Alerts: Configure alerts for trend shifts or volatility changes to support manual or automated trading workflows.
• Combine with Analysis: Use the indicator alongside other tools or market context, as it is designed to complement, not replace, comprehensive analysis.
🔷Technical Notes
• Data Requirements: Requires at least 100 bars for accurate volatility clustering. Ensure sufficient historical data is loaded.
• Market Suitability: The indicator is designed for trend detection and may perform differently in ranging or volatile markets due to its reliance on RSI and ADX filters.
• Backtesting Scope: The backtest module uses SmartTrend3 values, which may differ from price-based outcomes. Results are for informational purposes only.
• Computational Intensity: The K-Means clustering and Gaussian smoothing may increase processing time on lower timeframes or with large datasets.
🔷For Developers
The script is modular, well-commented, encouraging reuse and modification with proper attribution.
Key functions include:
• gaussianSmooth: Applies Gaussian kernel smoothing to any data series.
• pineSmartTrend: Computes adaptive trend lines with volatility and momentum filters.
• getDynamicFactor: Adjusts trend sensitivity based on volatility clusters.
• get_backtest: Evaluates signal performance using SmartTrend3.
Developers can extend these functions for custom indicators or strategies, leveraging the volatility clustering and smoothing methodologies. The K-Means implementation is particularly useful for adaptive volatility analysis.
🔷Limitations
• The indicator is not predictive and should be used as part of a broader trading strategy.
• Performance varies by market, timeframe, and parameter settings, requiring user experimentation.
• Backtest results are based on historical data and internal logic, not real-world trading conditions.
• Volatility clustering assumes sufficient historical data; incomplete data may affect accuracy.
🔷Acknowledgments
Developed by Bitwardex, inspired by machine learning concepts and adaptive trading methodologies. Community feedback is welcome via TradingView’s platform.
🔷 Risk Disclaimer
Trading involves significant risks, and most traders may incur losses. Bitwardex AI Algo is provided for informational and educational purposes only and does not constitute financial advice or a recommendation to buy or sell any financial instrument. The signals, metrics, and features are tools for analysis and do not guarantee profits or specific outcomes. Past performance is not indicative of future results. Always conduct your own due diligence and consult a financial advisor before making trading decisions.
🔷Overview
Machine Learning | Adaptive Trend Signals is a Pine Script™ v6 indicator designed to visualize market trends and generate signals through a combination of volatility clustering, Gaussian smoothing, and adaptive trend calculations. Built as an overlay indicator, it integrates advanced techniques inspired by machine learning concepts, such as K-Means clustering, to adapt to changing market conditions. The script is highly customizable, includes a backtesting module, and supports alert conditions, making it suitable for traders exploring trend-based strategies and developers studying volatility-driven indicator design.
🔷Functionality
The indicator performs the following core functions:
• Volatility Clustering: Uses K-Means clustering to categorize market volatility into high, medium, and low states, adjusting trend sensitivity accordingly.
• Trend Calculation: Computes adaptive trend lines (SmartTrend) based on volatility-adjusted standard deviation, smoothed RSI, and ADX filters.
• Signal Generation: Identifies potential buy and sell points through trend line crossovers and directional confirmation.
• Backtesting Module: Tracks trade outcomes based on the SmartTrend3 value, displaying win rate and total trades.
• Visualization: Plots trend lines with gradient colors and optional signal markers (bullish 🐮 and bearish 🐻).
• Alerts: Provides configurable alerts for trend shifts and volatility state changes.
🔷Technical Methodology
Volatility Clustering with K-Means
The indicator employs a K-Means clustering algorithm to classify market volatility, measured via the Average True Range (ATR), into three distinct clusters:
• Data Collection: Gathers ATR values over a user-defined training period (default: 100 bars).
• Centroid Initialization: Sets initial centroids at the highest, lowest, and midpoint ATR values within the training period.
• Iterative Clustering: Assigns ATR data points to the nearest centroid, recalculates centroid means, and repeats until convergence.
• Dynamic Adjustment: Assigns a volatility state (high, medium, or low) based on the closest centroid, adjusting the trend factor (e.g., tighter for high volatility, wider for low volatility).
This approach allows the indicator to adapt its sensitivity to varying market conditions, providing a data-driven foundation for trend calculations.
🔷Gaussian Smoothing
To enhance signal clarity and reduce noise, the indicator applies Gaussian kernel smoothing to:
• RSI: Smooths the Relative Strength Index (calculated from OHLC4) to filter short-term fluctuations.
• SmartTrend: Smooths the primary trend line for a more stable output.
The Gaussian kernel uses a sigma value derived from the user-defined smoothing length, ensuring mathematically consistent noise reduction.
🔷SmartTrend Calculation
The pineSmartTrend function is the core of the indicator, producing three trend lines:
• SmartTrend: The primary trend line, calculated using a volatility-adjusted standard deviation, smoothed RSI, and ADX conditions.
• SmartTrend2: A secondary trend line with a wider factor (base factor * 1.382) for signal confirmation.
* SmartTrend3: The average of SmartTrend and SmartTrend2, used for plotting and backtesting.
Key components of the calculation include:
• Dynamic Standard Deviation: Scales based on ATR relative to its 50-period smoothed average, with multipliers (1.0 to 1.4) applied according to volatility thresholds.
• RSI and ADX Filters: Requires RSI > 50 for bullish trends or < 50 for bearish trends, alongside ADX > 15 and rising to confirm trend strength.
* Volatility-Adjusted Bands: Constructs upper and lower bands around price action, adjusted by the volatility cluster’s dynamic factor.
🔷Signal Generation
The generate_signals function generates signals as follows:
• Buy Signal: Triggered when SmartTrend crosses above SmartTrend2 and the price is above SmartTrend, with directional confirmation.
• Sell Signal: Triggered when SmartTrend crosses below SmartTrend2 and the price is below SmartTrend, with directional confirmation.
* Directional Logic: Tracks trend direction to filter out conflicting signals, ensuring alignment with the broader market context.
Signals are visualized as small circles with bullish (🐮) or bearish (🐻) emojis, with an option to toggle visibility.
🔷Backtesting
The get_backtest function evaluates signal outcomes using the SmartTrend3 value (rather than closing prices) to align with the trend-based methodology.
It tracks:
• Total Trades: Counts completed long and short trades.
• Win Rate: Calculates the percentage of trades where SmartTrend3 moves favorably (higher for longs, lower for shorts).
* Position Management: Closes opposite positions before opening new ones, simulating a single-position trading system.
Results are displayed in a table at the top-right of the chart, showing win rate and total trades. Note that backtest results reflect the indicator’s internal logic and should not be interpreted as predictive of real-world performance.
🔷Visualization and Alerts
• Trend Lines: SmartTrend3 is plotted with gradient colors reflecting trend direction and volatility cluster, accompanied by a secondary line for visual clarity.
• Signal Markers: Optional buy/sell signals are plotted as small circles with customizable colors.
• Alerts: Supports alerts for:
• Bullish and bearish trend shifts (confirmed on bar close).
* Transitions to high, medium, or low volatility states.
🔷Input Parameters
• ATR Length (default: 14): Period for ATR calculation, used in volatility clustering.
• Period (default: 21): Common period for RSI, ADX, and standard deviation calculations.
• Base SmartTrend Factor (default: 2.0): Base multiplier for volatility-adjusted bands.
• SmartTrend Smoothing Length (default: 10): Length for Gaussian smoothing of the trend line.
• Show Buy/Sell Signals? (default: true): Enables/disables signal markers.
• Bullish/Bearish Color: Customizable colors for trend lines and signals.
🔷Usage Instructions
• Apply to Chart: Add the indicator to any TradingView chart.
• Configure Inputs: Adjust parameters to align with your trading style or market conditions (e.g., shorter ATR length for faster markets).
• Interpret Output:
• Trend Lines: Use SmartTrend3’s direction and color to gauge market bias.
• Signals: Monitor bullish (🐮) and bearish (🐻) markers for potential entry/exit points.
• Backtest Table: Review win rate and total trades to understand the indicator’s behavior in historical data.
• Set Alerts: Configure alerts for trend shifts or volatility changes to support manual or automated trading workflows.
• Combine with Analysis: Use the indicator alongside other tools or market context, as it is designed to complement, not replace, comprehensive analysis.
🔷Technical Notes
• Data Requirements: Requires at least 100 bars for accurate volatility clustering. Ensure sufficient historical data is loaded.
• Market Suitability: The indicator is designed for trend detection and may perform differently in ranging or volatile markets due to its reliance on RSI and ADX filters.
• Backtesting Scope: The backtest module uses SmartTrend3 values, which may differ from price-based outcomes. Results are for informational purposes only.
• Computational Intensity: The K-Means clustering and Gaussian smoothing may increase processing time on lower timeframes or with large datasets.
🔷For Developers
The script is modular, well-commented, encouraging reuse and modification with proper attribution.
Key functions include:
• gaussianSmooth: Applies Gaussian kernel smoothing to any data series.
• pineSmartTrend: Computes adaptive trend lines with volatility and momentum filters.
• getDynamicFactor: Adjusts trend sensitivity based on volatility clusters.
• get_backtest: Evaluates signal performance using SmartTrend3.
Developers can extend these functions for custom indicators or strategies, leveraging the volatility clustering and smoothing methodologies. The K-Means implementation is particularly useful for adaptive volatility analysis.
🔷Limitations
• The indicator is not predictive and should be used as part of a broader trading strategy.
• Performance varies by market, timeframe, and parameter settings, requiring user experimentation.
• Backtest results are based on historical data and internal logic, not real-world trading conditions.
• Volatility clustering assumes sufficient historical data; incomplete data may affect accuracy.
🔷Acknowledgments
Developed by Bitwardex, inspired by machine learning concepts and adaptive trading methodologies. Community feedback is welcome via TradingView’s platform.
🔷 Risk Disclaimer
Trading involves significant risks, and most traders may incur losses. Bitwardex AI Algo is provided for informational and educational purposes only and does not constitute financial advice or a recommendation to buy or sell any financial instrument. The signals, metrics, and features are tools for analysis and do not guarantee profits or specific outcomes. Past performance is not indicative of future results. Always conduct your own due diligence and consult a financial advisor before making trading decisions.
Release Notes
Visual minor fixesOpen-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
For quick access on a chart, add this script to your favorites — learn more here.
🔥Get more here
ENG - t.me/bitwardex_ai
RU - t.me/bitwardex
Support - t.me/bitwardex_support
ENG - t.me/bitwardex_ai
RU - t.me/bitwardex
Support - t.me/bitwardex_support
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
For quick access on a chart, add this script to your favorites — learn more here.
🔥Get more here
ENG - t.me/bitwardex_ai
RU - t.me/bitwardex
Support - t.me/bitwardex_support
ENG - t.me/bitwardex_ai
RU - t.me/bitwardex
Support - t.me/bitwardex_support
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.