Commit Graph
9 Commits
Author SHA1 Message Date
momentum devandClaude Opus 4.8 559083b4ab Day-extension entry guard + percentage breakeven stop
Day-extension guard (the H1 gap from the prior review): the trigger-extension
ceiling only sees distance above the ORB high, so a name up huge intraday whose
break is itself CLEAN slips through — real example ATPC, entered +1.7% above the
trigger yet +32% above the session open, now a loser. New guard blocks when the
entry is > day_extension_max_pct above the SESSION OPEN. Default 0.30 calibrated
on 22 real fires: normal entries are <=14% above the open, the parabolic tail is
20-83% (ICCM +83/+41, BIRD +36, ATPC +34/+32, NEOV +29). day_open is computed in
step_arm (first RTH bar open), carried on ArmedTrigger, checked in
submit_breakout_now. Env TRADING_DAY_EXTENSION_MAX_PCT; 0 = off.

Percentage breakeven (the "ratchet to a better stop once it works" request): the
broker-side stop ratchet already exists (exit_manager replace_order), but its
earliest move was +1R — a big move for a wide opening-range stop. breakeven_at_pct
moves the stop to entry once price is +this fraction above entry, BEFORE 1R, so a
pop that reverses can't round-trip to a loss (the documented small-cap failure).
Lives in the shared strategy/exits._trail_stop (backtest + live agree), only ever
ratchets up. Default 0.05 live (TRADING_EXIT_BREAKEVEN_PCT); _is_active updated so
the manager runs when it's the only rule set.

tests/unit: 160 passed (+ day-ext block/allow/no-open, + pct-breakeven move/hold/
saves-reverser).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 07:49:27 -04:00
momentum devandClaude Opus 4.8 129e8d4b15 Cleanup: consolidate flatten logic + refresh .env.example
- Extract the cancel-protective-legs-then-close routine (duplicated in the exit
  manager and the execution service after fixing the held-qty 403 in both) into
  one shared, heavily-documented helper: runtime/flatten.py. Both callers now
  delegate, so the fix can't drift out of sync. Behaviour unchanged; 121 tests
  pass.
- Refresh .env.example: document every key added this session (liquidity gate +
  sizing, backout cooldown, re-entry guard, managed-exit ladder, EOD flatten)
  with the why, and flag MAX_DAILY_LOSS_PCT to revert to 0.03 before live.
- Remove throwaway data/_watch_*.py monitoring scripts (gitignored clutter).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 16:51:35 -04:00
momentum devandClaude Opus 4.8 e8533446b2 Exit manager: cancel protective orders before market-closing (held qty)
The trail-breach (and first-red) exit called close_position directly, but the
bracket stop/TP legs RESERVE the full quantity (held_for_orders). Alpaca then
rejects the market close 403 "insufficient qty available (available: 0)". The
position can never exit, so the manager retried every pass forever — observed
live: PLUG logged 191 identical 403s while a legitimate trail exit (+286) and
WPRT/ATPC stop-outs were all blocked.

Add _flatten(): cancel the symbol's active protective sell legs to release the
shares, THEN liquidate (retry the close so a not-yet-settled cancel doesn't
hang). Route the two full-close paths through it. Verified live: PLUG flattened
cleanly (0 dangling orders, profit locked), zero 403s after restart, remaining
book still fully stop-protected. Test: _flatten cancels protective then closes;
42 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:28:23 -04:00
momentum devandClaude Opus 4.8 11ab6c7b56 Exit manager: scope get_orders to held symbols (stop-leg truncation)
Alpaca's orders `limit` keeps only the most-RECENT orders and counts child
legs toward the cap. On a busy day the order list runs to hundreds (every
backed-out entry is an order), so the exit manager's limit=100 snapshot
silently dropped the stop legs of older OPEN positions. A stop-leg lookup then
read "no stop" on a fully-protected position -> broken trailing/profit-lock for
that name (and false-naked alarms in monitoring).

Fix: get_orders gains a `symbols` filter; the exit manager scopes its snapshot
to the handful of held names (no truncation possible). Verified live: an
unscoped limit=100 query reported PLUG stop=None while the scoped query
correctly surfaced PLUG's stop @2.65.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 12:34:43 -04:00
momentum devandClaude Opus 4.8 6dfc074c6d Profit-lock checkpoints + fix uPnL display
- strategy/exits.py: percentage profit-lock tiers (TRADING_EXIT_PROFIT_TIERS,
  e.g. 8:3,15:9,25:18,40:30). Once a trade has been up gain%, the stop is pinned
  to entry*(1+lock%) so a winner can only give back to a locked-in minimum gain
  and a fade sells you out IN PROFIT. Shared by backtest + live, active-trades
  only (ratchets the broker stop up via replace, never cancel).
- momentum_cli.py: open-positions uPnL was reading 'unrealized_pl' but the sync
  stores 'unrealized_pnl' -> always blank. Read the right key (+ green/red).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 15:57:27 -04:00
momentum devandClaude Opus 4.8 52b43245d5 Fix slow loop passes: cache account/positions + fewer broker calls
The single-threaded passes (and the trigger thread) ballooned to 60-120s.
Cause: flaky WSL DNS makes ~1 in 5 Alpaca calls take ~5s to resolve, and each
pass fired ~20 calls (breaker, sync, guard, exit manager all re-reading
account/positions/orders). Fixes:
- client: 2.5s TTL cache for get_account/get_positions (invalidated on any
  order mutation) — collapses the redundant per-pass reads to one.
- exit manager: fetch the (heavy) status=all orders snapshot ONCE per pass and
  reuse it for every position's stop-leg + entry-time lookup (was 2 calls/pos).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 15:21:31 -04:00
momentum devandClaude Opus 4.8 9cc02e01ac Exit manager: trail from actual broker fill time
Track entry_ts from the broker entry order's filled_at (not first-sight), so the
high-water mark and R-multiple reflect the move since the real entry — correct
trailing for positions that predate the manager (e.g. across a restart).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 13:36:49 -04:00
momentum devandClaude Opus 4.8 2a315d87d6 Exit manager: find held stop legs + trail-breach market exit
Two fixes found by running the manager against the live book:
- _stop_leg queried status="open", but a bracket's protective stop is a 'held'
  child of the FILLED entry, so it was never found -> stops never trailed.
  Query status="all" and match active leg statuses.
- when the trailed stop would sit ABOVE current price (price fell back through
  the prior swing low), a sell-stop there is rejected; that IS the trail firing,
  so exit at market instead.
Also drop the hardcoded "6" in the board title (armed set is now 10).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 13:28:25 -04:00
momentum devandClaude Opus 4.8 ab5a92447f Managed exits (swept + OOS-verified) + bigger armed set
Replace the static -1R/+2R bracket with active, parameterised exit management
shared by the backtest and live (strategy/exits.py): move to breakeven, trail
under prior-bar lows or by %, scale out, or first-red exit.

Swept all variants over 187 sessions with a held-out train/test split
(sweep_exits.py), then an adversarial 3-judge workflow picked the robust winner
OUT-OF-SAMPLE: trailLow_a1 (trail under the prior bar's low after +1R) — test
avgR 0.128 vs the old static_2R 0.067 (~1.9x), win 49% vs 38%. The naive
in-sample winner (trailPct10) was correctly rejected as overfit
(train 0.684 -> test 0.085).

- strategy/exits.py: ExitConfig + simulate_exit (backtest) + manage_live (live)
- strategy/backtest/engine.py: simulate the managed exit on entry; Trade.entry_index
- runtime/exit_manager.py: live manager — ratchets the broker stop UP via
  REPLACE/PATCH (never cancel = never naked), scales out, first-red exit
- alpaca_paper/client.py: replace_order (PATCH) + partial close_position
- run_live_paper.py: 'exits' step (12s); TRIGGER_MAX_ARMED 6 -> 10
- tests: exits sim/live + manager ratchet-never-cancel

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 13:16:47 -04:00