重构qmt_service:移除QMT直连与推送器,保留HTTP链路,trade/signal路由重建,strategy_engine支持链式信号检测
This commit is contained in:
parent
587e9bc6db
commit
1fe879183a
@ -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": "账户数据已同步"}
|
|
||||||
@ -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}
|
|
||||||
125
src/qmt_service/routes/signal.py
Normal file
125
src/qmt_service/routes/signal.py
Normal file
@ -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}",
|
||||||
|
}
|
||||||
@ -1,72 +1,104 @@
|
|||||||
"""
|
"""
|
||||||
交易相关路由
|
交易相关路由
|
||||||
|
|
||||||
|
处理成交同步、股票池管理等
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from ..services.qmt_client import qmt_client
|
from fastapi import APIRouter, HTTPException
|
||||||
from ..services.order_executor import order_executor
|
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 = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
@router.get("/status")
|
class DealSyncRequest(BaseModel):
|
||||||
async def trade_status() -> dict:
|
"""成交同步请求"""
|
||||||
"""获取交易状态"""
|
|
||||||
|
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 {
|
return {
|
||||||
"connected": qmt_client.is_connected,
|
"159915.SZ": {"name": "创业板ETF", "strategies": ["MA", "MACD"]},
|
||||||
"executor_running": order_executor.is_running,
|
"510300.SH": {"name": "沪深300ETF", "strategies": ["MA"]},
|
||||||
"pending_orders": len(order_executor.pending_orders),
|
"510500.SH": {"name": "中证500ETF", "strategies": ["MA"]},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/order")
|
@router.patch("/dealsync/{stock}/{order_id}")
|
||||||
async def place_order(
|
async def sync_deal(
|
||||||
code: str,
|
stock: str, order_id: str, request: DealSyncRequest
|
||||||
direction: str, # buy/sell
|
) -> dict[str, Any]:
|
||||||
quantity: int,
|
"""
|
||||||
price: float | None = None,
|
同步成交信息
|
||||||
order_type: str = "limit", # limit/market
|
|
||||||
) -> dict:
|
QMT 客户端成交后回调,同步成交信息到数据库
|
||||||
"""手动下单(测试用)
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
code: 股票代码
|
stock: 股票代码
|
||||||
direction: 买卖方向 buy/sell
|
order_id: 订单号
|
||||||
quantity: 数量
|
request: 成交信息
|
||||||
price: 价格,市价单可不填
|
|
||||||
order_type: 订单类型 limit/market
|
|
||||||
"""
|
"""
|
||||||
result = await qmt_client.place_order(
|
logger.info(
|
||||||
code=code,
|
f"收到成交同步: stock={stock}, order_id={order_id}, "
|
||||||
direction=direction,
|
f"price={request.dealPrice}, volume={request.volume}, "
|
||||||
quantity=quantity,
|
f"direction={request.bsDirection}"
|
||||||
price=price,
|
|
||||||
order_type=order_type,
|
|
||||||
)
|
)
|
||||||
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}")
|
@router.get("/positions")
|
||||||
async def cancel_order(order_id: str) -> dict:
|
async def get_positions() -> dict[str, Any]:
|
||||||
"""撤单
|
|
||||||
|
|
||||||
Args:
|
|
||||||
order_id: 订单 ID
|
|
||||||
"""
|
"""
|
||||||
result = await qmt_client.cancel_order(order_id)
|
获取策略持仓
|
||||||
return result
|
|
||||||
|
返回所有策略实例的持仓汇总
|
||||||
|
"""
|
||||||
|
# TODO: 从数据库获取策略持仓
|
||||||
|
return {"positions": [], "total_value": 0}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/orders")
|
@router.get("/performance")
|
||||||
async def get_orders() -> dict:
|
async def get_performance() -> dict[str, Any]:
|
||||||
"""获取当日委托"""
|
"""
|
||||||
orders = await qmt_client.get_orders()
|
获取策略收益统计
|
||||||
return {"count": len(orders), "orders": orders}
|
"""
|
||||||
|
# TODO: 从数据库获取收益统计
|
||||||
|
return {"instances": [], "total_profit": 0}
|
||||||
@router.get("/trades")
|
|
||||||
async def get_trades() -> dict:
|
|
||||||
"""获取当日成交"""
|
|
||||||
trades = await qmt_client.get_trades()
|
|
||||||
return {"count": len(trades), "trades": trades}
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user