Add batch kline sending method and fix type hints
- Added send_klines_batch() method in BacktestClientAdapter for sending multiple symbols' klines in one request - Updated imports to include Dict and List types - Fixed Pylance type checking warning in xtquant_downloader.py (added type: ignore for xtdc.close()) - Updated bt_engine.py for compatibility with new adapter methods
This commit is contained in:
parent
67b85ab232
commit
61feb5daa0
@ -7,7 +7,7 @@
|
|||||||
- 调用底层WebSocket客户端进行通信
|
- 调用底层WebSocket客户端进行通信
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Optional
|
from typing import Optional, Dict, List
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@ -116,6 +116,81 @@ class BacktestClientAdapter:
|
|||||||
)
|
)
|
||||||
return signal
|
return signal
|
||||||
|
|
||||||
|
def send_klines_batch(
|
||||||
|
self,
|
||||||
|
klines_data: Dict[str, pd.Series],
|
||||||
|
kline_time: datetime,
|
||||||
|
period: str = "1d",
|
||||||
|
) -> Dict[str, Optional[TradeSignal]]:
|
||||||
|
"""
|
||||||
|
批量发送多个标的的K线数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
klines_data: 字典,key为标的代码,value为K线数据(Series,包含open/high/low/close/volume)
|
||||||
|
kline_time: K线时间戳
|
||||||
|
period: K线周期 (1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
字典,key为标的代码,value为交易信号或None
|
||||||
|
"""
|
||||||
|
# 构建批量请求数据 v1.0
|
||||||
|
batch_data = []
|
||||||
|
for symbol, kline in klines_data.items():
|
||||||
|
batch_data.append(
|
||||||
|
{
|
||||||
|
"symbol": symbol,
|
||||||
|
"period": period,
|
||||||
|
"kline_time": kline_time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"data": {
|
||||||
|
"open": float(kline["open"]),
|
||||||
|
"high": float(kline["high"]),
|
||||||
|
"low": float(kline["low"]),
|
||||||
|
"close": float(kline["close"]),
|
||||||
|
"volume": int(kline["volume"]),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
request_data = {
|
||||||
|
"header": self._create_header(),
|
||||||
|
"msg_type": "KLINE_DATA_BATCH",
|
||||||
|
"batch_data": batch_data,
|
||||||
|
}
|
||||||
|
|
||||||
|
# 发送消息
|
||||||
|
response = self.ws_client.send(request_data)
|
||||||
|
if not response:
|
||||||
|
return {symbol: None for symbol in klines_data.keys()}
|
||||||
|
|
||||||
|
# 检查是否是错误消息
|
||||||
|
if response.get("msg_type") == "ERROR":
|
||||||
|
logger.error(
|
||||||
|
f"Server error: {response.get('error_code')} - {response.get('error_message')}"
|
||||||
|
)
|
||||||
|
return {symbol: None for symbol in klines_data.keys()}
|
||||||
|
|
||||||
|
# 解析批量交易信号
|
||||||
|
results = {}
|
||||||
|
signals = response.get("signals", [])
|
||||||
|
for signal_data in signals:
|
||||||
|
symbol = signal_data.get("symbol")
|
||||||
|
if symbol:
|
||||||
|
results[symbol] = TradeSignal(
|
||||||
|
symbol=symbol,
|
||||||
|
action=signal_data.get("action", "HOLD"),
|
||||||
|
price=signal_data.get("price", 0.0),
|
||||||
|
quantity=signal_data.get("quantity", 0),
|
||||||
|
message=signal_data.get("message", ""),
|
||||||
|
req_msg_id=response.get("header", {}).get("req_msg_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 对于没有返回信号的标的,填充None
|
||||||
|
for symbol in klines_data.keys():
|
||||||
|
if symbol not in results:
|
||||||
|
results[symbol] = None
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
"""关闭连接"""
|
"""关闭连接"""
|
||||||
self.ws_client.close()
|
self.ws_client.close()
|
||||||
|
|||||||
@ -4,6 +4,7 @@
|
|||||||
简单的回测引擎类
|
简单的回测引擎类
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
from src.data_service.data_service import DataService
|
from src.data_service.data_service import DataService
|
||||||
@ -116,13 +117,15 @@ class BacktestEngine:
|
|||||||
if self.backtest_client:
|
if self.backtest_client:
|
||||||
for symbol, bar in current_bars.items():
|
for symbol, bar in current_bars.items():
|
||||||
# 使用send_kline接口,传入period信息
|
# 使用send_kline接口,传入period信息
|
||||||
self.backtest_client.send_kline(
|
response = self.backtest_client.send_kline(
|
||||||
symbol=symbol,
|
symbol=symbol,
|
||||||
kline=bar,
|
kline=bar,
|
||||||
kline_time=timestamp,
|
kline_time=timestamp,
|
||||||
period=task.period,
|
period=task.period,
|
||||||
)
|
)
|
||||||
# 暂不处理返回的信号,后续可以添加策略逻辑
|
# 处理返回信号
|
||||||
|
if response is not None:
|
||||||
|
logger.info(f"Received response: {response}")
|
||||||
|
|
||||||
# 每50个时间点输出一次进度
|
# 每50个时间点输出一次进度
|
||||||
if idx % 50 == 0:
|
if idx % 50 == 0:
|
||||||
|
|||||||
@ -71,7 +71,7 @@ class XtQuantDownloader(BaseDataDownloader):
|
|||||||
def __del__(self):
|
def __del__(self):
|
||||||
"""析构函数:关闭 XtQuant 连接"""
|
"""析构函数:关闭 XtQuant 连接"""
|
||||||
try:
|
try:
|
||||||
xtdc.close()
|
xtdc.close() # type: ignore
|
||||||
self.logger.debug("XtQuant connection closed")
|
self.logger.debug("XtQuant connection closed")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.debug(f"Error closing XtQuant connection: {e}")
|
self.logger.debug(f"Error closing XtQuant connection: {e}")
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user