1
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:
listik committed 2026-10-23 20:49:12 +03:00
1 parent 2ea1a79bda
commit 85425483c0
50 files changed
+6468 -1854

No files matched your search

+491 -89
View File
@@ -27,6 +27,7 @@ after each real trade they are replaced by what the exchanges actually charged,
from __future__ import annotations
import json
from persistence import atomic_write_json
import queue
import threading
import time
@@ -175,6 +176,8 @@ class CrossSettings:
negative_funding_before_minutes: float = 60.0 # block negative funding only this long before settlement
min_funding_pct: float = -1.0 # block entry when funding is below this rate, per funding interval
simulation_execution_delay_ms: float = 600.0 # paper orders fill this long after the signal
simulation_entry_delay_ms: float = 600.0
simulation_exit_delay_ms: float = 600.0
@dataclass
@@ -217,6 +220,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:
@@ -394,14 +400,27 @@ def _quote_now(l: "Link", usd: float) -> tuple[float, float, float, float, float
b["spread_pct"])
def _quote_close(l: Link, usd: float):
import fastquote
a = fastquote.execution(l.spot_ex, "spot", l.spot_symbol, usd)
b = fastquote.execution(l.fut_ex, "spot" if l.ss else "fut", l.fut_symbol, usd)
if a["bid"] is None or b["ask"] is None:
raise ThinBook("недостаточная глубина для закрытия")
return a["bid"], a["best_ask"], b["best_bid"] / l.fut_mult, b["ask"] / l.fut_mult, a["spread_pct"], b["spread_pct"]
class CrossEngine:
"""One engine per kind of trading: paper (simulation) or real — each started and stopped by itself. The real
one follows the paper one: it is handed the same prices and usual gaps every cycle (no second set of requests)."""
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] = []
@@ -431,6 +450,7 @@ class CrossEngine:
# real trading
self.client_for = _client
self.quote_now = _quote_now if start else None # fresh prices right before a real entry (tests: none)
self.quote_close = _quote_close if start else None
self.balances: dict = {} # web_sim's BALANCES (exchange key → account figures)
self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"}
self.opening: set[str] = set() # coins with a real entry in progress
@@ -459,6 +479,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()
@@ -470,10 +506,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:
@@ -491,11 +540,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)."""
@@ -551,7 +605,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:
@@ -595,17 +653,92 @@ 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}}
tmp = self.file.with_suffix(".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(self.file)
"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:
import math
for name in ('simulation_entry_delay_ms', 'simulation_exit_delay_ms'):
if name in values:
try:
value = float(values[name])
if not math.isfinite(value) or not 0 <= value <= 60000:
raise ValueError()
except (ValueError, TypeError):
return 'Задержка должна быть от 0 до 60000 мс'
with self.lock:
was = (self.settings.running, self.settings.real)
for f in fields(CrossSettings):
@@ -641,7 +774,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:
@@ -938,10 +1073,12 @@ 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 and base not in self.opening:
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):
self.opening.add(base)
self.pending[base] = info
del self.recover[base]
self.jobs.put(("recover", base, info))
if s.real:
@@ -951,11 +1088,12 @@ class CrossEngine:
# links itself); the hot links are refreshed in between by the hot watch
rows = self.candidates(now)
self.cand, self.cand_time = {r["key"]: r for r in rows}, now
real_busy = s.real and (self.opening or now < self.real_pause_until or self.waiting_baseline(now))
real_busy = s.real and (self.opening or self.pending or self.recover
or now < self.real_pause_until or self.waiting_baseline(now))
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")
BASELINE_WAIT_S = 60.0
@@ -977,8 +1115,8 @@ class CrossEngine:
for r in rows:
self.cand[r["key"]] = r
s = self.settings
if s.running and not (s.real and (self.opening or now < self.real_pause_until
or self.waiting_baseline(now))):
if s.running and not (s.real and (self.opening or self.pending or self.recover
or now < self.real_pause_until or self.waiting_baseline(now))):
if self._entries(now, rows):
self.save()
@@ -997,10 +1135,18 @@ class CrossEngine:
if not pos.real and pos.uid in self.paper_closing:
continue
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
@@ -1043,48 +1189,85 @@ class CrossEngine:
else:
if self._schedule_paper_close(pos.uid, reason):
changed = True
elif self.account_error:
return False
return changed
def _paper_delay(self) -> float:
def _paper_delay(self, closing: bool = False) -> float:
"""Delay used only by the simulator; tests without a running loop stay synchronous."""
if self.quote_now is None:
return 0.0
return max(0.0, float(self.settings.simulation_execution_delay_ms)) / 1000.0
value = self.settings.simulation_exit_delay_ms if closing else self.settings.simulation_entry_delay_ms
return max(0.0, float(value)) / 1000.0
def _schedule_paper_close(self, uid: int, reason: str) -> bool:
if uid in self.paper_closing:
return False
self.paper_closing.add(uid)
delay = self._paper_delay()
delay = self._paper_delay(closing=True)
if delay <= 0:
self._paper_close(uid, reason)
return self._paper_close(uid, reason)
else:
timer = threading.Timer(delay, self._paper_close, args=(uid, reason))
timer.daemon = True
timer.start()
return True
def _paper_close(self, uid: int, reason: str) -> None:
def _paper_close(self, uid: int, reason: str) -> bool:
# Fetch outside the engine lock so slow public APIs do not freeze the UI.
with self.lock:
pos = next((p for p in self.positions if p.uid == uid), None)
link = self.links.get(pos.key) if pos else None
if link is not None and self.quote_now is not None:
try:
import dataclasses
sb, sa, fb, fa, _, _ = (self.quote_close or self.quote_now)(link, pos.qty * max(link.spot_bid, link.fut_ask))
if min(sb, sa, fb, fa) <= 0:
raise ValueError("пустой стакан")
with self.lock:
self.links[link.key] = dataclasses.replace(link, spot_bid=sb, spot_ask=sa, fut_bid=fb, fut_ask=fa)
except Exception:
with self.lock:
self.paper_closing.discard(uid)
return False
with self.lock:
self.paper_closing.discard(uid)
pos = next((p for p in self.positions if p.uid == uid), None)
if pos is None:
return
return False
l = self.links.get(pos.key)
if l is None:
return
self._close(pos, l, time.time(), reason)
self.save()
return False
now = time.time()
if not self._close(pos, l, now, reason):
return False
return self.save()
def _paper_open(self, base: str, key: str, usual: float, amount: float, signal_time: float) -> None:
def _paper_open(self, base: str, key: str, usual: float, amount: float, signal_time: float) -> bool:
with self.lock:
link = self.links.get(key)
if link is not None and self.quote_now is not None:
link = self._still_good(link, usual, amount)
if link is None:
with self.lock:
self.paper_opening.discard(base)
return False
with self.lock:
self.paper_opening.discard(base)
if self.quote_now is not None:
if not self.settings.running or self.paper_closing:
return False
rows = self.candidates(time.time(), [key])
if not rows or not rows[0]["fits"]:
return False
if self.account is not None and self.account_error:
return False
if any(p.base == base for p in self.positions) or self.elsewhere(base):
return
return False
l = self.links.get(key)
if l is None or l.spot_ask <= 0 or l.fut_bid <= 0:
return
now = time.time()
if l is None or l.spot_ask <= 0 or l.fut_bid <= 0 or self.full(l):
return False
now = time.time() if self._paper_delay() > 0 else signal_time
qty = amount / l.spot_ask
fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \
+ qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100
@@ -1094,12 +1277,21 @@ 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, 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
self.save()
if self.account is not None:
self.cash_total -= fee_in
return self.save(event=f"Арбитраж: вход {base}")
def _entries(self, now: float, rows: list[dict] | None = None) -> bool:
import basis
s = self.settings
if not s.real and self.quote_now is not None and (self.paper_opening or self.paper_closing):
return False
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 | self.paper_opening
best: dict[str, dict] = {}
@@ -1113,6 +1305,8 @@ class CrossEngine:
continue
if l.base in busy or now - self.last_close.get(l.base, 0.0) < s.cooldown_s:
continue
if self.real_block.get(l.base, ("", 0.0))[1] > now:
continue
if self.elsewhere(l.base):
continue # the coin is already in a trade on a spot–futures tab
if s.real:
@@ -1124,12 +1318,15 @@ class CrossEngine:
self.paper_opening.add(l.base)
delay = self._paper_delay()
if delay <= 0:
self._paper_open(l.base, l.key, r["usual"], s.amount, now)
if not self._paper_open(l.base, l.key, r["usual"], s.amount, now):
break
else:
timer = threading.Timer(delay, self._paper_open,
args=(l.base, l.key, r["usual"], s.amount, now))
timer.daemon = True
timer.start()
changed = True
break
busy.add(l.base)
changed = True
return changed
@@ -1172,8 +1369,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 ---------
@@ -1239,7 +1437,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,
@@ -1247,6 +1445,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:
@@ -1264,18 +1466,24 @@ class CrossEngine:
l = self.links.get(pos.key)
if l is None:
continue
self._schedule_paper_close(pos.uid, "вручную")
n += 1
self.save()
if self._schedule_paper_close(pos.uid, "вручную"):
n += 1
elif self.account_error:
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) ------------------
@@ -1309,8 +1517,91 @@ class CrossEngine:
elif kind in ("open", "recover"):
base = args[0].base if kind == "open" else args[0]
self.opening.discard(base)
if self.pending.pop(base, None) is not None:
self.save()
info = self.pending.pop(base, None)
if info is not None:
# Only preparation is certainly unsent. Every later stage survives errors and restart.
if info.get("phase") != "prepared":
info["retry_at"] = time.time() + 5
self.recover[base] = info
try:
self.save()
except (OSError, ValueError) as exc:
self.real_pause_until = time.time() + 60
self.real_pause_reason = f"не удалось сохранить восстановление: {exc}"
def _pending_update(self, base: str, **values) -> None:
with self.lock:
before = dict(self.pending[base])
self.pending[base].update(values)
try:
self.save()
except Exception:
self.pending[base] = before
raise
def _pending_done(self, base: str) -> None:
with self.lock:
pending, recovering = self.pending.pop(base, None), self.recover.pop(base, None)
self.last_close[base] = time.time()
try:
self.save()
except Exception:
if pending is not None:
self.pending[base] = pending
if recovering is not None:
self.recover[base] = recovering
raise
def _pending_problem(self, base: str, text: str) -> None:
with self.lock:
info = self.pending[base]
changed = info.get("error") != text
info["error"] = text
self.save()
if changed:
self._journal(base, "recover", False, text + "; новые реальные входы заблокированы")
def _cancel_entry(self, l: Link, cb, oid: str) -> dict | None:
"""A cancel acknowledgement is not terminal confirmation; never hedge a still-working entry."""
import live
try:
state = cb.fut_order_status(l.fut_symbol, oid)
if state["final"]:
return state
except live.LiveError:
pass
try:
cb.fut_cancel(l.fut_symbol, oid)
except live.LiveError:
pass
try:
state = cb.fut_order_status(l.fut_symbol, oid)
if state["final"]:
return state
except live.LiveError:
pass
self._pending_problem(l.base, f"не подтверждена отмена входа {oid} на {l.fut_ex}; повторяю сверку")
return None
def _rollback_entry(self, l: Link, cb) -> None:
"""Retain the durable entry until the exchange confirms the short has actually gone."""
import live
try:
held = cb.fut_position(l.fut_symbol)
if held < -1e-12:
try:
cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True)
except live.LiveError as exc:
if not exc.sent:
raise
held = cb.fut_position(l.fut_symbol)
if abs(held) > 1e-12:
raise live.LiveError(f"на фьючерсе осталось {held:+g} {l.base}")
except live.LiveError as exc:
self._pending_problem(l.base, f"откат входа не завершён: {exc}; повторяю закрытие")
return
self._pending_done(l.base)
self._journal(l.base, "recover", True, "откат входа завершён: биржа подтвердила отсутствие позиции")
@staticmethod
def _api_closed(error: str) -> bool:
@@ -1370,10 +1661,11 @@ 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}
"amount": amount, "link": asdict(l), "phase": "prepared"}
self.save()
notional = coins * l.fut_bid
fut_need = max(notional * self.FUT_NEED, equity_for(s.min_liq_pct, notional))
@@ -1413,14 +1705,21 @@ class CrossEngine:
# leaves nothing filled and nothing is bought on A; otherwise it waits «Лимитный вход: ждать, с»
hold = 0.0 if s.entry_ioc else max(0.0, s.limit_hold_s)
name = "IOC-шорт" if s.entry_ioc else "лимитный шорт"
self._pending_update(l.base, phase="limit_submitted")
try:
oid = cb.fut_limit(l.fut_symbol, "sell", coins, l.fut_bid)
except (live.LiveError, AttributeError) as exc:
if getattr(exc, "sent", False):
self._pending_update(l.base, order_id=getattr(exc, "order_id", ""))
self._pending_problem(l.base, f"результат лимитного входа неизвестен: {exc}")
return
self._pending_done(l.base)
self._journal(l.base, "open", False, f"{name} на {l.fut_ex} не выставлен: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
self._pause_if_balance(str(exc), l.fut_ex)
return
self._pending_update(l.base, order_id=oid)
st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False}
end = time.time() + hold
while True: # one look a second: the exchange's request limit
@@ -1432,25 +1731,19 @@ class CrossEngine:
break
time.sleep(1.0)
if not st["final"]:
try:
cb.fut_cancel(l.fut_symbol, oid)
except live.LiveError:
pass
try:
st = cb.fut_order_status(l.fut_symbol, oid)
except live.LiveError:
try:
st = {**st, "coins": max(0.0, -cb.fut_position(l.fut_symbol))}
except live.LiveError:
pass
st = self._cancel_entry(l, cb, oid)
if st is None:
return
shorted, fut_price, fut_fee_usd = st["coins"], st["price"] or l.fut_bid, st["fee"]
if shorted <= 0:
self._pending_done(l.base)
self._journal(l.base, "open", False, f"{name} на {l.fut_ex} по {l.fut_bid:.10g} не исполнился"
f"{'' if s.entry_ioc else f' за {hold:g} с'} — снят, на {l.spot_ex} ничего не покупалось")
with self.lock:
self.last_close[l.base] = time.time()
return
else:
self._pending_update(l.base, phase="market_submitted")
try:
fut = cb.fut_order(l.fut_symbol, "sell", coins, reduce_only=False)
shorted, fut_price, fut_fee_usd, fut_exact = fut.coins, fut.price, fut.fee_usd, fut.exact
@@ -1462,6 +1755,11 @@ class CrossEngine:
except live.LiveError:
held = coins # unknown: assume open — the close is reduce-only
if held <= 0:
if getattr(exc, "sent", False):
self._pending_update(l.base, order_id=exc.order_id)
self._pending_problem(l.base, f"результат рыночного входа неизвестен: {exc}")
return
self._pending_done(l.base)
self._journal(l.base, "open", False, f"шорт на {l.fut_ex} не открыт: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
@@ -1469,6 +1767,7 @@ class CrossEngine:
return
shorted, fut_price = held, l.fut_bid
fut_fee_usd, fut_exact = held * l.fut_bid * fut_fee(l.fut_ex, self.fees, l.innovation) / 100, False
self._pending_update(l.base, phase="hedge_submitted", shorted=shorted)
# 2) the hedge: the same coins on spot on A (the buy fee is taken in coins: a little more USDT)
try:
buy = ca.spot_buy(l.base, shorted * l.spot_ask * (1 + a_fee / 100) * 1.003)
@@ -1480,25 +1779,24 @@ class CrossEngine:
except live.LiveError:
bought = 0.0
if bought <= 0:
try:
cb.fut_order(l.fut_symbol, "buy", shorted, reduce_only=True)
text = f"шорт {shorted:g} на {l.fut_ex} открыт, но спот на {l.spot_ex} не куплен ({exc}); шорт закрыт"
except live.LiveError as exc2:
text = (f"шорт {shorted:g} на {l.fut_ex} открыт, спот на {l.spot_ex} не куплен ({exc}); ШОРТ НЕ "
f"ЗАКРЫТ ({exc2}) — закройте вручную")
self._journal(l.base, "open", False, text)
with self.lock:
self.last_close[l.base] = time.time()
if self._api_closed(str(exc)): # PTB: tried 7 times, fees paid each time
if getattr(exc, "sent", False):
self._pending_problem(l.base, f"результат покупки спота неизвестен: {exc}; требуется сверка")
return
self._pending_update(l.base, phase="rollback")
self._rollback_entry(l, cb)
if self._api_closed(str(exc)):
self._not_tradable(l.base, f"биржа {l.spot_ex} не даёт торговать {l.base} через API: {exc}", 86400)
self._pause_if_balance(str(exc), l.spot_ex)
return
buy = live.Fill(bought, l.spot_ask, bought * l.spot_ask * a_fee / 100, exc.order_id, exact=False)
self._pending_update(l.base, phase="hedge_confirmed", buy=asdict(buy), shorted=shorted,
fut_price=fut_price, fut_fee=fut_fee_usd)
try:
free = ca.spot_free(l.base)
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()
@@ -1511,9 +1809,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)
@@ -1590,10 +1897,11 @@ 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}
"amount": amount, "link": asdict(l), "phase": "prepared"}
self.save()
if s.auto_transfer:
try:
@@ -1607,10 +1915,12 @@ class CrossEngine:
return
self._journal(l.base, "transfer", False, f"{l.spot_ex}: перевод не удался: {exc} — пробую без него")
# 1) sell the stock on B
self._pending_update(l.base, phase="spot_submitted", stock_before=have)
try:
sold = cb.spot_sell(l.base, coins)
except live.LiveError as exc:
if not getattr(exc, "sent", False):
self._pending_done(l.base)
self._journal(l.base, "open", False, f"продажа {l.base} на споте {l.fut_ex} не прошла: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
@@ -1626,6 +1936,8 @@ class CrossEngine:
else:
try:
cb.spot_buy(l.base, sold.coins * l.fut_ask * (1 + b_fee_pct / 100) * 1.003)
if cb.spot_free(l.base) >= have - 1e-9:
self._pending_done(l.base)
text = (f"{l.base} продан на {l.fut_ex}, но на {l.spot_ex} не куплен ({exc}); запас на "
f"{l.fut_ex} выкуплен обратно")
except live.LiveError as exc2:
@@ -1651,6 +1963,7 @@ class CrossEngine:
[l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]])
self.next_uid += 1
self.positions.append(pos)
self.pending.pop(l.base, None)
self.save()
self._journal(l.base, "open", True, f"спот-спот: продано {sold.coins:g} на {l.fut_ex} по {sold.price:.10g}, "
f"куплено {got:g} на {l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% "
@@ -1680,6 +1993,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
@@ -1691,7 +2060,7 @@ class CrossEngine:
# Refresh both executable sides immediately before the first close order. The fast watcher normally
# updates every 250 ms, but its previous snapshot may have been taken before the close job reached here.
# A normal convergence close is postponed when the current executable prices are already losing after fees.
if reason != "вручную" and "стоп:" not in reason and "ликвидац" not in reason:
if not pos.closing and reason != "вручную" and "стоп:" not in reason and "ликвидац" not in reason:
try:
l0 = self.links.get(pos.key)
if l0 is not None:
@@ -1727,23 +2096,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:
@@ -1871,39 +2225,79 @@ class CrossEngine:
import live
with self.lock:
l = self.links.get(info.get("key", ""))
if l is None and info.get("link"):
l = Link(**info["link"])
already_owned = any(p.real and p.base == base for p in self.positions)
if already_owned or info.get("phase") == "prepared":
self._pending_done(base)
return
if l is None:
self._pending_problem(base, "нет сохранённых параметров незавершённой сделки")
return
phase = info.get("phase")
if not l.ss and phase in ("limit_submitted", "market_submitted", "rollback"):
cb = self.client_for(l.fut_ex)
if phase != "rollback":
oid = info.get("order_id")
if not oid:
self._pending_problem(base, "отправленный вход без ID: требуется ручная сверка ордеров биржи")
# Retain the intent even when flat; a delayed fill must not permit another entry.
held = cb.fut_position(l.fut_symbol)
if held < -1e-12:
cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True)
return
if self._cancel_entry(l, cb, oid) is None:
return
self._pending_update(base, phase="rollback")
self._rollback_entry(l, cb)
return
if phase == "hedge_submitted":
# Without an exchange order id, an unchanged spot balance does not prove rejection.
self._pending_problem(base, "незавершённая покупка спота: требуется ручная сверка обеих ног")
return
if l.ss: # a spot sale cannot be told apart from the user's own trades: say so, no guess
self._journal(base, "open", False, f"после перезапуска: незавершённый вход спот-спот {l.spot_ex} → "
f"{l.fut_ex} — проверьте {base} на обеих биржах вручную")
self._pending_problem(base, f"незавершённый вход спот-спот {l.spot_ex} → "
f"{l.fut_ex} — проверьте {base} на обеих биржах вручную")
return
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
self._journal(base, "open", False, f"после перезапуска: не удалось проверить незавершённый вход: {exc}")
return
if short <= 0 and coins * l.spot_bid < 1.0:
self._pending_done(base)
self._journal(base, "open", True, "после перезапуска: незавершённый вход — на биржах ничего не открыто")
return
with self.lock:
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)
self.recover.pop(base, None)
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:
@@ -2061,11 +2455,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,
"real_pause": (f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)"
"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 "завершение закрытия: " + ", ".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