Files
signal-platform/app/routers/trades.py
T
dennisthiessenandClaude Fable 5 6a10c8ff09 fix: guarantee shadow scan freshness, long-only, user-scoped setup list
Second review round on the shadow book; all three findings were real.

- Scan freshness is now proven, not assumed. Pipeline steps run and fail
  independently, so a disabled or failed scan step still let the shadow
  step run on the newest *stored* setups -- a prior session's picks at
  stale prices. scan_all_tickers now records a run boundary
  (last_scan_run_started_at / _completed_at) only on successful
  completion; the shadow book refuses to trade unless COMPLETED is fresh
  and selects only setups with detected_at >= the run start. Deduplication
  to the latest row per ticker now happens BEFORE qualification, so a newer
  unqualified row suppresses an older qualified one rather than the reverse.

- Shadow selection is hard long-only. setup_qualifies only enforces
  long-only when min_momentum_percentile > 0, but 0 is a legal admin
  setting, and the cash accounting assumes long positions -- so the
  constraint is enforced in shadow selection regardless of gate config.

- The personal setup list excludes only the caller's own open positions.
  get_trade_setups gained exclude_open_trade_user_id; the trades route
  passes the authenticated user, while the Telegram broadcast stays global
  since it has no single owner.

New tests cover stale/absent scan markers, prior-run exclusion, newer
unqualified suppressing older qualified, long-only under a disabled gate,
and both sides of the user-scoped exclusion.

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

136 lines
5.1 KiB
Python

"""Trades router — R:R scanner trade setup endpoints."""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.dependencies import get_db, require_access
from app.schemas.common import APIEnvelope
from app.schemas.trade_setup import RecommendationSummaryResponse, TradeSetupResponse
from app.services import admin_service
from app.services.outcome_service import get_performance_stats
from app.services.rr_scanner_service import get_trade_setup_history, get_trade_setups
router = APIRouter(tags=["trades"])
@router.get("/trades", response_model=APIEnvelope)
async def list_trade_setups(
direction: str | None = Query(
None, description="Filter by direction: long or short"
),
min_confidence: float | None = Query(
None, ge=0, le=100, description="Minimum confidence score"
),
recommended_action: str | None = Query(
None,
description="Filter by action: LONG_HIGH, LONG_MODERATE, SHORT_HIGH, SHORT_MODERATE, NEUTRAL",
),
user=Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
"""Get latest trade setups with recommendation data."""
rows = await get_trade_setups(
db,
direction=direction,
min_confidence=min_confidence,
recommended_action=recommended_action,
live_recommendation=True,
exclude_open_trade_tickers=True,
exclude_open_trade_user_id=user.id,
exclude_reentry_gate_locked_tickers=True,
)
data = []
for row in rows:
summary = RecommendationSummaryResponse(
action=row.get("recommended_action") or "NEUTRAL",
reasoning=row.get("reasoning"),
risk_level=row.get("risk_level"),
composite_score=row["composite_score"],
)
payload = {**row, "recommendation_summary": summary}
data.append(TradeSetupResponse(**payload).model_dump(mode="json"))
return APIEnvelope(status="success", data=data)
@router.get("/trades/activation", response_model=APIEnvelope)
async def get_activation_thresholds(
_user=Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
"""Activation thresholds (min R:R, min confidence) for actionable signals.
Readable by any user with access — drives Signals-page default filters
and the Dashboard's qualified-setup metrics. Configured by admins via
PUT /admin/settings/activation.
"""
config = await admin_service.get_activation_config(db)
return APIEnvelope(status="success", data=config)
@router.get("/trades/performance", response_model=APIEnvelope)
async def get_trade_performance(
qualified_only: bool = Query(
False, description="Restrict overall/direction/action stats to setups that clear the activation gate"
),
_user=Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
"""Aggregate setup-outcome statistics (gate barrier diagnostic).
Outcomes come from the nightly outcome_evaluator: win = gate target first,
loss = stop first, expired = neither in the window. This is **not** the
production ATR-trail book; it checks setup grading plumbing only.
With qualified_only, overall/direction/action cover only gate-clearing
setups; the confidence breakdown always covers all setups.
"""
config = await admin_service.get_activation_config(db) if qualified_only else None
stats = await get_performance_stats(db, config=config)
return APIEnvelope(status="success", data=stats)
@router.get("/trades/{symbol}", response_model=APIEnvelope)
async def get_ticker_trade_setups(
symbol: str,
_user=Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
rows = await get_trade_setups(
db,
symbol=symbol,
live_recommendation=True,
include_reentry_gate_lock=True,
)
data = []
for row in rows:
summary = RecommendationSummaryResponse(
action=row.get("recommended_action") or "NEUTRAL",
reasoning=row.get("reasoning"),
risk_level=row.get("risk_level"),
composite_score=row["composite_score"],
)
payload = {**row, "recommendation_summary": summary}
data.append(TradeSetupResponse(**payload).model_dump(mode="json"))
return APIEnvelope(status="success", data=data)
@router.get("/trades/{symbol}/history", response_model=APIEnvelope)
async def get_ticker_trade_history(
symbol: str,
_user=Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
rows = await get_trade_setup_history(db, symbol=symbol)
data = []
for row in rows:
summary = RecommendationSummaryResponse(
action=row.get("recommended_action") or "NEUTRAL",
reasoning=row.get("reasoning"),
risk_level=row.get("risk_level"),
composite_score=row["composite_score"],
)
payload = {**row, "recommendation_summary": summary}
data.append(TradeSetupResponse(**payload).model_dump(mode="json"))
return APIEnvelope(status="success", data=data)