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

+115 -26
View File
@@ -8,14 +8,15 @@ whose real order did not go through is closed at once, so paper and real trades
Results (prices, fees) are the exchange's own fills; `exact` is False where the exchange did not report a figure.
- the tab-wide switch is in web_sim_data/real_simulator.json; it gates new trades only — an open real trade is
always closed with its paper twin;
- real positions are saved (web_sim_data/real_positions_<coin>.json); paper positions do not survive a restart, so
a saved real position is closed right after a restart («осиротевшая»);
- real positions are saved (web_sim_data/real_positions_<coin>.json); a saved real position is conservatively
closed right after a restart («осиротевшая»), independently of the restored paper account;
- every order and every error goes to web_sim_data/real_orders.jsonl (journal on the page).
"""
from __future__ import annotations
import json
from persistence import atomic_write_json
import queue
import threading
import time
@@ -107,7 +108,7 @@ def save_settings(values: dict) -> str:
if values.get("reset_stats"):
c["since"] = time.time()
DATA_DIR.mkdir(exist_ok=True)
SETTINGS_FILE.write_text(json.dumps(s), encoding="utf-8")
atomic_write_json(SETTINGS_FILE, s)
return ""
@@ -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,11 +314,26 @@ 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", "закрыта в симуляторе"))
def request_close(self, reason: str = "удаление подключения") -> None:
"""Also close a recovered real position whose paper twin no longer exists."""
with self.lock:
if self.position and self.state not in ("recover", "blocked"):
self.jobs.put(("close", reason))
def ready_to_remove(self) -> bool:
with self.lock:
return self.position is None and self.state == "" and not self.storage_error and self.jobs.empty()
# --- worker ------------------------------------------------------------------------------------------------
WATCH_S = 1.0 # while a real position is open: how often to ask the exchange whether TP/SL closed it
@@ -286,11 +348,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 +397,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 +431,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 +455,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 +563,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 +655,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"),