From 6dfc074c6dfd7bc1b7825f75afd4e0d6f74c59dd Mon Sep 17 00:00:00 2001 From: momentum dev Date: Wed, 17 Jun 2026 15:57:27 -0400 Subject: [PATCH] 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 --- momentum_cli.py | 12 +++++++++--- runtime/exit_manager.py | 3 ++- strategy/exits.py | 34 ++++++++++++++++++++++++++++++++++ tests/unit/test_exits.py | 22 ++++++++++++++++++++++ 4 files changed, 67 insertions(+), 4 deletions(-) diff --git a/momentum_cli.py b/momentum_cli.py index 899f2c5..f68b58c 100644 --- a/momentum_cli.py +++ b/momentum_cli.py @@ -503,9 +503,15 @@ def _render_board(con): pt.add_column("symbol"); pt.add_column("qty", justify="right"); pt.add_column("uPnL", justify="right") if pos_ev: for p in (json.loads(pos_ev[0][0]).get("positions") or []): - upl = p.get("unrealized_pl") - pt.add_row(str(p.get("symbol")), str(p.get("quantity") or p.get("qty") or ""), - f"{float(upl):+.2f}" if upl not in (None, "") else "-") + # the sync stores it as 'unrealized_pnl'; fall back to 'unrealized_pl' + upl = p.get("unrealized_pnl") + if upl is None: + upl = p.get("unrealized_pl") + try: + upl_str = f"[{'green' if float(upl) >= 0 else 'red'}]{float(upl):+.0f}[/]" + except (TypeError, ValueError): + upl_str = "-" + pt.add_row(str(p.get("symbol")), str(p.get("quantity") or p.get("qty") or ""), upl_str) risk = con.execute("SELECT timestamp, message FROM events WHERE event_type='risk_rule_triggered' " "ORDER BY timestamp DESC LIMIT 4").fetchall() diff --git a/runtime/exit_manager.py b/runtime/exit_manager.py index d66ea90..09a08f1 100644 --- a/runtime/exit_manager.py +++ b/runtime/exit_manager.py @@ -35,7 +35,8 @@ class _Tracked: def _is_active(cfg: ExitConfig) -> bool: return bool(cfg and (cfg.breakeven_at_r or cfg.trail_mode != TRAIL_NONE - or cfg.scale_out_r or cfg.first_red_exit)) + or cfg.scale_out_r or cfg.first_red_exit + or cfg.profit_lock_tiers)) class LiveExitManager: diff --git a/strategy/exits.py b/strategy/exits.py index 3a39511..135118e 100644 --- a/strategy/exits.py +++ b/strategy/exits.py @@ -32,6 +32,25 @@ TRAIL_PRIOR_LOW = "prior_low" TRAIL_PCT = "pct" +def parse_profit_tiers(raw: str) -> list[tuple[float, float]]: + """Parse 'gain:lock' percentage pairs, e.g. '8:3,15:9' -> [(.08,.03),(.15,.09)]. + + Each pair means: once price has been up >= gain%, never let the trade close + for less than lock% of profit (the stop ratchets to entry*(1+lock%)). + """ + tiers: list[tuple[float, float]] = [] + for part in (raw or "").split(","): + part = part.strip() + if ":" not in part: + continue + g, lock = part.split(":", 1) + try: + tiers.append((float(g) / 100.0, float(lock) / 100.0)) + except ValueError: + continue + return sorted(tiers) # ascending by gain trigger + + @dataclass class ExitConfig: target_r: float = 2.0 # final take-profit in R (0 = no fixed target) @@ -42,6 +61,10 @@ class ExitConfig: scale_out_r: float = 0.0 # sell scale_out_pct at +this R (0 = off) scale_out_pct: float = 0.5 # fraction sold at scale_out_r first_red_exit: bool = False # exit on first close below the prior bar's low + # percentage profit-lock checkpoints: [(gain_frac, lock_frac), ...]. Once the + # trade has been up gain%, the stop never sits below entry*(1+lock%) — so a + # winner can only give back down to a locked-in minimum gain. + profit_lock_tiers: list = field(default_factory=list) @classmethod def from_env(cls, env: dict | None = None) -> "ExitConfig": @@ -67,6 +90,7 @@ class ExitConfig: scale_out_r=f("TRADING_EXIT_SCALE_OUT_R", "0.0"), scale_out_pct=f("TRADING_EXIT_SCALE_OUT_PCT", "0.5"), first_red_exit=b("TRADING_EXIT_FIRST_RED", "0"), + profit_lock_tiers=parse_profit_tiers(v.get("TRADING_EXIT_PROFIT_TIERS", "")), ) def describe(self) -> str: @@ -80,6 +104,9 @@ class ExitConfig: parts.append(f"scale {self.scale_out_pct:.0%}@{self.scale_out_r:g}R") if self.first_red_exit: parts.append("first-red") + if self.profit_lock_tiers: + parts.append("lock " + "/".join( + f"+{g * 100:g}%->{lk * 100:g}%" for g, lk in self.profit_lock_tiers)) return ", ".join(parts) @@ -109,6 +136,13 @@ def _trail_stop(stop: float, entry: float, high_water: float, new = max(new, bar_low) elif cfg.trail_mode == TRAIL_PCT and cfg.trail_pct > 0: new = max(new, high_water * (1.0 - cfg.trail_pct)) + # percentage profit-lock checkpoints: once the trade has been up gain%, pin + # the stop to at least entry*(1+lock%) so a winner keeps a minimum gain. + if cfg.profit_lock_tiers and entry > 0: + gain = (high_water - entry) / entry + for gain_pct, lock_pct in cfg.profit_lock_tiers: + if gain >= gain_pct: + new = max(new, entry * (1.0 + lock_pct)) return new diff --git a/tests/unit/test_exits.py b/tests/unit/test_exits.py index 54ed22e..bb962b4 100644 --- a/tests/unit/test_exits.py +++ b/tests/unit/test_exits.py @@ -11,10 +11,32 @@ from strategy.exits import ( TRAIL_PCT, TRAIL_PRIOR_LOW, manage_live, + parse_profit_tiers, simulate_exit, ) +def test_parse_profit_tiers(): + assert parse_profit_tiers("8:3,15:9") == [(0.08, 0.03), (0.15, 0.09)] + assert parse_profit_tiers("") == [] + + +def test_profit_lock_keeps_minimum_gain(): + # entry 10, stop 9. price runs to +12% (11.2) then fades; +8%->lock+3% tier + # pins the stop to 10.30, so the fade exits in profit instead of at the stop. + bars = _bars([(10.5, 9.9, 10.4), (11.2, 10.6, 11.0), (10.4, 9.5, 9.6)]) + cfg = ExitConfig(target_r=20.0, profit_lock_tiers=[(0.08, 0.03)]) + r = simulate_exit(10.0, 9.0, bars, cfg) + assert r.fills[-1].price >= 10.30 - 1e-6 # sold at/above the +3% lock + assert r.r_multiple > 0 # a locked-in WIN, not a loss + + +def test_profit_lock_live_desired_stop(): + bars = _bars([(11.2, 10.6, 11.0)]) # high-water +12% + d = manage_live(10.0, 9.0, bars, ExitConfig(profit_lock_tiers=[(0.08, 0.03), (0.15, 0.09)])) + assert round(d.desired_stop, 2) == 10.30 # +3% locked (only +8% tier reached) + + def _bars(seq): return pd.DataFrame([{"high": h, "low": lo, "close": c} for h, lo, c in seq])