Crypto trading bot: engine, brokers, backtester, dashboard, deploy
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.
This commit is contained in:
1 parent
98028248c2
commit
9c3bee87ac
73 files changed
+9759
-1
No files matched your search
@@ -0,0 +1,142 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
import pytest
|
||||
|
||||
from app.backtest import Backtester
|
||||
from app.backtest.metrics import max_drawdown_pct, sharpe_ratio
|
||||
from app.engine.strategies.base import Strategy, StrategyContext
|
||||
from app.schemas import BacktestPointOut, BacktestTradeOut, Candle
|
||||
|
||||
|
||||
class HoldStrategy(Strategy):
|
||||
"""Enter long on the first candle and stay in (closed at end of data)."""
|
||||
|
||||
key: ClassVar[str] = "test_hold"
|
||||
name: ClassVar[str] = "Test Hold"
|
||||
default_params: ClassVar[dict] = {}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
if ctx.is_flat:
|
||||
ctx.enter_long(size=1.0)
|
||||
|
||||
|
||||
class NeverStrategy(Strategy):
|
||||
key: ClassVar[str] = "test_never"
|
||||
name: ClassVar[str] = "Test Never"
|
||||
default_params: ClassVar[dict] = {}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class StopStrategy(Strategy):
|
||||
key: ClassVar[str] = "test_stop"
|
||||
name: ClassVar[str] = "Test Stop"
|
||||
default_params: ClassVar[dict] = {}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
if ctx.is_flat and not getattr(self, "_entered", False):
|
||||
self._entered = True
|
||||
ctx.enter_long(size=1.0, stop_loss=ctx.price * 0.9)
|
||||
|
||||
|
||||
def candles_from_closes(closes: list[float]) -> list[Candle]:
|
||||
return [Candle(ts=i, open=c, high=c, low=c, close=c, volume=1.0) for i, c in enumerate(closes)]
|
||||
|
||||
|
||||
def test_hold_backtest_math() -> None:
|
||||
backtester = Backtester(fee_bps=0, slippage_bps=0, starting_balance=10_000)
|
||||
result = backtester.run(candles_from_closes([100, 110, 120]), HoldStrategy(), "BTC/USDT", "1h")
|
||||
|
||||
assert result.error is None
|
||||
assert result.metrics.num_trades == 1
|
||||
# 99 units bought at 100 (cash capped at 99%), closed at 120.
|
||||
assert result.metrics.final_equity == pytest.approx(11_980.0)
|
||||
assert result.trades[0].pnl == pytest.approx(1_980.0)
|
||||
assert result.trades[0].return_pct == pytest.approx(20.0)
|
||||
assert result.trades[0].reason == "end of data"
|
||||
assert len(result.equity_curve) == 3
|
||||
|
||||
|
||||
def test_no_trades_leaves_balance_untouched() -> None:
|
||||
backtester = Backtester(fee_bps=10, slippage_bps=5, starting_balance=5_000)
|
||||
result = backtester.run(
|
||||
candles_from_closes([100, 101, 102, 103]), NeverStrategy(), "BTC/USDT", "1m"
|
||||
)
|
||||
assert result.metrics.num_trades == 0
|
||||
assert result.metrics.final_equity == pytest.approx(5_000.0)
|
||||
assert result.metrics.total_return_pct == pytest.approx(0.0)
|
||||
assert result.metrics.max_drawdown_pct == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_stop_loss_is_honoured() -> None:
|
||||
backtester = Backtester(fee_bps=0, slippage_bps=0, starting_balance=10_000)
|
||||
candles = candles_from_closes([100, 100, 80])
|
||||
candles[2] = Candle(ts=2, open=100, high=100, low=80, close=80, volume=1.0)
|
||||
result = backtester.run(candles, StopStrategy(), "BTC/USDT", "1h")
|
||||
|
||||
assert result.metrics.num_trades == 1
|
||||
assert "stop loss" in result.trades[0].reason
|
||||
assert result.metrics.final_equity < 10_000
|
||||
|
||||
|
||||
def test_strategy_error_is_surfaced() -> None:
|
||||
class Boom(Strategy):
|
||||
key = "test_boom"
|
||||
name = "Boom"
|
||||
default_params: ClassVar[dict] = {}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
raise RuntimeError("kaboom")
|
||||
|
||||
result = Backtester().run(candles_from_closes([1, 2, 3]), Boom(), "BTC/USDT", "1m")
|
||||
assert result.error is not None and "kaboom" in result.error
|
||||
|
||||
|
||||
def test_max_drawdown() -> None:
|
||||
assert max_drawdown_pct([100, 120, 90, 130]) == pytest.approx(25.0)
|
||||
assert max_drawdown_pct([100, 100, 100]) == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_sharpe_none_for_unknown_timeframe() -> None:
|
||||
assert sharpe_ratio([100, 101, 102, 103], "nonsense") is None
|
||||
|
||||
|
||||
def _points(equities: list[float]) -> list[BacktestPointOut]:
|
||||
return [BacktestPointOut(ts=i, equity=e, buy_hold=e, price=e) for i, e in enumerate(equities)]
|
||||
|
||||
|
||||
def test_metrics_profit_factor_and_win_rate() -> None:
|
||||
from app.backtest.metrics import compute_metrics
|
||||
|
||||
trades = [
|
||||
BacktestTradeOut(
|
||||
side="long",
|
||||
entry_ts=0,
|
||||
exit_ts=1,
|
||||
entry_price=100,
|
||||
exit_price=110,
|
||||
qty=1,
|
||||
pnl=10,
|
||||
return_pct=10,
|
||||
reason="x",
|
||||
),
|
||||
BacktestTradeOut(
|
||||
side="long",
|
||||
entry_ts=2,
|
||||
exit_ts=3,
|
||||
entry_price=100,
|
||||
exit_price=95,
|
||||
qty=1,
|
||||
pnl=-5,
|
||||
return_pct=-5,
|
||||
reason="x",
|
||||
),
|
||||
]
|
||||
metrics = compute_metrics(_points([10_000, 10_010, 10_005]), trades, 10_000, "1h")
|
||||
assert metrics.win_rate_pct == pytest.approx(50.0)
|
||||
assert metrics.profit_factor == pytest.approx(2.0)
|
||||
assert metrics.best_trade_pct == pytest.approx(10.0)
|
||||
assert metrics.worst_trade_pct == pytest.approx(-5.0)
|
||||
Reference in new issue
Block a user