Bitwardex AI Algo 2.0

══════════════════════════════════════════════
📋 OVERVIEW
This comprehensive algorithmic strategy combines adaptive trend detection using Gaussian smoothing, statistical cluster analysis for support/resistance identification, and intelligent risk management into a unified decision-support system.
Unlike simple indicator combinations, this strategy implements an integrated analytical architecture where each component directly influences the others — the Heikin Ashi transformation feeds into Gaussian smoothing with adaptive sigma parameters, which adapts to volatility metrics (ATR), while the clustering engine uses this preprocessed data to identify statistically significant price zones that the trend filter validates before execution. This creates a synergistic system where removing any component fundamentally changes the behavior of the others.
══════════════════════════════════════════════
🎯 WHAT MAKES THIS UNIQUE
▸ Integrated Analytical Pipeline
Most strategies use independent indicators that don't interact. This system implements a complete analytical chain where:
- Heikin Ashi preprocessing reduces noise before Gaussian smoothing
- Gaussian smoothing adapts its sigma parameter based on pseudo-K-means trend classification
- Statistical clustering uses the smoothed data to identify statistically significant price zones
- Trend filter validates cluster-based signals using the same Gaussian-smoothed trend line
- Removing any component fundamentally changes the behavior of the others
▸ Statistical Cluster-Based Support/Resistance
Unlike traditional pivot-based or Fibonacci levels, this system uses statistical clustering methods to identify support/resistance zones. The algorithm dynamically adjusts boundaries based on:
- Current volatility (ATR ratio)
- Cluster strength (density of price points in each cluster)
- Price dispersion metrics
This creates adaptive levels that respond to market conditions rather than fixed historical points.
▸ Self-Analyzing Performance
Built-in real-time performance tracking monitors winrates for each TP level across three time windows (last 10, last 25, all trades), automatically tests 40 parameter variations in parallel, and provides optimization recommendations with overfitting protection filters.
▸ Human-Readable Market Intelligence System
The system transforms complex multi-indicator analysis (RSI, MACD, ADX, Bollinger Bands, ATR, volume) into clear text summaries that evaluate inter-indicator relationships, identify conflicts and consistency, and provide actionable market insights.
══════════════════════════════════════════════
🧠 HOW IT WORKS — METHODOLOGY
▸ Price Preprocessing with Heikin Ashi
The system uses Heikin Ashi transformation to reduce market noise and highlight significant trend patterns. Critical design decision: only confirmed values from previous bars (ha_close_prev, ha_open_prev, ha_high_prev, ha_low_prev) are used, which completely eliminates signal repainting. This means that signals you see in backtest are identical to those you would receive in real-time — no changes after appearance.
▸ Adaptive Trend Detection using Gaussian Smoothing
Instead of standard moving averages, the system uses Gaussian smoothing with adaptive sigma parameters. The Gaussian kernel is calculated as: weight = exp(-i²/(2σ²)), where sigma = length / (6.0 * trendStrength).
The trendStrength parameter dynamically adjusts based on market conditions detected via pseudo-K-means clustering:
- In trending conditions (cluster 1 or -1): sigma is reduced (0.5x), making the filter more responsive
- In sideways conditions (cluster 0): standard sigma (1.0x) is used for balanced filtering
The trend line itself is calculated using a pseudo-K-means approach that classifies market state into three clusters:
- Feature vector: [normalized_price_change, normalized_CCI, normalized_price_deviation]
- Normalization: price_change uses sigmoid(priceChange/ATR), CCI is clamped to [-1,1] then scaled to [0,1], price_deviation uses sigmoid
- Centroids: uptrend=0.75, downtrend=0.25, sideways=0.5
- Classification: assigns to nearest centroid via Euclidean distance
- Adaptive response: in trending clusters, trend line is pulled closer to price (0.5x distance multiplier) and smoothing is reduced
▸ Intelligent Sensitivity Adaptation
The key innovation is dynamic adaptation of processing parameters depending on current market state. The system uses pseudo-K-means clustering to classify market conditions:
- Cluster 1 (Uptrend): Centroid at 0.75, based on normalized price change + normalized CCI + normalized price deviation
- Cluster -1 (Downtrend): Centroid at 0.25
- Cluster 0 (Sideways): Centroid at 0.5
Based on cluster assignment, the system automatically adjusts:
- In trending conditions (cluster 1 or -1): Sensitivity multiplier reduced to 0.5x, trendStrength reduced to 0.5, making the system more responsive
- In volatile conditions: Volatility factor (ATR / SMA(ATR, 14)) increases noise filtering
- In sideways movements: Standard parameters apply balanced approach
▸ Signal Generation through Statistical Cluster Analysis
The system uses statistical clustering methods to identify significant price zones that represent potential support and resistance levels. The clustering algorithm analyzes recent price data to group prices into statistically significant clusters, identifying areas where price has historically consolidated.
The identified cluster boundaries are dynamically adjusted based on multiple market factors:
- Current market volatility (measured through ATR ratios)
- Statistical strength of cluster formations
- Price dispersion metrics
- User-defined sensitivity parameters
This creates adaptive support/resistance levels that respond to changing market conditions rather than relying on fixed historical points. The boundaries are recalculated on each bar to reflect current market structure.
Signals are generated when Heikin Ashi close crosses these statistically justified boundaries:
- Long signals occur when price crosses below the lower cluster boundary, indicating a move toward a potential support zone
- Short signals occur when price crosses above the upper cluster boundary, indicating a move toward a potential resistance zone
▸ Validation through Trend Filter
All signals undergo validation through a trend filter using the Gaussian-smoothed trend line. The filter confirms signal direction matches current trend:
- Long signals require: trendSide == 1 (trend >= trend[1] and ha_close_prev > trend)
- Short signals require: trendSide == -1 (trend <= trend[1] and ha_close_prev < trend)
Optional multi-timeframe confirmation is available, where the system automatically selects a higher timeframe (e.g., 1min → 5min, 5min → 15min) for additional signal validation, ensuring consistency with broader market context.
══════════════════════════════════════════════
🔬 WHY THIS COMBINATION IS ORIGINAL
This strategy is not a simple mashup of indicators. The integration creates novel behavior:
1. Feedback Loop Between Components
- Statistical clustering identifies price zones, but these zones are calculated using Gaussian-smoothed Heikin Ashi data
- The Gaussian smoothing adapts its responsiveness based on pseudo-K-means trend classification
- The trend filter validates cluster-based signals using the same adaptive trend line
- This creates a feedback loop where each component informs and adjusts the others
2. Statistical Justification for Levels
Unlike fixed pivot points or Fibonacci retracements, support/resistance levels are:
- Dynamically recalculated using statistical clustering methods with minimum point requirements for validity
- Adjusted by volatility factor (ATR ratio) and cluster strength (density)
- Statistically validated through cluster formation strength
- This adapts to changing market regimes rather than relying on historical levels
3. Adaptive Smoothing Based on Market Regime
The Gaussian smoothing doesn't use fixed parameters. Instead:
- Sigma adapts based on market regime classification (trending vs sideways)
- In trending markets, reduced smoothing (0.5x sigma) allows faster response
- In sideways markets, standard smoothing filters noise effectively
- This prevents the common problem of lag in trends and noise in ranges
4. Multi-Layer Signal Validation
Signals must pass multiple validation layers:
- Cluster boundary crossing (statistical significance)
- Trend direction confirmation (adaptive trend filter)
- Optional multi-timeframe validation
- This reduces false signals compared to single-indicator approaches
══════════════════════════════════════════════
📊 UNIQUE FEATURES
▸ 🤖 AI Market Summary — Intelligent Market Analysis
The system transforms complex multi-indicator analysis into understandable text summaries written in the style of professional market reports. The system collects data from multiple sources:
Data Collection:
- Trend metrics: price position relative to EMA, trend direction, trend strength (ADX)
- Momentum indicators: RSI levels, MACD signals, momentum histogram
- Volatility: ATR percentage value, Bollinger Bands width, squeeze detection
- Volume analysis: current volume to average ratio, volume spike detection
- Price action: candlestick pattern analysis, proximity to key levels
Processing and Analysis:
Each category is analyzed through specialized functions that not only calculate numerical scores but also evaluate inter-indicator relationships. The system identifies conflicts and consistency between different signals, creating a holistic picture of market conditions.
Summary Generation:
The result is a coherent text report that includes:
- Current market state (trend/flat, volatility, phase)
- Key support and resistance levels
- Possible development scenarios
- Identified risk factors and warnings
- Recommendations for interpreting current situation
The summary updates with configurable frequency (default every 10 bars) to balance information freshness and readability.
▸ 📈 Multi-Level Winrate Tracking
The system provides detailed performance statistics for each take-profit level across three time windows, allowing tracking of both short-term changes and long-term trends.
Time Windows:
- Last 10 trades: Shows immediate changes in performance, helps identify current shifts in strategy effectiveness
- Last 25 trades: Reflects medium-term trends, balances between relevance and statistical significance
- All trades: Provides long-term baseline for comparison
Visualization:
Each winrate matrix cell has color coding with gradient from dark red (0%) to bright green (100%), allowing instant assessment of each TP level's effectiveness.
Practical Applications:
- Identifying most reliable TP levels in current market conditions
- Detecting strategy degradation (when recent performance is significantly lower than historical)
- Validating parameter changes — comparing performance before and after adjustments
- Comparing effectiveness across different timeframes and instruments
- Making decisions about volume distribution between TP levels
▸ ⚙️ AI Strategy Optimizer — Automatic Optimization
The system automatically tests 40 sensitivity parameter variations in real-time, providing optimization recommendations without the need for manual backtesting.
Mechanism:
On each confirmed bar, the system runs parallel sensitivity simulations using the backtest library. Each simulation:
1. Generates signals using calculateLevelsAndConditions() with different sensitivity multipliers
2. Fully reproduces the strategy's trading logic, including all risk management mechanisms (TP/SL, trailing stop, breakeven)
3. Calculates metrics: comprehensive score, winrate, profit factor, net profit
4. Applies configurable filters (minimum trades, winrate, profit, profit factor)
5. Selects best parameters based on four criteria: Optimal (balanced score), Best Profit, Best Winrate, Best Profit Factor
Optimization Metrics:
The system provides four different criteria for selecting optimal parameters:
- Optimal: Balanced comprehensive score considering profit, winrate, and profit factor simultaneously. Recommended for most cases.
- Best Profit: Maximizes net profit in absolute values. Suitable for aggressive traders willing to accept lower winrate for greater profit.
- Best Winrate: Focuses on maximum percentage of winning trades. Ideal for conservative traders preferring stability.
- Best Profit Factor: Optimizes profit to loss ratio. Shows how efficiently the strategy generates profit relative to risk.
Protection Filters:
To prevent overfitting and ensure statistical significance, configurable filters are available:
- Minimum trades: Requires minimum number of historical trades for result validation (recommended ≥30)
- Minimum winrate: Excludes options with unacceptably low win percentage
- Minimum profit: Filters options that don't reach target profitability level
- Minimum profit factor: Ensures profit/loss ratio meets requirements
Overfitting Protection:
- Multiple metrics prevent optimization on a single statistic
- Minimum trade requirements ensure statistical validity
- Comparing different time windows helps identify degradation of "optimal" parameters
══════════════════════════════════════════════
🎯 RISK MANAGEMENT
▸ Take-Profit: Multi-Level Exit System
The strategy supports up to 4 independent take-profit levels, each configurable individually.
Calculation Modes:
- Percentage mode: Fixed percentage from entry price, simple and clear
- ATR mode: Distance calculated based on Average True Range, automatically adapts to current instrument volatility
Partial Exits:
Each TP level can close a configurable percentage of position, allowing flexible profit distribution strategy:
- Default: 25% at each of first three TPs, 100% at fourth
- Fully configurable volume distribution between levels
- Ability to disable any level while keeping others
Multi-Level System Advantages:
- Capturing profit at early stages of movement
- Preserving part of position for potentially large moves
- Reducing psychological pressure through partial profit locking
▸ Stop-Loss: Adaptive Protection
The system offers several stop-loss calculation methods for optimal capital protection.
Calculation Modes:
- ATR mode: Stop is placed at distance multiple of current ATR. Automatically widens in volatile conditions and narrows in calm markets, providing adequate protection without excessive risk.
- Percentage mode: Fixed percentage from entry price. Simple and predictable method, suitable for stable instruments.
Features:
- Fully configurable multiplier/percentage
- Ability to disable stop-loss (not recommended)
- Automatic adjustment when breakeven or trailing stop activates
▸ Trailing Stop: Profit Protection
Advanced trailing stop system that automatically moves stop-loss in favorable direction, protecting profit while maintaining potential for further growth.
Activation Modes:
- Immediate activation: Trailing starts immediately after position entry
- Threshold activation: Trailing activates only after reaching certain profit percentage, allowing position to "breathe" at early stages
Calculation Modes:
- Percentage mode: Stop held at fixed percentage from maximum achieved price
- ATR mode: Trail distance calculated based on ATR, adapting to volatility
Key Features:
- Stop moves only in favorable direction, never backward
- Automatic update when new extremes are reached
- Full integration with alert system for change notifications
▸ Breakeven: Automatic Entry Protection
The system automatically moves stop-loss to entry level after reaching certain profit threshold, guaranteeing no loss on further movement.
Activation Modes:
- Percentage mode: Activation when reaching certain profit percentage
- ATR mode: Activation when reaching distance multiple of ATR
- TP-based mode: Activation when reaching one of take-profit levels (TP1, TP2, TP3, or TP4)
Advantages:
- Psychological comfort — position protected from loss
- Ability to hold position for large moves without risk
- Automatic management without need for manual intervention
▸ Position Size Management
Flexible position size management system with multiple modes and additional optimization mechanisms.
Size Modes:
- Fixed amount: Position opened for fixed amount in dollars (or other currency)
- Percentage of deposit: Position size calculated as percentage of current deposit, automatically adapts to balance changes
Consolidation Risk Control:
Unique function that automatically increases position size when detecting periods of low volatility (consolidation). Logic is based on the fact that during low volatility periods, stop-losses are placed closer to price, meaning lower absolute risk per position. Size increase compensates for this, maintaining constant risk level.
Martingale (Optional):
The system supports optional martingale mechanism with configurable multiplier:
- Activation only after losing trade
- Configurable size increase multiplier (default 1.5x)
- Protection against excessive increase through maximum position size limit
- Automatic reset to base size after profitable trade
Leverage:
Full support for trading with leverage:
- Configurable leverage value (default 10x)
- Automatic position size calculation considering leverage
- Correct profit/loss calculation including commissions
▸ Commissions
Full support for commission accounting:
- Configurable commission percentage (default 0.04%)
- Automatic commission accounting in profit/loss calculations
- Commission impact considered in all backtests and optimizations
══════════════════════════════════════════════
📐 VISUAL INTERFACE
Information Tables:
▸ Control Panel
Comprehensive information panel displaying all key metrics:
Header and Status:
- Strategy status indicator (LONG/SHORT/Waiting)
- First trade date for history tracking
- Current instrument and timeframe information
Winrate Matrix:
- Three-dimensional matrix: 4 TP levels × 3 time windows
- Color coding with gradient for instant assessment
- Percentage values with integer precision
- Allows quick identification of most effective levels
AI Strategy Optimizer:
- Four recommendation rows with different optimization criteria
- Display of recommended sensitivity for each criterion
- Corresponding profit and profit factor metrics
- Color coding for quick assessment of recommendation quality
- Information about active optimization filters
Display Settings:
- Table position selection (4 screen corners)
- Configurable text size (tiny, small, normal)
- Dark color scheme for comfortable viewing
▸ AI Market Summary Table
Separate table with textual market analysis in professional report style:
Content:
- Complete textual summary of current market state
- Analysis of trend, momentum, volatility, and volume
- Identified key levels and scenarios
- Risk factors and warnings
Settings:
- Independent positioning from main panel
- Configurable text size
- Update frequency (default every 10 bars)
- Automatic caching for performance optimization
Alert System:
▸ Internal Alerts
Human-readable alerts for manual trading or notifications:
Entry Alert:
- Instrument ticker
- Position direction (LONG/SHORT)
- Entry price
- All active TP levels with exit volumes
- Stop-loss level
- Leverage
- Order size
TP Achievement Alert:
- Ticker and position direction
- Number of achieved TP level
- Entry price for reference
SL Trigger Alert:
- Ticker and position direction
- Notification of position closure by stop-loss
Trailing Stop Alert:
- Notification of trailing stop trigger
- Position direction information
Breakeven Alert:
- Notification of breakeven activation
- New stop-loss level
Dynamic Exit Alert:
- Exit reason (e.g., "RSI overbought exit")
- Closed position direction
▸ Custom Alerts
Fully configurable text messages for each event type:
- Custom entry alert
- Custom TP achievement alert
- Custom SL trigger alert
- Useful for integration with external systems or message personalization
▸ JSON Format Alerts
JSON format alerts for integration with external trading systems
Features:
- Complete information about all TP levels with exit volumes
- Automatic generation of correct JSON structure
- Support for all event types (entry, exit, SL change)
- Structured format includes: key_hash, signal_hash, action, side, symbol, amount, leverage, stopLoss, take_profits array
══════════════════════════════════════════════
⚠️ IMPORTANT DISCLAIMERS
DOES NOT:
- Predict future prices — identifies probabilistic setups
- Guarantee profits — all trading involves risk
- Work equally everywhere — performance varies by instrument/TF
- Eliminate need for risk management — use appropriate sizing
Recommendations:
- Paper trade first
- Start with small positions
- Monitor winrate tables continuously
- Re-optimize if recent performance degrades
- Understand the logic before live trading
This strategy is intended for educational and informational purposes. Conduct your own research before trading with real capital. Past performance does not guarantee future results.
Script su invito
Solo gli utenti approvati dall'autore possono accedere a questo script. È necessario richiedere e ottenere l'autorizzazione per utilizzarlo. Tale autorizzazione viene solitamente concessa dopo il pagamento. Per ulteriori dettagli, seguire le istruzioni dell'autore riportate di seguito o contattare direttamente bitwardex.
TradingView NON consiglia di acquistare o utilizzare uno script a meno che non si abbia piena fiducia nel suo autore e se ne comprenda il funzionamento. È inoltre possibile trovare alternative gratuite e open source nei nostri script della community.
Istruzioni dell'autore
🤖Support - t.me/bitwardex_support
Declinazione di responsabilità
Script su invito
Solo gli utenti approvati dall'autore possono accedere a questo script. È necessario richiedere e ottenere l'autorizzazione per utilizzarlo. Tale autorizzazione viene solitamente concessa dopo il pagamento. Per ulteriori dettagli, seguire le istruzioni dell'autore riportate di seguito o contattare direttamente bitwardex.
TradingView NON consiglia di acquistare o utilizzare uno script a meno che non si abbia piena fiducia nel suo autore e se ne comprenda il funzionamento. È inoltre possibile trovare alternative gratuite e open source nei nostri script della community.
Istruzioni dell'autore
🤖Support - t.me/bitwardex_support