263 lines
11 KiB
Python
Executable File
263 lines
11 KiB
Python
Executable File
"""The trading loop: fetch market data, run strategies, rebalance, record history."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import time
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import pandas as pd
|
|
|
|
from .broker import Broker, LiveBroker, PaperBroker
|
|
from .config import AppConfig, Settings, StrategyConfig
|
|
from .kraken import USD_ASSETS, KrakenClient
|
|
from .portfolio import DUST, Portfolio
|
|
from .storage import Store
|
|
from .strategies import Context, Strategy, get_strategy_class
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
class StrategyRunner:
|
|
def __init__(
|
|
self,
|
|
cfg: StrategyConfig,
|
|
strategy: Strategy,
|
|
broker: Broker,
|
|
client: KrakenClient,
|
|
store: Store,
|
|
app_cfg: AppConfig,
|
|
):
|
|
self.cfg = cfg
|
|
self.strategy = strategy
|
|
self.broker = broker
|
|
self.client = client
|
|
self.store = store
|
|
self.app_cfg = app_cfg
|
|
self.last_error: str | None = None
|
|
self.last_decision: datetime | None = None
|
|
self.last_targets: dict[str, float] = {}
|
|
|
|
state = store.load_state(cfg.id)
|
|
if state is None:
|
|
self.portfolio = Portfolio(cash=cfg.starting_capital)
|
|
self.starting_capital = cfg.starting_capital
|
|
self.last_candle: datetime | None = None
|
|
self._save()
|
|
else:
|
|
self.portfolio, self.starting_capital, self.last_candle = state
|
|
|
|
@property
|
|
def id(self) -> str:
|
|
return self.cfg.id
|
|
|
|
@property
|
|
def price_pairs(self) -> set[str]:
|
|
return set(self.cfg.pairs) | set(self.portfolio.positions)
|
|
|
|
def _save(self) -> None:
|
|
self.store.save_state(self.id, self.portfolio, self.starting_capital, self.last_candle)
|
|
|
|
async def step(
|
|
self, now: datetime, candles: dict[str, pd.DataFrame], prices: dict[str, float]
|
|
) -> None:
|
|
if any(df.empty for df in candles.values()):
|
|
return
|
|
# Wait until every pair has the new candle so multi-pair strategies see aligned data.
|
|
latest = min(df.index[-1] for df in candles.values()).to_pydatetime()
|
|
if self.last_candle is not None and latest <= self.last_candle:
|
|
return
|
|
|
|
my_prices = {p: prices[p] for p in self.price_pairs}
|
|
ctx = Context(
|
|
now=now,
|
|
candles=candles,
|
|
prices=my_prices,
|
|
weights=self.portfolio.weights(my_prices),
|
|
cash=self.portfolio.cash,
|
|
equity=self.portfolio.equity(my_prices),
|
|
)
|
|
targets = self.strategy.decide(ctx) or {}
|
|
self.last_targets = targets
|
|
self.last_decision = now
|
|
await self.rebalance(targets, my_prices)
|
|
self.last_candle = latest
|
|
self._save()
|
|
|
|
async def rebalance(self, targets: dict[str, float], prices: dict[str, float]) -> None:
|
|
targets = {p: min(max(float(w), 0.0), 1.0) for p, w in targets.items() if p in self.cfg.pairs}
|
|
total = sum(targets.values())
|
|
if total > 1:
|
|
targets = {p: w / total for p, w in targets.items()}
|
|
|
|
equity = self.portfolio.equity(prices)
|
|
deltas = []
|
|
for pair, weight in targets.items():
|
|
delta = weight * equity - self.portfolio.market_value(pair, prices)
|
|
full_exit = weight == 0 and self.portfolio.volume(pair) > 0
|
|
if full_exit or abs(delta) >= self.app_cfg.min_trade_fraction * equity:
|
|
deltas.append((pair, delta, full_exit))
|
|
|
|
# Sells first so their proceeds can fund buys.
|
|
for pair, delta, full_exit in sorted(deltas, key=lambda d: d[1]):
|
|
price = prices[pair]
|
|
info = self.client.pair(pair)
|
|
if delta < 0:
|
|
side = "sell"
|
|
held = self.portfolio.volume(pair)
|
|
volume = held if full_exit else min(held, -delta / price)
|
|
else:
|
|
side = "buy"
|
|
cost_factor = (1 + self.app_cfg.fee_rate) * (1 + self.app_cfg.slippage)
|
|
budget = min(delta, self.portfolio.cash / cost_factor)
|
|
volume = budget / price
|
|
volume = info.round_volume(volume)
|
|
if volume <= 0 or volume < info.ordermin or volume * price < info.costmin:
|
|
log.debug("[%s] skip %s %s %.8f: below exchange minimum", self.id, side, pair, volume)
|
|
continue
|
|
|
|
fill = await self.broker.execute(pair, side, volume, price)
|
|
if fill is None:
|
|
continue
|
|
pnl = self.portfolio.apply(fill)
|
|
self.store.record_trade(self.id, self.broker.mode, fill, pnl)
|
|
self._save()
|
|
log.info(
|
|
"[%s] %s %s %.8f @ %.2f (fee %.4f)",
|
|
self.id, side, pair, fill.volume, fill.price, fill.fee,
|
|
)
|
|
|
|
|
|
class Engine:
|
|
def __init__(self, settings: Settings, app_cfg: AppConfig, client: KrakenClient, store: Store):
|
|
self.settings = settings
|
|
self.app_cfg = app_cfg
|
|
self.client = client
|
|
self.store = store
|
|
self.runners: list[StrategyRunner] = []
|
|
self.prices: dict[str, float] = {}
|
|
self.ready = False
|
|
self.started = datetime.now(timezone.utc)
|
|
self.last_tick: datetime | None = None
|
|
self.last_error: str | None = None
|
|
self._heartbeat = time.monotonic()
|
|
self._last_snapshot: datetime | None = None
|
|
self._candles: dict[tuple[str, int], pd.DataFrame] = {}
|
|
|
|
self.configs = [c for c in app_cfg.strategies if c.enabled]
|
|
for cfg in self.configs:
|
|
# Instantiate once now so bad types/params fail at startup, not on first tick.
|
|
get_strategy_class(cfg.type)(cfg.pairs, cfg.interval, cfg.params)
|
|
if cfg.mode == "live":
|
|
if not settings.live_trading_enabled:
|
|
raise RuntimeError(
|
|
f"Strategy '{cfg.id}' is in live mode but LIVE_TRADING_ENABLED is not true"
|
|
)
|
|
if not client.has_credentials:
|
|
raise RuntimeError(f"Strategy '{cfg.id}' is in live mode but has no API keys")
|
|
|
|
def healthy(self) -> bool:
|
|
return time.monotonic() - self._heartbeat < 5 * self.app_cfg.poll_interval_seconds + 120
|
|
|
|
def runner(self, strategy_id: str) -> StrategyRunner | None:
|
|
return next((r for r in self.runners if r.id == strategy_id), None)
|
|
|
|
async def start(self) -> None:
|
|
await self.client.load_metadata()
|
|
paper = PaperBroker(self.app_cfg.fee_rate, self.app_cfg.slippage)
|
|
live = LiveBroker(self.client) if self.client.has_credentials else None
|
|
runners = []
|
|
for cfg in self.configs:
|
|
pairs = [self.client.pair(p).altname for p in cfg.pairs]
|
|
cfg = cfg.model_copy(update={"pairs": pairs})
|
|
strategy = get_strategy_class(cfg.type)(pairs, cfg.interval, cfg.params)
|
|
broker = live if cfg.mode == "live" else paper
|
|
runners.append(StrategyRunner(cfg, strategy, broker, self.client, self.store, self.app_cfg))
|
|
self.runners = runners
|
|
self.ready = True
|
|
log.info("Engine started with %d strategies", len(runners))
|
|
|
|
async def run_forever(self) -> None:
|
|
while not self.ready:
|
|
self._heartbeat = time.monotonic()
|
|
try:
|
|
await self.start()
|
|
except Exception as e:
|
|
self.last_error = f"Startup failed: {e}"
|
|
log.exception("Engine startup failed; retrying in 30s")
|
|
await asyncio.sleep(30)
|
|
|
|
while True:
|
|
began = time.monotonic()
|
|
try:
|
|
await self.tick()
|
|
self.last_error = None
|
|
except Exception as e:
|
|
self.last_error = f"{type(e).__name__}: {e}"
|
|
log.exception("Tick failed")
|
|
self._heartbeat = time.monotonic()
|
|
await asyncio.sleep(max(0.0, self.app_cfg.poll_interval_seconds - (time.monotonic() - began)))
|
|
|
|
async def _get_candles(self, pair: str, interval: int, now: datetime) -> pd.DataFrame:
|
|
key = (pair, interval)
|
|
df = self._candles.get(key)
|
|
# A new closed candle can only exist once the one after the latest closed one has ended.
|
|
if df is None or df.empty or now >= df.index[-1] + timedelta(minutes=2 * interval):
|
|
df = await self.client.ohlc(pair, interval)
|
|
self._candles[key] = df
|
|
return df
|
|
|
|
async def tick(self) -> None:
|
|
now = datetime.now(timezone.utc)
|
|
pairs = sorted(set().union(*(r.price_pairs for r in self.runners)))
|
|
self.prices = await self.client.last_prices(pairs)
|
|
|
|
for runner in self.runners:
|
|
try:
|
|
candles = {
|
|
p: await self._get_candles(p, runner.cfg.interval, now) for p in runner.cfg.pairs
|
|
}
|
|
await runner.step(now, candles, self.prices)
|
|
runner.last_error = None
|
|
except Exception as e:
|
|
runner.last_error = f"{type(e).__name__}: {e}"
|
|
log.exception("[%s] strategy step failed", runner.id)
|
|
|
|
interval = timedelta(seconds=self.app_cfg.snapshot_interval_seconds)
|
|
if self._last_snapshot is None or now - self._last_snapshot >= interval:
|
|
for runner in self.runners:
|
|
self.store.record_equity(runner.id, now, runner.portfolio.equity(self.prices))
|
|
try:
|
|
await self.snapshot_account(now)
|
|
except Exception:
|
|
log.exception("Account snapshot failed")
|
|
self._last_snapshot = now
|
|
self.last_tick = now
|
|
|
|
async def snapshot_account(self, now: datetime) -> None:
|
|
if not self.client.has_credentials:
|
|
return
|
|
balances = await self.client.balance()
|
|
holdings = []
|
|
pricing: dict[str, str] = {}
|
|
for asset, amount in balances.items():
|
|
if amount <= DUST:
|
|
continue
|
|
if asset.split(".")[0] in USD_ASSETS:
|
|
holdings.append({"asset": asset, "amount": amount, "price": 1.0, "value": amount})
|
|
elif (pair := self.client.usd_pair_for_asset(asset)) is not None:
|
|
pricing[asset] = pair.altname
|
|
holdings.append({"asset": asset, "amount": amount})
|
|
else:
|
|
holdings.append({"asset": asset, "amount": amount, "price": None, "value": None})
|
|
|
|
prices = await self.client.last_prices(sorted(set(pricing.values())))
|
|
for h in holdings:
|
|
if h["asset"] in pricing:
|
|
h["price"] = prices.get(pricing[h["asset"]])
|
|
h["value"] = h["amount"] * h["price"] if h["price"] is not None else None
|
|
holdings.sort(key=lambda h: h["value"] or 0, reverse=True)
|
|
total = sum(h["value"] or 0 for h in holdings)
|
|
self.store.record_account(now, total, holdings)
|