summaryrefslogtreecommitdiff
path: root/services/api/src/trading_api/routers/orders.py
blob: a29ae2f55177152d78935f2467ea172d5f6bfeb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Order endpoints."""

import logging

from fastapi import APIRouter, HTTPException, Request
from shared.sa_models import OrderRow, SignalRow
from sqlalchemy import select
from sqlalchemy.exc import OperationalError

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/")
async def get_orders(request: Request, limit: int = 50):
    """Get recent orders."""
    try:
        db = request.app.state.db
        async with db.get_session() as session:
            stmt = select(OrderRow).order_by(OrderRow.created_at.desc()).limit(limit)
            result = await session.execute(stmt)
            rows = result.scalars().all()
            return [
                {
                    "id": r.id,
                    "signal_id": r.signal_id,
                    "symbol": r.symbol,
                    "side": r.side,
                    "type": r.type,
                    "price": float(r.price),
                    "quantity": float(r.quantity),
                    "status": r.status,
                    "created_at": r.created_at.isoformat() if r.created_at else None,
                    "filled_at": r.filled_at.isoformat() if r.filled_at else None,
                }
                for r in rows
            ]
    except OperationalError as exc:
        logger.error("Database error fetching orders: %s", exc)
        raise HTTPException(status_code=503, detail="Database unavailable")
    except Exception as exc:
        logger.error("Failed to get orders: %s", exc, exc_info=True)
        raise HTTPException(status_code=500, detail="Failed to retrieve orders")


@router.get("/signals")
async def get_signals(request: Request, limit: int = 50):
    """Get recent signals."""
    try:
        db = request.app.state.db
        async with db.get_session() as session:
            stmt = select(SignalRow).order_by(SignalRow.created_at.desc()).limit(limit)
            result = await session.execute(stmt)
            rows = result.scalars().all()
            return [
                {
                    "id": r.id,
                    "strategy": r.strategy,
                    "symbol": r.symbol,
                    "side": r.side,
                    "price": float(r.price),
                    "quantity": float(r.quantity),
                    "reason": r.reason,
                    "created_at": r.created_at.isoformat() if r.created_at else None,
                }
                for r in rows
            ]
    except OperationalError as exc:
        logger.error("Database error fetching signals: %s", exc)
        raise HTTPException(status_code=503, detail="Database unavailable")
    except Exception as exc:
        logger.error("Failed to get signals: %s", exc, exc_info=True)
        raise HTTPException(status_code=500, detail="Failed to retrieve signals")