279 lines
8.0 KiB
Python
279 lines
8.0 KiB
Python
|
|
"""
|
|||
|
|
MiniQMT 实盘交易客户端适配器
|
|||
|
|
|
|||
|
|
负责业务逻辑:
|
|||
|
|
- 连接 MiniQMT 交易接口
|
|||
|
|
- 发送 K线数据到策略服务器
|
|||
|
|
- 接收交易信号
|
|||
|
|
- 执行实盘交易委托
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from typing import Optional, Dict
|
|||
|
|
from datetime import datetime
|
|||
|
|
from dataclasses import dataclass
|
|||
|
|
import pandas as pd
|
|||
|
|
import uuid
|
|||
|
|
|
|||
|
|
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
|
|||
|
|
from xtquant.xttype import StockAccount
|
|||
|
|
from xtquant import xtconstant
|
|||
|
|
from xtquant import xtdata
|
|||
|
|
|
|||
|
|
from src.networks.client.ws_client import WSClient
|
|||
|
|
from src.core.logger import Logger
|
|||
|
|
|
|||
|
|
g_wsclient: Optional[WSClient] = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def init_wsclient(server_url: str, timeout: int) -> WSClient:
|
|||
|
|
"""初始化全局 WSClient 实例"""
|
|||
|
|
global g_wsclient
|
|||
|
|
if g_wsclient is None:
|
|||
|
|
g_wsclient = WSClient(server_url, timeout)
|
|||
|
|
return g_wsclient
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_wsclient() -> Optional[WSClient]:
|
|||
|
|
"""获取全局 WSClient 实例"""
|
|||
|
|
global g_wsclient
|
|||
|
|
return g_wsclient
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 实时行情数据回调
|
|||
|
|
# on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... }
|
|||
|
|
def on_realtime_data(datas):
|
|||
|
|
Logger.info(f"Received realtime data: {datas}")
|
|||
|
|
wsclient = get_wsclient()
|
|||
|
|
if wsclient:
|
|||
|
|
message = []
|
|||
|
|
for symbol, data in datas.items():
|
|||
|
|
# 构造消息
|
|||
|
|
|
|||
|
|
message = {
|
|||
|
|
"symbol": symbol,
|
|||
|
|
"datetime": data.get(
|
|||
|
|
"datetime", datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|||
|
|
),
|
|||
|
|
"open": data.get("open", 0.0),
|
|||
|
|
"high": data.get("high", 0.0),
|
|||
|
|
"low": data.get("low", 0.0),
|
|||
|
|
"close": data.get("close", 0.0),
|
|||
|
|
"volume": data.get("volume", 0),
|
|||
|
|
}
|
|||
|
|
# respone = wsclient.send("kline_data", message)
|
|||
|
|
# 获取买卖信号
|
|||
|
|
|
|||
|
|
Logger.info(f"Sent data to server: {message}")
|
|||
|
|
|
|||
|
|
|
|||
|
|
class MiniQMTTraderCallback(XtQuantTraderCallback):
|
|||
|
|
"""MiniQMT 交易回调"""
|
|||
|
|
|
|||
|
|
def __init__(self):
|
|||
|
|
super().__init__()
|
|||
|
|
|
|||
|
|
def on_disconnected(self):
|
|||
|
|
"""连接断开"""
|
|||
|
|
Logger.warning("MiniQMT 连接断开")
|
|||
|
|
|
|||
|
|
def on_stock_order(self, order):
|
|||
|
|
"""
|
|||
|
|
委托回报推送
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
order: XtOrder对象
|
|||
|
|
"""
|
|||
|
|
Logger.info(
|
|||
|
|
f"委托回报: {order.stock_code}, "
|
|||
|
|
f"状态={order.order_status}, "
|
|||
|
|
f"系统编号={order.order_sysid}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def on_stock_trade(self, trade):
|
|||
|
|
"""
|
|||
|
|
成交变动推送
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
trade: XtTrade对象
|
|||
|
|
"""
|
|||
|
|
Logger.info(
|
|||
|
|
f"成交回报: {trade.stock_code}, "
|
|||
|
|
f"订单ID={trade.order_id}, "
|
|||
|
|
f"成交价={trade.traded_price}, "
|
|||
|
|
f"成交量={trade.traded_volume}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def on_order_error(self, order_error):
|
|||
|
|
"""
|
|||
|
|
委托失败推送
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
order_error: XtOrderError对象
|
|||
|
|
"""
|
|||
|
|
Logger.error(
|
|||
|
|
f"委托失败: 订单ID={order_error.order_id}, "
|
|||
|
|
f"错误码={order_error.error_id}, "
|
|||
|
|
f"错误信息={order_error.error_msg}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def on_cancel_error(self, cancel_error):
|
|||
|
|
"""
|
|||
|
|
撤单失败推送
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
cancel_error: XtCancelError对象
|
|||
|
|
"""
|
|||
|
|
Logger.error(
|
|||
|
|
f"撤单失败: 订单ID={cancel_error.order_id}, "
|
|||
|
|
f"错误码={cancel_error.error_id}, "
|
|||
|
|
f"错误信息={cancel_error.error_msg}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def on_order_stock_async_response(self, response):
|
|||
|
|
"""
|
|||
|
|
异步下单回报
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
response: XtOrderResponse对象
|
|||
|
|
"""
|
|||
|
|
Logger.info(
|
|||
|
|
f"异步下单回报: 订单ID={response.order_id}, 响应={response.order_remark}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def on_account_status(self, status):
|
|||
|
|
"""
|
|||
|
|
账户状态变化推送
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
status: XtAccountStatus对象
|
|||
|
|
"""
|
|||
|
|
Logger.info(f"账户状态: {status.account_id}, 状态={status.account_type}")
|
|||
|
|
|
|||
|
|
|
|||
|
|
class MiniQMTClientAdapter:
|
|||
|
|
"""
|
|||
|
|
MiniQMT 实盘交易客户端适配器
|
|||
|
|
|
|||
|
|
负责:
|
|||
|
|
- 连接 MiniQMT 交易接口
|
|||
|
|
- 发送 K线数据到策略服务器获取信号
|
|||
|
|
- 执行实盘交易委托
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
def __init__(
|
|||
|
|
self,
|
|||
|
|
server_url: str,
|
|||
|
|
timeout: int,
|
|||
|
|
miniqmt_path: str,
|
|||
|
|
session_id: int,
|
|||
|
|
account_id: str,
|
|||
|
|
account_type: str = "STOCK",
|
|||
|
|
stockpool: Optional[list] = None,
|
|||
|
|
):
|
|||
|
|
"""
|
|||
|
|
初始化 MiniQMT 客户端适配器
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
server_url: 策略服务器 WebSocket 地址
|
|||
|
|
timeout: 超时时间(秒)
|
|||
|
|
miniqmt_path: MiniQMT userdata_mini 路径
|
|||
|
|
session_id: 会话ID(不同策略使用不同ID)
|
|||
|
|
account_id: 交易账号
|
|||
|
|
account_type: 账户类型(STOCK/HUGANGTONG/SHENGANGTONG)
|
|||
|
|
stockpool: 交易股票池(默认为空,表示全部股票)
|
|||
|
|
"""
|
|||
|
|
# 策略服务器 WebSocket 客户端
|
|||
|
|
init_wsclient(server_url, timeout)
|
|||
|
|
self.stockpool = stockpool if stockpool is not None else []
|
|||
|
|
# MiniQMT 交易客户端
|
|||
|
|
self.xt_trader = XtQuantTrader(miniqmt_path, session_id)
|
|||
|
|
self.account = StockAccount(account_id, account_type)
|
|||
|
|
self.callback = MiniQMTTraderCallback()
|
|||
|
|
# 注册回调
|
|||
|
|
self.xt_trader.register_callback(self.callback)
|
|||
|
|
|
|||
|
|
# 交易股票池
|
|||
|
|
if len(self.stockpool) == 0:
|
|||
|
|
Logger.warning("交易股票池为空,表示全部股票可交易")
|
|||
|
|
else:
|
|||
|
|
for symbol_info in self.stockpool:
|
|||
|
|
symbol = symbol_info.get("symbol")
|
|||
|
|
symbol_name = symbol_info.get("name", "")
|
|||
|
|
symbol_period = symbol_info.get("period")
|
|||
|
|
xtdata.subscribe_quote(
|
|||
|
|
symbol, period=symbol_period, callback=on_realtime_data
|
|||
|
|
)
|
|||
|
|
Logger.info(
|
|||
|
|
f"Subscribed to quote: {symbol} ({symbol_name}), period={symbol_period}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 连接状态
|
|||
|
|
self.is_connected = False
|
|||
|
|
|
|||
|
|
Logger.info(
|
|||
|
|
f"MiniQMTClientAdapter initialized: "
|
|||
|
|
f"account={account_id}, type={account_type}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def run(self) -> bool:
|
|||
|
|
"""启动连接"""
|
|||
|
|
self.is_connected = self._connect()
|
|||
|
|
if not self.is_connected:
|
|||
|
|
Logger.error("MiniQMT 连接失败,无法运行客户端适配器")
|
|||
|
|
return self.is_connected
|
|||
|
|
|
|||
|
|
Logger.info("MiniQMT 客户端适配器运行中,按 Ctrl+C 退出")
|
|||
|
|
try:
|
|||
|
|
self.xt_trader.run_forever()
|
|||
|
|
except KeyboardInterrupt:
|
|||
|
|
Logger.info("收到退出信号,正在关闭连接...")
|
|||
|
|
self.close()
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
def close(self):
|
|||
|
|
"""关闭连接"""
|
|||
|
|
try:
|
|||
|
|
if self.is_connected:
|
|||
|
|
self.xt_trader.stop()
|
|||
|
|
self.is_connected = False
|
|||
|
|
Logger.info("MiniQMT 连接已关闭")
|
|||
|
|
|
|||
|
|
wsclient = get_wsclient()
|
|||
|
|
if wsclient:
|
|||
|
|
wsclient.close()
|
|||
|
|
Logger.info("WebSocket 连接已关闭")
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
Logger.error(f"关闭连接异常: {e}")
|
|||
|
|
|
|||
|
|
def _connect(self) -> bool:
|
|||
|
|
"""
|
|||
|
|
连接 MiniQMT 交易接口
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
是否连接成功
|
|||
|
|
"""
|
|||
|
|
try:
|
|||
|
|
# 启动交易线程
|
|||
|
|
self.xt_trader.start()
|
|||
|
|
|
|||
|
|
# 建立交易连接
|
|||
|
|
connect_result = self.xt_trader.connect()
|
|||
|
|
if connect_result != 0:
|
|||
|
|
Logger.error(f"MiniQMT 连接失败: {connect_result}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
# 订阅账户推送
|
|||
|
|
subscribe_result = self.xt_trader.subscribe(self.account)
|
|||
|
|
if subscribe_result != 0:
|
|||
|
|
Logger.error(f"MiniQMT 订阅账户失败: {subscribe_result}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
self.is_connected = True
|
|||
|
|
Logger.info("MiniQMT 连接成功")
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
Logger.error(f"MiniQMT 连接异常: {e}")
|
|||
|
|
return False
|