Bitcoin favicon, more strategies, default timeframe 5m
- Add an SVG Bitcoin favicon and link it in index.html. - New indicators: macd() and roc(). - Five new strategies: macd_trend, bollinger_reversion, donchian_breakout, ema_cross, momentum (plus the existing sma_cross, rsi_reversion). - Default TIMEFRAME is now 5m (config, .env.example, compose, workflow, UI).
This commit is contained in:
1 parent
186a6949ee
commit
c500fb7572
18 files changed
+488
-11
No files matched your search
@@ -5,7 +5,7 @@ from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, Literal, Protocol
|
||||
|
||||
from app.engine.indicators import atr, ema, rolling_std, rsi, sma
|
||||
from app.engine.indicators import atr, ema, macd, roc, rolling_std, rsi, sma
|
||||
from app.models import PositionSide
|
||||
from app.schemas import Candle, ParamSpec, StrategyOut
|
||||
|
||||
@@ -106,6 +106,15 @@ class StrategyContext:
|
||||
def std(self, period: int = 20) -> float | None:
|
||||
return rolling_std(self.closes, period)[-1]
|
||||
|
||||
def macd(
|
||||
self, fast: int = 12, slow: int = 26, signal: int = 9
|
||||
) -> tuple[float | None, float | None, float | None]:
|
||||
macd_line, signal_line, histogram = macd(self.closes, fast, slow, signal)
|
||||
return macd_line[-1], signal_line[-1], histogram[-1]
|
||||
|
||||
def roc(self, period: int = 10) -> float | None:
|
||||
return roc(self.closes, period)[-1]
|
||||
|
||||
# --- order intents ------------------------------------------------
|
||||
def enter_long(
|
||||
self,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from app.engine.strategies.base import Strategy, StrategyContext, register
|
||||
from app.models import PositionSide
|
||||
|
||||
|
||||
@register
|
||||
class BollingerReversion(Strategy):
|
||||
"""Buy the lower Bollinger band, exit at the middle band."""
|
||||
|
||||
key: ClassVar[str] = "bollinger_reversion"
|
||||
name: ClassVar[str] = "Bollinger Reversion"
|
||||
description: ClassVar[str] = (
|
||||
"Enter long when the close falls below the lower Bollinger band and exit "
|
||||
"when it returns to the middle band (SMA). Optional ATR stop."
|
||||
)
|
||||
default_params: ClassVar[dict] = {
|
||||
"period": 20,
|
||||
"num_std": 2.0,
|
||||
"atr_period": 14,
|
||||
"atr_stop_mult": 0.0,
|
||||
"size": 1.0,
|
||||
}
|
||||
param_help: ClassVar[dict] = {
|
||||
"period": "Bollinger lookback",
|
||||
"num_std": "Band width in standard deviations",
|
||||
"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": (5, 100),
|
||||
"num_std": (0.5, 4.0),
|
||||
"atr_stop_mult": (0.0, 10.0),
|
||||
"size": (0.01, 1.0),
|
||||
}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
period = int(self.params["period"])
|
||||
if len(ctx.closes) < period:
|
||||
return
|
||||
middle = ctx.sma(period)
|
||||
deviation = ctx.std(period)
|
||||
if middle is None or deviation is None:
|
||||
return
|
||||
lower = middle - float(self.params["num_std"]) * deviation
|
||||
|
||||
if ctx.is_flat and ctx.price < lower:
|
||||
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="close below lower band",
|
||||
)
|
||||
elif ctx.side == PositionSide.LONG and ctx.price >= middle:
|
||||
ctx.close(reason="close back at middle band")
|
||||
@@ -0,0 +1,64 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from app.engine.strategies.base import Strategy, StrategyContext, register
|
||||
from app.models import PositionSide
|
||||
|
||||
|
||||
@register
|
||||
class DonchianBreakout(Strategy):
|
||||
"""Breakout of the highest high, exit on the lowest low."""
|
||||
|
||||
key: ClassVar[str] = "donchian_breakout"
|
||||
name: ClassVar[str] = "Donchian Breakout"
|
||||
description: ClassVar[str] = (
|
||||
"Open long when the close breaks above the highest high of the entry "
|
||||
"lookback; exit on a close below the lowest low of the exit lookback. "
|
||||
"Optional ATR stop."
|
||||
)
|
||||
default_params: ClassVar[dict] = {
|
||||
"entry_period": 20,
|
||||
"exit_period": 10,
|
||||
"atr_period": 14,
|
||||
"atr_stop_mult": 2.0,
|
||||
"size": 1.0,
|
||||
}
|
||||
param_help: ClassVar[dict] = {
|
||||
"entry_period": "Breakout lookback for entries",
|
||||
"exit_period": "Lookback for the exit channel",
|
||||
"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] = {
|
||||
"entry_period": (2, 200),
|
||||
"exit_period": (2, 200),
|
||||
"atr_stop_mult": (0.0, 10.0),
|
||||
"size": (0.01, 1.0),
|
||||
}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
entry_period = int(self.params["entry_period"])
|
||||
exit_period = int(self.params["exit_period"])
|
||||
if len(ctx.candles) < max(entry_period, exit_period) + 1:
|
||||
return
|
||||
|
||||
# Exclude the current candle from the channel.
|
||||
recent_high = max(c.high for c in ctx.candles[-entry_period - 1 : -1])
|
||||
recent_low = min(c.low for c in ctx.candles[-exit_period - 1 : -1])
|
||||
|
||||
if ctx.is_flat and ctx.price > recent_high:
|
||||
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"broke {entry_period}-bar high",
|
||||
)
|
||||
elif ctx.side == PositionSide.LONG and ctx.price < recent_low:
|
||||
ctx.close(reason=f"broke {exit_period}-bar low")
|
||||
@@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from app.engine.indicators import ema, sma
|
||||
from app.engine.strategies.base import Strategy, StrategyContext, register
|
||||
from app.models import PositionSide
|
||||
|
||||
|
||||
@register
|
||||
class EmaCross(Strategy):
|
||||
"""EMA crossover with an optional long-term trend filter."""
|
||||
|
||||
key: ClassVar[str] = "ema_cross"
|
||||
name: ClassVar[str] = "EMA Crossover"
|
||||
description: ClassVar[str] = (
|
||||
"Open long when the fast EMA crosses above the slow EMA (and price is "
|
||||
"above the trend filter, if enabled); exit on the opposite cross."
|
||||
)
|
||||
default_params: ClassVar[dict] = {
|
||||
"fast": 9,
|
||||
"slow": 21,
|
||||
"trend_filter": 200,
|
||||
"size": 1.0,
|
||||
}
|
||||
param_help: ClassVar[dict] = {
|
||||
"fast": "Fast EMA period",
|
||||
"slow": "Slow EMA period",
|
||||
"trend_filter": "SMA trend filter period (0 disables)",
|
||||
"size": "Fraction of equity per trade",
|
||||
}
|
||||
param_bounds: ClassVar[dict] = {"fast": (2, 100), "slow": (3, 300), "size": (0.01, 1.0)}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
fast_period = int(self.params["fast"])
|
||||
slow_period = int(self.params["slow"])
|
||||
trend_period = int(self.params["trend_filter"])
|
||||
needed = max(slow_period, trend_period) + 2
|
||||
if len(ctx.closes) < needed:
|
||||
return
|
||||
|
||||
fast = ema(ctx.closes, fast_period)
|
||||
slow = ema(ctx.closes, slow_period)
|
||||
f_prev, f_now = fast[-2], fast[-1]
|
||||
s_prev, s_now = slow[-2], slow[-1]
|
||||
if None in (f_prev, f_now, s_prev, s_now):
|
||||
return
|
||||
|
||||
trend_ok = True
|
||||
if trend_period > 0:
|
||||
trend = sma(ctx.closes, trend_period)[-1]
|
||||
trend_ok = trend is not None and ctx.price > trend
|
||||
|
||||
crossed_up = f_prev <= s_prev and f_now > s_now
|
||||
crossed_down = f_prev >= s_prev and f_now < s_now
|
||||
|
||||
if ctx.is_flat and crossed_up and trend_ok:
|
||||
ctx.enter_long(size=float(self.params["size"]), reason="EMA cross up")
|
||||
elif ctx.side == PositionSide.LONG and crossed_down:
|
||||
ctx.close(reason="EMA cross down")
|
||||
@@ -0,0 +1,50 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from app.engine.indicators import macd
|
||||
from app.engine.strategies.base import Strategy, StrategyContext, register
|
||||
from app.models import PositionSide
|
||||
|
||||
|
||||
@register
|
||||
class MacdTrend(Strategy):
|
||||
"""MACD crossover trend following, long-only."""
|
||||
|
||||
key: ClassVar[str] = "macd_trend"
|
||||
name: ClassVar[str] = "MACD Trend"
|
||||
description: ClassVar[str] = (
|
||||
"Open long when the MACD line crosses above its signal line and close when "
|
||||
"it crosses back below."
|
||||
)
|
||||
default_params: ClassVar[dict] = {"fast": 12, "slow": 26, "signal": 9, "size": 1.0}
|
||||
param_help: ClassVar[dict] = {
|
||||
"fast": "Fast EMA period",
|
||||
"slow": "Slow EMA period",
|
||||
"signal": "Signal EMA period",
|
||||
"size": "Fraction of equity per trade",
|
||||
}
|
||||
param_bounds: ClassVar[dict] = {"fast": (2, 100), "slow": (3, 200), "signal": (2, 100)}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
closes = ctx.closes
|
||||
if len(closes) < int(self.params["slow"]) + int(self.params["signal"]) + 2:
|
||||
return
|
||||
macd_line, signal_line, _ = macd(
|
||||
closes,
|
||||
int(self.params["fast"]),
|
||||
int(self.params["slow"]),
|
||||
int(self.params["signal"]),
|
||||
)
|
||||
m_prev, m_now = macd_line[-2], macd_line[-1]
|
||||
s_prev, s_now = signal_line[-2], signal_line[-1]
|
||||
if None in (m_prev, m_now, s_prev, s_now):
|
||||
return
|
||||
|
||||
crossed_up = m_prev <= s_prev and m_now > s_now
|
||||
crossed_down = m_prev >= s_prev and m_now < s_now
|
||||
|
||||
if ctx.is_flat and crossed_up:
|
||||
ctx.enter_long(size=float(self.params["size"]), reason="MACD crossed above signal")
|
||||
elif ctx.side == PositionSide.LONG and crossed_down:
|
||||
ctx.close(reason="MACD crossed below signal")
|
||||
@@ -0,0 +1,58 @@
|
||||
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,
|
||||
"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 stop",
|
||||
"atr_stop_mult": "Stop distance in ATRs (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),
|
||||
"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,
|
||||
reason=f"ROC {value:.2%} above threshold",
|
||||
)
|
||||
elif ctx.side == PositionSide.LONG and value < 0:
|
||||
ctx.close(reason=f"ROC {value:.2%} turned negative")
|
||||
Reference in new issue
Block a user