You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.6 KiB
71 lines
2.6 KiB
from fastapi import APIRouter, HTTPException, Query
|
|
from schemas import ConnectRequest, ConnectResponse, ContractResponse, TickResponse, KlineResponse, DisconnectResponse
|
|
from tqapi_service import TqApiService
|
|
|
|
router = APIRouter()
|
|
tq_service = TqApiService()
|
|
|
|
@router.post("/connect", response_model=ConnectResponse)
|
|
async def connect(request: ConnectRequest):
|
|
"""连接到天勤服务器"""
|
|
try:
|
|
success = await tq_service.connect(request.username, request.password)
|
|
if success:
|
|
return ConnectResponse(success=True, message="连接成功")
|
|
else:
|
|
raise HTTPException(status_code=400, detail="连接失败")
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/contracts", response_model=ContractResponse)
|
|
async def get_contracts():
|
|
"""获取合约列表"""
|
|
try:
|
|
contracts = await tq_service.get_contracts()
|
|
return ContractResponse(success=True, data=contracts)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/contract/{symbol}", response_model=ContractResponse)
|
|
async def get_contract(symbol: str):
|
|
"""获取合约详情"""
|
|
try:
|
|
contract = await tq_service.get_contract(symbol)
|
|
return ContractResponse(success=True, data=contract)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/klines/{symbol}", response_model=KlineResponse)
|
|
async def get_klines(
|
|
symbol: str,
|
|
period: str = Query(..., description="周期,如 1M, 5M, 1H, 1D"),
|
|
count: int = Query(30, description="数据数量")
|
|
):
|
|
"""获取 K 线数据"""
|
|
try:
|
|
klines = await tq_service.get_klines(symbol, period, count)
|
|
return KlineResponse(success=True, data=klines)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/tick/{symbol}", response_model=TickResponse)
|
|
async def get_tick(symbol: str):
|
|
"""获取 tick 数据"""
|
|
try:
|
|
tick = await tq_service.get_tick(symbol)
|
|
return TickResponse(success=True, data=tick)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.post("/disconnect", response_model=DisconnectResponse)
|
|
async def disconnect():
|
|
"""断开连接"""
|
|
try:
|
|
success = await tq_service.disconnect()
|
|
if success:
|
|
return DisconnectResponse(success=True, message="断开成功")
|
|
else:
|
|
raise HTTPException(status_code=400, detail="断开失败")
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|