myTestFreqAI/tools/test_ccxt_okx.py
2026-02-25 01:29:26 +08:00

120 lines
4.1 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
"""
直接使用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测试完成!")