test_database.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #!/usr/bin/env python3
  2. """
  3. 测试数据库功能
  4. """
  5. import sys
  6. import time
  7. import random
  8. from pathlib import Path
  9. # 添加项目路径到Python路径
  10. project_root = Path(__file__).parent
  11. sys.path.insert(0, str(project_root / "src"))
  12. from leadlag.database import TradingDatabase
  13. def test_database():
  14. """测试数据库功能"""
  15. print("🧪 开始测试数据库功能...")
  16. # 创建测试数据库
  17. db_path = "test_trading_data.db"
  18. db = TradingDatabase(db_path)
  19. print(f"✅ 数据库创建成功: {db_path}")
  20. # 测试价格数据记录
  21. print("\n📊 测试价格数据记录...")
  22. base_price = 50000.0
  23. for i in range(10):
  24. # 模拟价格波动
  25. binance_price = base_price + random.uniform(-100, 100)
  26. lighter_price = binance_price + random.uniform(-5, 5)
  27. spread_bps = (lighter_price - binance_price) / binance_price * 10000
  28. db.record_price_data(
  29. symbol="BTCUSDT",
  30. binance_price=binance_price,
  31. lighter_price=lighter_price,
  32. lighter_bid=lighter_price - 0.5,
  33. lighter_ask=lighter_price + 0.5,
  34. lighter_bid_size=random.uniform(0.1, 1.0),
  35. lighter_ask_size=random.uniform(0.1, 1.0),
  36. spread_bps=spread_bps,
  37. raw_data={"test": True, "index": i}
  38. )
  39. print(f" 记录 {i+1}: Binance={binance_price:.2f}, Lighter={lighter_price:.2f}, Spread={spread_bps:.2f}bps")
  40. time.sleep(0.1) # 模拟时间间隔
  41. # 测试交易事件记录
  42. print("\n🔄 测试交易事件记录...")
  43. events = [
  44. ("open_long", 49950.0, 0.1, "long", True),
  45. ("open_long_success", 49950.0, 0.1, "long", True),
  46. ("close_long", 50050.0, 0.1, "long", True),
  47. ("close_long_success", 50050.0, 0.1, "long", True),
  48. ("open_short", 50100.0, 0.1, "short", False),
  49. ("open_short_failed", 50100.0, 0.1, "short", False)
  50. ]
  51. for event_type, price, quantity, side, success in events:
  52. db.record_trading_event(
  53. symbol="BTCUSDT",
  54. event_type=event_type,
  55. price=price,
  56. quantity=quantity,
  57. side=side,
  58. strategy_state="EXECUTING_OPEN" if "open" in event_type else "EXECUTING_CLOSE",
  59. spread_bps=random.uniform(-10, 10),
  60. lighter_price=price + random.uniform(-1, 1),
  61. binance_price=price + random.uniform(-2, 2),
  62. success=success,
  63. tx_hash="0x123456789abcdef" if success else None,
  64. error_message="Test error" if not success else None,
  65. metadata={"test": True, "event": event_type}
  66. )
  67. status = "✅ 成功" if success else "❌ 失败"
  68. print(f" 事件: {event_type} - 价格={price:.2f}, 数量={quantity}, {status}")
  69. # 测试数据查询
  70. print("\n📈 测试数据查询...")
  71. # 查询价格数据 (最近1小时)
  72. current_time = time.time()
  73. one_hour_ago = current_time - 3600
  74. price_data = db.get_price_data(start_time=one_hour_ago, limit=100)
  75. print(f" 价格数据记录数: {len(price_data)}")
  76. # 查询交易事件
  77. trading_events = db.get_trading_events(start_time=one_hour_ago, limit=100)
  78. print(f" 交易事件记录数: {len(trading_events)}")
  79. # 查询统计信息
  80. stats = db.get_statistics()
  81. print(f" 统计信息: {stats}")
  82. print("\n🎉 数据库功能测试完成!")
  83. print(f"📁 测试数据库文件: {Path(db_path).absolute()}")
  84. return db_path
  85. def main():
  86. """主函数"""
  87. try:
  88. test_db_path = test_database()
  89. print("\n" + "="*60)
  90. print("🚀 现在可以启动Web Dashboard查看测试数据:")
  91. print(f" python run_dashboard.py")
  92. print(" 或者修改 run_dashboard.py 中的数据库路径为:")
  93. print(f" {Path(test_db_path).absolute()}")
  94. print("="*60)
  95. except Exception as e:
  96. print(f"❌ 测试失败: {e}")
  97. import traceback
  98. traceback.print_exc()
  99. sys.exit(1)
  100. if __name__ == '__main__':
  101. main()