skyfffire 6 days ago
parent
commit
05e991c5b8
4 changed files with 42 additions and 61 deletions
  1. 16 4
      check_db.py
  2. 11 33
      src/leadlag/database.py
  3. 2 2
      src/leadlag/main.py
  4. 13 22
      src/leadlag/strategy.py

+ 16 - 4
check_db.py

@@ -9,14 +9,26 @@ cursor.execute('SELECT * FROM price_data ORDER BY timestamp DESC LIMIT 10')
 rows = cursor.fetchall()
 for row in rows:
     ts = datetime.fromtimestamp(row[1]).strftime('%Y-%m-%d %H:%M:%S')
-    print(f"时间: {ts}, 标的: {row[3]}, Binance: {row[5]}, Lighter: {row[4]}, 价差: {row[6]} bps")
+    print(f"所有列: {row}")
+    print(f"  时间: {ts}")
+    print(f"  ID: {row[0]}, 时间戳: {row[1]}, 会话ID: {row[2]}, 标的: {row[3]}")
+    print(f"  Lighter价格: {row[4]}, Binance价格: {row[5]}, 价差(bps): {row[6]}")
+    print()
 
 print('\n=== Trading Events (最新10条) ===')
 cursor.execute('SELECT * FROM trading_events ORDER BY timestamp DESC LIMIT 10')
 rows = cursor.fetchall()
-for row in rows:
-    ts = datetime.fromtimestamp(row[1]).strftime('%Y-%m-%d %H:%M:%S')
-    print(f"时间: {ts}, 标的: {row[3]}, 事件: {row[4]}, 价格: {row[5]}, 状态: {row[8]}")
+if rows:
+    for row in rows:
+        ts = datetime.fromtimestamp(row[1]).strftime('%Y-%m-%d %H:%M:%S')
+        print(f"所有列: {row}")
+        print(f"  时间: {ts}")
+        print(f"  ID: {row[0]}, 时间戳: {row[1]}, 会话ID: {row[2]}, 标的: {row[3]}")
+        print(f"  事件类型: {row[4]}, 价格: {row[5]}, 数量: {row[6]}, 策略状态: {row[7]}")
+        print(f"  价差(bps): {row[8]}, 成功: {row[9]}, 错误信息: {row[10]}")
+        print()
+else:
+    print("  (无数据)")
 
 print('\n=== 数据统计 ===')
 cursor.execute('SELECT COUNT(*) FROM price_data')

+ 11 - 33
src/leadlag/database.py

@@ -56,22 +56,16 @@ class TradingDatabase:
         """创建数据库表结构"""
         cursor = self.connection.cursor()
         
-        # 价格数据表
+        # 价格数据表 - 简化版本,只保留关键字段
         cursor.execute("""
             CREATE TABLE IF NOT EXISTS price_data (
                 id INTEGER PRIMARY KEY AUTOINCREMENT,
                 timestamp REAL NOT NULL,
-                datetime_str TEXT NOT NULL,
                 symbol TEXT NOT NULL,
-                lighter_price REAL,
                 binance_price REAL,
-                spread_bps REAL,
-                lighter_bid REAL,
                 lighter_ask REAL,
-                lighter_bid_size REAL,
-                lighter_ask_size REAL,
-                binance_volume REAL,
-                raw_data TEXT,
+                lighter_bid REAL,
+                spread_bps REAL,
                 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
             )
         """)
@@ -112,46 +106,30 @@ class TradingDatabase:
     
     def record_price_data(self, 
                          symbol: str,
-                         lighter_price: Optional[float] = None,
                          binance_price: Optional[float] = None,
-                         spread_bps: Optional[float] = None,
-                         lighter_bid: Optional[float] = None,
                          lighter_ask: Optional[float] = None,
-                         lighter_bid_size: Optional[float] = None,
-                         lighter_ask_size: Optional[float] = None,
-                         binance_volume: Optional[float] = None,
-                         raw_data: Optional[Dict] = None):
+                         lighter_bid: Optional[float] = None,
+                         spread_bps: Optional[float] = None):
         """
-        记录价格数据
+        记录价格数据 - 简化版本
         
         Args:
             symbol: 交易对符号
-            lighter_price: Lighter价格
             binance_price: Binance价格
-            spread_bps: 价差(基点)
-            lighter_bid: Lighter买价
             lighter_ask: Lighter卖价
-            lighter_bid_size: Lighter买量
-            lighter_ask_size: Lighter卖量
-            binance_volume: Binance成交量
-            raw_data: 原始数据(字典格式)
+            lighter_bid: Lighter买价
+            spread_bps: 价差(基点)
         """
         try:
             timestamp = datetime.now().timestamp()
-            datetime_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
             
             cursor = self.connection.cursor()
             cursor.execute("""
                 INSERT INTO price_data (
-                    timestamp, datetime_str, symbol, lighter_price, binance_price, 
-                    spread_bps, lighter_bid, lighter_ask, lighter_bid_size, 
-                    lighter_ask_size, binance_volume, raw_data
-                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+                    timestamp, symbol, binance_price, lighter_ask, lighter_bid, spread_bps
+                ) VALUES (?, ?, ?, ?, ?, ?)
             """, (
-                timestamp, datetime_str, symbol, lighter_price, binance_price,
-                spread_bps, lighter_bid, lighter_ask, lighter_bid_size,
-                lighter_ask_size, binance_volume, 
-                json.dumps(raw_data) if raw_data else None
+                timestamp, symbol, binance_price, lighter_ask, lighter_bid, spread_bps
             ))
             
             self.connection.commit()

+ 2 - 2
src/leadlag/main.py

@@ -283,13 +283,13 @@ async def handle_order_book_websocket(config):
                                 "timestamp": time.time()
                             }
                             
-                            logger.debug(f"收到Order Book更新: market_index={market_index}, offset={offset}")
+                            logger.info(f"收到Order Book更新: market_index={market_index}, offset={offset}")
                             
                             # 触发策略更新
                             await trigger_strategy_update()
                         
                         else:
-                            logger.debug(f"收到未处理的消息类型: {message_type}")
+                            logger.warning(f"收到未处理的消息类型: {message_type}")
                     
                     except json.JSONDecodeError as e:
                         logger.error(f"解析WebSocket消息失败: {str(e)}")

+ 13 - 22
src/leadlag/strategy.py

@@ -214,51 +214,42 @@ class TradingStrategy:
         # logger.info(f"[{symbol}] Binance: 最新价={binance_price} | Lighter: 最新价={lighter_price} | 价差={price_diff_str}")
     
     async def _record_price_data(self, market_data):
-        """记录价格数据到数据库"""
+        """记录价格数据到数据库 - 简化版本"""
         try:
             symbol = market_data.get('symbol')
             binance_price = market_data.get('binance_price')
-            lighter_price = market_data.get('lighter_price')
             orderbook = market_data.get('orderbook', {})
             
-            # 计算价差(bps)
-            spread_bps = None
-            if binance_price and lighter_price:
-                binance_price_float = float(binance_price) if isinstance(binance_price, str) else binance_price
-                lighter_price_float = float(lighter_price) if isinstance(lighter_price, str) else lighter_price
-                spread_bps = (lighter_price_float - binance_price_float) / binance_price_float * 10000 if binance_price_float else 0
-            
-            # 提取orderbook信息
+            # 提取orderbook中的ask1和bid1
             lighter_bid = None
             lighter_ask = None
-            lighter_bid_size = None
-            lighter_ask_size = None
             
             if orderbook:
-                # 从orderbook中提取买卖价和数量
+                # 从orderbook中提取买卖价
                 if 'bids' in orderbook and orderbook['bids']:
                     best_bid = orderbook['bids'][0] if isinstance(orderbook['bids'][0], list) else orderbook['bids'][0]
                     if isinstance(best_bid, list) and len(best_bid) >= 2:
                         lighter_bid = float(best_bid[0])
-                        lighter_bid_size = float(best_bid[1])
                 
                 if 'asks' in orderbook and orderbook['asks']:
                     best_ask = orderbook['asks'][0] if isinstance(orderbook['asks'][0], list) else orderbook['asks'][0]
                     if isinstance(best_ask, list) and len(best_ask) >= 2:
                         lighter_ask = float(best_ask[0])
-                        lighter_ask_size = float(best_ask[1])
             
-            # 记录到数据库
+            # 计算价差(bps) - 使用lighter的中间价与binance价格比较
+            spread_bps = None
+            if binance_price and lighter_bid and lighter_ask:
+                binance_price_float = float(binance_price) if isinstance(binance_price, str) else binance_price
+                lighter_mid_price = (lighter_bid + lighter_ask) / 2
+                spread_bps = (lighter_mid_price - binance_price_float) / binance_price_float * 10000 if binance_price_float else 0
+            
+            # 记录到数据库 - 只保存关键字段
             self.database.record_price_data(
                 symbol=symbol,
-                lighter_price=float(lighter_price) if lighter_price else None,
                 binance_price=float(binance_price) if binance_price else None,
-                spread_bps=spread_bps,
-                lighter_bid=lighter_bid,
                 lighter_ask=lighter_ask,
-                lighter_bid_size=lighter_bid_size,
-                lighter_ask_size=lighter_ask_size,
-                raw_data=market_data
+                lighter_bid=lighter_bid,
+                spread_bps=spread_bps
             )
             
         except Exception as e: