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

+30
View File
@@ -82,6 +82,36 @@ def test_stop_loss_is_honoured() -> None:
assert result.metrics.final_equity < 10_000
class TrailStrategy(Strategy):
key: ClassVar[str] = "test_trail"
name: ClassVar[str] = "Test Trail"
default_params: ClassVar[dict] = {}
def on_candle(self, ctx: StrategyContext) -> None:
if ctx.is_flat and not getattr(self, "_entered", False):
self._entered = True
ctx.enter_long(size=1.0, trailing_stop_pct=0.10)
def test_trailing_stop_locks_in_profit() -> None:
# Entry at 100, rise to 150, then a reversal. A 10% trail should exit near
# 135 (150 * 0.9) instead of round-tripping to the entry.
backtester = Backtester(fee_bps=0, slippage_bps=0, starting_balance=10_000)
candles = candles_from_closes([100, 120, 150, 130, 125, 120])
candles[2] = Candle(ts=2, open=120, high=150, low=120, close=150, volume=1.0)
candles[3] = Candle(ts=3, open=150, high=150, low=130, close=130, volume=1.0)
candles[4] = Candle(ts=4, open=130, high=132, low=125, close=125, volume=1.0)
candles[5] = Candle(ts=5, open=125, high=128, low=120, close=120, volume=1.0)
result = backtester.run(candles, TrailStrategy(), "BTC/USDT", "1h")
assert result.metrics.num_trades == 1
trade = result.trades[0]
assert "stop loss" in trade.reason
# 99 units, exit at the trailing stop (135), well above entry 100.
assert trade.exit_price == pytest.approx(135.0)
assert result.metrics.final_equity > 10_000
def test_strategy_error_is_surfaced() -> None:
class Boom(Strategy):
key = "test_boom"