QTrade/src/data_service/routes/kline.py

238 lines
6.2 KiB
Python
Raw Normal View History

"""
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"},
],
}