Download qrypto/runner.py from Qempireautomation/qrypto-engine: direct link, hf CLI and curl.
- Browser
- Download file 6.27 kB
-
https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/qrypto/runner.py
- Command line
-
hf download hf://Qempireautomation/qrypto-engine/qrypto/runner.py
-
curl -L -o runner.py https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/qrypto/runner.py
6.27 kB
| """BotRunner: one strategy + one symbol + one broker, ticked on a schedule. | |
| The runner is deliberately boring. Each tick it: | |
| 1. pulls fresh candles, | |
| 2. marks equity and updates the risk manager, | |
| 3. checks the stop, | |
| 4. asks the strategy for a signal, | |
| 5. asks the risk manager for permission, | |
| 6. sends at most one market order. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timezone | |
| from typing import Any, Optional | |
| from .broker import Broker, PaperBroker | |
| from .data import MarketData | |
| from .portfolio import Position | |
| from .risk import RiskLimits, RiskManager | |
| from .strategies import Strategy | |
| log = logging.getLogger("qrypto.runner") | |
| class TickReport: | |
| at: str | |
| price: float | |
| equity: float | |
| action: str | |
| reason: str | |
| position_qty: float | |
| unrealized_pct: float | |
| halted: Optional[str] | |
| error: Optional[str] = None | |
| extra: dict[str, Any] = field(default_factory=dict) | |
| class BotRunner: | |
| def __init__(self, bot_id: str, strategy: Strategy, symbol: str, timeframe: str, broker: Broker, | |
| market: MarketData, limits: RiskLimits | None = None, candles_limit: int = 400): | |
| self.bot_id = bot_id | |
| self.strategy = strategy | |
| self.symbol = symbol | |
| self.timeframe = timeframe | |
| self.broker = broker | |
| self.market = market | |
| self.rm = RiskManager(limits) | |
| self.candles_limit = candles_limit | |
| self.position = Position(symbol) | |
| self.history: list[TickReport] = [] | |
| self._last_closed_ts = None # only evaluate the strategy once per closed candle | |
| self._sync_position() | |
| def quote_ccy(self) -> str: | |
| """Crypto pairs carry their quote ("BTC/USDT"); equities and ETFs are cash-settled in USD.""" | |
| return self.symbol.split("/")[1] if "/" in self.symbol else "USD" | |
| def base_ccy(self) -> str: | |
| return self.symbol.split("/")[0] if "/" in self.symbol else self.symbol | |
| def _sync_position(self) -> None: | |
| """For live brokers, treat existing base balance as the position (avg entry unknown → last price).""" | |
| if isinstance(self.broker, PaperBroker): | |
| self.position = self.broker.ledger.position(self.symbol) | |
| return | |
| try: | |
| qty = self.broker.base_balance(self.base_ccy) | |
| if qty > 0 and not self.position.open: | |
| px = self.broker.price(self.symbol) | |
| self.position.add(qty, px, datetime.now(timezone.utc)) | |
| self.position.stop = self.rm.stop_price(px) | |
| except Exception as e: # pragma: no cover | |
| log.warning("position sync failed: %s", e) | |
| def equity(self, price: float) -> float: | |
| return self.broker.quote_balance(self.quote_ccy) + self.position.value(price) | |
| def tick(self) -> TickReport: | |
| now = datetime.now(timezone.utc) | |
| try: | |
| raw = self.market.candles(self.symbol, self.timeframe, self.candles_limit) | |
| price = float(raw["close"].iloc[-1]) # live price = forming candle's close | |
| candles = raw.iloc[:-1] # closed candles only for signals | |
| closed_ts = candles["timestamp"].iloc[-1] | |
| new_candle = closed_ts != self._last_closed_ts | |
| eq = self.equity(price) | |
| self.rm.observe(eq, now) | |
| action, reason = "hold", "" | |
| # stop-loss first, on every tick, against the live price | |
| if self.position.open and self.position.stop and price <= self.position.stop: | |
| fill = self.broker.market_sell(self.symbol, self.position.qty, "stop-loss") | |
| self.position.reduce(fill.qty) | |
| if hasattr(self.strategy, "reset"): | |
| self.strategy.reset() | |
| action, reason = "sell", "stop-loss" | |
| elif not new_candle: | |
| reason = "waiting for next candle close" | |
| elif not self.rm.halted: | |
| self._last_closed_ts = closed_ts | |
| sig = self.strategy.evaluate(candles, self.position.open, self.position.avg_entry or None) | |
| exposure = self.position.value(price) | |
| if sig.action == "buy": | |
| quote_amt = self.rm.position_size_quote(eq, exposure, sig.fraction) | |
| quote_amt = min(quote_amt, self.broker.quote_balance(self.quote_ccy)) | |
| ok, why = self.rm.approve("buy", quote_amt, eq, exposure) | |
| if ok and quote_amt > 0: | |
| fill = self.broker.market_buy(self.symbol, quote_amt, sig.reason) | |
| self.position.add(fill.qty, fill.price, now) | |
| self.position.stop = self.rm.stop_price(self.position.avg_entry, sig.stop) | |
| action, reason = "buy", sig.reason | |
| else: | |
| reason = f"buy blocked: {why}" | |
| elif sig.action == "sell" and self.position.open: | |
| qty = self.position.qty * min(1.0, sig.fraction) | |
| ok, why = self.rm.approve("sell", qty * price, eq, exposure) | |
| if ok: | |
| fill = self.broker.market_sell(self.symbol, qty, sig.reason) | |
| self.position.reduce(fill.qty) | |
| action, reason = "sell", sig.reason | |
| else: | |
| reason = f"sell blocked: {why}" | |
| else: | |
| reason = sig.reason | |
| else: | |
| reason = f"halted: {self.rm.state.halted_reason}" | |
| rep = TickReport(now.isoformat(), price, round(self.equity(price), 2), action, reason, | |
| self.position.qty, round(self.position.unrealized_pct(price) * 100, 2), | |
| self.rm.state.halted_reason) | |
| except Exception as e: | |
| log.exception("tick failed for %s", self.bot_id) | |
| rep = TickReport(now.isoformat(), 0.0, 0.0, "error", "", self.position.qty, 0.0, | |
| self.rm.state.halted_reason, error=str(e)[:300]) | |
| self.history.append(rep) | |
| self.history = self.history[-500:] | |
| return rep | |