Răsfoiți Sursa

Enhance trading statistics retrieval by updating the get_token_performance method to support both specific token queries and aggregate performance data for all tokens. Improved error handling and added detailed performance metrics, including win rate and recent trades, ensuring comprehensive insights into trading performance.

Carles Sentis 1 săptămână în urmă
părinte
comite
3a1d0b8242
2 a modificat fișierele cu 97 adăugiri și 5 ștergeri
  1. 96 4
      src/stats/trading_stats.py
  2. 1 1
      trading_bot.py

+ 96 - 4
src/stats/trading_stats.py

@@ -7,7 +7,7 @@ Main class that coordinates between specialized manager components.
 
 import logging
 from datetime import datetime, timezone
-from typing import Dict, List, Any, Optional, Tuple
+from typing import Dict, List, Any, Optional, Tuple, Union
 import math
 import numpy as np
 import uuid
@@ -327,9 +327,101 @@ class TradingStats:
         """Get performance stats."""
         return self.performance_calculator.get_performance_stats()
     
-    def get_token_performance(self, limit: int = 20) -> List[Dict[str, Any]]:
-        """Get token performance."""
-        return self.performance_calculator.get_token_performance(limit)
+    def get_token_performance(self, token: Optional[str] = None) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
+        """Get performance data for a specific token or all tokens."""
+        try:
+            if token:
+                # Get performance for specific token
+                query = """
+                    SELECT 
+                        symbol,
+                        COUNT(*) as total_trades,
+                        SUM(CASE WHEN realized_pnl > 0 THEN 1 ELSE 0 END) as winning_trades,
+                        SUM(realized_pnl) as total_pnl,
+                        AVG(realized_pnl) as avg_trade,
+                        MAX(realized_pnl) as largest_win,
+                        MIN(realized_pnl) as largest_loss,
+                        AVG(CASE WHEN realized_pnl > 0 THEN realized_pnl ELSE NULL END) as avg_win,
+                        AVG(CASE WHEN realized_pnl < 0 THEN realized_pnl ELSE NULL END) as avg_loss
+                    FROM trades
+                    WHERE symbol = ? AND status = 'position_closed'
+                    GROUP BY symbol
+                """
+                result = self.db_manager._fetchone_query(query, (token,))
+                
+                if not result:
+                    return {}
+                
+                # Calculate win rate
+                total_trades = result['total_trades']
+                winning_trades = result['winning_trades']
+                win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
+                
+                # Get recent trades
+                recent_trades_query = """
+                    SELECT 
+                        side,
+                        entry_price,
+                        exit_price,
+                        realized_pnl as pnl,
+                        position_opened_at,
+                        position_closed_at
+                    FROM trades
+                    WHERE symbol = ? AND status = 'position_closed'
+                    ORDER BY position_closed_at DESC
+                    LIMIT 5
+                """
+                recent_trades = self.db_manager._fetch_query(recent_trades_query, (token,))
+                
+                return {
+                    'token': token,
+                    'total_trades': total_trades,
+                    'winning_trades': winning_trades,
+                    'win_rate': win_rate,
+                    'total_pnl': result['total_pnl'],
+                    'avg_trade': result['avg_trade'],
+                    'largest_win': result['largest_win'],
+                    'largest_loss': result['largest_loss'],
+                    'avg_win': result['avg_win'],
+                    'avg_loss': result['avg_loss'],
+                    'recent_trades': recent_trades
+                }
+            else:
+                # Get performance for all tokens
+                query = """
+                    SELECT 
+                        symbol,
+                        COUNT(*) as total_trades,
+                        SUM(CASE WHEN realized_pnl > 0 THEN 1 ELSE 0 END) as winning_trades,
+                        SUM(realized_pnl) as total_pnl,
+                        AVG(realized_pnl) as avg_trade
+                    FROM trades
+                    WHERE status = 'position_closed'
+                    GROUP BY symbol
+                    ORDER BY total_pnl DESC
+                """
+                results = self.db_manager._fetch_query(query)
+                
+                performance_data = []
+                for result in results:
+                    total_trades = result['total_trades']
+                    winning_trades = result['winning_trades']
+                    win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
+                    
+                    performance_data.append({
+                        'token': result['symbol'],
+                        'total_trades': total_trades,
+                        'winning_trades': winning_trades,
+                        'win_rate': win_rate,
+                        'total_pnl': result['total_pnl'],
+                        'avg_trade': result['avg_trade']
+                    })
+                
+                return performance_data
+                
+        except Exception as e:
+            logger.error(f"Error getting token performance: {e}")
+            return [] if token is None else {}
     
     def get_balance_history(self, days: int = 30) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
         """Get balance history."""

+ 1 - 1
trading_bot.py

@@ -14,7 +14,7 @@ from datetime import datetime
 from pathlib import Path
 
 # Bot version
-BOT_VERSION = "2.4.196"
+BOT_VERSION = "2.4.197"
 
 # Add src directory to Python path
 sys.path.insert(0, str(Path(__file__).parent / "src"))