# Indicator Preferences & AI Plan Generation Implementation ## 🎯 Overview This document describes the complete implementation of **Indicator Preferences** and **AI-Powered Trading Plan Generation** features for the Gold Trading Simulator. ## ✨ Features Implemented ### 1. **Indicator Preferences System** - Users can select their preferred technical indicators - Configure priority levels for each indicator (1-10) - Add custom notes for why they prefer each indicator - Enable/disable indicators individually - Preferences are stored in the database and used for AI analysis ### 2. **AI Trading Plan Generation** - AI generates comprehensive daily trading plans - Uses user's indicator preferences in the analysis - Provides market bias, entry zones, targets, stop losses - Includes support/resistance levels - Generates strategy notes and reasoning - One-click plan generation with "AI Plan" button --- ## 📂 Files Created/Modified ### Backend Files #### **New Models** (`backend/app/models/models.py`) ```python - UserIndicatorPreferences: Stores user's preferred indicators - AIPlanGeneration: Stores AI-generated trading plans ``` #### **New Schemas** (`backend/app/schemas/schemas.py`) ```python - IndicatorPreferenceCreate/Update/Response - IndicatorPreferencesListResponse - AIPlanGenerationRequest/Response - AIPlanFeedback - MarketBias enum ``` #### **New API Endpoints** (`backend/app/api/settings_api.py`) ```python GET /settings/indicators/preferences POST /settings/indicators/preferences PUT /settings/indicators/preferences/{id} DELETE /settings/indicators/preferences/{id} POST /settings/indicators/preferences/bulk ``` #### **New AI Endpoints** (`backend/app/api/ai.py`) ```python POST /ai/generate-plan GET /ai/plans/history POST /ai/plans/feedback ``` #### **New Service** (`backend/app/services/ai_plan_service.py`) - `AIPlanService` class with methods: - `generate_plan()`: Generate AI trading plan - `get_plan_history()`: Get historical plans - `submit_feedback()`: Submit user feedback #### **Enhanced Service** (`backend/app/services/openrouter.py`) - Added `generate_trading_plan()` method for AI plan generation #### **Migration Script** (`backend/migrate_indicator_ai_tables.py`) - Creates new database tables - Includes rollback functionality - Verification checks ### Frontend Files #### **New Component** (`frontend/src/components/IndicatorPreferences.tsx`) - Visual indicator selection interface - Priority slider with star ratings - Enable/disable toggles - Notes for each indicator - Bulk save functionality - Real-time validation #### **Enhanced Component** (`frontend/src/components/DailyTradingPlan.tsx`) - Added "AI Plan" button with sparkle icon - Integrated AI plan generation - Maps AI response to plan structure - Loading states and error handling - User feedback with confidence display #### **Enhanced Service** (`frontend/src/services/api.ts`) - Added `aiApi.generateTradingPlan()` - Added `aiApi.getPlanHistory()` - Added `aiApi.submitPlanFeedback()` - Added `settingsApi` methods for indicator preferences #### **Enhanced Settings** (`frontend/src/components/SettingsPanel.tsx`) - Integrated IndicatorPreferences component - New section in settings panel --- ## 🗄️ Database Schema ### **user_indicator_preferences** ```sql id INTEGER PRIMARY KEY user_id VARCHAR (nullable) indicator_name VARCHAR (e.g., 'SMA', 'RSI', 'MACD') enabled BOOLEAN (default: true) parameters JSON (indicator-specific parameters) priority INTEGER (1-10, higher = more important) notes TEXT (user notes) created_at TIMESTAMP updated_at TIMESTAMP ``` ### **ai_plan_generations** ```sql id INTEGER PRIMARY KEY user_id VARCHAR (nullable) plan_date DATE market_bias VARCHAR (BULLISH/BEARISH/NEUTRAL) confidence FLOAT (0-100) daily_target FLOAT max_loss FLOAT entry_zone_min FLOAT entry_zone_max FLOAT target_price FLOAT stop_loss FLOAT support_levels JSON (array of prices) resistance_levels JSON (array of prices) max_trades INTEGER trading_notes TEXT indicators_used JSON (array of indicator names) reasoning TEXT market_conditions JSON ai_model VARCHAR accepted BOOLEAN modified BOOLEAN feedback TEXT created_at TIMESTAMP updated_at TIMESTAMP ``` --- ## 🚀 Usage Guide ### Setting Up Indicator Preferences 1. **Navigate to Settings** - Click "Settings" tab in the main navigation 2. **Configure Indicators** - Scroll to "Indicator Preferences" section - Click on indicators to add them - Set priority level (1-10) with slider - Add notes explaining why you prefer this indicator - Enable/disable as needed 3. **Save Preferences** - Click "Save" button at the top - Preferences are stored in database ### Generating AI Trading Plans 1. **Open Daily Trading Plan** - Navigate to any panel showing the Daily Trading Plan component 2. **Generate Plan** - Click the "AI Plan" button (purple gradient with sparkle icon) - Confirm generation when prompted - Wait for AI to analyze (5-15 seconds) 3. **Review Plan** - AI plan is loaded into the form - Shows market bias and confidence level - Review all fields (entry zones, targets, levels) - Edit if needed - Save when satisfied 4. **Submit Feedback (Optional)** - After trading, submit feedback on plan accuracy - Helps improve future AI generations --- ## 🔧 Installation & Setup ### 1. Run Database Migration ```bash cd backend python migrate_indicator_ai_tables.py ``` This will create the two new tables in your database. ### 2. Verify Backend ```bash # Start backend server cd backend python -m uvicorn app.main:app --reload ``` ### 3. Test New Endpoints ```bash # Test indicator preferences curl http://localhost:8000/settings/indicators/preferences # Test AI plan generation curl -X POST http://localhost:8000/ai/generate-plan \ -H "Content-Type: application/json" \ -d '{"current_price": 2025.50, "risk_tolerance": "moderate"}' ``` ### 4. Start Frontend ```bash cd frontend npm run dev ``` --- ## 📊 Available Indicators The system supports 10 technical indicators: | Indicator | Description | |-----------|-------------| | **SMA** | Simple Moving Average - Smooths price data | | **EMA** | Exponential Moving Average - Recent price focus | | **RSI** | Relative Strength Index - Momentum (0-100) | | **MACD** | Moving Average Convergence Divergence | | **BB** | Bollinger Bands - Volatility bands | | **ATR** | Average True Range - Volatility measure | | **Stochastic** | Momentum indicator vs range | | **Fibonacci** | Support/resistance retracement levels | | **VWAP** | Volume Weighted Average Price | | **Pivot** | Key support and resistance levels | --- ## 🤖 AI Plan Generation Logic ### How It Works 1. **User Preferences Loading** - System loads user's enabled indicators - Sorts by priority (highest first) 2. **Prompt Construction** - Builds detailed prompt with: - Current market price - User's risk tolerance - Preferred indicators with parameters - Recent price action (if available) - Current indicator values 3. **AI Analysis** - Sends prompt to Claude 3.5 Sonnet - AI analyzes using specified indicators - Generates comprehensive trading plan 4. **Plan Storage** - Stores plan in database - Includes metadata (confidence, reasoning) - Tracks indicators used 5. **User Review** - Plan displayed in UI - User can edit before accepting - Feedback can be submitted later --- ## 🎨 UI Features ### Indicator Preferences Component - **Visual Design**: Clean card-based layout - **Priority System**: Star ratings (1-10) - **Status Badges**: Green (enabled) / Gray (disabled) - **Quick Actions**: Remove indicators easily - **Info Box**: Explains how system works - **Validation**: Prevents duplicate indicators ### AI Plan Button - **Prominent Design**: Purple gradient with sparkle icon - **Loading State**: Shows "Generating..." during AI call - **Success Feedback**: Alert with bias and confidence - **Error Handling**: Graceful fallback message --- ## 🔐 Security Considerations - User preferences are user-specific (user_id field) - AI plan history is private per user - No sensitive data in AI prompts - OpenRouter API key stored securely in .env - Input validation on all endpoints --- ## 📈 Future Enhancements Potential improvements for future versions: 1. **Multi-timeframe Analysis** - Generate plans for different timeframes - 1H, 4H, Daily plans 2. **Backtesting** - Test AI plans against historical data - Measure accuracy over time 3. **Learning System** - AI learns from user feedback - Improves accuracy for individual users 4. **Custom Indicators** - Allow users to add custom indicators - Configure parameters per indicator 5. **Plan Templates** - Save favorite plan configurations - Quick load common strategies 6. **Notifications** - Alert when conditions match plan - Price hits entry zone notification --- ## 🐛 Troubleshooting ### Migration Issues **Problem**: Tables already exist ```bash # Use checkfirst=True (already implemented) # Or rollback first: python migrate_indicator_ai_tables.py --rollback ``` **Problem**: Database connection error - Check DATABASE_URL in .env - Verify PostgreSQL is running - Check credentials ### AI Generation Issues **Problem**: AI Plan button does nothing - Check browser console for errors - Verify OPENROUTER_API_KEY is set - Check backend logs **Problem**: Plan generation fails - Ensure indicator preferences are saved - Check current price is valid - Verify AI service is responding ### Frontend Issues **Problem**: Component not showing - Clear browser cache - Check React dev tools for errors - Verify component import in Settings --- ## 📝 API Examples ### Create Indicator Preference ```bash curl -X POST http://localhost:8000/settings/indicators/preferences \ -H "Content-Type: application/json" \ -d '{ "indicator_name": "RSI", "enabled": true, "priority": 8, "parameters": {"period": 14}, "notes": "Good for identifying overbought/oversold" }' ``` ### Generate AI Trading Plan ```bash curl -X POST http://localhost:8000/ai/generate-plan \ -H "Content-Type: application/json" \ -d '{ "current_price": 2025.50, "risk_tolerance": "moderate", "use_indicator_preferences": true, "user_capital": 100000 }' ``` ### Get Plan History ```bash curl http://localhost:8000/ai/plans/history?limit=5 ``` --- ## ✅ Testing Checklist - [ ] Database migration runs successfully - [ ] Can create indicator preferences - [ ] Can edit indicator preferences - [ ] Can delete indicator preferences - [ ] Preferences appear in Settings panel - [ ] AI Plan button appears in Daily Trading Plan - [ ] AI Plan generation works - [ ] Generated plan loads into form - [ ] Can edit AI-generated plan - [ ] Can save plan after AI generation - [ ] Plan history is stored - [ ] Backend API endpoints respond correctly --- ## 📚 Related Documentation - `DAILY_HELPER_ENHANCEMENT_PLAN.md` - Original feature proposal - `DAILY_TRADING_WORKFLOW.md` - Daily trading workflow - `DAILY_TRADING_IMPLEMENTATION.md` - Previous trading features --- ## 👥 Credits Implementation completed as part of the Phase 1 Daily Helper Enhancements. **Date**: November 16, 2025 **Features**: Indicator Preferences + AI Plan Generation **Status**: ✅ Complete and Ready for Use