fix: 批处理脚本注释改为REM,消除乱码和命令行报错

This commit is contained in:
cuizhan 2025-12-10 01:39:30 +08:00
parent 1fe879183a
commit 430660415f
9 changed files with 114 additions and 1696 deletions

View File

@ -4,9 +4,8 @@
统一管理所有服务的启动、停止和配置
"""
import asyncio
from enum import Enum
from typing import Any, Callable, Optional
from typing import Optional
from src.core.logger import get_logger
@ -329,15 +328,13 @@ class DataSyncService(Service):
self._service = None
async def start(self):
from src.qmt_service.services.data_sync_service import data_sync_service
self._service = data_sync_service
await data_sync_service.start()
# data_sync_service 已移除,如需数据同步请实现新服务或用 data_downloader 替代
self._service = None
pass
async def stop(self):
if self._service:
await self._service.stop()
self._service = None
pass
@property
def service(self):

View File

@ -67,22 +67,22 @@ async def run_service(service: dict):
await server.serve()
async def main():
"""主函数 - 启动所有服务"""
logger.info(f"QTrade {settings.app.version} 启动")
logger.info(f"环境: {settings.app.env}")
print("\n" + "=" * 50)
print("QTrade 量化交易系统")
print("=" * 50)
print("\n服务列表:")
for svc in SERVICES:
print(f" - {svc['name']}: http://{svc['host']}:{svc['port']}")
print("\n" + "=" * 50 + "\n")
# 并行启动所有服务
tasks = [run_service(svc) for svc in SERVICES]
await asyncio.gather(*tasks)
# async def main():
# """主函数 - 启动所有服务"""
# logger.info(f"QTrade {settings.app.version} 启动")
# logger.info(f"环境: {settings.app.env}")
#
# print("\n" + "=" * 50)
# print("QTrade 量化交易系统")
# print("=" * 50)
# print("\n服务列表:")
# for svc in SERVICES:
# print(f" - {svc['name']}: http://{svc['host']}:{svc['port']}")
# print("\n" + "=" * 50 + "\n")
#
# # 并行启动所有服务
# tasks = [run_service(svc) for svc in SERVICES]
# await asyncio.gather(*tasks)
def run_single(service_name: str):
@ -108,8 +108,5 @@ if __name__ == "__main__":
# 运行单个服务: python main.py DataService
run_single(sys.argv[1])
else:
# 运行所有服务
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n用户中断")
print("请指定要启动的服务名,如: python main.py QMTService")
print(f"可用服务: {[s['name'] for s in SERVICES]}")

View File

@ -2,9 +2,9 @@
QMT Service 应用入口
QMT 服务:
- 对接 XtQuant SDK
- 行情数据获取与推送
- 订单执行与回报处理
- 接收 QMT 客户端推送的 K 线数据
- 调用策略引擎计算交易信号
- 返回信号给 QMT 客户端执行
"""
from fastapi import FastAPI
@ -18,62 +18,23 @@ class QMTServiceApp(BaseApp):
name = "qmt_service"
title = "QTrade QMT Service"
description = "QMT 交易服务"
need_database = False # QMT 服务不需要数据库
def __init__(self):
super().__init__()
self._qmt_client = None
self._order_executor = None
self._quote_pusher = None
description = "QMT 交易服务 - 接收K线数据,返回交易信号"
need_database = True # 需要数据库存储成交记录等
async def on_startup(self):
"""启动 QMT 服务"""
from .services.qmt_client import qmt_client
from .services.order_executor import order_executor
from .services.quote_pusher import quote_pusher
self._qmt_client = qmt_client
self._order_executor = order_executor
self._quote_pusher = quote_pusher
# 连接 QMT
try:
await qmt_client.connect()
self.logger.info("QMT 客户端已连接")
except Exception as e:
self.logger.warning(f"QMT 客户端连接失败: {e}")
# 启动订单执行器
try:
await order_executor.start()
self.logger.info("订单执行器已启动")
except Exception as e:
self.logger.warning(f"订单执行器启动失败: {e}")
# 启动行情推送
try:
await quote_pusher.start()
self.logger.info("行情推送器已启动")
except Exception as e:
self.logger.warning(f"行情推送器启动失败: {e}")
"""启动服务"""
self.logger.info("QMT 服务已启动")
async def on_shutdown(self):
"""关闭 QMT 服务"""
if self._quote_pusher:
await self._quote_pusher.stop()
if self._order_executor:
await self._order_executor.stop()
if self._qmt_client:
await self._qmt_client.disconnect()
"""关闭服务"""
self.logger.info("QMT 服务已关闭")
def setup_routes(self, app: FastAPI):
"""注册路由"""
from .routes import quote, trade, account
from .routes import signal, trade
app.include_router(quote.router, prefix="/quote", tags=["行情"])
app.include_router(signal.router, prefix="/signal", tags=["信号"])
app.include_router(trade.router, prefix="/trade", tags=["交易"])
app.include_router(account.router, prefix="/account", tags=["账户"])
# 创建应用实例

View File

@ -1,480 +0,0 @@
"""
数据同步服务
后台服务,通过 Redis 接收命令,下载 K 线数据并保存
"""
import asyncio
import json
from datetime import datetime
from typing import Optional
from src.core.database import db
from src.core.logger import get_logger
from src.core.redis_client import redis_client, RedisKeys, RedisChannels
from src.core.service_manager import Service
from src.qmt_service.services.data_downloader import data_downloader, DataDownloadError
from src.core.models.kline import (
Kline1m,
Kline5m,
Kline15m,
Kline30m,
Kline60m,
Kline1d,
)
logger = get_logger("data_sync_service")
# 周期 -> 模型映射
PERIOD_MODEL_MAP = {
"1m": Kline1m,
"5m": Kline5m,
"15m": Kline15m,
"30m": Kline30m,
"60m": Kline60m,
"1d": Kline1d,
}
class DataSyncCommand:
"""数据同步命令"""
DOWNLOAD = "download" # 下载历史数据
REALTIME = "realtime" # 获取实时数据
STATUS = "status" # 查询服务状态
STOP = "stop" # 停止服务
class DataSyncService(Service):
"""
数据同步服务
功能:
- 监听 Redis 队列接收下载命令
- 调用 xtquant 下载 K 线数据
- 保存数据到 Redis 缓存
- 持久化到 MySQL 数据库
命令格式:
{
"cmd": "download",
"symbol": "159915.SZ", # 股票代码
"period": "1d", # K线周期
"start_date": "20241101", # 开始日期 (可选)
"end_date": "20241209", # 结束日期 (可选)
"days": 120, # 下载天数 (可选, 默认120)
"request_id": "xxx" # 请求ID (用于结果回调)
}
"""
def __init__(self, name: str = "data_sync", **config):
super().__init__(name, **config)
self._task: Optional[asyncio.Task] = None
self._running = False
self._stop_event = asyncio.Event()
async def start(self):
"""启动数据同步服务"""
if self._running:
logger.warning("数据同步服务已在运行")
return
# 初始化 xtquant 下载器
await data_downloader.init()
logger.info("xtquant 数据下载器已初始化")
# 启动后台任务
self._running = True
self._stop_event.clear()
self._task = asyncio.create_task(self._listen_queue())
logger.info("数据同步服务已启动,监听队列: %s", RedisKeys.DATA_DOWNLOAD_QUEUE)
async def stop(self):
"""停止数据同步服务"""
if not self._running:
return
logger.info("正在停止数据同步服务...")
self._running = False
self._stop_event.set()
# 发送停止命令到队列 (解除 BRPOP 阻塞)
await redis_client.lpush(
RedisKeys.DATA_DOWNLOAD_QUEUE, json.dumps({"cmd": DataSyncCommand.STOP})
)
if self._task:
try:
await asyncio.wait_for(self._task, timeout=5.0)
except asyncio.TimeoutError:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
self._task = None
logger.info("数据同步服务已停止")
async def _listen_queue(self):
"""监听 Redis 队列"""
while self._running:
try:
# 阻塞等待命令 (超时 5 秒)
result = await redis_client.brpop(
RedisKeys.DATA_DOWNLOAD_QUEUE, timeout=5
)
if result is None:
continue
key, message = result
try:
command = json.loads(message)
except json.JSONDecodeError:
logger.error(f"无效的 JSON 命令: {message}")
continue
cmd = command.get("cmd", "")
if cmd == DataSyncCommand.STOP:
logger.info("收到停止命令")
break
elif cmd == DataSyncCommand.DOWNLOAD:
await self._handle_download(command)
elif cmd == DataSyncCommand.REALTIME:
await self._handle_realtime(command)
elif cmd == DataSyncCommand.STATUS:
await self._handle_status(command)
else:
logger.warning(f"未知命令: {cmd}")
except Exception as e:
logger.error(f"处理命令异常: {e}")
await asyncio.sleep(1)
async def _handle_download(self, command: dict):
"""
处理下载命令
Args:
command: 命令参数
"""
symbol = command.get("symbol")
period = command.get("period", "1d")
start_date = command.get("start_date")
# end_date 默认为今天
end_date = command.get("end_date") or datetime.now().strftime("%Y%m%d")
days = command.get("days", 120)
request_id = command.get("request_id", "")
if not symbol:
await self._send_result(
request_id, False, "缺少 symbol 参数", command=command
)
return
if period not in PERIOD_MODEL_MAP:
await self._send_result(
request_id,
False,
f"不支持的周期: {period},支持: {list(PERIOD_MODEL_MAP.keys())}",
command=command,
)
return
logger.info(
f"[{request_id}] 开始下载: {symbol} {period} {start_date or f'近{days}天'}"
)
try:
# 下载数据
result = await data_downloader.download_history(
stocks=[symbol],
period=period,
start_date=start_date,
end_date=end_date,
days=days,
)
klines = result.get(symbol, [])
if not klines:
await self._send_result(
request_id, True, "无数据", count=0, command=command
)
return
# 保存到 Redis 缓存
await self._save_to_redis(symbol, period, klines)
# 保存到数据库
saved_count = await self._save_to_database(symbol, period, klines)
await self._send_result(
request_id,
True,
f"下载成功: {saved_count} 条",
count=saved_count,
command=command,
)
except DataDownloadError as e:
logger.error(f"[{request_id}] 下载失败: {e}")
await self._send_result(request_id, False, str(e), command=command)
except Exception as e:
logger.error(f"[{request_id}] 处理异常: {e}")
await self._send_result(request_id, False, str(e), command=command)
async def _handle_realtime(self, command: dict):
"""处理实时数据请求"""
symbol = command.get("symbol")
request_id = command.get("request_id", "")
if not symbol:
await self._send_result(
request_id, False, "缺少 symbol 参数", command=command
)
return
try:
symbols = [symbol] if isinstance(symbol, str) else symbol
result = await data_downloader.download_realtime(symbols)
await self._send_result(
request_id, True, "获取成功", data=result, command=command
)
except Exception as e:
logger.error(f"[{request_id}] 获取实时数据失败: {e}")
await self._send_result(request_id, False, str(e), command=command)
async def _handle_status(self, command: dict):
"""处理状态查询"""
request_id = command.get("request_id", "")
await self._send_result(
request_id,
True,
"服务运行中",
data={
"status": "running",
"queue": RedisKeys.DATA_DOWNLOAD_QUEUE,
"time": datetime.now().isoformat(),
},
command=command,
)
async def _save_to_redis(self, symbol: str, period: str, klines: list[dict]):
"""
保存 K 线数据到 Redis 缓存
Args:
symbol: 股票代码
period: K线周期
klines: K线数据列表
"""
if not klines:
return
# 缓存 Key: kline:{symbol}:{period}
cache_key = f"{RedisKeys.KLINE_PREFIX}{symbol}:{period}"
# 使用 Hash 存储, field 为时间, value 为 JSON
data = {k["time"]: json.dumps(k) for k in klines}
await redis_client.hset_dict(cache_key, data)
# 设置过期时间 (7 天)
await redis_client.expire(cache_key, 7 * 24 * 3600)
logger.debug(f"Redis 缓存: {cache_key}, {len(klines)} 条")
async def _save_to_database(
self, symbol: str, period: str, klines: list[dict]
) -> int:
"""
保存 K 线数据到数据库
Args:
symbol: 股票代码
period: K线周期
klines: K线数据列表
Returns:
保存的数据条数
"""
if not klines:
return 0
model_class = PERIOD_MODEL_MAP.get(period)
if not model_class:
logger.error(f"未知周期: {period}")
return 0
saved_count = 0
async with db.session() as session:
from sqlalchemy.dialects.mysql import insert
for kline in klines:
try:
# 解析时间
time_str = kline["time"]
if len(time_str) == 8: # YYYYMMDD
kline_time = datetime.strptime(time_str, "%Y%m%d")
elif len(time_str) == 14: # YYYYMMDDHHMMSS
kline_time = datetime.strptime(time_str, "%Y%m%d%H%M%S")
else:
# 尝试 ISO 格式
kline_time = datetime.fromisoformat(time_str.replace("Z", ""))
# 构建数据
data = {
"symbol": symbol,
"time": kline_time,
"open": kline["open"],
"high": kline["high"],
"low": kline["low"],
"close": kline["close"],
"volume": kline["volume"],
"amount": kline.get("amount", 0),
}
# 使用 INSERT ... ON DUPLICATE KEY UPDATE
stmt = insert(model_class).values(**data)
stmt = stmt.on_duplicate_key_update(
open=stmt.inserted.open,
high=stmt.inserted.high,
low=stmt.inserted.low,
close=stmt.inserted.close,
volume=stmt.inserted.volume,
amount=stmt.inserted.amount,
)
await session.execute(stmt)
saved_count += 1
except Exception as e:
logger.error(f"保存 K 线失败: {kline} - {e}")
await session.commit()
logger.info(f"数据库保存: {symbol} {period}, {saved_count} 条")
return saved_count
async def _send_result(
self,
request_id: str,
success: bool,
message: str,
**extra,
):
"""
发送结果通知
Args:
request_id: 请求ID
success: 是否成功
message: 消息
**extra: 额外数据
"""
result = {
"request_id": request_id,
"success": success,
"message": message,
"time": datetime.now().isoformat(),
**extra,
}
# 发布到结果通知频道
await redis_client.publish(
RedisChannels.DATA_DOWNLOAD_RESULT, json.dumps(result)
)
logger.debug(f"结果通知: {result}")
# 便捷函数
async def send_download_command(
symbol: str,
period: str = "1d",
start_date: Optional[str] = None,
end_date: Optional[str] = None,
days: int = 120,
request_id: Optional[str] = None,
) -> str:
"""
发送下载命令到队列
Args:
symbol: 股票代码
period: K线周期
start_date: 开始日期 (格式: YYYYMMDD)
end_date: 结束日期 (格式: YYYYMMDD, 默认今天)
days: 下载天数 (start_date 未指定时使用)
request_id: 请求ID (不传则自动生成)
Returns:
request_id
"""
if request_id is None:
request_id = f"dl_{datetime.now().strftime('%Y%m%d%H%M%S%f')}"
# end_date 默认为今天
if end_date is None:
end_date = datetime.now().strftime("%Y%m%d")
command = {
"cmd": DataSyncCommand.DOWNLOAD,
"symbol": symbol,
"period": period,
"end_date": end_date,
"days": days,
"request_id": request_id,
}
if start_date:
command["start_date"] = start_date
await redis_client.lpush(RedisKeys.DATA_DOWNLOAD_QUEUE, json.dumps(command))
logger.info(f"发送下载命令: {command}")
return request_id
async def send_realtime_command(
symbol: str | list[str],
request_id: Optional[str] = None,
) -> str:
"""
发送实时数据命令
Args:
symbol: 股票代码 (单个或列表)
request_id: 请求ID
Returns:
request_id
"""
if request_id is None:
request_id = f"rt_{datetime.now().strftime('%Y%m%d%H%M%S%f')}"
command = {
"cmd": DataSyncCommand.REALTIME,
"symbol": symbol,
"request_id": request_id,
}
await redis_client.lpush(RedisKeys.DATA_DOWNLOAD_QUEUE, json.dumps(command))
return request_id
# 单例
data_sync_service = DataSyncService()

View File

@ -1,216 +0,0 @@
"""
订单执行器 - Order Executor
监听 Redis 订单通道,通过 QMT 执行订单
"""
import asyncio
import json
from src.core.redis_client import redis_client
from src.core.logger import get_logger
from .qmt_client import qmt_client
logger = get_logger(__name__)
class OrderExecutor:
"""订单执行器
监听订单创建和撤销事件,通过 QMT 执行
"""
def __init__(self) -> None:
self._running = False
self._task: asyncio.Task | None = None
self._pending_orders: dict[str, dict] = {}
@property
def is_running(self) -> bool:
"""是否运行中"""
return self._running
@property
def pending_orders(self) -> dict[str, dict]:
"""待处理订单"""
return self._pending_orders
async def start(self) -> None:
"""启动订单执行器"""
if self._running:
return
self._running = True
self._task = asyncio.create_task(self._run())
logger.info("订单执行器已启动")
async def stop(self) -> None:
"""停止订单执行器"""
self._running = False
if self._task:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
logger.info("订单执行器已停止")
async def _run(self) -> None:
"""运行主循环"""
# 订阅多个通道
channels = ["order:created", "order:cancelled"]
while self._running:
try:
async with redis_client.subscribe(*channels) as pubsub: # type: ignore
async for message in pubsub.listen(): # type: ignore
if not self._running:
break
if message["type"] != "message":
continue
channel = message["channel"]
try:
data = json.loads(message["data"])
except json.JSONDecodeError:
continue
if channel == "order:created":
await self._handle_order_created(data)
elif channel == "order:cancelled":
await self._handle_order_cancelled(data)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"订单执行器异常: {e}")
await asyncio.sleep(1)
async def _handle_order_created(self, data: dict) -> None:
"""处理订单创建
Args:
data: 订单数据
"""
logger.info(f"收到新订单: {data}")
order_id = data.get("order_id", "")
code = data.get("code", "")
direction = data.get("direction", "buy")
quantity = data.get("quantity", 0)
price = data.get("price")
order_type = data.get("order_type", "limit")
if not code or not quantity:
logger.warning(f"无效订单数据: {data}")
return
# 记录待处理订单
self._pending_orders[order_id] = data
try:
# 通过 QMT 下单
result = await qmt_client.place_order(
code=code,
direction=direction,
quantity=quantity,
price=price,
order_type=order_type,
)
if result.get("success"):
qmt_order_id = result.get("order_id", "")
# 发布订单提交成功事件
await redis_client.publish(
"order:submitted",
{
"order_id": order_id,
"qmt_order_id": qmt_order_id,
"status": "submitted",
},
)
# 更新待处理订单
self._pending_orders[order_id]["qmt_order_id"] = qmt_order_id
self._pending_orders[order_id]["status"] = "submitted"
logger.info(f"订单已提交: {order_id} -> {qmt_order_id}")
else:
error = result.get("error", "未知错误")
# 发布订单失败事件
await redis_client.publish(
"order:rejected",
{
"order_id": order_id,
"status": "rejected",
"error": error,
},
)
# 移除待处理订单
self._pending_orders.pop(order_id, None)
logger.error(f"订单提交失败: {order_id}, 原因: {error}")
except Exception as e:
logger.error(f"订单执行异常: {e}")
await redis_client.publish(
"order:rejected",
{
"order_id": order_id,
"status": "rejected",
"error": str(e),
},
)
async def _handle_order_cancelled(self, data: dict) -> None:
"""处理订单撤销
Args:
data: 撤销数据
"""
logger.info(f"收到撤单请求: {data}")
order_id = data.get("order_id", "")
# 获取 QMT 订单 ID
pending = self._pending_orders.get(order_id, {})
qmt_order_id = pending.get("qmt_order_id") or data.get("qmt_order_id", "")
if not qmt_order_id:
logger.warning(f"找不到对应的 QMT 订单: {order_id}")
return
try:
# 通过 QMT 撤单
result = await qmt_client.cancel_order(qmt_order_id)
if result.get("success"):
# 发布撤单成功事件
await redis_client.publish(
"order:cancel_success",
{
"order_id": order_id,
"qmt_order_id": qmt_order_id,
"status": "cancelled",
},
)
# 移除待处理订单
self._pending_orders.pop(order_id, None)
logger.info(f"撤单成功: {order_id}")
else:
error = result.get("error", "未知错误")
logger.error(f"撤单失败: {order_id}, 原因: {error}")
except Exception as e:
logger.error(f"撤单异常: {e}")
# 全局单例
order_executor = OrderExecutor()

View File

@ -1,663 +0,0 @@
"""
QMT Client - XtQuant SDK 封装
QMT (迅投量化终端) 客户端
负责与 XtQuant 交互,提供行情和交易接口
"""
from datetime import datetime
from typing import Any
from src.core.logger import get_logger
from src.core.config import settings
logger = get_logger(__name__)
class QMTClient:
"""QMT 客户端封装类
封装 XtQuant SDK,提供异步接口
注意:XtQuant 需要 Python 3.6 环境,实际使用时需要在独立进程中运行
"""
def __init__(self) -> None:
self._connected = False
self._xt_trader = None
self._xt_quote = None
self._account_id: str | None = None
self._callbacks: dict[str, list[Any]] = {}
self._simulation_mode = True # 模拟模式,用于测试
@property
def is_connected(self) -> bool:
"""是否已连接"""
return self._connected
async def connect(self) -> bool:
"""连接 QMT
Returns:
是否连接成功
"""
logger.info("正在连接 QMT...")
try:
# 检查是否启用模拟模式
if settings.qmt.simulation:
logger.info("QMT 配置为模拟模式")
self._simulation_mode = True
self._connected = True
return True
# 尝试导入 XtQuant
try:
from xtquant import xttrader # type: ignore # noqa: F401
from xtquant.xttrader import XtQuantTrader # type: ignore
from xtquant.xttype import StockAccount # type: ignore
self._simulation_mode = False
logger.info("XtQuant SDK 已加载")
except ImportError:
logger.warning("XtQuant SDK 未安装,使用模拟模式")
self._simulation_mode = True
self._connected = True
return True
# 从配置读取 QMT 参数
path = settings.qmt.path
session_id = settings.qmt.session_id
account_id = settings.qmt.account_id
if not path or not account_id:
logger.warning("QMT 路径或账号未配置,使用模拟模式")
self._simulation_mode = True
self._connected = True
return True
# 创建交易对象
self._xt_trader = XtQuantTrader(path, session_id)
# 创建账户对象
account = StockAccount(account_id)
self._account_id = account_id
# 启动交易线程
self._xt_trader.start()
# 连接
connect_result = self._xt_trader.connect()
if connect_result != 0:
logger.error(f"QMT 连接失败: {connect_result}")
return False
# 订阅账户
subscribe_result = self._xt_trader.subscribe(account)
if subscribe_result != 0:
logger.error(f"账户订阅失败: {subscribe_result}")
return False
self._connected = True
logger.info(f"QMT 连接成功,账户: {account_id}")
return True
except Exception as e:
logger.error(f"QMT 连接异常: {e}")
# 降级到模拟模式
self._simulation_mode = True
self._connected = True
return True
async def disconnect(self) -> None:
"""断开连接"""
logger.info("断开 QMT 连接...")
if self._xt_trader and not self._simulation_mode:
self._xt_trader.stop()
self._connected = False
logger.info("QMT 已断开")
async def get_tick(self, code: str) -> dict | None:
"""获取最新 Tick
Args:
code: 股票代码
Returns:
Tick 数据
"""
if self._simulation_mode:
return self._mock_tick(code)
try:
from xtquant import xtdata # type: ignore
tick = xtdata.get_full_tick([code])
if tick and code in tick:
data = tick[code]
return {
"code": code,
"time": datetime.now().isoformat(),
"price": data.get("lastPrice", 0),
"open": data.get("open", 0),
"high": data.get("high", 0),
"low": data.get("low", 0),
"volume": data.get("volume", 0),
"amount": data.get("amount", 0),
"bid_price": data.get("bidPrice", [0] * 5),
"bid_volume": data.get("bidVol", [0] * 5),
"ask_price": data.get("askPrice", [0] * 5),
"ask_volume": data.get("askVol", [0] * 5),
}
except Exception as e:
logger.error(f"获取 Tick 失败: {e}")
return None
async def get_kline(
self, code: str, period: str = "1d", count: int = 100
) -> list[dict]:
"""获取 K 线数据
Args:
code: 股票代码
period: K线周期
count: 获取数量
Returns:
K线数据列表
"""
if self._simulation_mode:
return self._mock_klines(code, count)
try:
from xtquant import xtdata # type: ignore
# 周期映射
period_map = {
"1m": "1m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"60m": "60m",
"1d": "1d",
"1w": "1w",
"1M": "1m",
}
xt_period = period_map.get(period, "1d")
# 获取数据
data = xtdata.get_market_data(
stock_list=[code],
period=xt_period,
count=count,
)
if data and code in data:
klines = []
for i, row in enumerate(data[code]):
klines.append(
{
"time": row.get("time", ""),
"open": row.get("open", 0),
"high": row.get("high", 0),
"low": row.get("low", 0),
"close": row.get("close", 0),
"volume": row.get("volume", 0),
"amount": row.get("amount", 0),
}
)
return klines
except Exception as e:
logger.error(f"获取 K 线失败: {e}")
return []
async def place_order(
self,
code: str,
direction: str,
quantity: int,
price: float | None = None,
order_type: str = "limit",
) -> dict:
"""下单
Args:
code: 股票代码
direction: 买卖方向 buy/sell
quantity: 数量
price: 价格
order_type: 订单类型 limit/market
Returns:
下单结果
"""
if self._simulation_mode:
return self._mock_place_order(code, direction, quantity, price)
try:
from xtquant.xttype import StockAccount # type: ignore
from xtquant import xtconstant # type: ignore
if not self._xt_trader or not self._account_id:
return {"success": False, "error": "未连接 QMT"}
account = StockAccount(self._account_id)
# 方向映射
if direction == "buy":
order_side = xtconstant.STOCK_BUY
else:
order_side = xtconstant.STOCK_SELL
# 订单类型
if order_type == "market":
price_type = xtconstant.FIX_PRICE # type: ignore
price = 0
else:
price_type = xtconstant.FIX_PRICE # type: ignore
# 下单
result = self._xt_trader.order_stock(
account=account,
stock_code=code,
order_type=order_side,
order_volume=quantity,
price_type=price_type,
price=price or 0,
)
if result > 0:
return {
"success": True,
"order_id": str(result),
"code": code,
"direction": direction,
"quantity": quantity,
"price": price,
}
else:
return {"success": False, "error": f"下单失败: {result}"}
except Exception as e:
logger.error(f"下单异常: {e}")
return {"success": False, "error": str(e)}
async def cancel_order(self, order_id: str) -> dict:
"""撤单
Args:
order_id: 订单 ID
Returns:
撤单结果
"""
if self._simulation_mode:
return {"success": True, "order_id": order_id, "message": "模拟撤单成功"}
try:
from xtquant.xttype import StockAccount # type: ignore
if not self._xt_trader or not self._account_id:
return {"success": False, "error": "未连接 QMT"}
account = StockAccount(self._account_id)
result = self._xt_trader.cancel_order_stock(account, int(order_id))
if result == 0:
return {"success": True, "order_id": order_id}
else:
return {"success": False, "error": f"撤单失败: {result}"}
except Exception as e:
logger.error(f"撤单异常: {e}")
return {"success": False, "error": str(e)}
async def get_orders(self) -> list[dict]:
"""获取当日委托
Returns:
委托列表
"""
if self._simulation_mode:
return self._mock_orders()
try:
from xtquant.xttype import StockAccount # type: ignore
if not self._xt_trader or not self._account_id:
return []
account = StockAccount(self._account_id)
orders = self._xt_trader.query_stock_orders(account)
return [
{
"order_id": str(o.order_id),
"code": o.stock_code,
"direction": "buy" if o.order_type == 23 else "sell",
"quantity": o.order_volume,
"price": o.price,
"filled_quantity": o.traded_volume,
"status": self._map_order_status(o.order_status),
"create_time": o.order_time,
}
for o in orders
]
except Exception as e:
logger.error(f"获取委托失败: {e}")
return []
async def get_trades(self) -> list[dict]:
"""获取当日成交
Returns:
成交列表
"""
if self._simulation_mode:
return self._mock_trades()
try:
from xtquant.xttype import StockAccount # type: ignore
if not self._xt_trader or not self._account_id:
return []
account = StockAccount(self._account_id)
trades = self._xt_trader.query_stock_trades(account)
return [
{
"trade_id": str(t.traded_id),
"order_id": str(t.order_id),
"code": t.stock_code,
"direction": "buy" if t.order_type == 23 else "sell",
"quantity": t.traded_volume,
"price": t.traded_price,
"amount": t.traded_amount,
"trade_time": t.traded_time,
}
for t in trades
]
except Exception as e:
logger.error(f"获取成交失败: {e}")
return []
async def get_balance(self) -> dict:
"""获取账户资金
Returns:
资金信息
"""
if self._simulation_mode:
return self._mock_balance()
try:
from xtquant.xttype import StockAccount # type: ignore
if not self._xt_trader or not self._account_id:
return {}
account = StockAccount(self._account_id)
asset = self._xt_trader.query_stock_asset(account)
if asset:
return {
"account_id": self._account_id,
"total_asset": asset.total_asset,
"cash": asset.cash,
"market_value": asset.market_value,
"frozen": asset.frozen_cash,
"available": asset.cash - asset.frozen_cash,
}
except Exception as e:
logger.error(f"获取资金失败: {e}")
return {}
async def get_positions(self) -> list[dict]:
"""获取持仓列表
Returns:
持仓列表
"""
if self._simulation_mode:
return self._mock_positions()
try:
from xtquant.xttype import StockAccount # type: ignore
if not self._xt_trader or not self._account_id:
return []
account = StockAccount(self._account_id)
positions = self._xt_trader.query_stock_positions(account)
return [
{
"code": p.stock_code,
"name": p.stock_name,
"quantity": p.volume,
"available": p.can_use_volume,
"frozen": p.frozen_volume,
"cost_price": p.open_price,
"market_value": p.market_value,
"profit": p.profit,
"profit_ratio": p.profit / p.market_value if p.market_value else 0,
}
for p in positions
]
except Exception as e:
logger.error(f"获取持仓失败: {e}")
return []
async def get_position(self, code: str) -> dict:
"""获取单只股票持仓
Args:
code: 股票代码
Returns:
持仓信息
"""
positions = await self.get_positions()
for pos in positions:
if pos["code"] == code:
return pos
return {"code": code, "quantity": 0, "available": 0}
def register_callback(self, event: str, callback: Any) -> None:
"""注册回调
Args:
event: 事件名称
callback: 回调函数
"""
if event not in self._callbacks:
self._callbacks[event] = []
self._callbacks[event].append(callback)
def _map_order_status(self, status: int) -> str:
"""映射订单状态"""
status_map = {
48: "pending", # 未报
49: "pending", # 待报
50: "submitted", # 已报
51: "partial", # 部分成交
52: "filled", # 全部成交
53: "cancelled", # 已撤
54: "rejected", # 废单
56: "cancelling", # 撤单中
}
return status_map.get(status, "unknown")
# ========== 模拟数据 ==========
def _mock_tick(self, code: str) -> dict:
"""模拟 Tick 数据"""
import random
base_price = 10.0 if code.startswith("60") else 15.0
price = base_price * (1 + random.uniform(-0.02, 0.02))
return {
"code": code,
"time": datetime.now().isoformat(),
"price": round(price, 2),
"open": round(base_price, 2),
"high": round(price * 1.02, 2),
"low": round(price * 0.98, 2),
"volume": random.randint(100000, 1000000),
"amount": random.randint(1000000, 10000000),
"bid_price": [round(price - 0.01 * i, 2) for i in range(5)],
"bid_volume": [random.randint(100, 1000) * 100 for _ in range(5)],
"ask_price": [round(price + 0.01 * (i + 1), 2) for i in range(5)],
"ask_volume": [random.randint(100, 1000) * 100 for _ in range(5)],
}
def _mock_klines(self, code: str, count: int) -> list[dict]:
"""模拟 K 线数据"""
import random
klines = []
base_price = 10.0 if code.startswith("60") else 15.0
price = base_price
for i in range(count):
change = random.uniform(-0.03, 0.03)
open_price = price
close_price = price * (1 + change)
high_price = max(open_price, close_price) * (1 + random.uniform(0, 0.01))
low_price = min(open_price, close_price) * (1 - random.uniform(0, 0.01))
klines.append(
{
"time": f"2024-01-{(count - i):02d}",
"open": round(open_price, 2),
"high": round(high_price, 2),
"low": round(low_price, 2),
"close": round(close_price, 2),
"volume": random.randint(100000, 1000000),
"amount": random.randint(1000000, 10000000),
}
)
price = close_price
return klines[::-1] # 时间正序
def _mock_place_order(
self, code: str, direction: str, quantity: int, price: float | None
) -> dict:
"""模拟下单"""
import uuid
order_id = str(uuid.uuid4())[:8]
return {
"success": True,
"order_id": order_id,
"code": code,
"direction": direction,
"quantity": quantity,
"price": price or 10.0,
"message": "模拟下单成功",
}
def _mock_orders(self) -> list[dict]:
"""模拟委托列表"""
return [
{
"order_id": "ORD001",
"code": "000001.SZ",
"direction": "buy",
"quantity": 1000,
"price": 10.50,
"filled_quantity": 500,
"status": "partial",
"create_time": "09:35:00",
},
{
"order_id": "ORD002",
"code": "600000.SH",
"direction": "sell",
"quantity": 500,
"price": 8.20,
"filled_quantity": 500,
"status": "filled",
"create_time": "09:40:00",
},
]
def _mock_trades(self) -> list[dict]:
"""模拟成交列表"""
return [
{
"trade_id": "TRD001",
"order_id": "ORD001",
"code": "000001.SZ",
"direction": "buy",
"quantity": 500,
"price": 10.50,
"amount": 5250.0,
"trade_time": "09:35:30",
},
{
"trade_id": "TRD002",
"order_id": "ORD002",
"code": "600000.SH",
"direction": "sell",
"quantity": 500,
"price": 8.20,
"amount": 4100.0,
"trade_time": "09:40:15",
},
]
def _mock_balance(self) -> dict:
"""模拟资金数据"""
return {
"account_id": "MOCK_ACCOUNT",
"total_asset": 1000000.0,
"cash": 500000.0,
"market_value": 500000.0,
"frozen": 10000.0,
"available": 490000.0,
}
def _mock_positions(self) -> list[dict]:
"""模拟持仓数据"""
return [
{
"code": "000001.SZ",
"name": "平安银行",
"quantity": 10000,
"available": 10000,
"frozen": 0,
"cost_price": 10.00,
"market_value": 105000.0,
"profit": 5000.0,
"profit_ratio": 0.05,
},
{
"code": "600000.SH",
"name": "浦发银行",
"quantity": 5000,
"available": 5000,
"frozen": 0,
"cost_price": 8.00,
"market_value": 41000.0,
"profit": 1000.0,
"profit_ratio": 0.025,
},
]
# 全局单例
qmt_client = QMTClient()

View File

@ -1,257 +0,0 @@
"""
行情推送器 - Quote Pusher
订阅 QMT 行情并推送到 Redis
"""
import asyncio
from datetime import datetime
from src.core.redis_client import redis_client
from src.core.logger import get_logger
from .qmt_client import qmt_client
logger = get_logger(__name__)
class QuotePusher:
"""行情推送器
订阅 QMT 行情数据,实时推送到 Redis
"""
def __init__(self) -> None:
self._running = False
self._task: asyncio.Task | None = None
self._subscribed_codes: set[str] = set()
self._push_interval: float = 0.5 # 推送间隔(秒)
@property
def subscribed_codes(self) -> set[str]:
"""已订阅的股票代码"""
return self._subscribed_codes
async def start(self) -> None:
"""启动行情推送"""
if self._running:
return
self._running = True
self._task = asyncio.create_task(self._run())
logger.info("行情推送器已启动")
async def stop(self) -> None:
"""停止行情推送"""
self._running = False
if self._task:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
logger.info("行情推送器已停止")
async def subscribe(self, codes: list[str]) -> None:
"""订阅股票行情
Args:
codes: 股票代码列表
"""
self._subscribed_codes.update(codes)
logger.info(f"新增订阅: {codes}, 当前订阅数量: {len(self._subscribed_codes)}")
# 如果有 XtQuant 实现,这里可以调用 xtdata.subscribe_quote
# xtdata.subscribe_quote(codes, period='tick', start_time='', end_time='', count=1, callback=self._on_tick)
async def unsubscribe(self, codes: list[str]) -> None:
"""取消订阅
Args:
codes: 股票代码列表
"""
for code in codes:
self._subscribed_codes.discard(code)
logger.info(f"取消订阅: {codes}, 当前订阅数量: {len(self._subscribed_codes)}")
# xtdata.unsubscribe_quote(codes)
async def _run(self) -> None:
"""运行主循环"""
while self._running:
try:
if self._subscribed_codes:
await self._push_ticks()
await asyncio.sleep(self._push_interval)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"行情推送异常: {e}")
await asyncio.sleep(1)
async def _push_ticks(self) -> None:
"""推送 Tick 数据"""
for code in list(self._subscribed_codes):
try:
tick = await qmt_client.get_tick(code)
if tick:
# 推送到 Redis
channel = f"tick:{code}"
await redis_client.publish(channel, tick)
# 缓存最新价格
cache_key = f"price:{code}"
await redis_client.set_json(
cache_key,
{
"code": code,
"price": tick["price"],
"time": tick["time"],
},
ex=60, # 60 秒过期
)
except Exception as e:
logger.error(f"推送 {code} 行情失败: {e}")
class TradeReportPusher:
"""成交回报推送器
监听 QMT 成交回报,推送到 Redis
"""
def __init__(self) -> None:
self._running = False
self._task: asyncio.Task | None = None
self._last_check_time: datetime | None = None
self._check_interval: float = 1.0 # 检查间隔(秒)
self._processed_trades: set[str] = set()
async def start(self) -> None:
"""启动成交回报推送"""
if self._running:
return
self._running = True
self._task = asyncio.create_task(self._run())
logger.info("成交回报推送器已启动")
async def stop(self) -> None:
"""停止成交回报推送"""
self._running = False
if self._task:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
logger.info("成交回报推送器已停止")
async def _run(self) -> None:
"""运行主循环"""
while self._running:
try:
await self._check_trades()
await asyncio.sleep(self._check_interval)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"成交回报检查异常: {e}")
await asyncio.sleep(1)
async def _check_trades(self) -> None:
"""检查新成交"""
trades = await qmt_client.get_trades()
for trade in trades:
trade_id = trade.get("trade_id", "")
# 跳过已处理的成交
if trade_id in self._processed_trades:
continue
# 推送成交回报
await redis_client.publish("trade:report", trade)
# 记录已处理
self._processed_trades.add(trade_id)
logger.info(f"新成交: {trade}")
# 清理过多的已处理记录
if len(self._processed_trades) > 10000:
self._processed_trades.clear()
class AccountSyncer:
"""账户同步器
定时同步账户数据到 Redis
"""
def __init__(self) -> None:
self._running = False
self._task: asyncio.Task | None = None
self._sync_interval: float = 5.0 # 同步间隔(秒)
async def start(self) -> None:
"""启动账户同步"""
if self._running:
return
self._running = True
self._task = asyncio.create_task(self._run())
logger.info("账户同步器已启动")
async def stop(self) -> None:
"""停止账户同步"""
self._running = False
if self._task:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
logger.info("账户同步器已停止")
async def _run(self) -> None:
"""运行主循环"""
while self._running:
try:
await self._sync()
await asyncio.sleep(self._sync_interval)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"账户同步异常: {e}")
await asyncio.sleep(1)
async def _sync(self) -> None:
"""同步账户数据"""
# 同步资金
balance = await qmt_client.get_balance()
if balance:
await redis_client.publish("account:balance", balance)
await redis_client.set_json("account:balance:cache", balance, ex=60)
# 同步持仓
positions = await qmt_client.get_positions()
if positions:
await redis_client.publish("position:sync", {"positions": positions})
await redis_client.set_json("account:positions:cache", positions, ex=60)
# 全局单例
quote_pusher = QuotePusher()
trade_report_pusher = TradeReportPusher()
account_syncer = AccountSyncer()

View File

@ -1,3 +1,62 @@
from typing import Any, Optional
from fastapi import Body, APIRouter, Query, HTTPException
from pydantic import BaseModel, Field
router = APIRouter()
class CalculateRequest(BaseModel):
pairing_id: Optional[str] = Field(None, description="配对ID,可选")
symbol: Optional[str] = Field(None, description="股票代码,可选")
strategy_id: Optional[str] = Field(None, description="策略ID,可选")
@router.post("/calculate")
async def calculate_signals(
req: CalculateRequest = Body(..., description="筛选条件,可选"),
) -> dict[str, Any]:
"""
批量同步检测策略信号,返回每个实例的信号结果
"""
try:
from ..services.strategy_executor import strategy_executor
instances = strategy_executor._instances.values()
results = []
for instance in instances:
if req.pairing_id and instance.pairing_id != req.pairing_id:
continue
if req.symbol and instance.symbol != req.symbol:
continue
if req.strategy_id and instance.strategy_id != req.strategy_id:
continue
try:
signals = instance.strategy.get_signals()
signals_data = [s.dict() if hasattr(s, "dict") else s for s in signals]
except Exception as e:
signals_data = []
logger.error(f"信号检测异常: {instance.pairing_id} - {e}")
results.append(
{
"pairing_id": instance.pairing_id,
"symbol": instance.symbol,
"strategy_id": instance.strategy_id,
"signals": signals_data,
}
)
return {
"code": 0,
"message": "success",
"data": {
"items": results,
"total": len(results),
},
}
except Exception as e:
logger.error(f"批量信号检测失败: {e}")
raise HTTPException(status_code=500, detail=str(e))
"""
策略管理路由

20
start_all_services.bat Normal file
View File

@ -0,0 +1,20 @@
@echo off
REM QTrade 一键启动脚本
REM 使用方法:双击或命令行运行 start_all_services.bat
@echo off
setlocal
set ROOT=%~dp0
cd /d %ROOT%
cd src
start "DataService" cmd /k "python main.py DataService"
start "CoreService" cmd /k "python main.py CoreService"
start "QMTService" cmd /k "python main.py QMTService"
start "StrategyEngine" cmd /k "python main.py StrategyEngine"
echo 所有服务已在独立窗口启动。
pause