From ffe587787b99b2046680ce38e64663a202318ae0 Mon Sep 17 00:00:00 2001 From: Igor Zharov Date: Fri, 23 Oct 2026 20:48:18 +0300 Subject: [PATCH] =?UTF-8?q?`feat:=20=D0=BF=D1=80=D0=B8=D0=B1=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=B8=D1=82=D1=8C=20=D1=81=D0=B8=D0=BC=D1=83=D0=BB=D1=8F?= =?UTF-8?q?=D1=86=D0=B8=D1=8E=20=D0=BA=20=D1=80=D0=B5=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D0=BE=D0=B9=20=D1=82=D0=BE=D1=80=D0=B3=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=20=D0=B8=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B7=D0=B0=D0=B4=D0=B5=D1=80=D0=B6=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cross.py | 64 +++++++++++++++++++++++++++++-- paper_execution.py | 72 +++++++++++++++++++++++++++++++++++ scalp_paper.py | 2 + tests/test_cross_account.py | 8 +++- tests/test_paper_execution.py | 54 ++++++++++++++++++++++++++ web/app.js | 5 ++- web/help-data.js | 4 ++ web_sim.py | 18 ++++++++- 8 files changed, 220 insertions(+), 7 deletions(-) create mode 100644 paper_execution.py create mode 100644 tests/test_paper_execution.py diff --git a/cross.py b/cross.py index fe4944b..b4ba3c7 100644 --- a/cross.py +++ b/cross.py @@ -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 diff --git a/paper_execution.py b/paper_execution.py new file mode 100644 index 0000000..c5505d6 --- /dev/null +++ b/paper_execution.py @@ -0,0 +1,72 @@ +"""Delayed paper execution for the web leader simulator; never uses private APIs.""" +import inspect +import threading +import time + + +def install(engine): + trader = engine.paper + if getattr(trader, '_execution_installed', False): + return + trader._execution_installed = True + pending = set() + original_open, original_close = trader.ledger.open, trader.close + + def schedule(function, opening, args, kwargs): + values = inspect.signature(function).bind(*args, **kwargs) + values.apply_defaults() + data = values.arguments + pos = None if opening else (data['pos'] or trader.ledger.position) + if not opening and pos is None: + return + key = 'entry' if opening else pos.uid + if key in pending: + return + pending.add(key) + delay = trader.settings.simulation_entry_delay_ms if opening else trader.settings.simulation_exit_delay_ms + + def execute(): + with engine.lock: + pending.discard(key) + if engine.paper is not trader or engine.stopped.is_set(): + return + now = time.time() + bid, ask = engine.book.best() + if not bid or not ask or now - engine.last_follower > trader.settings.max_data_age_ms / 1000: + trader.message = 'Исполнение отложено: нет свежего стакана' + return + if opening: + if not trader.settings.enabled or engine.removing or trader.ledger.positions: + trader.message = 'Вход отменён: остановка или незавершённая позиция' + return + limit = float(engine.mirror.settings().get('max_ping_ms', 400) or 0) + ping = engine.mirror.ping() + if limit > 0 and ping is not None and ping > limit: + trader.message = 'Вход отменён: превышен допустимый пинг' + return + old = data['price'] + price = ask if data['side'] == 'LONG' else bid + import minorder + ps = trader.settings + exchange = {'bybit': 'Bybit', 'binance': 'Binance', 'mexc': 'MEXC'}.get(ps.follow_exchange, ps.follow_exchange) + rule = minorder.RULES.fut(exchange, ps.follow_ticker) + notional = data['notional_usd'] or ps.stake * ps.leverage + if rule is None or notional < max(rule.get('usd', 0), rule.get('coins', 0) * price): + trader.message = 'Вход отменён: неизвестен или не достигнут минимальный лот' + return + data['price'], data['now'], data['entry_mid'] = price, now, (bid + ask) / 2 + data['target'] *= price / old + if data['stop'] is not None: + data['stop'] *= price / old + function(**data) + elif pos in trader.ledger.positions: + data.update(price=bid if pos.side == 'LONG' else ask, now=now, pos=pos, utc=None, + fee_pct=trader.policy.taker) + function(**data) + + timer = threading.Timer(max(0, delay) / 1000, execute) + timer.daemon = True + timer.start() + + trader.ledger.open = lambda *a, **kw: schedule(original_open, True, a, kw) + trader.close = lambda *a, **kw: schedule(original_close, False, a, kw) diff --git a/scalp_paper.py b/scalp_paper.py index 9e5079a..99ecb60 100644 --- a/scalp_paper.py +++ b/scalp_paper.py @@ -54,6 +54,8 @@ MODES = {"simple": "Простая (вход по рынку, выход при @dataclass class PaperSettings: + simulation_entry_delay_ms: float = 600.0 + simulation_exit_delay_ms: float = 600.0 enabled: bool = True mode: str = "adaptive" data_source: str = "metascalp" # "metascalp" or "bybit" (direct public WebSocket, Bybit pairs only) diff --git a/tests/test_cross_account.py b/tests/test_cross_account.py index fb38d53..206fa62 100644 --- a/tests/test_cross_account.py +++ b/tests/test_cross_account.py @@ -51,7 +51,9 @@ class CrossAccountTests(unittest.TestCase): self.assertAlmostEqual(self.account.view()["balance"], 300 + net) def test_delayed_fill_charges_and_reserves_once_then_close_settles(self): - self.e.quote_now = mock.Mock() + self.e.quote_now = mock.Mock(return_value=(self.l.spot_bid, self.l.spot_ask, self.l.fut_bid, self.l.fut_ask, 0, 0)) + self.e._still_good = mock.Mock(return_value=self.l) + self.e.candidates = mock.Mock(return_value=[{"fits": True}]) with mock.patch.object(cross.threading, "Timer") as timer: self.assertTrue(self.enter()) self.assertEqual(self.e.positions, []) @@ -71,7 +73,9 @@ class CrossAccountTests(unittest.TestCase): self.assertAlmostEqual(self.account.view()["balance"], 300 + self.e.trades[0].net) def test_delayed_fill_rechecks_shared_cash_at_execution(self): - self.e.quote_now = mock.Mock() + self.e.quote_now = mock.Mock(return_value=(self.l.spot_bid, self.l.spot_ask, self.l.fut_bid, self.l.fut_ask, 0, 0)) + self.e._still_good = mock.Mock(return_value=self.l) + self.e.candidates = mock.Mock(return_value=[{"fits": True}]) with mock.patch.object(cross.threading, "Timer") as timer: self.assertTrue(self.enter()) self.account.commit("simulator:other", {}, cash_total=0, reserved=150) diff --git a/tests/test_paper_execution.py b/tests/test_paper_execution.py new file mode 100644 index 0000000..669ea40 --- /dev/null +++ b/tests/test_paper_execution.py @@ -0,0 +1,54 @@ +import threading +import time +import unittest +from types import SimpleNamespace as NS +from unittest.mock import Mock, patch +import paper_execution + + +class ExecutionTests(unittest.TestCase): + def setUp(self): + self.fills = [] + def enter(ticker, side, price, now, fee_pct, target, stop, entry_mid, + regime='', features=None, notional_usd=None): + self.fills.append((price, target)) + def close(price, now, reason, fee_pct, utc=None, pos=None): + self.fills.append(price) + settings = NS(simulation_entry_delay_ms=600, simulation_exit_delay_ms=800, + max_data_age_ms=2000, enabled=True, follow_exchange='bybit', + follow_ticker='TESTUSDT', stake=10, leverage=1) + self.trader = NS(settings=settings, ledger=NS(open=enter, positions=[]), close=close) + self.engine = NS(paper=self.trader, lock=threading.RLock(), stopped=threading.Event(), + last_follower=time.time(), book=NS(best=lambda: (109, 110)), removing=False, + mirror=NS(settings=lambda: {}, ping=lambda: 10)) + paper_execution.install(self.engine) + + def enqueue(self, timer): + self.trader.ledger.open('TEST', 'LONG', 100, time.time(), .05, 102, 99, 100) + self.assertEqual(timer.call_args.args[0], .6) + self.assertEqual(self.fills, []) + return timer.call_args.args[1] + + def test_execution_uses_new_quote_and_rebases_targets(self): + with patch('paper_execution.threading.Timer') as timer, patch('minorder.RULES.fut', return_value={'usd': 5}): + self.enqueue(timer)() + self.assertEqual(len(self.fills), 1) + self.assertEqual(self.fills[0][0], 110) + self.assertAlmostEqual(self.fills[0][1], 112.2) + + def test_stopped_or_stale_signal_never_spends(self): + with patch('paper_execution.threading.Timer') as timer: + callback = self.enqueue(timer) + self.trader.settings.enabled = False + callback() + self.assertEqual(self.fills, []) + self.trader.settings.enabled = True + callback = self.enqueue(timer) + self.engine.last_follower = 0 + callback() + self.assertEqual(self.fills, []) + + def test_missing_lot_blocks_entry(self): + with patch('paper_execution.threading.Timer') as timer, patch('minorder.RULES.fut', return_value=None): + self.enqueue(timer)() + self.assertEqual(self.fills, []) diff --git a/web/app.js b/web/app.js index 400ee4b..cc92cd9 100644 --- a/web/app.js +++ b/web/app.js @@ -6,6 +6,8 @@ const MAIN_FIELDS = [ ["auto_tp", "Авто тейк-профит по прогнозу", "check"], ["require_leader", "Входить, только если ведущая правда ведёт", "check"], ]; const MORE_FIELDS = [ + ["simulation_entry_delay_ms", "Задержка открытия в симуляции, мс"], + ["simulation_exit_delay_ms", "Задержка закрытия в симуляции, мс"], ["cooldown_ms", "Пауза после сделки, мс"], ["lead_threshold_pct", "Отставание для входа, %"], ["lead_window_ms", "Окно сравнения, мс"], ["vector_window_seconds", "Вектор за, с"], ["vector_min_move_pct", "Мин. движение, %"], ["auto_tp_share_pct", "Доля догоняния, %"], ["auto_tp_horizon_seconds", "Горизонт прогноза, с"], @@ -839,7 +841,8 @@ const CX_FIELDS = [ ["min_turnover", "Мин. оборот каждой ноги 24ч, $"], ["limit_hold_s", "Лимитный вход: ждать, с"], ["negative_funding_before_minutes", "При отрицательном funding не входить за, мин"], ["min_funding_pct", "Не входить, если funding ниже, %"], - ["simulation_execution_delay_ms", "Задержка исполнения в симуляции, мс"], + ["simulation_entry_delay_ms", "Задержка открытия в симуляции, мс"], + ["simulation_exit_delay_ms", "Задержка закрытия в симуляции, мс"], ["max_spread_pct", "Макс. спред каждой ноги, % (0 — нет)"], ["confirm_ms", "Подтверждение по стакану: пауза между 2 проверками, мс"], ["min_liq_pct", "Мин. запас до ликвидации шорта при входе, %"], diff --git a/web/help-data.js b/web/help-data.js index 6298739..c594f74 100644 --- a/web/help-data.js +++ b/web/help-data.js @@ -1,6 +1,8 @@ // Local reference content. Keys are checked against the controls in web_context.test.cjs. const HELP_SETTINGS = { sim: { + simulation_entry_delay_ms: "Пауза перед виртуальным входом: 600 мс по умолчанию, от 0 до 60000 мс. При исполнении проверяются свежая цена, остановка, занятость позиции, пинг, минимальный лот и виртуальные средства. TP/SL пересчитываются от цены исполнения.", + simulation_exit_delay_ms: "Пауза перед виртуальным закрытием: 600 мс по умолчанию. Исполнение по доступной свежей цене с тейкер-комиссией; при отсутствии цены позиция сохраняется. Это консервативная модель рыночного выхода, а не точная очередь биржевого лимитного TP.", mode: "Алгоритм виртуальных входов и выходов. Настройки применяются ко всем монетам кнопкой «Применить ко всем монетам». Описание каждого доступного режима — в разделе «Режимы».", stake: "Маржа одной позиции в долларах. Номинальный объём сделки = ставка × плечо. Для виртуального входа общий счёт резервирует маржу и должен покрывать комиссии.", leverage: "Множитель номинального объёма относительно ставки: при ставке 10 $ и плече 3 объём равен 30 $. Прибыль, убыток и комиссии считаются от объёма. Допустимо от 1 до 100.", @@ -35,6 +37,8 @@ const HELP_SETTINGS = { block_negative_funding: "Запрещает вход при отрицательном funding в указанное окно перед выплатой.", negative_funding_before_minutes: "Длительность окна перед выплатой funding в минутах. Применяется при включённом запрете отрицательного funding.", min_funding_pct: "Нижний порог funding в процентах за период выплаты. Ставка ниже порога блокирует вход независимо от окна.", + simulation_entry_delay_ms: "Пауза перед проверкой и исполнением виртуального входа, по умолчанию 600 мс. После неё стакан проверяется дважды с интервалом подтверждения; исчезнувший сигнал отменяет вход.", + simulation_exit_delay_ms: "Пауза перед виртуальным закрытием, по умолчанию 600 мс. После неё запрашиваются свежие цены; при ошибке позиция остаётся открытой.", simulation_execution_delay_ms: "Задержка виртуального входа и выхода в миллисекундах. Исполнение использует цены на момент окончания задержки; 0 отключает задержку.", amount: "Номинальная сумма одной ноги сделки, в долларах. Общий виртуальный счёт должен покрыть обе ноги, резерв и комиссии. Это не размер всего счёта.", min_net_pct: "Минимальная расчётная чистая прибыль для входа: превышение разницы над обычной минус запас выхода и комиссии обеих ног. Проценты от суммы одной ноги; фактический результат может отличаться.", diff --git a/web_sim.py b/web_sim.py index 5398be1..41d5fda 100644 --- a/web_sim.py +++ b/web_sim.py @@ -132,7 +132,7 @@ COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings) "vector_min_move_pct", "auto_tp", "auto_tp_share_pct", "auto_tp_learn", "auto_tp_horizon_seconds", "one_per_tick", "cut_loss", "cut_loss_ticks", "max_data_age_ms", "require_leader", "leader_min_edge", "auto_stop_pct", - "basis_window_seconds", + "basis_window_seconds", "simulation_entry_delay_ms", "simulation_exit_delay_ms", "basis_entry_z", "basis_exit_z", "basis_min_gap_pct"}] SERIES_STEP = 0.5 # chart sampling, s SERIES_KEEP = 1200 # 10 minutes @@ -207,6 +207,15 @@ def load_common() -> dict: def check_common(values: dict) -> tuple[dict, str]: """Cast and validate settings coming from the page.""" + import math + for name in ('simulation_entry_delay_ms', 'simulation_exit_delay_ms'): + if name in values: + try: + value = float(str(values[name]).replace(',', '.')) + if not math.isfinite(value) or not 0 <= value <= 60000: + raise ValueError() + except (ValueError, TypeError): + return {}, 'Задержка должна быть от 0 до 60000 мс' out = {} defaults = sp.PaperSettings() for k in COMMON_FIELDS: @@ -306,6 +315,9 @@ class Engine: self.paper.ledger.signal_only = self.signal_mode self.paper.ledger.hooks = [self.mirror.hook] if real_signals else [] self.paper.gate = self.mirror.gate if real_signals else None + if not real_signals and getattr(self, 'execution_live', False): + import paper_execution + paper_execution.install(self) def switch_real(self, enabled: bool) -> str: """Switch only while flat, using independent real-signal and paper ledgers.""" @@ -351,6 +363,8 @@ class Engine: # --- lifecycle --------------------------------------------------------------------------- def start(self) -> None: + self.execution_live = True + self._connect_trader() ps = self.paper.settings if ps.follow_exchange == "mexc": self.tick, size = sh.mexc_contract(ps.follow_ticker) @@ -448,6 +462,8 @@ class Engine: if self.paper.ledger.storage_error: self.close_error = self.paper.ledger.storage_error return f"Закрыто позиций: {closed}; ошибка: {self.paper.ledger.storage_error}" + if not closed and getattr(self.paper, '_execution_installed', False) and self.paper.ledger.positions: + return 'Запрос закрытия поставлен в очередь с заданной задержкой' return f"закрыто позиций: {closed}" def _auto_stop(self, now: float) -> None: