|
| 1 | +"""Backtest endpoints: enqueue backtest jobs and fetch results.""" |
| 2 | +from __future__ import annotations |
| 3 | +import uuid |
| 4 | +import os |
| 5 | +from fastapi import APIRouter, Depends, BackgroundTasks, UploadFile, File, HTTPException, WebSocket |
| 6 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +from .. import schemas, db, models, auth |
| 10 | +from ..tasks.celery_app import celery_app |
| 11 | +from ..utils.ws_manager import manager |
| 12 | + |
| 13 | +router = APIRouter(prefix="/api/backtest", tags=["backtest"]) |
| 14 | + |
| 15 | + |
| 16 | +@router.post("/", response_model=schemas.BacktestStatus) |
| 17 | +async def submit_backtest(req: schemas.BacktestRequest, current_user=Depends(auth.require_active_user), session: AsyncSession = Depends(db.get_session)): |
| 18 | + # Create job |
| 19 | + job_id = uuid.uuid4().hex |
| 20 | + job = models.BacktestJob(id=job_id, user_id=current_user.id, status="queued", params=req.dict()) |
| 21 | + session.add(job) |
| 22 | + await session.commit() |
| 23 | + |
| 24 | + # Enqueue celery task |
| 25 | + celery_app.send_task("quant_research_starter.api.tasks.tasks.run_backtest", args=[job_id, req.dict()]) |
| 26 | + |
| 27 | + return {"job_id": job_id, "status": "queued"} |
| 28 | + |
| 29 | + |
| 30 | +@router.get("/{job_id}/results") |
| 31 | +async def get_results(job_id: str, current_user=Depends(auth.require_active_user), session: AsyncSession = Depends(db.get_session)): |
| 32 | + q = await session.execute(models.BacktestJob.__table__.select().where(models.BacktestJob.id == job_id)) |
| 33 | + row = q.first() |
| 34 | + if not row: |
| 35 | + raise HTTPException(status_code=404, detail="Job not found") |
| 36 | + job = row[0] |
| 37 | + if job.user_id != current_user.id and current_user.role != "admin": |
| 38 | + raise HTTPException(status_code=403, detail="Not authorized to view this job") |
| 39 | + |
| 40 | + if job.result_path and os.path.exists(job.result_path): |
| 41 | + import json |
| 42 | + |
| 43 | + with open(job.result_path, "r") as f: |
| 44 | + return json.load(f) |
| 45 | + return {"status": job.status} |
| 46 | + |
| 47 | + |
| 48 | +@router.websocket("/ws/{job_id}") |
| 49 | +async def websocket_backtest(websocket: WebSocket, job_id: str): |
| 50 | + """WebSocket endpoint that registers the client and relays messages from Redis pub/sub. |
| 51 | +
|
| 52 | + The Redis listener broadcasts messages to the ConnectionManager which then sends |
| 53 | + them to connected WebSocket clients. |
| 54 | + """ |
| 55 | + await manager.connect(job_id, websocket) |
| 56 | + try: |
| 57 | + while True: |
| 58 | + # keep the connection alive; client may send ping messages |
| 59 | + msg = await websocket.receive_text() |
| 60 | + # ignore incoming messages; server pushes updates |
| 61 | + await websocket.send_text("ok") |
| 62 | + except Exception: |
| 63 | + manager.disconnect(job_id, websocket) |
| 64 | + try: |
| 65 | + await websocket.close() |
| 66 | + except Exception: |
| 67 | + pass |
0 commit comments