浏览代码

Optimize data fetching and margin calculations in info_commands.

- Fetch exchange positions data once to improve efficiency and reduce redundant calls.
- Enhance ROE and margin calculations by utilizing pre-fetched exchange data, ensuring more accurate metrics.
- Implement fallback mechanisms for margin data retrieval to improve robustness in position analysis.
Carles Sentis 1 周之前
父节点
当前提交
105340d08d
共有 2 个文件被更改,包括 25 次插入6 次删除
  1. 24 5
      src/commands/info_commands.py
  2. 1 1
      trading_bot.py

+ 24 - 5
src/commands/info_commands.py

@@ -172,6 +172,9 @@ class InfoCommands:
                 total_margin_used = 0
                 total_margin_used = 0
                 total_equity_used = 0  # For ROE calculation
                 total_equity_used = 0  # For ROE calculation
                 
                 
+                # Fetch exchange data once for the entire command
+                exchange_positions_data = self.trading_engine.get_positions() or []
+                
                 # Fetch all exchange orders once to use throughout the command if needed by other parts
                 # Fetch all exchange orders once to use throughout the command if needed by other parts
                 # For this specific change, we'll use it inside the loop, but good practice to fetch once.
                 # For this specific change, we'll use it inside the loop, but good practice to fetch once.
                 # self._cached_all_exchange_orders = self.trading_engine.get_orders() or [] 
                 # self._cached_all_exchange_orders = self.trading_engine.get_orders() or [] 
@@ -243,13 +246,17 @@ class InfoCommands:
                         logger.debug(f"Using position value calculation for {symbol}: {pnl_percentage}%")
                         logger.debug(f"Using position value calculation for {symbol}: {pnl_percentage}%")
                     # else pnl_percentage remains 0.0
                     # else pnl_percentage remains 0.0
 
 
-                    # Get ROE (Return on Equity) from exchange data
+                    # Get ROE (Return on Equity) and margin info from exchange data
                     roe_percentage = None
                     roe_percentage = None
-                    # Try to get ROE from the raw exchange data
-                    exchange_data = self.trading_engine.get_positions()
-                    if exchange_data:
-                        for pos_data in exchange_data:
+                    live_margin_used = None
+                    # Use the exchange data we fetched once at the beginning
+                    if exchange_positions_data:
+                        for pos_data in exchange_positions_data:
                             if pos_data.get('symbol') == symbol:
                             if pos_data.get('symbol') == symbol:
+                                # Get margin from CCXT data
+                                live_margin_used = pos_data.get('initialMargin')
+                                
+                                # Get ROE from raw exchange info
                                 info_data = pos_data.get('info', {})
                                 info_data = pos_data.get('info', {})
                                 position_info = info_data.get('position', {})
                                 position_info = info_data.get('position', {})
                                 roe_raw = position_info.get('returnOnEquity')
                                 roe_raw = position_info.get('returnOnEquity')
@@ -259,7 +266,19 @@ class InfoCommands:
                                         logger.debug(f"Found ROE for {symbol}: {roe_percentage}%")
                                         logger.debug(f"Found ROE for {symbol}: {roe_percentage}%")
                                     except (ValueError, TypeError):
                                     except (ValueError, TypeError):
                                         logger.warning(f"Could not parse ROE value: {roe_raw} for {symbol}")
                                         logger.warning(f"Could not parse ROE value: {roe_raw} for {symbol}")
+                                
+                                # Also try to get margin from raw exchange info if CCXT doesn't have it
+                                if live_margin_used is None:
+                                    live_margin_used = position_info.get('marginUsed')
+                                    if live_margin_used is not None:
+                                        try:
+                                            live_margin_used = float(live_margin_used)
+                                        except (ValueError, TypeError):
+                                            live_margin_used = None
                                 break
                                 break
+                    
+                    # Use live margin data if available, otherwise fall back to database
+                    margin_used = live_margin_used if live_margin_used is not None else position_trade.get('margin_used')
 
 
                     # Add to totals
                     # Add to totals
                     individual_position_value = position_trade.get('position_value')
                     individual_position_value = position_trade.get('position_value')

+ 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.3.161"
+BOT_VERSION = "2.3.162"
 
 
 # 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"))