Features: - AI analyzes market conditions to suggest optimal SL/TP percentages - Considers volatility, technical levels, timeframe, and risk/reward ratios - Falls back to config defaults when AI optimization unavailable - Enforces minimum safety constraints (3% SL, 1% TP) - Enhanced status API with AI risk management info - Comprehensive logging of decision sources Benefits: - Dynamic adaptation to market conditions - Improved risk/reward optimization - Reduced need for manual tuning - Safety-first approach with fallbacks Technical Implementation: - Enhanced AnalysisResult interface with optimalRiskManagement - Modified AI analysis prompt for risk management calculation - Updated makeTradeDecision to use AI recommendations - Enhanced executeLiveTrade with AI-optimized parameters - Added lastAIRiskManagement tracking and status reporting - Comprehensive documentation and examples
5.6 KiB
AI-Powered Risk Management System
Overview
The trading bot now features an AI-powered risk management system that automatically calculates optimal stop loss and take profit percentages based on market conditions, technical analysis, and current volatility.
How It Works
1. AI Analysis Enhancement
The AI now analyzes charts and provides optimal risk management recommendations in addition to trade signals:
{
"optimalRiskManagement": {
"stopLossPercent": 4.5,
"takeProfitPercent": 12.0,
"riskRewardRatio": 2.7,
"reasoning": "Based on current volatility, key levels, and timeframe analysis. Accounts for minimum 3% SL and 1% TP constraints.",
"marketVolatility": "MEDIUM",
"timeHorizon": "INTRADAY"
}
}
2. Minimum Safety Constraints
The system enforces minimum values to prevent trades from being canceled immediately:
- Stop Loss: Minimum 3% (system enforced)
- Take Profit: Minimum 1% (system enforced)
These minimums were determined through testing with Drift Protocol to ensure orders don't get canceled due to normal market volatility.
3. AI Decision Factors
The AI considers multiple factors when calculating optimal SL/TP:
Market Volatility Assessment
- LOW: Tighter stops (3-4%), smaller targets (3-6%)
- MEDIUM: Moderate stops (4-6%), balanced targets (8-12%)
- HIGH: Wider stops (6-10%), larger targets (15-25%)
Technical Levels
- Support/Resistance: Places stops beyond key levels
- Trend Strength: Adjusts targets based on momentum
- Volume Profile: Considers volume-based support/resistance
Timeframe Analysis
- SCALP (1m-5m): Tight stops, quick targets
- INTRADAY (15m-4h): Balanced risk/reward
- SWING (4h-1D): Wider stops, larger targets
Risk/Reward Optimization
- Targets minimum 1:2 risk/reward ratio
- Adjusts based on market conditions
- Considers probability of success
4. Implementation Flow
- Chart Analysis: AI analyzes screenshot and market conditions
- Risk Calculation: Determines optimal SL/TP percentages
- Safety Check: Enforces minimum constraints (3% SL, 1% TP)
- Trade Execution: Uses AI values or falls back to config defaults
- Logging: Records decision source and reasoning
5. Configuration Priority
The system uses the following priority order:
- AI Optimized (if available): Uses AI-calculated percentages
- Config Defaults: Falls back to user-configured values
- System Minimums: Enforces safety constraints
6. Monitoring
Status API Enhancement
The /api/automation/status endpoint now includes:
{
"lastAIRiskManagement": {
"stopLossPercent": 4.5,
"takeProfitPercent": 12.0,
"riskRewardRatio": 2.7,
"marketVolatility": "MEDIUM",
"timeHorizon": "INTRADAY",
"reasoning": "Current volatility suggests moderate stops with extended targets based on strong momentum",
"source": "AI_OPTIMIZED",
"timestamp": "2025-01-23T..."
}
}
Console Logging
Each trade shows risk management source:
🤖 AI Risk Management: {
useAIOptimal: true,
stopLossPercent: 4.5,
takeProfitPercent: 12.0,
riskRewardRatio: 2.7,
marketVolatility: 'MEDIUM',
reasoning: 'Based on current volatility and technical levels'
}
🎯 Risk Management (AI_OPTIMIZED): {
stopLoss: '4.5%',
takeProfit: '12.0%',
source: 'AI_OPTIMIZED'
}
Benefits
1. Dynamic Adaptation
- Adjusts to changing market conditions
- Considers current volatility and trend strength
- Optimizes for each specific setup
2. Improved Risk/Reward
- Targets optimal risk/reward ratios
- Reduces over-conservative or over-aggressive positioning
- Based on statistical analysis of market behavior
3. Reduced Manual Tuning
- Eliminates need to constantly adjust SL/TP settings
- Automatically adapts to different timeframes
- Considers multiple market factors simultaneously
4. Safety First
- Always enforces minimum safety constraints
- Falls back to config defaults if AI analysis fails
- Logs all decisions for transparency
Example Scenarios
Scenario 1: High Volatility Market
Market Conditions: SOL showing 8% daily range
AI Recommendation:
- Stop Loss: 6% (wider due to volatility)
- Take Profit: 18% (larger target to match volatility)
- Risk/Reward: 1:3
- Reasoning: "High volatility requires wider stops but offers larger profit potential"
Scenario 2: Low Volatility Consolidation
Market Conditions: SOL in tight range, low volume
AI Recommendation:
- Stop Loss: 3% (minimum enforced)
- Take Profit: 6% (conservative target)
- Risk/Reward: 1:2
- Reasoning: "Low volatility suggests tight range-bound trading with conservative targets"
Scenario 3: Strong Trend with Momentum
Market Conditions: Clear uptrend, strong volume
AI Recommendation:
- Stop Loss: 4% (below key support)
- Take Profit: 15% (trend extension target)
- Risk/Reward: 1:3.75
- Reasoning: "Strong momentum supports extended targets with stop below structural support"
Configuration
To use AI-optimized risk management, simply ensure your automation is running. The system will:
- Use AI recommendations when available
- Fall back to your config settings if AI analysis doesn't provide optimal values
- Always enforce minimum safety constraints
Your original config settings serve as fallbacks and minimums:
{
"stopLossPercent": 2, // Will be upgraded to 3% minimum
"takeProfitPercent": 6 // Used if AI doesn't suggest better value
}
Future Enhancements
- Machine learning from trade outcomes
- Volatility-based dynamic adjustment
- Correlation with market regimes
- Multi-asset risk optimization
- Real-time market sentiment integration