feat: 阶段2 Gateway服务完成
- 新增 Gateway 服务 (src/gateway/) - FastAPI 应用框架 (app.py) - 健康检查路由 (/health, /ping) - 行情路由 (/api/v1/market/*) - 交易路由 (/api/v1/trading/*) - 账户路由 (/api/v1/account/*) - 回测路由 (/api/v1/backtest/*) - 修复 Pydantic 模型中 datetime 字段命名冲突 - Gateway 监听端口 8001,支持 Swagger 文档
This commit is contained in:
parent
be4ee5d41c
commit
7ca782b27a
@ -6,7 +6,7 @@
|
||||
- KlineData: K线数据
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime as dt
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
@ -41,7 +41,7 @@ class Quote(BaseModel):
|
||||
ask_volume1: Optional[int] = Field(None, description="卖一量")
|
||||
|
||||
# 时间
|
||||
timestamp: datetime = Field(default_factory=datetime.now, description="行情时间")
|
||||
timestamp: dt = Field(default_factory=dt.now, description="行情时间")
|
||||
|
||||
@property
|
||||
def change(self) -> Decimal:
|
||||
@ -58,7 +58,7 @@ class Quote(BaseModel):
|
||||
class Config:
|
||||
json_encoders = {
|
||||
Decimal: lambda v: float(v),
|
||||
datetime: lambda v: v.isoformat(),
|
||||
dt: lambda v: v.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@ -81,12 +81,12 @@ class KlineData(BaseModel):
|
||||
amount: Decimal = Field(..., description="成交额")
|
||||
|
||||
# 时间
|
||||
datetime: datetime = Field(..., description="K线时间")
|
||||
datetime: dt = Field(..., description="K线时间")
|
||||
|
||||
class Config:
|
||||
json_encoders = {
|
||||
Decimal: lambda v: float(v),
|
||||
datetime: lambda v: v.isoformat(),
|
||||
dt: lambda v: v.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@ -95,6 +95,6 @@ class KlineQuery(BaseModel):
|
||||
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
period: str = Field(..., description="周期")
|
||||
start_time: Optional[datetime] = Field(None, description="开始时间")
|
||||
end_time: Optional[datetime] = Field(None, description="结束时间")
|
||||
start_time: Optional[dt] = Field(None, description="开始时间")
|
||||
end_time: Optional[dt] = Field(None, description="结束时间")
|
||||
limit: int = Field(default=100, ge=1, le=1000, description="返回数量")
|
||||
|
||||
@ -7,7 +7,7 @@
|
||||
- OrderUpdate: 更新订单请求
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime as dt
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
@ -71,10 +71,10 @@ class Order(BaseModel):
|
||||
message: Optional[str] = Field(None, description="状态消息")
|
||||
|
||||
# 时间
|
||||
created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
|
||||
updated_at: datetime = Field(default_factory=datetime.now, description="更新时间")
|
||||
submitted_at: Optional[datetime] = Field(None, description="提交时间")
|
||||
filled_at: Optional[datetime] = Field(None, description="成交时间")
|
||||
created_at: dt = Field(default_factory=dt.now, description="创建时间")
|
||||
updated_at: dt = Field(default_factory=dt.now, description="更新时间")
|
||||
submitted_at: Optional[dt] = Field(None, description="提交时间")
|
||||
filled_at: Optional[dt] = Field(None, description="成交时间")
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
@ -103,7 +103,7 @@ class Order(BaseModel):
|
||||
class Config:
|
||||
json_encoders = {
|
||||
Decimal: lambda v: float(v),
|
||||
datetime: lambda v: v.isoformat(),
|
||||
dt: lambda v: v.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
- PositionUpdate: 更新持仓请求
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime as dt
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
@ -40,8 +40,8 @@ class Position(BaseModel):
|
||||
realized_pnl: Decimal = Field(default=Decimal(0), description="已实现盈亏")
|
||||
|
||||
# 时间
|
||||
created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
|
||||
updated_at: datetime = Field(default_factory=datetime.now, description="更新时间")
|
||||
created_at: dt = Field(default_factory=dt.now, description="创建时间")
|
||||
updated_at: dt = Field(default_factory=dt.now, description="更新时间")
|
||||
|
||||
@property
|
||||
def pnl_ratio(self) -> Optional[Decimal]:
|
||||
@ -65,7 +65,7 @@ class Position(BaseModel):
|
||||
class Config:
|
||||
json_encoders = {
|
||||
Decimal: lambda v: float(v),
|
||||
datetime: lambda v: v.isoformat(),
|
||||
dt: lambda v: v.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
- PairingCreate: 创建配对请求
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime as dt
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
@ -57,8 +57,8 @@ class SymbolStrategy(BaseModel):
|
||||
max_drawdown: Decimal = Field(default=Decimal(0), description="最大回撤")
|
||||
|
||||
# 时间
|
||||
created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
|
||||
updated_at: datetime = Field(default_factory=datetime.now, description="更新时间")
|
||||
created_at: dt = Field(default_factory=dt.now, description="创建时间")
|
||||
updated_at: dt = Field(default_factory=dt.now, description="更新时间")
|
||||
|
||||
@property
|
||||
def win_rate(self) -> Optional[float]:
|
||||
@ -79,7 +79,7 @@ class SymbolStrategy(BaseModel):
|
||||
class Config:
|
||||
json_encoders = {
|
||||
Decimal: lambda v: float(v),
|
||||
datetime: lambda v: v.isoformat(),
|
||||
dt: lambda v: v.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
|
||||
9
src/gateway/__init__.py
Normal file
9
src/gateway/__init__.py
Normal file
@ -0,0 +1,9 @@
|
||||
"""
|
||||
QTrade Gateway 服务
|
||||
|
||||
API 网关,作为外部访问入口
|
||||
"""
|
||||
|
||||
from .app import app, create_app
|
||||
|
||||
__all__ = ["app", "create_app"]
|
||||
104
src/gateway/app.py
Normal file
104
src/gateway/app.py
Normal file
@ -0,0 +1,104 @@
|
||||
"""
|
||||
Gateway FastAPI 应用
|
||||
|
||||
API 网关服务,提供:
|
||||
- 统一的 API 入口
|
||||
- 请求路由转发
|
||||
- 健康检查
|
||||
- 日志中间件
|
||||
"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncIterator
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
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, trading, account, backtest
|
||||
|
||||
logger = get_logger("gateway")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
"""应用生命周期管理"""
|
||||
# 启动时
|
||||
logger.info("Gateway 服务启动中...")
|
||||
|
||||
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}")
|
||||
|
||||
logger.info("Gateway 服务启动完成")
|
||||
|
||||
yield
|
||||
|
||||
# 关闭时
|
||||
logger.info("Gateway 服务关闭中...")
|
||||
await redis_client.disconnect()
|
||||
await db.disconnect()
|
||||
logger.info("Gateway 服务已关闭")
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""创建 FastAPI 应用实例"""
|
||||
|
||||
application = FastAPI(
|
||||
title="QTrade Gateway",
|
||||
description="量化交易系统 API 网关",
|
||||
version=settings.app.version,
|
||||
lifespan=lifespan,
|
||||
docs_url="/docs" if settings.app.debug else None,
|
||||
redoc_url="/redoc" if settings.app.debug else None,
|
||||
)
|
||||
|
||||
# CORS 中间件
|
||||
application.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 注册路由
|
||||
application.include_router(health.router, tags=["健康检查"])
|
||||
application.include_router(market.router, prefix="/api/v1/market", tags=["行情"])
|
||||
application.include_router(trading.router, prefix="/api/v1/trading", tags=["交易"])
|
||||
application.include_router(account.router, prefix="/api/v1/account", tags=["账户"])
|
||||
application.include_router(
|
||||
backtest.router, prefix="/api/v1/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()
|
||||
7
src/gateway/routes/__init__.py
Normal file
7
src/gateway/routes/__init__.py
Normal file
@ -0,0 +1,7 @@
|
||||
"""
|
||||
Gateway 路由模块
|
||||
"""
|
||||
|
||||
from . import health, market, trading, account, backtest
|
||||
|
||||
__all__ = ["health", "market", "trading", "account", "backtest"]
|
||||
181
src/gateway/routes/account.py
Normal file
181
src/gateway/routes/account.py
Normal file
@ -0,0 +1,181 @@
|
||||
"""
|
||||
账户路由
|
||||
|
||||
提供账户、持仓、配对管理接口(转发到 Core Service)
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models.symbol_strategy import PairingCreate, PairingStatus
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger("gateway.account")
|
||||
|
||||
|
||||
# ========== 配对管理 ==========
|
||||
|
||||
|
||||
@router.post("/pairing")
|
||||
async def create_pairing(pairing: PairingCreate) -> dict[str, Any]:
|
||||
"""
|
||||
创建股票-策略配对
|
||||
|
||||
Args:
|
||||
pairing: 配对创建请求
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"创建配对: {pairing.symbol} - {pairing.strategy_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"pairing_id": None,
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/pairing/{pairing_id}")
|
||||
async def get_pairing(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对详情
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询配对: {pairing_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/pairings")
|
||||
async def list_pairings(
|
||||
symbol: Optional[str] = Query(default=None, description="股票代码"),
|
||||
strategy_id: Optional[str] = Query(default=None, description="策略ID"),
|
||||
status: Optional[PairingStatus] = Query(default=None, description="配对状态"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=100),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对列表
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询配对列表: symbol={symbol}, strategy={strategy_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"pairings": [],
|
||||
"total": 0,
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.put("/pairing/{pairing_id}/status")
|
||||
async def update_pairing_status(
|
||||
pairing_id: str,
|
||||
status: PairingStatus,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
更新配对状态(启动/暂停/停止)
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"更新配对状态: {pairing_id} -> {status}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"pairing_id": pairing_id,
|
||||
"status": status,
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ========== 持仓管理 ==========
|
||||
|
||||
|
||||
@router.get("/position/{pairing_id}")
|
||||
async def get_position(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对持仓
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询持仓: {pairing_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/positions")
|
||||
async def list_positions(
|
||||
strategy_id: Optional[str] = Query(default=None, description="策略ID"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询所有持仓
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询持仓列表: strategy={strategy_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"positions": [],
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ========== 资金管理 ==========
|
||||
|
||||
|
||||
@router.get("/balance/{pairing_id}")
|
||||
async def get_balance(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对资金
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询资金: {pairing_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
async def get_account_summary() -> dict[str, Any]:
|
||||
"""
|
||||
查询账户汇总(总资产、总盈亏等)
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info("查询账户汇总")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"total_assets": 0,
|
||||
"total_market_value": 0,
|
||||
"total_cash": 0,
|
||||
"total_pnl": 0,
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
145
src/gateway/routes/backtest.py
Normal file
145
src/gateway/routes/backtest.py
Normal file
@ -0,0 +1,145 @@
|
||||
"""
|
||||
回测路由
|
||||
|
||||
提供回测相关接口(转发到 Data Service / Strategy Engine)
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from src.core.logger import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger("gateway.backtest")
|
||||
|
||||
|
||||
class BacktestRequest(BaseModel):
|
||||
"""回测请求"""
|
||||
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
start_date: datetime = Field(..., description="开始日期")
|
||||
end_date: datetime = Field(..., description="结束日期")
|
||||
initial_capital: float = Field(default=100000, gt=0, description="初始资金")
|
||||
params: dict = Field(default_factory=dict, description="策略参数")
|
||||
|
||||
|
||||
class BacktestResult(BaseModel):
|
||||
"""回测结果"""
|
||||
|
||||
task_id: str
|
||||
status: str
|
||||
progress: float = 0
|
||||
result: Optional[dict] = None
|
||||
|
||||
|
||||
@router.post("/run")
|
||||
async def run_backtest(request: BacktestRequest) -> dict[str, Any]:
|
||||
"""
|
||||
启动回测任务
|
||||
|
||||
Args:
|
||||
request: 回测请求参数
|
||||
"""
|
||||
# TODO: 转发到 Strategy Engine / Data Service
|
||||
logger.info(
|
||||
f"启动回测: {request.symbol}, {request.strategy_id}, "
|
||||
f"{request.start_date} - {request.end_date}"
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"task_id": None,
|
||||
"message": "回测服务未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/status/{task_id}")
|
||||
async def get_backtest_status(task_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询回测任务状态
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
"""
|
||||
# TODO: 转发到 Strategy Engine
|
||||
logger.info(f"查询回测状态: {task_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"task_id": task_id,
|
||||
"status": "unknown",
|
||||
"message": "回测服务未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/result/{task_id}")
|
||||
async def get_backtest_result(task_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
获取回测结果
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
"""
|
||||
# TODO: 转发到 Strategy Engine
|
||||
logger.info(f"获取回测结果: {task_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "回测服务未实现",
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/task/{task_id}")
|
||||
async def cancel_backtest(task_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
取消回测任务
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
"""
|
||||
# TODO: 转发到 Strategy Engine
|
||||
logger.info(f"取消回测: {task_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"task_id": task_id,
|
||||
"message": "回测服务未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/tasks")
|
||||
async def list_backtest_tasks(
|
||||
status: Optional[str] = Query(default=None, description="任务状态"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=100),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询回测任务列表
|
||||
"""
|
||||
# TODO: 转发到 Strategy Engine
|
||||
logger.info(f"查询回测任务列表: status={status}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"tasks": [],
|
||||
"total": 0,
|
||||
"message": "回测服务未实现",
|
||||
},
|
||||
}
|
||||
71
src/gateway/routes/health.py
Normal file
71
src/gateway/routes/health.py
Normal file
@ -0,0 +1,71 @@
|
||||
"""
|
||||
健康检查路由
|
||||
|
||||
提供服务健康状态检查接口
|
||||
"""
|
||||
|
||||
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 和数据库连接状态
|
||||
"""
|
||||
# 检查 Redis
|
||||
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": "gateway",
|
||||
"version": settings.app.version,
|
||||
"environment": settings.app.env,
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"components": {
|
||||
"redis": "up" if redis_ok else "down",
|
||||
"database": "up" if db_ok else "down",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def root() -> dict[str, str]:
|
||||
"""根路径"""
|
||||
return {
|
||||
"service": "QTrade Gateway",
|
||||
"version": settings.app.version,
|
||||
"docs": "/docs" if settings.app.debug else "disabled",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/ping")
|
||||
async def ping() -> dict[str, str]:
|
||||
"""简单的存活检查"""
|
||||
return {"status": "pong"}
|
||||
104
src/gateway/routes/market.py
Normal file
104
src/gateway/routes/market.py
Normal file
@ -0,0 +1,104 @@
|
||||
"""
|
||||
行情路由
|
||||
|
||||
提供行情数据查询接口(转发到 Data Service)
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models.market import Quote, KlineData, KlineQuery
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger("gateway.market")
|
||||
|
||||
|
||||
@router.get("/quote/{symbol}")
|
||||
async def get_quote(symbol: str) -> dict[str, Any]:
|
||||
"""
|
||||
获取实时行情
|
||||
|
||||
Args:
|
||||
symbol: 股票代码,如 000001.SZ
|
||||
"""
|
||||
# TODO: 转发到 Data Service 或从 Redis 获取
|
||||
logger.info(f"获取行情: {symbol}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"symbol": symbol,
|
||||
"price": 0,
|
||||
"message": "Data Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/kline/{symbol}")
|
||||
async def get_kline(
|
||||
symbol: str,
|
||||
period: str = Query(
|
||||
default="1d", description="K线周期: 1m, 5m, 15m, 30m, 60m, 1d, 1w"
|
||||
),
|
||||
start_time: Optional[datetime] = Query(default=None, description="开始时间"),
|
||||
end_time: Optional[datetime] = Query(default=None, description="结束时间"),
|
||||
limit: int = Query(default=100, ge=1, le=1000, description="返回数量"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
获取 K 线数据
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
period: K线周期
|
||||
start_time: 开始时间
|
||||
end_time: 结束时间
|
||||
limit: 返回数量限制
|
||||
"""
|
||||
# TODO: 转发到 Data Service
|
||||
logger.info(f"获取K线: {symbol}, 周期: {period}, 数量: {limit}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"symbol": symbol,
|
||||
"period": period,
|
||||
"klines": [],
|
||||
"message": "Data Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/quotes")
|
||||
async def get_quotes(
|
||||
symbols: str = Query(..., description="股票代码列表,逗号分隔"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
批量获取实时行情
|
||||
|
||||
Args:
|
||||
symbols: 股票代码列表,逗号分隔,如 000001.SZ,000002.SZ
|
||||
"""
|
||||
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) > 50:
|
||||
raise HTTPException(status_code=400, detail="一次最多查询50只股票")
|
||||
|
||||
# TODO: 转发到 Data Service
|
||||
logger.info(f"批量获取行情: {symbol_list}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"quotes": [],
|
||||
"message": "Data Service 未实现",
|
||||
},
|
||||
}
|
||||
124
src/gateway/routes/trading.py
Normal file
124
src/gateway/routes/trading.py
Normal file
@ -0,0 +1,124 @@
|
||||
"""
|
||||
交易路由
|
||||
|
||||
提供交易相关接口(转发到 Core Service)
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models.order import OrderCreate, OrderCancel, OrderStatus
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger("gateway.trading")
|
||||
|
||||
|
||||
@router.post("/order")
|
||||
async def create_order(order: OrderCreate) -> dict[str, Any]:
|
||||
"""
|
||||
创建订单
|
||||
|
||||
Args:
|
||||
order: 订单创建请求
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"创建订单: {order.symbol}, {order.side}, 数量: {order.quantity}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"order_id": None,
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/order/{order_id}")
|
||||
async def cancel_order(order_id: str, reason: Optional[str] = None) -> dict[str, Any]:
|
||||
"""
|
||||
撤销订单
|
||||
|
||||
Args:
|
||||
order_id: 订单ID
|
||||
reason: 撤销原因
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"撤销订单: {order_id}, 原因: {reason}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"order_id": order_id,
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/order/{order_id}")
|
||||
async def get_order(order_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询订单详情
|
||||
|
||||
Args:
|
||||
order_id: 订单ID
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询订单: {order_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": None,
|
||||
"message": "Core Service 未实现",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/orders")
|
||||
async def list_orders(
|
||||
pairing_id: Optional[str] = Query(default=None, description="配对ID"),
|
||||
symbol: Optional[str] = Query(default=None, description="股票代码"),
|
||||
status: Optional[OrderStatus] = Query(default=None, description="订单状态"),
|
||||
page: int = Query(default=1, ge=1, description="页码"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询订单列表
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询订单列表: pairing={pairing_id}, symbol={symbol}, status={status}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"orders": [],
|
||||
"total": 0,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/orders/active")
|
||||
async def list_active_orders(
|
||||
pairing_id: Optional[str] = Query(default=None, description="配对ID"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询活跃订单(未完成的订单)
|
||||
"""
|
||||
# TODO: 转发到 Core Service
|
||||
logger.info(f"查询活跃订单: pairing={pairing_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"orders": [],
|
||||
"message": "Core Service 未实现",
|
||||
},
|
||||
}
|
||||
@ -110,7 +110,7 @@ def run_service(service_name: str) -> None:
|
||||
config["module"],
|
||||
host=config["host"],
|
||||
port=config["port"],
|
||||
reload=settings.app.debug,
|
||||
reload=False, # Windows 下 reload 可能有问题,暂时关闭
|
||||
log_level="info" if settings.app.debug else "warning",
|
||||
)
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user