Fix trade recovery, local web isolation and backtest risk accounting
This commit is contained in:
1 parent
5c6b0dc54a
commit
6aa76064dc
29 files changed
+2662
-1693
No files matched your search
@@ -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
|
||||
@@ -595,9 +596,7 @@ class CrossEngine:
|
||||
"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)
|
||||
atomic_write_json(self.file, data)
|
||||
|
||||
def set_settings(self, values: dict) -> str:
|
||||
with self.lock:
|
||||
@@ -923,8 +922,9 @@ class CrossEngine:
|
||||
s = self.settings
|
||||
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:
|
||||
@@ -934,7 +934,7 @@ 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)
|
||||
real_busy = s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until)
|
||||
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:
|
||||
@@ -947,7 +947,7 @@ 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)):
|
||||
if s.running and not (s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until)):
|
||||
if self._entries(now, rows):
|
||||
self.save()
|
||||
|
||||
@@ -1226,8 +1226,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:
|
||||
@@ -1290,7 +1373,7 @@ class CrossEngine:
|
||||
if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l):
|
||||
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))
|
||||
@@ -1330,14 +1413,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
|
||||
@@ -1349,25 +1439,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
|
||||
@@ -1379,6 +1463,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()
|
||||
@@ -1386,6 +1475,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)
|
||||
@@ -1397,20 +1487,18 @@ 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:
|
||||
@@ -1430,6 +1518,7 @@ class CrossEngine:
|
||||
[l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]])
|
||||
self.next_uid += 1
|
||||
self.positions.append(pos)
|
||||
self.pending.pop(l.base, None)
|
||||
self.save()
|
||||
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}%), "
|
||||
@@ -1510,7 +1599,7 @@ class CrossEngine:
|
||||
if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l):
|
||||
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:
|
||||
@@ -1524,10 +1613,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()
|
||||
@@ -1543,6 +1634,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:
|
||||
@@ -1568,6 +1661,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}% "
|
||||
@@ -1752,11 +1846,39 @@ 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)
|
||||
@@ -1768,6 +1890,7 @@ class CrossEngine:
|
||||
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:
|
||||
@@ -1782,6 +1905,8 @@ class CrossEngine:
|
||||
pos.retry_at, pos.usual = 0.0, 1e9
|
||||
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}; ведётся программой")
|
||||
@@ -1944,7 +2069,9 @@ class CrossEngine:
|
||||
"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 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)
|
||||
return out
|
||||
Reference in new issue
Block a user