Parcourir la source

refactor(record): 优化错误日志处理并添加账户信息存储

移除冗余的traceback打印,简化错误日志输出
在TradingStrategy中添加account_info字段存储账户信息
将账户查询逻辑整合到主循环中
skyfffire il y a 1 semaine
Parent
commit
7fbeed3c11
2 fichiers modifiés avec 28 ajouts et 21 suppressions
  1. 9 18
      src/record/market_data_recorder.py
  2. 19 3
      src/record/strategy.py

+ 9 - 18
src/record/market_data_recorder.py

@@ -16,7 +16,6 @@ import time
 import logging
 import os
 import requests
-import traceback
 from datetime import datetime
 from strategy import TradingStrategy
 
@@ -86,8 +85,7 @@ async def fetch_lighter_orderbooks(session):
                 logger.error(f"获取Lighter orderBooks数据失败: HTTP {response.status}")
                 return None
     except Exception as e:
-        error_info = traceback.format_exc()
-        logger.error(f"获取Lighter orderBooks数据时出错: {str(e)}\n{error_info}")
+        logger.error(f"获取Lighter orderBooks数据时出错: {str(e)}")
         return None
 
 
@@ -103,8 +101,7 @@ async def fetch_binance_premium_index(session):
                 logger.error(f"获取Binance标记价格数据失败: HTTP {response.status}")
                 return None
     except Exception as e:
-        error_info = traceback.format_exc()
-        logger.error(f"获取Binance标记价格数据时出错: {str(e)}\n{error_info}")
+        logger.error(f"获取Binance标记价格数据时出错: {str(e)}")
         return None
 
 
@@ -120,8 +117,7 @@ async def fetch_binance_ticker_price(session):
                 logger.error(f"获取Binance最新价格数据失败: HTTP {response.status}")
                 return None
     except Exception as e:
-        error_info = traceback.format_exc()
-        logger.error(f"获取Binance最新价格数据时出错: {str(e)}\n{error_info}")
+        logger.error(f"获取Binance最新价格数据时出错: {str(e)}")
         return None
 
 
@@ -140,8 +136,7 @@ def update_market_id_mapping(orderbooks_data):
         
         logger.info(f"更新market_id映射,共 {len(market_id_to_symbol)} 个交易对,{market_id_to_symbol}")
     except Exception as e:
-        error_info = traceback.format_exc()
-        logger.error(f"更新market_id映射时出错: {str(e)}\n{error_info}")
+        logger.error(f"更新market_id映射时出错: {str(e)}")
 
 
 async def handle_binance_data_collection():
@@ -181,6 +176,7 @@ async def handle_binance_data_collection():
                 await asyncio.sleep(0.3)
                 
         except Exception as e:
+            import traceback
             error_info = traceback.format_exc()
             logger.error(f"Binance数据收集出错: {str(e)}\n{error_info}")
             await asyncio.sleep(1)  # 出错时等待1秒再重试
@@ -253,17 +249,14 @@ async def handle_market_stats_websocket():
                             logger.debug(f"收到未处理的消息类型: {message_type}")
                     
                     except json.JSONDecodeError as e:
-                        error_info = traceback.format_exc()
-                        logger.error(f"解析WebSocket消息失败: {str(e)}\n{error_info}")
+                        logger.error(f"解析WebSocket消息失败: {str(e)}")
                     except Exception as e:
-                        error_info = traceback.format_exc()
-                        logger.error(f"处理WebSocket消息时出错: {str(e)}\n{error_info}")
+                        logger.error(f"处理WebSocket消息时出错: {str(e)}")
                         
         except websockets.exceptions.ConnectionClosed:
             logger.warning("Market Stats WebSocket连接断开,5秒后重连...")
             await asyncio.sleep(5)
         except Exception as e:
-            error_info = traceback.format_exc()
             logger.error(f"Market Stats WebSocket连接出错: {str(e)},5秒后重连...")
             await asyncio.sleep(5)
 
@@ -307,8 +300,7 @@ def write_batch_to_questdb(data_batch):
             return False
             
     except Exception as e:
-        error_info = traceback.format_exc()
-        logger.error(f"批量写入数据到QuestDB时出错: {str(e)}\n{error_info}")
+        logger.error(f"批量写入数据到QuestDB时出错: {str(e)}")
         return False
 
 
@@ -478,5 +470,4 @@ if __name__ == "__main__":
     except KeyboardInterrupt:
         logger.info("行情数据记录器被用户停止")
     except Exception as e:
-        error_info = traceback.format_exc()
-        logger.error(f"发生意外错误: {str(e)}\n{error_info}")
+        logger.error(f"发生意外错误: {str(e)}")

+ 19 - 3
src/record/strategy.py

@@ -39,6 +39,7 @@ class TradingStrategy:
         self.current_position = None    # 当前持仓信息
         self.entry_price_bps = 5        # 入场时的价差
         self.target_symbol = "DOGE"     # 目标交易对
+        self.account_info = None        # 存储账户信息
 
         self.account_index = 281474976643718
         self.api_client = lighter.ApiClient()
@@ -77,6 +78,18 @@ class TradingStrategy:
         if not market_data:
             return
         
+        # 每次执行时更新账户信息
+        try:
+            account_response = await self.account_api.account(by="index", value=f"{self.account_index}")
+            if account_response.code == 200:
+                self.account_info = account_response
+                # logger.info(f"账户信息更新成功: 可用余额={account_response.accounts[0].available_balance}, 总资产={account_response.accounts[0].total_asset_value}")
+            else:
+                logger.warning(f"账户信息查询失败: code={account_response.code}, message={account_response.message}")
+        except Exception as e:
+            logger.error(f"查询账户信息时出错: {str(e)}")
+            return
+        
         symbol = market_data.get('symbol')
         
         # 如果是DOGE交易对,打印实时行情
@@ -120,8 +133,6 @@ class TradingStrategy:
         price_diff_str = f"{price_diff_bps}bps" if price_diff_bps is not None else "N/A"
         
         logger.info(f"[{symbol}] Binance: 最新价={binance_price} | Lighter: 最新价={lighter_price} | 价差={price_diff_str}")
-        account = await self.account_api.account(by="index", value=f"{self.account_index}")
-        logger.info(f"账户状态: {account}")
     
     async def _handle_waiting_init(self):
         """处理等待初始化状态"""
@@ -153,4 +164,9 @@ class TradingStrategy:
         """处理平仓完成状态"""
         # 平仓完成后回到空闲监听状态
         self.state = StrategyState.IDLE_MONITORING
-        logger.info("状态转换: POSITION_CLOSED -> IDLE_MONITORING")
+        logger.info("状态转换: POSITION_CLOSED -> IDLE_MONITORING")
+
+if __name__ == '__main__':
+    strategy = TradingStrategy()
+
+