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).
62 lines
2.1 KiB
Python
62 lines
2.1 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 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")
|