Эх сурвалжийг харах

refactor(strategy): 重构持仓状态管理和交易事件记录逻辑

将持仓状态检查和交易事件记录逻辑集中到状态切换处,避免重复代码
移除分散的交易事件记录代码,统一在状态变更时处理
添加持仓方向同步和状态变更日志记录
skyfffire 4 өдөр өмнө
parent
commit
4681d7c32d
1 өөрчлөгдсөн 72 нэмэгдсэн , 45 устгасан
  1. 72 45
      src/leadlag/strategy.py

+ 72 - 45
src/leadlag/strategy.py

@@ -196,11 +196,79 @@ class TradingStrategy:
         # 记录价格数据到数据库
         await self._record_price_data(market_data)
         
-        # 根据持仓情况决定主要状态
-        if self.current_position and self.current_position.quantity > 0:
-            self.state = StrategyState.CLOSING_WITH_LIMIT_ORDER
+        # 基于账户信息更新 current_position
+        prev_position = self.current_position
+        position = None
+        if self.account_info and self.account_info.accounts:
+            try:
+                for pos in self.account_info.accounts[0].positions:
+                    if pos.symbol == self.target_symbol:
+                        try:
+                            position_size = float(pos.position)
+                        except Exception:
+                            position_size = 0.0
+                        if position_size != 0.0:
+                            position = pos
+                            break
+            except Exception as e:
+                logger.warning(f"解析账户持仓失败: {e}")
+        self.current_position = position
+        
+        # 同步持仓方向
+        if self.current_position:
+            self.position_side = 'long' if getattr(self.current_position, 'sign', 1) == 1 else 'short'
         else:
-            self.state = StrategyState.IDLE_MONITORING
+            self.position_side = None
+        
+        # 状态切换与变化日志
+        prev_state = self.state
+        new_state = StrategyState.CLOSING_WITH_LIMIT_ORDER if self.current_position else StrategyState.IDLE_MONITORING
+        if prev_state != new_state:
+            prev_name = prev_state.name if prev_state else 'None'
+            logger.info(f"状态转换: {prev_name} -> {new_state.name}")
+            if self.current_position:        
+                # 记录开仓成功事件
+                event_type = 'open_long' if self.position_side == 'long' else 'open_short'
+                self.database.record_trading_event(
+                    symbol=self.target_symbol,
+                    event_type=event_type,
+                    price=binance_price_float,
+                    quantity=self.trade_quantity,
+                    side=self.position_side,
+                    strategy_state=self.state.name if self.state else 'IDLE_MONITORING',
+                    binance_price=binance_price_float,
+                    success=True,
+                    metadata={
+                        'tx_hash': tx_hash,
+                        'order_id': oid
+                    }
+                )
+                
+                logger.info(f"检测到持仓:方向={'做多' if getattr(self.current_position, 'sign', 1) == 1 else '做空'},数量={self.current_position.position}")
+            else:
+                # 记录平仓成功事件
+                event_type = 'close_long' if self.position_side == 'long' else 'close_short'
+                self.database.record_trading_event(
+                    symbol=self.target_symbol,
+                    event_type=event_type,
+                    price=binance_price_float,
+                    quantity=abs(float(self.current_position.position)),
+                    side=self.position_side,
+                    strategy_state=self.state.name,
+                    binance_price=binance_price_float,
+                    success=True,
+                    metadata={'closing_order_id': self.closing_order_id}
+                )
+                logger.info("检测到无持仓,进入空闲监听")
+                # 清理状态
+                self.current_position = None
+                self.position_side = None
+                self.closing_order_id = None
+                self.last_closing_price = None
+                self.state = StrategyState.IDLE_MONITORING
+                logger.info(f"状态转换: CLOSING_WITH_LIMIT_ORDER -> IDLE_MONITORING")
+                logger.info(f"========================================================================")
+        self.state = new_state
 
         # 根据当前状态执行相应逻辑
         if self.state == StrategyState.IDLE_MONITORING:
@@ -340,26 +408,6 @@ class TradingStrategy:
         # 记录开仓时间
         self.last_trade_time = time.time()
         logger.info(f"开仓交易已发送,交易哈希={tx_hash}")
-        
-        # 记录开仓成功事件
-        event_type = 'open_long' if self.position_side == 'long' else 'open_short'
-        self.database.record_trading_event(
-            symbol=self.target_symbol,
-            event_type=event_type,
-            price=binance_price_float,
-            quantity=self.trade_quantity,
-            side=self.position_side,
-            strategy_state=self.state.name if self.state else 'IDLE_MONITORING',
-            binance_price=binance_price_float,
-            success=True,
-            metadata={
-                'tx_hash': tx_hash,
-                'order_id': oid
-            }
-        )
-    
-
-
     
     async def _handle_closing_with_limit_order(self, market_data):
         """处理限价单平仓状态 - 挂仅减仓的限价单平仓"""
@@ -393,27 +441,6 @@ class TradingStrategy:
         # 情况2.2:持仓已消失,平仓完成
         if not position:
             logger.info("检测到持仓已消失,平仓完成")
-            # 记录平仓成功事件
-            event_type = 'close_long' if self.position_side == 'long' else 'close_short'
-            self.database.record_trading_event(
-                symbol=self.target_symbol,
-                event_type=event_type,
-                price=binance_price_float,
-                quantity=abs(float(self.current_position.position)),
-                side=self.position_side,
-                strategy_state=self.state.name,
-                binance_price=binance_price_float,
-                success=True,
-                metadata={'closing_order_id': self.closing_order_id}
-            )
-            # 清理状态
-            self.current_position = None
-            self.position_side = None
-            self.closing_order_id = None
-            self.last_closing_price = None
-            self.state = StrategyState.IDLE_MONITORING
-            logger.info(f"状态转换: CLOSING_WITH_LIMIT_ORDER -> IDLE_MONITORING")
-            logger.info(f"========================================================================")
             return
         
         # 确定平仓方向和价格