Add trailing stops and parameter sweeps
CI/CD / backend (pull_request) Successful in 6m6s
CI/CD / frontend (pull_request) Successful in 5m17s
CI/CD / build (pull_request) Skipped
CI/CD / deploy (pull_request) Skipped
CI/CD / cleanup (pull_request) Skipped

Trailing stops: strategies can pass trailing_stop_pct to enter_long/enter_short.
advance_trailing_stop in app/engine/portfolio.py ratchets the stop with the price
(up for longs, down for shorts) and never loosens; the engine persists the
ratcheted level and the backtester applies the same logic. Position gains a
trailing_stop_pct column (additive migration). momentum exposes it as a param.

Parameter sweeps: app/backtest/sweep.py runs a cartesian grid through the same
backtester and ranks by return minus max drawdown. POST /api/sweep plus a
dashboard Parameter sweep panel.
This commit is contained in:
matitos committed 2026-09-19 23:04:20 +00:00
1 parent d80e7b155e
commit 9dc00eba95
22 files changed
+575 -7

No files matched your search

+24
View File
@@ -18,9 +18,33 @@ class OpenPosition:
entry_fee: float = 0.0
stop_loss: float | None = None
take_profit: float | None = None
# Distance to trail the stop below the high (long) / above the low (short),
# as a fraction of price (0.02 = 2%). 0 disables trailing.
trailing_stop_pct: float = 0.0
entry_ts: int = 0
def advance_trailing_stop(
side: PositionSide,
stop_loss: float | None,
trailing_stop_pct: float,
high: float,
low: float,
) -> float | None:
"""Ratchet a trailing stop toward the price; never loosens.
For a long the stop trails ``pct`` below the running high; for a short it
trails ``pct`` above the running low. Returns the (possibly unchanged) stop.
"""
if trailing_stop_pct <= 0:
return stop_loss
if side == PositionSide.LONG:
candidate = high * (1 - trailing_stop_pct)
return candidate if stop_loss is None else max(stop_loss, candidate)
candidate = low * (1 + trailing_stop_pct)
return candidate if stop_loss is None else min(stop_loss, candidate)
def apply_open(cash: float, side: PositionSide, qty: float, price: float, fee: float) -> float:
"""Cash after opening a position (buying long / selling short)."""
notional = qty * price