FastAPI backend with a single-strategy async engine, paper and Binance brokers, pure-python indicators, a backtester that shares the engine's portfolio math, and a Vue dashboard with a live WebSocket feed. Adds the Gitea Actions CI/CD workflow that deploys to Traefik via docker_default.
49 lines
1.7 KiB
Python
49 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import ClassVar
|
|
|
|
from app.engine.indicators import sma
|
|
from app.engine.strategies.base import Strategy, StrategyContext, register
|
|
from app.models import PositionSide
|
|
|
|
|
|
@register
|
|
class SmaCross(Strategy):
|
|
"""Classic moving-average crossover, long-only."""
|
|
|
|
key: ClassVar[str] = "sma_cross"
|
|
name: ClassVar[str] = "SMA Crossover"
|
|
description: ClassVar[str] = (
|
|
"Open a long position when the fast SMA crosses above the slow SMA, "
|
|
"close it when the fast SMA crosses back below."
|
|
)
|
|
default_params: ClassVar[dict] = {"fast": 10, "slow": 30, "size": 1.0}
|
|
param_help: ClassVar[dict] = {
|
|
"fast": "Fast SMA period",
|
|
"slow": "Slow SMA period",
|
|
"size": "Fraction of equity to allocate per trade",
|
|
}
|
|
param_bounds: ClassVar[dict] = {"fast": (2, 200), "slow": (3, 400), "size": (0.01, 1.0)}
|
|
|
|
def on_candle(self, ctx: StrategyContext) -> None:
|
|
fast_period = int(self.params["fast"])
|
|
slow_period = int(self.params["slow"])
|
|
closes = ctx.closes
|
|
if len(closes) < slow_period + 2:
|
|
return
|
|
|
|
fast = sma(closes, fast_period)
|
|
slow = sma(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
|
|
|
|
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:
|
|
ctx.enter_long(size=float(self.params["size"]), reason="fast SMA crossed above slow")
|
|
elif ctx.side == PositionSide.LONG and crossed_down:
|
|
ctx.close(reason="fast SMA crossed below slow")
|