Browse Source

Enhance risk command error handling and update trading stats method

- Improved the `risk_command` in `RiskCommands` to include error handling for position formatting, ensuring robustness against data inconsistencies.
- Updated the `get_token_performance` method in `TradingStats` to provide a more straightforward performance report without the limit parameter.
- Enhanced code clarity and maintainability through better use of default values and exception logging.
Carles Sentis 2 days ago
parent
commit
3c5bbb5ec8
3 changed files with 17 additions and 5 deletions
  1. 15 3
      src/commands/info/risk.py
  2. 1 1
      src/stats/trading_stats.py
  3. 1 1
      trading_bot.py

+ 15 - 3
src/commands/info/risk.py

@@ -56,9 +56,21 @@ class RiskCommands(InfoCommandsBase):
 
         lines = ["<b>Open Positions:</b>"]
         for p in positions:
-            position_info = p.get('position', p) # Handle both old and new structures for safety
-            pnl_emoji = "🟢" if float(p.get('unrealizedPnl', 0.0)) >= 0 else "🔴"
-            lines.append(f"• {position_info['coin']}: {position_info['szi']} {position_info['side']} @ ${position_info['entryPx']} {pnl_emoji}")
+            try:
+                position_info = p.get('position', p)
+                pnl = float(p.get('unrealizedPnl', 0.0))
+                pnl_emoji = "🟢" if pnl >= 0 else "🔴"
+                
+                # Use .get() with defaults to avoid KeyErrors
+                asset = position_info.get('asset', 'N/A')
+                size = position_info.get('szi', 'N/A')
+                side = position_info.get('side', 'N/A')
+                entry_price = position_info.get('entryPx', 'N/A')
+
+                lines.append(f"• {asset}: {size} {side} @ ${entry_price} {pnl_emoji}")
+            except Exception as e:
+                logger.error(f"Error formatting a position: {p}, error: {e}")
+                lines.append("• Error displaying one position.")
         return "\n".join(lines) + "\n"
 
     async def _format_portfolio_summary(self, balance_data, positions):

+ 1 - 1
src/stats/trading_stats.py

@@ -340,7 +340,7 @@ class TradingStats:
             normalized_token = normalize_token_case(token)
             return self.performance_calculator.get_single_token_performance(normalized_token)
         else:
-            return self.performance_calculator.get_all_token_performance()
+            return self.performance_calculator.get_token_performance()
     
     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.259"
+BOT_VERSION = "2.4.260"
 
 # Add src directory to Python path
 sys.path.insert(0, str(Path(__file__).parent / "src"))