Files
signal-platform/app/routers/paper_trades.py
T
dennisthiessenandClaude Fable 5 06fdd92faa
Deploy / lint (push) Successful in 7s
Deploy / test (push) Successful in 1m9s
Deploy / deploy (push) Successful in 36s
Overview: focus|radar pairing, selectable radar, performance chart
Layout regrouped by relationship, not size: the setup-in-focus card
and the radar sit side by side (they are one decision surface), the
four account ribbons move directly above the open positions they
describe, and a new performance chart closes the page.

- Radar rows are selectable: clicking one swaps the focus card to that
  setup - including below-gate rows, whose card shows a muted
  "rank N / below gate" badge and the disqualify reason in the footer,
  with a "back to top pick" reset. The row currently in focus is
  highlighted; ticker links still deep-link without selecting.
- Performance chart (the mockup's missing piece): new
  GET /paper-trades/equity-curve computes, per benchmark trading day
  since the first paper trade, the book's cumulative P&L (realized +
  mark-to-market from stored OHLCV) vs the same cost basis riding SPY
  over each trade's window (benchmark_prices). Pure curve math in
  paper_trade_service with unit tests; hidden until there are 2+
  points of data. Frontend renders both lines with crosshair readout,
  zero baseline, and direct end labels.

Backend unit suite: 501 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 18:09:31 +02:00

112 lines
3.7 KiB
Python

"""Paper trades router — take, list, and close simulated trades."""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.dependencies import get_db, require_access, require_admin
from app.models.user import User
from app.schemas.common import APIEnvelope
from app.schemas.paper_trade import (
ExitPolicyUpdate,
PaperTradeClose,
PaperTradeCreate,
PaperTradeResponse,
)
from app.services import paper_trade_service
router = APIRouter(tags=["paper-trades"])
def _resp(trade, symbol: str, current_price=None) -> dict:
return PaperTradeResponse(
id=trade.id,
symbol=symbol,
direction=trade.direction,
entry_price=trade.entry_price,
shares=trade.shares,
stop_loss=trade.stop_loss,
target=trade.target,
status=trade.status,
opened_at=trade.opened_at,
close_price=trade.close_price,
closed_at=trade.closed_at,
current_price=current_price,
).model_dump(mode="json")
@router.get("/paper-trades", response_model=APIEnvelope)
async def list_paper_trades(
status: str | None = Query(default=None, pattern=r"^(open|closed)$"),
user: User = Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
rows = await paper_trade_service.list_trades(db, user.id, status=status)
data = [PaperTradeResponse(**r).model_dump(mode="json") for r in rows]
return APIEnvelope(status="success", data=data)
@router.get("/paper-trades/exit-policy", response_model=APIEnvelope)
async def read_exit_policy(
_user: User = Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
"""The active auto-exit policy for open paper trades (shown in the UI)."""
return APIEnvelope(status="success", data=await paper_trade_service.get_exit_policy(db))
@router.get("/paper-trades/equity-curve", response_model=APIEnvelope)
async def paper_trade_equity_curve(
user: User = Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
"""Daily cumulative P&L of the paper book vs the same dollars riding SPY."""
return APIEnvelope(
status="success", data=await paper_trade_service.equity_curve(db, user.id)
)
@router.put("/paper-trades/exit-policy", response_model=APIEnvelope)
async def write_exit_policy(
body: ExitPolicyUpdate,
_user: User = Depends(require_admin),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
"""Change the auto-exit policy (admin)."""
data = await paper_trade_service.set_exit_policy(
db,
mode=body.mode,
trailing_pct=body.trailing_pct,
atr_multiplier=body.atr_multiplier,
hold_days=body.hold_days,
)
return APIEnvelope(status="success", data=data)
@router.post("/paper-trades", response_model=APIEnvelope, status_code=201)
async def create_paper_trade(
body: PaperTradeCreate,
user: User = Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
trade = await paper_trade_service.create_trade(
db, user.id,
symbol=body.symbol,
direction=body.direction,
entry_price=body.entry_price,
shares=body.shares,
stop_loss=body.stop_loss,
target=body.target,
)
return APIEnvelope(status="success", data=_resp(trade, body.symbol.strip().upper()))
@router.post("/paper-trades/{trade_id}/close", response_model=APIEnvelope)
async def close_paper_trade(
trade_id: int,
body: PaperTradeClose,
user: User = Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
trade = await paper_trade_service.close_trade(db, user.id, trade_id, body.close_price)
return APIEnvelope(status="success", data={"id": trade.id, "status": trade.status})