""" Phase 5: Real-time AI Trading Coach AI-powered real-time trading assistance and guidance """ from fastapi import APIRouter, Query, HTTPException from typing import List, Optional from datetime import datetime router = APIRouter(prefix="/api/ai-coach", tags=["AI Trading Coach"]) @router.get("/coaching-session") async def start_coaching_session( trading_style: str = Query("swing", regex="^(scalping|swing|position)$"), experience_level: str = Query("intermediate", regex="^(beginner|intermediate|advanced)$"), ): """Start an AI coaching session with personalized guidance""" guidance = { "beginner": { "focus_points": [ "Risk management is paramount - never risk more than 1% per trade", "Keep trade journal to track mistakes and improve", "Start with one strategy and master it", "Understand support/resistance before entering trades", "Use stop losses on every single trade", ], "common_mistakes": [ "Over-leveraging accounts", "Trading without a plan", "Revenge trading after losses", "Ignoring risk management rules", "Chasing losses", ], "daily_routine": [ "Review previous day trades (15 min)", "Check economic calendar for events (5 min)", "Plan setups for today (10 min)", "Trade with discipline (pre-planned stops/targets)", "End-of-day review and journal (10 min)", ], }, "intermediate": { "focus_points": [ "Develop multiple strategies for different market conditions", "Focus on win rate AND risk/reward optimization", "Use advanced technical analysis effectively", "Understand market correlations (gold/USD/bonds)", "Build robust trading systems", ], "common_mistakes": [ "Over-optimization of strategies", "Ignoring current market regime", "Not adapting to changing conditions", "Trading too many timeframes simultaneously", "Revenge trading", ], "daily_routine": [ "Multi-timeframe analysis (20 min)", "Economic calendar review (5 min)", "Identify 3-5 key setups (15 min)", "Execute with high probability setups only (pre-market to close)", "Full session review and optimization (20 min)", ], }, "advanced": { "focus_points": [ "Develop proprietary edge and algorithms", "Statistical edge validation and backtesting", "Portfolio optimization and diversification", "Advanced risk metrics (Sharpe, Sortino, Calmar ratios)", "Systematic execution with automation", ], "common_mistakes": [ "Over-fitting strategies to historical data", "Ignoring black swan events", "Negligent risk monitoring", "Insufficient position sizing", "Emotional override of systems", ], "daily_routine": [ "Pre-market algorithmic analysis (15 min)", "Monitor system performance metrics (10 min)", "Execute systematic trades (monitoring only)", "Real-time risk management (ongoing)", "Post-market data analysis and optimization (20 min)", ], }, } strategy_focus = { "scalping": { "holding_period": "Seconds to 5 minutes", "best_indicators": "Fast MA, RSI(14), MACD", "position_sizing": "0.5-1% per trade", "daily_goal": "5-10 trades, 0.5-1% daily return", "key_rule": "Get in, get out quickly with defined exit", }, "swing": { "holding_period": "Minutes to hours", "best_indicators": "EMA(12/26), RSI(14), Pivot Points", "position_sizing": "1-2% per trade", "daily_goal": "2-5 trades, 1-3% daily return", "key_rule": "Let winners run, cut losers quickly", }, "position": { "holding_period": "Hours to days", "best_indicators": "SMA(50/200), Support/Resistance, Trends", "position_sizing": "2-5% per trade", "daily_goal": "0-2 trades, 2-5% weekly return", "key_rule": "Focus on trend direction, ignore noise", }, } return { "session_id": f"coach_{datetime.now().timestamp()}", "trading_style": trading_style, "experience_level": experience_level, "guidance": guidance[experience_level], "strategy_focus": strategy_focus[trading_style], "coaching_tips": f"Welcome to AI Coach! As a {experience_level} trader using {trading_style} strategy, focus on: {', '.join(guidance[experience_level]['focus_points'][:3])}", "session_started": datetime.now().isoformat(), } @router.get("/real-time-advice") async def get_real_time_advice( current_price: float = Query(...), high_24h: float = Query(...), low_24h: float = Query(...), rsi: float = Query(..., ge=0, le=100), macd_signal: str = Query("neutral", regex="^(bullish|bearish|neutral)$"), market_condition: str = Query("normal", regex="^(trending_up|trending_down|ranging|volatile)$"), ): """Get real-time AI coaching advice based on current market conditions""" advice_pieces = [] confidence = 0.5 # RSI analysis if rsi > 70: advice_pieces.append({ "indicator": "RSI", "signal": "OVERBOUGHT", "advice": "Consider taking profits on long positions. Watch for reversal signals.", "weight": 0.7, }) confidence = min(0.9, confidence + 0.2) elif rsi < 30: advice_pieces.append({ "indicator": "RSI", "signal": "OVERSOLD", "advice": "Look for buy signals. Market is stretched lower with bounce potential.", "weight": 0.7, }) confidence = min(0.9, confidence + 0.2) else: advice_pieces.append({ "indicator": "RSI", "signal": "NEUTRAL", "advice": "RSI is in neutral zone. Confirm with other indicators.", "weight": 0.3, }) # Market condition analysis if market_condition == "trending_up": advice_pieces.append({ "indicator": "Market Trend", "signal": "BULLISH", "advice": "Market in uptrend. Favor long positions. Avoid shorts.", "weight": 0.9, }) confidence = min(1.0, confidence + 0.3) elif market_condition == "trending_down": advice_pieces.append({ "indicator": "Market Trend", "signal": "BEARISH", "advice": "Market in downtrend. Favor short positions. Avoid longs.", "weight": 0.9, }) confidence = min(1.0, confidence + 0.3) else: advice_pieces.append({ "indicator": "Market Trend", "signal": "RANGING/VOLATILE", "advice": "No clear trend. Focus on support/resistance bounces.", "weight": 0.6, }) # Price action price_range = high_24h - low_24h price_from_low = current_price - low_24h range_pct = (price_from_low / price_range * 100) if price_range > 0 else 50 if range_pct > 75: advice_pieces.append({ "indicator": "Price Action", "signal": "NEAR HIGH", "advice": "Price near 24h high. Be cautious with new longs. Watch for reversals.", "weight": 0.6, }) elif range_pct < 25: advice_pieces.append({ "indicator": "Price Action", "signal": "NEAR LOW", "advice": "Price near 24h low. Good bounce opportunity if conditions align.", "weight": 0.6, }) # Overall recommendation if confidence >= 0.8: recommendation = "STRONG BUY" if market_condition == "trending_up" and rsi < 50 else "STRONG SELL" if market_condition == "trending_down" and rsi > 50 else "WAIT FOR CONFIRMATION" elif confidence >= 0.6: recommendation = "BUY" if market_condition == "trending_up" else "SELL" if market_condition == "trending_down" else "NEUTRAL" else: recommendation = "WAIT FOR BETTER SETUP" return { "current_price": current_price, "market_condition": market_condition, "rsi_level": rsi, "macd_signal": macd_signal, "advice_pieces": advice_pieces, "overall_recommendation": recommendation, "confidence_level": round(confidence, 2), "suggested_action": { "action": recommendation.split()[0], "entry": current_price * (1 - 0.003) if "BUY" in recommendation else current_price * (1 + 0.003), "take_profit": current_price * (1 + 0.015) if "BUY" in recommendation else current_price * (1 - 0.015), "stop_loss": current_price * (1 - 0.008) if "BUY" in recommendation else current_price * (1 + 0.008), }, "risk_assessment": "HIGH" if "STRONG" not in recommendation else "MEDIUM" if confidence < 0.85 else "LOW", } @router.get("/trade-review/{trade_id}") async def review_trade( trade_id: str, entry_price: float = Query(...), exit_price: float = Query(...), quantity: float = Query(...), hold_time_minutes: int = Query(..., ge=1), win_loss: str = Query(..., regex="^(win|loss)$"), ): """AI coach reviews a completed trade and provides feedback""" pnl = (exit_price - entry_price) * quantity return_pct = ((exit_price - entry_price) / entry_price) * 100 feedback = [] score = 50 # Entry analysis if abs(return_pct) > 2: feedback.append("✓ Good risk/reward ratio achieved") score += 15 elif abs(return_pct) > 1: feedback.append("✓ Decent risk/reward ratio") score += 5 else: feedback.append("⚠ Small return - may need better entry timing") # Hold time analysis if hold_time_minutes < 30 and win_loss == "win": feedback.append("✓ Executed quickly - good scalping") score += 10 elif hold_time_minutes > 120 and win_loss == "win": feedback.append("✓ Allowed winner to run - good discipline") score += 15 elif hold_time_minutes > 120 and win_loss == "loss": feedback.append("⚠ Held losing trade too long - cut losses faster") score -= 15 # Trade size if abs(return_pct) <= 3: feedback.append("✓ Conservative position sizing managed risk") score += 5 # Consistency if win_loss == "win": feedback.append("✓ Won trade - well executed!") score += 20 else: feedback.append("⚠ Lost trade - learn from mistakes, don't revenge trade") score = max(10, score - 20) return { "trade_id": trade_id, "entry_price": entry_price, "exit_price": exit_price, "pnl": round(pnl, 2), "return_percentage": round(return_pct, 2), "hold_time_minutes": hold_time_minutes, "result": win_loss, "trade_score": score, "feedback": feedback, "overall_assessment": "EXCELLENT TRADE" if score >= 80 else "GOOD TRADE" if score >= 60 else "ACCEPTABLE" if score >= 40 else "IMPROVE NEXT TIME", "next_steps": [ "Review your entry signal - was it clear?", "Check your exit - was it based on plan or emotion?", "Journal this trade with conditions and setup", "Identify the pattern/cluster this belongs to", ], } @router.get("/performance-coach") async def performance_coaching( total_trades: int = Query(..., ge=1), winning_trades: int = Query(..., ge=0), total_pnl: float = Query(...), avg_win: float = Query(...), avg_loss: float = Query(...), ): """AI coach analyzes overall performance and provides improvement suggestions""" win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0 profit_factor = (avg_win * winning_trades / (avg_loss * (total_trades - winning_trades))) if (total_trades - winning_trades) > 0 and avg_loss > 0 else 0 coaching_notes = [] priority_areas = [] # Win rate analysis if win_rate < 40: coaching_notes.append("⚠ Low win rate (<40%). Focus on entry signal quality.") priority_areas.append("Improve Entry Signals") elif win_rate > 70: coaching_notes.append("✓ Excellent win rate (>70%)! Keep this up.") elif win_rate > 55: coaching_notes.append("✓ Good win rate (>55%). This is solid.") else: coaching_notes.append("⚠ Win rate below 50%. Work on strategy validation.") priority_areas.append("Validate Strategy Edge") # Profit factor analysis if profit_factor > 2: coaching_notes.append("✓ Excellent profit factor (>2). Great risk/reward management.") elif profit_factor > 1.5: coaching_notes.append("✓ Good profit factor (>1.5). Continue this discipline.") elif profit_factor > 1: coaching_notes.append("⚠ Profit factor at 1:1. Improve risk/reward or exits.") priority_areas.append("Optimize Risk/Reward") else: coaching_notes.append("⚠ Losses exceed gains. Immediate action needed.") priority_areas.append("Fix Risk Management") # Trade count if total_trades < 30: coaching_notes.append("⚠ Low sample size (<30 trades). Need more data for analysis.") priority_areas.append("Increase Sample Size") elif total_trades > 200: coaching_notes.append("✓ Large sample size (>200). Statistics are reliable.") # PnL assessment daily_avg = total_pnl / max(1, total_trades) if daily_avg > avg_win * 0.5: coaching_notes.append(f"✓ Good average trade profit: ${daily_avg:.2f}") elif daily_avg > 0: coaching_notes.append(f"⚠ Average profit is low: ${daily_avg:.2f}. Look for better setups.") priority_areas.append("Select Higher Probability Trades") else: coaching_notes.append("⚠ Negative average trade. Review your entire system.") priority_areas.append("Complete System Review") return { "performance_summary": { "total_trades": total_trades, "winning_trades": winning_trades, "losing_trades": total_trades - winning_trades, "win_rate": round(win_rate, 1), "total_pnl": round(total_pnl, 2), "avg_winning_trade": round(avg_win, 2), "avg_losing_trade": round(avg_loss, 2), "profit_factor": round(profit_factor, 2), "avg_trade_profit": round(daily_avg, 2), }, "coaching_analysis": coaching_notes, "priority_improvement_areas": priority_areas, "action_plan": { "immediate": priority_areas[:2] if priority_areas else ["Continue current strategy"], "short_term": [ "Keep detailed trade journal with reasons for each trade", "Identify your best performing trade patterns", "Eliminate your worst performing patterns", ], "long_term": [ "Develop multiple strategies for different market conditions", "Backtest strategies thoroughly before live trading", "Track and analyze all statistics systematically", ], }, "encouragement": "You're on the right track!" if win_rate > 50 and profit_factor > 1 else "Every successful trader started where you are. Keep improving!", } @router.get("/decision-helper") async def get_decision_help( trade_setup: str = Query(...), risk_per_trade_pct: float = Query(1.0, ge=0.1, le=5), account_size: float = Query(10000), current_streak: str = Query("neutral", regex="^(winning|losing|neutral)$"), ): """AI coach helps with specific trade decisions""" max_loss = account_size * (risk_per_trade_pct / 100) decision_factors = { "winning": { "advice": "Great! You're in a winning streak. Stay disciplined and don't over-trade.", "risk_adjustment": "Keep position size normal", "caution": "Over-confidence risk. Stick to your plan.", }, "losing": { "advice": "In a losing streak? Take a break or reduce position size.", "risk_adjustment": "Consider dropping to 0.5% risk temporarily", "caution": "Revenge trading risk. Your plan is still valid.", }, "neutral": { "advice": "Neutral momentum. Trade only high probability setups.", "risk_adjustment": "Keep position size at plan", "caution": "None - stay focused on setup quality", }, } return { "trade_setup": trade_setup, "account_analysis": { "account_size": account_size, "risk_per_trade_pct": risk_per_trade_pct, "max_loss_per_trade": round(max_loss, 2), "trades_before_account_ruin": round(account_size / max_loss / 10), }, "trading_streak": current_streak, "streak_guidance": decision_factors[current_streak], "recommendation": "TAKE THIS SETUP" if "high" in trade_setup.lower() else "PASS - WAIT FOR BETTER" if "low" in trade_setup.lower() else "PROCEED WITH CAUTION", "risk_management": { "suggested_entry": "Execute at pre-defined level", "suggested_stop_loss": f"${max_loss:.2f} maximum loss", "position_size": f"{round(max_loss / 50, 2)} contracts or shares", "profit_target": f"2:1 risk/reward = ${max_loss * 2:.2f} profit target", }, "emotional_check": [ "Are you making this trade for the right reason?", "Does this fit your written trading plan?", "Have you seen this setup before successfully?", "Can you afford the risk on this trade?", ], }