From 883d7e654961af5d7272f73f51bd58458a57c1f6 Mon Sep 17 00:00:00 2001 From: cuizhan <3971687@qq.com> Date: Mon, 8 Dec 2025 23:24:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=98=B6=E6=AE=B53=20Data=20Service=20?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 完成数据服务模块: - data_service/app.py: FastAPI 应用框架,端口 8020 - data_service/routes/: 路由模块 - health.py: 健康检查 /ping, /health - market.py: 行情查询 /market/quote, /market/quotes, /market/snapshot - kline.py: K线查询 /kline/history, /kline/latest, /kline/periods - backtest.py: 回测控制 /backtest/start, /backtest/stop, /backtest/pause - data_service/services/: 核心服务 - market_receiver.py: 行情接收器,订阅 Redis 频道接收 QMT 推送 - kline_service.py: K线服务,批量存储K线到分周期表 - data_player.py: 数据回放器,支持回测数据按时间回放 功能特性: - 行情接收与分发 (Redis Pub/Sub) - K线数据持久化 (按周期分表存储) - 回测数据回放 (支持暂停/恢复/调速) --- src/data_service/__init__.py | 12 + src/data_service/app.py | 108 ++++++ src/data_service/routes/__init__.py | 7 + src/data_service/routes/backtest.py | 160 ++++++++ src/data_service/routes/health.py | 52 +++ src/data_service/routes/kline.py | 237 ++++++++++++ src/data_service/routes/market.py | 202 ++++++++++ src/data_service/services/__init__.py | 7 + src/data_service/services/data_player.py | 384 +++++++++++++++++++ src/data_service/services/kline_service.py | 295 ++++++++++++++ src/data_service/services/market_receiver.py | 199 ++++++++++ 11 files changed, 1663 insertions(+) create mode 100644 src/data_service/__init__.py create mode 100644 src/data_service/app.py create mode 100644 src/data_service/routes/__init__.py create mode 100644 src/data_service/routes/backtest.py create mode 100644 src/data_service/routes/health.py create mode 100644 src/data_service/routes/kline.py create mode 100644 src/data_service/routes/market.py create mode 100644 src/data_service/services/__init__.py create mode 100644 src/data_service/services/data_player.py create mode 100644 src/data_service/services/kline_service.py create mode 100644 src/data_service/services/market_receiver.py diff --git a/src/data_service/__init__.py b/src/data_service/__init__.py new file mode 100644 index 0000000..1963a3a --- /dev/null +++ b/src/data_service/__init__.py @@ -0,0 +1,12 @@ +""" +QTrade Data Service 数据服务 + +提供: +- 行情数据接收与分发 +- K线数据存储与查询 +- 回测数据回放 +""" + +from .app import app, create_app + +__all__ = ["app", "create_app"] diff --git a/src/data_service/app.py b/src/data_service/app.py new file mode 100644 index 0000000..670d711 --- /dev/null +++ b/src/data_service/app.py @@ -0,0 +1,108 @@ +""" +Data Service FastAPI 应用 + +数据服务,提供: +- 行情数据接收(从 QMT Adapter) +- 行情数据分发(到 Strategy Engine) +- K线数据存储与查询 +- 回测数据回放 +""" + +from contextlib import asynccontextmanager +from typing import AsyncIterator + +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse + +from src.core.config import settings +from src.core.logger import get_logger +from src.core.database import db +from src.core.redis_client import redis_client + +from .routes import health, market, kline, backtest + +logger = get_logger("data_service") + + +@asynccontextmanager +async def lifespan(app: FastAPI) -> AsyncIterator[None]: + """应用生命周期管理""" + from .services.market_receiver import market_receiver + from .services.kline_service import kline_service + + logger.info("Data Service 启动中...") + + try: + await redis_client.connect() + logger.info("Redis 连接成功") + except Exception as e: + logger.warning(f"Redis 连接失败: {e}") + + try: + await db.connect() + logger.info("数据库连接成功") + except Exception as e: + logger.warning(f"数据库连接失败: {e}") + + # 启动行情接收器 + try: + await market_receiver.start() + logger.info("行情接收器已启动") + except Exception as e: + logger.warning(f"行情接收器启动失败: {e}") + + # 启动K线服务 + try: + await kline_service.start() + logger.info("K线服务已启动") + except Exception as e: + logger.warning(f"K线服务启动失败: {e}") + + logger.info("Data Service 启动完成") + + yield + + logger.info("Data Service 关闭中...") + await market_receiver.stop() + await kline_service.stop() + await redis_client.disconnect() + await db.disconnect() + logger.info("Data Service 已关闭") + + +def create_app() -> FastAPI: + """创建 FastAPI 应用实例""" + + application = FastAPI( + title="QTrade Data Service", + description="量化交易系统数据服务", + version=settings.app.version, + lifespan=lifespan, + docs_url="/docs" if settings.app.debug else None, + redoc_url="/redoc" if settings.app.debug else None, + ) + + # 注册路由 + application.include_router(health.router, tags=["健康检查"]) + application.include_router(market.router, prefix="/market", tags=["行情"]) + application.include_router(kline.router, prefix="/kline", tags=["K线"]) + application.include_router(backtest.router, prefix="/backtest", tags=["回测"]) + + # 全局异常处理 + @application.exception_handler(Exception) + async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"未处理的异常: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "code": 500, + "message": "服务器内部错误", + "detail": str(exc) if settings.app.debug else None, + }, + ) + + return application + + +# 创建应用实例 +app = create_app() diff --git a/src/data_service/routes/__init__.py b/src/data_service/routes/__init__.py new file mode 100644 index 0000000..45903d8 --- /dev/null +++ b/src/data_service/routes/__init__.py @@ -0,0 +1,7 @@ +""" +Data Service 路由模块 +""" + +from . import health, market, kline, backtest + +__all__ = ["health", "market", "kline", "backtest"] diff --git a/src/data_service/routes/backtest.py b/src/data_service/routes/backtest.py new file mode 100644 index 0000000..ad62625 --- /dev/null +++ b/src/data_service/routes/backtest.py @@ -0,0 +1,160 @@ +""" +回测数据路由 + +提供: +- 回测数据回放控制 +- 历史行情模拟推送 +""" + +from typing import Any +from datetime import datetime as dt + +from fastapi import APIRouter, Query, HTTPException +from pydantic import BaseModel + +from src.core.logger import get_logger +from ..services.data_player import data_player, PlaybackStatus + +logger = get_logger("data_service.backtest") +router = APIRouter() + + +class PlaybackConfig(BaseModel): + """回放配置""" + + symbols: list[str] + start_date: str + end_date: str + speed: float = 1.0 # 回放速度倍数 + period: str = "1m" # 回放K线周期 + + +@router.get("/status") +async def get_playback_status() -> dict[str, Any]: + """获取回放状态""" + return { + "code": 0, + "message": "success", + "data": data_player.state, + } + + +@router.post("/start") +async def start_playback(config: PlaybackConfig) -> dict[str, Any]: + """启动回测数据回放 + + Args: + config: 回放配置 + + Returns: + 操作结果 + """ + if data_player.status == PlaybackStatus.PLAYING: + raise HTTPException(status_code=400, detail="回放已在运行中") + + # 验证配置 + if not config.symbols: + raise HTTPException(status_code=400, detail="请指定回放股票") + + try: + start_dt = dt.strptime(config.start_date, "%Y-%m-%d") + end_dt = dt.strptime(config.end_date, "%Y-%m-%d") + if start_dt >= end_dt: + raise HTTPException(status_code=400, detail="结束日期必须大于开始日期") + except ValueError: + raise HTTPException(status_code=400, detail="日期格式错误,请使用 YYYY-MM-DD") + + # 启动回放 + success = await data_player.start( + symbols=config.symbols, + start_date=config.start_date, + end_date=config.end_date, + period=config.period, + speed=config.speed, + ) + + if not success: + raise HTTPException( + status_code=400, detail="启动回放失败,可能没有符合条件的数据" + ) + + logger.info( + f"回测回放已启动: {config.symbols}, {config.start_date} - {config.end_date}" + ) + + return { + "code": 0, + "message": "回放已启动", + "data": data_player.state, + } + + +@router.post("/stop") +async def stop_playback() -> dict[str, Any]: + """停止回测数据回放""" + if data_player.status == PlaybackStatus.STOPPED: + raise HTTPException(status_code=400, detail="回放未在运行") + + await data_player.stop() + + logger.info("回测回放已停止") + + return { + "code": 0, + "message": "回放已停止", + "data": data_player.state, + } + + +@router.post("/pause") +async def pause_playback() -> dict[str, Any]: + """暂停回测数据回放""" + if data_player.status != PlaybackStatus.PLAYING: + raise HTTPException(status_code=400, detail="回放未在运行") + + await data_player.pause() + + logger.info("回测回放已暂停") + + return { + "code": 0, + "message": "回放已暂停", + "data": data_player.state, + } + + +@router.post("/resume") +async def resume_playback() -> dict[str, Any]: + """恢复回测数据回放""" + if data_player.status != PlaybackStatus.PAUSED: + raise HTTPException(status_code=400, detail="回放未在暂停状态") + + await data_player.resume() + + logger.info("回测回放已恢复") + + return { + "code": 0, + "message": "回放已恢复", + "data": data_player.state, + } + + +@router.post("/speed") +async def set_playback_speed( + speed: float = Query(..., ge=0.1, le=100.0, description="回放速度倍数"), +) -> dict[str, Any]: + """设置回放速度 + + Args: + speed: 速度倍数,0.1-100 + """ + data_player.set_speed(speed) + + logger.info(f"回放速度已设置为 {speed}x") + + return { + "code": 0, + "message": f"速度已设置为 {speed}x", + "data": {"speed": speed}, + } diff --git a/src/data_service/routes/health.py b/src/data_service/routes/health.py new file mode 100644 index 0000000..df9c2d6 --- /dev/null +++ b/src/data_service/routes/health.py @@ -0,0 +1,52 @@ +""" +健康检查路由 +""" + +from datetime import datetime +from typing import Any + +from fastapi import APIRouter + +from src.core.config import settings +from src.core.redis_client import redis_client +from src.core.database import db + +router = APIRouter() + + +@router.get("/health") +async def health_check() -> dict[str, Any]: + """健康检查""" + redis_ok = False + try: + if redis_client._client: + await redis_client.client.ping() + redis_ok = True + except Exception: + pass + + db_ok = False + try: + if db._engine: + async with db.session() as session: + await session.execute("SELECT 1") + db_ok = True + except Exception: + pass + + return { + "status": "healthy" if (redis_ok and db_ok) else "degraded", + "service": "data_service", + "version": settings.app.version, + "timestamp": datetime.now().isoformat(), + "components": { + "redis": "up" if redis_ok else "down", + "database": "up" if db_ok else "down", + }, + } + + +@router.get("/ping") +async def ping() -> dict[str, str]: + """存活检查""" + return {"status": "pong"} diff --git a/src/data_service/routes/kline.py b/src/data_service/routes/kline.py new file mode 100644 index 0000000..96104a9 --- /dev/null +++ b/src/data_service/routes/kline.py @@ -0,0 +1,237 @@ +""" +K线数据路由 + +提供: +- K线数据查询 +- K线数据存储 +- K线周期转换 +""" + +from typing import Any, Optional +from datetime import datetime as dt, timedelta +from enum import Enum + +from fastapi import APIRouter, Query, HTTPException +from pydantic import BaseModel + +from src.core.logger import get_logger +from src.core.database import db +from src.core.redis_client import redis_client, RedisKeys + +logger = get_logger("data_service.kline") +router = APIRouter() + + +class KlinePeriod(str, Enum): + """K线周期""" + + M1 = "1m" + M5 = "5m" + M15 = "15m" + M30 = "30m" + M60 = "60m" + D1 = "1d" + W1 = "1w" + + +class KlineData(BaseModel): + """K线数据""" + + symbol: str + period: str + open: float + high: float + low: float + close: float + volume: int + amount: float + timestamp: dt + + +class KlineResponse(BaseModel): + """K线响应""" + + code: int = 0 + message: str = "success" + data: list[dict] + count: int + + +# K线周期到表名的映射 +PERIOD_TABLE_MAP = { + "1m": "klines_1m", + "5m": "klines_5m", + "15m": "klines_15m", + "30m": "klines_30m", + "60m": "klines_60m", + "1d": "klines_1d", + "1w": "klines_1w", +} + + +@router.get("/history/{symbol}") +async def get_kline_history( + symbol: str, + period: KlinePeriod = Query(KlinePeriod.D1, description="K线周期"), + start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"), + end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"), + limit: int = Query(100, ge=1, le=1000, description="返回数量"), +) -> dict[str, Any]: + """获取K线历史数据 + + Args: + symbol: 股票代码 + period: K线周期 + start_date: 开始日期 + end_date: 结束日期 + limit: 返回数量限制 + + Returns: + K线数据列表 + """ + try: + table_name = PERIOD_TABLE_MAP.get(period.value) + if not table_name: + raise HTTPException(status_code=400, detail=f"不支持的K线周期: {period}") + + # 构建查询条件 + conditions = ["symbol = :symbol"] + params = {"symbol": symbol, "limit": limit} + + if start_date: + conditions.append("timestamp >= :start_date") + params["start_date"] = start_date + + if end_date: + conditions.append("timestamp <= :end_date") + params["end_date"] = end_date + + where_clause = " AND ".join(conditions) + + query = f""" + SELECT symbol, open, high, low, close, volume, amount, timestamp + FROM {table_name} + WHERE {where_clause} + ORDER BY timestamp DESC + LIMIT :limit + """ + + async with db.session() as session: + result = await session.execute(query, params) + rows = result.fetchall() + + data = [ + { + "symbol": row[0], + "open": float(row[1]), + "high": float(row[2]), + "low": float(row[3]), + "close": float(row[4]), + "volume": int(row[5]), + "amount": float(row[6]), + "timestamp": row[7].isoformat() if row[7] else None, + } + for row in rows + ] + + return { + "code": 0, + "message": "success", + "data": list(reversed(data)), # 按时间正序 + "count": len(data), + "period": period.value, + } + + except HTTPException: + raise + except Exception as e: + logger.error(f"获取K线数据失败: {symbol}, {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/latest/{symbol}") +async def get_latest_kline( + symbol: str, + period: KlinePeriod = Query(KlinePeriod.D1, description="K线周期"), +) -> dict[str, Any]: + """获取最新K线数据 + + Args: + symbol: 股票代码 + period: K线周期 + + Returns: + 最新一根K线数据 + """ + try: + # 先从 Redis 缓存获取 + cache_key = f"kline:{period.value}:{symbol}" + cached = await redis_client.hgetall(cache_key) + + if cached: + return { + "code": 0, + "message": "success", + "data": cached, + "source": "cache", + } + + # 缓存未命中,从数据库获取 + table_name = PERIOD_TABLE_MAP.get(period.value) + + query = f""" + SELECT symbol, open, high, low, close, volume, amount, timestamp + FROM {table_name} + WHERE symbol = :symbol + ORDER BY timestamp DESC + LIMIT 1 + """ + + async with db.session() as session: + result = await session.execute(query, {"symbol": symbol}) + row = result.fetchone() + + if not row: + raise HTTPException(status_code=404, detail=f"未找到 {symbol} 的K线数据") + + data = { + "symbol": row[0], + "open": float(row[1]), + "high": float(row[2]), + "low": float(row[3]), + "close": float(row[4]), + "volume": int(row[5]), + "amount": float(row[6]), + "timestamp": row[7].isoformat() if row[7] else None, + } + + return { + "code": 0, + "message": "success", + "data": data, + "source": "database", + } + + except HTTPException: + raise + except Exception as e: + logger.error(f"获取最新K线失败: {symbol}, {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/periods") +async def get_available_periods() -> dict[str, Any]: + """获取支持的K线周期列表""" + return { + "code": 0, + "message": "success", + "data": [ + {"value": "1m", "name": "1分钟", "table": "klines_1m"}, + {"value": "5m", "name": "5分钟", "table": "klines_5m"}, + {"value": "15m", "name": "15分钟", "table": "klines_15m"}, + {"value": "30m", "name": "30分钟", "table": "klines_30m"}, + {"value": "60m", "name": "60分钟", "table": "klines_60m"}, + {"value": "1d", "name": "日线", "table": "klines_1d"}, + {"value": "1w", "name": "周线", "table": "klines_1w"}, + ], + } diff --git a/src/data_service/routes/market.py b/src/data_service/routes/market.py new file mode 100644 index 0000000..d80d687 --- /dev/null +++ b/src/data_service/routes/market.py @@ -0,0 +1,202 @@ +""" +行情数据路由 + +提供: +- 实时行情查询 +- 行情快照 +- 行情订阅管理 +""" + +from typing import Any, Optional +from datetime import datetime + +from fastapi import APIRouter, Query, HTTPException +from pydantic import BaseModel + +from src.core.logger import get_logger +from src.core.redis_client import redis_client, RedisKeys + +logger = get_logger("data_service.market") +router = APIRouter() + + +class QuoteResponse(BaseModel): + """行情响应""" + + symbol: str + name: Optional[str] = None + last_price: float + open_price: float + high_price: float + low_price: float + pre_close: float + volume: int + amount: float + bid_price: list[float] + bid_volume: list[int] + ask_price: list[float] + ask_volume: list[int] + timestamp: datetime + + +class QuoteListResponse(BaseModel): + """行情列表响应""" + + code: int = 0 + message: str = "success" + data: list[QuoteResponse] + count: int + + +@router.get("/quote/{symbol}") +async def get_quote(symbol: str) -> dict[str, Any]: + """获取单个股票实时行情 + + Args: + symbol: 股票代码,如 600000.SH + + Returns: + 实时行情数据 + """ + try: + quote_key = RedisKeys.quote(symbol) + quote_data = await redis_client.hgetall(quote_key) + + if not quote_data: + raise HTTPException( + status_code=404, detail=f"未找到股票 {symbol} 的行情数据" + ) + + return { + "code": 0, + "message": "success", + "data": quote_data, + } + except HTTPException: + raise + except Exception as e: + logger.error(f"获取行情失败: {symbol}, {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/quotes") +async def get_quotes( + symbols: str = Query(..., description="股票代码列表,逗号分隔"), +) -> dict[str, Any]: + """批量获取股票实时行情 + + Args: + symbols: 股票代码列表,逗号分隔,如 600000.SH,000001.SZ + + Returns: + 行情数据列表 + """ + symbol_list = [s.strip() for s in symbols.split(",") if s.strip()] + + if not symbol_list: + raise HTTPException(status_code=400, detail="请提供股票代码") + + if len(symbol_list) > 100: + raise HTTPException(status_code=400, detail="单次查询最多100个股票") + + try: + result = [] + for symbol in symbol_list: + quote_key = RedisKeys.quote(symbol) + quote_data = await redis_client.hgetall(quote_key) + if quote_data: + quote_data["symbol"] = symbol + result.append(quote_data) + + return { + "code": 0, + "message": "success", + "data": result, + "count": len(result), + } + except Exception as e: + logger.error(f"批量获取行情失败: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/snapshot") +async def get_market_snapshot( + market: Optional[str] = Query(None, description="市场代码: SH/SZ"), +) -> dict[str, Any]: + """获取市场行情快照 + + Args: + market: 市场代码,SH 上海,SZ 深圳,不传则获取全部 + + Returns: + 市场行情快照统计 + """ + try: + # 从 Redis 获取所有行情数据 + pattern = "quote:*" + quotes = [] + + async for key in redis_client.scan_iter(match=pattern): + quote_data = await redis_client.hgetall(key) + if quote_data: + symbol = key.split(":")[-1] + # 过滤市场 + if market: + if market.upper() == "SH" and not symbol.endswith(".SH"): + continue + if market.upper() == "SZ" and not symbol.endswith(".SZ"): + continue + quote_data["symbol"] = symbol + quotes.append(quote_data) + + # 统计信息 + up_count = 0 + down_count = 0 + flat_count = 0 + + for q in quotes: + last = float(q.get("last_price", 0)) + pre_close = float(q.get("pre_close", 0)) + if pre_close > 0: + if last > pre_close: + up_count += 1 + elif last < pre_close: + down_count += 1 + else: + flat_count += 1 + + return { + "code": 0, + "message": "success", + "data": { + "market": market or "ALL", + "total": len(quotes), + "up": up_count, + "down": down_count, + "flat": flat_count, + "timestamp": datetime.now().isoformat(), + }, + } + except Exception as e: + logger.error(f"获取市场快照失败: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/subscriptions") +async def get_subscriptions() -> dict[str, Any]: + """获取当前订阅的股票列表""" + try: + # 从 Redis 获取订阅列表 + subscriptions = await redis_client.smembers("market:subscriptions") + + return { + "code": 0, + "message": "success", + "data": { + "symbols": list(subscriptions) if subscriptions else [], + "count": len(subscriptions) if subscriptions else 0, + }, + } + except Exception as e: + logger.error(f"获取订阅列表失败: {e}") + raise HTTPException(status_code=500, detail=str(e)) diff --git a/src/data_service/services/__init__.py b/src/data_service/services/__init__.py new file mode 100644 index 0000000..2bb6e22 --- /dev/null +++ b/src/data_service/services/__init__.py @@ -0,0 +1,7 @@ +""" +Data Service 服务模块 +""" + +from . import market_receiver, kline_service, data_player + +__all__ = ["market_receiver", "kline_service", "data_player"] diff --git a/src/data_service/services/data_player.py b/src/data_service/services/data_player.py new file mode 100644 index 0000000..7b59134 --- /dev/null +++ b/src/data_service/services/data_player.py @@ -0,0 +1,384 @@ +""" +回测数据回放服务 + +职责: +- 从数据库加载历史数据 +- 按时间顺序模拟推送行情 +- 支持暂停、恢复、调速 +""" + +import asyncio +import json +from typing import Any, Optional +from datetime import datetime as dt, timedelta +from enum import Enum + +from sqlalchemy import text + +from src.core.logger import get_logger +from src.core.database import db +from src.core.redis_client import redis_client, RedisChannels + +logger = get_logger("data_service.data_player") + + +class PlaybackStatus(str, Enum): + """回放状态""" + + STOPPED = "stopped" + PLAYING = "playing" + PAUSED = "paused" + + +class DataPlayer: + """ + 数据回放器 + + 从数据库加载历史K线数据,按时间顺序模拟推送, + 用于策略回测 + """ + + def __init__(self): + self._status = PlaybackStatus.STOPPED + self._task: Optional[asyncio.Task] = None + + # 回放配置 + self._symbols: list[str] = [] + self._start_date: Optional[dt] = None + self._end_date: Optional[dt] = None + self._period: str = "1m" + self._speed: float = 1.0 + + # 回放状态 + self._current_time: Optional[dt] = None + self._progress: float = 0.0 + self._total_bars: int = 0 + self._played_bars: int = 0 + + # 暂停事件 + self._pause_event = asyncio.Event() + self._pause_event.set() # 初始非暂停 + + @property + def status(self) -> PlaybackStatus: + """回放状态""" + return self._status + + @property + def progress(self) -> float: + """回放进度 0-100""" + return self._progress + + @property + def current_time(self) -> Optional[str]: + """当前回放时间""" + return self._current_time.isoformat() if self._current_time else None + + @property + def config(self) -> dict: + """回放配置""" + return { + "symbols": self._symbols, + "start_date": self._start_date.strftime("%Y-%m-%d") + if self._start_date + else None, + "end_date": self._end_date.strftime("%Y-%m-%d") if self._end_date else None, + "period": self._period, + "speed": self._speed, + } + + @property + def state(self) -> dict: + """完整状态""" + return { + "status": self._status.value, + "current_time": self.current_time, + "progress": self._progress, + "total_bars": self._total_bars, + "played_bars": self._played_bars, + "config": self.config, + } + + async def start( + self, + symbols: list[str], + start_date: str, + end_date: str, + period: str = "1m", + speed: float = 1.0, + ) -> bool: + """ + 启动数据回放 + + Args: + symbols: 股票代码列表 + start_date: 开始日期 YYYY-MM-DD + end_date: 结束日期 YYYY-MM-DD + period: K线周期 + speed: 回放速度倍数 + + Returns: + 是否启动成功 + """ + if self._status == PlaybackStatus.PLAYING: + logger.warning("回放已在运行中") + return False + + try: + self._symbols = symbols + self._start_date = dt.strptime(start_date, "%Y-%m-%d") + self._end_date = dt.strptime(end_date, "%Y-%m-%d") + self._period = period + self._speed = max(0.1, min(100.0, speed)) + + # 重置状态 + self._current_time = self._start_date + self._progress = 0.0 + self._played_bars = 0 + + # 计算总K线数 + self._total_bars = await self._count_bars() + + if self._total_bars == 0: + logger.warning("未找到符合条件的K线数据") + return False + + # 启动回放任务 + self._status = PlaybackStatus.PLAYING + self._pause_event.set() + self._task = asyncio.create_task(self._run()) + + logger.info( + f"回放已启动: {len(symbols)} 只股票, " + f"{start_date} - {end_date}, " + f"共 {self._total_bars} 根K线" + ) + + # 发布回放开始事件 + await redis_client.publish( + "backtest:event", + { + "event": "started", + "config": self.config, + "total_bars": self._total_bars, + }, + ) + + return True + + except Exception as e: + logger.error(f"启动回放失败: {e}") + return False + + async def stop(self) -> None: + """停止回放""" + if self._status == PlaybackStatus.STOPPED: + return + + self._status = PlaybackStatus.STOPPED + self._pause_event.set() # 解除暂停以便退出 + + if self._task: + self._task.cancel() + try: + await self._task + except asyncio.CancelledError: + pass + self._task = None + + # 发布回放停止事件 + await redis_client.publish( + "backtest:event", + { + "event": "stopped", + "played_bars": self._played_bars, + "progress": self._progress, + }, + ) + + logger.info(f"回放已停止: 已播放 {self._played_bars}/{self._total_bars}") + + async def pause(self) -> None: + """暂停回放""" + if self._status != PlaybackStatus.PLAYING: + return + + self._status = PlaybackStatus.PAUSED + self._pause_event.clear() + + await redis_client.publish( + "backtest:event", {"event": "paused", "current_time": self.current_time} + ) + + logger.info(f"回放已暂停: {self.current_time}") + + async def resume(self) -> None: + """恢复回放""" + if self._status != PlaybackStatus.PAUSED: + return + + self._status = PlaybackStatus.PLAYING + self._pause_event.set() + + await redis_client.publish( + "backtest:event", {"event": "resumed", "current_time": self.current_time} + ) + + logger.info("回放已恢复") + + def set_speed(self, speed: float) -> None: + """设置回放速度""" + self._speed = max(0.1, min(100.0, speed)) + logger.info(f"回放速度已设置为 {self._speed}x") + + async def _count_bars(self) -> int: + """计算总K线数""" + table_name = f"klines_{self._period}" + placeholders = ",".join([f":symbol_{i}" for i in range(len(self._symbols))]) + + query = text(f""" + SELECT COUNT(*) + FROM {table_name} + WHERE symbol IN ({placeholders}) + AND timestamp >= :start_date + AND timestamp <= :end_date + """) + + params = { + "start_date": self._start_date, + "end_date": self._end_date, + } + for i, symbol in enumerate(self._symbols): + params[f"symbol_{i}"] = symbol + + try: + async with db.session() as session: + result = await session.execute(query, params) + row = result.fetchone() + return row[0] if row else 0 + except Exception as e: + logger.error(f"统计K线数失败: {e}") + return 0 + + async def _run(self) -> None: + """运行回放循环""" + table_name = f"klines_{self._period}" + placeholders = ",".join([f":symbol_{i}" for i in range(len(self._symbols))]) + + query = text(f""" + SELECT symbol, open, high, low, close, volume, amount, timestamp + FROM {table_name} + WHERE symbol IN ({placeholders}) + AND timestamp >= :start_date + AND timestamp <= :end_date + ORDER BY timestamp ASC + """) + + params = { + "start_date": self._start_date, + "end_date": self._end_date, + } + for i, symbol in enumerate(self._symbols): + params[f"symbol_{i}"] = symbol + + try: + async with db.session() as session: + result = await session.execute(query, params) + rows = result.fetchall() + + # 按时间戳分组 + bars_by_time: dict[dt, list[dict]] = {} + for row in rows: + timestamp = row[7] + bar = { + "symbol": row[0], + "open": float(row[1]) if row[1] else 0, + "high": float(row[2]) if row[2] else 0, + "low": float(row[3]) if row[3] else 0, + "close": float(row[4]) if row[4] else 0, + "volume": int(row[5]) if row[5] else 0, + "amount": float(row[6]) if row[6] else 0, + "timestamp": timestamp.isoformat() if timestamp else None, + "period": self._period, + } + + if timestamp not in bars_by_time: + bars_by_time[timestamp] = [] + bars_by_time[timestamp].append(bar) + + # 按时间顺序回放 + sorted_times = sorted(bars_by_time.keys()) + + # 计算时间间隔 + interval_map = { + "1m": 60, + "5m": 300, + "15m": 900, + "30m": 1800, + "60m": 3600, + "1d": 86400, + "1w": 604800, + } + base_interval = interval_map.get(self._period, 60) + + for i, timestamp in enumerate(sorted_times): + # 检查是否停止 + if self._status == PlaybackStatus.STOPPED: + break + + # 等待暂停解除 + await self._pause_event.wait() + + # 更新当前时间 + self._current_time = timestamp + self._played_bars = i + 1 + self._progress = (self._played_bars / self._total_bars) * 100 + + # 发布K线数据 + for bar in bars_by_time[timestamp]: + await redis_client.publish(RedisChannels.MARKET_KLINE, bar) + + # 同时发布模拟行情 + quote = { + "symbol": bar["symbol"], + "last_price": bar["close"], + "open_price": bar["open"], + "high_price": bar["high"], + "low_price": bar["low"], + "volume": bar["volume"], + "amount": bar["amount"], + "timestamp": bar["timestamp"], + "source": "backtest", + } + await redis_client.publish(RedisChannels.MARKET_QUOTE, quote) + + # 按速度延迟 + delay = base_interval / self._speed + # 限制最小延迟,避免过快 + delay = max(0.001, min(delay, 1.0)) + await asyncio.sleep(delay) + + # 回放完成 + if self._status == PlaybackStatus.PLAYING: + self._status = PlaybackStatus.STOPPED + self._progress = 100.0 + + await redis_client.publish( + "backtest:event", + { + "event": "completed", + "total_bars": self._total_bars, + }, + ) + + logger.info("回放完成") + + except asyncio.CancelledError: + logger.info("回放被取消") + except Exception as e: + logger.error(f"回放异常: {e}", exc_info=True) + self._status = PlaybackStatus.STOPPED + + +# 全局单例 +data_player = DataPlayer() diff --git a/src/data_service/services/kline_service.py b/src/data_service/services/kline_service.py new file mode 100644 index 0000000..00928b3 --- /dev/null +++ b/src/data_service/services/kline_service.py @@ -0,0 +1,295 @@ +""" +K线存储与查询服务 + +职责: +- K线数据持久化存储 +- K线数据查询 +- K线周期聚合 +""" + +import asyncio +from typing import Any, Optional +from datetime import datetime as dt, timedelta +from decimal import Decimal + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from src.core.logger import get_logger +from src.core.database import db +from src.core.redis_client import redis_client, RedisChannels + +logger = get_logger("data_service.kline_service") + + +# K线周期配置 +KLINE_PERIODS = { + "1m": {"table": "klines_1m", "interval": timedelta(minutes=1)}, + "5m": {"table": "klines_5m", "interval": timedelta(minutes=5)}, + "15m": {"table": "klines_15m", "interval": timedelta(minutes=15)}, + "30m": {"table": "klines_30m", "interval": timedelta(minutes=30)}, + "60m": {"table": "klines_60m", "interval": timedelta(minutes=60)}, + "1d": {"table": "klines_1d", "interval": timedelta(days=1)}, + "1w": {"table": "klines_1w", "interval": timedelta(weeks=1)}, +} + + +class KlineService: + """ + K线服务 + + 提供K线数据的存储、查询、聚合功能 + """ + + def __init__(self): + self._running = False + self._task: Optional[asyncio.Task] = None + self._pending_klines: list[dict] = [] + self._batch_size = 100 + self._flush_interval = 5.0 # 秒 + self._save_count = 0 + + async def start(self) -> None: + """启动K线服务""" + if self._running: + logger.warning("K线服务已在运行") + return + + self._running = True + self._task = asyncio.create_task(self._run()) + logger.info("K线服务已启动") + + async def stop(self) -> None: + """停止K线服务""" + self._running = False + + # 刷新剩余数据 + if self._pending_klines: + await self._flush_klines() + + if self._task: + self._task.cancel() + try: + await self._task + except asyncio.CancelledError: + pass + self._task = None + + logger.info(f"K线服务已停止 (保存K线: {self._save_count})") + + async def _run(self) -> None: + """运行K线接收循环""" + try: + pubsub = redis_client.client.pubsub() + await pubsub.subscribe(RedisChannels.MARKET_KLINE) + logger.info(f"已订阅K线频道: {RedisChannels.MARKET_KLINE}") + + last_flush = dt.now() + + while self._running: + try: + message = await asyncio.wait_for( + pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0), + timeout=2.0, + ) + + if message and message["type"] == "message": + import json + + data = message["data"] + if isinstance(data, bytes): + data = json.loads(data.decode("utf-8")) + elif isinstance(data, str): + data = json.loads(data) + + await self._process_kline(data) + + # 定时刷新 + if (dt.now() - last_flush).total_seconds() >= self._flush_interval: + if self._pending_klines: + await self._flush_klines() + last_flush = dt.now() + + except asyncio.TimeoutError: + # 超时检查是否需要刷新 + if (dt.now() - last_flush).total_seconds() >= self._flush_interval: + if self._pending_klines: + await self._flush_klines() + last_flush = dt.now() + except Exception as e: + logger.error(f"K线处理异常: {e}") + await asyncio.sleep(0.1) + + await pubsub.unsubscribe(RedisChannels.MARKET_KLINE) + await pubsub.close() + + except Exception as e: + logger.error(f"K线服务异常: {e}", exc_info=True) + + async def _process_kline(self, data: dict) -> None: + """处理单条K线数据""" + self._pending_klines.append(data) + + # 达到批量大小则刷新 + if len(self._pending_klines) >= self._batch_size: + await self._flush_klines() + + async def _flush_klines(self) -> None: + """批量保存K线数据""" + if not self._pending_klines: + return + + klines = self._pending_klines + self._pending_klines = [] + + # 按周期分组 + klines_by_period: dict[str, list] = {} + for kline in klines: + period = kline.get("period", "1m") + if period not in klines_by_period: + klines_by_period[period] = [] + klines_by_period[period].append(kline) + + # 分表保存 + for period, period_klines in klines_by_period.items(): + await self._save_klines(period, period_klines) + + self._save_count += len(klines) + logger.debug(f"已保存 {len(klines)} 条K线数据") + + async def _save_klines(self, period: str, klines: list[dict]) -> None: + """保存指定周期的K线数据""" + config = KLINE_PERIODS.get(period) + if not config: + logger.warning(f"未知K线周期: {period}") + return + + table_name = config["table"] + + # 使用 INSERT ... ON DUPLICATE KEY UPDATE + query = text(f""" + INSERT INTO {table_name} + (symbol, open, high, low, close, volume, amount, timestamp) + VALUES + (:symbol, :open, :high, :low, :close, :volume, :amount, :timestamp) + ON DUPLICATE KEY UPDATE + open = VALUES(open), + high = VALUES(high), + low = VALUES(low), + close = VALUES(close), + volume = VALUES(volume), + amount = VALUES(amount) + """) + + try: + async with db.session() as session: + for kline in klines: + await session.execute( + query, + { + "symbol": kline.get("symbol"), + "open": kline.get("open", 0), + "high": kline.get("high", 0), + "low": kline.get("low", 0), + "close": kline.get("close", 0), + "volume": kline.get("volume", 0), + "amount": kline.get("amount", 0), + "timestamp": kline.get("timestamp"), + }, + ) + await session.commit() + except Exception as e: + logger.error(f"保存K线失败: {e}") + + async def get_klines( + self, + symbol: str, + period: str = "1d", + start_time: Optional[dt] = None, + end_time: Optional[dt] = None, + limit: int = 100, + ) -> list[dict]: + """ + 查询K线数据 + + Args: + symbol: 股票代码 + period: K线周期 + start_time: 开始时间 + end_time: 结束时间 + limit: 返回数量 + + Returns: + K线数据列表 + """ + config = KLINE_PERIODS.get(period) + if not config: + return [] + + table_name = config["table"] + + conditions = ["symbol = :symbol"] + params: dict[str, Any] = {"symbol": symbol, "limit": limit} + + if start_time: + conditions.append("timestamp >= :start_time") + params["start_time"] = start_time + + if end_time: + conditions.append("timestamp <= :end_time") + params["end_time"] = end_time + + where_clause = " AND ".join(conditions) + + query = text(f""" + SELECT symbol, open, high, low, close, volume, amount, timestamp + FROM {table_name} + WHERE {where_clause} + ORDER BY timestamp DESC + LIMIT :limit + """) + + try: + async with db.session() as session: + result = await session.execute(query, params) + rows = result.fetchall() + + return [ + { + "symbol": row[0], + "open": float(row[1]) if row[1] else 0, + "high": float(row[2]) if row[2] else 0, + "low": float(row[3]) if row[3] else 0, + "close": float(row[4]) if row[4] else 0, + "volume": int(row[5]) if row[5] else 0, + "amount": float(row[6]) if row[6] else 0, + "timestamp": row[7].isoformat() if row[7] else None, + } + for row in reversed(rows) + ] + except Exception as e: + logger.error(f"查询K线失败: {e}") + return [] + + async def get_latest_kline(self, symbol: str, period: str = "1d") -> Optional[dict]: + """获取最新K线""" + klines = await self.get_klines(symbol, period, limit=1) + return klines[0] if klines else None + + @property + def is_running(self) -> bool: + """是否在运行""" + return self._running + + @property + def stats(self) -> dict: + """统计信息""" + return { + "running": self._running, + "pending_count": len(self._pending_klines), + "save_count": self._save_count, + } + + +# 全局单例 +kline_service = KlineService() diff --git a/src/data_service/services/market_receiver.py b/src/data_service/services/market_receiver.py new file mode 100644 index 0000000..8e81d80 --- /dev/null +++ b/src/data_service/services/market_receiver.py @@ -0,0 +1,199 @@ +""" +行情接收与分发服务 + +职责: +- 订阅 Redis 行情频道,接收 QMT Adapter 推送的行情数据 +- 将行情数据缓存到 Redis +- 转发行情到策略引擎 +""" + +import asyncio +import json +from typing import Any, Callable, Optional +from datetime import datetime as dt + +from src.core.logger import get_logger +from src.core.redis_client import redis_client, RedisChannels, RedisKeys + +logger = get_logger("data_service.market_receiver") + + +class MarketReceiver: + """ + 行情接收器 + + 接收 QMT Adapter 推送的行情数据,缓存到 Redis, + 并转发到策略引擎 + """ + + def __init__(self): + self._running = False + self._task: Optional[asyncio.Task] = None + self._handlers: list[Callable[[dict], Any]] = [] + self._quote_count = 0 + self._kline_count = 0 + + async def start(self) -> None: + """启动行情接收""" + if self._running: + logger.warning("行情接收器已在运行") + 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 + self._task = None + + logger.info( + f"行情接收器已停止 (处理行情: {self._quote_count}, K线: {self._kline_count})" + ) + + def add_handler(self, handler: Callable[[dict], Any]) -> None: + """添加行情处理器""" + self._handlers.append(handler) + + def remove_handler(self, handler: Callable[[dict], Any]) -> None: + """移除行情处理器""" + if handler in self._handlers: + self._handlers.remove(handler) + + async def _run(self) -> None: + """运行行情接收循环""" + channels = [ + RedisChannels.MARKET_QUOTE, + RedisChannels.MARKET_KLINE, + ] + + try: + pubsub = redis_client.client.pubsub() + await pubsub.subscribe(*channels) + logger.info(f"已订阅频道: {channels}") + + while self._running: + try: + message = await asyncio.wait_for( + pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0), + timeout=2.0, + ) + + if message is None: + continue + + if message["type"] == "message": + channel = message["channel"] + if isinstance(channel, bytes): + channel = channel.decode("utf-8") + + data = message["data"] + if isinstance(data, bytes): + data = json.loads(data.decode("utf-8")) + elif isinstance(data, str): + data = json.loads(data) + + # 根据频道处理不同类型的数据 + if channel == RedisChannels.MARKET_QUOTE: + await self._handle_quote(data) + elif channel == RedisChannels.MARKET_KLINE: + await self._handle_kline(data) + + except asyncio.TimeoutError: + continue + except json.JSONDecodeError as e: + logger.warning(f"行情数据解析失败: {e}") + except Exception as e: + logger.error(f"行情处理异常: {e}") + await asyncio.sleep(0.1) + + await pubsub.unsubscribe(*channels) + await pubsub.close() + + except Exception as e: + logger.error(f"行情接收器异常: {e}", exc_info=True) + + async def _handle_quote(self, data: dict) -> None: + """ + 处理实时行情数据 + + Args: + data: 行情数据,包含 symbol, last_price, volume 等 + """ + symbol = data.get("symbol") + if not symbol: + return + + self._quote_count += 1 + + # 添加接收时间戳 + data["receive_time"] = dt.now().isoformat() + + # 缓存到 Redis + quote_key = RedisKeys.quote(symbol) + await redis_client.hmset(quote_key, data) + await redis_client.expire(quote_key, 300) # 5分钟过期 + + # 调用注册的处理器 + for handler in self._handlers: + try: + result = handler(data) + if asyncio.iscoroutine(result): + await result + except Exception as e: + logger.error(f"行情处理器异常: {e}") + + # 转发到策略引擎 + await redis_client.publish(RedisChannels.STRATEGY_QUOTE, data) + + if self._quote_count % 100 == 0: + logger.debug(f"已处理 {self._quote_count} 条行情数据") + + async def _handle_kline(self, data: dict) -> None: + """ + 处理K线数据 + + Args: + data: K线数据,包含 symbol, period, open, high, low, close 等 + """ + symbol = data.get("symbol") + period = data.get("period", "1m") + + if not symbol: + return + + self._kline_count += 1 + + # 缓存最新K线到 Redis + kline_key = f"kline:{period}:{symbol}" + await redis_client.hmset(kline_key, data) + await redis_client.expire(kline_key, 3600) # 1小时过期 + + # 转发到策略引擎 + await redis_client.publish(RedisChannels.STRATEGY_KLINE, data) + + @property + def is_running(self) -> bool: + """是否在运行""" + return self._running + + @property + def stats(self) -> dict: + """统计信息""" + return { + "running": self._running, + "quote_count": self._quote_count, + "kline_count": self._kline_count, + } + + +# 全局单例 +market_receiver = MarketReceiver()