# AI Features & Integration **Complete guide to AI-powered features in the Gold Trading Simulator** --- ## ๐ŸŽฏ Overview The platform integrates professional-grade AI analysis powered by OpenRouter (Claude 3.5 Sonnet, GPT-4, and other models) to provide gold-specific market analysis, trading recommendations, and daily trading plans. --- ## ๐Ÿš€ Core AI Features ### 1. AI Scenario Analysis **Purpose**: Real-time market analysis with BUY/SELL/HOLD recommendations **Endpoint**: `POST /api/ai/analyze` **Capabilities**: - Gold market structure analysis (trend vs consolidation) - Technical indicator interpretation (RSI, MACD, EMAs, etc.) - Support/resistance level identification - Risk assessment (LOW/MEDIUM/HIGH) - Confidence scoring (0-100%) - Actionable trade recommendations **Gold-Specific Context**: - โœ… Typical volatility range ($20-40 daily) - โœ… Price levels to nearest $0.50 - โœ… USD inverse correlation - โœ… Safe-haven demand factors - โœ… Session timing (London/NY overlap optimal) **Response Format**: ```json { "recommendation": "BUY", "confidence": 78, "reasoning": "Gold showing bullish momentum above key support...", "support_levels": [2045.50, 2038.00, 2030.50], "resistance_levels": [2067.50, 2075.00, 2082.50], "risk_level": "MEDIUM", "entry_price": 2050.00, "target_price": 2070.00, "stop_loss": 2043.00 } ``` --- ### 2. Daily Trading Plan Generation **Purpose**: Comprehensive daily trading strategy with specific levels and rules **Endpoint**: `POST /api/ai/daily-plan` **Capabilities**: - Market bias assessment (BULLISH/BEARISH/NEUTRAL) - Entry zone identification - Multiple target levels - Stop loss placement - Support/resistance mapping - Max trade recommendations - Risk/reward calculations - Contingency planning **Trader Profile Integration**: - Capital size - Risk tolerance (conservative/moderate/aggressive) - Trading style (scalping/day trading/swing) - Preferred session times **Output Structure**: ```json { "date": "2025-11-23", "market_bias": "BULLISH", "confidence": 75, "key_levels": { "support": [2045.50, 2038.00, 2030.50], "resistance": [2067.50, 2075.00, 2082.50] }, "trade_setups": [ { "direction": "LONG", "entry_zone": [2048.00, 2051.00], "targets": [2060.00, 2070.00, 2080.00], "stop_loss": 2043.00, "risk_reward": 2.5 } ], "max_trades": 3, "risk_per_trade": "1-2% of capital", "notes": "Focus on London/NY overlap. Watch USD movements..." } ``` --- ### 3. AI Trading Coach **Component**: `AITradingCoach.tsx` **Features**: - Interactive chat interface - Real-time market Q&A - Strategy refinement - Trade review assistance - Educational guidance **Use Cases**: - "Should I enter this trade?" - "How do I manage this position?" - "What's happening with gold prices?" - "Explain this indicator pattern" --- ### 4. News Summarization **Endpoint**: `POST /api/ai/summarize-news` **Capabilities**: - Multi-article summarization - Sentiment analysis - Key takeaways extraction - Market impact assessment --- ## โš™๏ธ Configuration ### Required Environment Variables ```bash # OpenRouter API Key (Required) OPENROUTER_API_KEY=sk-or-v1-xxxxxxxxxxxxx # Model Selection (Optional, defaults to claude-3.5-sonnet) OPENROUTER_MODEL=anthropic/claude-3.5-sonnet # Alternative models available: # - anthropic/claude-3.5-sonnet (recommended for trading) # - openai/gpt-4-turbo # - google/gemini-pro # - meta-llama/llama-3.1-70b ``` ### Model Settings **Default Configuration**: - **Model**: Claude 3.5 Sonnet - **Temperature**: 0.7 (balanced creativity/consistency) - **Max Tokens**: 1500-3000 - **Timeout**: 60 seconds **Cost Optimization**: - Analysis: ~$0.01-0.03 per request - Daily Plan: ~$0.03-0.05 per generation - News Summary: ~$0.01-0.02 per batch **Recommended**: Start with $5 OpenRouter credit (~200-500 analyses) --- ## ๐Ÿ“‹ Prompt Templates ### Available Templates Located in `backend/app/services/prompts.py`: 1. **analysis_default** - General gold market analysis - Technical and fundamental factors - Risk-aware recommendations 2. **risk_control_default** - Position sizing guidance - Stop loss recommendations - Risk management rules 3. **daily_plan_template** - Comprehensive daily strategy - Multiple scenarios - Time-based execution 4. **technical_analysis_focused** - Deep dive on indicators - Chart pattern recognition - Momentum analysis 5. **market_sentiment_analysis** - News impact assessment - Sentiment scoring - Fundamental drivers ### Customizing Prompts **Edit System Prompts**: ```python # backend/app/services/openrouter.py SYSTEM_MESSAGE = """ You are an expert gold (XAU/USD) trading analyst... [Customize persona and expertise here] """ ``` **Edit Analysis Prompt**: ```python # backend/app/services/openrouter.py - analyze_scenario() analysis_prompt = f""" Analyze the current gold market... [Customize analysis framework here] """ ``` **Edit Plan Prompt**: ```python # backend/app/services/ai_plan_service.py - generate_plan() plan_prompt = f""" Generate a comprehensive daily trading plan... [Customize plan structure here] """ ``` --- ## ๐Ÿงช Testing ### Basic Connectivity Test ```bash cd backend python test_openrouter.py ``` **Expected Output**: ``` โœ… SUCCESS! OpenRouter API is working Model: anthropic/claude-3.5-sonnet Response: [AI-generated text about gold trading] ``` ### Comprehensive Prompt Test ```bash cd backend python test_improved_prompts.py ``` **Tests**: - โœ… AI scenario analysis - โœ… Daily plan generation - โœ… Response formatting - โœ… Error handling --- ## ๐Ÿ’ก Best Practices ### For Optimal AI Performance 1. **Provide Quality Data** - Include 20-50 recent candles - Send current technical indicators - Update price data frequently 2. **Set Proper Context** - Specify user's capital and risk tolerance - Include current positions - Mention trading style preferences 3. **Use at Optimal Times** - Before market open (for daily plans) - During London/NY overlap (for real-time analysis) - After major news events 4. **Combine Multiple Features** - Start with Daily Plan - Use Scenario Analysis for specific setups - Consult Trading Coach for questions - Review with News Summarization --- ## ๐Ÿ”ง Implementation Details ### Service Architecture ``` Frontend (React) โ†“ API Layer (FastAPI) โ†“ AI Services โ”œโ”€โ”€ openrouter.py (Scenario Analysis) โ”œโ”€โ”€ ai_plan_service.py (Daily Plans) โ””โ”€โ”€ prompts.py (Template Library) โ†“ OpenRouter API โ””โ”€โ”€ Claude 3.5 Sonnet / GPT-4 ``` ### Key Files **Backend Services**: - `backend/app/services/openrouter.py` - Core AI analysis service - `backend/app/services/ai_plan_service.py` - Daily plan generator - `backend/app/services/prompts.py` - Prompt template library - `backend/app/api/ai.py` - AI API endpoints - `backend/app/api/ai_coach.py` - Trading coach endpoint **Frontend Components**: - `frontend/src/components/AIAnalysisPanel.tsx` - AI analysis UI - `frontend/src/components/DailyTradingPlan.tsx` - Daily plan UI - `frontend/src/components/AITradingCoach.tsx` - Interactive coach - `frontend/src/services/api.ts` - API client **Database Models**: - `TradingPlan` - Stores generated plans - `DecisionLog` - Tracks AI recommendations vs actions - `IndicatorPreference` - User's preferred indicators for AI --- ## ๐Ÿ“Š Response Quality Examples ### Scenario Analysis Response **Before Enhancement**: ``` Generic recommendation with basic reasoning. No specific levels or risk assessment. ``` **After Enhancement**: ``` RECOMMENDATION: BUY CONFIDENCE: 78% REASONING: Gold is showing bullish momentum above the key $2,045 support level. The 20-EMA has crossed above the 50-EMA (golden cross), indicating strengthening uptrend. RSI at 58 shows room to run before overbought. MACD histogram turning positive supports the bullish case. ENTRY: $2,050.00 (on pullback to 20-EMA) TARGETS: $2,060 (R1), $2,070 (previous high), $2,082 (R2) STOP LOSS: $2,043 (below recent swing low + $4 buffer) RISK LEVEL: MEDIUM - USD showing weakness supporting gold - Safe-haven demand elevated - Watch for reversal at $2,070 resistance RISK/REWARD: 1:2.8 (Favorable) ``` ### Daily Plan Response **Before Enhancement**: ``` Basic market outlook without specific levels or rules. ``` **After Enhancement**: ``` GOLD TRADING PLAN - November 23, 2025 MARKET BIAS: BULLISH (Confidence: 75%) STRATEGY: Pullback buying on strong uptrend - Look for dips to 20/50-EMA zone - Target breakout above yesterday's high - Respect key support at $2,045 TRADE SETUPS: Setup #1 (Primary): DIRECTION: LONG ENTRY ZONE: $2,048-2,051 (pullback to EMA zone) TARGETS: T1=$2,060 (25%), T2=$2,070 (50%), T3=$2,082 (25%) STOP: $2,043 (below swing low) R:R: 2.5:1 Setup #2 (Breakout): DIRECTION: LONG ENTRY: $2,070 break and retest TARGETS: $2,082, $2,095 STOP: $2,065 R:R: 2:1 MAX TRADES: 3 RISK PER TRADE: 1-2% of capital MAX DAILY LOSS: -3% (stop trading if hit) BEST TIMING: 8:00-11:00 AM EST (London/NY overlap) KEY LEVELS: Resistance: $2,067.50, $2,075, $2,082.50 Support: $2,045.50, $2,038, $2,030.50 WATCH FOR: - USD weakness continuation - 10Y Treasury yields - Any Fed speaker comments CONTINGENCY: If price drops below $2,045: Switch to BEARISH bias, target $2,038 and $2,030 support levels. ``` --- ## ๐Ÿšจ Troubleshooting ### Issue: AI responses seem generic **Cause**: API key not set or incorrect **Fix**: ```bash # Check .env file cat backend/.env | grep OPENROUTER # Should show: OPENROUTER_API_KEY=sk-or-v1-xxxxx ``` ### Issue: Slow response times **Cause**: Large context or complex analysis **Fix**: - Reduce price history to 50 candles max - Use faster model (e.g., GPT-3.5) - Reduce max_tokens to 1500 ### Issue: Responses don't include specific levels **Cause**: Insufficient price data **Fix**: Send at least 20 recent candles with OHLC data ### Issue: 500 Error on AI analysis **Cause**: Empty price_data array (fixed in latest version) **Fix**: Update to latest `openrouter.py` with graceful handling ### Issue: High API costs **Optimization**: - Cache daily plans (regenerate only on user request) - Use scenario analysis sparingly - Consider cheaper models for news summarization - Set usage limits in OpenRouter dashboard --- ## ๐Ÿ“ˆ Future Enhancements ### Planned Features - [ ] Pattern recognition training - [ ] Backtesting AI recommendations - [ ] Multi-timeframe analysis - [ ] Correlation analysis with other assets - [ ] AI-powered alert generation - [ ] Custom prompt templates per user - [ ] Performance tracking (AI vs manual trades) --- ## ๐Ÿ” Security & Privacy ### Data Handling - โœ… API keys stored in environment variables - โœ… No sensitive data sent to OpenRouter - โœ… User trading data stays in local database - โœ… AI responses cached to minimize API calls ### API Key Security **Never commit API keys to git**: ```bash # Add to .gitignore backend/.env ``` **Use environment-specific keys**: - Development: Use test key with low limits - Production: Use main key with higher limits - Rotate keys periodically --- ## ๐Ÿ“ž Support ### Getting Help 1. Check test scripts: ```bash python test_openrouter.py python test_improved_prompts.py ``` 2. Review logs: ```bash # Backend logs tail -f backend/logs/app.log ``` 3. OpenRouter Dashboard: - Monitor usage: https://openrouter.ai/activity - Check credits: https://openrouter.ai/credits - View API logs: https://openrouter.ai/logs ### Common Questions **Q: Which AI model should I use?** A: Claude 3.5 Sonnet for best trading analysis. GPT-4 Turbo for faster responses. GPT-3.5 for cost optimization. **Q: How much does it cost?** A: ~$0.01-0.05 per analysis. $5 credit = 200-500 analyses. **Q: Can I use multiple models?** A: Yes, switch via `OPENROUTER_MODEL` env variable. **Q: Does it work offline?** A: No, requires internet connection to OpenRouter API. **Q: Can I self-host?** A: Yes, modify services to use local LLM (Ollama, LM Studio). --- **Status**: โœ… Production Ready **Version**: 2.0 **Last Updated**: November 2025 **Maintained**: Active