Add the Williams %R strategy

New williams_r indicator (in [-100, 0]) exposed as ctx.williams_r(period), and a
long-only mean-reversion strategy: enter when %R is at/below the oversold level,
exit when it reaches the overbought level, with an optional ATR stop. 11
strategies total. Adds indicator and strategy tests; smoke-tested on live
BTC/USDT 5m (backtest + parameter sweep).
This commit is contained in:
matitos committed 2026-09-26 18:44:00 +00:00
1 parent ef895b6b9c
commit d92f152f9b
6 files changed
+171 -2

No files matched your search

+4
View File
@@ -15,6 +15,7 @@ from app.engine.indicators import (
sma,
supertrend,
vwap,
williams_r,
)
from app.models import PositionSide
from app.schemas import Candle, ParamSpec, StrategyOut
@@ -129,6 +130,9 @@ class StrategyContext:
def vwap(self, period: int | None = None) -> float | None:
return vwap(self._candles, period)[-1]
def williams_r(self, period: int = 14) -> float | None:
return williams_r(self._candles, period)[-1]
def supertrend(
self, period: int = 10, multiplier: float = 3.0
) -> tuple[float | None, bool | None]:
@@ -0,0 +1,61 @@
from __future__ import annotations
from typing import ClassVar
from app.engine.strategies.base import Strategy, StrategyContext, register
from app.models import PositionSide
@register
class WilliamsR(Strategy):
"""Williams %R mean reversion, long-only."""
key: ClassVar[str] = "williams_r"
name: ClassVar[str] = "Williams %R"
description: ClassVar[str] = (
"Enter long when Williams %R is oversold (at or below the oversold "
"level) and exit when it becomes overbought. Optional ATR stop."
)
default_params: ClassVar[dict] = {
"period": 14,
"oversold": -80.0,
"overbought": -20.0,
"atr_period": 14,
"atr_stop_mult": 2.0,
"size": 1.0,
}
param_help: ClassVar[dict] = {
"period": "Williams %R lookback",
"oversold": "Oversold level (e.g. -80)",
"overbought": "Overbought level (e.g. -20)",
"atr_period": "ATR lookback for the stop",
"atr_stop_mult": "Stop distance in ATRs (0 disables)",
"size": "Fraction of equity per trade",
}
param_bounds: ClassVar[dict] = {
"period": (2, 100),
"oversold": (-100.0, -50.0),
"overbought": (-50.0, 0.0),
"atr_stop_mult": (0.0, 10.0),
"size": (0.01, 1.0),
}
def on_candle(self, ctx: StrategyContext) -> None:
value = ctx.williams_r(int(self.params["period"]))
if value is None:
return
if ctx.is_flat and value <= float(self.params["oversold"]):
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,
reason=f"Williams %R {value:.1f} oversold",
)
elif ctx.side == PositionSide.LONG and value >= float(self.params["overbought"]):
ctx.close(reason=f"Williams %R {value:.1f} overbought")