Files
crypto_trading/backend/app/engine/strategies/momentum.py
T
matitos 9dc00eba95
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
Add trailing stops and parameter sweeps
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.
2026-09-19 23:04:20 +00:00

63 lines
2.2 KiB
Python

from __future__ import annotations
from typing import ClassVar
from app.engine.strategies.base import Strategy, StrategyContext, register
from app.models import PositionSide
@register
class Momentum(Strategy):
"""Rate-of-change momentum, long-only."""
key: ClassVar[str] = "momentum"
name: ClassVar[str] = "Momentum (ROC)"
description: ClassVar[str] = (
"Open long when the rate of change over the lookback exceeds the entry "
"threshold; exit when momentum turns negative."
)
default_params: ClassVar[dict] = {
"period": 10,
"entry_threshold": 0.01,
"atr_period": 14,
"atr_stop_mult": 2.0,
"trailing_stop_pct": 0.0,
"size": 1.0,
}
param_help: ClassVar[dict] = {
"period": "ROC lookback in bars",
"entry_threshold": "Minimum ROC to enter (0.01 = 1%)",
"atr_period": "ATR lookback for the initial stop",
"atr_stop_mult": "Stop distance in ATRs (0 disables)",
"trailing_stop_pct": "Trailing stop distance as a fraction of price (0 disables)",
"size": "Fraction of equity per trade",
}
param_bounds: ClassVar[dict] = {
"period": (2, 200),
"entry_threshold": (0.0, 1.0),
"atr_stop_mult": (0.0, 10.0),
"trailing_stop_pct": (0.0, 0.5),
"size": (0.01, 1.0),
}
def on_candle(self, ctx: StrategyContext) -> None:
value = ctx.roc(int(self.params["period"]))
if value is None:
return
if ctx.is_flat and value > float(self.params["entry_threshold"]):
stop = None
mult = float(self.params["atr_stop_mult"])
if mult > 0:
atr_value = ctx.atr(int(self.params["atr_period"]))
if atr_value:
stop = ctx.price - mult * atr_value
ctx.enter_long(
size=float(self.params["size"]),
stop_loss=stop,
trailing_stop_pct=float(self.params["trailing_stop_pct"]),
reason=f"ROC {value:.2%} above threshold",
)
elif ctx.side == PositionSide.LONG and value < 0:
ctx.close(reason=f"ROC {value:.2%} turned negative")