feat: добавить общий виртуальный счёт, справку и восстановление позиций
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s

This commit is contained in:
Igol committed 2026-10-22 23:07:50 +03:00
1 parent 6aa76064dc
commit c5aed5b970
29 files changed
+3600 -224

No files matched your search

+252 -40
View File
@@ -214,6 +214,9 @@ class CrossPosition:
entry_signal: list = field(default_factory=list) # A ask, B bid confirmed right before the entry orders
exit_signal: list = field(default_factory=list) # A bid, B ask when the close was decided
exit_since: float = 0.0 # when the gap last came back to the usual level (0 = it is not there now)
close_buy: dict = field(default_factory=dict) # durable spot-stock repurchase; never replay an unknown order
paper_reserve: float = 0.0 # collateral fixed at entry/import; later settings only affect new positions
paper_unrealized: float | None = None # last observed gross PnL minus exit fees; retained when a venue disappears
@property
def kind(self) -> str:
@@ -397,8 +400,12 @@ class CrossEngine:
mode = "cross"
def __init__(self, data_dir: Path = DATA_DIR, start: bool = True, real: bool = False,
leader: "CrossEngine | None" = None) -> None:
leader: "CrossEngine | None" = None, account=None) -> None:
self.is_real = real
self.account = account if not real else None
self.account_error = ""
self.cash_total = 0.0
self._account_initializing = True
self.key = "cross_real" if real else "cross"
self.file = data_dir / ("basis_cross_real.json" if real else "basis_cross.json")
self.followers: list[CrossEngine] = []
@@ -454,6 +461,22 @@ class CrossEngine:
self.usual, self.seen_since, self.last_seen = leader.usual, leader.seen_since, leader.last_seen
self.innovation = leader.innovation
leader.followers.append(self)
self._account_initializing = False
if self.account is not None and not self.account_error:
from virtual_account import AccountError
try:
registered = self.account.restore("cross")
if registered is None:
unrealized = self._unrealized()
self.account.commit("cross", self._state(), cash_total=self.cash_total,
reserved=self._reserved(), unrealized=unrealized,
allow_existing=True, event="Подключение бумажного арбитража")
elif self._state() != registered:
# Newly discovered legacy venues must reserve their exposure before any worker starts.
self.save(event="Арбитраж: импорт сохранённых позиций")
except AccountError as exc:
self.account_error = str(exc)
self.settings.running = False
if start:
if leader is None:
threading.Thread(target=self._loop, daemon=True).start()
@@ -465,10 +488,23 @@ class CrossEngine:
# --- persistence -----------------------------------------------------------------------------------------
def _load(self) -> None:
d = None
if self.account is not None:
from virtual_account import AccountError
try:
d = self.account.restore("cross")
except AccountError as exc:
self.account_error = str(exc)
try:
d = json.loads(self.file.read_text(encoding="utf-8"))
if d is None:
d = json.loads(self.file.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
self._load_state(d)
if self.account_error:
self.settings.running = False
def _load_state(self, d: dict) -> None:
known = {f.name for f in fields(CrossSettings)}
for k, v in (d.get("settings") or {}).items():
if k in known:
@@ -486,11 +522,16 @@ class CrossEngine:
if v is not None:
self.limits[ex] = int(v)
self.positions = [CrossPosition(**p) for p in d.get("positions", [])]
for pos in self.positions:
if not pos.real and pos.paper_reserve <= 0:
pos.paper_reserve = self._position_reserve(pos)
self.trades = [CrossTrade(**t) for t in d.get("trades", [])]
self.next_uid = d.get("next_uid", 1)
self.baseline = d.get("baseline") or {}
self.recover = dict(d.get("pending") or {})
self.migrated = list(d.get("migrated") or [])
self.last_close = dict(d.get("last_close") or {})
self.cash_total = float(d.get("cash_total", sum(p.funding - p.fees for p in self.positions if not p.real)))
def _seed_from(self, paper_file: Path) -> None:
"""The real engine's first settings, fee table and limits: those of the simulation (stopped)."""
@@ -546,7 +587,11 @@ class CrossEngine:
sold_fees=p.get("sold_fees", 0.0), exact=p.get("exact", True),
innovation=p.get("innovation", False))
self.next_uid += 1
if not pos.real:
pos.paper_reserve = self._position_reserve(pos)
self.positions.append(pos)
if self.account is not None:
self.cash_total += pos.funding - pos.fees
moved.append(f"{p['base']} ({ex}{', реальная' if pos.real else ''})")
for t in d.get("trades", []):
if bool(t.get("real", False)) != self.is_real:
@@ -590,13 +635,81 @@ class CrossEngine:
except OSError:
pass
def save(self) -> None:
self.file.parent.mkdir(exist_ok=True)
def _state(self) -> dict:
# Legacy/manual paper positions acquire their fixed reserve before the recovery snapshot is serialized.
if self.account is not None:
self._reserved()
data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions],
"trades": [asdict(t) for t in self.trades[-KEEP_TRADES:]], "next_uid": self.next_uid,
"fees": self.fees, "limits": self.limits, "baseline": self.baseline, "migrated": self.migrated,
"pending": {**self.recover, **self.pending}}
atomic_write_json(self.file, data)
"pending": {**self.recover, **self.pending}, "last_close": self.last_close}
if self.account is not None:
data["cash_total"] = self.cash_total
return data
def _position_reserve(self, pos: CrossPosition) -> float:
notional = pos.qty * pos.fut_entry
return pos.qty * pos.spot_entry + (notional if pos.ss else
max(notional * self.FUT_NEED, equity_for(self.settings.min_liq_pct, notional)))
def _reserved(self) -> float:
total = 0.0
for pos in self.positions:
if pos.real:
continue
if pos.paper_reserve <= 0:
pos.paper_reserve = self._position_reserve(pos)
total += pos.paper_reserve
return total
def _unrealized(self) -> float:
total = 0.0
for pos in self.positions:
if pos.real:
continue
link = self.links.get(pos.key)
if link is not None or pos.paper_unrealized is None:
bid, ask = (link.spot_bid, link.fut_ask) if link else (pos.spot_entry, pos.fut_entry)
_, _, _, net = close_result(pos, bid, ask, self.fees)
# entry fees/funding already changed cash; quote loss must survive outages/settings/restarts.
pos.paper_unrealized = net + pos.fees - pos.funding
total += pos.paper_unrealized
return total
def _mark_account(self, snapshot_fresh: bool = False) -> None:
now = time.time()
if self.account is not None and all(
p.key in self.links and (snapshot_fresh or now - max(self.updated, self.fast_seen.get(p.key, 0)) <= 30)
for p in self.positions if not p.real):
self.account.mark("cross", self._unrealized())
def save(self, event: str = "") -> bool:
unrealized = self._unrealized() if self.account is not None else 0.0
data = self._state()
shared = self.account is not None and not self._account_initializing
if shared:
from virtual_account import AccountError
try:
self.account.commit("cross", data, cash_total=self.cash_total,
reserved=self._reserved(), unrealized=unrealized, event=event)
except AccountError as exc:
try:
saved = self.account.restore("cross")
if saved is not None:
self._load_state(saved)
except AccountError:
pass
self.account_error = str(exc)
self.settings.running = False
return False
try:
self.file.parent.mkdir(exist_ok=True)
atomic_write_json(self.file, data)
except (OSError, ValueError):
if not shared:
raise
# The account owns the authoritative snapshot; a failed compatibility copy cannot undo a commit.
return True
def set_settings(self, values: dict) -> str:
with self.lock:
@@ -634,7 +747,9 @@ class CrossEngine:
self.save()
return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под "
f"одним тикером). Установлено {basis.HARD_MAX_GAP_PCT:g}%, остальное сохранено")
self.save()
if not self.save():
return self.account_error
self.account_error = ""
return ""
def _set_fees(self, given) -> str:
@@ -920,6 +1035,7 @@ class CrossEngine:
def step(self, now: float) -> None:
s = self.settings
self._mark_account(snapshot_fresh=True)
for base, info in list(self.recover.items()):
# an entry cut off by a stop of the program: whatever was opened becomes a position again
if (info.get("key") in self.links or info.get("link")) and base not in self.opening and time.time() >= info.get("retry_at", 0):
@@ -938,7 +1054,7 @@ class CrossEngine:
if s.running and not real_busy: # real: the next trade only after the previous is confirmed
changed = self._entries(now, rows) or changed
if changed:
self.save()
self.save(event="Арбитраж: обновление позиций и funding")
def hot_step(self, keys: list[str], now: float) -> None:
"""The hot links have fresh prices: their rows again, and an entry if one of them fits now."""
@@ -964,10 +1080,18 @@ class CrossEngine:
changed = False
for pos in list(self.positions):
l = self.links.get(pos.key)
# Once a real unwind has started it must not depend on a fresh listing or another exit signal.
if pos.real and pos.closing and pos.uid not in self.busy and now >= pos.retry_at:
self.busy.add(pos.uid)
self.jobs.put(("close", pos.uid, "завершение начатого закрытия"))
continue
if l is None:
continue
while pos.next_funding and now >= pos.next_funding:
pos.funding += pos.qty * (l.fut_bid + l.fut_ask) / 2 * l.funding # the short receives positive
funding = pos.qty * (l.fut_bid + l.fut_ask) / 2 * l.funding
pos.funding += funding # the short receives positive funding
if self.account is not None and not pos.real:
self.cash_total += funding
step = l.interval_h * 3600
pos.next_funding += step
changed = True
@@ -1008,13 +1132,18 @@ class CrossEngine:
pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap]
self.jobs.put(("close", pos.uid, reason))
else:
self._close(pos, l, now, reason)
if not self._close(pos, l, now, reason):
return False
changed = True
return changed
def _entries(self, now: float, rows: list[dict] | None = None) -> bool:
import basis
s = self.settings
if self.account is not None and self.account_error:
return False
if s.real and any(p.real and p.closing for p in self.positions):
return False
changed = False
busy = {p.base for p in self.positions} | self.opening
best: dict[str, dict] = {}
@@ -1046,7 +1175,12 @@ class CrossEngine:
self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, qty, l.spot_ask,
l.fut_bid, l.entry_gap, r["usual"], fee_in, 0.0 if l.ss else (now // step + 1) * step,
innovation=l.innovation, liq_price=liq, liq_calc=liq, liq_src="" if l.ss else "расчёт", ss=l.ss))
self.positions[-1].paper_reserve = self._position_reserve(self.positions[-1])
self.next_uid += 1
if self.account is not None:
self.cash_total -= fee_in
if not self.save(event=f"Арбитраж: вход {l.base}"):
break
busy.add(l.base)
changed = True
return changed
@@ -1089,8 +1223,9 @@ class CrossEngine:
for k in fresh:
self.fast_seen[k] = now
self.fast_ms = int((now - start) * 1000)
self._mark_account()
if self._check_exits(now):
self.save()
self.save(event="Арбитраж: обновление позиций и funding")
time.sleep(max(0.05, self.FAST_S - (time.time() - start)))
# --- hot watch: links already in profit on paper, priced every HOT_S so an entry point is not missed ---------
@@ -1156,7 +1291,7 @@ class CrossEngine:
e.hot_step(done or keys, now)
time.sleep(max(0.05, self.HOT_S - (time.time() - start)))
def _close(self, pos: CrossPosition, l: Link, now: float, reason: str) -> None:
def _close(self, pos: CrossPosition, l: Link, now: float, reason: str) -> bool:
spot_pnl, fut_pnl, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees)
self.trades.append(CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty,
pos.spot_entry, l.spot_bid, pos.fut_entry, l.fut_ask, pos.entry_gap, l.exit_gap,
@@ -1164,6 +1299,10 @@ class CrossEngine:
pos.qty * pos.spot_entry, kind=pos.kind))
self.positions.remove(pos)
self.last_close[pos.base] = now
if self.account is not None:
self.cash_total += net + pos.fees - pos.funding
return self.save(event=f"Арбитраж: закрытие {pos.base}")
return True
def close(self, uid: int | None) -> str:
with self.lock:
@@ -1181,18 +1320,24 @@ class CrossEngine:
l = self.links.get(pos.key)
if l is None:
continue
self._close(pos, l, time.time(), "вручную")
n += 1
self.save()
if self._close(pos, l, time.time(), "вручную"):
n += 1
else:
return self.account_error
if not self.save():
return self.account_error
return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "")
def reset(self) -> str:
with self.lock:
if any(p.real for p in self.positions):
return "есть открытые реальные позиции — сначала закройте их"
if self.account is not None and self.positions:
return "есть открытые бумажные позиции — сначала закройте их, затем сбросьте статистику"
self.positions, self.trades, self.last_close = [], [], {}
self.baseline = {"time": time.time(), "total": None, "by_ex": {}} if self.settings.real else {}
self.save()
if not self.save():
return self.account_error
return "статистика сброшена"
# --- real orders (worker thread; never under the engine lock while waiting for an exchange) ------------------
@@ -1370,7 +1515,8 @@ class CrossEngine:
with self.lock:
# last check right before money is spent
held = [x.base for x in self.positions if x.real]
if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l):
if (l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l)
or any(p.real and p.closing for p in self.positions)):
return
self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual,
"amount": amount, "link": asdict(l), "phase": "prepared"}
@@ -1504,6 +1650,7 @@ class CrossEngine:
except live.LiveError:
free = 0.0
held = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100)
mismatch = shorted > held + max(1e-12, shorted * 1e-8)
with self.lock:
step = l.interval_h * 3600
now = time.time()
@@ -1516,10 +1663,18 @@ class CrossEngine:
entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap],
fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact],
[l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]])
if mismatch:
# Persist the unwind before any close request. A restart must never adopt an uncovered short.
pos.closing = "hedge_mismatch"
pos.error = f"частичный хедж: спот {held:g}, шорт {shorted:g}; закрываю обе ноги"
self.next_uid += 1
self.positions.append(pos)
self.pending.pop(l.base, None)
self.save()
if mismatch:
self._journal(l.base, "open", False, pos.error)
self._real_close(pos.uid, "частичный хедж")
return
self._journal(l.base, "open", True, f"шорт {shorted:g} на {l.fut_ex} по {fut_price:.10g}, спот {held:g} на "
f"{l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% (обычная {usual:+.3f}%), "
f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount)
@@ -1596,7 +1751,8 @@ class CrossEngine:
return
with self.lock:
held = [x.base for x in self.positions if x.real]
if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l):
if (l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l)
or any(p.real and p.closing for p in self.positions)):
return
self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual,
"amount": amount, "link": asdict(l), "phase": "prepared"}
@@ -1691,6 +1847,62 @@ class CrossEngine:
f"(+{(liq / pos.fut_entry - 1) * 100:.0f}% от входа), расчёт {pos.liq_calc:.10g} — "
f"расхождение {diff:+.1f}%")
def _restore_stock(self, pos: CrossPosition, cb) -> None:
"""Buy B's stock once, and release A only after a confirmed fill and the restored balance.
Spot clients have no common order-status API. An unknown submission therefore remains durable and
requires manual reconciliation: a balance change alone cannot distinguish our order from another trade.
"""
import live
intent = pos.close_buy
if not intent:
l = self.links.get(pos.key)
ask = l.fut_ask if l else pos.fut_entry
usdt = pos.qty * ask * (1 + spot_fee(pos.fut_ex, self.fees) / 100) * 1.003
before = cb.spot_free(pos.base)
with self.lock:
old_closing = pos.closing
pos.close_buy = {"phase": "submitted", "before": before, "usdt": usdt,
"required": pos.qty, "time": time.time()}
pos.closing = "spot_buy_submitted"
try:
self.save() # no buy unless its durable intent is on disk
except Exception:
pos.close_buy, pos.closing = {}, old_closing
raise
try:
back = cb.spot_buy(pos.base, usdt)
except live.LiveError as exc:
with self.lock:
if exc.sent:
pos.close_buy.update(phase="unknown", order_id=exc.order_id)
else: # certainly unsent: a later attempt is safe
pos.close_buy = {}
self.save()
raise
with self.lock:
pos.close_buy.update(phase="confirmed", fill=asdict(back))
self.save()
intent = pos.close_buy
if intent.get("phase") != "confirmed":
raise live.LiveError("результат выкупа спота неизвестен; требуется ручная сверка ордера, "
"повторная покупка заблокирована")
back = live.Fill(**intent["fill"])
required = float(intent["required"])
restored = cb.spot_free(pos.base) - float(intent["before"])
tolerance = max(1e-12, required * 1e-8)
if back.coins + tolerance < required:
raise live.LiveError(f"частичный выкуп спота: исполнено {back.coins:g} из {required:g}; "
"требуется ручная сверка, повторная покупка заблокирована")
if restored + tolerance < required:
raise live.LiveError(f"запас спота ещё не восстановлен: получено {max(0.0, restored):g} "
f"из {required:g}; проверяю баланс без повторного ордера")
with self.lock:
pos.fut_exit, pos.exit_fees, pos.closing = back.price, back.fee_usd, "fut_done"
pos.exact = pos.exact and back.exact
pos.fills.append([pos.fut_ex, "spot", back.fee_usd, back.coins * back.price, back.exact])
self.save()
def _real_close(self, uid: int, reason: str) -> None:
"""Buy the short back on B (reduce-only), make sure B shows no short left, then sell the coins on A."""
import live
@@ -1702,23 +1914,8 @@ class CrossEngine:
try:
ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex)
if pos.ss and pos.closing != "fut_done":
# spot–spot: buy the coins sold on B back (the stock there is restored), a little over for the fee
stage = f"выкуп монет на споте {pos.fut_ex}"
l = self.links.get(pos.key)
ask_b = l.fut_ask if l else pos.fut_entry
usdt = pos.qty * ask_b * (1 + spot_fee(pos.fut_ex, self.fees) / 100) * 1.003
try:
back = cb.spot_buy(pos.base, usdt)
price, fee, exact = back.price, back.fee_usd, back.exact
except live.LiveError as exc:
if not getattr(exc, "sent", False):
raise
price, fee, exact = ask_b, usdt * spot_fee(pos.fut_ex, self.fees) / 100, False
with self.lock:
pos.fut_exit, pos.exit_fees, pos.closing = price, fee, "fut_done"
pos.exact = pos.exact and exact
pos.fills.append([pos.fut_ex, "spot", fee, usdt, exact])
self.save()
self._restore_stock(pos, cb)
if pos.closing != "fut_done":
fut_coins, fut_price, fee, exact = 0.0, 0.0, 0.0, True
if pos.qty > 0:
@@ -1883,7 +2080,9 @@ class CrossEngine:
try:
ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex)
short = max(0.0, -cb.fut_position(l.fut_symbol))
coins = min(ca.spot_free(l.base), float(info.get("coins") or 0) * 1.05)
bought = info.get("buy") or {}
cap = float(bought.get("coins") or info.get("coins") or 0)
coins = min(ca.spot_free(l.base), cap if bought else cap * 1.05)
except live.LiveError as exc:
with self.lock:
self.recover[base] = info # tried again on the next cycle
@@ -1897,12 +2096,17 @@ class CrossEngine:
now = time.time()
step = l.interval_h * 3600
pos = CrossPosition(self.next_uid, base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, short,
l.spot_ask, l.fut_bid if short else 0.0, l.entry_gap, float(info.get("usual") or 0.0),
0.0, (now // step + 1) * step, real=True, spot_qty=coins, exact=False,
float(bought.get("price") or l.spot_ask),
float(info.get("fut_price") or l.fut_bid) if short else 0.0,
l.entry_gap, float(info.get("usual") or 0.0),
float(bought.get("fee_usd") or 0) + float(info.get("fut_fee") or 0),
(now // step + 1) * step, real=True, spot_qty=coins, exact=False,
innovation=l.innovation,
error="подхвачено после перезапуска — цены оценочные")
if short <= 0 or coins * l.spot_bid < 1.0: # one leg only: close what there is at once
pos.retry_at, pos.usual = 0.0, 1e9
unwind = short <= 0 or short > coins + max(1e-12, short * 1e-8)
if unwind: # one leg / partial hedge: close both legs immediately
pos.retry_at, pos.closing = 0.0, "hedge_mismatch"
pos.error = f"после перезапуска: неполный хедж (спот {coins:g}, шорт {short:g})"
self.next_uid += 1
self.positions.append(pos)
self.pending.pop(base, None)
@@ -1910,6 +2114,8 @@ class CrossEngine:
self.save()
self._journal(base, "open", True, f"после перезапуска: найден незавершённый вход — шорт {short:g} на "
f"{l.fut_ex}, спот {coins:g} на {l.spot_ex}; ведётся программой")
if unwind:
self._real_close(pos.uid, "восстановление частичного хеджа")
# --- balances --------------------------------------------------------------------------------------------
def coins_value(self, exchange: str) -> float:
@@ -2065,13 +2271,19 @@ class CrossEngine:
"real": s.real, "exact": all(t.exact for t in closed),
"avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None}
out = {"mode": "cross", "venue": "Арбитраж", "key": "cross", "settings": asdict(s),
"account_error": self.account_error,
"status": self.status, "ex_status": self.ex_status, "updated": self.updated,
"cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.links),
"memes_source": "", "rows": rows[:300], "positions": positions,
"trades": [asdict(t) for t in reversed(closed[-200:])], "stats": stats,
"recovery": {base: dict(info) for base, info in {**self.recover, **self.pending}.items()},
"real_pause": ("сверка незавершённых ордеров: " + ", ".join({**self.recover, **self.pending})
if s.real and (self.pending or self.recover) else f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)"
if s.real and (self.pending or self.recover)
else "завершение закрытия: " + ", ".join(p.base for p in self.positions if p.real and p.closing)
if s.real and any(p.real and p.closing for p in self.positions)
else f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)"
if s.real and now < self.real_pause_until else "")}
out["balances"] = self.balance_view(now)
if self.account is not None:
out["virtual_account"] = self.account.view()
return out