Browse Source

Refactor risk management to utilize database positions for accuracy and update logging for clarity. Adjusted performance metrics retrieval in stats and changed default log level to INFO for production readiness.

Carles Sentis 6 days ago
parent
commit
4ecb9b2101
4 changed files with 14 additions and 26 deletions
  1. 1 1
      src/commands/info/stats.py
  2. 1 1
      src/config/config.py
  3. 11 23
      src/monitoring/risk_cleanup_manager.py
  4. 1 1
      trading_bot.py

+ 1 - 1
src/commands/info/stats.py

@@ -102,7 +102,7 @@ class StatsCommands(InfoCommandsBase):
             # --- Old format for overall stats ---
             # --- Old format for overall stats ---
             formatter = get_formatter()
             formatter = get_formatter()
             s = stats.get_basic_stats()
             s = stats.get_basic_stats()
-            perf = stats.get_performance_metrics()
+            perf = stats.get_basic_stats()
             session = stats.get_session_info()
             session = stats.get_session_info()
 
 
             # Account Overview
             # Account Overview

+ 1 - 1
src/config/config.py

@@ -41,7 +41,7 @@ class Config:
     DEFAULT_SLIPPAGE = 0.005  # 0.5%
     DEFAULT_SLIPPAGE = 0.005  # 0.5%
     
     
     # Logging
     # Logging
-    LOG_LEVEL = os.getenv('LOG_LEVEL', 'DEBUG').upper()
+    LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO').upper()
     
     
     # Log file configuration
     # Log file configuration
     LOG_TO_FILE: bool = os.getenv('LOG_TO_FILE', 'true').lower() == 'true'
     LOG_TO_FILE: bool = os.getenv('LOG_TO_FILE', 'true').lower() == 'true'

+ 11 - 23
src/monitoring/risk_cleanup_manager.py

@@ -128,40 +128,28 @@ class RiskCleanupManager:
                 logger.debug(f"Risk management disabled or STOP_LOSS_PERCENTAGE <= 0 (value: {Config.STOP_LOSS_PERCENTAGE})")
                 logger.debug(f"Risk management disabled or STOP_LOSS_PERCENTAGE <= 0 (value: {Config.STOP_LOSS_PERCENTAGE})")
                 return
                 return
 
 
-            positions = self.market_monitor_cache.cached_positions or []
+            # Use DB positions for risk checks to ensure validated, up-to-date data
+            stats = self.trading_engine.get_stats()
+            positions = stats.get_open_positions() if stats else []
             if not positions:
             if not positions:
-                logger.debug("No positions found in cache for risk management check.")
+                logger.debug("No open positions found in DB for risk management check.")
                 await self._cleanup_orphaned_stop_losses() # Call within class
                 await self._cleanup_orphaned_stop_losses() # Call within class
                 return
                 return
 
 
             for position in positions:
             for position in positions:
                 try:
                 try:
                     symbol = position.get('symbol', '')
                     symbol = position.get('symbol', '')
-                    contracts = float(position.get('contracts', 0))
-                    entry_price = float(position.get('entryPx', 0))
-                    mark_price = float(position.get('markPx', 0))
-                    unrealized_pnl = float(position.get('unrealizedPnl', 0))
-                    
+                    contracts = float(position.get('current_position_size', 0))
+                    entry_price = float(position.get('entry_price', 0))
+                    mark_price = float(position.get('mark_price', 0))
+                    unrealized_pnl = float(position.get('unrealized_pnl', 0))
+                    roe_percentage = float(position.get('roe_percentage', 0))
+
                     if contracts == 0 or entry_price <= 0 or mark_price <= 0:
                     if contracts == 0 or entry_price <= 0 or mark_price <= 0:
                         logger.debug(f"Skipping position {symbol}: contracts={contracts}, entry_price={entry_price}, mark_price={mark_price}")
                         logger.debug(f"Skipping position {symbol}: contracts={contracts}, entry_price={entry_price}, mark_price={mark_price}")
                         continue
                         continue
 
 
-                    # Get ROE directly from exchange data
-                    info_data = position.get('info', {})
-                    position_info = info_data.get('position', {})
-                    roe_raw = position_info.get('returnOnEquity')
-                    if roe_raw is not None:
-                        try:
-                            roe_percentage = float(roe_raw) * 100
-                            logger.debug(f"[RiskMgmt] {symbol}: ROE from exchange: {roe_percentage:+.2f}% (raw: {roe_raw})")
-                        except (ValueError, TypeError):
-                            logger.warning(f"Could not parse ROE value: {roe_raw} for {symbol}")
-                            roe_percentage = 0.0
-                    else:
-                        logger.warning(f"No ROE data available from exchange for {symbol}")
-                        roe_percentage = 0.0
-
-                    logger.info(f"[RiskMgmt] {symbol}: ROE={roe_percentage:+.2f}%, Threshold=-{Config.STOP_LOSS_PERCENTAGE}% (Trigger: {roe_percentage <= -Config.STOP_LOSS_PERCENTAGE})")
+                    logger.debug(f"[RiskMgmt] {symbol}: ROE={roe_percentage:+.2f}%, Threshold=-{Config.STOP_LOSS_PERCENTAGE}% (Trigger: {roe_percentage <= -Config.STOP_LOSS_PERCENTAGE})")
 
 
                     if roe_percentage <= -Config.STOP_LOSS_PERCENTAGE:
                     if roe_percentage <= -Config.STOP_LOSS_PERCENTAGE:
                         token = symbol.split('/')[0] if '/' in symbol else symbol.split(':')[0]
                         token = symbol.split('/')[0] if '/' in symbol else symbol.split(':')[0]

+ 1 - 1
trading_bot.py

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