stock-ai-agent/scripts/test_websocket_monitor.py
2026-02-20 22:53:42 +08:00

119 lines
3.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
测试 WebSocket 价格监控服务
"""
import sys
import os
import asyncio
import threading
import time
# 确保路径正确
script_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(script_dir)
backend_dir = os.path.join(project_root, 'backend')
sys.path.insert(0, backend_dir)
from app.services.websocket_monitor import get_ws_price_monitor
from app.utils.logger import logger
# 用于接收价格更新的队列
price_updates = []
def on_price_update(symbol: str, price: float):
"""价格更新回调"""
price_updates.append((symbol, price))
print(f"📊 [回调] {symbol}: ${price:,.2f}")
async def main():
print("=" * 60)
print("🔌 测试 WebSocket 价格监控服务")
print("=" * 60)
ws_monitor = get_ws_price_monitor()
# 订阅几个交易对
symbols = ['BTCUSDT', 'ETHUSDT']
print(f"\n订阅交易对: {', '.join(symbols)}")
for symbol in symbols:
print(f" 订阅 {symbol}...")
ws_monitor.subscribe_symbol(symbol)
# 注册回调
print("注册价格回调...")
ws_monitor.add_price_callback(on_price_update)
print("\n等待价格推送30秒...")
print("提示: WebSocket 连接可能需要几秒钟建立...")
print("-" * 60)
# 给 WebSocket 线程一些时间启动
await asyncio.sleep(2)
# 检查状态
print(f"\n📡 WebSocket 运行状态: {ws_monitor.is_running()}")
print(f"📡 已订阅交易对: {ws_monitor.get_subscribed_symbols()}")
print(f"📡 WebSocket 线程存活: {ws_monitor._thread.is_alive() if ws_monitor._thread else 'None'}")
print(f"📡 事件循环: {'已创建' if ws_monitor._loop else '未创建'}")
print("-" * 60)
# 等待价格更新
start_time = time.time()
last_price_count = 0
for i in range(30):
await asyncio.sleep(1)
# 每5秒打印一次状态
if (i + 1) % 5 == 0:
elapsed = time.time() - start_time
current_count = len(price_updates)
new_updates = current_count - last_price_count
last_price_count = current_count
print(f"\n⏱️ 已运行 {i+1} 秒 | 收到 {current_count} 次价格更新 (最近5秒: +{new_updates})")
print(f" WebSocket 状态: {'🟢 运行中' if ws_monitor.is_running() else '🔴 未运行'}")
# 显示当前缓存的价格
for symbol in symbols:
price = ws_monitor.get_latest_price(symbol)
if price:
print(f" 📊 {symbol}: ${price:,.2f}")
# 显示获取到的价格
print("\n" + "=" * 60)
print("📊 最终结果:")
print("=" * 60)
print(f" 共收到 {len(price_updates)} 次价格更新")
for symbol in symbols:
price = ws_monitor.get_latest_price(symbol)
if price:
print(f" {symbol}: ${price:,.2f}")
else:
print(f" {symbol}: 未获取到价格")
# 停止服务
print("\n停止服务...")
ws_monitor.stop()
# 等待线程结束
if ws_monitor._thread:
ws_monitor._thread.join(timeout=3)
print(f"线程已结束: {not ws_monitor._thread.is_alive()}")
print("=" * 60)
print("✅ 测试完成")
print("=" * 60)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n\n⚠️ 测试中断")
sys.exit(0)