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
+102
-23
@@ -16,6 +16,7 @@ Results (prices, fees) are the exchange's own fills; `exact` is False where the
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from persistence import atomic_write_json
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
@@ -191,6 +192,7 @@ class FuturesMirror:
|
||||
self.position: dict | None = None # the one real position (opening / open / closing)
|
||||
self.trades: list[dict] = []
|
||||
self.state = "" # "" idle · "opening" · "open" · "closing" · "check" (verify zero)
|
||||
self.storage_error = ""
|
||||
self.problem = "" # last error that keeps the coin blocked
|
||||
self.on_failed_open = None # callback(uid): close the paper twin of a real order that failed
|
||||
self.exchange_trades: list[dict] | None = None # rebuilt from the exchange's fills (None: not synced yet)
|
||||
@@ -207,24 +209,67 @@ class FuturesMirror:
|
||||
def _load(self) -> None:
|
||||
try:
|
||||
d = json.loads(self.file.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
except FileNotFoundError:
|
||||
return
|
||||
except (OSError, ValueError) as exc:
|
||||
self.state, self.problem = "blocked", f"не прочитано состояние реальных ордеров: {exc}"
|
||||
return
|
||||
self.trades = d.get("trades", [])[-500:]
|
||||
pos = d.get("position")
|
||||
if pos:
|
||||
# paper positions do not survive a restart: the saved real one is closed at once
|
||||
pos["uid"] = None
|
||||
self.position, self.state = pos, "closing"
|
||||
self.jobs.put(("close", "осиротевшая после перезапуска"))
|
||||
self.position = pos
|
||||
if pos.get("phase") in ("prepared", "submitted"):
|
||||
self.state = "recover"
|
||||
self.jobs.put(("recover", None))
|
||||
else:
|
||||
self.state = "closing"
|
||||
self.jobs.put(("close", "осиротевшая после перезапуска"))
|
||||
|
||||
def _save(self) -> None:
|
||||
try:
|
||||
self.file.parent.mkdir(exist_ok=True)
|
||||
pos = self.position if self.state in ("open", "closing", "check") else None
|
||||
self.file.write_text(json.dumps({"position": pos, "trades": self.trades[-500:]}, ensure_ascii=False),
|
||||
encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
atomic_write_json(self.file, {"version": 2, "state": self.state,
|
||||
"position": self.position, "trades": self.trades[-500:]})
|
||||
except (OSError, ValueError) as exc:
|
||||
self.storage_error = f"не сохранено состояние ордеров: {exc}"
|
||||
raise
|
||||
self.storage_error = ""
|
||||
|
||||
def _recover_open(self) -> None:
|
||||
"""Never replay an entry after a crash. Resolve known orders; contain unknown submissions."""
|
||||
pos = self.position
|
||||
if not pos:
|
||||
return
|
||||
if pos.get("phase") == "prepared":
|
||||
self._failed_open("перезапуск до отправки ордера")
|
||||
return
|
||||
c = self.client_for(self.exchange)
|
||||
oid = pos.get("order_in")
|
||||
if pos.get("phase") != "filled":
|
||||
if not oid:
|
||||
# A lost submit response cannot be declared absent from one flat position snapshot.
|
||||
held = c.fut_position(self.symbol)
|
||||
if abs(held) > self.VERIFY_TOLERANCE:
|
||||
expected = 1 if pos["side"] == "LONG" else -1
|
||||
if held * expected <= 0:
|
||||
self.problem = "позиция другого направления — требуется ручная сверка"
|
||||
return
|
||||
c.fut_order(self.symbol, "sell" if held > 0 else "buy", abs(held), reduce_only=True)
|
||||
self.problem = "результат входа без ID неизвестен; новые входы заблокированы, сверяю и закрываю остаток"
|
||||
return
|
||||
status = c.fut_order_status(self.symbol, oid)
|
||||
if not status["final"]:
|
||||
c.fut_cancel(self.symbol, oid)
|
||||
status = c.fut_order_status(self.symbol, oid)
|
||||
if not status["final"]:
|
||||
self.problem = "ожидаю окончательный статус входа"
|
||||
return
|
||||
pos.update(phase="filled", coins=status["coins"], entry=status["price"] or pos["paper_entry"],
|
||||
fee_in=status["fee"], exact=False)
|
||||
with self.lock:
|
||||
self.state = "closing"
|
||||
self._save()
|
||||
self._close("восстановление незавершённого входа")
|
||||
|
||||
# --- the simulator's side ----------------------------------------------------------------------------------
|
||||
def coin_settings(self) -> dict:
|
||||
@@ -238,6 +283,8 @@ class FuturesMirror:
|
||||
if not self.enabled():
|
||||
return ""
|
||||
with self.lock:
|
||||
if self.storage_error:
|
||||
return self.storage_error
|
||||
left = self.paused_until - time.time()
|
||||
if self.state == "" and left > 0:
|
||||
# the exchange refused the last entry: no new trade (paper or real) until the pause ends
|
||||
@@ -258,7 +305,7 @@ class FuturesMirror:
|
||||
"""Paper events, called under the engine's lock: only queue work here."""
|
||||
with self.lock:
|
||||
if event == "open":
|
||||
if not self.enabled() or self.state or time.time() < self.paused_until:
|
||||
if not self.enabled() or self.state or self.storage_error or time.time() < self.paused_until:
|
||||
return # real mode off, or a real trade still runs (gate was bypassed)
|
||||
self.state = "opening"
|
||||
units = symbol_units(self.symbol)
|
||||
@@ -267,7 +314,12 @@ class FuturesMirror:
|
||||
# the paper take-profit as a distance from the entry: the real TP is placed at
|
||||
# the same distance from the REAL fill price, not at the paper price
|
||||
"tp_pct": (pos.target / pos.entry - 1) * 100 if getattr(pos, "target", None) else None,
|
||||
"ping": self.ping()}
|
||||
"ping": self.ping(), "phase": "prepared"}
|
||||
try:
|
||||
self._save()
|
||||
except (OSError, ValueError):
|
||||
self.state, self.problem = "recover", self.storage_error
|
||||
return
|
||||
self.jobs.put(("open", None))
|
||||
elif event == "close" and self.position and self.position.get("uid") == pos.uid:
|
||||
self.jobs.put(("close", "закрыта в симуляторе"))
|
||||
@@ -286,11 +338,15 @@ class FuturesMirror:
|
||||
self._open()
|
||||
elif kind == "close":
|
||||
self._close(arg)
|
||||
elif kind == "recover":
|
||||
self._recover_open()
|
||||
elif kind == "watch":
|
||||
self._watch()
|
||||
except Exception as exc: # never let the worker die
|
||||
with self.lock:
|
||||
self.problem = f"сбой: {exc}"
|
||||
if kind == "open" and self.position:
|
||||
self.state = "recover"
|
||||
journal("simulator", self.exchange, self.coin, kind, False, f"сбой: {exc}")
|
||||
if kind == "close":
|
||||
self._retry_close(arg)
|
||||
@@ -331,6 +387,12 @@ class FuturesMirror:
|
||||
def _watch(self) -> None:
|
||||
"""An open real position may be closed by the exchange itself (its TP / SL): then record it now.
|
||||
Every SYNC_S seconds (and right after a close) the trades are synced with the exchange's history."""
|
||||
if self.storage_error and self.position is None:
|
||||
with self.lock:
|
||||
self._save()
|
||||
if self.state == "recover":
|
||||
self._recover_open()
|
||||
return
|
||||
if (self.state in ("", "open") and time.time() - self.last_sync >= self.SYNC_S
|
||||
and (self.enabled() or self.exchange_trades is None)):
|
||||
self.sync()
|
||||
@@ -359,6 +421,15 @@ class FuturesMirror:
|
||||
|
||||
def _open(self) -> None:
|
||||
pos = self.position
|
||||
if pos is None or self.state != "opening":
|
||||
return
|
||||
with self.lock:
|
||||
pos["phase"] = "submitted"
|
||||
try:
|
||||
self._save() # must complete before an exchange request is allowed
|
||||
except (OSError, ValueError):
|
||||
pos["phase"] = "prepared" # no request was sent
|
||||
raise
|
||||
side = "buy" if pos["side"] == "LONG" else "sell"
|
||||
sign = 1 if side == "buy" else -1
|
||||
c = None
|
||||
@@ -374,23 +445,27 @@ class FuturesMirror:
|
||||
else:
|
||||
fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False)
|
||||
except live.LiveError as exc:
|
||||
if getattr(exc, "sent", False) and c is not None:
|
||||
# accepted, fill not confirmed: the exchange's position decides
|
||||
if getattr(exc, "sent", False):
|
||||
with self.lock:
|
||||
pos["order_in"] = exc.order_id
|
||||
self.state, self.problem = "recover", str(exc)
|
||||
self._save()
|
||||
try:
|
||||
held = abs(c.fut_position(self.symbol))
|
||||
held = c.fut_position(self.symbol)
|
||||
except live.LiveError:
|
||||
held = pos["coins"] # cannot tell: treat as open, the close is reduce-only
|
||||
if held > self.VERIFY_TOLERANCE:
|
||||
fill = live.Fill(held, pos["paper_entry"], 0.0, exc.order_id, exact=False)
|
||||
journal("simulator", self.exchange, self.coin, "open", False,
|
||||
f"{exc} — позиция на бирже есть ({held:g}), веду её", side=pos["side"])
|
||||
else:
|
||||
self._failed_open(f"{exc}; позиции на бирже нет")
|
||||
return
|
||||
if held * sign <= self.VERIFY_TOLERANCE:
|
||||
return
|
||||
fill = live.Fill(abs(held), pos["paper_entry"], 0.0, exc.order_id, exact=False)
|
||||
else:
|
||||
self._top_up_futures(c, str(exc), pos["coins"] * pos["paper_entry"])
|
||||
self._failed_open(str(exc))
|
||||
return
|
||||
# Persist the accepted fill before any additional network call (TP, fee sync, etc.).
|
||||
with self.lock:
|
||||
pos.update(phase="filled", coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd,
|
||||
exact=fill.exact, order_in=fill.order_id)
|
||||
self._save()
|
||||
# the exchange's real fee rate (it decides how far the TP has to be, and the paper model uses it too)
|
||||
fee_pct = fill.fee_usd / (fill.coins * fill.price) * 100 if fill.exact and fill.coins and fill.price else None
|
||||
if fee_pct:
|
||||
@@ -478,6 +553,10 @@ class FuturesMirror:
|
||||
self.on_failed_open(uid)
|
||||
|
||||
def _close(self, reason: str) -> None:
|
||||
if self.position and self.position.get("phase") in ("prepared", "submitted"):
|
||||
self.state = "recover"
|
||||
self._recover_open()
|
||||
return
|
||||
with self.lock:
|
||||
pos = self.position
|
||||
if pos is None or self.state == "":
|
||||
@@ -566,7 +645,7 @@ class FuturesMirror:
|
||||
t for t in self.trades if t.get("closed", 0) >= (self.coin_settings().get("since") or 0)]
|
||||
stats = trade_stats(trades)
|
||||
pos = dict(self.position) if self.position and self.state else None
|
||||
return {"open": 1 if pos else 0, "state": self.state, "problem": self.problem, "position": pos,
|
||||
return {"open": 1 if pos else 0, "state": self.state, "problem": self.storage_error or self.problem, "position": pos,
|
||||
**stats, "positions": [pos] if pos else [], "enabled": self.enabled(),
|
||||
"source": "биржа" if self.exchange_trades is not None else "программа",
|
||||
"synced": self.synced, "sync_error": self.sync_error, "since": self.coin_settings().get("since"),
|
||||
|
||||
Reference in new issue
Block a user