127 lines
5.1 KiB
Python
Executable File
127 lines
5.1 KiB
Python
Executable File
import asyncio
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import pandas as pd
|
|
import pytest
|
|
|
|
from kraken_trader.broker import PaperBroker
|
|
from kraken_trader.config import AppConfig, StrategyConfig
|
|
from kraken_trader.engine import StrategyRunner
|
|
from kraken_trader.kraken import PairInfo, sign
|
|
from kraken_trader.portfolio import Fill, Portfolio
|
|
from kraken_trader.stats import compute_stats, max_drawdown
|
|
from kraken_trader.storage import Store
|
|
from kraken_trader.strategies import available_strategies, get_strategy_class
|
|
|
|
NOW = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
|
|
|
|
|
def test_signature_matches_kraken_docs_example():
|
|
secret = "kQH5HW/8p1uGOVjbgWA7FunAmGO8lsSUXNsu3eow76sz84Q18fWxnyRzBHCd3pd5nE9qa99HAZtuZuj6F1huXg=="
|
|
postdata = "nonce=1616492376594&ordertype=limit&pair=XBTUSD&price=37500&type=buy&volume=1.25"
|
|
assert (
|
|
sign("/0/private/AddOrder", "1616492376594", postdata, secret)
|
|
== "4/dpxb3iT4tp/ZCVEwSnEsLxx0bqyhLpdfOpc6fn7OR8+UClSV5n9E6aSS8MPtnRfp32bAb0nmbRn6H8ndwLUQ=="
|
|
)
|
|
|
|
|
|
def test_portfolio_buy_then_sell_tracks_cost_and_pnl():
|
|
p = Portfolio(cash=1000)
|
|
p.apply(Fill("XBTUSD", "buy", 0.01, 50_000, 2.0, NOW))
|
|
assert p.cash == pytest.approx(498)
|
|
assert p.positions["XBTUSD"].avg_price == pytest.approx(50_200)
|
|
pnl = p.apply(Fill("XBTUSD", "sell", 0.01, 60_000, 2.4, NOW))
|
|
assert pnl == pytest.approx(0.01 * (60_000 - 50_200) - 2.4)
|
|
assert "XBTUSD" not in p.positions
|
|
assert p.cash == pytest.approx(498 + 600 - 2.4)
|
|
|
|
|
|
def test_portfolio_rejects_oversell():
|
|
p = Portfolio(cash=0)
|
|
with pytest.raises(ValueError):
|
|
p.apply(Fill("XBTUSD", "sell", 1, 1, 0, NOW))
|
|
|
|
|
|
def test_registry_contains_examples_and_validates_params():
|
|
assert {"buy_and_hold", "sma_crossover", "rsi_mean_reversion"} <= set(available_strategies())
|
|
with pytest.raises(ValueError):
|
|
get_strategy_class("sma_crossover")(["XBTUSD"], 60, {"bogus": 1})
|
|
with pytest.raises(ValueError):
|
|
get_strategy_class("does_not_exist")
|
|
|
|
|
|
def test_duplicate_strategy_ids_rejected():
|
|
s = {"id": "a", "type": "buy_and_hold", "starting_capital": 1, "pairs": ["XBTUSD"]}
|
|
with pytest.raises(ValueError):
|
|
AppConfig(strategies=[s, s])
|
|
|
|
|
|
def test_stats():
|
|
assert max_drawdown(pd.Series([100, 120, 90, 130])) == pytest.approx(-0.25)
|
|
start = NOW
|
|
series = [(start + timedelta(hours=i), 100 + i) for i in range(48)]
|
|
trades = [
|
|
{"realized_pnl": None, "fee": 1.0},
|
|
{"realized_pnl": 5.0, "fee": 1.0},
|
|
{"realized_pnl": -2.0, "fee": 1.0},
|
|
]
|
|
stats = compute_stats(100, 147, series, trades)
|
|
assert stats["total_return"] == pytest.approx(0.47)
|
|
assert stats["win_rate"] == pytest.approx(0.5)
|
|
assert stats["fees"] == pytest.approx(3.0)
|
|
assert stats["sharpe"] is not None
|
|
|
|
|
|
class FakeClient:
|
|
def pair(self, name):
|
|
return PairInfo(name, name, "XXBT", "ZUSD", 8, 1, 0.0001, 0.5)
|
|
|
|
|
|
def _candles(closes, start=NOW):
|
|
idx = pd.date_range(start, periods=len(closes), freq="1h", tz="UTC")
|
|
return pd.DataFrame({"close": closes}, index=idx)
|
|
|
|
|
|
def test_runner_rebalances_and_persists(tmp_path):
|
|
store = Store(tmp_path / "test.db")
|
|
cfg = StrategyConfig(id="bh", type="buy_and_hold", starting_capital=1000, pairs=["XBTUSD"])
|
|
app_cfg = AppConfig(fee_rate=0.004, slippage=0.0005)
|
|
strategy = get_strategy_class("buy_and_hold")(cfg.pairs, cfg.interval, cfg.params)
|
|
runner = StrategyRunner(cfg, strategy, PaperBroker(0.004, 0.0005), FakeClient(), store, app_cfg)
|
|
|
|
prices = {"XBTUSD": 50_000.0}
|
|
asyncio.run(runner.step(NOW, {"XBTUSD": _candles([1, 2, 3])}, prices))
|
|
|
|
assert runner.portfolio.cash >= 0
|
|
assert runner.portfolio.equity(prices) == pytest.approx(1000, rel=0.01)
|
|
assert runner.portfolio.volume("XBTUSD") > 0
|
|
assert len(store.trades("bh")) == 1
|
|
|
|
# Same candle again: no new decision.
|
|
asyncio.run(runner.step(NOW, {"XBTUSD": _candles([1, 2, 3])}, prices))
|
|
assert len(store.trades("bh")) == 1
|
|
|
|
# State survives a restart.
|
|
restored = StrategyRunner(cfg, strategy, PaperBroker(0.004, 0), FakeClient(), store, app_cfg)
|
|
assert restored.portfolio.volume("XBTUSD") == runner.portfolio.volume("XBTUSD")
|
|
assert restored.last_candle == runner.last_candle
|
|
|
|
|
|
def test_sma_crossover_exits_on_downtrend(tmp_path):
|
|
store = Store(tmp_path / "test.db")
|
|
cfg = StrategyConfig(
|
|
id="sma", type="sma_crossover", starting_capital=1000, pairs=["XBTUSD"],
|
|
params={"fast": 2, "slow": 5},
|
|
)
|
|
strategy = get_strategy_class(cfg.type)(cfg.pairs, cfg.interval, cfg.params)
|
|
runner = StrategyRunner(cfg, strategy, PaperBroker(0, 0), FakeClient(), store, AppConfig())
|
|
|
|
up = [100, 101, 102, 103, 104, 110]
|
|
asyncio.run(runner.step(NOW, {"XBTUSD": _candles(up)}, {"XBTUSD": 110.0 * 400}))
|
|
assert runner.portfolio.volume("XBTUSD") > 0
|
|
|
|
down = up + [90, 80]
|
|
asyncio.run(runner.step(NOW, {"XBTUSD": _candles(down)}, {"XBTUSD": 80.0 * 400}))
|
|
assert runner.portfolio.volume("XBTUSD") == 0
|
|
assert [t["side"] for t in store.trades("sma")] == ["sell", "buy"]
|