Review of the shadow book found seven ways the two books could leak into
each other; all are fixed here. The most serious silently invalidated the
comparison the shadow book exists to make.
- Shadow holdings no longer suppress the manual candidate list. The
open-trade exclusion filtered on any book, so shadow taking the
top-ranked names removed exactly those from the user's list and alerts,
confining the discretionary book to leftovers. Scoped to the manual
book. Closed-trade alerts and paper-book equity were leaking the same
way and are likewise scoped.
- Shadow sizing now matches _simulate_portfolio: min(1% risk, 20% notional
cap, available cash) from marked equity, plus the sub- dust guard.
Previously risk-only from realized equity, so a tight stop produced a
multiples-of-equity leveraged position the strategy would never take.
- Shadow only trades setups from the scan that just ran (<6h old) with one
setup per ticker. A failed or disabled scan step could otherwise open
positions from a prior session at stale prices.
- Gate-reset transitions are observed for both books, so a shadow stop-out
completes fail -> requalify instead of staying locked forever.
- Manual list/close endpoints default to the manual book and reject
hand-closing shadow trades; the performance endpoint is scoped to the
caller so 'your picks' is not every user's book.
- run_shadow_book is registered as a paused job so Admin can trigger it.
Also anchors three pre-existing paper-trade tests (and the new alpaca
window test) on the UTC date. They build fixtures from the local date but
the service stamps opened_at in UTC, so they failed only between 00:00 and
02:00 in a UTC+hh timezone -- latent on ba2df8b, exposed by the clock.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
124 lines
4.2 KiB
Python
124 lines
4.2 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.get("/paper-trades/performance", response_model=APIEnvelope)
|
|
async def paper_trade_performance(
|
|
user: User = Depends(require_access),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> APIEnvelope:
|
|
"""Shadow book vs discretionary book vs SPY since the configured start date."""
|
|
return APIEnvelope(
|
|
status="success",
|
|
data=await paper_trade_service.performance_summary(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})
|