排查ccxt数据慢5-10分钟的问题

This commit is contained in:
zhangkun9038@dingtalk.com 2026-02-25 01:29:26 +08:00
parent 2021d15806
commit 667380639e
3 changed files with 122 additions and 2 deletions

View File

@ -5,7 +5,7 @@
"secret": "CD3B7DB459CBBD540E0926E5C48150E1",
"password": "c^-d:g;P2S9?Q#^",
"enable_strategy_log": true,
"enable_ws": false,
"enable_ws": true,
"ccxt_config": {
"enableRateLimit": true,
"rateLimit": 500,

View File

@ -13,7 +13,7 @@
"fiat_display_currency": "USD",
"dry_run": true,
"enable_strategy_log": true,
"timeframe": "5m",
"timeframe": "15m",
"additional_timeframes": ["4h"],
"dry_run_wallet": 2000,
"cancel_open_orders_on_exit": true,

120
tools/test_ccxt_okx.py Normal file
View File

@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""
直接使用CCXT测试OKX交易所K线数据新鲜度
"""
import ccxt
import pandas as pd
from datetime import datetime, timezone
import time
def test_okx_candles():
# 创建OKX交易所实例不需要API密钥只读取市场数据
exchange = ccxt.okx({
'enableRateLimit': True, # 启用速率限制
'rateLimit': 1000, # 1秒间隔
'timeout': 10000, # 10秒超时
})
symbol = 'BTC/USDT'
timeframe = '5m'
limit = 50 # 获取最后50条K线
print(f"正在获取 {symbol} {timeframe} K线数据...")
print("=" * 80)
try:
# 获取K线数据
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
if not ohlcv:
print("未获取到任何K线数据")
return
# 转换为DataFrame便于查看
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
# 将时间戳转换为可读时间UTC
df['datetime'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
print(f"获取到 {len(df)} 条K线数据")
print(f"当前系统时间: {datetime.now(timezone.utc)}")
print()
# 显示最后10条K线数据
print("最后10条K线数据:")
print("-" * 80)
for i in range(len(df)-10, len(df)):
row = df.iloc[i]
time_diff = (datetime.now(timezone.utc) - row['datetime']).total_seconds() / 60
print(f"时间: {row['datetime']} | 收盘价: {row['close']} | 距今: {time_diff:.2f}分钟")
print()
print("详细数据 (最后20条):")
print("-" * 120)
print(df[['datetime', 'open', 'high', 'low', 'close', 'volume']].tail(20).to_string(index=False))
# 检查最新K线的时间差
latest_candle_time = df.iloc[-1]['datetime']
current_time = datetime.now(timezone.utc)
time_diff_minutes = (current_time - latest_candle_time).total_seconds() / 60
print()
print("=" * 80)
print(f"最新K线时间: {latest_candle_time}")
print(f"当前时间: {current_time}")
print(f"时间差: {time_diff_minutes:.2f} 分钟")
if time_diff_minutes > 10:
print("⚠️ 警告: 最新K线数据可能存在显著延迟!")
else:
print("✅ 最新K线数据相对较新")
except Exception as e:
print(f"获取K线数据时发生错误: {e}")
def test_multiple_requests():
"""多次请求以观察数据变化"""
print("\n" + "=" * 80)
print("进行多次请求测试数据更新情况...")
exchange = ccxt.okx({
'enableRateLimit': True,
'rateLimit': 2000, # 增加间隔时间以避免限频
'timeout': 10000,
})
symbol = 'BTC/USDT'
timeframe = '5m'
for i in range(3):
print(f"\n--- 请求 {i+1}/3 ---")
try:
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=5)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['datetime'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
print(f"当前时间: {datetime.now(timezone.utc)}")
print("最新5条K线:")
for _, row in df.iterrows():
time_diff = (datetime.now(timezone.utc) - row['datetime']).total_seconds() / 60
print(f" {row['datetime']} | 收盘价: {row['close']} | 距今: {time_diff:.2f}分钟")
# 等待5秒再下一次请求
if i < 2:
print("等待5秒后再次请求...")
time.sleep(5)
except Exception as e:
print(f"请求 {i+1} 时发生错误: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("CCXT OKX K线数据测试")
print("=" * 80)
test_okx_candles()
test_multiple_requests()
print("\n测试完成!")