diff --git a/src/qmt_service/routes/account.py b/src/qmt_service/routes/account.py deleted file mode 100644 index e171012..0000000 --- a/src/qmt_service/routes/account.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -账户相关路由 -""" - -from fastapi import APIRouter - -from ..services.qmt_client import qmt_client - -router = APIRouter() - - -@router.get("/balance") -async def get_balance() -> dict: - """获取账户资金""" - balance = await qmt_client.get_balance() - return balance - - -@router.get("/positions") -async def get_positions() -> dict: - """获取持仓列表""" - positions = await qmt_client.get_positions() - return {"count": len(positions), "positions": positions} - - -@router.get("/position/{code}") -async def get_position(code: str) -> dict: - """获取单只股票持仓 - - Args: - code: 股票代码 - """ - position = await qmt_client.get_position(code) - return position - - -@router.post("/sync") -async def sync_account() -> dict: - """同步账户数据到 Redis""" - # 同步资金 - balance = await qmt_client.get_balance() - from src.core.redis_client import redis_client - - await redis_client.publish("account:balance", balance) - - # 同步持仓 - positions = await qmt_client.get_positions() - await redis_client.publish("position:sync", {"positions": positions}) - - return {"success": True, "message": "账户数据已同步"} diff --git a/src/qmt_service/routes/quote.py b/src/qmt_service/routes/quote.py deleted file mode 100644 index 43d17b5..0000000 --- a/src/qmt_service/routes/quote.py +++ /dev/null @@ -1,70 +0,0 @@ -""" -行情相关路由 -""" - -from fastapi import APIRouter, Query - -from ..services.qmt_client import qmt_client -from ..services.quote_pusher import quote_pusher - -router = APIRouter() - - -@router.get("/status") -async def quote_status() -> dict: - """获取行情服务状态""" - return { - "connected": qmt_client.is_connected, - "subscribed_count": len(quote_pusher.subscribed_codes), - "subscribed_codes": list(quote_pusher.subscribed_codes)[:50], # 最多显示50个 - } - - -@router.post("/subscribe") -async def subscribe(codes: list[str]) -> dict: - """订阅行情 - - Args: - codes: 股票代码列表,如 ["000001.SZ", "600000.SH"] - """ - await quote_pusher.subscribe(codes) - return {"success": True, "message": f"已订阅 {len(codes)} 只股票"} - - -@router.post("/unsubscribe") -async def unsubscribe(codes: list[str]) -> dict: - """取消订阅 - - Args: - codes: 股票代码列表 - """ - await quote_pusher.unsubscribe(codes) - return {"success": True, "message": f"已取消订阅 {len(codes)} 只股票"} - - -@router.get("/tick/{code}") -async def get_tick(code: str) -> dict: - """获取最新 Tick - - Args: - code: 股票代码,如 "000001.SZ" - """ - tick = await qmt_client.get_tick(code) - return {"code": code, "tick": tick} - - -@router.get("/kline/{code}") -async def get_kline( - code: str, - period: str = Query("1d", description="周期:1m/5m/15m/30m/60m/1d/1w/1M"), - count: int = Query(100, description="获取数量", le=1000), -) -> dict: - """获取 K 线数据 - - Args: - code: 股票代码 - period: K线周期 - count: 获取数量 - """ - klines = await qmt_client.get_kline(code, period, count) - return {"code": code, "period": period, "count": len(klines), "data": klines} diff --git a/src/qmt_service/routes/signal.py b/src/qmt_service/routes/signal.py new file mode 100644 index 0000000..69ec27f --- /dev/null +++ b/src/qmt_service/routes/signal.py @@ -0,0 +1,125 @@ +""" +信号检测路由 + +接收 QMT 客户端推送的 K 线数据,调用策略引擎计算信号 +""" + +from typing import Any +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel +import httpx + +from src.core.config import settings +from src.core.logger import get_logger + +logger = get_logger(__name__) +router = APIRouter() + + +class KLineData(BaseModel): + """K 线数据""" + + code: str # 股票代码 + datetime: str # 时间 YYYYMMDDHHMMSS + period: str # 周期 1m/5m/1d + open: float + high: float + low: float + close: float + volume: int + amount: float + + +class AccountInfo(BaseModel): + """账户信息""" + + Balance: float # 总资产 + available: float # 可用资金 + + +class PositionInfo(BaseModel): + """持仓信息""" + + code: str + volume: int # 持仓数量 + canUseVolume: int # 可用数量 + price: float # 成本价 + profit: float # 浮动盈亏 + profitRate: float # 收益率 + + +class SignalDetectRequest(BaseModel): + """信号检测请求""" + + realTime: str # 当前时间 YYYYMMDDHHMMSS + kdata: list[KLineData] # K 线数据列表 + account: AccountInfo # 账户信息 + positionInfos: list[PositionInfo] # 持仓列表 + allowTrade: bool = True # 是否允许交易 + + +class SignalResponse(BaseModel): + """单个股票的信号响应""" + + direction: int # 48=买入, 49=卖出, 51=加仓, 52=减仓, 0=无操作 + volume: int # 交易数量 + limit: float # 资金比例限制 + + +@router.post("/detect") +async def detect_signal(request: SignalDetectRequest) -> dict[str, Any]: + """ + 检测交易信号 + + 接收 QMT 客户端推送的 K 线数据,同步调用策略引擎计算信号 + + Args: + request: 包含 K 线数据、账户信息、持仓信息的请求 + + Returns: + 各股票的交易信号 + """ + logger.info( + f"收到信号检测请求: realTime={request.realTime}, " + f"kdata_count={len(request.kdata)}, " + f"positions={len(request.positionInfos)}" + ) + + # 调用策略引擎 + strategy_engine_url = ( + f"http://{settings.services.strategy_engine.host}" + f":{settings.services.strategy_engine.port}" + "/strategy/calculate" + ) + + try: + async with httpx.AsyncClient(timeout=30.0) as client: + response = await client.post( + strategy_engine_url, + json=request.model_dump(), + ) + response.raise_for_status() + signals = response.json() + + logger.info(f"策略引擎返回信号: {len(signals)} 个股票") + return signals + + except httpx.TimeoutException: + logger.error("策略引擎请求超时") + raise HTTPException(status_code=504, detail="策略引擎请求超时") + except httpx.HTTPStatusError as e: + logger.error(f"策略引擎返回错误: {e.response.status_code}") + raise HTTPException(status_code=502, detail=f"策略引擎错误: {e.response.text}") + except Exception as e: + logger.error(f"信号检测失败: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/status") +async def signal_status() -> dict: + """获取信号服务状态""" + return { + "service": "qmt_service", + "status": "running", + "strategy_engine": f"{settings.services.strategy_engine.host}:{settings.services.strategy_engine.port}", + } diff --git a/src/qmt_service/routes/trade.py b/src/qmt_service/routes/trade.py index facc002..7a3b5e3 100644 --- a/src/qmt_service/routes/trade.py +++ b/src/qmt_service/routes/trade.py @@ -1,72 +1,104 @@ """ 交易相关路由 + +处理成交同步、股票池管理等 """ -from fastapi import APIRouter +from datetime import datetime +from typing import Any -from ..services.qmt_client import qmt_client -from ..services.order_executor import order_executor +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel +from sqlalchemy import select +from src.core.database import db +from src.core.logger import get_logger + +logger = get_logger(__name__) router = APIRouter() -@router.get("/status") -async def trade_status() -> dict: - """获取交易状态""" +class DealSyncRequest(BaseModel): + """成交同步请求""" + + dealPrice: float # 成交价格 + bsDirection: int # 买卖方向 + dealTime: str # 成交时间 + dealDate: str # 成交日期 + barRealTime: str # K 线时间 + volume: int # 成交数量 + + +@router.get("/all_stocks") +async def get_all_stocks() -> dict[str, Any]: + """ + 获取所有股票池 + + 返回所有启用的策略实例关联的股票 + + Returns: + 股票代码到配置的映射 + """ + # TODO: 从数据库获取策略实例绑定的股票 + # 暂时返回示例数据 return { - "connected": qmt_client.is_connected, - "executor_running": order_executor.is_running, - "pending_orders": len(order_executor.pending_orders), + "159915.SZ": {"name": "创业板ETF", "strategies": ["MA", "MACD"]}, + "510300.SH": {"name": "沪深300ETF", "strategies": ["MA"]}, + "510500.SH": {"name": "中证500ETF", "strategies": ["MA"]}, } -@router.post("/order") -async def place_order( - code: str, - direction: str, # buy/sell - quantity: int, - price: float | None = None, - order_type: str = "limit", # limit/market -) -> dict: - """手动下单(测试用) +@router.patch("/dealsync/{stock}/{order_id}") +async def sync_deal( + stock: str, order_id: str, request: DealSyncRequest +) -> dict[str, Any]: + """ + 同步成交信息 + + QMT 客户端成交后回调,同步成交信息到数据库 Args: - code: 股票代码 - direction: 买卖方向 buy/sell - quantity: 数量 - price: 价格,市价单可不填 - order_type: 订单类型 limit/market + stock: 股票代码 + order_id: 订单号 + request: 成交信息 """ - result = await qmt_client.place_order( - code=code, - direction=direction, - quantity=quantity, - price=price, - order_type=order_type, + logger.info( + f"收到成交同步: stock={stock}, order_id={order_id}, " + f"price={request.dealPrice}, volume={request.volume}, " + f"direction={request.bsDirection}" ) - return result + + # TODO: 保存成交记录到数据库 + # TODO: 更新策略实例的持仓记录 + # TODO: 更新策略收益统计 + + return { + "success": True, + "message": "成交同步成功", + "data": { + "stock": stock, + "order_id": order_id, + "price": request.dealPrice, + "volume": request.volume, + }, + } -@router.post("/cancel/{order_id}") -async def cancel_order(order_id: str) -> dict: - """撤单 - - Args: - order_id: 订单 ID +@router.get("/positions") +async def get_positions() -> dict[str, Any]: """ - result = await qmt_client.cancel_order(order_id) - return result + 获取策略持仓 + + 返回所有策略实例的持仓汇总 + """ + # TODO: 从数据库获取策略持仓 + return {"positions": [], "total_value": 0} -@router.get("/orders") -async def get_orders() -> dict: - """获取当日委托""" - orders = await qmt_client.get_orders() - return {"count": len(orders), "orders": orders} - - -@router.get("/trades") -async def get_trades() -> dict: - """获取当日成交""" - trades = await qmt_client.get_trades() - return {"count": len(trades), "trades": trades} +@router.get("/performance") +async def get_performance() -> dict[str, Any]: + """ + 获取策略收益统计 + """ + # TODO: 从数据库获取收益统计 + return {"instances": [], "total_profit": 0}