Infinity Algo Backtest

Stop-loss is now working in backtest
Alert function message
Fixed reverse trading
Changed Colors
New ribbon and channel bands
This update brings the backtesting strategy script in line with the main Infinity Algo V3.0 indicator, incorporating the AI optimization engine and refining the strategy logic and settings.
๐ Major Updates & New Features:
Pine Script V6 Update: The strategy script has been migrated to Pine Script version 6, enabling the use of newer Pine features and aligning it with the indicator script.
๐ง AI Optimization Engine Integration:
Adaptive Signals: Introduced the "AI" option in the ๐ Show Signals Type input. When selected and ๐ง Enable AI Optimization is checked, the strategy uses signals generated by the AI engine, which dynamically adapts its parameters based on simulated performance and market volatility.
AI Engine Core: Includes the same core AI logic as the indicator: simulation of configurations, performance evaluation based on selectable metrics (๐ AI Performance Metric), K-Means clustering based on volatility, and dynamic selection of the best configuration for the current market regime.
AI Inputs: Added the ๐ง AI Clustering settings group, allowing configuration of the AI engine (Enable, Update Frequency, Range, Simulation TP/SL%, Performance Metric). Note: The AI Dashboard visualization is not included in the strategy script.
"Opposite Signal" Exit Type: Added a new option to the ๐ Exit Type input (Opposite Signal) which closes the current position when a signal in the opposite direction occurs.
๐งน Removed Features:
Visualizations Removed:
Keltner Channel Bands
EMA Ribbon
Peak Profit Line. These were primarily visual aids not essential for backtesting logic.
โจ Refinements & Improvements:
Signal Type Input: Added the ๐ Show Signals Type dropdown (Normal + Smart, Normal Only, etc., including AI), providing explicit control over which signal logic drives the strategy entries, similar to the indicator.
Signal Toggle Logic: Integrated ๐ Toggle Same Signal Consecutively and ๐ Next Signal Must Be Opposite Signal inputs to control signal generation behavior consistently with the indicator.
Exit Logic Overhaul:
Refactored the strategy.exit and strategy.close logic to handle the different ๐ Exit Type options ('Percentage', 'Signals', 'Opposite Signal') more clearly.
Improved handling of partial exits for 'Signals'and 'Percentage' modes.
Ensured Stop Loss is applied correctly across different exit types.
State Management: Improved internal tracking of position state to work reliably with strategy.* functions and the different exit modes.
Settings Organization: Grouped related inputs more logically (e.g., ๐ Strategy Settings, โ๏ธ Signal Settings, ๐ง AI Clustering, ๐ฐ Take Profit Settings, ๐ช Exit Settings, ๐ Precision Settings, Alerts), mirroring the indicator's structure.
Alerts:
Code Structure: General refactoring for better readability, consistency with the V3 indicator, and integration of the AI components. Removed redundant code related to visual elements.
Note: As with the indicator, bugs may appear due to the significant changes. Thorough testing across different settings and market conditions is recommended.
The backtesting strategy has been updated in lockstep with the main indicator to ensure its parameters and logic are aligned. This allows for more accurate and reliable backtesting of the new features.
**Static Optimization Mode** ๐
- "Train once, apply forever" optimization
- Analyzes first 4900 bars to find optimal settings
- Locks configuration for consistent forward testing
- Perfect for backtesting and strategy validation
- Prevents parameter drift and overfitting
**AI Sniper Mode** โจ
- New signal type combining AI with advanced algorithms
- Independent optimization tracking from standard AI mode
- Designed for high-precision entries in volatile markets
**Advanced Performance Metrics** ๐
- Sharpe Ratio & Sortino Ratio
- Calmar Ratio & Martin Ratio
- System Quality Number (SQN)
- Robust ML Score with Lorentzian distance
- Sortino + Calmar Composite scoring
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ **CHANGED**
**AI Optimization Modes** ๐ง
- New choice: Walk-Forward vs Static optimization
- Walk-Forward: Continuous adaptation every N bars
- Static: One-time optimization with locked parameters
- Static mode optimizes at bar 4900 for best results
**AI Update Frequency** โก
- Static mode eliminates update lag completely
- Massive performance improvement (up to 3x faster)
- Prevents timeouts on all timeframes
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ **IMPROVED**
**HL Sniper Mode** ๐ฏ
- Enhanced calculations
- Better parameter optimization
- Improved signal accuracy
**Performance & Memory** ๐
- 5000 bar lookback capability
- Advanced caching system
- Intelligent configuration pruning
- 40% reduction in computational overhead
- Static mode eliminates real-time recalculation
**Mathematical Precision** ๐ฌ
- Lorentzian distance for outlier resistance
- Enhanced normalization algorithms
- More stable optimization convergence
- Better handling of edge cases
Improvements:
- Faster loading - AI disabled by default
Enable AI Optimization manually in settings when needed
๐ฏ New Backtest Features
- Enhanced Alert Messages: Alerts now optionally display TP/SL percentages alongside price levels
- Advanced Performance Metrics: Added compound growth calculations for better long-term strategy evaluation
- Time-Based Performance Analysis: Improved tracking of trade timing and duration for more accurate annual returns
- Dynamic Training Period: Optimized warm-up and training periods for AI calculations
โ๏ธ Backtest Improvements
- More Reliable Results: Increased minimum trade requirement for statistical significance
- Accurate Profit Calculations: Switched to multiplicative equity tracking for compound returns
- Improved Signal Processing: Better handling of entry/exit timing with close price processing
- Performance Optimization: Refined calculation methods for faster backtesting on large datasets
๐ง Technical Enhancements
- Alert System: Added percentage display option for all TP/SL levels in alert messages
- Memory Management: Optimized array handling for better performance on extended backtests
- Trade Validation: Enhanced trade entry/exit detection with bar-level precision
- Performance Metrics: Added time-elapsed calculations for annualized return accuracy
๐ Bug Fixes
- Fixed profit factor calculation errors in edge cases
- Corrected take profit calculations using proper price levels
- Resolved array indexing issues in configuration storage
- Fixed equity calculation methods for accurate drawdown reporting
- Improved trade counting and timing accuracy
๐ Important Notes for Backtesting
- Some previous backtest results may differ due to improved calculation methods
- Alert messages now support percentage display - check your alert settings
- The AI training period has been optimized - allow sufficient bars for full functionality
- Performance threshold adjustments may affect strategy selection in AI mode
The backtest version maintains full compatibility with the main indicator while providing enhanced testing capabilities.
โก Performance Optimization
- Faster Loading: Significantly improved indicator initialization and loading times
- Smart Processing: Calculations now run only when needed based on selected signal type
- Resource Efficiency: Reduced memory usage when certain signal modes are not active
๐ฏ New Backtest Features
- Advanced Trailing Stop System: Same revolutionary trailing modes now in backtest:
โข None: Traditional static stop loss
โข Breakeven: Auto-moves SL to entry after hitting chosen TP
โข Moving Target: Progressive trailing to previous TP levels - Strategy-Optimized Execution: Trailing stops now properly integrated with TradingView strategy tester
- Partial Position Management: Improved handling of remaining quantities after partial TP exits
โ๏ธ Backtest Improvements
- Accurate Position Tracking: Uses strategy.position_avg_price for precise entry calculations
- Better Exit Management: Refined strategy.exit and strategy.close logic for realistic fills
- Enhanced Signal Filtering: Improved signal detection matching live trading behavior
๐ง Technical Enhancements
- Dynamic Stop Adjustments: Stop loss properly updates with strategy position changes
- Remainder Handling: Automatic cleanup of small remaining positions after multiple TPs
- Alert Compatibility: Backtest alerts now match live trading format with percentages
๐ Important Notes
- Trailing stops significantly impact backtest results - test all modes thoroughly
- Strategy tester now accurately reflects trailing stop behavior
- Alert messages in backtest mode now include all TP/SL levels with percentages
- Previous backtest results may differ due to improved exit logic
Invite-only script
Only users approved by the author can access this script. You'll need to request and get permission to use it. This is typically granted after payment. For more details, follow the author's instructions below or contact InfinityAlgo directly.
Note that this private, invite-only script has not been reviewed by script moderators, and its compliance with House Rules is undetermined. TradingView does NOT recommend paying for or using a script unless you fully trust its author and understand how it works. You may also find free, open-source alternatives in our community scripts.
Author's instructions
Disclaimer
Invite-only script
Only users approved by the author can access this script. You'll need to request and get permission to use it. This is typically granted after payment. For more details, follow the author's instructions below or contact InfinityAlgo directly.
Note that this private, invite-only script has not been reviewed by script moderators, and its compliance with House Rules is undetermined. TradingView does NOT recommend paying for or using a script unless you fully trust its author and understand how it works. You may also find free, open-source alternatives in our community scripts.