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-23 20:48:18 +03:00
1 parent dbc044fc49
commit ffe587787b
8 files changed
+220 -7

No files matched your search

+61 -3
View File
@@ -176,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
@@ -398,6 +400,15 @@ 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)."""
@@ -439,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
@@ -718,6 +730,15 @@ class CrossEngine:
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):
@@ -1172,17 +1193,18 @@ class CrossEngine:
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:
return self._paper_close(uid, reason)
else:
@@ -1192,6 +1214,22 @@ class CrossEngine:
return True
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)
@@ -1206,8 +1244,22 @@ class CrossEngine:
return self.save()
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):
@@ -1234,6 +1286,8 @@ class CrossEngine:
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):
@@ -1251,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:
@@ -1269,6 +1325,8 @@ class CrossEngine:
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