From 85425483c0b1831cea1ff08158246aa14ff12db1 Mon Sep 17 00:00:00 2001 From: listik Date: Fri, 23 Oct 2026 20:49:12 +0300 Subject: [PATCH] 1 --- .github/workflows/tests.yml | 25 + .gitignore | 23 + README.md | 55 + algo_hunter.py | 70 +- cross.py | 580 ++++++++-- desktop_chart.py | 201 ++++ desktop_models.py | 74 ++ docs/reliability.md | 176 +++ historical_backtest.py | 61 +- lead_connections_removed.json | 9 + live.py | 9 +- main.py | 279 +---- paper_execution.py | 72 ++ pending_removals.py | 45 + persistence.py | 27 + real_mirror.py | 141 ++- request_security.py | 43 + requirements.txt | 5 +- run_web_sim.bat | 10 +- runtime_lock.py | 45 + scalp_paper.py | 261 ++++- scripts/run_tests.py | 34 + server_control.ps1 | 16 +- setup.ps1 | 14 +- tests/test_account_invariants.py | 83 ++ tests/test_backtest.py | 42 + tests/test_connections_remove.py | 9 +- tests/test_cross_account.py | 217 ++++ tests/test_cross_execution_safety.py | 203 ++++ tests/test_cross_recovery.py | 95 ++ tests/test_live_uncertainty.py | 30 + tests/test_mirror_recovery.py | 96 ++ tests/test_paper_execution.py | 54 + tests/test_paper_recovery_account.py | 224 ++++ tests/test_persistence.py | 29 + tests/test_removal_recovery.py | 81 ++ tests/test_request_security.py | 83 ++ tests/test_virtual_account.py | 173 +++ tests/test_web_account.py | 445 ++++++++ tests/test_web_proxy.py | 2 +- tests/test_web_sim.py | 7 + tests/web_context.test.cjs | 320 ++++++ virtual_account.py | 245 +++++ web/app.css | 179 +++ web/app.js | 1499 ++++++++++++++++++++++++++ web/help-data.js | 148 +++ web/help.js | 78 ++ web_proxy.py | 5 +- web_sim.html | 1362 +---------------------- web_sim.py | 338 +++++- 50 files changed, 6468 insertions(+), 1854 deletions(-) create mode 100644 .github/workflows/tests.yml create mode 100644 .gitignore create mode 100644 desktop_chart.py create mode 100644 desktop_models.py create mode 100644 docs/reliability.md create mode 100644 lead_connections_removed.json create mode 100644 paper_execution.py create mode 100644 pending_removals.py create mode 100644 persistence.py create mode 100644 request_security.py create mode 100644 runtime_lock.py create mode 100644 scripts/run_tests.py create mode 100644 tests/test_account_invariants.py create mode 100644 tests/test_cross_account.py create mode 100644 tests/test_cross_execution_safety.py create mode 100644 tests/test_cross_recovery.py create mode 100644 tests/test_live_uncertainty.py create mode 100644 tests/test_mirror_recovery.py create mode 100644 tests/test_paper_execution.py create mode 100644 tests/test_paper_recovery_account.py create mode 100644 tests/test_persistence.py create mode 100644 tests/test_removal_recovery.py create mode 100644 tests/test_request_security.py create mode 100644 tests/test_virtual_account.py create mode 100644 tests/test_web_account.py create mode 100644 tests/web_context.test.cjs create mode 100644 virtual_account.py create mode 100644 web/app.css create mode 100644 web/app.js create mode 100644 web/help-data.js create mode 100644 web/help.js diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..ff2ddd5 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,25 @@ +name: Offline regression tests +on: + push: + pull_request: +permissions: + contents: read +jobs: + windows: + runs-on: windows-latest + strategy: + matrix: + python-version: ['3.11', '3.12', '3.13'] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - uses: actions/setup-node@v4 + with: + node-version: '22' + - run: python -m pip install -r requirements.txt + - run: python -B scripts/run_tests.py + - run: node --test tests/web_context.test.cjs + - run: python -B -c "import main, websocket, numpy" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..48496e9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +__pycache__/ +*.py[cod] +.venv/ +*.log +*.tmp +web_sim_data/ +scalp_recordings/ +historical_reports/ +*.sqlite3* +settings.json +account_state.json +*credentials*.json +*credentials*.bin +*keys*.bin +lead_connections.json +lead_paper_state.json +lead_paper_trades.csv +scalp_hint_journal.csv +scalp_paper_state.json +scalp_paper_trades.csv +meme_matcher/autoscan_state.json +meme_matcher/autoscan_history.csv +meme_matcher/autoscan_config.json diff --git a/README.md b/README.md index 07b9642..42d6e28 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ ### Установка вручную через PowerShell +Python 3.11+; dependencies are pinned in `requirements.txt`. Recovery semantics, module layout and offline tests: [docs/reliability.md](docs/reliability.md). + ```powershell cd C:\Crypto_Scam py -3 -m venv .venv @@ -88,7 +90,52 @@ py -3 -m venv .venv `scalp_paper.py` и `algo_hunter.py` содержат экспериментальные модели по стакану, imbalance, микроцене и повторяющимся заявкам. Они предназначены для dry-run и анализа: видимый агрегированный стакан не позволяет надёжно доказать наличие конкретного маркет-мейкера или реальную очередь исполнения. +<<<<<<< HEAD +**Web interface** (`py -3 web_sim.py` or `run_web_sim.bat` → [local page](http://127.0.0.1:8765), opens in the +browser): every coin has its own feeds, trade history and Start/Stop. A new coin starts stopped; Stop forbids +new entries while existing positions remain managed. All paper coins in «Симулятор» and «Арбитраж → Симуляция» +use **one virtual account**, persisted in `web_sim_data/virtual_account.json`. The Tk window +(`py -3 scalp_hint.py`) and the main desktop application keep their separate accounts. + +The «Общий виртуальный счёт» panel shows balance, equity, reserved capital and free capital. Enter a positive +amount and click «Пополнить» to add it or «Списать» to subtract it; the journal shows recent operations newest +first. These are virtual adjustments, not exchange transfers, and do not change the recorded trading result. +Free capital is `max(0, min(balance, equity) - reserved)`: unrealized profits cannot fund another entry, while +unrealized losses reduce the available amount. Every paper entry must fit the shared capital limit, including +its reserve and fees. Withdrawals cannot exceed free capital and are refused if an open position's valuation +is older than 30 seconds. Deposits remain available with a working connection. The initial deposit comes once +from the old common budget (default 300 $); initial balances of individual coins are not added together. + +Open paper positions, their reserved capital and strategy exit state survive a restart. The shared account +snapshot is authoritative for the attached coin and paper-arbitrage engines; old closed trades remain available +as history. Restored valuations remain stale until fresh quotes arrive. «Сбросить статистику» does not replenish +the virtual account and is refused while the selected engine has open positions or unfinished real execution. +Changing a coin between simulation and real trading also requires both modes to be free of open positions and +unfinished orders. Real mode uses a **separate private signal ledger**, not the common virtual wallet: virtual +top-ups, withdrawals and paper profits cannot change real order sizing or allow real entries. Exchange balances +and the real execution gate determine whether those orders can be sent. + +The top status bar distinguishes the selected mode from connection health. A failed initial request is retried +by the read polling loop; missing or stale server data disables commands until reconnection. Submitted trading +commands are never automatically retried. The separate «Справка» button opens a searchable reference covering +terms, every exposed setting, strategy modes, account controls, API keys, the scanner and the budget calculator. + +Common coin settings are applied with «Применить ко всем монетам» and stored in `web_sim_data/settings.json`; +the first start copies the Tk window's settings. The former editable per-coin budget is replaced by the shared +account controls. Arbitrage simulation and real trading retain separate settings and unsaved drafts when +switching between them in the current browser page. Coin tiles show the trading status, open positions, price, +result and win rate. The centre shows both prices as percentage changes over 1/5/10 minutes, entry/exit markers, +the selected coin's statistics, Start/Stop, «Закрыть все позиции» and the trade table. Open positions appear in +yellow with a close button; closed trades follow newest first. + +The last tile «+» opens the **scanner panel**: start/stop of `meme_matcher/autoscan.py`, its log and checked coins. +«+ Добавить» adds a supported pool/futures pair stopped and ready to test. «Добавлять найденные автоматически» +allows automatic additions (off by default; `meme_matcher/autoscan_config.json`); new connections appear within +30 seconds. Removing a pair first stops new entries and requests closing its exposure. If execution or recovery +is unfinished, the connection stays available for management; the removal intent survives restart. +======= ## Реальная торговля и API-ключи +>>>>>>> main Используйте реальную торговлю только после проверки в симуляции и на Testnet. @@ -102,7 +149,15 @@ py -3 -m venv .venv В проекте предусмотрены отдельные состояния виртуального и реального счёта. Они не смешиваются. Для реального режима учитывайте funding, проскальзывание, минимальный размер ордера, задержку сети и риск ликвидации при усреднении или плече. +<<<<<<< HEAD +**Local proxy with a VPN on**: `run_web_sim.bat` starts the engine on `127.0.0.1:8766` +(`python.exe`) and the page proxy on `127.0.0.1:8765` (`pythonw.exe`). The page remains local even when +`pythonw.exe` is excluded from the VPN. Both processes validate the original local Host and browser Origin; +POST commands require the page's `X-Sim` header. The app is not configured for public internet hosting. +`py -3 web_sim.py` serves the page directly on `127.0.0.1:8765`. +======= ## VPN, внешний доступ и безопасность +>>>>>>> main - Если биржи не отдают цены, проверьте VPN и доступ к публичным API. - По умолчанию страница доступна только локально через `127.0.0.1`; это безопаснее, чем открывать её в интернет. diff --git a/algo_hunter.py b/algo_hunter.py index 5fa90e9..37001fd 100644 --- a/algo_hunter.py +++ b/algo_hunter.py @@ -527,6 +527,38 @@ class AlgoHunterPolicy: self.status_reason = "" # --- helpers ------------------------------------------------------------------------ + def export_state(self) -> dict: + return {"cfg": asdict(self.cfg), "filled_at": self.filled_at, "stop": self.stop, + "target": self.target, "tick": self.tick, "ticker": self.ticker, + "entry_order": asdict(self.entry_order) if self.entry_order else None, + "stats": dict(self.stats), "guard": { + name: getattr(self.guard, name) for name in + ("day", "daily_pnl", "losses", "pause_until", "last_exit", "disabled_reason")}, + "trade_times": list(self.guard.trade_times)} + + def restore_state(self, state: dict, position=None) -> None: + if state.get("cfg"): + self.cfg = AlgoHunterConfig(**state["cfg"]) + self.detector.cfg = self.tracker.cfg = self.guard.cfg = self.cfg + for name in ("filled_at", "stop", "target", "tick", "ticker"): + if name in state: + setattr(self, name, state[name]) + self.stats.update(state.get("stats", {})) + for name, value in state.get("guard", {}).items(): + if name in ("day", "daily_pnl", "losses", "pause_until", "last_exit", "disabled_reason"): + setattr(self.guard, name, value) + self.guard.trade_times = deque(state.get("trade_times", [])) + row = state.get("entry_order") + if row is not None and position is not None: + row = dict(row) + row["signature"] = AlgoSignature(**row["signature"]) + self.entry_order = HunterOrder(**row) + if position is not None: + # The persisted position is authoritative even if the last policy checkpoint was interrupted. + self.ticker, self.filled_at = position.ticker, position.opened + self.target = position.target + self.stop = position.stop if position.stop is not None else self.stop + def _latency(self, trader) -> float | None: """Effective delay of our view of the book: measured data latency, or the source cadence at least.""" measured = getattr(trader, "data_latency_ms", None) @@ -669,6 +701,9 @@ class AlgoHunterPolicy: self.status_reason = "волатильность за 1 с выше порога" return None notional = self.s.stake * self.s.leverage + if trader.ledger.account is not None and trader.ledger.available < self.s.stake: + self.status_reason = "Недостаточно свободных виртуальных средств" + return None allowed, reason = self.guard.allow(now, notional, self._latency(trader)) if not allowed: if reason != self.warned: @@ -767,13 +802,14 @@ class AlgoHunterPolicy: long = order.side == "LONG" hits_us = (trade.side == "Sell") if long else (trade.side == "Buy") if (trade.price < order.price) if long else (trade.price > order.price): - self._fill(trader, trade.ts) + self._fill(trader, trade.ts, trade.size) elif hits_us and abs(trade.price - order.price) < self.tick / 2: consumed = min(order.ahead, trade.size) order.ahead -= consumed order.algo_ahead = max(0.0, order.algo_ahead - consumed) - if trade.size > consumed or order.ahead <= 0: - self._fill(trader, trade.ts) + available = max(0.0, trade.size - consumed) + if available > 0: + self._fill(trader, trade.ts, available) return pos = trader.ledger.position if pos is None: @@ -790,6 +826,7 @@ class AlgoHunterPolicy: if self.cfg.trailing and (trade.price >= pos.entry + self.cfg.tp_partial_ticks * self.tick if long else trade.price <= pos.entry - self.cfg.tp_partial_ticks * self.tick): self.stop = max(self.stop, pos.entry) if long else min(self.stop, pos.entry) + pos.stop = self.stop if (trade.price <= self.stop) if long else (trade.price >= self.stop): slip = self.tick self._close(trader, self.stop - slip if long else self.stop + slip, trade.ts, @@ -797,16 +834,26 @@ class AlgoHunterPolicy: elif (trade.price > self.target) if long else (trade.price < self.target): self._close(trader, self.target, trade.ts, "цель", sh.MAKER_FEE_PCT) - def _fill(self, trader, now: float) -> None: + def _fill(self, trader, now: float, available_usd: float | None = None) -> None: + """Fill only observed executable volume; cancel the unfilled remainder after a partial fill.""" order = self.order + filled_usd = min(order.size_usd, available_usd) if available_usd is not None else order.size_usd + if filled_usd <= 0: + return self.order = None long = order.side == "LONG" - trader.ledger.open(self.ticker, order.side, order.price, now, sh.MAKER_FEE_PCT, 0.0, None, order.price, - order.scenario) + target = order.price + (1 if long else -1) * self.cfg.tp_ticks * self.tick + stop = order.price - (1 if long else -1) * self.cfg.sl_ticks * self.tick + pos = trader.ledger.open(self.ticker, order.side, order.price, now, sh.MAKER_FEE_PCT, + target, stop, order.price, order.scenario, notional_usd=filled_usd) + if pos is None: + trader.message = trader.ledger.storage_error + self.status_reason = trader.message + return + order.size_usd = filled_usd self.entry_order = order self.filled_at = now - self.target = order.price + (1 if long else -1) * self.cfg.tp_ticks * self.tick - self.stop = order.price - (1 if long else -1) * self.cfg.sl_ticks * self.tick + self.target, self.stop = target, stop trader.ledger.position.target = self.target trader.ledger.position.stop = self.stop self.guard.on_entry(now) @@ -815,6 +862,7 @@ class AlgoHunterPolicy: self.stats["front_run"] += 1 trader.message = f"Algo Hunter: исполнена {order.side} {order.price:.10g} ({order.scenario})" self.log.info("fill %s %s %.10g front_run=%s", self.ticker, order.side, order.price, order.front_run) + trader.ledger.save() def _cancel(self, trader, now: float, reason: str, quiet: bool = False) -> None: if self.order is not None: @@ -828,7 +876,10 @@ class AlgoHunterPolicy: if pos is None: return order = self.entry_order + before = len(trader.ledger.trades) trader.close(price, now, reason, fee_pct) + if len(trader.ledger.trades) == before: + return trade = trader.ledger.trades[-1] pnl_ticks = (price - pos.entry) / self.tick * (1 if pos.side == "LONG" else -1) self.stats["pnl_ticks"] += pnl_ticks @@ -855,6 +906,7 @@ class AlgoHunterPolicy: except OSError: pass self.entry_order = None + trader.ledger.save() def rearm(self) -> None: """Switch the mode back on after an 'algo adapted' shutdown (user pressed Apply, or a new ticker).""" @@ -874,6 +926,8 @@ class AlgoHunterPolicy: out.append("тестовые сделки выключены") if self.guard.disabled_reason: out.append(self.guard.disabled_reason) + if trader.ledger.account is not None and trader.ledger.available < self.s.stake: + out.append("Недостаточно свободных виртуальных средств") sig = self.sig n = len(sig.signals) if sig else 0 if cfg.fallback: diff --git a/cross.py b/cross.py index 0154579..b4ba3c7 100644 --- a/cross.py +++ b/cross.py @@ -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 @@ -175,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 @@ -217,6 +220,9 @@ class CrossPosition: entry_signal: list = field(default_factory=list) # A ask, B bid confirmed right before the entry orders exit_signal: list = field(default_factory=list) # A bid, B ask when the close was decided exit_since: float = 0.0 # when the gap last came back to the usual level (0 = it is not there now) + close_buy: dict = field(default_factory=dict) # durable spot-stock repurchase; never replay an unknown order + paper_reserve: float = 0.0 # collateral fixed at entry/import; later settings only affect new positions + paper_unrealized: float | None = None # last observed gross PnL minus exit fees; retained when a venue disappears @property def kind(self) -> str: @@ -394,14 +400,27 @@ 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).""" mode = "cross" def __init__(self, data_dir: Path = DATA_DIR, start: bool = True, real: bool = False, - leader: "CrossEngine | None" = None) -> None: + leader: "CrossEngine | None" = None, account=None) -> None: self.is_real = real + self.account = account if not real else None + self.account_error = "" + self.cash_total = 0.0 + self._account_initializing = True self.key = "cross_real" if real else "cross" self.file = data_dir / ("basis_cross_real.json" if real else "basis_cross.json") self.followers: list[CrossEngine] = [] @@ -431,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 @@ -459,6 +479,22 @@ class CrossEngine: self.usual, self.seen_since, self.last_seen = leader.usual, leader.seen_since, leader.last_seen self.innovation = leader.innovation leader.followers.append(self) + self._account_initializing = False + if self.account is not None and not self.account_error: + from virtual_account import AccountError + try: + registered = self.account.restore("cross") + if registered is None: + unrealized = self._unrealized() + self.account.commit("cross", self._state(), cash_total=self.cash_total, + reserved=self._reserved(), unrealized=unrealized, + allow_existing=True, event="Подключение бумажного арбитража") + elif self._state() != registered: + # Newly discovered legacy venues must reserve their exposure before any worker starts. + self.save(event="Арбитраж: импорт сохранённых позиций") + except AccountError as exc: + self.account_error = str(exc) + self.settings.running = False if start: if leader is None: threading.Thread(target=self._loop, daemon=True).start() @@ -470,10 +506,23 @@ class CrossEngine: # --- persistence ----------------------------------------------------------------------------------------- def _load(self) -> None: + d = None + if self.account is not None: + from virtual_account import AccountError + try: + d = self.account.restore("cross") + except AccountError as exc: + self.account_error = str(exc) try: - d = json.loads(self.file.read_text(encoding="utf-8")) + if d is None: + d = json.loads(self.file.read_text(encoding="utf-8")) except (OSError, ValueError): return + self._load_state(d) + if self.account_error: + self.settings.running = False + + def _load_state(self, d: dict) -> None: known = {f.name for f in fields(CrossSettings)} for k, v in (d.get("settings") or {}).items(): if k in known: @@ -491,11 +540,16 @@ class CrossEngine: if v is not None: self.limits[ex] = int(v) self.positions = [CrossPosition(**p) for p in d.get("positions", [])] + for pos in self.positions: + if not pos.real and pos.paper_reserve <= 0: + pos.paper_reserve = self._position_reserve(pos) self.trades = [CrossTrade(**t) for t in d.get("trades", [])] self.next_uid = d.get("next_uid", 1) self.baseline = d.get("baseline") or {} self.recover = dict(d.get("pending") or {}) self.migrated = list(d.get("migrated") or []) + self.last_close = dict(d.get("last_close") or {}) + self.cash_total = float(d.get("cash_total", sum(p.funding - p.fees for p in self.positions if not p.real))) def _seed_from(self, paper_file: Path) -> None: """The real engine's first settings, fee table and limits: those of the simulation (stopped).""" @@ -551,7 +605,11 @@ class CrossEngine: sold_fees=p.get("sold_fees", 0.0), exact=p.get("exact", True), innovation=p.get("innovation", False)) self.next_uid += 1 + if not pos.real: + pos.paper_reserve = self._position_reserve(pos) self.positions.append(pos) + if self.account is not None: + self.cash_total += pos.funding - pos.fees moved.append(f"{p['base']} ({ex}{', реальная' if pos.real else ''})") for t in d.get("trades", []): if bool(t.get("real", False)) != self.is_real: @@ -595,17 +653,92 @@ class CrossEngine: except OSError: pass - def save(self) -> None: - self.file.parent.mkdir(exist_ok=True) + def _state(self) -> dict: + # Legacy/manual paper positions acquire their fixed reserve before the recovery snapshot is serialized. + if self.account is not None: + self._reserved() data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions], "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) + "pending": {**self.recover, **self.pending}, "last_close": self.last_close} + if self.account is not None: + data["cash_total"] = self.cash_total + return data + + def _position_reserve(self, pos: CrossPosition) -> float: + notional = pos.qty * pos.fut_entry + return pos.qty * pos.spot_entry + (notional if pos.ss else + max(notional * self.FUT_NEED, equity_for(self.settings.min_liq_pct, notional))) + + def _reserved(self) -> float: + total = 0.0 + for pos in self.positions: + if pos.real: + continue + if pos.paper_reserve <= 0: + pos.paper_reserve = self._position_reserve(pos) + total += pos.paper_reserve + return total + + def _unrealized(self) -> float: + total = 0.0 + for pos in self.positions: + if pos.real: + continue + link = self.links.get(pos.key) + if link is not None or pos.paper_unrealized is None: + bid, ask = (link.spot_bid, link.fut_ask) if link else (pos.spot_entry, pos.fut_entry) + _, _, _, net = close_result(pos, bid, ask, self.fees) + # entry fees/funding already changed cash; quote loss must survive outages/settings/restarts. + pos.paper_unrealized = net + pos.fees - pos.funding + total += pos.paper_unrealized + return total + + def _mark_account(self, snapshot_fresh: bool = False) -> None: + now = time.time() + if self.account is not None and all( + p.key in self.links and (snapshot_fresh or now - max(self.updated, self.fast_seen.get(p.key, 0)) <= 30) + for p in self.positions if not p.real): + self.account.mark("cross", self._unrealized()) + + def save(self, event: str = "") -> bool: + unrealized = self._unrealized() if self.account is not None else 0.0 + data = self._state() + shared = self.account is not None and not self._account_initializing + if shared: + from virtual_account import AccountError + try: + self.account.commit("cross", data, cash_total=self.cash_total, + reserved=self._reserved(), unrealized=unrealized, event=event) + except AccountError as exc: + try: + saved = self.account.restore("cross") + if saved is not None: + self._load_state(saved) + except AccountError: + pass + self.account_error = str(exc) + self.settings.running = False + return False + try: + self.file.parent.mkdir(exist_ok=True) + atomic_write_json(self.file, data) + except (OSError, ValueError): + if not shared: + raise + # The account owns the authoritative snapshot; a failed compatibility copy cannot undo a commit. + 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): @@ -641,7 +774,9 @@ class CrossEngine: self.save() return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под " f"одним тикером). Установлено {basis.HARD_MAX_GAP_PCT:g}%, остальное сохранено") - self.save() + if not self.save(): + return self.account_error + self.account_error = "" return "" def _set_fees(self, given) -> str: @@ -938,10 +1073,12 @@ class CrossEngine: def step(self, now: float) -> None: s = self.settings + self._mark_account(snapshot_fresh=True) 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: @@ -951,11 +1088,12 @@ 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 or self.waiting_baseline(now)) + real_busy = s.real and (self.opening or self.pending or self.recover + or now < self.real_pause_until or self.waiting_baseline(now)) 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: - self.save() + self.save(event="Арбитраж: обновление позиций и funding") BASELINE_WAIT_S = 60.0 @@ -977,8 +1115,8 @@ 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 - or self.waiting_baseline(now))): + if s.running and not (s.real and (self.opening or self.pending or self.recover + or now < self.real_pause_until or self.waiting_baseline(now))): if self._entries(now, rows): self.save() @@ -997,10 +1135,18 @@ class CrossEngine: if not pos.real and pos.uid in self.paper_closing: continue l = self.links.get(pos.key) + # Once a real unwind has started it must not depend on a fresh listing or another exit signal. + if pos.real and pos.closing and pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + self.jobs.put(("close", pos.uid, "завершение начатого закрытия")) + continue if l is None: continue while pos.next_funding and now >= pos.next_funding: - pos.funding += pos.qty * (l.fut_bid + l.fut_ask) / 2 * l.funding # the short receives positive + funding = pos.qty * (l.fut_bid + l.fut_ask) / 2 * l.funding + pos.funding += funding # the short receives positive funding + if self.account is not None and not pos.real: + self.cash_total += funding step = l.interval_h * 3600 pos.next_funding += step changed = True @@ -1043,48 +1189,85 @@ class CrossEngine: else: if self._schedule_paper_close(pos.uid, reason): changed = True + elif self.account_error: + 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: - self._paper_close(uid, reason) + return self._paper_close(uid, reason) else: timer = threading.Timer(delay, self._paper_close, args=(uid, reason)) timer.daemon = True timer.start() return True - def _paper_close(self, uid: int, reason: str) -> None: + 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) if pos is None: - return + return False l = self.links.get(pos.key) if l is None: - return - self._close(pos, l, time.time(), reason) - self.save() + return False + now = time.time() + if not self._close(pos, l, now, reason): + return False + return self.save() - def _paper_open(self, base: str, key: str, usual: float, amount: float, signal_time: float) -> None: + 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): - return + return False l = self.links.get(key) - if l is None or l.spot_ask <= 0 or l.fut_bid <= 0: - return - now = time.time() + if l is None or l.spot_ask <= 0 or l.fut_bid <= 0 or self.full(l): + return False + now = time.time() if self._paper_delay() > 0 else signal_time qty = amount / l.spot_ask fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \ + qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100 @@ -1094,12 +1277,21 @@ class CrossEngine: self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, qty, l.spot_ask, l.fut_bid, l.entry_gap, usual, fee_in, 0.0 if l.ss else (now // step + 1) * step, innovation=l.innovation, liq_price=liq, liq_calc=liq, liq_src="" if l.ss else "расчёт", ss=l.ss)) + self.positions[-1].paper_reserve = self._position_reserve(self.positions[-1]) self.next_uid += 1 - self.save() + if self.account is not None: + self.cash_total -= fee_in + return self.save(event=f"Арбитраж: вход {base}") 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): + return False changed = False busy = {p.base for p in self.positions} | self.opening | self.paper_opening best: dict[str, dict] = {} @@ -1113,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: @@ -1124,12 +1318,15 @@ class CrossEngine: self.paper_opening.add(l.base) delay = self._paper_delay() if delay <= 0: - self._paper_open(l.base, l.key, r["usual"], s.amount, now) + if not self._paper_open(l.base, l.key, r["usual"], s.amount, now): + break else: timer = threading.Timer(delay, self._paper_open, 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 @@ -1172,8 +1369,9 @@ class CrossEngine: for k in fresh: self.fast_seen[k] = now self.fast_ms = int((now - start) * 1000) + self._mark_account() if self._check_exits(now): - self.save() + self.save(event="Арбитраж: обновление позиций и funding") time.sleep(max(0.05, self.FAST_S - (time.time() - start))) # --- hot watch: links already in profit on paper, priced every HOT_S so an entry point is not missed --------- @@ -1239,7 +1437,7 @@ class CrossEngine: e.hot_step(done or keys, now) time.sleep(max(0.05, self.HOT_S - (time.time() - start))) - def _close(self, pos: CrossPosition, l: Link, now: float, reason: str) -> None: + def _close(self, pos: CrossPosition, l: Link, now: float, reason: str) -> bool: spot_pnl, fut_pnl, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees) self.trades.append(CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty, pos.spot_entry, l.spot_bid, pos.fut_entry, l.fut_ask, pos.entry_gap, l.exit_gap, @@ -1247,6 +1445,10 @@ class CrossEngine: pos.qty * pos.spot_entry, kind=pos.kind)) self.positions.remove(pos) self.last_close[pos.base] = now + if self.account is not None: + self.cash_total += net + pos.fees - pos.funding + return self.save(event=f"Арбитраж: закрытие {pos.base}") + return True def close(self, uid: int | None) -> str: with self.lock: @@ -1264,18 +1466,24 @@ class CrossEngine: l = self.links.get(pos.key) if l is None: continue - self._schedule_paper_close(pos.uid, "вручную") - n += 1 - self.save() + if self._schedule_paper_close(pos.uid, "вручную"): + n += 1 + elif self.account_error: + return self.account_error + if not self.save(): + return self.account_error return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "") def reset(self) -> str: with self.lock: if any(p.real for p in self.positions): return "есть открытые реальные позиции — сначала закройте их" + if self.account is not None and self.positions: + return "есть открытые бумажные позиции — сначала закройте их, затем сбросьте статистику" self.positions, self.trades, self.last_close = [], [], {} self.baseline = {"time": time.time(), "total": None, "by_ex": {}} if self.settings.real else {} - self.save() + if not self.save(): + return self.account_error return "статистика сброшена" # --- real orders (worker thread; never under the engine lock while waiting for an exchange) ------------------ @@ -1309,8 +1517,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: @@ -1370,10 +1661,11 @@ class CrossEngine: with self.lock: # last check right before money is spent held = [x.base for x in self.positions if x.real] - if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l): + if (l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l) + or any(p.real and p.closing for p in self.positions)): 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)) @@ -1413,14 +1705,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 @@ -1432,25 +1731,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 @@ -1462,6 +1755,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() @@ -1469,6 +1767,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) @@ -1480,25 +1779,24 @@ 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: free = 0.0 held = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100) + mismatch = shorted > held + max(1e-12, shorted * 1e-8) with self.lock: step = l.interval_h * 3600 now = time.time() @@ -1511,9 +1809,18 @@ class CrossEngine: entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact], [l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]]) + if mismatch: + # Persist the unwind before any close request. A restart must never adopt an uncovered short. + pos.closing = "hedge_mismatch" + pos.error = f"частичный хедж: спот {held:g}, шорт {shorted:g}; закрываю обе ноги" self.next_uid += 1 self.positions.append(pos) + self.pending.pop(l.base, None) self.save() + if mismatch: + self._journal(l.base, "open", False, pos.error) + self._real_close(pos.uid, "частичный хедж") + return 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}%), " f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount) @@ -1590,10 +1897,11 @@ class CrossEngine: return with self.lock: held = [x.base for x in self.positions if x.real] - if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l): + if (l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l) + or any(p.real and p.closing for p in self.positions)): 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: @@ -1607,10 +1915,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() @@ -1626,6 +1936,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: @@ -1651,6 +1963,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}% " @@ -1680,6 +1993,62 @@ class CrossEngine: f"(+{(liq / pos.fut_entry - 1) * 100:.0f}% от входа), расчёт {pos.liq_calc:.10g} — " f"расхождение {diff:+.1f}%") + def _restore_stock(self, pos: CrossPosition, cb) -> None: + """Buy B's stock once, and release A only after a confirmed fill and the restored balance. + + Spot clients have no common order-status API. An unknown submission therefore remains durable and + requires manual reconciliation: a balance change alone cannot distinguish our order from another trade. + """ + import live + intent = pos.close_buy + if not intent: + l = self.links.get(pos.key) + ask = l.fut_ask if l else pos.fut_entry + usdt = pos.qty * ask * (1 + spot_fee(pos.fut_ex, self.fees) / 100) * 1.003 + before = cb.spot_free(pos.base) + with self.lock: + old_closing = pos.closing + pos.close_buy = {"phase": "submitted", "before": before, "usdt": usdt, + "required": pos.qty, "time": time.time()} + pos.closing = "spot_buy_submitted" + try: + self.save() # no buy unless its durable intent is on disk + except Exception: + pos.close_buy, pos.closing = {}, old_closing + raise + try: + back = cb.spot_buy(pos.base, usdt) + except live.LiveError as exc: + with self.lock: + if exc.sent: + pos.close_buy.update(phase="unknown", order_id=exc.order_id) + else: # certainly unsent: a later attempt is safe + pos.close_buy = {} + self.save() + raise + with self.lock: + pos.close_buy.update(phase="confirmed", fill=asdict(back)) + self.save() + intent = pos.close_buy + if intent.get("phase") != "confirmed": + raise live.LiveError("результат выкупа спота неизвестен; требуется ручная сверка ордера, " + "повторная покупка заблокирована") + back = live.Fill(**intent["fill"]) + required = float(intent["required"]) + restored = cb.spot_free(pos.base) - float(intent["before"]) + tolerance = max(1e-12, required * 1e-8) + if back.coins + tolerance < required: + raise live.LiveError(f"частичный выкуп спота: исполнено {back.coins:g} из {required:g}; " + "требуется ручная сверка, повторная покупка заблокирована") + if restored + tolerance < required: + raise live.LiveError(f"запас спота ещё не восстановлен: получено {max(0.0, restored):g} " + f"из {required:g}; проверяю баланс без повторного ордера") + with self.lock: + pos.fut_exit, pos.exit_fees, pos.closing = back.price, back.fee_usd, "fut_done" + pos.exact = pos.exact and back.exact + pos.fills.append([pos.fut_ex, "spot", back.fee_usd, back.coins * back.price, back.exact]) + self.save() + def _real_close(self, uid: int, reason: str) -> None: """Buy the short back on B (reduce-only), make sure B shows no short left, then sell the coins on A.""" import live @@ -1691,7 +2060,7 @@ class CrossEngine: # Refresh both executable sides immediately before the first close order. The fast watcher normally # updates every 250 ms, but its previous snapshot may have been taken before the close job reached here. # A normal convergence close is postponed when the current executable prices are already losing after fees. - if reason != "вручную" and "стоп:" not in reason and "ликвидац" not in reason: + if not pos.closing and reason != "вручную" and "стоп:" not in reason and "ликвидац" not in reason: try: l0 = self.links.get(pos.key) if l0 is not None: @@ -1727,23 +2096,8 @@ class CrossEngine: try: ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex) if pos.ss and pos.closing != "fut_done": - # spot–spot: buy the coins sold on B back (the stock there is restored), a little over for the fee stage = f"выкуп монет на споте {pos.fut_ex}" - l = self.links.get(pos.key) - ask_b = l.fut_ask if l else pos.fut_entry - usdt = pos.qty * ask_b * (1 + spot_fee(pos.fut_ex, self.fees) / 100) * 1.003 - try: - back = cb.spot_buy(pos.base, usdt) - price, fee, exact = back.price, back.fee_usd, back.exact - except live.LiveError as exc: - if not getattr(exc, "sent", False): - raise - price, fee, exact = ask_b, usdt * spot_fee(pos.fut_ex, self.fees) / 100, False - with self.lock: - pos.fut_exit, pos.exit_fees, pos.closing = price, fee, "fut_done" - pos.exact = pos.exact and exact - pos.fills.append([pos.fut_ex, "spot", fee, usdt, exact]) - self.save() + self._restore_stock(pos, cb) if pos.closing != "fut_done": fut_coins, fut_price, fee, exact = 0.0, 0.0, 0.0, True if pos.qty > 0: @@ -1871,39 +2225,79 @@ 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) short = max(0.0, -cb.fut_position(l.fut_symbol)) - coins = min(ca.spot_free(l.base), float(info.get("coins") or 0) * 1.05) + bought = info.get("buy") or {} + cap = float(bought.get("coins") or info.get("coins") or 0) + coins = min(ca.spot_free(l.base), cap if bought else cap * 1.05) except live.LiveError as exc: with self.lock: self.recover[base] = info # tried again on the next cycle 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: now = time.time() step = l.interval_h * 3600 pos = CrossPosition(self.next_uid, base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, short, - l.spot_ask, l.fut_bid if short else 0.0, l.entry_gap, float(info.get("usual") or 0.0), - 0.0, (now // step + 1) * step, real=True, spot_qty=coins, exact=False, + float(bought.get("price") or l.spot_ask), + float(info.get("fut_price") or l.fut_bid) if short else 0.0, + l.entry_gap, float(info.get("usual") or 0.0), + float(bought.get("fee_usd") or 0) + float(info.get("fut_fee") or 0), + (now // step + 1) * step, real=True, spot_qty=coins, exact=False, innovation=l.innovation, error="подхвачено после перезапуска — цены оценочные") - if short <= 0 or coins * l.spot_bid < 1.0: # one leg only: close what there is at once - pos.retry_at, pos.usual = 0.0, 1e9 + unwind = short <= 0 or short > coins + max(1e-12, short * 1e-8) + if unwind: # one leg / partial hedge: close both legs immediately + pos.retry_at, pos.closing = 0.0, "hedge_mismatch" + pos.error = f"после перезапуска: неполный хедж (спот {coins:g}, шорт {short:g})" 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}; ведётся программой") + if unwind: + self._real_close(pos.uid, "восстановление частичного хеджа") # --- balances -------------------------------------------------------------------------------------------- def coins_value(self, exchange: str) -> float: @@ -2061,11 +2455,19 @@ class CrossEngine: "real": s.real, "exact": all(t.exact for t in closed), "avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None} out = {"mode": "cross", "venue": "Арбитраж", "key": "cross", "settings": asdict(s), + "account_error": self.account_error, "status": self.status, "ex_status": self.ex_status, "updated": self.updated, "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 "завершение закрытия: " + ", ".join(p.base for p in self.positions if p.real and p.closing) + if s.real and any(p.real and p.closing for p in self.positions) + 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) + if self.account is not None: + out["virtual_account"] = self.account.view() return out diff --git a/desktop_chart.py b/desktop_chart.py new file mode 100644 index 0000000..6a0e813 --- /dev/null +++ b/desktop_chart.py @@ -0,0 +1,201 @@ +"""Tk chart rendering and viewport interaction for the desktop simulator.""" +from __future__ import annotations +from datetime import datetime +import tkinter as tk +import strategy + + +class ChartView: + def _draw_chart(self) -> None: + if not hasattr(self, "canvas"): + return + c = self.canvas + c.delete("all") + width, height = c.winfo_width(), c.winfo_height() + if width < 80 or height < 80: + return + left, right, top, bottom = 58, width - 82, 22, height - 34 + c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей") + candles = list(self.candles) + if not candles: + c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…") + return + prices = [p for candle in candles for p in (candle[2], candle[3])] + low, high = min(prices), max(prices) + pad = (high - low) * .08 if high != low else max(high * .001, 1e-8) + low -= pad + high += pad + t0 = candles[0][0] + t1 = max(candles[-1][0] + 60, t0 + 60) + view_end = self.chart_view_end if self.chart_view_end is not None else t1 + view_start = view_end - self.chart_visible_seconds + visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end] + visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end] + if visible_candles: + candles = visible_candles + prices = [p for candle in candles for p in (candle[2], candle[3])] + low, high = min(prices), max(prices) + base_span = high - low + pad = base_span * .08 if base_span else max(high * .001, 1e-8) + natural_low, natural_high = low - pad, high + pad + if self.chart_price_center is None or self.chart_price_span is None: + low, high = natural_low, natural_high + if self.chart_price_center is not None and self.chart_price_span is not None: + span = self.chart_price_span + low = self.chart_price_center - span / 2 + high = self.chart_price_center + span / 2 + t0 = view_start + t1 = view_end + if t1 <= t0: + return + for i in range(5): + y = top + i * (bottom - top) / 4 + value = high - i * (high - low) / 4 + c.create_line(left, y, right, y, fill="#263746") + c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value)) + c.create_line(left, bottom, right, bottom, fill="#6c7e8c") + candle_seconds = self.interval_minutes * 60 + slot = (right - left) * candle_seconds / (t1 - t0) + body_width = max(2.0, min(16.0, slot * .62)) + for candle in candles: + t, open_price, high_price, low_price, close_price = candle + if t < t0 - candle_seconds or t > t1: + continue + x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left) + y_high = bottom - (high_price - low) / (high - low) * (bottom - top) + y_low = bottom - (low_price - low) / (high - low) * (bottom - top) + y_open = bottom - (open_price - low) / (high - low) * (bottom - top) + y_close = bottom - (close_price - low) / (high - low) * (bottom - top) + color = "#38d996" if close_price >= open_price else "#ef5965" + c.create_line(x, y_high, x, y_low, fill=color, width=1) + body_top, body_bottom = sorted((y_open, y_close)) + if body_bottom - body_top < 1: + body_bottom = body_top + 1 + c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color) + for marker_time, marker_price, trade_id in visible_markers: + if not t0 <= marker_time <= t1: + continue + x = left + (marker_time - t0) / (t1 - t0) * (right - left) + y = bottom - (marker_price - low) / (high - low) * (bottom - top) + if top <= y <= bottom: + c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1) + c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}") + position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position + if position and position.mode != strategy.STRATEGY_CLASSIC: + self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, + f"Вход {position.side.upper()}", "#63a8ff") + self._draw_level(c, position.stop_price, low, high, left, right, top, bottom, + "Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42") + if position.partial_target > 0 and not position.partial_done: + self._draw_level(c, position.partial_target, low, high, left, right, top, bottom, + "Частичная фиксация", "#40d6b0") + if position.final_target > 0: + self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0") + liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side) + if liquidation is not None: + self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d") + elif position: + self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff") + s = self.applied_settings or self._safe_read_settings() + if s["add_step"] > 0 and position.add_count < s["max_adds"]: + next_add = position.last_add_price * (1 - s["add_step"] / 100) + self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff") + if s["stop_loss"] > 0: + stop_price = position.entry_price * (1 - s["stop_loss"] / 100) + self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42") + if s["take_profit"] > 0: + effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"])) + take_profit_price = position.entry_price * (1 + effective_tp_pct / 100) + self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0") + if self.last_price: + y = bottom - (self.last_price - low) / (high - low) * (bottom - top) + if top <= y <= bottom: + c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3)) + c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M")) + c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M")) + + def _chart_bounds(self) -> tuple[int, int, int, int]: + width, height = self.canvas.winfo_width(), self.canvas.winfo_height() + return 58, width - 82, 22, height - 34 + + def _on_chart_wheel(self, event: tk.Event) -> None: + direction = 1 if event.delta > 0 else -1 + self._zoom_chart(event.x, event.y, direction) + + def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None: + self._zoom_chart(event.x, event.y, direction) + + def _zoom_chart(self, x: int, y: int, direction: int) -> None: + if not self.candles: + return + old_span = self.chart_visible_seconds + factor = 0.8 if direction > 0 else 1.25 + self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor)) + if self.chart_view_end is None: + self.chart_view_end = self.candles[-1][0] + 60 + left, right, top, bottom = self._chart_bounds() + fraction_x = min(1, max(0, (x - left) / max(1, right - left))) + old_start = self.chart_view_end - old_span + anchor_time = old_start + fraction_x * old_span + self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds + if self.chart_price_center is None or self.chart_price_span is None: + prices = [p for candle in self.candles for p in (candle[2], candle[3])] + center = (max(prices) + min(prices)) / 2 + self.chart_price_center = center + self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8) + fraction_y = min(1, max(0, (y - top) / max(1, bottom - top))) + anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span + self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor) + self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span + self._draw_chart() + + def _on_chart_press(self, event: tk.Event) -> None: + if not self.candles: + return + left, right, top, bottom = self._chart_bounds() + if not left <= event.x <= right or not top <= event.y <= bottom: + return + if self.chart_view_end is None: + self.chart_view_end = self.candles[-1][0] + 60 + if self.chart_price_center is None or self.chart_price_span is None: + prices = [p for candle in self.candles for p in (candle[2], candle[3])] + low, high = min(prices), max(prices) + pad = (high - low) * .08 if high != low else max(high * .001, 1e-8) + self.chart_price_center = (high + low) / 2 + self.chart_price_span = high - low + 2 * pad + self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center, + self.chart_price_span, self.chart_visible_seconds) + self.canvas.configure(cursor="fleur") + + def _on_chart_drag(self, event: tk.Event) -> None: + if not self._drag_anchor: + return + x0, y0, end0, center0, price_span, time_span = self._drag_anchor + left, right, top, bottom = self._chart_bounds() + self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span + self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span + self.chart_price_span = price_span + self._draw_chart() + + def _on_chart_release(self, _event: tk.Event) -> None: + self._drag_anchor = None + self.canvas.configure(cursor="") + + def _reset_chart_view(self, _event: tk.Event | None = None) -> None: + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self.chart_view_end = None + self.chart_price_center = None + self.chart_price_span = None + self._drag_anchor = None + self._draw_chart() + + def _go_to_live(self) -> None: + """Return the chart's right edge to the newest market candle.""" + if self.candles: + self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60 + else: + self.chart_view_end = None + self.chart_price_center = None + self.chart_price_span = None + self._draw_chart() + diff --git a/desktop_models.py b/desktop_models.py new file mode 100644 index 0000000..b9ef352 --- /dev/null +++ b/desktop_models.py @@ -0,0 +1,74 @@ +"""Desktop account and per-symbol state, independent of Tk widgets.""" +from __future__ import annotations +from collections import deque +from dataclasses import dataclass, field +import strategy + +@dataclass +class Position: + trade_id: int + symbol: str + entry_price: float + qty: float + stake: float + entry_fee: float + opened_at: float + last_add_price: float + add_count: int = 0 + # Strategy-mode fields; classic positions keep the defaults. + side: str = "long" + mode: str = strategy.STRATEGY_CLASSIC + leverage: float = 1.0 + stop_price: float = 0.0 + initial_stop: float = 0.0 + atr: float = 0.0 + extreme: float = 0.0 + partial_target: float = 0.0 # 0 = none + final_target: float = 0.0 # 0 = none + partial_done: bool = False + realized_gross: float = 0.0 + realized_fees: float = 0.0 + opened_stake: float = 0.0 + + +@dataclass +class ClosedTrade: + trade_id: int + symbol: str + entry_price: float + exit_price: float + qty: float + gross_pnl: float + fees: float + net_pnl: float + roi_pct: float + opened_at: float + closed_at: float + reason: str + + +@dataclass +class CurrencyState: + """Independent market and position state for one concurrently traded symbol.""" + prices: deque = field(default_factory=deque) + candles: deque = field(default_factory=deque) + entry_markers: deque = field(default_factory=deque) + last_price: float | None = None + baseline_close: float | None = None + last_signal_pct: float | None = None + last_signal_ready: bool = False + previous_entry_signal_pct: float | None = None + live_minute_prices: deque = field(default_factory=deque) + last_ws_message: float = 0.0 + position: Position | None = None + live_position: Position | None = None + live_position_info: dict | None = None + live_order_busy: bool = False + live_transition_pending: bool = False + live_halted: bool = False + # Strategy modes A/B: last evaluated signal candle and the signal valid until the next close. + mode_signal: dict | None = None + mode_signal_bucket: int = 0 + mode_eval_busy: bool = False + + diff --git a/docs/reliability.md b/docs/reliability.md new file mode 100644 index 0000000..1dc10eb --- /dev/null +++ b/docs/reliability.md @@ -0,0 +1,176 @@ +# Recovery and development + +## Shared virtual capital and paper recovery + +`virtual_account.py` owns the web application's paper capital in +`web_sim_data/virtual_account.json`. All simulated coin engines use owners named `coin:`; +the paper arbitrage engine uses `cross`. Real arbitrage, real-signal ledgers, the Tk leader window +and the main desktop account do not draw on this wallet. + +An owner commit stores its complete recovery snapshot, cumulative cash movement and reserved capital +in the same account document. Only the difference from its previous cash total changes the balance. +This keeps a close, fee or funding payment from being credited again after restart. The account's owner +snapshot takes precedence over legacy per-engine files. Coin snapshots include open positions, IDs, +trade history and policy state needed to resume exits; paper arbitrage snapshots include both legs +and their fixed entry reserves. Restoring these positions does not emit a new entry. + +The initial balance is taken once from the old common budget, with a 300 $ default. Migration preserves +existing positions and their reserve even when that reserve exceeds the chosen initial deposit; free +capital then remains zero until the deficit is resolved. Individual legacy starting balances and old +closed profits are not summed into a new deposit. Open-position entry costs are brought into account +cash; the old closed trades remain statistical history. Reopening the same owner does not import it twice. + +| Account figure | Meaning | +| --- | --- | +| `balance` | Initial deposit + subsequent adjustments + settled trading cash movements | +| `equity` | Balance + current unrealized result | +| `reserved` | Total capital reserved by all paper owners | +| `free` | `max(0, min(balance, equity) - reserved)` | +| `realized` | Balance minus net deposits; deposits and withdrawals do not change this result | +| `stale` | Array of owners whose open-position marks are missing or older than 30 seconds | + +Coin reserve is the margin fixed at entry. Spot/futures arbitrage reserves the spot cost plus the greater +of 103% of futures notional and the capital required by the configured liquidation buffer. Spot/spot +arbitrage reserves the capital of both legs. Changing the settings does not release an existing position's +entry reserve. A new or increased reservation must fit the shared capital after fees. Unrealized losses +reduce free capital; unrealized profits do not fund new entries. + +Marks are refreshed only by market data. Saving settings or restoring a checkpoint does not make an old +quote fresh, and one current arbitrage link cannot refresh unrelated positions. If any open owner's mark +is stale, new reservations and withdrawals are refused. Deposits and reductions/settlement remain permitted +by the account, while the trading engine separately checks that it has a usable quote for a paper close. +A restart retains the last known unrealized result but treats its mark as stale until fresh data arrives. + +`GET /api/account`, `state.account` and the paper basis response's `paper_account` expose the same account. +`POST /api/account/adjust` accepts a signed `amount` and a `request_id`; the same ID and amount is idempotent, +including after server restart, while reuse for a different amount is refused. Numeric inputs must be finite; +zero adjustments, booleans and out-of-range amounts are rejected. The API journal returns the newest 100 +entries first. `version` orders persisted changes; `updated_at` also reflects newer in-memory market marks. +The browser uses both to reject older account snapshots arriving through different endpoints. Its pending +adjustment ID is retained in the currently open page for an explicit retry; after reloading the page, inspect +the journal before starting another adjustment. + +Statistics reset cannot erase open shared positions or replenish the account. A coin's web reset is also +refused while real execution is unfinished. Paper and real modes of a coin use separate ledgers: +`signal_.json/.csv` is the private real-signal state, with no shared-account funding gate or paper +entry hooks. Switching modes requires the current exposure, the destination ledger's saved positions and +real pending/recovery work to be clear. The saved mode and active trader are changed only after the new +ledger and mode settings have been saved successfully. + +## Persistence and concurrency + +`persistence.atomic_write_json` writes a unique temporary file in the destination directory, flushes and +fsyncs it, then replaces the old JSON file. Account operations prepare a new document and publish it only +after this write succeeds. Failed account writes leave both account cash and the authoritative owner +snapshot unchanged; the engine restores its previous position/history state instead of reporting a fill. +Unreadable or malformed recovery data is surfaced as an error and blocks entries, rather than silently +starting an independent empty paper account. CSV histories are exports, not the recovery authority for +an owner attached to the shared account. + +`runtime_lock.py` holds an OS file lock on `web_sim_data/engine.lock` for the entire engine lifetime. +It prevents a second engine using the same data directory even if a different HTTP port is requested. +The OS releases the lock when the process exits; the existence of the lock file alone does not mean a +process still owns it. The HTTP port is bound before recovery workers or exchange connections start. + +Within one process, account instances resolving to the same path share an `RLock`; a commit or adjustment +refreshes the latest persisted version while holding that lock before applying its change. Per-engine locks +protect their position/state transitions, and a separate registry lock protects engine lookup and removal. +The account stores snapshots and performs no exchange calls or callbacks into engines while its lock is held. +Atomic replacement does not substitute for these locks: it protects a single file replacement, not two +independent read/modify/write operations. + +## Real orders + +`cross.py` records an entry intent before sending its first order. A working limit order stays pending until +the exchange reports a terminal status; a cancel acknowledgement alone is insufficient. If the spot hedge is +rejected, the remaining short is closed with reduce-only orders and the actual position is checked again. +Failed and partial rollbacks survive restart and block further real entries while recovery is in progress. +The saved instrument snapshot allows cancellation/rollback even before the market scanner rediscovers the pair. + +`real_mirror.py` records prepared, submitted and filled stages. A prepared entry is never replayed on restart. +A confirmed fill is saved before requesting a take-profit. Saved positions are closed after restart, consistent +with the previous simulator behaviour. Atomic JSON writes are shared through `persistence.py`; persistence +failures block new entries and appear in the UI. + +An accepted submission whose response was lost may have no exchange order ID. A flat position snapshot does +not prove that such an order cannot fill later. These intents remain blocked; the futures recovery path checks +and reduces any remaining position without submitting another entry. Unknown spot submissions and interrupted +spot-to-spot entries require manual reconciliation on the exchanges. The application does not provide a blind +“forget pending order” button. The `/api/basis?ex=cross_real` response includes `recovery` details; the UI displays +the reason for pausing. A supervised resolution must verify the exchange's open orders and fills, not just its +current position. Automatic resolution by client order ID across every exchange is not implemented. + +Coin removal is a durable workflow in `pending_removals.py`, not an immediate deletion of the connection. +The intent and connection are saved first, new entries stop, and paper/real closes are requested. The engine +and its feeds remain available until paper positions are gone and the real mirror reports no position, +pending state, queued job or storage error. Only then are the connection and removal intent removed and +the engine stopped. Restart merges pending-removal connections back into the managed list, so a crash +between deleting the normal connection and completing the intent does not forget unfinished exposure. + +## Browser boundary + +Both the proxy and the engine validate the original loopback Host on GET and POST. A browser Origin, if present, +must match that authority; POST also requires `X-Sim: 1`. The proxy preserves the validated Host when forwarding. +Both listeners remain bound to loopback. This is local-app isolation, not user authentication for internet hosting. +Static assets are served from an explicit allowlist. + +Read timers are registered before the initial request, so a failed first fetch cannot permanently prevent +startup. GET requests have bounded timeouts and share one in-flight request per endpoint within the same +context; slow periodic tasks do not queue duplicate rendering work. Switching a coin or venue invalidates +the old read generation and starts a fresh request. Old responses, including old connection failures, cannot +replace the new context. Row close actions carry their original venue or coin. Sequence numbers also reject +older completed poll responses. The scanner checks the selected context before changing the DOM and again +after awaiting its response. + +An error or more than 10 seconds without a successful relevant read disables browser commands and displays +the last-data age. This is distinct from the account's 30-second market-mark rule. GET polling reconnects +automatically; POST commands are never automatically replayed. A lost command response is shown as an +unconfirmed result, requiring inspection of positions/state before an explicit repeat. Business refusals, +including statistics-reset refusals, are displayed instead of discarded. The selected mode and account +scope remain visible. Main arbitrage settings and fee/limit edits have separate Save buttons; switching +between paper and real views keeps their unsaved drafts separate in the current browser page. + +`web/help-data.js` contains the local reference descriptions; `web/help.js` builds a searchable native dialog +from them and the actual settings/modes used by the page. It supports keyboard focus, Escape and returning +focus to the opener. A regression test checks that all declared settings and static controls have help text. + +## Code boundaries + +| Responsibility | Files | +| --- | --- | +| Web layout, styles, behaviour | `web_sim.html`, `web/app.css`, `web/app.js` | +| Searchable help and field descriptions | `web/help.js`, `web/help-data.js` | +| HTTP routing and local browser policy | `web_sim.py`, `web_proxy.py`, `request_security.py` | +| Shared paper cash, owner snapshots and reservations | `virtual_account.py`, `scalp_paper.py`, `cross.py` | +| Single-engine ownership and deferred removal | `runtime_lock.py`, `pending_removals.py` | +| Desktop account models and chart | `desktop_models.py`, `desktop_chart.py` | +| Desktop coordination | `main.py` | +| Order execution and recovery | `cross.py`, `real_mirror.py` | +| Exchange adapters | `live.py`, `bybit_live.py` | +| Atomic snapshots | `persistence.py` | +| Historical execution and risk metrics | `historical_backtest.py`, `strategy.py` | + +## Verification + +Python 3.11+ is supported by the pinned dependencies in `requirements.txt`; the primary local validation uses +Python 3.12. JavaScript regression tests use Node.js 22+ and its built-in test runner, with no npm dependencies. + +```powershell +python -m pip install -r requirements.txt +python -B scripts/run_tests.py +node --test tests/web_context.test.cjs +``` + +The Python runner blocks external connections and DNS while permitting loopback HTTP fixtures. Exchange orders +are tested using fake clients. The CI workflow is configured for Windows with Python 3.11, 3.12 and 3.13; +configuration does not imply that a remote CI run or a real exchange integration has been performed. Browser +preview checks use a separate mocked local API, not a running trading backend. + +Regression cases cover refused/partial rollback, uncertain cancellation and submission, restart before and +after order acceptance, failed disk writes, hostile Host/Origin, response ordering, percentage drawdown and +capital-floor ordering for long/short backtests including fees. Shared-account cases additionally cover +competing coins/arbitrage for one reserve limit, idempotent adjustments and settlement, migration/restart, +stale marks and retained unrealized losses, entry/close rollback on write failure, fixed collateral after +settings changes, reset without creating money, and separation of real signal execution from virtual funding. +Browser tests cover first-fetch recovery, single-flight reads, context invalidation, stale controls, scanner +navigation, refused reset, account snapshot ordering, signed adjustments, retry IDs and help coverage. diff --git a/historical_backtest.py b/historical_backtest.py index 3a59efc..024483d 100644 --- a/historical_backtest.py +++ b/historical_backtest.py @@ -495,6 +495,24 @@ def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_ return windows, sorted(failed) +def _track_risk(risk: dict[str, float], equity: float) -> None: + risk["peak"] = max(risk["peak"], equity) + drawdown = risk["peak"] - equity + drawdown_pct = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0 + # The largest dollar loss and largest percentage loss may follow different peaks. + risk["max_dd_usdt"] = max(risk["max_dd_usdt"], drawdown) + risk["max_dd_pct"] = max(risk["max_dd_pct"], drawdown_pct) + risk["min_equity"] = min(risk["min_equity"], equity) + + +def _equity_floor_crossing(start: float, end: float, start_equity: float, + end_equity: float, floor: float) -> float | None: + """Price where linearly marked equity first reaches the floor on this segment.""" + if start_equity > floor >= end_equity: + return start + (end - start) * (floor - start_equity) / (end_equity - start_equity) + return None + + def run_backtest(candles_by_symbol: dict[str, list[list[float]]], strategies: dict[str, dict[str, float]], initial_capital: float, fee_pct: float = TAKER_FEE_PCT, @@ -560,21 +578,12 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]], equity += unrealized - estimated_exit_fee return equity - def track_risk(equity: float) -> None: - if equity > risk["peak"]: - risk["peak"] = equity - drawdown = risk["peak"] - equity - if drawdown > risk["max_dd_usdt"]: - risk["max_dd_usdt"] = drawdown - risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0 - risk["min_equity"] = min(risk["min_equity"], equity) - def mark_and_check_stop(symbol: str, price: float, stamp: int) -> bool: if equity_stop["triggered"]: return True marks[symbol] = price equity = equity_at() - track_risk(equity) + _track_risk(risk, equity) if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12): equity_stop.update(triggered=True, timestamp=stamp, equity=equity) return True @@ -742,12 +751,10 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]], # Add the precise capital-floor crossing as an event so a later rebound # inside the same candle cannot hide a drawdown breach. if min_equity_pct > 0 and end < current: - current_equity = equity_at(symbol, current) - end_equity = equity_at(symbol, end) - if current_equity > equity_floor >= end_equity and current_equity != end_equity: - stop_level = current + (end - current) * ( - (equity_floor - current_equity) / (end_equity - current_equity) - ) + stop_level = _equity_floor_crossing( + current, end, equity_at(symbol, current), equity_at(symbol, end), equity_floor, + ) + if stop_level is not None: candidates.append((stop_level, "EQUITY_STOP")) _tp, stop_level, liq_level = exit_levels(symbol, pos) if stop_level is not None and end <= stop_level < current: @@ -1118,10 +1125,11 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str def iso(stamp: int) -> str: return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat() - def equity_at() -> float: + def equity_at(symbol: str | None = None, price: float | None = None) -> float: equity = cash for position_symbol, pos in positions.items(): - mark = marks.get(position_symbol, pos.entry_price) + mark = (price if position_symbol == symbol and price is not None + else marks.get(position_symbol, pos.entry_price)) equity += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) - mark * pos.qty * fee_pct / 100) return equity @@ -1131,13 +1139,7 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str return True marks[symbol] = price equity = equity_at() - if equity > risk["peak"]: - risk["peak"] = equity - drawdown = risk["peak"] - equity - if drawdown > risk["max_dd_usdt"]: - risk["max_dd_usdt"] = drawdown - risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0 - risk["min_equity"] = min(risk["min_equity"], equity) + _track_risk(risk, equity) if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12): equity_stop.update(triggered=True, timestamp=stamp, equity=equity) return True @@ -1296,6 +1298,12 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str return liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side) candidates = [] + if min_equity_pct > 0: + floor_price = _equity_floor_crossing( + start, end, equity_at(symbol, start), equity_at(symbol, end), equity_floor, + ) + if floor_price is not None: + candidates.append((floor_price, "EQUITY_STOP")) lo, hi = min(start, end), max(start, end) if lo <= pos.stop <= hi: candidates.append((pos.stop, "STOP")) @@ -1307,6 +1315,9 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str # The first level crossed on the way from ``start`` is the nearest one. level, event = min(candidates, key=lambda item: abs(item[0] - start)) marks[symbol] = level + if event == "EQUITY_STOP": + mark_and_check_stop(symbol, level, stamp) + return if event == "LIQ": close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True) else: diff --git a/lead_connections_removed.json b/lead_connections_removed.json new file mode 100644 index 0000000..da8aa64 --- /dev/null +++ b/lead_connections_removed.json @@ -0,0 +1,9 @@ +[ + { + "lead_market": "raydium", + "lead_ticker": "CLAUDIAUSDTM", + "lead_pool": "Fe7bpDYCs74GqiCUF14HwgUMToPKV1d9mDYVX5BTohFr", + "follow_exchange": "mexc", + "follow_ticker": "CLAUDIA_USDT" + } +] \ No newline at end of file diff --git a/live.py b/live.py index 43ba67e..c9db10b 100644 --- a/live.py +++ b/live.py @@ -167,8 +167,13 @@ def _http(method: str, url: str, headers: dict | None = None, body: bytes | None else: _give_back(parts.scheme, parts.netloc, conn) if resp.status >= 400: - raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}") - return json.loads(data or b"{}") + raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}", + sent=method in ("POST", "DELETE") and resp.status >= 500) + try: + return json.loads(data or b"{}") + except (ValueError, UnicodeDecodeError) as exc: + raise LiveError(f"не удалось прочитать ответ биржи: {exc}", + sent=method in ("POST", "DELETE")) from None raise LiveError("нет связи") diff --git a/main.py b/main.py index ac594ad..5fad405 100644 --- a/main.py +++ b/main.py @@ -12,7 +12,6 @@ import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed from collections import deque -from dataclasses import dataclass, field from datetime import datetime from pathlib import Path import tkinter as tk @@ -22,6 +21,9 @@ from credential_store import CredentialStoreError, delete_credentials, load_cred from historical_backtest import (fetch_funding_history, fetch_klines, prepare_universe, run_backtest, run_mode_backtest, save_report) import strategy +from desktop_models import Position, ClosedTrade, CurrencyState +from desktop_chart import ChartView +from persistence import atomic_write_json try: import websocket @@ -59,75 +61,7 @@ MAX_EVENTS_PER_POLL = 2000 MANUAL_CLOSE_CONFIRM_SECONDS = 15 -@dataclass -class Position: - trade_id: int - symbol: str - entry_price: float - qty: float - stake: float - entry_fee: float - opened_at: float - last_add_price: float - add_count: int = 0 - # Strategy-mode fields; classic positions keep the defaults. - side: str = "long" - mode: str = strategy.STRATEGY_CLASSIC - leverage: float = 1.0 - stop_price: float = 0.0 - initial_stop: float = 0.0 - atr: float = 0.0 - extreme: float = 0.0 - partial_target: float = 0.0 # 0 = none - final_target: float = 0.0 # 0 = none - partial_done: bool = False - realized_gross: float = 0.0 - realized_fees: float = 0.0 - opened_stake: float = 0.0 - - -@dataclass -class ClosedTrade: - trade_id: int - symbol: str - entry_price: float - exit_price: float - qty: float - gross_pnl: float - fees: float - net_pnl: float - roi_pct: float - opened_at: float - closed_at: float - reason: str - - -@dataclass -class CurrencyState: - """Independent market and position state for one concurrently traded symbol.""" - prices: deque = field(default_factory=deque) - candles: deque = field(default_factory=deque) - entry_markers: deque = field(default_factory=deque) - last_price: float | None = None - baseline_close: float | None = None - last_signal_pct: float | None = None - last_signal_ready: bool = False - previous_entry_signal_pct: float | None = None - live_minute_prices: deque = field(default_factory=deque) - last_ws_message: float = 0.0 - position: Position | None = None - live_position: Position | None = None - live_position_info: dict | None = None - live_order_busy: bool = False - live_transition_pending: bool = False - live_halted: bool = False - # Strategy modes A/B: last evaluated signal candle and the signal valid until the next close. - mode_signal: dict | None = None - mode_signal_bucket: int = 0 - mode_eval_busy: bool = False - - -class PaperSimulator: +class PaperSimulator(ChartView): def __init__(self, root: tk.Tk) -> None: self.root = root self.root.title("Bybit — симулятор сделок в реальном времени") @@ -2134,10 +2068,8 @@ class PaperSimulator: "live_initial_deposits": self.live_initial_deposits, } try: - temp_path = STATE_FILE.with_suffix(".json.tmp") - temp_path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8") - os.replace(temp_path, STATE_FILE) - except OSError as exc: + atomic_write_json(STATE_FILE, state) + except (OSError, ValueError) as exc: if hasattr(self, "status_var"): self.status_var.set(f"Не удалось сохранить историю счёта: {exc}") @@ -2154,10 +2086,8 @@ class PaperSimulator: def _save_settings(self) -> None: self._settings_save_job = None try: - temp_path = SETTINGS_FILE.with_suffix(".json.tmp") - temp_path.write_text(json.dumps(self._settings_payload(), ensure_ascii=False, indent=2), encoding="utf-8") - os.replace(temp_path, SETTINGS_FILE) - except OSError as exc: + atomic_write_json(SETTINGS_FILE, self._settings_payload()) + except (OSError, ValueError) as exc: self.status_var.set(f"Не удалось сохранить настройки: {exc}") @staticmethod @@ -4513,199 +4443,6 @@ class PaperSimulator: return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}" return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}" - def _draw_chart(self) -> None: - if not hasattr(self, "canvas"): - return - c = self.canvas - c.delete("all") - width, height = c.winfo_width(), c.winfo_height() - if width < 80 or height < 80: - return - left, right, top, bottom = 58, width - 82, 22, height - 34 - c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей") - candles = list(self.candles) - if not candles: - c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…") - return - prices = [p for candle in candles for p in (candle[2], candle[3])] - low, high = min(prices), max(prices) - pad = (high - low) * .08 if high != low else max(high * .001, 1e-8) - low -= pad - high += pad - t0 = candles[0][0] - t1 = max(candles[-1][0] + 60, t0 + 60) - view_end = self.chart_view_end if self.chart_view_end is not None else t1 - view_start = view_end - self.chart_visible_seconds - visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end] - visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end] - if visible_candles: - candles = visible_candles - prices = [p for candle in candles for p in (candle[2], candle[3])] - low, high = min(prices), max(prices) - base_span = high - low - pad = base_span * .08 if base_span else max(high * .001, 1e-8) - natural_low, natural_high = low - pad, high + pad - if self.chart_price_center is None or self.chart_price_span is None: - low, high = natural_low, natural_high - if self.chart_price_center is not None and self.chart_price_span is not None: - span = self.chart_price_span - low = self.chart_price_center - span / 2 - high = self.chart_price_center + span / 2 - t0 = view_start - t1 = view_end - if t1 <= t0: - return - for i in range(5): - y = top + i * (bottom - top) / 4 - value = high - i * (high - low) / 4 - c.create_line(left, y, right, y, fill="#263746") - c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value)) - c.create_line(left, bottom, right, bottom, fill="#6c7e8c") - candle_seconds = self.interval_minutes * 60 - slot = (right - left) * candle_seconds / (t1 - t0) - body_width = max(2.0, min(16.0, slot * .62)) - for candle in candles: - t, open_price, high_price, low_price, close_price = candle - if t < t0 - candle_seconds or t > t1: - continue - x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left) - y_high = bottom - (high_price - low) / (high - low) * (bottom - top) - y_low = bottom - (low_price - low) / (high - low) * (bottom - top) - y_open = bottom - (open_price - low) / (high - low) * (bottom - top) - y_close = bottom - (close_price - low) / (high - low) * (bottom - top) - color = "#38d996" if close_price >= open_price else "#ef5965" - c.create_line(x, y_high, x, y_low, fill=color, width=1) - body_top, body_bottom = sorted((y_open, y_close)) - if body_bottom - body_top < 1: - body_bottom = body_top + 1 - c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color) - for marker_time, marker_price, trade_id in visible_markers: - if not t0 <= marker_time <= t1: - continue - x = left + (marker_time - t0) / (t1 - t0) * (right - left) - y = bottom - (marker_price - low) / (high - low) * (bottom - top) - if top <= y <= bottom: - c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1) - c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}") - position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position - if position and position.mode != strategy.STRATEGY_CLASSIC: - self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, - f"Вход {position.side.upper()}", "#63a8ff") - self._draw_level(c, position.stop_price, low, high, left, right, top, bottom, - "Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42") - if position.partial_target > 0 and not position.partial_done: - self._draw_level(c, position.partial_target, low, high, left, right, top, bottom, - "Частичная фиксация", "#40d6b0") - if position.final_target > 0: - self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0") - liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side) - if liquidation is not None: - self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d") - elif position: - self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff") - s = self.applied_settings or self._safe_read_settings() - if s["add_step"] > 0 and position.add_count < s["max_adds"]: - next_add = position.last_add_price * (1 - s["add_step"] / 100) - self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff") - if s["stop_loss"] > 0: - stop_price = position.entry_price * (1 - s["stop_loss"] / 100) - self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42") - if s["take_profit"] > 0: - effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"])) - take_profit_price = position.entry_price * (1 + effective_tp_pct / 100) - self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0") - if self.last_price: - y = bottom - (self.last_price - low) / (high - low) * (bottom - top) - if top <= y <= bottom: - c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3)) - c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M")) - c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M")) - - def _chart_bounds(self) -> tuple[int, int, int, int]: - width, height = self.canvas.winfo_width(), self.canvas.winfo_height() - return 58, width - 82, 22, height - 34 - - def _on_chart_wheel(self, event: tk.Event) -> None: - direction = 1 if event.delta > 0 else -1 - self._zoom_chart(event.x, event.y, direction) - - def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None: - self._zoom_chart(event.x, event.y, direction) - - def _zoom_chart(self, x: int, y: int, direction: int) -> None: - if not self.candles: - return - old_span = self.chart_visible_seconds - factor = 0.8 if direction > 0 else 1.25 - self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor)) - if self.chart_view_end is None: - self.chart_view_end = self.candles[-1][0] + 60 - left, right, top, bottom = self._chart_bounds() - fraction_x = min(1, max(0, (x - left) / max(1, right - left))) - old_start = self.chart_view_end - old_span - anchor_time = old_start + fraction_x * old_span - self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds - if self.chart_price_center is None or self.chart_price_span is None: - prices = [p for candle in self.candles for p in (candle[2], candle[3])] - center = (max(prices) + min(prices)) / 2 - self.chart_price_center = center - self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8) - fraction_y = min(1, max(0, (y - top) / max(1, bottom - top))) - anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span - self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor) - self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span - self._draw_chart() - - def _on_chart_press(self, event: tk.Event) -> None: - if not self.candles: - return - left, right, top, bottom = self._chart_bounds() - if not left <= event.x <= right or not top <= event.y <= bottom: - return - if self.chart_view_end is None: - self.chart_view_end = self.candles[-1][0] + 60 - if self.chart_price_center is None or self.chart_price_span is None: - prices = [p for candle in self.candles for p in (candle[2], candle[3])] - low, high = min(prices), max(prices) - pad = (high - low) * .08 if high != low else max(high * .001, 1e-8) - self.chart_price_center = (high + low) / 2 - self.chart_price_span = high - low + 2 * pad - self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center, - self.chart_price_span, self.chart_visible_seconds) - self.canvas.configure(cursor="fleur") - - def _on_chart_drag(self, event: tk.Event) -> None: - if not self._drag_anchor: - return - x0, y0, end0, center0, price_span, time_span = self._drag_anchor - left, right, top, bottom = self._chart_bounds() - self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span - self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span - self.chart_price_span = price_span - self._draw_chart() - - def _on_chart_release(self, _event: tk.Event) -> None: - self._drag_anchor = None - self.canvas.configure(cursor="") - - def _reset_chart_view(self, _event: tk.Event | None = None) -> None: - self.chart_visible_seconds = self.interval_minutes * 60 * 30 - self.chart_view_end = None - self.chart_price_center = None - self.chart_price_span = None - self._drag_anchor = None - self._draw_chart() - - def _go_to_live(self) -> None: - """Return the chart's right edge to the newest market candle.""" - if self.candles: - self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60 - else: - self.chart_view_end = None - self.chart_price_center = None - self.chart_price_span = None - self._draw_chart() - def _update_candle(self, timestamp: float, price: float) -> None: interval_seconds = self.interval_minutes * 60 candle_start = int(timestamp // interval_seconds) * interval_seconds 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/pending_removals.py b/pending_removals.py new file mode 100644 index 0000000..81eb452 --- /dev/null +++ b/pending_removals.py @@ -0,0 +1,45 @@ +"""Durable removal intents: retain a connection until its real exposure is closed.""" +from __future__ import annotations + +import copy +import json +import threading +from pathlib import Path + +from persistence import atomic_write_json + + +class PendingRemovals: + def __init__(self, path: Path): + self.path = Path(path) + self.lock = threading.RLock() + self.items = {} + self.error = "" + try: + value = json.loads(self.path.read_text(encoding="utf-8")) + if not isinstance(value, dict) or not all(isinstance(v, dict) for v in value.values()): + raise ValueError("неверный формат") + self.items = value + except FileNotFoundError: + pass + except (OSError, ValueError) as exc: + self.error = f"Не прочитаны ожидающие удаления: {exc}" + + def connections(self): + with self.lock: + return copy.deepcopy(self.items) + + def schedule(self, key: str, connection: dict): + with self.lock: + if self.error: + raise ValueError(self.error) + updated = {**self.items, key: dict(connection)} + atomic_write_json(self.path, updated) + self.items = updated + + def complete(self, key: str): + with self.lock: + updated = dict(self.items) + updated.pop(key, None) + atomic_write_json(self.path, updated) + self.items = updated diff --git a/persistence.py b/persistence.py new file mode 100644 index 0000000..0dbc4b3 --- /dev/null +++ b/persistence.py @@ -0,0 +1,27 @@ +"""Atomic local JSON snapshots; callers must handle write failures explicitly.""" + +from __future__ import annotations + +import json +import os +import tempfile +from pathlib import Path + + +def atomic_write_json(path: Path, payload) -> None: + """Flush a new snapshot before replacing the old file, or leave the old file intact.""" + path = Path(path) + encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8") + path.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(fd, "wb") as stream: + stream.write(encoded) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + try: + os.unlink(temporary) + except FileNotFoundError: + pass diff --git a/real_mirror.py b/real_mirror.py index 5898583..a6fce30 100644 --- a/real_mirror.py +++ b/real_mirror.py @@ -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_.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_.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"), diff --git a/request_security.py b/request_security.py new file mode 100644 index 0000000..135de56 --- /dev/null +++ b/request_security.py @@ -0,0 +1,43 @@ +"""Validate the original browser request before proxying or executing local commands.""" +from __future__ import annotations + +import ipaddress +from urllib.parse import urlsplit + +LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"} + + +def _authority(value: str): + try: + url = urlsplit("http://" + value) + if (url.hostname not in LOCAL_HOSTS or url.username is not None or url.password is not None + or url.path or url.query or url.fragment or any(c.isspace() for c in value)): + return None + return url.hostname, url.port or 80 + except ValueError: + return None + + +def trusted_request(handler, *, command: bool = False) -> bool: + try: + if not ipaddress.ip_address(handler.client_address[0]).is_loopback: + return False + except ValueError: + return False + hosts = handler.headers.get_all("Host", []) + if len(hosts) != 1 or (host := _authority(hosts[0])) is None: + return False + origins = handler.headers.get_all("Origin", []) + if len(origins) > 1: + return False + if origins: + try: + origin = urlsplit(origins[0]) + if (origin.scheme != "http" or origin.path or origin.query or origin.fragment + or _authority(origin.netloc) != host): + return False + except ValueError: + return False + if handler.headers.get("Sec-Fetch-Site") == "cross-site": + return False + return not command or handler.headers.get("X-Sim") == "1" diff --git a/requirements.txt b/requirements.txt index 7b39e8e..0ee383c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ -websocket-client>=1.8,<2 -numpy>=1.26 +# Python 3.11+ +websocket-client==1.8.0 +numpy==2.3.5 diff --git a/run_web_sim.bat b/run_web_sim.bat index 562c2cb..5fb6b1c 100644 --- a/run_web_sim.bat +++ b/run_web_sim.bat @@ -1,9 +1,5 @@ @echo off -rem Web simulator in two parts: -rem engine - python.exe web_sim.py --backend (127.0.0.1:8766, exchange data, stays in the VPN) -rem page - pythonw.exe web_proxy.py (0.0.0.0:8765, public; add pythonw.exe to the VPN exclusions) +rem Validate/repair the environment, then start the local proxy and engine. cd /d "%~dp0" -start "web_proxy" pyw -3 web_proxy.py -start "" http://127.0.0.1:8765 -py -3 web_sim.py --backend -pause +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0server_control.ps1" start +if errorlevel 1 pause diff --git a/runtime_lock.py b/runtime_lock.py new file mode 100644 index 0000000..18a02a5 --- /dev/null +++ b/runtime_lock.py @@ -0,0 +1,45 @@ +"""One trading engine per data directory, even with different HTTP ports.""" +from __future__ import annotations + +import os +from pathlib import Path + + +class RuntimeLock: + def __init__(self, path: Path): + self.path = Path(path) + self.stream = None + + def __enter__(self): + self.path.parent.mkdir(parents=True, exist_ok=True) + stream = self.path.open("a+b") + if stream.seek(0, os.SEEK_END) == 0: + stream.write(b"\0") + stream.flush() + stream.seek(0) + try: + if os.name == "nt": + import msvcrt + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + stream.close() + raise RuntimeError("Движок уже запущен для этой папки. Откройте существующее окно программы.") from None + self.stream = stream + return self + + def __exit__(self, *args): + if self.stream is not None: + try: + self.stream.seek(0) + if os.name == "nt": + import msvcrt + msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + fcntl.flock(self.stream.fileno(), fcntl.LOCK_UN) + finally: + self.stream.close() + self.stream = None diff --git a/scalp_paper.py b/scalp_paper.py index 64a158e..99ecb60 100644 --- a/scalp_paper.py +++ b/scalp_paper.py @@ -26,11 +26,12 @@ import statistics import sys import time from collections import deque -from dataclasses import dataclass, field +from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path import scalp_hint as sh +from persistence import atomic_write_json ROOT = Path(__file__).resolve().parent STATE_FILE = ROOT / "scalp_paper_state.json" @@ -53,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) @@ -137,6 +140,7 @@ class Position: regime: str = "" features: dict = field(default_factory=dict) uid: int = 0 # unique per ledger, so one of several open positions can be closed by hand + margin: float = 0.0 # fixed at entry; changing leverage later must not release collateral @dataclass @@ -178,20 +182,59 @@ class Ledger: self.balance = settings.budget self.positions: list[Position] = [] self.trades: list[PaperTrade] = [] + self.policy_state: dict = {} + self.state_provider = None + self.storage_error = "" + self._recovery_error = "" + self._uid = 0 + self.account = None + self.signal_only = False # private real-signal bookkeeping, never a shared wallet setting + self.account_owner = "" + self.account_origin = self.balance + self._unrealized = 0.0 + self._position_marks: dict[int, float] = {} self.hooks: list = [] # hook(event, pos): "open" / "close" — real trading mirrors the paper positions self._load() def _load(self) -> None: + snapshot_trades = False if self.state_path: try: state = json.loads(self.state_path.read_text(encoding="utf-8")) - self.balance = float(state.get("balance", self.settings.budget)) + balance = float(state.get("balance", self.settings.budget)) + positions = [Position(**row) for row in state.get("positions", [])] + next_uid = max(int(state.get("next_uid", 0)), + max((pos.uid for pos in positions), default=0)) + policy_state = state.get("policy_state", {}) + if not math.isfinite(balance) or not isinstance(policy_state, dict): + raise ValueError("повреждён снимок счёта") + restored_trades = None + if "trades" in state: + restored_trades = [PaperTrade(**row) for row in state["trades"]] + settings = PaperSettings(**vars(self.settings)) for key, value in state.get("settings", {}).items(): - if hasattr(self.settings, key): - setattr(self.settings, key, type(getattr(self.settings, key))(value)) - except (OSError, ValueError, TypeError): + if hasattr(settings, key): + setattr(settings, key, type(getattr(settings, key))(value)) + for pos in positions: + if (pos.side not in ("LONG", "SHORT") or not math.isfinite(pos.qty) or pos.qty <= 0 + or not math.isfinite(pos.entry) or pos.entry <= 0): + raise ValueError("повреждена открытая позиция") + if pos.margin <= 0: + pos.margin = pos.qty * pos.entry / max(settings.leverage, 1.0) + self.balance, self.positions, self._uid = balance, positions, next_uid + self.policy_state = policy_state + self._position_marks = {int(uid): float(value) for uid, value in state.get("position_marks", {}).items()} + self._unrealized = float(state.get("unrealized", sum(self._position_marks.values()))) + vars(self.settings).update(vars(settings)) + if restored_trades is not None: + self.trades = restored_trades + snapshot_trades = True + except FileNotFoundError: pass - if self.trades_path: + except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: + self.storage_error = f"Не удалось восстановить бумажный счёт: {exc}" + self._recovery_error = self.storage_error + if self.trades_path and not snapshot_trades: header: list[str] = [] try: with self.trades_path.open(encoding="utf-8-sig") as file: @@ -220,38 +263,109 @@ class Ledger: except OSError: pass - def save(self) -> None: - if self.state_path: - try: - self.state_path.write_text(json.dumps({"balance": self.balance, "settings": vars(self.settings)}, - ensure_ascii=False, indent=2), encoding="utf-8") - except OSError: - pass + def snapshot(self) -> dict: + state = self.state_provider() if self.state_provider else self.policy_state + return {"version": 2, "balance": self.balance, "settings": vars(self.settings).copy(), + "positions": [asdict(pos) for pos in self.positions], "next_uid": self._uid, + "policy_state": state, "account_origin": self.account_origin, + "position_marks": dict(self._position_marks), "unrealized": self._unrealized, + "trades": [asdict(trade) for trade in self.trades]} - def reset(self) -> None: - for pos in list(self.positions): # positions dropped by a reset are closed for real too - for hook in self.hooks: - hook("close", pos) - self.balance = self.settings.budget + @property + def available(self) -> float: + """Free common collateral when bound; retain standalone balance semantics otherwise.""" + if self.signal_only and self.account is None: + return math.inf + return self.account.view()["free"] if self.account is not None else self.balance + + def bind_account(self, account, owner: str) -> None: + """Attach this ledger to one shared virtual wallet; its snapshot is authoritative.""" + saved = account.restore(owner) + if saved is not None: + self.balance = float(saved["balance"]) + self.account_origin = float(saved["account_origin"]) + self.positions = [Position(**row) for row in saved.get("positions", [])] + self.trades = [PaperTrade(**row) for row in saved.get("trades", [])] + self._uid = int(saved.get("next_uid", 0)) + self.policy_state = saved.get("policy_state", {}) + self._position_marks = {int(uid): float(value) for uid, value in saved.get("position_marks", {}).items()} + self._unrealized = float(saved.get("unrealized", sum(self._position_marks.values()))) + for key, value in saved.get("settings", {}).items(): + if hasattr(self.settings, key): + setattr(self.settings, key, value) + self.storage_error = self._recovery_error = "" + else: + if self._recovery_error: + raise ValueError(self._recovery_error) + self.account_origin = self.balance + sum(pos.fee_in for pos in self.positions) + self.account, self.account_owner = account, owner + if saved is None: + account.commit(owner, self.snapshot(), cash_total=self.balance - self.account_origin, + reserved=sum(pos.margin for pos in self.positions), allow_existing=True, + event="import paper ledger") + + def save(self) -> bool: + if self._recovery_error: + self.storage_error = self._recovery_error + return False + try: + payload = self.snapshot() + if self.account is not None: + self.account.commit(self.account_owner, payload, + cash_total=self.balance - self.account_origin, + reserved=sum(pos.margin for pos in self.positions), unrealized=self._unrealized, + event="paper ledger") + elif self.state_path: + atomic_write_json(self.state_path, payload) + self.storage_error = "" + return True + except Exception as exc: + self.storage_error = f"Не удалось сохранить бумажный счёт: {exc}" + return False + + def reset(self) -> bool: + if self.account is not None and self.positions: + self.storage_error = "Сначала закройте открытые позиции общего виртуального счёта" + return False + previous_balance, previous_positions, previous_trades = self.balance, self.positions, self.trades + previous_marks, previous_unrealized = self._position_marks, self._unrealized + if self.account is None: + self.balance = self.settings.budget self.position = None self.trades = [] + self._position_marks, self._unrealized = {}, 0.0 + if not self.save(): + self.balance, self.positions, self.trades = previous_balance, previous_positions, previous_trades + self._position_marks, self._unrealized = previous_marks, previous_unrealized + return False + for pos in previous_positions: # positions dropped by an explicit standalone reset close for real too + for hook in self.hooks: + hook("close", pos) if self.trades_path: try: self.trades_path.unlink() except OSError: pass - self.save() + return True def open(self, ticker: str, side: str, price: float, now: float, fee_pct: float, target: float, - stop: float | None, entry_mid: float, regime: str = "", features: dict | None = None) -> Position: - notional = self.settings.stake * self.settings.leverage + stop: float | None, entry_mid: float, regime: str = "", features: dict | None = None, + notional_usd: float | None = None) -> Position | None: + notional = self.settings.stake * self.settings.leverage if notional_usd is None else notional_usd + if not math.isfinite(notional) or notional <= 0 or not math.isfinite(price) or price <= 0: + raise ValueError("Размер и цена бумажной позиции должны быть положительными") qty = notional / price fee = notional * fee_pct / 100 + old_balance, old_uid = self.balance, self._uid self.balance -= fee self._uid = getattr(self, "_uid", 0) + 1 - pos = Position(ticker, side, qty, price, target, stop, now, fee, entry_mid, regime, features or {}, self._uid) + pos = Position(ticker, side, qty, price, target, stop, now, fee, entry_mid, regime, features or {}, self._uid, + notional / max(self.settings.leverage, 1.0)) self.positions.append(pos) - self.save() + if not self.save(): + self.positions.remove(pos) + self.balance, self._uid = old_balance, old_uid + return None for hook in self.hooks: hook("open", pos) return pos @@ -266,12 +380,15 @@ class Ledger: self.positions = [] if value is None else [value] def close(self, price: float, now: float, reason: str, fee_pct: float, utc: str | None = None, - pos: Position | None = None) -> PaperTrade: + pos: Position | None = None) -> PaperTrade | None: pos = pos or self.position assert pos is not None + old_balance, old_unrealized = self.balance, self._unrealized + index = self.positions.index(pos) self.positions.remove(pos) - for hook in self.hooks: - hook("close", pos) + # The next quote will remark any remaining positions; do not retain a closed position's P&L. + previous_mark = self._position_marks.pop(pos.uid, 0.0) + self._unrealized -= previous_mark sign = 1 if pos.side == "LONG" else -1 gross = sign * (price - pos.entry) * pos.qty fee_out = price * pos.qty * fee_pct / 100 @@ -281,6 +398,14 @@ class Ledger: sign * (price / pos.entry - 1) * 100, gross - pos.fee_in - fee_out, pos.fee_in + fee_out, reason, max(0.0, now - pos.opened), pos.regime) self.trades.append(trade) + if not self.save(): + self.trades.pop() + self.positions.insert(index, pos) + self.balance, self._unrealized = old_balance, old_unrealized + self._position_marks[pos.uid] = previous_mark + return None + for hook in self.hooks: + hook("close", pos) if self.trades_path: new_file = not self.trades_path.exists() try: @@ -294,7 +419,6 @@ class Ledger: trade.reason, f"{trade.hold_seconds:.1f}", trade.regime]) except OSError: pass - self.save() return trade @@ -337,7 +461,7 @@ class SimplePolicy: trader.message = (f"Сигнал {hint.side}, но до цели {target_pct:.2f}% < {self.s.min_target_pct:g}% — " "сделка не открыта") return - if led.balance < self.s.stake: + if led.available < self.s.stake: trader.message = "Баланс меньше ставки — сделки остановлены" return led.open(ticker, hint.side, entry, now, TAKER, hint.target, None, mid) @@ -426,7 +550,7 @@ class AdaptivePolicy: trader.message = f"Лимитка {order.side} снята: перевес сменился" return if (not self.s.enabled or now < self.pause_until or now - trader.last_close < self.s.cooldown_seconds - or not hint.metrics or led.balance < self.s.stake): + or not hint.metrics or led.available < self.s.stake): return spread = best_ask - best_bid min_risk = max(self.s.noise_mult * state["noise"], 2 * spread, mid * 0.001, 2 * tick) @@ -570,7 +694,7 @@ class PulsePolicy: self.order = None if not self.s.enabled or self.book is None or self.hint is None or trader.ledger.position is not None: return - if trader.ledger.balance < self.s.stake: + if trader.ledger.available < self.s.stake: self.status = "Баланс меньше ставки — сделки остановлены" return best_bid, best_ask = self.book.best() @@ -671,7 +795,7 @@ class SumsPolicy: self.order = Order(ticker, self.order.side, touch, self._target(touch, direction, tick), 0.0, now, "суммы", {}) # follow the best price return - if not s.enabled or signal == 0 or led.balance < s.stake or now - trader.last_close < s.cooldown_seconds: + if not s.enabled or signal == 0 or led.available < s.stake or now - trader.last_close < s.cooldown_seconds: return price = best_bid if signal > 0 else best_ask self.order = Order(ticker, "LONG" if signal > 0 else "SHORT", price, self._target(price, signal, tick), 0.0, @@ -982,7 +1106,7 @@ class LeadPolicy: reason = f"данные устарели ({stale:.0f} мс)" elif (now - trader.last_close) * 1000 < self.s.cooldown_ms and not self.skip_pause: reason = f"пауза после сделки ещё {self.s.cooldown_ms - (now - trader.last_close) * 1000:.0f} мс" - elif trader.ledger.balance < self.s.stake * (open_n + 1): + elif trader.ledger.available < self.s.stake * (1 if trader.ledger.account is not None else open_n + 1): reason = "баланса не хватает ещё на одну ставку" elif direction == 0: reason = wait @@ -1160,6 +1284,45 @@ class PaperTrader: import algo_hunter self.algo_config = algo_hunter.AlgoHunterConfig.load() if state_path else algo_hunter.AlgoHunterConfig() self.policy = self._make_policy() + self._restore_policy() + self.ledger.state_provider = self._policy_snapshot + self._last_checkpoint = 0.0 + + def _policy_snapshot(self) -> dict: + # Quotes and pending orders are deliberately not restored: the feeds must warm up again. + names = ("losses", "bump", "pause_until", "last_entry", "last_entry_price", "skip_pause", + "b_mean", "b_var", "b_count", "tick", "ticker") + policy = {name: getattr(self.policy, name) for name in names if hasattr(self.policy, name)} + export = getattr(self.policy, "export_state", None) + if export: + policy.update(export()) + return {"mode": self.settings.mode, "last_close": self.last_close, + "weights": dict(self.hint_settings.weights), "policy": policy} + + def _restore_policy(self) -> None: + state = self.ledger.policy_state + if state.get("mode") != self.settings.mode: + return + self.last_close = float(state.get("last_close", 0.0)) + self.hint_settings.weights.update(state.get("weights", {})) + policy = state.get("policy", {}) + for name in ("losses", "bump", "pause_until", "last_entry", "last_entry_price", "skip_pause", + "b_mean", "b_var", "b_count", "tick", "ticker"): + if name in policy and hasattr(self.policy, name): + setattr(self.policy, name, policy[name]) + restore = getattr(self.policy, "restore_state", None) + if restore: + restore(policy, self.ledger.position) + + def bind_account(self, account, owner: str) -> None: + self.ledger.bind_account(account, owner) + self.policy = self._make_policy() + self._restore_policy() + + def _checkpoint(self, now: float, force: bool = False) -> None: + if force or (self.ledger.positions and now - self._last_checkpoint >= 5): + self.ledger.save() + self._last_checkpoint = now def _make_policy(self): if self.settings.mode == "adaptive": @@ -1194,6 +1357,8 @@ class PaperTrader: handler = getattr(self.policy, "on_book", None) if handler is not None: handler(self, now, book, tick) + self.mark_account(book) + self._checkpoint(now) def on_leader(self, now: float, bid: float, ask: float) -> None: """Best quotes of the leader exchange (lead mode only).""" @@ -1218,19 +1383,28 @@ class PaperTrader: def on_tick(self, now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, tick: float) -> None: self.policy.on_tick(self, now, ticker, hint, book, tick) + self._checkpoint(now) def on_trade(self, trade: sh.Trade) -> None: + before = [(p.uid, p.qty, p.stop, p.target) for p in self.ledger.positions] self.policy.on_trade(self, trade) + after = [(p.uid, p.qty, p.stop, p.target) for p in self.ledger.positions] + if before != after: + self._checkpoint(trade.ts, force=True) def close(self, price: float, now: float, reason: str, fee_pct: float, utc: str | None = None, pos: Position | None = None) -> None: target = pos or self.ledger.position features = target.features if target else {} trade = self.ledger.close(price, now, reason, fee_pct, utc, pos) + if trade is None: + self.message = self.ledger.storage_error + return self.last_close = now self.message = f"Закрыта {trade.side} {trade.ticker}: {reason}, итог {trade.net_usd:+.4f}$" if isinstance(self.policy, AdaptivePolicy): self.policy.on_close(trade, features, now) + self.ledger.save() def close_now(self, book: sh.OrderBook, now: float, reason: str) -> None: if hasattr(self.policy, "order"): @@ -1241,9 +1415,12 @@ class PaperTrader: self.close(price, now, reason, TAKER, pos=pos) def reset(self) -> None: - self.ledger.reset() + if not self.ledger.reset(): + self.message = self.ledger.storage_error + return self.policy = self._make_policy() self.hint_settings.weights = dict(sh.DEFAULT_WEIGHTS) + self.ledger.save() def unrealized(self, book: sh.OrderBook) -> float: best_bid, best_ask = book.best() @@ -1251,9 +1428,25 @@ class PaperTrader: for pos in self.ledger.positions: price = best_bid if pos.side == "LONG" else best_ask if price is not None: - total += (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty + gross = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty + total += gross return total + def mark_account(self, book: sh.OrderBook) -> None: + """Call only for a fresh follower-book update, never for a UI/timer refresh.""" + if self.ledger.account is None: + return + bid, ask = book.best() + if bid is None or ask is None: + return + marks = {} + for pos in self.ledger.positions: + price = bid if pos.side == "LONG" else ask + marks[pos.uid] = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty - price * pos.qty * TAKER / 100 + self.ledger._position_marks = marks + self.ledger._unrealized = sum(marks.values()) + self.ledger.account.mark(self.ledger.account_owner, self.ledger._unrealized) + def summary(self) -> str: trades = self.ledger.trades n = len(trades) diff --git a/scripts/run_tests.py b/scripts/run_tests.py new file mode 100644 index 0000000..cc07c46 --- /dev/null +++ b/scripts/run_tests.py @@ -0,0 +1,34 @@ +"""Run offline tests. Loopback HTTP fixtures are allowed; exchange connections are forbidden.""" +from pathlib import Path +import os +import subprocess +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.dont_write_bytecode = True + + +def offline(event, args): + if event == 'socket.connect': + host = args[1][0] + elif event == 'socket.getaddrinfo': + host = args[0] + else: + return + if host not in (None, 'localhost', '::1') and not str(host).startswith('127.'): + raise RuntimeError('External network is disabled during tests') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + for suite in ('tests', 'meme_matcher/tests'): + result = subprocess.run([sys.executable, '-B', __file__, suite], cwd=ROOT) + if result.returncode: + sys.exit(result.returncode) + else: + os.chdir(ROOT) + sys.path.insert(0, str(ROOT)) + sys.addaudithook(offline) + suite = unittest.defaultTestLoader.discover(str(ROOT / sys.argv[1])) + sys.exit(not unittest.TextTestRunner(verbosity=1).run(suite).wasSuccessful()) diff --git a/server_control.ps1 b/server_control.ps1 index 86dc0d8..762322c 100644 --- a/server_control.ps1 +++ b/server_control.ps1 @@ -64,15 +64,21 @@ if ((Server-Processes) -and (Answers)) { Start-Process $Url exit 0 } -$haveVenv = Test-Path (Join-Path $Dir ".venv\Scripts\pythonw.exe") -$havePy = [bool](Get-Command py -ErrorAction SilentlyContinue) -if (-not $haveVenv -and -not $havePy) { - Write-Host "Python и библиотеки ещё не установлены — устанавливаю..." +$VenvPython = Join-Path $Dir ".venv\Scripts\python.exe" +$haveVenv = $false +if (Test-Path -LiteralPath $VenvPython) { + try { + & $VenvPython -B -c "import sys, websocket, numpy; sys.exit(0 if sys.version_info >= (3, 11) else 1)" 2>$null + $haveVenv = $LASTEXITCODE -eq 0 + } catch { $haveVenv = $false } +} +if (-not $haveVenv) { + Write-Host "Окружение отсутствует или повреждено — запускаю восстановление..." & powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Dir "setup.ps1") /install-only if ($LASTEXITCODE -ne 0) { exit 1 } } Write-Host "Запускаю сервер в фоне (без окон)..." -Start-Process -FilePath "wscript.exe" -ArgumentList "`"$(Join-Path $Dir 'web_sim_autostart.vbs')`"" -WorkingDirectory $Dir +Start-Process -FilePath "wscript.exe" -ArgumentList "`"$(Join-Path $Dir 'web_sim_autostart.vbs')`"" -WorkingDirectory $Dir -WindowStyle Hidden Set-Watchdog $true foreach ($i in 1..45) { if (Answers) { diff --git a/setup.ps1 b/setup.ps1 index 877198c..26f4026 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -15,8 +15,11 @@ $VenvPyw = Join-Path $Dir ".venv\Scripts\pythonw.exe" function Find-Python { foreach ($v in "3.13", "3.12", "3.11", "3.10") { try { - $exe = & py "-$v" -c "import sys; print(sys.executable)" 2>$null - if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() } + $exe = & py "-$v" -c "import sys, json; print(json.dumps(sys.executable, ensure_ascii=True))" 2>$null + if ($LASTEXITCODE -eq 0 -and $exe) { + $path = $exe | ConvertFrom-Json + if (Test-Path -LiteralPath $path -PathType Leaf) { return $path } + } } catch {} } foreach ($d in "Python313", "Python312", "Python311", "Python310") { @@ -24,8 +27,11 @@ function Find-Python { if (Test-Path $p) { return $p } } try { - $exe = & python -c "import sys; assert sys.version_info >= (3, 10); print(sys.executable)" 2>$null - if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() } + $exe = & python -c "import sys, json; assert sys.version_info >= (3, 10); print(json.dumps(sys.executable, ensure_ascii=True))" 2>$null + if ($LASTEXITCODE -eq 0 -and $exe) { + $path = $exe | ConvertFrom-Json + if (Test-Path -LiteralPath $path -PathType Leaf) { return $path } + } } catch {} return $null } diff --git a/tests/test_account_invariants.py b/tests/test_account_invariants.py new file mode 100644 index 0000000..c3fb8aa --- /dev/null +++ b/tests/test_account_invariants.py @@ -0,0 +1,83 @@ +"""Independent adversarial account checks: an outage must not erase a known loss.""" +import tempfile +import unittest +import json +from dataclasses import replace +from pathlib import Path +from unittest import mock + +import cross +from virtual_account import AccountError, VirtualAccount + + +class MissingQuoteAccountingTests(unittest.TestCase): + def setUp(self): + journal = mock.patch.object(cross.CrossEngine, "_journal") + journal.start() + self.addCleanup(journal.stop) + + def test_later_legacy_import_is_accounted_before_engine_starts(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + account = VirtualAccount(root / "wallet.json", 300) + cross.CrossEngine(root, start=False, account=account) + legacy = {"positions": [{"base": "XYZ", "opened": 1000, "qty": 100, + "spot_entry": 1, "fut_entry": 1.02, "entry_gap": 2, + "fees": .15, "funding": .02}]} + (root / "basis_bybit.json").write_text(json.dumps(legacy), encoding="utf-8") + again = cross.CrossEngine(root, start=False, account=account) + self.assertEqual(len(again.positions), 1) + self.assertEqual(len(account.restore("cross")["positions"]), 1) + self.assertAlmostEqual(account.view()["balance"], 300 - .15 + .02) + self.assertGreater(account.view()["reserved"], 200) + + def test_unaffordable_later_import_is_not_adopted_without_reserved_cash(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + account = VirtualAccount(root / "wallet.json", 10) + cross.CrossEngine(root, start=False, account=account) + legacy = {"positions": [{"base": "XYZ", "opened": 1000, "qty": 100, + "spot_entry": 1, "fut_entry": 1.02, "entry_gap": 2, "fees": .15}]} + path = root / "basis_bybit.json" + path.write_text(json.dumps(legacy), encoding="utf-8") + again = cross.CrossEngine(root, start=False, account=account) + self.assertTrue(again.account_error) + self.assertFalse(again.settings.running) + self.assertEqual(again.positions, []) + self.assertEqual(account.view()["balance"], 10) + self.assertEqual(account.view()["reserved"], 0) + self.assertEqual(json.loads(path.read_text(encoding="utf-8")), legacy) + + def test_missing_quote_and_settings_save_cannot_make_known_loss_withdrawable(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + account = VirtualAccount(root / "wallet.json", 300) + engine = cross.CrossEngine(root, start=False, account=account) + quote = cross.Link("XYZ", "Gate", "Binance", "XYZUSDT", "XYZUSDT", + .999, 1, 1.02, 1.021, 1e5, 1e5, 1e7, 1e7, .0001, 8) + engine.settings.amount = 100 + engine.links[quote.key] = quote + engine._entries(1000, [{"link": quote, "fits": True, "net": 1, "usual": .5}]) + engine.links[quote.key] = replace(quote, spot_bid=.5) + engine._mark_account(snapshot_fresh=True) + loss, free = account.view()["unrealized"], account.view()["free"] + self.assertLess(loss, -50) + self.assertLess(free, 50) + engine.links.clear() # one exchange vanished from the fresh market snapshot + self.assertEqual(engine.set_settings({"running": False}), "") + self.assertAlmostEqual(account.view()["unrealized"], loss) + self.assertAlmostEqual(account.view()["free"], free) + with self.assertRaises(AccountError): + account.adjust(-80, "must-not-withdraw-lost-money") + + # The loss is in the authoritative position snapshot, not just an in-memory aggregate. + restored_account = VirtualAccount(root / "wallet.json") + restored = cross.CrossEngine(root, start=False, account=restored_account) + self.assertAlmostEqual(restored.positions[0].paper_unrealized, loss) + restored.save() + self.assertAlmostEqual(restored_account.view()["unrealized"], loss) + self.assertIn("cross", restored_account.view()["stale"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_backtest.py b/tests/test_backtest.py index 4a5e61a..10d60a2 100644 --- a/tests/test_backtest.py +++ b/tests/test_backtest.py @@ -310,5 +310,47 @@ class CacheTests(unittest.TestCase): self.assertEqual(len(hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path)[0]), 5) +class RiskRegressionTests(unittest.TestCase): + def test_percentage_and_absolute_drawdown_have_independent_peaks(self): + rows = [[0, 90, 90, 90, 90], [MIN, 100, 100, 100, 100], + [2 * MIN, 100, 100, 80, 80], [3 * MIN, 80, 200, 80, 200], + [4 * MIN, 200, 200, 170, 170]] + result = run({'AAA': rows}, {'AAA': cfg(stake=100, take_profit=0, max_adds=0)}) + self.assertAlmostEqual(result['summary']['max_drawdown_usdt'], 30) + self.assertAlmostEqual(result['summary']['max_drawdown_pct'], 20) + + def test_mode_capital_floor_precedes_later_stop_with_fees(self): + fixture = ModeBacktestTests() + candles = fixture.breakout_rows([(102.5, 102.6, 90, 91, 10)]) + params = fixture.params(stake_pct=50, leverage=10, partial_r=0, partial_pct=0) + for fee in (0, 0.055): + with self.subTest(fee=fee): + result = hb.run_mode_backtest(candles, strategy.STRATEGY_BREAKOUT, params, + 100, fee_pct=fee, min_equity_pct=95) + self.assertTrue(result['summary']['equity_stop_triggered']) + self.assertAlmostEqual(result['summary']['equity_at_stop_usdt'], 95) + self.assertTrue(any(t['status'] != 'CLOSED' for t in result['trades'])) + + def test_position_stop_before_capital_floor_is_not_skipped(self): + fixture = ModeBacktestTests() + result = fixture.run_mode(fixture.breakout_rows([(102.5, 102.6, 90, 91, 10)]), + fixture.params(stake_pct=50, leverage=10), min_equity_pct=80) + self.assertFalse(result['summary']['equity_stop_triggered']) + self.assertTrue(result['trades'][0]['reason'].startswith('Стоп')) + + def test_short_floor_is_crossed_on_rising_price(self): + params = mode_params(strategy.STRATEGY_FADE, timeframe_min=60, min_growth_24h=30, + min_funding_pct=0, high_lookback_hours=6, pullback_pct=3, vwap_hours=6, atr_period=3, + stop_buffer_atr=0.5, max_stop_pct=30, trail_atr=0, take_profit_r=0, + partial_r=0, partial_pct=0, max_hold_hours=48, stake_pct=50, leverage=10) + rows = [(100, 101, 99, 100, 1)] * 20 + rows += [(p - 2, p + 2, p - 4, p, 5) for p in (110, 125, 140, 150, 146)] + rows += [(146, 147, 128, 130, 5), (130, 160, 129, 155, 5)] + result = hb.run_mode_backtest({'AAA': minute_rows(rows, tf_min=60)}, strategy.STRATEGY_FADE, + params, 100, fee_pct=0.055, min_equity_pct=95) + self.assertEqual(result['trades'][0]['side'], 'SHORT') + self.assertAlmostEqual(result['summary']['equity_at_stop_usdt'], 95) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_connections_remove.py b/tests/test_connections_remove.py index 5361d6c..7b97f46 100644 --- a/tests/test_connections_remove.py +++ b/tests/test_connections_remove.py @@ -56,16 +56,21 @@ class SimulatorRemoveTests(unittest.TestCase): engine = mock.Mock(conn={"x": 1}, lock=threading.RLock()) engine.name = "TRUMP: test" engine.paper.ledger.positions = [object(), object()] - engine.close.side_effect = lambda uid: calls.append(("close", uid)) + def close(uid): + calls.append(("close", uid)) + engine.paper.ledger.positions = [] + engine.close.side_effect = close + engine.mirror.ready_to_remove.return_value = True engine.shutdown.side_effect = lambda: calls.append("shutdown") sim = ws.Simulator.__new__(ws.Simulator) sim.engines, sim.lock = {"k": engine}, threading.Lock() + sim.removals = mock.Mock() with mock.patch.object(ws.lw, "remove_connection") as removed: message = sim.remove("k") removed.assert_called_once_with({"x": 1}) self.assertEqual(calls, [("close", None), "shutdown"]) self.assertNotIn("k", sim.engines) - self.assertFalse(engine.paper.settings.enabled) + engine.set_trading.assert_called_once_with(False) self.assertIn("закрыто позиций: 2", message) self.assertEqual(sim.remove("k"), "нет такой монеты") diff --git a/tests/test_cross_account.py b/tests/test_cross_account.py new file mode 100644 index 0000000..206fa62 --- /dev/null +++ b/tests/test_cross_account.py @@ -0,0 +1,217 @@ +"""Shared paper cash/reservation accounting, independent of live clients.""" +import json +import sys +import tempfile +import time +import unittest +from dataclasses import asdict, replace +from pathlib import Path +from unittest import mock + +sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)] +import cross +import virtual_account +from test_cross_real import link + + +class CrossAccountTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.directory = Path(self.tmp.name) + self.account = virtual_account.VirtualAccount(self.directory / "account.json", initial_balance=300) + self.e = cross.CrossEngine(self.directory, start=False, account=self.account) + self.e.settings.amount = 100 + self.e.settings.running = True + self.e.settings.max_hold_hours = self.e.settings.stop_widen_pct = 0 + self.e.settings.exit_hold_s = 0 + self.e.limits = {ex: 10 for ex in self.e.limits} + self.l = link() + self.e.links[self.l.key] = self.l + self.e.save() + + def enter(self, l=None): + l = l or self.l + self.e.links[l.key] = l + return self.e._entries(1000, [{"link": l, "fits": True, "net": 1.0, "usual": 0.5}]) + + def test_entry_reserves_both_legs_and_close_settles_cash_once(self): + self.assertTrue(self.enter()) + pos = self.e.positions[0] + metrics = self.account.view() + expected_reserve = 100 + max(102 * self.e.FUT_NEED, cross.equity_for(self.e.settings.min_liq_pct, 102)) + self.assertAlmostEqual(metrics["balance"], 300 - pos.fees) + self.assertAlmostEqual(metrics["reserved"], expected_reserve) + self.assertEqual(len(self.account.restore("cross")["positions"]), 1) + self.assertTrue(self.e._close(pos, self.l, 1001, "test")) + net = self.e.trades[0].net + self.assertAlmostEqual(self.account.view()["balance"], 300 + net) + self.assertEqual(self.account.view()["reserved"], 0) + self.e.save() + 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(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, []) + self.assertEqual(self.account.view()["balance"], 300) + self.assertFalse(self.enter()) + self.assertEqual(timer.call_count, 1) + _, callback = timer.call_args.args + self.assertTrue(callback(*timer.call_args.kwargs["args"])) + pos = self.e.positions[0] + self.assertAlmostEqual(self.account.view()["balance"], 300 - pos.fees) + self.assertGreater(self.account.view()["reserved"], 200) + self.assertTrue(self.e._schedule_paper_close(pos.uid, "test")) + self.assertFalse(self.e._schedule_paper_close(pos.uid, "test")) + _, callback = timer.call_args.args + self.assertTrue(callback(*timer.call_args.kwargs["args"])) + self.assertEqual(self.account.view()["reserved"], 0) + 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(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) + _, callback = timer.call_args.args + self.assertFalse(callback(*timer.call_args.kwargs["args"])) + self.assertEqual(self.e.positions, []) + self.assertEqual(self.account.view()["balance"], 300) + self.assertEqual(self.account.view()["reserved"], 150) + self.assertFalse(self.e.settings.running) + + def test_other_owner_reservation_blocks_entry_without_cash_or_state_change(self): + self.account.commit("simulator:other", {}, cash_total=0, reserved=150) + before = self.account.view()["balance"] + self.assertFalse(self.enter()) + self.assertEqual(self.e.positions, []) + self.assertEqual(self.e.cash_total, 0) + self.assertEqual(self.account.restore("cross")["positions"], []) + self.assertEqual(self.account.view()["balance"], before) + self.assertEqual(self.account.view()["reserved"], 150) + self.assertFalse(self.e.settings.running) + self.assertIn("Недостаточно", self.e.account_error) + + def test_top_up_and_explicit_start_clear_rejected_entry(self): + self.account.commit("simulator:other", {}, cash_total=0, reserved=150) + self.assertFalse(self.enter()) + self.account.adjust(100, "topup-test-1") + self.assertEqual(self.e.set_settings({"running": True}), "") + self.assertEqual(self.e.account_error, "") + self.assertTrue(self.enter()) + + def test_funding_is_credited_once_and_not_credited_again_at_close(self): + self.enter() + pos = self.e.positions[0] + when = pos.next_funding + entry_balance = self.account.view()["balance"] + self.e._check_exits(when) + self.e.save(event="funding") + funding = pos.funding + self.assertGreater(funding, 0) + self.assertAlmostEqual(self.account.view()["balance"], entry_balance + funding) + self.e._check_exits(when) + self.e.save() + self.assertAlmostEqual(self.account.view()["balance"], entry_balance + funding) + self.e._close(pos, self.l, when + 1, "test") + self.assertAlmostEqual(self.account.view()["balance"], 300 + self.e.trades[0].net) + + def test_failed_account_write_rolls_back_entry_and_close(self): + with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")): + self.assertFalse(self.enter()) + self.assertEqual(self.e.positions, []) + self.assertEqual(self.account.view()["balance"], 300) + self.e.set_settings({"running": True}) + self.enter() + before = self.account.view() + with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")): + self.assertFalse(self.e._close(self.e.positions[0], self.l, 1001, "test")) + self.assertEqual(len(self.e.positions), 1) + self.assertEqual(self.e.trades, []) + self.assertEqual(self.account.view()["balance"], before["balance"]) + self.assertEqual(self.account.view()["reserved"], before["reserved"]) + + def test_restart_uses_authoritative_account_snapshot_not_legacy_file(self): + self.enter() + before = self.account.view() + self.e.file.write_text(json.dumps({"positions": [], "cash_total": 100000}), encoding="utf-8") + account = virtual_account.VirtualAccount(self.directory / "account.json") + again = cross.CrossEngine(self.directory, start=False, account=account) + self.assertEqual(len(again.positions), 1) + self.assertEqual(again.cash_total, self.e.cash_total) + self.assertEqual(account.view()["balance"], before["balance"]) + self.assertEqual(account.view()["reserved"], before["reserved"]) + + def test_reset_preserves_cash_and_cannot_erase_reserved_positions(self): + self.enter() + self.assertIn("сначала закройте", self.e.reset()) + self.assertEqual(len(self.e.positions), 1) + self.e._close(self.e.positions[0], self.l, 1001, "test") + before = self.account.view()["balance"] + cash = self.e.cash_total + self.assertEqual(self.e.reset(), "статистика сброшена") + self.assertEqual(self.e.trades, []) + self.assertEqual(self.e.cash_total, cash) + self.assertEqual(self.account.view()["balance"], before) + again = cross.CrossEngine(self.directory, start=False, account=self.account) + self.assertEqual(again.cash_total, cash) + + def test_one_fresh_link_cannot_refresh_all_open_positions(self): + self.account.adjust(1000, "freshness-deposit") + self.enter() + other = replace(self.l, base="OTHER", spot_symbol="OTHERUSDT", fut_symbol="OTHERUSDT") + self.enter(other) + self.account.marks["cross"] = (self.e._unrealized(), 0) + self.e.updated = 0 + self.e.fast_seen = {self.l.key: time.time()} + self.e._mark_account() + self.e.save() # a settings/checkpoint save is not a fresh price + self.assertIn("cross", self.account.view()["stale"]) + self.e.fast_seen[other.key] = time.time() + self.e._mark_account() + self.assertNotIn("cross", self.account.view()["stale"]) + + def test_margin_setting_does_not_release_existing_position_collateral(self): + self.account.adjust(1000, "frozen-margin-deposit") + self.e.set_settings({"min_liq_pct": 300}) + self.enter() + held = self.account.view()["reserved"] + self.assertGreater(held, 400) + self.assertEqual(self.e.positions[0].paper_reserve, held) + self.assertEqual(self.e.set_settings({"min_liq_pct": 0}), "") + self.assertEqual(self.account.view()["reserved"], held) + again = cross.CrossEngine(self.directory, start=False, account=self.account) + self.assertEqual(again._reserved(), held) + self.assertEqual(again.positions[0].paper_reserve, held) + other = replace(self.l, base="OTHER", spot_symbol="OTHERUSDT", fut_symbol="OTHERUSDT") + self.enter(other) + self.assertAlmostEqual(self.account.view()["reserved"] - held, 100 + 102 * self.e.FUT_NEED) + + def test_first_legacy_migration_imports_open_costs_without_closed_history(self): + directory = self.directory / "legacy" + directory.mkdir() + old = cross.CrossEngine(directory, start=False) + old.settings.amount = 100 + old.links[self.l.key] = self.l + old._entries(1000, [{"link": self.l, "fits": True, "net": 1.0, "usual": 0.5}]) + old.positions[0].funding = 0.25 + old.save() + account = virtual_account.VirtualAccount(directory / "account.json", initial_balance=10) + again = cross.CrossEngine(directory, start=False, account=account) + pos = again.positions[0] + self.assertAlmostEqual(account.view()["balance"], 10 + pos.funding - pos.fees) + self.assertGreater(account.view()["deficit"], 0) + self.assertEqual(len(again.positions), 1) + before = account.view()["balance"] + cross.CrossEngine(directory, start=False, account=account) + self.assertEqual(account.view()["balance"], before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cross_execution_safety.py b/tests/test_cross_execution_safety.py new file mode 100644 index 0000000..d8b1172 --- /dev/null +++ b/tests/test_cross_execution_safety.py @@ -0,0 +1,203 @@ +"""Real execution reconciliation with fake clients only; no exchange requests.""" +import json +import sys +import unittest +from dataclasses import asdict, replace +from pathlib import Path +from unittest import mock + +sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)] +import cross +import live +import test_cross_real + + +class ExecutionSafetyTests(unittest.TestCase): + def setUp(self): + self.fixture = test_cross_real.CrossRealTests() + self.fixture.setUp() + self.addCleanup(self.fixture.tearDown) + self.e, self.a, self.b = self.fixture.e, self.fixture.a, self.fixture.b + + def open_partial(self): + def buy(base, usdt): + self.a.spot_balance = 10.0 + return live.Fill(10.0, 1.0, 0.01, "partial") + self.a.spot_buy = buy + self.e.step(1000) + self.fixture.run_jobs() + + def restart(self): + again = cross.CrossEngine(Path(self.fixture.dir.name), start=False, real=True) + again.client_for = self.e.client_for + return again + + def open_ss(self): + link = replace(test_cross_real.link(), ss=True) + self.e.links = {link.key: link} + self.b.spot_balance = 200.0 + self.e._real_open_ss(link, 0.5, 100.0) + return self.e.positions[0] + + def test_partial_spot_fill_unwinds_both_legs(self): + self.open_partial() + self.assertEqual(self.b.position, 0) + self.assertEqual(self.a.spot_balance, 0) + self.assertEqual(self.e.positions, []) + self.assertIn("частичный хедж", self.e.trades[0].reason) + + def test_partial_hedge_intent_is_on_disk_before_unwind_order(self): + original = self.b.fut_order + def order(symbol, side, coins, reduce_only, **kwargs): + if reduce_only: + saved = json.loads(self.e.file.read_text(encoding="utf-8")) + self.assertEqual(saved["positions"][0]["closing"], "hedge_mismatch") + return original(symbol, side, coins, reduce_only, **kwargs) + self.b.fut_order = order + self.open_partial() + self.assertEqual(self.e.positions, []) + + def test_failed_entry_handoff_retains_on_disk_intent_without_replaying_entry(self): + original = cross.atomic_write_json + def write(path, data): + if data.get("positions") and not data.get("pending"): + raise OSError("handoff write failed") + return original(path, data) + with mock.patch.object(cross, "atomic_write_json", side_effect=write): + self.e.step(1000) + self.fixture.run_jobs() + saved = json.loads(self.e.file.read_text(encoding="utf-8")) + self.assertEqual(saved["pending"]["XYZ"]["phase"], "hedge_confirmed") + a_count, b_count = len(self.a.orders), len(self.b.orders) + again = self.restart() + again.step(1001) + while not again.jobs.empty(): + again.do_job(again.jobs.get()) + self.assertEqual((len(self.a.orders), len(self.b.orders)), (a_count, b_count)) + self.assertEqual(len(again.positions), 1) + self.assertEqual(again.recover, {}) + + def test_partial_hedge_close_rejection_survives_restart_without_listing(self): + self.b.fail_close = 1 + self.open_partial() + saved = json.loads(self.e.file.read_text(encoding="utf-8")) + self.assertEqual(saved["positions"][0]["closing"], "hedge_mismatch") + self.assertEqual(self.b.position, -99) + again = self.restart() + again.positions[0].retry_at = 0 + again.step(1001) + while not again.jobs.empty(): + again.do_job(again.jobs.get()) + self.assertEqual(again.positions, []) + self.assertEqual(self.b.position, 0) + self.assertEqual(self.a.spot_balance, 0) + + def test_restart_between_confirmed_partial_fill_and_position_unwinds(self): + link = test_cross_real.link() + self.b.position, self.a.spot_balance = -99.0, 10.0 + self.e.pending["XYZ"] = {"phase": "hedge_confirmed", "link": asdict(link), "key": link.key, + "coins": 99.0, "shorted": 99.0, "usual": 0.5, + "buy": asdict(live.Fill(10, 1, 0.01, "partial")), + "fut_price": 1.02, "fut_fee": 0.05} + self.e.save() + again = self.restart() + again.step(1001) + while not again.jobs.empty(): + again.do_job(again.jobs.get()) + self.assertEqual(self.b.position, 0) + self.assertEqual(self.a.spot_balance, 0) + self.assertEqual(again.positions, []) + self.assertEqual(again.recover, {}) + + def test_unknown_ss_buy_never_sells_a_or_repeats_buy_after_restart(self): + pos = self.open_ss() + before = self.a.spot_balance + self.b.spot_buy = mock.Mock(side_effect=live.LiveError("lost response", sent=True, order_id="lost")) + self.e._real_close(pos.uid, "test") + self.assertEqual(pos.close_buy["phase"], "unknown") + self.assertEqual(self.a.spot_balance, before) + self.assertEqual(len(self.e.positions), 1) + self.assertEqual(self.e.trades, []) + other = replace(test_cross_real.link(), base="OTHER") + self.assertFalse(self.e._entries(2000, [{"link": other, "fits": True, "net": 1.0, "usual": 0.5}])) + self.assertTrue(self.e.jobs.empty()) + again = self.restart() + # Even a later balance increase alone is not proof that this particular order completed. + self.b.spot_balance += pos.qty + again._real_close(pos.uid, "retry") + self.assertEqual(self.b.spot_buy.call_count, 1) + self.assertEqual(self.a.spot_balance, before) + self.assertIn("ручная сверка", again.positions[0].error) + + def test_ss_buy_intent_is_durable_before_submit(self): + pos = self.open_ss() + original = self.b.spot_buy + def buy(base, usdt): + saved = json.loads(self.e.file.read_text(encoding="utf-8")) + self.assertEqual(saved["positions"][0]["close_buy"]["phase"], "submitted") + return original(base, usdt) + self.b.spot_buy = buy + self.e._real_close(pos.uid, "test") + self.assertEqual(self.e.positions, []) + self.assertGreaterEqual(self.b.spot_balance, 200) + + def test_ss_buy_not_sent_when_intent_save_fails(self): + pos = self.open_ss() + self.b.spot_buy = mock.Mock() + with mock.patch.object(self.e, "save", side_effect=OSError("disk full")): + with self.assertRaises(OSError): + self.e._real_close(pos.uid, "test") + self.b.spot_buy.assert_not_called() + self.assertEqual(pos.close_buy, {}) + + def test_ss_buy_response_checkpoint_failure_cannot_replay_after_restart(self): + pos = self.open_ss() + original = cross.atomic_write_json + original_buy = self.b.spot_buy + self.b.spot_buy = mock.Mock(side_effect=original_buy) + def write(path, data): + if any(p.get("close_buy", {}).get("phase") == "confirmed" for p in data.get("positions", [])): + raise OSError("fill checkpoint failed") + return original(path, data) + with mock.patch.object(cross, "atomic_write_json", side_effect=write): + with self.assertRaises(OSError): + self.e._real_close(pos.uid, "test") + saved = json.loads(self.e.file.read_text(encoding="utf-8")) + self.assertEqual(saved["positions"][0]["close_buy"]["phase"], "submitted") + self.assertGreater(self.b.spot_balance, 200) + again = self.restart() + again._real_close(pos.uid, "retry") + self.assertEqual(self.b.spot_buy.call_count, 1) + self.assertGreater(self.a.spot_balance, 0) + self.assertIn("ручная сверка", again.positions[0].error) + + def test_partial_ss_repurchase_keeps_a_and_does_not_repeat(self): + pos = self.open_ss() + before = self.a.spot_balance + def buy(base, usdt): + self.b.spot_balance += 5 + return live.Fill(5, 1.02, 0.0051, "partial") + self.b.spot_buy = mock.Mock(side_effect=buy) + self.e._real_close(pos.uid, "test") + again = self.restart() + again._real_close(pos.uid, "retry") + self.assertEqual(self.b.spot_buy.call_count, 1) + self.assertEqual(self.a.spot_balance, before) + self.assertEqual(len(again.positions), 1) + + def test_confirmed_ss_buy_waits_for_balance_without_duplicate_order(self): + pos = self.open_ss() + before = self.a.spot_balance + self.b.spot_buy = mock.Mock(return_value=live.Fill(pos.qty * 1.01, 1.02, 0.1, "confirmed")) + self.e._real_close(pos.uid, "test") + self.assertEqual(self.a.spot_balance, before) + self.b.spot_balance += pos.qty + again = self.restart() + again._real_close(pos.uid, "retry") + self.assertEqual(self.b.spot_buy.call_count, 1) + self.assertEqual(again.positions, []) + self.assertEqual(self.a.spot_balance, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cross_recovery.py b/tests/test_cross_recovery.py new file mode 100644 index 0000000..4338dc8 --- /dev/null +++ b/tests/test_cross_recovery.py @@ -0,0 +1,95 @@ +"""Durable recovery of rejected/partial rollback and uncertain entry cancellation.""" +import json +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)] +import cross +import live +import test_cross_real + + +class RecoveryTests(unittest.TestCase): + def setUp(self): + self.fixture = test_cross_real.CrossRealTests() + self.fixture.setUp() + self.addCleanup(self.fixture.tearDown) + self.e, self.a, self.b = self.fixture.e, self.fixture.a, self.fixture.b + + def open(self): + self.e.step(1000) + self.fixture.run_jobs() + + def recover(self): + info = self.e.recover['XYZ'] + info['retry_at'] = 0 + self.e.step(1001) + self.fixture.run_jobs() + + def test_failed_and_partial_rollback_remain_durable_until_confirmed_flat(self): + self.a.spot_buy = mock.Mock(side_effect=live.LiveError('rejected')) + self.b.fail_close = 1 + self.open() + self.assertEqual(self.b.position, -99) + self.assertEqual(self.e.recover['XYZ']['phase'], 'rollback') + saved = json.loads(self.e.file.read_text(encoding='utf-8')) + self.assertEqual(saved['pending']['XYZ']['phase'], 'rollback') + self.b.partial_close = 5 + self.recover() + self.assertEqual(self.b.position, -5) + self.assertIn('XYZ', self.e.recover) + self.recover() + self.assertEqual(self.b.position, 0) + self.assertEqual(self.e.recover, {}) + self.assertEqual(self.e.pending, {}) + + def test_failed_cancel_blocks_entries_and_late_fill_is_closed_after_restart(self): + self.e.settings.entry_limit, self.e.settings.limit_hold_s = True, 0 + self.b.limit_fill = 0 + cancel = self.b.fut_cancel + self.b.fut_cancel = mock.Mock(side_effect=live.LiveError('timeout', sent=True)) + self.open() + self.assertTrue(self.b.limits['L1']['open']) + self.assertEqual(self.e.recover['XYZ']['order_id'], 'L1') + self.assertEqual(self.a.orders, []) + self.e.step(2000) + self.assertTrue(self.e.jobs.empty()) + self.b.fill_take_profit('L1') # fake exchange fills the still-working short + self.b.fut_cancel = cancel + again = cross.CrossEngine(Path(self.fixture.dir.name), start=False, real=True) + again.client_for = self.e.client_for + again.recover['XYZ']['retry_at'] = 0 + # No current listing is needed: the intent contains its instrument snapshot. + again.step(2001) + while not again.jobs.empty(): + again.do_job(again.jobs.get()) + self.assertEqual(self.b.position, 0) + self.assertEqual(again.recover, {}) + self.assertEqual(again.pending, {}) + + def test_unknown_submit_without_id_is_not_declared_absent_when_flat(self): + self.e.settings.entry_limit = True + self.b.fut_limit = mock.Mock(side_effect=live.LiveError('lost response', sent=True)) + self.open() + self.assertIn('XYZ', self.e.recover) + self.recover() + self.assertIn('XYZ', self.e.recover) + self.assertEqual(self.b.fut_limit.call_count, 1) + self.assertIn('сверка', self.e.view()['real_pause']) + + def test_no_order_when_intent_cannot_be_saved(self): + with mock.patch.object(cross, 'atomic_write_json', side_effect=OSError('disk full')): + # Queue directly: failing the pre-order durable intent must prevent every order. + self.e.do_job(('open', next(iter(self.e.links.values())), 0.5, 100)) + self.assertEqual(self.a.orders + self.b.orders, []) + + def test_successful_entry_is_handed_off_without_pending_recovery(self): + self.open() + self.assertEqual(len(self.e.positions), 1) + self.assertEqual(self.e.recover, {}) + saved = json.loads(self.e.file.read_text(encoding='utf-8')) + self.assertEqual(saved['pending'], {}) + self.assertEqual(len(saved['positions']), 1) diff --git a/tests/test_live_uncertainty.py b/tests/test_live_uncertainty.py new file mode 100644 index 0000000..95d1fcb --- /dev/null +++ b/tests/test_live_uncertainty.py @@ -0,0 +1,30 @@ +"""Ambiguous mutating HTTP responses must trigger reconciliation, not a fresh entry.""" +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import live + + +class UncertainResponseTests(unittest.TestCase): + def request(self, method, status, body): + response = mock.Mock(status=status, will_close=True) + response.read.return_value = body + response.getheader.return_value = 'close' + connection = mock.Mock() + connection.getresponse.return_value = response + with mock.patch.object(live, '_take', return_value=(connection, False)): + with self.assertRaises(live.LiveError) as error: + live._http(method, 'https://exchange.invalid/order') + return error.exception + + def test_server_error_on_submit_is_uncertain(self): + self.assertTrue(self.request('POST', 503, b'unavailable').sent) + self.assertTrue(self.request('DELETE', 500, b'error').sent) + self.assertFalse(self.request('GET', 503, b'unavailable').sent) + self.assertFalse(self.request('POST', 400, b'rejected').sent) + + def test_unreadable_success_response_is_uncertain(self): + self.assertTrue(self.request('POST', 200, b'{truncated').sent) diff --git a/tests/test_mirror_recovery.py b/tests/test_mirror_recovery.py new file mode 100644 index 0000000..b2486c8 --- /dev/null +++ b/tests/test_mirror_recovery.py @@ -0,0 +1,96 @@ +"""Crash windows and filesystem failures must never cause a second entry.""" +import json +import sys +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)] +import real_mirror +from test_real import FakeClient + + +class MirrorRecoveryTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.client = FakeClient(price=1) + self.settings = {'coins': {'k': {'on': True}}, 'exchange_tpsl': True} + self.threads = mock.patch.object(real_mirror.threading.Thread, 'start') + self.threads.start() + self.addCleanup(self.threads.stop) + self.journal = mock.patch.object(real_mirror, 'journal') + self.journal.start() + self.addCleanup(self.journal.stop) + + def mirror(self): + return real_mirror.FuturesMirror('k', 'X', 'bybit', 'XUSDT', Path(self.tmp.name), + client_for=lambda ex: self.client, settings=lambda: self.settings) + + def prepare(self, m): + m.hook('open', SimpleNamespace(uid=1, side='LONG', qty=10, entry=1, target=1.02)) + + def test_restart_before_submission_never_replays_entry(self): + m = self.mirror() + self.prepare(m) + self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'prepared') + again = self.mirror() + again._recover_open() + self.assertEqual(self.client.orders, []) + self.assertIsNone(again.position) + + def test_crash_after_exchange_accepts_is_contained_and_never_replayed(self): + m = self.mirror() + self.prepare(m) + order = self.client.fut_order + def crash(*args, **kwargs): + self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'submitted') + order(*args, **kwargs) + raise SystemExit('power loss') + with mock.patch.object(self.client, 'fut_order', side_effect=crash): + with self.assertRaises(SystemExit): + m._open() + again = self.mirror() + again._recover_open() + self.assertEqual(self.client.position, 0) + self.assertTrue(again.gate()) + again._close('paper closed') + self.assertEqual(again.state, 'recover') + self.prepare(again) + self.assertEqual(sum(not o[3] for o in self.client.orders), 1) + + def test_accepted_fill_is_saved_before_take_profit_request(self): + m = self.mirror() + self.prepare(m) + def crash(*args): + saved = json.loads(m.file.read_text())['position'] + self.assertEqual(saved['phase'], 'filled') + self.assertEqual(saved['coins'], 10) + raise SystemExit('power loss') + with mock.patch.object(self.client, 'fut_take_profit', side_effect=crash): + with self.assertRaises(SystemExit): + m._open() + again = self.mirror() + again._close('restart') + self.assertEqual(self.client.position, 0) + self.assertIsNone(again.position) + + def test_failed_persistence_blocks_order_and_is_visible(self): + m = self.mirror() + with mock.patch.object(real_mirror, 'atomic_write_json', side_effect=OSError('disk full')): + self.prepare(m) + self.assertEqual(self.client.orders, []) + self.assertTrue(m.jobs.empty()) + self.assertIn('disk full', m.gate()) + m._watch() + self.assertIsNone(m.position) + + def test_corrupt_saved_state_blocks_new_entries(self): + Path(self.tmp.name, 'real_positions_k.json').write_text('{broken', encoding='utf-8') + m = self.mirror() + self.prepare(m) + self.assertEqual(m.state, 'blocked') + self.assertTrue(m.gate()) + self.assertEqual(self.client.orders, []) 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/tests/test_paper_recovery_account.py b/tests/test_paper_recovery_account.py new file mode 100644 index 0000000..090b38b --- /dev/null +++ b/tests/test_paper_recovery_account.py @@ -0,0 +1,224 @@ +"""Offline regression cases for recovery, shared collateral and partial paper fills.""" +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import algo_hunter as ah +import scalp_hint as sh +import scalp_paper as sp +from virtual_account import VirtualAccount + + +def trader(folder=None, mode="simple", stake=6.0, leverage=1.0): + paths = (Path(folder) / "paper.json", Path(folder) / "trades.csv") if folder else (None, None) + return sp.PaperTrader(sp.PaperSettings(mode=mode, stake=stake, leverage=leverage), sh.HintSettings(), *paths) + + +def open_position(t, price=100, now=100): + return t.ledger.open("AAA", "LONG", price, now, 0.1, 110, 90, price) + + +def book(bid=100, ask=101): + result = sh.OrderBook() + result.bids, result.asks = {bid: 1000}, {ask: 1000} + return result + + +class RecoveryTests(unittest.TestCase): + def test_corrupt_snapshot_is_not_overwritten_by_new_entry(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "paper.json" + path.write_text('{"balance": 299, "positions": [', encoding="utf-8") + previous = path.read_bytes() + t = trader(folder) + self.assertIsNone(open_position(t)) + self.assertEqual(path.read_bytes(), previous) + self.assertEqual(t.balance, 300) + self.assertIn("восстановить", t.ledger.storage_error) + + def test_open_position_survives_restart_and_closes_once(self): + with tempfile.TemporaryDirectory() as folder: + first = trader(folder) + position = open_position(first) + restored = trader(folder) + self.assertEqual(restored.position, position) + restored.close(105, 110, "manual", 0.1) + again = trader(folder) + self.assertIsNone(again.position) + self.assertEqual(len(again.trades), 1) + self.assertAlmostEqual(again.balance, 300 + again.trades[0].net_usd) + next_position = open_position(again, now=120) + self.assertGreater(next_position.uid, position.uid) + + def test_atomic_write_failure_preserves_snapshot_and_memory(self): + with tempfile.TemporaryDirectory() as folder: + t = trader(folder) + open_position(t) + path = Path(folder) / "paper.json" + previous = path.read_bytes() + previous_balance = t.balance + with patch("scalp_paper.atomic_write_json", side_effect=OSError("disk full")): + t.close(105, 110, "manual", 0.1) + self.assertEqual(path.read_bytes(), previous) + self.assertIsNotNone(t.position) + self.assertEqual(t.trades, []) + self.assertEqual(t.balance, previous_balance) + self.assertIn("disk full", t.message) + + def test_hunter_restores_exit_levels_and_risk_guard(self): + with tempfile.TemporaryDirectory() as folder: + t = trader(folder, mode="algo_hunter") + policy = t.policy + policy.tick, policy.ticker = 1.0, "AAA" + policy.guard.daily_pnl = -7.5 + policy.guard.pause_until = 1000 + policy.guard.disabled_reason = "risk test" + policy.order = ah.HunterOrder("LONG", 100, 6, 99, 99, "test", + ah.AlgoSignature("bid", [100], [10], .9, 99, ["test"], 10), ahead=0) + policy._fill(t, 100, 2) + t.last_close = 80 + t.ledger.save() + restored = trader(folder, mode="algo_hunter") + self.assertEqual(restored.position.qty, .02) + self.assertEqual(restored.policy.stop, t.policy.stop) + self.assertEqual(restored.policy.target, t.policy.target) + self.assertEqual(restored.policy.filled_at, 100) + self.assertEqual(restored.last_close, 80) + self.assertEqual(restored.policy.guard.daily_pnl, -7.5) + self.assertEqual(restored.policy.guard.pause_until, 1000) + self.assertEqual(restored.policy.guard.disabled_reason, "risk test") + self.assertIsNone(restored.policy.order) + restored.policy._close(restored, 101, 110, "manual", 0.1) + self.assertIsNone(restored.position) + + +class PartialFillTests(unittest.TestCase): + def pending(self, ahead=100): + t = trader(mode="algo_hunter", stake=20) + t.policy.tick, t.policy.ticker = 1, "AAA" + signature = ah.AlgoSignature("bid", [100], [ahead], .9, 99, ["test"], ahead) + t.policy.order = ah.HunterOrder("LONG", 100, 20, 99, 99, "test", signature, ahead=ahead) + return t + + def test_trade_equal_to_queue_does_not_fill_us(self): + t = self.pending() + t.on_trade(sh.Trade(100, 100, 100, "Sell")) + self.assertIsNone(t.position) + self.assertEqual(t.policy.order.ahead, 0) + t.on_trade(sh.Trade(101, 100, 3, "Sell")) + self.assertAlmostEqual(t.position.qty * t.position.entry, 3) + self.assertAlmostEqual(t.position.fee_in, 3 * sh.MAKER_FEE_PCT / 100) + self.assertEqual(t.position.margin, 3) + self.assertIsNone(t.policy.order) # conservative cancellation of unfilled remainder + + def test_only_volume_after_queue_can_fill(self): + t = self.pending() + t.on_trade(sh.Trade(100, 100, 102, "Sell")) + self.assertAlmostEqual(t.position.qty * t.position.entry, 2) + self.assertEqual(t.policy.entry_order.size_usd, 2) + + def test_fill_cannot_exceed_requested_size(self): + t = self.pending() + t.on_trade(sh.Trade(100, 100, 200, "Sell")) + self.assertAlmostEqual(t.position.qty * t.position.entry, 20) + + def test_wrong_trade_side_does_not_consume_queue(self): + t = self.pending() + t.on_trade(sh.Trade(100, 100, 200, "Buy")) + self.assertIsNone(t.position) + self.assertEqual(t.policy.order.ahead, 100) + + +class SharedAccountTests(unittest.TestCase): + def test_common_top_up_unblocks_policy_despite_old_local_balance(self): + with tempfile.TemporaryDirectory() as folder: + account = VirtualAccount(Path(folder) / "account.json", 1) + t = trader() + t.ledger.balance = 1 + t.bind_account(account, "coin") + hint = sh.Hint("LONG", "test", .9, target=110) + t.on_tick(100, "AAA", hint, book(), 1) + self.assertIsNone(t.position) + account.adjust(10, "test-top-up") + t.on_tick(101, "AAA", hint, book(), 1) + self.assertIsNotNone(t.position) + self.assertLess(t.balance, 1) # accounting baseline is separate from the common spending limit + + def test_two_coins_share_capital_and_close_releases_margin(self): + with tempfile.TemporaryDirectory() as folder: + account = VirtualAccount(Path(folder) / "account.json", 10) + first, second = trader(), trader() + first.bind_account(account, "first") + second.bind_account(account, "second") + self.assertIsNotNone(open_position(first)) + first.mark_account(book()) + self.assertIsNone(open_position(second)) + self.assertIn("Недостаточно", second.ledger.storage_error) + self.assertEqual(second.ledger.positions, []) + self.assertEqual(account.view()["reserved"], 6) + first.close(100, 110, "manual", 0.1) + self.assertEqual(account.view()["reserved"], 0) + self.assertIsNotNone(open_position(second)) + self.assertAlmostEqual(account.view()["balance"], 10 - .006 * 3) + + def test_failed_shared_commit_does_not_trigger_hooks_or_change_exposure(self): + with tempfile.TemporaryDirectory() as folder: + account = VirtualAccount(Path(folder) / "account.json", 10) + t = trader() + t.bind_account(account, "coin") + events = [] + t.ledger.hooks.append(lambda event, pos: events.append(event)) + with patch("virtual_account.atomic_write_json", side_effect=OSError("disk full")): + self.assertIsNone(open_position(t)) + self.assertEqual(events, []) + self.assertEqual(t.balance, 300) + self.assertEqual(account.view()["reserved"], 0) + self.assertEqual(account.view()["balance"], 10) + + def test_account_snapshot_restores_position_and_is_idempotent(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "account.json" + account = VirtualAccount(path, 10) + t = trader() + t.bind_account(account, "coin") + position = open_position(t) + balance = account.view()["balance"] + restarted = VirtualAccount(path, 999) + again = trader() + again.bind_account(restarted, "coin") + again.ledger.save() + self.assertEqual(again.position, position) + self.assertEqual(restarted.view()["balance"], balance) + self.assertEqual(restarted.view()["reserved"], 6) + + def test_reset_never_erases_shared_position_or_creates_money(self): + with tempfile.TemporaryDirectory() as folder: + account = VirtualAccount(Path(folder) / "account.json", 10) + t = trader(leverage=2) + t.bind_account(account, "coin") + position = open_position(t) + t.settings.leverage = 20 + t.ledger.save() + self.assertEqual(account.view()["reserved"], 6) + self.assertFalse(t.ledger.reset()) + self.assertEqual(t.position, position) + t.close(101, 110, "manual", .1) + previous = account.view()["balance"] + self.assertTrue(t.ledger.reset()) + self.assertEqual(account.view()["balance"], previous) + + def test_migration_debits_only_fees_of_existing_positions(self): + with tempfile.TemporaryDirectory() as folder: + account = VirtualAccount(Path(folder) / "account.json", 10) + t = trader() + t.ledger.balance = 321 # historic results do not seed the new common account + position = open_position(t) + t.bind_account(account, "coin") + self.assertAlmostEqual(account.view()["balance"], 10 - position.fee_in) + self.assertEqual(account.view()["reserved"], 6) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_persistence.py b/tests/test_persistence.py new file mode 100644 index 0000000..3183f1a --- /dev/null +++ b/tests/test_persistence.py @@ -0,0 +1,29 @@ +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import persistence + + +class AtomicSnapshotTests(unittest.TestCase): + def test_failed_replace_keeps_previous_snapshot_and_cleans_temporary_file(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'state.json' + persistence.atomic_write_json(path, {'position': 1}) + with mock.patch.object(persistence.os, 'replace', side_effect=OSError('disk error')): + with self.assertRaises(OSError): + persistence.atomic_write_json(path, {'position': 2}) + self.assertEqual(json.loads(path.read_text()), {'position': 1}) + self.assertEqual(list(Path(directory).iterdir()), [path]) + + def test_invalid_numbers_do_not_destroy_existing_snapshot(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'state.json' + persistence.atomic_write_json(path, {'balance': 100}) + with self.assertRaises(ValueError): + persistence.atomic_write_json(path, {'balance': float('nan')}) + self.assertEqual(json.loads(path.read_text()), {'balance': 100}) diff --git a/tests/test_removal_recovery.py b/tests/test_removal_recovery.py new file mode 100644 index 0000000..8785df2 --- /dev/null +++ b/tests/test_removal_recovery.py @@ -0,0 +1,81 @@ +import tempfile +import threading +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import web_sim as ws +from pending_removals import PendingRemovals + + +CONN = {'lead_market': 'raydium', 'lead_ticker': '', 'lead_pool': 'POOL1', + 'follow_exchange': 'binance', 'follow_ticker': 'XYZUSDT'} + + +class RemovalRecoveryTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.path = Path(self.tmp.name) / 'pending.json' + self.key = ws.coin_key(CONN) + + def simulator(self, real_pending=True): + sim = ws.Simulator.__new__(ws.Simulator) + sim.lock = threading.Lock() + sim.removals = PendingRemovals(self.path) + engine = mock.Mock(conn=CONN, lock=threading.RLock()) + engine.name = 'XYZ' + engine.paper.ledger.positions = [] + engine.mirror.ready_to_remove.return_value = not real_pending + sim.engines = {self.key: engine} + return sim, engine + + def test_failed_real_close_retains_connection_and_intent_after_restart(self): + sim, engine = self.simulator() + with mock.patch.object(ws.lw, 'remove_connection') as remove: + message = sim.remove(self.key) + self.assertIn('ожидает', message) + remove.assert_not_called() + engine.shutdown.assert_not_called() + engine.mirror.request_close.assert_called_once() + self.assertEqual(PendingRemovals(self.path).connections(), {self.key: CONN}) + self.assertIn(self.key, sim.engines) + + def test_only_confirmed_close_finishes_removal(self): + sim, engine = self.simulator() + sim.removals.schedule(self.key, CONN) + with mock.patch.object(ws.lw, 'remove_connection') as remove: + self.assertFalse(sim._finish_removal(self.key)) + engine.mirror.ready_to_remove.return_value = True + self.assertTrue(sim._finish_removal(self.key)) + remove.assert_called_once_with(CONN) + engine.shutdown.assert_called_once() + self.assertEqual(PendingRemovals(self.path).connections(), {}) + self.assertNotIn(self.key, sim.engines) + + def test_restart_recreates_pending_connection_even_after_connection_file_deletion(self): + sim, engine = self.simulator() + sim.removals.schedule(self.key, CONN) + sim.engines = {} + sim.common, sim.account, sim.start_feeds = {}, object(), False + with mock.patch.object(ws.lw, 'load_connections', return_value=[]), \ + mock.patch.object(ws, 'Engine', return_value=engine): + sim.sync_connections() + self.assertIs(sim.engines[self.key], engine) + self.assertTrue(engine.removing) + engine.set_trading.assert_called_with(False) + engine.mirror.request_close.assert_called_once() + + def test_disk_failure_before_intent_does_not_close_or_remove(self): + sim, engine = self.simulator() + with mock.patch('pending_removals.atomic_write_json', side_effect=OSError('full')), \ + mock.patch.object(ws.lw, 'remove_connection') as remove: + message = sim.remove(self.key) + self.assertIn('не начато', message) + engine.close.assert_not_called() + remove.assert_not_called() + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_request_security.py b/tests/test_request_security.py new file mode 100644 index 0000000..b94d031 --- /dev/null +++ b/tests/test_request_security.py @@ -0,0 +1,83 @@ +"""Requests retain their original authority through the local proxy.""" +import json +import sys +import unittest +import urllib.error +import urllib.request +from email.message import Message +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)] +import request_security as security +import test_web_proxy as fixtures +import web_proxy +import web_sim + + +class AuthorityTests(unittest.TestCase): + def request(self, host='localhost:8765', origin=None, peer='127.0.0.1'): + headers = Message() + headers['Host'] = host + headers['X-Sim'] = '1' + if origin is not None: + headers['Origin'] = origin + return SimpleNamespace(headers=headers, client_address=(peer, 1000)) + + def test_only_local_authorities_and_same_origin_are_accepted(self): + for host, origin in [('localhost:8765', 'http://localhost:8765'), + ('127.0.0.1:8765', None), ('[::1]:8765', 'http://[::1]:8765')]: + self.assertTrue(security.trusted_request(self.request(host, origin), command=True)) + for host in ['attacker.example:8765', 'localhost.attacker.example', 'attacker@localhost:8765', + 'localhost:bad', 'localhost:8765/path', 'localhost:8765#x', 'localhost:8765,evil']: + self.assertFalse(security.trusted_request(self.request(host))) + for origin in ['null', 'http://attacker.example', 'http://localhost:1234', 'http://evil@localhost:8765']: + self.assertFalse(security.trusted_request(self.request(origin=origin), command=True)) + self.assertFalse(security.trusted_request(self.request(peer='192.168.1.1'))) + + def test_duplicate_host_and_missing_command_header_are_rejected(self): + req = self.request() + req.headers['Host'] = 'evil.example' + self.assertFalse(security.trusted_request(req)) + req = self.request() + del req.headers['X-Sim'] + self.assertFalse(security.trusted_request(req, command=True)) + + +class ProxyIntegrationTests(unittest.TestCase): + def setUp(self): + self.sim = mock.patch.object(web_sim, 'SIM', SimpleNamespace(state=lambda: {'ok': True}), create=True) + self.sim.start() + self.addCleanup(self.sim.stop) + self.engine = fixtures.serve(web_sim.Handler) + self.backend = mock.patch.object(web_proxy, 'ENGINE', f'http://127.0.0.1:{self.engine.server_port}') + self.backend.start() + self.addCleanup(self.backend.stop) + self.proxy = fixtures.serve(web_proxy.Proxy) + for server in (self.engine, self.proxy): + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + + def test_host_is_checked_at_both_boundaries(self): + for server in (self.proxy, self.engine): + for method in ('GET', 'POST'): + req = urllib.request.Request(f'http://127.0.0.1:{server.server_port}/api/state', + data=b'{}' if method == 'POST' else None, method=method, + headers={'Host': 'attacker.example', 'X-Sim': '1'}) + with self.assertRaises(urllib.error.HTTPError) as error: + urllib.request.urlopen(req) + self.assertEqual(error.exception.code, 403) + + def test_proxy_preserves_browser_origin_and_static_assets_are_allowlisted(self): + base = f'http://127.0.0.1:{self.proxy.server_port}' + req = urllib.request.Request(base + '/api/state', headers={'Origin': base}) + with urllib.request.urlopen(req) as response: + self.assertEqual(json.load(response), {'ok': True}) + for asset, kind in [('app.js', 'text/javascript'), ('app.css', 'text/css')]: + with urllib.request.urlopen(base + '/static/' + asset) as response: + self.assertIn(kind, response.headers['Content-Type']) + self.assertGreater(len(response.read()), 10) + with self.assertRaises(urllib.error.HTTPError) as error: + urllib.request.urlopen(base + '/static/../keystore.py') + self.assertEqual(error.exception.code, 404) diff --git a/tests/test_virtual_account.py b/tests/test_virtual_account.py new file mode 100644 index 0000000..a35b85c --- /dev/null +++ b/tests/test_virtual_account.py @@ -0,0 +1,173 @@ +import json +import tempfile +import threading +import unittest +from pathlib import Path +from unittest import mock + +from virtual_account import AccountError, VirtualAccount + + +class VirtualAccountTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.path = Path(self.temp.name) / 'account.json' + self.account = VirtualAccount(self.path, 100) + + def test_one_balance_fees_reservations_profit_and_deposits(self): + a = self.account + a.commit('coin:a', {'positions': [1]}, cash_total=-1, reserved=60, event='entry') + self.assertEqual(a.view()['free'], 39) + with self.assertRaises(AccountError): + a.commit('cross', {}, cash_total=-1, reserved=40) + a.mark('coin:a', -10) + self.assertEqual(a.view()['free'], 29) + with self.assertRaises(AccountError): + a.adjust(-30, 'withdraw-1') + a.adjust(25, 'deposit-1') + self.assertEqual(a.view()['realized'], -1) + a.commit('coin:a', {'positions': []}, cash_total=9, reserved=0, event='close') + self.assertEqual(a.view()['balance'], 134) + self.assertEqual(a.view()['free'], 134) + self.assertEqual(a.view()['realized'], 9) + + def test_repeat_adjustment_is_idempotent_across_restart(self): + self.account.adjust(50, 'deposit-123') + again = VirtualAccount(self.path, 9999) + again.adjust(50, 'deposit-123') + self.assertEqual(again.view()['balance'], 150) + with self.assertRaises(AccountError): + again.adjust(60, 'deposit-123') + + def test_owner_snapshot_and_cash_are_committed_together(self): + self.account.commit('a', {'position': 12}, cash_total=-2, reserved=50) + again = VirtualAccount(self.path) + self.assertEqual(again.restore('a'), {'position': 12}) + again.commit('a', {'position': 12}, cash_total=-2, reserved=50) + self.assertEqual(again.view()['balance'], 98) + with mock.patch('virtual_account.atomic_write_json', side_effect=OSError('disk full')): + with self.assertRaises(AccountError): + again.commit('a', {'position': None}, cash_total=8, reserved=0) + self.assertEqual(again.restore('a'), {'position': 12}) + self.assertEqual(again.view()['balance'], 98) + self.assertEqual(VirtualAccount(self.path).restore('a'), {'position': 12}) + + def test_concurrent_entries_cannot_spend_same_free_money(self): + barrier = threading.Barrier(2) + results = [] + def enter(owner): + barrier.wait() + try: + self.account.commit(owner, {'open': True}, cash_total=-1, reserved=60) + results.append(True) + except AccountError: + results.append(False) + jobs = [threading.Thread(target=enter, args=(name,)) for name in ('a', 'b')] + for job in jobs: + job.start() + for job in jobs: + job.join() + self.assertEqual(sorted(results), [False, True]) + self.assertEqual(self.account.view()['reserved'], 60) + + def test_existing_exposure_imported_but_new_risk_blocked(self): + self.account.commit('old', {'open': True}, cash_total=0, reserved=150, allow_existing=True) + with self.assertRaises(AccountError): + self.account.commit('old', {}, cash_total=0, reserved=160, allow_existing=True) + self.account.commit('old', {'open': False}, cash_total=-120, reserved=0) + self.assertEqual(self.account.view()['balance'], -20) + self.assertEqual(self.account.view()['free'], 0) + + def test_invalid_values_do_not_change_balance(self): + for value in (0, True, 'NaN', 'inf', '-inf', 'abc', None, -101): + with self.subTest(value=value), self.assertRaises(AccountError): + self.account.adjust(value, 'request-123') + self.assertEqual(self.account.view()['balance'], 100) + + def test_corrupt_file_blocks_without_overwriting(self): + self.path.write_text('{broken', encoding='utf-8') + broken = VirtualAccount(self.path) + self.assertTrue(broken.view()['error']) + with self.assertRaises(AccountError): + broken.adjust(10, 'deposit-321') + self.assertEqual(self.path.read_text(), '{broken') + + def test_stale_open_position_blocks_withdrawal_but_allows_close(self): + self.account.commit('a', {}, cash_total=-1, reserved=60) + again = VirtualAccount(self.path) + self.assertEqual(again.view()['stale'], ['a']) + with self.assertRaises(AccountError): + again.adjust(-1, 'withdraw-321') + again.commit('a', {}, cash_total=-3, reserved=0) + self.assertEqual(again.view()['free'], 97) + + def test_second_instance_cannot_overwrite_prior_adjustment(self): + other = VirtualAccount(self.path) + self.account.adjust(50, 'first-123') + other.adjust(25, 'second-123') + self.assertEqual(VirtualAccount(self.path).view()['balance'], 175) + + def test_external_owner_change_invalidates_old_valuation(self): + self.account.commit('x', {}, cash_total=0, reserved=20, unrealized=-10) + other = VirtualAccount(self.path) + other.commit('x', {'changed': True}, cash_total=0, reserved=20, unrealized=-60) + with self.assertRaises(AccountError): + self.account.adjust(-70, 'withdraw-xyz') + self.assertEqual(self.account.view()['equity'], 40) + + def test_structurally_corrupt_account_reports_error(self): + original = json.loads(self.path.read_text()) + for patch in ({'balance': '100'}, {'owners': {'broken': []}}, {'balance': True}): + self.path.write_text(json.dumps({**original, **patch}), encoding='utf-8') + account = VirtualAccount(self.path) + self.assertTrue(account.view()['error']) + + def test_runtime_lock_prevents_two_engines_for_same_directory(self): + from runtime_lock import RuntimeLock + path = Path(self.temp.name) / 'engine.lock' + with RuntimeLock(path): + with self.assertRaises(RuntimeError): + with RuntimeLock(path): + self.fail('second engine acquired directory') + with RuntimeLock(path): + pass + + def test_repeated_large_adjustment_cannot_write_unreadable_totals(self): + path = Path(self.temp.name) / 'large-account.json' + account = VirtualAccount(path, 0) + account.adjust(1e12, 'large-deposit-1') + before = path.read_bytes() + with self.assertRaises(AccountError): + account.adjust(1e12, 'large-deposit-2') + self.assertEqual(path.read_bytes(), before) + self.assertEqual(account.view()['balance'], 1e12) + self.assertEqual(account.view()['error'], '') + restarted = VirtualAccount(path) + self.assertEqual(restarted.view()['error'], '') + self.assertEqual(restarted.view()['balance'], 1e12) + self.assertNotIn('large-deposit-2', restarted.data['adjustments']) + + def test_commit_and_net_deposits_are_validated_before_persistence(self): + path = Path(self.temp.name) / 'large-account.json' + account = VirtualAccount(path, 1e12) + before = path.read_bytes() + with self.assertRaises(AccountError): + account.commit('profit', {}, cash_total=1, reserved=0) + self.assertEqual(path.read_bytes(), before) + self.assertIsNone(account.restore('profit')) + + account.commit('loss', {}, cash_total=-1000, reserved=0) + before = path.read_bytes() + with self.assertRaises(AccountError): + # Balance would stay below the cap, but cumulative net deposits would exceed it. + account.adjust(500, 'net-deposits-overflow') + self.assertEqual(path.read_bytes(), before) + restarted = VirtualAccount(path) + self.assertEqual(restarted.view()['error'], '') + self.assertEqual(restarted.view()['balance'], 1e12 - 1000) + self.assertEqual(restarted.view()['net_deposits'], 1e12) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_web_account.py b/tests/test_web_account.py new file mode 100644 index 0000000..8f9ae2f --- /dev/null +++ b/tests/test_web_account.py @@ -0,0 +1,445 @@ +"""Shared-wallet integration through web engines and HTTP handlers, without threads or exchanges.""" +import io +import json +import tempfile +import time +import unittest +from email.message import Message +from pathlib import Path +from unittest import mock + +import cross +import scalp_hint as sh +import scalp_paper as sp +import virtual_account +import web_sim as ws + + +class NoRealMirror: + def __init__(self, *args, **kwargs): + self.trades = [] + self.state = "" + self.position = None + self.storage_error = "" + self.events = [] + + def hook(self, event, pos): + self.events.append(event) + + def gate(self): + return "" + + def enabled(self): + return False + + def request_close(self): + pass + + def ready_to_remove(self): + return self.position is None + + def reset_stats(self): + pass + + def view(self): + return {"open": 0, "trades": 0, "net": 0.0, "wins": 0, "positions": [], "state": "", + "problem": "", "enabled": False, "trade_list": []} + + +def connection(symbol): + return {"lead_market": "spot", "lead_ticker": symbol + "-USDT", "lead_pool": "", + "follow_exchange": "bybit", "follow_ticker": symbol + "USDT"} + + +def book(mid=.08): + b = sh.OrderBook() + b.bids, b.asks = {round(mid - .00002, 5): 1000}, {round(mid + .00002, 5): 1000} + return b + + +class WebAccountTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.directory = Path(temporary.name) + self.account_path = self.directory / "account.json" + self.account = virtual_account.VirtualAccount(self.account_path, 10) + self.common = dict(ws.load_common(), mode="vector", stake=6, budget=300, leverage=1, + vector_window_seconds=2, vector_min_move_pct=.05, max_positions=5, + entry_gap_seconds=0, cooldown_ms=0, stop_loss_pct=.3, + min_confidence=0, auto_tp=False, one_per_tick=False, require_leader=False) + patches = [mock.patch.object(ws, "DATA_DIR", self.directory), + mock.patch.object(ws, "SETTINGS_FILE", self.directory / "settings.json"), + mock.patch.object(ws, "paper_account", return_value=self.account), + mock.patch.object(ws.real_mirror, "FuturesMirror", NoRealMirror), + mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {}}), + mock.patch.object(ws.real_mirror, "save_settings", side_effect=AssertionError("real settings touched")), + mock.patch.object(ws.live, "client", side_effect=AssertionError("real client requested")), + mock.patch.object(cross.arb, "_get", side_effect=AssertionError("network request"))] + for item in patches: + item.start() + self.addCleanup(item.stop) + + def engine(self, symbol="AAA", common=None, account=True): + engine = ws.Engine(connection(symbol), common or self.common, self.account if account else None) + engine.tick, engine.book = .00001, book() + return engine + + def warm(self, engine): + engine.set_trading(True) + for index in range(31): + stamp = 1000 + index / 10 + engine.paper.on_leader(stamp, .08, .08) + engine.paper.on_book(stamp, engine.book, engine.tick) + + def direct_open(self, engine): + return engine.paper.ledger.open(engine.paper.settings.follow_ticker, "LONG", .08002, 1003, + .055, .09, .07, .08) + + def post(self, body, *, raw=False, path="/api/account/adjust", headers=None): + data = body if raw else json.dumps(body).encode() + handler = ws.Handler.__new__(ws.Handler) + handler.path = path + handler.client_address = ("127.0.0.1", 12345) + handler.rfile = io.BytesIO(data) + handler.headers = Message() + for name, value in {"Host": "127.0.0.1:8765", "Origin": "http://127.0.0.1:8765", "X-Sim": "1", + "Content-Length": str(len(data)), **(headers or {})}.items(): + handler.headers[name] = value + responses = [] + handler._json = lambda payload, status=200: responses.append((status, payload)) + handler.do_POST() + self.assertEqual(len(responses), 1) + return responses[0] + + def test_competing_coins_topup_and_close_through_engine(self): + first, second = self.engine("AAA"), self.engine("BBB") + self.warm(first) + self.warm(second) + first.paper.on_leader(1003.1, .08016, .08016) + self.assertEqual(len(first.paper.ledger.positions), 1) + second.paper.on_leader(1003.1, .08016, .08016) + self.assertEqual(second.paper.ledger.positions, []) + self.assertAlmostEqual(self.account.view()["reserved"], 6) + status, reply = self.post({"amount": 10, "request_id": "topup-for-second"}) + self.assertEqual(status, 200) + self.assertTrue(reply["ok"]) + second.paper.on_leader(1003.2, .08032, .08032) + self.assertEqual(len(second.paper.ledger.positions), 1) + self.assertAlmostEqual(self.account.view()["reserved"], 12) + self.assertIn("1", first.close(None)) + self.assertIsNone(first.paper.position) + self.assertAlmostEqual(self.account.view()["reserved"], 6) + expected = 20 + first.paper.trades[0].net_usd - second.paper.position.fee_in + self.assertAlmostEqual(self.account.view()["balance"], expected) + + def test_restart_restores_common_owner_and_policy_despite_common_mode_change(self): + settings = dict(self.common, mode="basis") + first = self.engine(common=settings) + first.paper.policy.b_mean, first.paper.policy.b_var, first.paper.policy.b_count = 1.25, .04, 100 + first.paper.policy.last_entry = 900 + pos = self.direct_open(first) + first.paper.ledger.save() + before = self.account.view() + self.account = virtual_account.VirtualAccount(self.account_path, 999) + again = self.engine(common=self.common) + self.assertEqual(again.paper.position, pos) + self.assertIsInstance(again.paper.policy, sp.BasisPolicy) + self.assertEqual(again.paper.policy.b_mean, 1.25) + self.assertEqual(again.paper.policy.last_entry, 900) + self.assertEqual(self.account.view()["balance"], before["balance"]) + self.assertEqual(self.account.view()["reserved"], before["reserved"]) + + def test_first_legacy_migration_keeps_policy_state(self): + settings = dict(self.common, mode="basis") + old = self.engine(common=settings, account=False) + old.paper.policy.b_mean, old.paper.policy.b_var, old.paper.policy.b_count = 1.25, .04, 100 + self.direct_open(old) + old.paper.ledger.save() + migrated = self.engine(common=settings) + self.assertEqual(migrated.paper.policy.b_mean, 1.25) + self.assertEqual(migrated.paper.policy.b_var, .04) + self.assertEqual(migrated.paper.policy.b_count, 100) + + def test_restart_checkpoint_keeps_last_known_unrealized_without_refreshing_quote_age(self): + engine = self.engine() + self.direct_open(engine) + engine.paper.mark_account(book(.079)) + engine.paper.ledger.save() + previous = self.account.view()["unrealized"] + self.assertLess(previous, 0) + self.account = virtual_account.VirtualAccount(self.account_path, 999) + again = self.engine() + again.set_trading(False) # a settings save is not a new market price + self.assertAlmostEqual(self.account.view()["unrealized"], previous) + self.assertIn("coin:" + again.key, self.account.view()["stale"]) + + def test_reset_refuses_open_exposure_and_preserves_wallet_after_close(self): + engine = self.engine() + self.direct_open(engine) + self.assertIn("закройте", engine.reset()) + self.assertIsNotNone(engine.paper.position) + self.assertEqual(self.account.view()["reserved"], 6) + engine.close(None) + before = self.account.view()["balance"] + self.assertEqual(engine.reset(), "Статистика сброшена") + self.assertEqual(self.account.view()["balance"], before) + + def test_failed_reset_retains_history_and_reports_error(self): + engine = self.engine() + self.direct_open(engine) + engine.close(None) + trades = list(engine.paper.trades) + with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")): + result = engine.reset() + self.assertIn("disk full", result) + self.assertEqual(engine.paper.trades, trades) + + def test_failed_close_does_not_report_a_closed_position(self): + engine = self.engine() + self.direct_open(engine) + before = self.account.view() + with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")): + message = engine.close(None) + self.assertIsNotNone(engine.paper.position) + self.assertNotIn("закрыто позиций: 1", message) + self.assertIn("disk full", message) + self.assertEqual(self.account.view()["balance"], before["balance"]) + self.assertEqual(self.account.view()["reserved"], before["reserved"]) + + def test_close_without_a_quote_preserves_position_and_common_reserve(self): + engine = self.engine() + position = self.direct_open(engine) + engine.book = sh.OrderBook() + engine.last_follower = 0 + previous = self.account.view() + snapshot = self.account_path.read_bytes() + message = engine.close(None) + self.assertIn("Нет свежей цены", message) + self.assertEqual(engine.close_error, message) + self.assertEqual(engine.paper.ledger.positions, [position]) + self.assertEqual(engine.paper.trades, []) + self.assertEqual(self.account.view()["reserved"], previous["reserved"]) + self.assertEqual(self.account.view()["balance"], previous["balance"]) + self.assertEqual(self.account_path.read_bytes(), snapshot) + + def test_stale_close_is_rejected_then_fresh_quote_settles_once(self): + engine = self.engine() + position = self.direct_open(engine) + previous = self.account.view()["balance"] + now = time.time() + engine.last_follower = now - engine.paper.settings.max_data_age_ms / 1000 - 1 + with mock.patch.object(ws.time, "time", return_value=now): + message = engine.close(position.uid) + self.assertIn("Нет свежей цены", message) + self.assertEqual(engine.paper.ledger.positions, [position]) + self.assertEqual(self.account.view()["balance"], previous) + self.assertEqual(self.account.view()["reserved"], position.margin) + engine.book = book(.081) + engine.last_follower = now + self.assertEqual(engine.close(position.uid), "закрыто позиций: 1") + self.assertEqual(engine.close_error, "") + self.assertIsNone(engine.paper.position) + self.assertEqual(len(engine.paper.trades), 1) + self.assertAlmostEqual(engine.paper.trades[0].exit, .08098) + self.assertAlmostEqual(self.account.view()["balance"], 10 + engine.paper.trades[0].net_usd) + self.assertEqual(self.account.view()["reserved"], 0) + self.assertEqual(engine.close(position.uid), "закрыто позиций: 0") + self.assertEqual(len(engine.paper.trades), 1) + + def test_corrupt_account_leaves_simulator_available_for_error_display(self): + self.account_path.write_text("{broken", encoding="utf-8") + broken = virtual_account.VirtualAccount(self.account_path) + with mock.patch.object(ws.lw, "load_connections", return_value=[connection("AAA")]): + simulator = ws.Simulator(account=broken, start=False) + self.assertTrue(simulator.state()["account"]["error"]) + self.assertTrue(simulator.state()["coins"][0]["account_error"]) + self.assertIsNone(self.direct_open(next(iter(simulator.engines.values())))) + self.assertEqual(self.account_path.read_text(), "{broken") + + def test_cross_and_coin_share_the_same_reservation_limit(self): + engine = self.engine() + self.direct_open(engine) + engine.paper.mark_account(engine.book) + arbitrage = cross.CrossEngine(self.directory, start=False, account=self.account) + self.assertEqual(arbitrage.set_settings({"amount": 6, "running": True}), "") + link = cross.Link("XYZ", "Gate", "Binance", "XYZUSDT", "XYZUSDT", .999, 1, 1.02, 1.021, + 1e5, 1e5, 1e7, 1e7, .0001, 8) + arbitrage.links[link.key] = link + row = {"link": link, "fits": True, "net": 1.0, "usual": .5} + self.assertFalse(arbitrage._entries(1000, [row])) + self.assertEqual(arbitrage.positions, []) + self.assertEqual(self.account.view()["reserved"], 6) + self.account.adjust(20, "cross-topup") + self.assertEqual(arbitrage.set_settings({"running": True}), "") + self.assertTrue(arbitrage._entries(1001, [row])) + self.assertGreater(self.account.view()["reserved"], 12) + + def test_http_adjustment_is_idempotent_and_only_virtual(self): + body = {"amount": 3, "request_id": "same-request-123"} + self.assertTrue(self.post(body)[1]["ok"]) + self.assertTrue(self.post(body)[1]["ok"]) + self.assertEqual(self.account.view()["balance"], 13) + self.assertFalse(self.post({**body, "amount": 4})[1]["ok"]) + self.assertEqual(self.account.view()["balance"], 13) + + def test_http_invalid_adjustments_and_json_do_not_mutate_account(self): + for amount in (None, True, "NaN", "inf", -11, 0, "wrong"): + with self.subTest(amount=amount): + self.assertFalse(self.post({"amount": amount, "request_id": "invalid-value"})[1]["ok"]) + for payload in (b"[]", b"null", b'{"amount":'): + self.assertEqual(self.post(payload, raw=True)[0], 400) + self.assertEqual(self.post({}, headers={"Content-Length": "65537"})[0], 413) + self.assertEqual(self.post({"amount": 2, "request_id": "request-x"}, headers={"X-Sim": "0"})[0], 403) + self.assertEqual(self.account.view()["balance"], 10) + self.assertEqual(self.account.view()["journal"], []) + + def test_virtual_entry_and_topup_never_reach_real_mirror_hooks(self): + engine = self.engine() + self.assertEqual(engine.paper.ledger.hooks, []) + self.direct_open(engine) + self.post({"amount": 5, "request_id": "paper-only-deposit"}) + engine.close(None) + self.assertEqual(engine.mirror.events, []) + + def test_real_switch_is_refused_while_any_exposure_is_open(self): + engine = self.engine() + self.direct_open(engine) + self.assertIn("закройте", engine.switch_real(True)) + self.assertFalse(engine.signal_mode) + self.assertIs(engine.paper.ledger.account, self.account) + engine.close(None) + engine.mirror.position = {"uid": 9} + self.assertIn("закройте", engine.switch_real(True)) + self.assertFalse(engine.signal_mode) + + def test_reset_cannot_close_private_real_signals_or_erase_pending_real_exposure(self): + engine = self.engine() + with mock.patch.object(ws.real_mirror, "save_settings", return_value=""): + self.assertEqual(engine.switch_real(True), "") + position = self.direct_open(engine) + self.assertEqual(engine.mirror.events, ["open"]) + self.assertIn("закройте", engine.reset()) + self.assertEqual(engine.paper.ledger.positions, [position]) + self.assertEqual(engine.mirror.events, ["open"]) + engine.close(None) + self.assertIsNone(engine.paper.position) + engine.mirror.position = {"uid": position.uid} + trades = list(engine.paper.trades) + self.assertIn("закройте", engine.reset()) + self.assertEqual(engine.paper.trades, trades) + + def test_real_signal_ledger_is_isolated_and_return_restores_paper_history(self): + engine = self.engine() + self.direct_open(engine) + engine.close(None) + paper_trade = engine.paper.trades[0] + balance = self.account.view()["balance"] + with mock.patch.object(ws.real_mirror, "save_settings", return_value="") as settings: + self.assertEqual(engine.switch_real(True), "") + self.assertTrue(engine.signal_mode) + self.assertIsNone(engine.paper.ledger.account) + self.assertEqual(engine.paper.trades, []) + self.direct_open(engine) + self.assertEqual(engine.mirror.events, ["open"]) + self.assertEqual(self.account.view()["balance"], balance) + self.assertEqual(self.account.view()["reserved"], 0) + engine.close(None) + self.assertEqual(engine.mirror.events, ["open", "close"]) + self.assertEqual(self.account.view()["balance"], balance) + self.assertEqual(engine.switch_real(False), "") + self.assertFalse(engine.signal_mode) + self.assertIs(engine.paper.ledger.account, self.account) + self.assertEqual(engine.paper.trades, [paper_trade]) + self.assertEqual(engine.paper.ledger.hooks, []) + self.assertEqual(self.account.view()["balance"], balance) + self.assertEqual(settings.call_args_list, + [mock.call({"coin": engine.key, "enabled": True}), + mock.call({"coin": engine.key, "enabled": False})]) + + def test_new_real_signal_ledger_uses_configured_standalone_budget(self): + engine = self.engine(common=dict(self.common, budget=1000, stake=500)) + with mock.patch.object(ws.real_mirror, "save_settings", return_value=""): + self.assertEqual(engine.switch_real(True), "") + self.assertEqual(engine.paper.ledger.balance, 1000) + self.assertEqual(engine.paper.ledger.available, float("inf")) + + def test_real_signal_policy_ignores_virtual_balance_and_legacy_paper_budget(self): + engine = self.engine(common=dict(self.common, budget=300, stake=500)) + with mock.patch.object(ws.real_mirror, "save_settings", return_value=""): + self.assertEqual(engine.switch_real(True), "") + # Empty the virtual wallet: private real-signal bookkeeping must remain independent. + self.assertTrue(self.post({"amount": -10, "request_id": "withdraw-paper-all"})[1]["ok"]) + self.warm(engine) + engine.paper.on_leader(1003.1, .08016, .08016) + self.assertIsNotNone(engine.paper.position) + self.assertEqual(engine.mirror.events, ["open"]) + self.assertEqual(self.account.view()["balance"], 0) + self.assertEqual(self.account.view()["reserved"], 0) + + def test_startup_selects_private_signal_ledger_for_saved_real_mode(self): + key = ws.coin_key(connection("AAA")) + with mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {key: {"on": True}}}): + engine = self.engine() + self.assertTrue(engine.signal_mode) + self.assertIsNone(engine.paper.ledger.account) + self.assertIsNone(self.account.restore("coin:" + key)) + self.assertEqual(engine.paper.ledger.state_path.name, "signal_" + key + ".json") + + def test_private_signal_restart_restores_open_position_without_reemitting_entry(self): + key = ws.coin_key(connection("AAA")) + settings = dict(self.common, mode="basis") + with mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {key: {"on": True}}}): + first = self.engine(common=settings) + first.paper.policy.b_mean, first.paper.policy.b_var = 1.25, .04 + pos = self.direct_open(first) + first.paper.ledger.save() + again = self.engine(common=settings) + self.assertEqual(again.paper.position, pos) + self.assertIsNone(again.paper.ledger.account) + self.assertTrue(again.paper.ledger.signal_only) + self.assertEqual(again.paper.policy.b_mean, 1.25) + self.assertEqual(again.paper.policy.b_var, .04) + self.assertEqual(again.mirror.events, []) + self.assertEqual(self.account.view()["balance"], 10) + self.assertEqual(self.account.view()["reserved"], 0) + + def test_private_signal_restart_keeps_open_basis_policy_until_settings_change_after_close(self): + key = ws.coin_key(connection("AAA")) + with mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {key: {"on": True}}}): + first = self.engine(common=dict(self.common, mode="basis")) + first.paper.policy.b_mean, first.paper.policy.b_var = 1.25, .04 + position = self.direct_open(first) + first.paper.ledger.save() + again = self.engine(common=dict(self.common, mode="vector")) + self.assertEqual(again.paper.position, position) + self.assertEqual(again.paper.settings.mode, "basis") + self.assertIsInstance(again.paper.policy, sp.BasisPolicy) + self.assertEqual(again.paper.policy.b_mean, 1.25) + self.assertEqual(again.paper.policy.b_var, .04) + self.assertEqual(again.mirror.events, []) + self.assertEqual(again.close(None), "закрыто позиций: 1") + again.apply({"mode": "vector"}) + self.assertEqual(again.paper.settings.mode, "vector") + self.assertIsInstance(again.paper.policy, sp.VectorPolicy) + self.assertEqual(self.account.view()["balance"], 10) + self.assertEqual(self.account.view()["reserved"], 0) + + def test_paper_reset_does_not_clear_real_mirror_statistics(self): + engine = self.engine() + with mock.patch.object(engine.mirror, "reset_stats") as reset_real: + self.assertEqual(engine.reset(), "Статистика сброшена") + reset_real.assert_not_called() + + def test_failed_real_mode_setting_keeps_active_paper_ledger(self): + engine = self.engine() + original = engine.paper + with mock.patch.object(ws.real_mirror, "save_settings", return_value="settings write failed"): + self.assertEqual(engine.switch_real(True), "settings write failed") + self.assertIs(engine.paper, original) + self.assertFalse(engine.signal_mode) + self.assertEqual(self.account.view()["balance"], 10) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web_proxy.py b/tests/test_web_proxy.py index 891ae7b..9974b91 100644 --- a/tests/test_web_proxy.py +++ b/tests/test_web_proxy.py @@ -53,7 +53,7 @@ class ProxyTests(unittest.TestCase): got = json.loads(urllib.request.urlopen(base + "/api/state?x=1").read()) self.assertEqual(got, {"method": "GET", "path": "/api/state?x=1"}) req = urllib.request.Request(base + "/api/coin/A/start", data=json.dumps({"a": 1}).encode(), - method="POST", headers={"Content-Type": "application/json"}) + method="POST", headers={"Content-Type": "application/json", "X-Sim": "1"}) got = json.loads(urllib.request.urlopen(req).read()) self.assertEqual(got["body"], {"a": 1}) finally: diff --git a/tests/test_web_sim.py b/tests/test_web_sim.py index 1d81665..10cdb04 100644 --- a/tests/test_web_sim.py +++ b/tests/test_web_sim.py @@ -37,6 +37,9 @@ class _NoReal: def reset_stats(self): pass + def ready_to_remove(self): + return True + def view(self): return {"open": 0, "trades": 0, "net": 0.0, "wins": 0, "positions": [], "state": "", "problem": "", "enabled": False, "trade_list": []} @@ -124,6 +127,9 @@ class WebSimTests(unittest.TestCase): e.paper.last_close = 0.0 # close() stamps the wall clock; this test runs on its own clock e.paper.on_leader(t + 0.05, 0.08016, 0.08016) self.assertEqual((len(e.paper.trades), len(e.paper.ledger.positions)), (1, 1)) + self.assertIn("закройте", e.reset()) + self.assertEqual((len(e.paper.trades), len(e.paper.ledger.positions)), (1, 1)) + e.close(None) e.reset() self.assertEqual((e.paper.trades, e.paper.ledger.positions), ([], [])) self.assertEqual(e.paper.ledger.balance, 1000.0) @@ -167,6 +173,7 @@ class WebSimTests(unittest.TestCase): def test_trading_pairs_are_listed_first(self): sim = ws.Simulator.__new__(ws.Simulator) + sim.lock = threading.Lock() sim.common = ws.load_common() a = ws.Engine(dict(CONN, follow_ticker="AAA_USDT"), sim.common) z = ws.Engine(dict(CONN, follow_ticker="ZZZ_USDT"), sim.common) diff --git a/tests/web_context.test.cjs b/tests/web_context.test.cjs new file mode 100644 index 0000000..1515a8a --- /dev/null +++ b/tests/web_context.test.cjs @@ -0,0 +1,320 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); + +function page() { + // Load actual application functions; omit DOM bootstrap and periodic polling only. + let source = fs.readFileSync(path.join(__dirname, '../web/app.js'), 'utf8'); + source = source.replace(/^\(function (calcInit|restoreArbSettings)\(\) \{[\s\S]*?^\}\)\(\);/gm, ''); + source = source.slice(0, source.indexOf('\n(async () => {')); + const elements = new Map(); + const intervals = []; + const context = vm.createContext({ + console, Intl, localStorage: {getItem: () => null, setItem() {}}, + AbortController, setTimeout, clearTimeout, setInterval(fn, ms) { intervals.push({fn, ms}); }, + document: {getElementById(id) { + if (!elements.has(id)) elements.set(id, {textContent: '', innerHTML: '', value: '', dataset: {}, style: {}, disabled: false, classList: {toggle() {}}, addEventListener() {}, getAttribute() { return ''; }}); + return elements.get(id); + }, querySelectorAll: () => [], querySelector: () => null}, + window: {addEventListener() {}}, confirm: () => true, + }); + vm.runInContext(source, context); + vm.runInContext(` + var originalApi = api, pending = [], commands = [], rendered = []; + api = (url, body) => body === undefined + ? new Promise(resolve => pending.push({url, resolve})) + : (commands.push(url), Promise.resolve({ok: true, message: 'ok'})); + renderBasis = () => rendered.push({venue: bxVenue, source: bx.source}); + bxBuild = () => { bxBuilt = true; }; + renderTiles = () => {}; + tab = 'basis'; bxVenue = 'cross'; + `, context); + return {context, elements, intervals, run: code => vm.runInContext(code, context)}; +} +const tick = () => new Promise(resolve => setImmediate(resolve)); + +test('late simulation response cannot populate real mode or send a real close', async () => { + const {context: c, run} = page(); + const old = run('loadBasis()'); + run("bxSelect('cross_real')"); + await run("basisClose(1, 'cross')"); + assert.equal(c.commands.length, 0); + c.pending[1].resolve({source: 'real', settings: {}, positions: [{uid: 1}]}); + await tick(); + c.pending[0].resolve({source: 'paper', settings: {}, positions: [{uid: 1}]}); + await old; + assert.equal(run('bx.source'), 'real'); + await run("basisClose(1, 'cross')"); + assert.equal(c.commands.length, 0); + await run("basisClose(1, 'cross_real')"); + assert.equal(c.commands[0], '/api/basis/cross_real/close/1'); +}); + +test('responses from an earlier visit to the same venue are discarded', async () => { + const {context: c, run} = page(); + const old = run('loadBasis()'); + run("bxSelect('cross_real'); bxSelect('cross')"); + c.pending[2].resolve({source: 'current', settings: {}}); + await tick(); + c.pending[0].resolve({source: 'old', settings: {}}); + await old; + assert.equal(run('bx.source'), 'current'); +}); + +test('older poll cannot overwrite a newer completed poll', async () => { + const {context: c, run} = page(); + const old = run('loadBasis()'), fresh = run('loadBasis()'); + c.pending[1].resolve({source: 'fresh', settings: {}}); + await fresh; + c.pending[0].resolve({source: 'old', settings: {}}); + await old; + assert.equal(run('bx.source'), 'fresh'); +}); + +test('coin switch rejects stale details and stale row actions', async () => { + const {context: c, run} = page(); + run("tab = 'sim'; selected = 'A'; detail = {key: 'A'}"); + const old = run('loadDetail()'); + run("selectCoin('B')"); + await run("closePos(1, 'A'); trade('start')"); + assert.equal(c.commands.length, 0); + c.pending[0].resolve({key: 'A'}); + await old; + assert.equal(run('detail'), null); + run("detail = {key: 'B'}"); + await run("closePos(1, 'A')"); + assert.equal(c.commands.length, 0); + await run("closePos(1, 'B')"); + assert.equal(c.commands[0], '/api/coin/B/close/1'); +}); + +test('a failed first state request still schedules retries and can recover', async () => { + const {run, intervals} = page(); + run(` + var attempts = 0, recovered = false; + loadState = async () => { if (++attempts === 1) throw new Error('offline'); recovered = true; }; + loadDetail = loadBasis = loadReal = loadAccount = async () => {}; + refreshCenter = showTab = () => {}; + startApplication(); + `); + await tick(); + assert.equal(intervals.length, 7); + assert.equal(run('attempts'), 1); + await intervals.find(t => t.ms === 2000).fn(); + assert.equal(run('recovered'), true); +}); + +test('late scanner refresh never replaces a selected coin', async () => { + const {run, context: c} = page(); + run(` + tab = 'sim'; selected = 'BTC'; var skeletons = 0; + scannerSkeleton = () => skeletons++; + document.getElementById = () => null; + `); + await run('loadScanner()'); + assert.equal(run('skeletons'), 0); + assert.equal(c.pending.length, 0); +}); + +test('late scanner response from an earlier visit is discarded', async () => { + const {run, context: c, elements} = page(); + run("tab = 'sim'; selected = SCANNER;"); + const old = run('loadScanner()'); + run('detailEpoch += 2'); // Leaving and returning is a new visit, even to the same scanner. + c.pending[0].resolve({running: false, auto_add: false, cycles: 1, log: [], coins: []}); + await old; + assert.equal(elements.has('scState'), false); +}); + +test('HTTP errors surface their message, with no automatic POST retry', async () => { + const {run, context: c, elements} = page(); + c.fetch = async () => ({ok: false, status: 503, json: async () => ({error: 'maintenance'})}); + run("api = originalApi; readHealth.set('/api/state', {time: Date.now(), error: ''});"); + await assert.rejects(run("api('/api/settings', {})"), /maintenance/); + assert.match(elements.get('commandNotice').textContent, /не подтверждён/); + let calls = 0; + c.fetch = async () => { calls++; throw new Error('connection lost'); }; + await assert.rejects(run("api('/api/settings', {})"), /connection lost/); + assert.equal(calls, 1); + assert.equal(run('pendingCommands.size'), 0); +}); + +test('stale controls block commands until a fresh read succeeds', async () => { + const {run, context: c} = page(); + const control = {dataset: {command: 'state'}, disabled: false}; + c.document.querySelectorAll = selector => selector === '[data-command]' ? [control] : []; + let calls = 0; + c.fetch = async () => { calls++; return {ok: true, status: 200, json: async () => ({ok: true})}; }; + run("api = originalApi; tab = 'sim'; selected = null; readHealth.set('/api/state', {time: Date.now() - 11000, error: ''}); refreshConnection();"); + assert.equal(control.disabled, true); + await assert.rejects(run("api('/api/settings', {})"), /не отправлена/); + assert.equal(calls, 0); + await run("api('/api/state')"); + assert.equal(control.disabled, false); + await run("api('/api/settings', {})"); + assert.equal(calls, 2); +}); + +test('concurrent polling for the same endpoint makes one GET', async () => { + const {run, context: c} = page(); + let calls = 0, resolve; + c.fetch = () => { calls++; return new Promise(done => { resolve = done; }); }; + run('api = originalApi'); + const first = run("api('/api/state')"), second = run("api('/api/state')"); + assert.equal(calls, 1); + resolve({ok: true, status: 200, json: async () => ({coins: []})}); + await Promise.all([first, second]); + assert.equal(run('pendingReads.size'), 0); +}); + +test('slow poll tasks do not accumulate duplicate render work', async () => { + const {run} = page(); + run('var pollCalls = 0, finishPoll; var slowTask = () => { pollCalls++; return new Promise(resolve => finishPoll = resolve); };'); + const first = run('poll(slowTask)'), second = run('poll(slowTask)'); + assert.equal(run('pollCalls'), 1); + run('finishPoll()'); + await Promise.all([first, second]); + assert.equal(run('pendingPolls.size'), 0); +}); + +test('context invalidation starts a fresh GET and ignores old connection failures', async () => { + const {run, context: c} = page(); + const fetches = []; + c.fetch = () => new Promise((resolve, reject) => fetches.push({resolve, reject})); + run('api = originalApi'); + const old = run("api('/api/basis?ex=cross')"); + const oldRejected = assert.rejects(old, /old request failed/); + run("invalidateRead('/api/basis?ex=cross')"); + const fresh = run("api('/api/basis?ex=cross')"); + assert.equal(fetches.length, 2); + fetches[1].resolve({ok: true, status: 200, json: async () => ({settings: {}})}); + await fresh; + fetches[0].reject(new Error('old request failed')); + await oldRejected; + assert.equal(run("freshRead('/api/basis?ex=cross')"), true); +}); + +test('reset refusal is visible instead of silently discarded', async () => { + const {run, elements} = page(); + run(` + bx = {settings: {}}; bxDataVenue = 'cross'; + api = async () => ({ok: false, error: 'Сначала закройте открытые позиции'}); + loadBasis = async () => {}; + `); + await run('basisReset()'); + assert.match(elements.get('bxMsg').textContent, /закройте открытые позиции/); +}); + +test('account snapshot ordering prevents an older poll from undoing a deposit', () => { + const {run, elements} = page(); + run(` + renderAccount({version: 2, updated_at: 20, balance: 400, equity: 400, reserved: 0, free: 400, journal: []}); + renderAccount({version: 1, updated_at: 21, balance: 300, journal: []}); + renderAccount({version: 2, updated_at: 19, balance: 350, journal: []}); + `); + assert.equal(elements.get('account-balance').textContent, '400.00 $'); +}); + +test('uncertain account adjustment reuses its identifier on explicit retry', async () => { + const {run, elements} = page(); + run(` + var adjustments = []; + readHealth.set('/api/account', {time: Date.now(), error: ''}); + loadAccount = async () => {}; + api = async (url, body) => { + adjustments.push({...body}); + if (adjustments.length === 1) throw new Error('response lost'); + return {ok: true, account: {version: 2, balance: 325, equity: 325, reserved: 0, free: 325, journal: []}}; + }; + `); + elements.set('accountDelta', {value: '25,00'}); + await run('adjustAccount(1)'); + assert.match(elements.get('accountMsg').textContent, /Ответ не получен/); + await run('adjustAccount(1)'); + assert.equal(run('adjustments.length'), 2); + assert.equal(run('adjustments[0].amount'), '25'); + assert.equal(run('adjustments[0].request_id === adjustments[1].request_id'), true); + assert.equal(elements.get('account-balance').textContent, '325.00 $'); +}); + +test('account does not send invalid amounts or stale withdrawals', async () => { + const {run, context: c, elements} = page(); + run("readHealth.set('/api/account', {time: Date.now(), error: ''});"); + elements.set('accountDelta', {value: '-10'}); + await run('adjustAccount(-1)'); + assert.equal(c.commands.length, 0); + elements.get('accountDelta').value = '10'; + run("accountData = {stale: ['coin:BTC']}"); + await run('adjustAccount(-1)'); + assert.equal(c.commands.length, 0); + assert.match(elements.get('accountMsg').textContent, /устарела/); +}); + +test('account controls send signed withdrawals and hide in real arbitrage', async () => { + const {run, elements} = page(); + run(` + var savedAdjustment; + accountData = {stale: [], error: ''}; + readHealth.set('/api/account', {time: Date.now(), error: ''}); + loadAccount = async () => {}; + api = async (url, body) => { savedAdjustment = body; return {ok: true}; }; + `); + elements.set('accountDelta', {value: '15.50'}); + await run('adjustAccount(-1)'); + assert.equal(run('savedAdjustment.amount'), '-15.5'); + run("tab = 'basis'; bxVenue = 'cross_real'; updateAccountVisibility();"); + assert.equal(elements.get('paperAccount').hidden, true); + run("bxVenue = 'cross'; updateAccountVisibility();"); + assert.equal(elements.get('paperAccount').hidden, false); +}); + +test('account journal preserves the server newest-first order and stale owner semantics', () => { + const {run, elements} = page(); + run(`renderAccount({balance: 300, equity: 300, reserved: 0, free: 300, stale: [], error: '', journal: [ + {time: 200, amount: 10, balance: 300, reason: 'Newest'}, + {time: 100, amount: -10, balance: 290, reason: 'Older'} + ]});`); + const html = elements.get('accountJournal').innerHTML; + assert.ok(html.indexOf('Newest') < html.indexOf('Older')); + assert.equal(run('accountIsStale(accountData)'), false); + assert.equal(run("accountIsStale({stale: ['coin:BTC']})"), true); +}); + +test('saving main arbitrage settings preserves separately unsaved fee edits', async () => { + const {run, context: c} = page(); + const main = {dataset: {bx: 'amount'}, type: 'text', value: '25'}; + const fee = {dataset: {cxfee: 'Bybit|spot', dirty: '1'}, type: 'text', value: '0.123'}; + c.document.querySelectorAll = selector => selector === '#bxSettings input' ? [main] + : selector.includes('#cxBal input[data-cxfee]') ? [main, fee] : []; + run("bx = {settings: {}}; bxDataVenue = 'cross'; bxBuilt = true; bxDirty = true; loadBasis = async () => {};"); + await run('basisSave()'); + assert.equal(run("basisDrafts.get('cross')['fee:Bybit|spot']"), '0.123'); + assert.equal(run("'bx:amount' in basisDrafts.get('cross')"), false); +}); + +test('scanner rejects invalid cycle inputs before sending any command', async () => { + const {run, elements, context: c} = page(); + elements.set('scMin', {value: '15'}); elements.set('scCoins', {value: '14'}); + await run("scanner('start')"); + assert.equal(c.commands.length, 0); + assert.match(elements.get('scMsg').textContent, /от 1 до 13/); +}); + +test('help covers every declared setting, all modes and account controls', () => { + const {run, context: c} = page(); + vm.runInContext(fs.readFileSync(path.join(__dirname, '../web/help-data.js'), 'utf8'), c); + vm.runInContext(fs.readFileSync(path.join(__dirname, '../web/help.js'), 'utf8'), c); + const missing = run(`[ + ...[...MAIN_FIELDS, ...MORE_FIELDS].filter(([k]) => !HELP_SETTINGS.sim[k]).map(([k]) => 'sim.' + k), + ...[...CX_FIELDS, ...CX_CHECKS].filter(([k]) => !HELP_SETTINGS.cross[k]).map(([k]) => 'cross.' + k), + ...[...BX_FIELDS, ...BX_CHECKS].filter(([k]) => !HELP_SETTINGS.basis[k]).map(([k]) => 'basis.' + k), + ...['lead', 'vector', 'basis'].filter(k => !HELP_MODES[k]), + ...[...CALC_IDS, 'scMin', 'scCoins', 'scAuto', 'simRealTpsl', 'simRealTransfer', 'simRealSl', 'simRealPing', 'accountDelta'].filter(k => !HELP_EXTRA.some(row => row[1] === k)) + ]`); + assert.equal(missing.length, 0, `Missing help: ${missing.join(', ')}`); + assert.equal(run("MAIN_FIELDS.concat(MORE_FIELDS).some(([k]) => k === 'budget')"), false); + assert.ok(run("filterHelp(helpEntries(), 'свободно').some(e => e.key === 'free')")); + assert.ok(run("filterHelp(helpEntries(), 'stop_loss_pct').length") > 0); +}); diff --git a/virtual_account.py b/virtual_account.py new file mode 100644 index 0000000..6e4784b --- /dev/null +++ b/virtual_account.py @@ -0,0 +1,245 @@ +"""One durable paper account shared by the web simulator and paper arbitrage. + +Each engine commits its complete recovery snapshot together with its cumulative +cash movement and reserved capital. A failed write changes neither the account +nor the authoritative engine snapshot. No exchange client is used here. +""" +from __future__ import annotations + +import copy +import math +import threading +import time +from pathlib import Path +import json + +from persistence import atomic_write_json + +_PATH_LOCKS: dict[str, threading.RLock] = {} +_PATH_LOCKS_LOCK = threading.Lock() + + +class AccountError(ValueError): + pass + + +def _number(value, name: str) -> float: + if isinstance(value, bool): + raise AccountError(f"{name}: введите число") + try: + result = float(value) + except (TypeError, ValueError, OverflowError): + raise AccountError(f"{name}: введите число") from None + if not math.isfinite(result) or abs(result) > 1e12: + raise AccountError(f"{name}: недопустимая сумма") + return result + + +class VirtualAccount: + MAX_MARK_AGE = 30.0 + + def __init__(self, path: Path, initial_balance: float = 300.0): + self.path = Path(path) + with _PATH_LOCKS_LOCK: + self.lock = _PATH_LOCKS.setdefault(str(self.path.resolve()).casefold(), threading.RLock()) + self.error = "" + self.marks: dict[str, tuple[float, float]] = {} + initial = _number(initial_balance, "Начальный баланс") + if initial < 0: + raise AccountError("Начальный баланс не может быть отрицательным") + self.data = {"schema": 1, "version": 0, "balance": initial, + "net_deposits": initial, "owners": {}, "adjustments": {}, "journal": [], + "updated_at": time.time()} + try: + loaded = json.loads(self.path.read_text(encoding="utf-8")) + self._validate(loaded) + self.data = loaded + except FileNotFoundError: + try: + atomic_write_json(self.path, self.data) + except (OSError, ValueError) as exc: + self.error = f"Не удалось создать виртуальный счёт: {exc}" + except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: + self.error = f"Виртуальный счёт не прочитан; операции заблокированы: {exc}" + + @staticmethod + def _validate(data): + if not isinstance(data, dict) or data.get("schema") != 1: + raise AccountError("неподдерживаемый формат счёта") + for key in ("balance", "net_deposits", "version", "updated_at"): + if isinstance(data[key], bool) or not isinstance(data[key], (int, float)): + raise AccountError(f"неверный тип поля {key}") + _number(data[key], key) + if not isinstance(data.get("owners"), dict) or not isinstance(data.get("adjustments"), dict): + raise AccountError("повреждён список операций") + if not isinstance(data.get("journal"), list): + raise AccountError("повреждён журнал") + for owner in data["owners"].values(): + if not isinstance(owner, dict) or not isinstance(owner.get("state"), dict): + raise AccountError("повреждено состояние симуляции") + for key in ("cash_total", "reserved", "unrealized"): + value = owner.get(key, 0.0) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise AccountError(f"неверный тип поля {key}") + _number(owner["cash_total"], "Движение средств") + if _number(owner["reserved"], "Резерв") < 0: + raise AccountError("отрицательный резерв") + _number(owner.get("unrealized", 0), "Открытый результат") + for key, value in data["adjustments"].items(): + if not isinstance(key, str) or isinstance(value, bool) or not isinstance(value, (int, float)): + raise AccountError("повреждены идентификаторы операций") + _number(value, "Пополнение / списание") + + def _refresh(self): + """Read the latest in-process writer under the lock shared by this path. + + The application-wide runtime lock prevents different server processes + from owning this account directory at the same time. + """ + self._ready() + try: + data = json.loads(self.path.read_text(encoding="utf-8")) + self._validate(data) + except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: + self.error = f"Виртуальный счёт не прочитан; операции заблокированы: {exc}" + raise AccountError(self.error) from None + if data["version"] != self.data["version"]: + for owner in list(self.marks): + if data["owners"].get(owner) != self.data["owners"].get(owner): + self.marks.pop(owner, None) + self.data = data + + def _ready(self): + if self.error: + raise AccountError(self.error) + + def restore(self, owner: str) -> dict | None: + with self.lock: + self._ready() + record = self.data["owners"].get(owner) + return copy.deepcopy(record["state"]) if record else None + + def _save(self, data): + data["version"] = self.data["version"] + 1 + data["updated_at"] = time.time() + try: + # Individual movements may be valid while their sum exceeds the readable storage range. + # Reject the entire transaction before replacing a valid snapshot with an unreadable one. + self._validate(data) + atomic_write_json(self.path, data) + except (OSError, ValueError, TypeError) as exc: + raise AccountError(f"Не удалось сохранить виртуальный счёт: {exc}") from None + self.data = data + + def _metrics(self, data=None, marks=None): + data = self.data if data is None else data + marks = self.marks if marks is None else marks + now = time.time() + reserved = unrealized = 0.0 + stale = [] + for name, owner in data["owners"].items(): + reserved += owner["reserved"] + value, at = marks.get(name, (owner.get("unrealized", 0.0), 0.0)) + unrealized += value + if owner["reserved"] > 1e-8 and now - at > self.MAX_MARK_AGE: + stale.append(name) + balance = data["balance"] + equity = balance + unrealized + return {"balance": balance, "equity": equity, "reserved": reserved, + "unrealized": unrealized, "free": max(0.0, min(balance, equity) - reserved), + "deficit": max(0.0, reserved - min(balance, equity)), "stale": stale} + + def view(self) -> dict: + with self.lock: + return {**self._metrics(), "net_deposits": self.data["net_deposits"], + "realized": self.data["balance"] - self.data["net_deposits"], + "version": self.data["version"], + "updated_at": max(self.data["updated_at"], + max((stamp for _, stamp in self.marks.values()), default=0.0)), + "error": self.error, + "journal": copy.deepcopy(self.data["journal"][-100:][::-1])} + + def mark(self, owner: str, unrealized: float) -> None: + value = _number(unrealized, "Открытый результат") + with self.lock: + if owner in self.data["owners"]: + self.marks[owner] = (value, time.time()) + + def commit(self, owner: str, state: dict, *, cash_total: float, reserved: float, + unrealized: float = 0.0, allow_existing: bool = False, event: str = "") -> dict: + """Atomically replace an owner's recovery state and apply only its new cash delta. + + allow_existing is only accepted for first-time migration. Existing exposure + is preserved even when the chosen initial deposit is smaller than its margin. + Decreasing exposure and settlement remain possible when the account is in deficit. + """ + cash = _number(cash_total, "Движение средств") + reserve = _number(reserved, "Резерв") + unrealized = _number(unrealized, "Открытый результат") + if reserve < 0 or not isinstance(state, dict) or not owner: + raise AccountError("Некорректное состояние симуляции") + with self.lock: + self._refresh() + old = self.data["owners"].get(owner, {"cash_total": 0.0, "reserved": 0.0}) + migration = allow_existing and owner not in self.data["owners"] + delta = cash - old["cash_total"] + before = self._metrics() + data = copy.deepcopy(self.data) + data["balance"] += delta + data["owners"][owner] = {"cash_total": cash, "reserved": reserve, + "unrealized": unrealized, "state": copy.deepcopy(state)} + marks = dict(self.marks) + # A settings/checkpoint write is not a new market quote. In particular, + # loading a saved position must not make its old valuation fresh. + if reserve <= 1e-8: + marks[owner] = (0.0, time.time()) + elif reserve > old["reserved"] + 1e-8: + marks[owner] = (unrealized, 0.0 if migration else time.time()) + elif owner in marks: + marks[owner] = (unrealized, marks[owner][1]) + after = self._metrics(data, marks) + if reserve > old["reserved"] + 1e-8 and not migration: + if before["stale"]: + raise AccountError("Нет свежей оценки открытых позиций; новый вход приостановлен") + if after["deficit"] > 1e-8: + needed = reserve - old["reserved"] + max(0.0, -delta) + raise AccountError(f"Недостаточно виртуальных средств: доступно {before['free']:.2f} USDT, " + f"требуется {needed:.2f} USDT") + if event and (abs(delta) > 1e-10 or reserve != old["reserved"]): + data["journal"].append({"time": time.time(), "type": "trade", "amount": delta, + "balance": data["balance"], "reason": event, "owner": owner, + "request_id": ""}) + data["journal"] = data["journal"][-1000:] + self._save(data) + self.marks = marks + return self.view() + + def adjust(self, amount, request_id: str) -> dict: + delta = round(_number(amount, "Сумма"), 8) + if delta == 0: + raise AccountError("Сумма должна быть больше нуля") + if not isinstance(request_id, str) or not 8 <= len(request_id) <= 120: + raise AccountError("Неверный идентификатор операции") + with self.lock: + self._refresh() + previous = self.data["adjustments"].get(request_id) + if previous is not None: + if previous != delta: + raise AccountError("Этот идентификатор уже использован для другой суммы") + return self.view() + metrics = self._metrics() + if delta < 0: + if metrics["stale"]: + raise AccountError("Списание приостановлено: нет свежей оценки открытых позиций") + if -delta > metrics["free"] + 1e-8: + raise AccountError(f"Можно списать не больше свободного остатка: {metrics['free']:.2f} USDT") + data = copy.deepcopy(self.data) + data["balance"] = round(data["balance"] + delta, 8) + data["net_deposits"] = round(data["net_deposits"] + delta, 8) + data["adjustments"][request_id] = delta + data["journal"].append({"time": time.time(), "type": "deposit" if delta > 0 else "withdrawal", + "amount": delta, "balance": data["balance"], + "reason": "Пополнение" if delta > 0 else "Списание", "request_id": request_id}) + data["journal"] = data["journal"][-1000:] + self._save(data) + return self.view() diff --git a/web/app.css b/web/app.css new file mode 100644 index 0000000..96aebac --- /dev/null +++ b/web/app.css @@ -0,0 +1,179 @@ +:root { + --bg: #0f1218; --panel: #161b23; --panel2: #1c222c; --line: #2a3240; --text: #e6e9ef; --muted: #8b95a7; + --accent: #4c8dff; --green: #2ecc71; --red: #ff5c5c; --yellow: #f5c542; --yellow-bg: rgba(245, 197, 66, 0.14); + --lead: #ff9f43; --follow: #4c8dff; +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +body { margin: 0; background: var(--bg); color: var(--text); font: 13px/1.4 "Segoe UI", system-ui, sans-serif; } +header { background: var(--panel); border-bottom: 1px solid var(--line); padding: 10px 16px; } +.title { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; } +.title h1 { font-size: 16px; margin: 0; font-weight: 600; } +.title .hint { color: var(--muted); } +.settings { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: flex-end; } +.field { display: flex; flex-direction: column; gap: 3px; } +.field label { color: var(--muted); font-size: 11px; white-space: nowrap; } +.field input, .field select { background: var(--panel2); border: 1px solid var(--line); color: var(--text); border-radius: 6px; + padding: 5px 7px; width: 92px; font: inherit; } +.field select { width: 230px; } +.check { display: flex; align-items: center; gap: 6px; color: var(--text); font-size: 12px; padding-bottom: 6px; white-space: nowrap; } +.more { display: none; margin-top: 8px; } +.more.open { display: flex; } +button { background: var(--panel2); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 6px 12px; + font: inherit; cursor: pointer; } +button:hover { border-color: var(--accent); } +button.primary { background: var(--accent); border-color: var(--accent); color: #fff; } +button.start { background: rgba(46, 204, 113, 0.15); border-color: var(--green); color: var(--green); font-weight: 600; } +button.stop { background: rgba(255, 92, 92, 0.12); border-color: var(--red); color: var(--red); font-weight: 600; } +button:disabled { opacity: 0.35; cursor: default; } +#settingsMsg { color: var(--muted); margin-left: 8px; } +main { display: grid; grid-template-columns: 270px 1fr; min-height: calc(100vh - 120px); } +aside { border-right: 1px solid var(--line); padding: 12px; display: flex; flex-direction: column; gap: 8px; overflow-y: auto; } +aside h2, section h2 { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; margin: 0 0 4px; } +.tile { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; cursor: pointer; position: relative; } +.tile:hover { border-color: #3a4558; } +.tile.active { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; } +.tile .sym { font-size: 16px; font-weight: 700; } +.tabs { display: flex; gap: 4px; padding: 8px 16px 0; background: var(--bg); border-bottom: 1px solid var(--line); } +.tab { border-radius: 8px 8px 0 0; border-bottom: none; padding: 8px 18px; font-weight: 600; color: var(--muted); } +.tab.on { background: var(--panel); color: var(--text); border-color: var(--line); } +#arbRows tr { cursor: pointer; } +td.plancell { white-space: normal; min-width: 380px; max-width: 460px; vertical-align: top; cursor: default; } +div.plancell { white-space: normal; padding: 4px 2px 6px; font-size: 12px; position: sticky; left: 0; + max-width: min(1200px, calc(100vw - 60px)); } +div.plancell ol.plan { font-size: 12.5px; margin-top: 4px; } +.planbtn { font-size: 11px; padding: 2px 8px; white-space: nowrap; cursor: pointer; } +ol.plan { margin: 0; padding-left: 18px; font-size: 11.5px; line-height: 1.45; } +ol.plan li { margin-bottom: 2px; } +#arbRows tr.detail td { background: var(--panel2); cursor: default; } +th[data-s] { cursor: pointer; } +th[data-s].sorted { color: var(--accent); } +.exname { font-weight: 600; } +.links { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; } +.links a { color: var(--accent); text-decoration: none; font-size: 12px; border: 1px solid var(--line); border-radius: 6px; + padding: 2px 8px; background: var(--panel2); } +.links a:hover { border-color: var(--accent); } +.cex { font-size: 11px; font-weight: 600; border-radius: 4px; padding: 1px 6px; vertical-align: middle; + background: rgba(76, 141, 255, 0.15); color: var(--accent); border: 1px solid rgba(76, 141, 255, 0.4); } +.fit { font-size: 11px; border-radius: 6px; padding: 3px 7px; margin: 4px 0 6px; } +.fit-check { color: var(--muted); background: rgba(139, 149, 167, 0.1); } +.fit-no { color: var(--red); background: rgba(255, 92, 92, 0.1); } +.fit-near { color: var(--yellow); background: var(--yellow-bg); } +.fit-ok, .fit-new { color: var(--green); background: rgba(46, 204, 113, 0.14); font-weight: 600; } +.tile.fit-ok, .tile.fit-new { border-color: rgba(46, 204, 113, 0.6); box-shadow: 0 0 10px rgba(46, 204, 113, 0.25); } +.tile.fit-new { animation: pulse 1.6s ease-in-out infinite; } +@keyframes pulse { 50% { box-shadow: 0 0 18px rgba(46, 204, 113, 0.65); } } +.tile.fit-ok.active, .tile.fit-new.active { border-color: var(--accent); } +.tile.plus { border-style: dashed; text-align: center; padding: 14px 12px 10px; } +.tile.plus .plusicon { font-size: 30px; line-height: 30px; color: var(--accent); font-weight: 300; } +button.add { background: rgba(76, 141, 255, 0.15); border-color: var(--accent); color: var(--accent); padding: 3px 10px; } +tr.leadrow td { background: rgba(46, 204, 113, 0.07); } +.tile .route { color: var(--muted); font-size: 11px; margin: 2px 0 6px; } +.tile .row { display: flex; justify-content: space-between; font-size: 12px; } +.dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; position: absolute; top: 12px; right: 34px; background: #555; } +.tile .del { position: absolute; top: 5px; right: 6px; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 6px; + background: transparent; color: var(--muted); font-size: 16px; line-height: 22px; cursor: pointer; } +.tile .del:hover { background: rgba(231, 76, 60, 0.18); color: var(--red, #e74c3c); } +.dot.run { background: var(--green); box-shadow: 0 0 6px var(--green); } +.badge { background: var(--yellow-bg); color: var(--yellow); border-radius: 10px; padding: 0 7px; font-size: 11px; } +.pos { color: var(--green); } .neg { color: var(--red); } .mut { color: var(--muted); } +section.center { padding: 14px 18px; display: flex; flex-direction: column; gap: 12px; min-width: 0; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; } +.coinhead { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; } +.coinhead .name { font-size: 18px; font-weight: 700; } +.coinhead .feeds { color: var(--muted); font-size: 12px; } +.chartbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; gap: 10px; flex-wrap: wrap; } +.legend { display: flex; gap: 16px; font-size: 12px; } +.legend i { display: inline-block; width: 14px; height: 3px; vertical-align: middle; margin-right: 6px; border-radius: 2px; } +.range button { padding: 3px 9px; font-size: 12px; } +.range button.on { border-color: var(--accent); color: var(--accent); } +canvas { width: 100%; height: 240px; display: block; } +.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 8px; } +.stat { background: var(--panel2); border-radius: 8px; padding: 8px 10px; } +.stat .k { color: var(--muted); font-size: 11px; } +.stat .v { font-size: 17px; font-weight: 600; margin-top: 2px; } +.controls { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.statusline { color: var(--muted); font-size: 12px; } +table { width: 100%; border-collapse: collapse; font-size: 12px; } +th { text-align: left; color: var(--muted); font-weight: 500; padding: 6px 8px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel); } +td { padding: 6px 8px; border-bottom: 1px solid #222a35; white-space: nowrap; } +td.why { white-space: normal; color: var(--muted); max-width: 320px; } +tr.open td { background: var(--yellow-bg); } +tr.open td:first-child { border-left: 3px solid var(--yellow); } +tr.flash td { animation: flash 1.5s ease-out; } +@keyframes flash { from { background: rgba(245, 197, 66, 0.45); } } +.x { background: transparent; border: 1px solid var(--red); color: var(--red); border-radius: 50%; width: 22px; height: 22px; + padding: 0; line-height: 18px; font-weight: 700; } +.x:hover { background: var(--red); color: #fff; } +.tablewrap { max-height: 46vh; overflow: auto; } +.empty { color: var(--muted); padding: 30px; text-align: center; } +.realbar { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: 8px; padding: 6px 10px; + border: 1px dashed var(--line); border-radius: 8px; } +.realbar.on { border: 1px solid var(--red); background: rgba(255, 92, 92, 0.08); } +.realtag { background: var(--red); color: #fff; border-radius: 4px; padding: 0 5px; font-size: 10px; font-weight: 700; } +.keygrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 10px; } +.keycard { background: var(--panel2); border-radius: 8px; padding: 10px 12px; display: flex; flex-direction: column; gap: 6px; } +.keycard input { background: var(--panel); border: 1px solid var(--line); color: var(--text); border-radius: 6px; padding: 5px 8px; } +button.realon { background: rgba(255, 92, 92, 0.18); border-color: var(--red); color: var(--red); font-weight: 700; } +.calcbtn { margin-left: auto; align-self: center; margin-bottom: 6px; border-color: var(--accent); color: var(--accent); + background: rgba(76, 141, 255, 0.12); font-weight: 600; } +.calcbtn.on { background: var(--accent); color: #fff; } +.calcpanel { position: fixed; top: 52px; right: 16px; z-index: 50; width: min(460px, calc(100vw - 32px)); max-height: calc(100vh - 70px); + overflow-y: auto; background: var(--panel); border: 1px solid var(--accent); border-radius: 10px; padding: 12px 14px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); } +.calchead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; font-size: 14px; } +.calcgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 8px; } +.calcgrid .field input { width: 100%; } +.calcout { margin-top: 10px; display: flex; flex-direction: column; gap: 6px; } +.calcout .big { background: var(--panel2); border-radius: 8px; padding: 8px 10px; } +.calcout .big b { font-size: 18px; color: var(--green); } +.calcout .row2 { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; } +.calcout .note { color: var(--muted); font-size: 11.5px; } +@media (max-width: 800px) { main { grid-template-columns: 1fr; } aside { flex-direction: row; overflow-x: auto; border-right: 0; border-bottom: 1px solid var(--line); } .tile { min-width: 200px; } } +.system-status { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 18px; padding: 10px 16px; border-bottom: 1px solid var(--line); background: var(--panel); } +.mode-status { color: #91baff; font-size: 12px; letter-spacing: .035em; } +.mode-status.mode-live { color: var(--red); } +.connection-status { font-size: 12px; } +.connection-status.connected { color: var(--muted); } +.connection-status.disconnected { color: var(--yellow); } +.command-notice { padding: 9px 16px; border-bottom: 1px solid var(--line); background: var(--panel2); overflow-wrap: anywhere; } +.paper-account { margin: 16px 18px 0; padding: 16px 18px; border: 1px solid #35517b; border-radius: 12px; background: linear-gradient(120deg, #172235, #151c28); } +.account-heading { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-bottom: 14px; } +.account-heading h2 { margin: 0; font-size: 17px; color: var(--text); letter-spacing: 0; text-transform: none; } +.paper-badge { font-size: 10px; font-weight: 700; color: #a9c8ff; border: 1px solid #35517b; padding: 3px 7px; border-radius: 5px; } +.account-metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; } +.account-metrics > div { display: flex; flex-direction: column; gap: 4px; } +.account-metrics span { color: #b1bdd0; font-size: 12px; } +.account-metrics strong { font-size: clamp(19px, 2vw, 26px); font-variant-numeric: tabular-nums; } +.account-metrics small { color: var(--muted); font-size: 11px; } +.paper-account .field input { width: 180px; } +.account-journal { margin-top: 14px; border-top: 1px solid var(--line); padding-top: 10px; } +.account-journal summary { cursor: pointer; color: #b1c9ed; } +.account-journal .tablewrap { margin-top: 8px; max-height: 220px; } +.account-journal td:nth-child(2) { white-space: normal; min-width: 160px; } +.help-btn { margin-left: auto; align-self: center; margin-bottom: 6px; font-weight: 600; } +.calcbtn { margin-left: 0; } +.help-dialog { width: min(900px, calc(100vw - 28px)); max-height: min(90vh, 980px); padding: 24px; background: var(--panel); color: var(--text); border: 1px solid #3c5273; border-radius: 14px; box-shadow: 0 20px 100px #000a; overflow: auto; } +.help-dialog::backdrop { background: #030812bd; backdrop-filter: blur(3px); } +.help-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; } +.help-heading h2 { margin: 0; font-size: 24px; } +.help-heading p { color: var(--muted); margin: 5px 0 20px; } +.help-close { font-size: 24px; padding: 0; width: 36px; height: 36px; flex: 0 0 auto; } +.help-search-label { display: block; font-size: 12px; color: var(--muted); margin-bottom: 6px; } +.help-search { width: 100%; padding: 11px 12px; color: var(--text); background: var(--panel2); border: 1px solid #3c5273; border-radius: 8px; font: inherit; } +.help-content h3 { margin: 22px 0 8px; color: #9fc4ff; font-size: 15px; } +.help-entry { padding: 12px 0; border-bottom: 1px solid var(--line); } +.help-entry h4 { margin: 0 0 5px; font-size: 13px; } +.help-entry p { margin: 0; color: #b8c2d2; line-height: 1.55; overflow-wrap: anywhere; } +.help-entry code { color: var(--muted); font-size: 11px; font-weight: 400; margin-left: 6px; overflow-wrap: anywhere; } +button:focus-visible, input:focus-visible, select:focus-visible, summary:focus-visible { outline: 2px solid #8db8ff; outline-offset: 3px; } +@media (max-width: 900px) { .tabs { flex-wrap: wrap; padding-bottom: 6px; } .tab { padding: 8px 10px; } .help-btn { margin-left: 0; } .title { flex-wrap: wrap; } } +@media (max-width: 620px) { + .account-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 10px; } + .paper-account { margin: 12px 10px 0; padding: 14px; } + .help-dialog { padding: 18px; } + .check { white-space: normal; } + .field label { white-space: normal; max-width: 260px; } + .keygrid { grid-template-columns: 1fr; } +} +@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; } } diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..cc92cd9 --- /dev/null +++ b/web/app.js @@ -0,0 +1,1499 @@ +const MAIN_FIELDS = [ + ["mode", "Режим", "select"], ["stake", "Ставка, $"], ["leverage", "Плечо"], ["min_target_pct", "Тейк-профит, %"], + ["stop_loss_pct", "Стоп-лосс, %"], ["max_hold_seconds", "Удержание, с"], ["max_positions", "Позиций одновременно"], + ["entry_gap_seconds", "Между входами, с"], ["min_confidence", "Мин. уверенность"], + ["auto_stop_pct", "Автостоп: CEX опережает на, %"], + ["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", "Горизонт прогноза, с"], + ["cut_loss_ticks", "Минус для закрытия, шагов"], ["max_data_age_ms", "Данные не старше, мс"], + ["leader_min_edge", "Перевес ведущей (корр.)"], ["basis_window_seconds", "Разрыв: обычный за, с"], + ["basis_entry_z", "Разрыв: вход, σ"], ["basis_exit_z", "Разрыв: выход, σ"], ["basis_min_gap_pct", "Разрыв: мин., %"], + ["auto_tp_learn", "Учить долю на истории", "check"], ["one_per_tick", "Одна позиция на шаг цены", "check"], + ["cut_loss", "Сразу закрывать в минусе", "check"], +]; +let state = null, selected = localStorage.getItem("sim.coin") || null, detail = null; +let detailEpoch = 0, detailRequest = 0, detailApplied = 0; +let bxEpoch = 0, bxRequest = 0, bxApplied = 0, bxDataVenue = null; +let range = +(localStorage.getItem("sim.range") || 300), seenOpen = new Set(), seenClosed = 0, settingsDirty = false; +let stateRequest = 0, stateApplied = 0, realRequest = 0, realApplied = 0; +const readHealth = new Map(), pendingReads = new Map(), pendingCommands = new Set(), pendingPolls = new Map(), readGenerations = new Map(); +const FRESH_MS = 10000; +let accountData = null, accountBusy = false, pendingAccountAdjustment = null; +const accountIsStale = account => Array.isArray(account?.stale) ? account.stale.length > 0 : !!account?.stale; +const escapeHtml = value => String(value ?? "").replace(/[&<>"']/g, c => ({"&":"&", "<":"<", ">":">", '"':""", "'":"'"}[c])); + +// all times on the page are Moscow time, whatever the computer's time zone +const MSK = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", hour: "2-digit", minute: "2-digit", second: "2-digit"}); +const MSK_DAY = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", day: "2-digit", month: "2-digit"}); +const msk = seconds => MSK.format(new Date(seconds * 1000)); +const mskFull = seconds => { + const d = new Date(seconds * 1000), today = MSK_DAY.format(new Date()); + return (MSK_DAY.format(d) === today ? "" : MSK_DAY.format(d) + " ") + MSK.format(d); +}; +const fmt = (v, d = 4) => v == null || isNaN(v) ? "—" : (+v).toFixed(d); +const price = v => v == null ? "—" : (+v).toPrecision(6); +const money = v => (v >= 0 ? "+" : "") + (+v).toFixed(4) + " $"; +const cls = v => v > 0 ? "pos" : v < 0 ? "neg" : "mut"; +function commandNotice(message, bad = false) { + const el = document.getElementById("commandNotice"); + if (!el) return; + el.textContent = message; el.hidden = !message; el.className = bad ? "command-notice neg" : "command-notice pos"; +} +function freshRead(path) { + const h = readHealth.get(path); + return !!h && !h.error && Date.now() - h.time < FRESH_MS; +} +function invalidateRead(path) { + readGenerations.set(path, (readGenerations.get(path) || 0) + 1); + pendingReads.delete(path); readHealth.delete(path); +} +function commandRead(path) { + if (path.startsWith("/api/account/")) return "/api/account"; + if (/^\/api\/coin\/[^/]+\/remove$/.test(path)) return "/api/state"; + if (path.startsWith("/api/coin/")) return path.split("/").slice(0, 4).join("/"); + if (path.startsWith("/api/basis/")) return `/api/basis?ex=${path.split("/")[3]}`; + if (path.startsWith("/api/scanner/")) return "/api/scanner"; + if (path.startsWith("/api/real/")) return "/api/real"; + return "/api/state"; +} +function activeRead() { + if (tab === "basis") return `/api/basis?ex=${bxVenue}`; + if (tab === "real") return "/api/real"; + return selected === SCANNER ? "/api/scanner" : selected ? `/api/coin/${selected}` : "/api/state"; +} +function connectionLabel(path) { + const h = readHealth.get(path); + if (!h) return "Подключение к серверу…"; + const age = h.time ? Math.max(0, Math.floor((Date.now() - h.time) / 1000)) : null; + if (!freshRead(path)) return `Связь потеряна или данные устарели${age == null ? "" : ` · последние данные ${age} с назад`}. ${h.error || "Жду обновления"}. Команды заблокированы до восстановления связи.`; + return `Связь с сервером есть · получено ${age} с назад`; +} +function refreshConnection() { + const path = activeRead(), fresh = freshRead(path); + const el = document.getElementById("connectionStatus"); + if (el) { el.textContent = connectionLabel(path); el.className = fresh ? "connection-status connected" : "connection-status disconnected"; } + const mode = document.getElementById("modeStatus"); + if (mode) { + const selectedCoin = detail?.key === selected ? detail : state?.coins?.find(c => c.key === selected); + const live = tab === "basis" ? bxVenue === "cross_real" : tab === "sim" && !!selectedCoin?.real?.enabled; + mode.textContent = tab === "real" ? "API-ключи и журнал бирж" : tab === "sim" && selected && selected !== SCANNER && !selectedCoin ? "Режим выбранной монеты загружается…" : live ? "РЕАЛЬНАЯ ТОРГОВЛЯ · средства биржи" : "СИМУЛЯЦИЯ · общий виртуальный счёт"; + mode.className = live ? "mode-status mode-live" : "mode-status"; + } + document.querySelectorAll("button[onclick], input[onchange]").forEach(control => { + const handler = control.getAttribute("onclick") || control.getAttribute("onchange") || ""; + if (/\b(saveSettings|trade|resetCoin|removeCoin|closePos|scanner|addCoin|keySave|keyCheck|keyDelete|coinReal|simRealTransfer|simRealPing|simRealSl|simRealTpsl|basisReal|crossToggle|crossFeesSave|basisSave|basisRun|basisClose|basisAdopt|basisReset)\s*\(/.test(handler)) { + control.dataset.command = /\b(saveSettings|removeCoin)\b/.test(handler) ? "state" : /\b(keySave|keyCheck|keyDelete|simRealTransfer|simRealPing|simRealSl|simRealTpsl)\b/.test(handler) ? "real" : "active"; + } + }); + document.querySelectorAll("[data-command]").forEach(control => { + const source = control.dataset.command === "account" ? "/api/account" : control.dataset.command === "state" ? "/api/state" : control.dataset.command === "real" ? "/api/real" : path; + const blocked = !freshRead(source) || (source === "/api/account" && (accountBusy || accountData?.error || (accountIsStale(accountData) && control.dataset.accountDirection === "-1"))); + if (blocked && !control.dataset.connectionDisabled) { + control.dataset.wasDisabled = control.disabled ? "1" : "0"; control.dataset.connectionDisabled = "1"; control.disabled = true; + } else if (!blocked && control.dataset.connectionDisabled) { + control.disabled = control.dataset.wasDisabled === "1"; + delete control.dataset.connectionDisabled; delete control.dataset.wasDisabled; + } else if (blocked) control.disabled = true; + }); + updateAccountVisibility(); +} +function setControlDisabled(control, disabled) { + if (control.dataset?.connectionDisabled) control.dataset.wasDisabled = disabled ? "1" : "0"; + else control.disabled = disabled; +} +async function api(path, body) { + const reading = body === undefined; + if (reading && pendingReads.has(path)) return pendingReads.get(path); + const generation = readGenerations.get(path) || 0; + if (!reading && (!freshRead(commandRead(path)) || (path === "/api/real/simulator" && body.coin && !freshRead(`/api/coin/${body.coin}`)))) { + const error = new Error("Команда не отправлена: сначала дождитесь свежих данных сервера."); + commandNotice(error.message, true); throw error; + } + if (!reading && pendingCommands.has(path)) { + const error = new Error("Эта команда уже выполняется. Дождитесь ответа сервера."); + commandNotice(error.message, true); throw error; + } + const request = (async () => { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), reading ? 8000 : 20000); + if (!reading) pendingCommands.add(path); + try { + const response = await fetch(path, reading ? {signal: controller.signal, cache: "no-store"} : {method: "POST", signal: controller.signal, + headers: {"Content-Type": "application/json", "X-Sim": "1"}, body: JSON.stringify(body)}); + let data; + try { data = await response.json(); } catch (_) { throw new Error(`Сервер вернул некорректный ответ (HTTP ${response.status})`); } + if (!response.ok) throw new Error(data.error || `Ошибка сервера HTTP ${response.status}`); + if (reading && data.error && !(path === "/api/account" && data.balance != null)) throw new Error(data.error); + if (reading) { + if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: Date.now(), error: data.error || ""}); + } + else if (data.ok === false || data.error) commandNotice(data.error || data.message || "Команда отклонена сервером", true); + else commandNotice(data.message || "Команда подтверждена сервером"); + return data; + } catch (cause) { + const reason = cause.name === "AbortError" ? "Сервер не ответил вовремя" : cause.message || "Нет связи с сервером"; + if (reading) { + if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: readHealth.get(path)?.time || 0, error: reason}); + } + else { + cause.userMessage = `Результат команды не подтверждён: ${reason}. Проверьте состояние перед повтором. Автоматического повтора нет.`; + commandNotice(cause.userMessage, true); + } + cause.apiHandled = true; + throw cause; + } finally { + clearTimeout(timeout); + if (!reading) pendingCommands.delete(path); + refreshConnection(); + } + })(); + if (reading) { + pendingReads.set(path, request); + try { return await request; } finally { if (pendingReads.get(path) === request) pendingReads.delete(path); } + } + return request; +} +async function poll(task) { + if (pendingPolls.has(task)) return pendingPolls.get(task); + const work = (async () => { + try { await task(); } catch (error) { + if (!error.apiHandled) commandNotice(`Не удалось обновить интерфейс: ${error.message || "неожиданная ошибка"}`, true); + // api() records connectivity; the next scheduled read recovers. + } + })(); + pendingPolls.set(task, work); + try { await work; } finally { if (pendingPolls.get(task) === work) pendingPolls.delete(task); } +} +function updateAccountVisibility() { + const panel = document.getElementById("paperAccount"); + if (panel) panel.hidden = !(tab === "sim" || (tab === "basis" && bxVenue === "cross")); +} +function renderAccount(account) { + if (!account) return; + if (accountData && account.version != null && accountData.version != null && account.version < accountData.version) return; + if (accountData && account.version === accountData.version && account.updated_at != null && accountData.updated_at != null && account.updated_at < accountData.updated_at) return; + accountData = account; + const health = document.getElementById("accountHealth"); + if (health) { health.textContent = account.error || (accountIsStale(account) ? "Оценка открытых позиций устарела. Дождитесь свежих котировок." : "Один счёт для всех виртуальных сделок. Реальные деньги бирж учитываются отдельно."); health.className = account.error || accountIsStale(account) ? "statusline neg" : "statusline"; } + for (const key of ["balance", "equity", "reserved", "free"]) { + const el = document.getElementById(`account-${key}`); + if (el) el.textContent = account[key] == null ? "—" : `${Number(account[key]).toFixed(2)} $`; + } + const rows = document.getElementById("accountJournal"); + if (rows) rows.innerHTML = (account.journal || []).slice(0, 100).map(entry => `${entry.time ? mskFull(entry.time) : "—"}${escapeHtml(entry.reason || entry.type || entry.action || "Операция")}${entry.amount == null ? "—" : money(entry.amount)}${entry.balance == null ? "—" : Number(entry.balance).toFixed(2)}`).join("") || 'Операций пока нет'; +} +async function loadAccount() { renderAccount(await api("/api/account")); } +async function adjustAccount(direction) { + if (accountBusy) return; + const input = document.getElementById("accountDelta"), msg = document.getElementById("accountMsg"); + const value = input.value.trim().replace(",", "."); + if (!/^\d+(?:\.\d{1,8})?$/.test(value) || !Number.isFinite(Number(value)) || Number(value) <= 0) { + msg.textContent = "Введите сумму больше 0, до 8 знаков после запятой."; return; + } + const [whole, fraction = ""] = value.split("."), decimals = fraction.replace(/0+$/, ""); + const amount = `${direction < 0 ? "-" : ""}${whole.replace(/^0+(?=\d)/, "")}${decimals ? "." + decimals : ""}`; + if (accountData?.error || (direction < 0 && accountIsStale(accountData))) { msg.textContent = accountData.error || "Оценка открытых позиций устарела. Списание доступно после обновления котировок."; return; } + if (pendingAccountAdjustment && pendingAccountAdjustment.amount !== amount) { + msg.textContent = `Прошлая операция (${pendingAccountAdjustment.amount} $) не подтверждена. Повторите её с той же суммой: повторное списание или пополнение исключено по идентификатору.`; return; + } + const request = pendingAccountAdjustment || {amount, request_id: globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}`}; + accountBusy = true; refreshConnection(); msg.textContent = "Сохраняю операцию…"; + try { + // Keep the identifier only after freshness checks: a blocked command has not been sent. + if (!freshRead("/api/account")) { msg.textContent = "Нет свежих данных счёта. Дождитесь восстановления связи."; return; } + pendingAccountAdjustment = request; + const result = await api("/api/account/adjust", request); + pendingAccountAdjustment = null; + if (result.account) renderAccount(result.account); + msg.textContent = result.ok ? `${direction > 0 ? "Пополнено" : "Списано"}: ${Number(value).toFixed(2)} $. Виртуальные деньги.` : result.error || result.message || "Операция отклонена"; + if (result.ok) input.value = ""; + await poll(loadAccount); + } catch (_) { + msg.textContent = "Ответ не получен. Проверьте журнал. Повтор этой суммы использует тот же идентификатор и не проведёт операцию дважды."; + } finally { accountBusy = false; refreshConnection(); } +} + +function buildSettings() { + const s = state.settings; + const make = (box, list) => { + box.innerHTML = ""; + for (const [key, label, kind] of list) { + if (kind === "check") { + box.insertAdjacentHTML("beforeend", ``); + } else if (kind === "select") { + const opts = Object.entries(state.modes).map(([k, v]) => ``).join(""); + box.insertAdjacentHTML("beforeend", `
`); + } else { + box.insertAdjacentHTML("beforeend", `
`); + } + } + }; + make(document.getElementById("settingsMain"), MAIN_FIELDS); + make(document.getElementById("settingsMore"), MORE_FIELDS); + document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => { + settingsDirty = true; + document.getElementById("settingsMsg").textContent = "Есть несохранённые изменения — нажмите «Применить ко всем монетам»"; + })); + if (typeof applyHelpHints === "function") applyHelpHints(); + refreshConnection(); +} +function toggleMore() { + const m = document.getElementById("settingsMore"); + m.classList.toggle("open"); + document.getElementById("moreBtn").textContent = m.classList.contains("open") ? "Скрыть ▴" : "Ещё настройки ▾"; +} +async function saveSettings() { + const body = {}; + document.querySelectorAll("header [data-k]").forEach(el => body[el.dataset.k] = el.type === "checkbox" ? el.checked : el.value); + const r = await api("/api/settings", body); + const msg = document.getElementById("settingsMsg"); + msg.textContent = r.ok ? "Настройки применены ко всем монетам" : "Ошибка: " + r.error; + msg.style.color = r.ok ? "var(--green)" : "var(--red)"; + if (r.ok) { settingsDirty = false; await loadState(true); } +} + +function leaderBadge(c) { + const l = c.leadership || {}; + if (l.edge == null) return 'проверяется…'; + const edge = l.edge, who = edge >= 0 ? c.leader : c.follower; + const ok = !c.leader_block; + return `${who} ${ok ? "✓" : "✗"} (${Math.abs(l.pct ?? 0).toFixed(0)}%)`; +} +// Is the coin suitable for trades now: does the leader (DEX / KuCoin) really move before the futures? +function suitability(c) { + const l = c.leadership || {}, edge = l.edge, min = c.min_edge ?? 0.1; + const tip = l.edge == null ? "" : `${c.leader}→${c.follower} ${l.lead.toFixed(2)} / ${c.follower}→${c.leader} ${l.follow.toFixed(2)} · перевес ${edge >= 0 ? "+" : ""}${edge.toFixed(2)}, нужно ${min}`; + const pct = l.pct ?? 0; + let level, text; + if (edge == null) { + level = "check"; text = `◌ проверяю, кто ведёт (${(c.grid_minutes || 0).toFixed(1)} из 2 мин данных)`; + } else if (edge >= min) { + const mins = l.since ? (c.now - l.since) / 60 : 0; + const fresh = mins < 2; + level = fresh ? "new" : "ok"; + text = `● подходит: ${c.leader} опережает ${c.follower} на ${pct.toFixed(0)}%` + + (l.since ? ` · ${fresh ? "только что" : "уже " + mins.toFixed(0) + " мин"}, с ${msk(l.since).slice(0, 5)}` : ""); + } else if (edge > 0) { + level = "near"; text = `◐ почти: ${c.leader} впереди на ${pct.toFixed(0)}%, мало`; + } else { + level = "no"; text = `○ не подходит: ${c.follower} опережает ${c.leader} на ${(-pct).toFixed(0)}%`; + } + const stop = c.auto_stop ? `
⏸ ${c.auto_stop}
` : ""; + return {level, html: `
${text}
${stop}`}; +} +function renderTiles() { + const box = document.getElementById("tiles"); + box.innerHTML = state.coins.map(c => { + const realOn = !!(c.real && c.real.enabled); + if (realOn) c = {...c, trades: c.real.trades, wins: c.real.wins, net: c.real.net, unrealized: 0}; // exchange figures + const pnl = c.net + c.unrealized; + const fit = suitability(c); + return `
+ ${realOn ? 'РЕАЛ' : ""} + + +
${c.symbol} ${c.follower} + ${c.open ? `${c.open} откр.` : ""}
+
сигнал: ${c.leader} → фьючерс ${c.follower} ${c.follow_ticker}${c.live ? "" : " · нет данных"}
+ ${suitability(c).html} +
цена${price(c.price)}
+
сделок ${c.trades}${money(pnl)}
+
винрейт${c.trades + ? `${(c.wins / c.trades * 100).toFixed(0)}% · ${c.wins} из ${c.trades}` + : '—'}
+
`; + }).join("") + `
+
+
сканер новых монет
`; +} +async function loadState(rebuild) { + const request = ++stateRequest, result = await api("/api/state"); + if (request < stateApplied) return; + stateApplied = request; state = result; + renderAccount(state.account); + if (rebuild || !document.querySelector("header [data-k]")) buildSettings(); + if ((!selected || (selected !== SCANNER && !state.coins.some(c => c.key === selected))) && state.coins.length) { + detailEpoch++; detail = null; selected = state.coins[0].key; + } + renderTiles(); + refreshConnection(); +} +function selectCoin(key) { + detailEpoch++; + invalidateRead(key === SCANNER ? "/api/scanner" : `/api/coin/${key}`); + pendingPolls.delete(loadDetail); pendingPolls.delete(loadScanner); + selected = key; localStorage.setItem("sim.coin", key); + seenOpen = new Set(); seenClosed = 0; detail = null; + document.getElementById("center").textContent = "Загрузка выбранной монеты…"; + if (state) renderTiles(); refreshCenter(); refreshConnection(); +} +function refreshCenter() { return poll(selected === SCANNER ? loadScanner : loadDetail); } + +// --- scanner panel ------------------------------------------------------------------------------- +const SCANNER = "__scanner__"; +let scannerBuilt = false; +function scannerSkeleton() { + document.getElementById("center").innerHTML = ` +
Сканер новых монет
+
ищет монеты, где цена на DEX опережает фьючерсы (запись 15 мин на цикл, по кругу)
+
+
+
+
+ + + + +
+
+
+
+

Проверенные монеты — «Добавить» переносит монету в левую панель (остановленной); зелёные — где DEX опережал

+
+ + +
МонетаПроверокDEX опережалПоследний выводФьючерсПул DEXЛаг, сt+1→t+5Попад.tКогда
+
+

Журнал сканера

`; + scannerBuilt = true; +} +async function loadScanner() { + if (selected !== SCANNER || tab !== "sim") return; + const epoch = detailEpoch; + if (!document.getElementById("scRows")) scannerSkeleton(); + const s = await api("/api/scanner"); + if (selected !== SCANNER || epoch !== detailEpoch || tab !== "sim" || !document.getElementById("scRows")) return; + if (s.error) { document.getElementById("scMsg").textContent = s.error; return; } + setControlDisabled(document.getElementById("scStart"), s.running); + setControlDisabled(document.getElementById("scStop"), !s.running); + document.getElementById("scAuto").checked = s.auto_add; + document.getElementById("scState").innerHTML = s.running + ? `● сканер работает · циклов ${s.cycles}` : `■ сканер остановлен · циклов ${s.cycles}`; + document.getElementById("scLog").textContent = s.log.join("\n"); + document.getElementById("scRows").innerHTML = s.coins.map(c => { + let action; + if (c.in_list) action = 'в левой панели'; + else if (c.addable && c.leads) action = ``; + else if (c.addable) action = ``; + else action = `${c.unsupported || "нельзя добавить"}`; + return `${c.symbol}${c.checks} + ${c.leads}${c.verdict}${c.futures} ${c.futures_symbol} + ${c.dex_pool}${c.lag}${c.follow}%${c.hit} + ${c.t_stat}${c.last_lead || c.last_time}${action}`; + }).join("") || 'Пока нет результатов — запустите сканер; первый цикл ≈ 20 минут'; + refreshConnection(); +} +async function scanner(action) { + const body = action === "config" ? {auto_add: document.getElementById("scAuto").checked} + : {minutes: document.getElementById("scMin").value, coins: document.getElementById("scCoins").value}; + if (action === "start") { + body.minutes = Number(String(body.minutes).replace(",", ".")); body.coins = Number(body.coins); + if (!Number.isFinite(body.minutes) || body.minutes <= 0 || !Number.isInteger(body.coins) || body.coins < 1 || body.coins > 13) { + document.getElementById("scMsg").textContent = "Минут на цикл — число больше 0; монет за цикл — целое число от 1 до 13."; return; + } + } + const epoch = detailEpoch; + const result = await api(`/api/scanner/${action}`, body); + if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = result.error || result.message || "Команда подтверждена"; + setTimeout(() => { if (selected === SCANNER && epoch === detailEpoch) poll(loadScanner); }, 1200); +} +async function addCoin(symbol) { + const epoch = detailEpoch; + const r = await api("/api/scanner/add", {symbol}); + if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = r.message || r.error || ""; + await loadState(); if (selected === SCANNER && epoch === detailEpoch) await loadScanner(); +} + +function centerSkeleton() { + document.getElementById("center").innerHTML = ` +
+
+
+
+
+
+
${[60, 300, 600].map(s => ``).join(" ")}
+
+ +
изменение цены в % от начала окна · ▲▼ — входы, ● — выходы
+
+
+
+
+ + + + + + +
+
+
+
+

Сделки — открытые сверху (жёлтым), ✕ закрывает по текущей цене

+
+ + +
Время (МСК)Напр.Объём, $ВходВыход / сейчас%Итог, $КомиссияПричинаСек.Почему вошли
+
`; + document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === range)); +} +function setRange(s) { range = s; localStorage.setItem("sim.range", s); document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === s)); drawChart(); } +async function trade(action) { if (!coinReady()) return; const key = detail.key; await api(`/api/coin/${key}/${action}`, {}); loadDetail(); loadState(); } +async function resetCoin() { + if (!coinReady() || !confirm(`Сбросить статистику ${detail.symbol} (${detail.leader} → ${detail.follower})?\nИстория этой пары будет очищена. Общий виртуальный счёт не меняется. При открытых позициях сброс недоступен.`)) return; + const r = await api(`/api/coin/${selected}/reset`, {}); + if (document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || ""; + if (r.ok) { seenOpen = new Set(); seenClosed = 0; } + loadDetail(); loadState(); +} +async function removeCoin(key) { + const c = state.coins.find(x => x.key === key); + if (!c || !confirm(`Удалить ${c.name}?\n\nСбор цен и сравнение для этой пары остановятся` + + (c.open ? `, открытые позиции (${c.open}) закроются по текущей цене` : "") + + `.\nВернуть можно через «+» → сканер → «Добавить».`)) return; + const r = await api(`/api/coin/${key}/remove`, {}); + const wasSelected = selected === key; + if (wasSelected) selected = null; + await loadState(); + if (wasSelected) selectCoin(selected || SCANNER); + alert(r.message || r.error || ""); +} +function coinReady() { return !!detail && detail.key === selected; } +async function closePos(uid, key = detail?.key) { + if (!coinReady() || key !== selected) return; + const r = await api(`/api/coin/${key}/close${uid ? "/" + uid : ""}`, {}); + if (key === selected && document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || ""; + loadDetail(); +} + +async function loadDetail() { + if (tab !== "sim" || !selected || selected === SCANNER) return; + const key = selected, epoch = detailEpoch, request = ++detailRequest; + const d = await api(`/api/coin/${key}`); + if (key !== selected || epoch !== detailEpoch || request < detailApplied) return; + detailApplied = request; + if (d.error) { document.getElementById("center").innerHTML = `
${d.error}
`; return; } + if (!document.getElementById("chart") || !detail || detail.key !== d.key) centerSkeleton(); + detail = d; + document.getElementById("cName").innerHTML = `${d.symbol} фьючерс на ${d.follower} + сигнал: ${d.leader} → ставки: ${d.follower} ${d.follow_ticker}`; + const lat = v => v == null ? "" : ` · ~${v.toFixed(0)} мс`; + const linksBox = document.getElementById("cLinks"); + const linksHtml = (d.links || []).map(l => `${l.label} ↗`).join(""); + if (linksBox.innerHTML !== linksHtml) linksBox.innerHTML = linksHtml; + document.getElementById("cFeeds").textContent = `${d.lead_status}${lat(d.lead_latency)} | ${d.follow_status}${lat(d.follow_latency)}`; + document.getElementById("lgLead").textContent = `${d.leader}: ${price(d.lead_price)}`; + document.getElementById("lgFollow").textContent = `${d.follower} ${d.follow_ticker}: ${price(d.bid)} / ${price(d.ask)}`; + const winPct = d.trades ? (d.wins / d.trades * 100).toFixed(0) + "%" : "—"; + const realOn = !!(d.real && d.real.enabled); + const rb = document.getElementById("btnReal"); + rb.textContent = realOn ? "● РЕАЛЬНАЯ торговля — выключить" : "Включить реальную торговлю"; + rb.className = realOn ? "realon" : ""; + let stats; + if (realOn) { + // real mode: every figure is from the exchange (its fill history for this coin, the account's balance) + const r = d.real, bal = real && real.balances && real.balances[d.exchange]; + const age = bal && bal.time ? Math.round(Date.now() / 1000 - bal.time) : null; + const balText = !bal ? "нет ключей" : !bal.values ? `${bal.error}` + : Object.entries(bal.values).map(([k, v]) => `
${k}: ${typeof v === "number" ? v.toFixed(4) : v}
`).join("") + + `
${bal.error ? 'не обновился: ' + bal.error + " · " : ""}${age} с назад
`; + const stateText = {"": "нет", opening: "открывается…", open: "открыта", closing: "закрывается…", check: "проверка закрытия…"}[r.state] || r.state; + const src = r.source === "биржа" ? `история биржи, ${Math.round(Date.now() / 1000 - r.synced)} с назад` + + (r.sync_error ? ` · ${r.sync_error}` : "") : `жду историю биржи${r.sync_error ? ": " + r.sync_error : ""}`; + stats = [ + ["Баланс на бирже", balText, ""], ["Реальных сделок", r.trades, ""], + ["В плюс", r.trades ? `${r.winrate.toFixed(0)}% · ${r.wins} из ${r.trades}` : "—", ""], + ["PNL биржи (до комиссий)", money(r.gross), cls(r.gross)], ["Комиссии биржи", "−" + r.fees.toFixed(4) + " $", "neg"], + ["Итог после комиссий", money(r.net), cls(r.net)], ["Итог, % от объёма", r.net_pct == null ? "—" : r.net_pct.toFixed(3) + "%", cls(r.net_pct || 0)], + ["Реальная позиция", stateText + (r.problem ? `
${r.problem}
` : "") + + (r.paused_s > 0 ? `
пауза ${Math.ceil(r.paused_s / 60)} мин: ${r.last_error}
` : ""), + r.state || r.paused_s > 0 ? "neg" : ""], + ["Откуда цифры", `${src}`, ""], + ]; + } else { + stats = [ + ["Общий виртуальный баланс", accountData ? Number(accountData.balance).toFixed(2) + " $" : "—", ""], ["Сделок", d.trades, ""], ["В плюс", winPct, ""], + ["Итог", money(d.net), cls(d.net)], ["Комиссии", d.fees.toFixed(4) + " $", ""], + ["Открыто", `${d.open} · ${money(d.unrealized)}`, cls(d.unrealized)], + ]; + } + stats.push( + ["Сигнал", `${d.signal >= 0 ? "+" : ""}${d.signal.toFixed(3)}%`, cls(d.signal)], + ["Уверенность", d.confidence.toFixed(2), ""], + ["Кто ведёт", leaderBadge(d), ""], + ["Подходит для сделок", suitability(d).html, ""]); + if (state && state.settings.auto_tp) stats.push(["Прогноз", `${d.forecast.toFixed(3)}%`, ""]); + document.getElementById("stats").innerHTML = stats.map(([k, v, c]) => `
${k}
${v}
`).join(""); + setControlDisabled(document.getElementById("btnStart"), d.running); + setControlDisabled(document.getElementById("btnStop"), !d.running); + document.getElementById("cStatus").textContent = (d.running ? "● сделки открываются · " : "■ новые сделки остановлены (цены и прогноз работают) · ") + d.status; + if (d.message) document.getElementById("cMsg").textContent = d.message; + renderRows(d); + drawChart(); + refreshConnection(); +} + +function renderRows(d) { + const t = mskFull; + const open = d.positions.map(p => { + const fresh = !seenOpen.has(p.uid); seenOpen.add(p.uid); + return `${t(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.side}${p.usd.toFixed(2)} + ${price(p.entry)}${price(p.side === "LONG" ? d.bid : d.ask)}${p.pct.toFixed(3)}% + ${money(p.pnl)}тейк ${price(p.target)} · стоп ${price(p.stop)} + открыта${p.age.toFixed(0)}${p.why} + `; + }).join(""); + if (d.real && d.real.enabled) { + // real mode: closed trades are the real ones, rebuilt from the exchange's own fills + const rows = (d.real_trades || []).map(c => ` + ${mskFull(c.closed)} РЕАЛ${c.side}${(c.entry * c.coins).toFixed(2)} + ${price(c.entry)}${price(c.exit)}${c.pct.toFixed(3)}% + ${money(c.net)} + ${c.fees.toFixed(4)}${c.exact ? "" : ' ≈'} + PNL биржи ${money(c.gross)}${(c.closed - c.opened).toFixed(0)}${c.reason}`).join(""); + document.getElementById("rows").innerHTML = open + rows || 'Реальных сделок пока нет'; + return; + } + const freshClosed = d.closed.length - seenClosed; seenClosed = d.closed.length; + const closed = d.closed.map((c, i) => ` + ${mskFull(Date.parse(c.closed) / 1000)}${c.side}${c.usd.toFixed(2)}${price(c.entry)}${price(c.exit)} + ${c.pct.toFixed(3)}%${money(c.net)}${c.fee.toFixed(4)} + ${c.reason}${c.hold.toFixed(0)}${c.why}`).join(""); + document.getElementById("rows").innerHTML = open + closed || 'Сделок пока нет'; +} + +function drawChart() { + const cv = document.getElementById("chart"); if (!cv || !detail) return; + const dpr = window.devicePixelRatio || 1, w = cv.clientWidth, h = cv.clientHeight; + cv.width = w * dpr; cv.height = h * dpr; + const g = cv.getContext("2d"); g.scale(dpr, dpr); g.clearRect(0, 0, w, h); + const t1 = detail.now, t0 = t1 - range, pad = {l: 52, r: 10, t: 10, b: 22}; + const norm = s => { const pts = s.filter(p => p[0] >= t0); if (!pts.length) return []; const b = pts[0][1]; return pts.map(p => [p[0], (p[1] / b - 1) * 100]); }; + const L = norm(detail.lead_series), F = norm(detail.follow_series); + const all = L.concat(F).map(p => p[1]); + let lo = Math.min(-0.05, ...all), hi = Math.max(0.05, ...all); const span = hi - lo; lo -= span * 0.08; hi += span * 0.08; + const X = t => pad.l + (t - t0) / (t1 - t0) * (w - pad.l - pad.r), Y = v => pad.t + (hi - v) / (hi - lo) * (h - pad.t - pad.b); + g.strokeStyle = "#2a3240"; g.fillStyle = "#8b95a7"; g.font = "11px Segoe UI"; g.lineWidth = 1; + const raw = (hi - lo) / 5, mag = Math.pow(10, Math.floor(Math.log10(raw))); + const step = [1, 2, 5, 10].map(k => k * mag).find(s => s >= raw); + for (let v = Math.ceil(lo / step) * step; v <= hi; v += step) { + g.beginPath(); g.moveTo(pad.l, Y(v)); g.lineTo(w - pad.r, Y(v)); g.stroke(); + g.fillText(v.toFixed(step < 0.01 ? 3 : 2) + "%", 4, Y(v) + 4); + } + for (let k = 0; k <= 4; k++) { const t = t0 + k * range / 4; g.fillText(msk(t), X(t) - 22, h - 6); } + const line = (pts, color, stepped) => { + if (!pts.length) return; g.strokeStyle = color; g.lineWidth = 1.8; g.beginPath(); + pts.forEach((p, i) => { const x = X(p[0]), y = Y(p[1]); if (!i) g.moveTo(x, y); else { if (stepped) g.lineTo(x, Y(pts[i - 1][1])); g.lineTo(x, y); } }); + g.lineTo(X(t1), Y(pts[pts.length - 1][1])); g.stroke(); + }; + line(L, getComputedStyle(document.body).getPropertyValue("--lead"), true); + line(F, getComputedStyle(document.body).getPropertyValue("--follow"), false); + // trade markers on the futures line + const at = t => { let best = null; for (const p of F) { if (p[0] <= t) best = p; else break; } return best || F[0]; }; + const mark = (t, up, color, circle) => { + if (t < t0 || !F.length) return; const p = at(t); if (!p) return; const x = X(t), y = Y(p[1]); + g.fillStyle = color; g.beginPath(); + if (circle) g.arc(x, y, 3.5, 0, 7); else if (up) { g.moveTo(x, y - 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); } else { g.moveTo(x, y + 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); } + g.fill(); + }; + for (const c of detail.closed) { + const tc = Date.parse(c.closed) / 1000; if (tc < t0) continue; + mark(tc - c.hold, c.side === "LONG", "#8b95a7"); mark(tc, false, c.net > 0 ? "#2ecc71" : "#ff5c5c", true); + } + for (const p of detail.positions) mark(p.opened, p.side === "LONG", "#f5c542"); + if (!L.length && !F.length) { g.fillStyle = "#8b95a7"; g.fillText("копятся цены…", w / 2 - 40, h / 2); } +} + +// --- arbitrage tab ------------------------------------------------------------------------------- +let tab = localStorage.getItem("sim.tab") || "sim", arb = null, arbSort = localStorage.getItem("arb.sort") || "net_transfer"; +let arbMarket = localStorage.getItem("arb.market") || "spot"; +let arbOpen = new Set(), arbExBuilt = false, feesFor = null; +const isSpot = () => arbMarket === "spot"; +const val = (id, d) => { const v = parseFloat(document.getElementById(id).value); return isNaN(v) ? d : v; }; +// --- budget calculator (top of the page, every tab) ----------------------------------------------------------- +// One spot–futures trade of «stake» $: the coins bought on spot (stake + fees) and the short's futures money. With +// E $ behind a short of N $ the short is liquidated at a rise of x = (E/N − mmr)/(1 + mmr), so for a wanted x: +// E = N·((1 + mmr)·x + mmr) — the same formula the program checks before every short. +const CALC_IDS = ["cStake", "cCount", "cLiq", "cEx", "cMmr", "cFee"]; +function calcToggle() { + const p = document.getElementById("calcPanel"), open = p.style.display === "none"; + p.style.display = open ? "" : "none"; + document.getElementById("calcBtn").classList.toggle("on", open); + if (open) calcRun(); +} +function calcRun() { + const v = id => { const x = parseFloat(String(document.getElementById(id).value).replace(",", ".")); return isFinite(x) ? x : NaN; }; + const stake = v("cStake"), n = Math.floor(v("cCount")), liq = v("cLiq"), ex = Math.floor(v("cEx")), mmr = v("cMmr") / 100, + fee = v("cFee") / 100; + const out = document.getElementById("calcOut"); + try { localStorage.setItem("calc", JSON.stringify(Object.fromEntries(CALC_IDS.map(i => [i, document.getElementById(i).value])))); } catch (e) {} + if (![stake, n, liq, ex, mmr, fee].every(isFinite) || stake <= 0 || n < 1 || liq <= 0 || ex < 1 || mmr < 0 || fee < 0) { + out.innerHTML = '
Заполните поля положительными числами
'; return; + } + const spot = stake * (1 + fee); // the coins bought on spot, with the buy fee + const futFor = x => stake * ((1 + mmr) * x / 100 + mmr); // futures money for a liquidation x % above the entry + const fut = futFor(liq), money = x => x.toFixed(2) + " $"; + const back = stake * (liq / 100); // what the short loses at the liquidation price + // what the program itself requires before an entry (cross.py: SPOT_NEED 1.01, FUT_NEED 1.03 or more for the + // liquidation reserve): spot of A ≥ 101 % of the stake, futures of B ≥ max(103 %, the reserve's money) + const pSpot = stake * 1.01, pFut = Math.max(stake * 1.03, fut); + const progLiq = ((pFut / stake) - mmr) / (1 + mmr) * 100; + // money on the accounts for the wanted move to the liquidation: the futures account carries the shorts, the spot + // account buys the coins; between exchanges every trade has its spot on one exchange and its short on another + const trades = Math.max(1, Math.floor(n * ex / 2)); // n per exchange, each trade takes two exchanges + const steps = [...new Set([25, 50, 100, 150, 200, Math.round(liq)])].sort((a, b) => a - b); + out.innerHTML = ` +
Цена может вырасти на ${liq}% до ликвидации шорта — для этого на счетах каждой биржи: +
Фьючерсный счёт (${n} шорт.)${money(n * fut)}
+
Спотовый счёт (${n} покупок монет)${money(n * spot)}
+
С автопереводом между спотом и фьючерсами биржи${money(n * Math.max(spot, fut))}
+
Под шорты: ${n} × ${money(fut)}; ликвидация при росте монеты на ${liq}% (шорт теряет ≈ ${money(back)} на сделку). + Сделки одной биржи: шорты на её фьючерсах, покупки — на её споте.
+
Всего на ${ex} ${ex === 1 ? "бирже" : "биржах"}: ${money(n * Math.max(spot, fut) * ex)} +
чтобы каждая биржа могла быть и стороной спота, и стороной шорта в ${n} сделках. Минимум, если + все ${trades} сделок в одну сторону (спот на одних биржах, шорт на других): ${money(trades * (spot + fut))}
+
Одна сделка: спот / фьючерсы / обе ноги${money(spot)} / ${money(fut)} / ${money(spot + fut)}
+
Спот-фьюч на одной бирже (обе ноги там же), ${n} сделок${money(n * (spot + fut))}
+ + ${steps.map(x => ` + `).join("")}
До ликвидацииФьючерсы на 1 шортФьючерсы на ${n} шорт.
+${x}%${money(futFor(x))}${money(n * futFor(x))}
+
По текущей логике программы на каждой бирже: ${money(n * Math.max(pSpot, pFut))}, + всего на ${ex}: ${money(n * Math.max(pSpot, pFut) * ex)} +
Фьючерсный / спотовый счёт${money(n * pFut)} / ${money(n * pSpot)}
+ ${liq < progLiq - 0.5 ? `
Желаемые ${liq}% меньше, чем держит программа: + на фьючерсах будет ${money(n * pFut)} и ликвидация ≈ +${progLiq.toFixed(0)}% — дальше, чем вы просили.
` : ""} +
Перед входом программа требует на споте биржи A 101% ставки, а на фьючерсах биржи B — не меньше + 103% ставки (ликвидация ≈ +${progLiq.toFixed(0)}%) или больше, если «Мин. запас до ликвидации» выше. Меньше — биржа + краснеет и не участвует в поиске.
`; +} +async function calcFromSettings() { + const r = await api("/api/basis?ex=cross_real"); + if (!r || r.error) return; + const limits = ((r.balances || {}).rows || []).map(x => x.limit).filter(x => x != null); + document.getElementById("cStake").value = r.settings.amount; + document.getElementById("cLiq").value = r.settings.min_liq_pct; + if (limits.length) document.getElementById("cCount").value = Math.max(...limits); + const keyed = ((r.balances || {}).rows || []).filter(x => x.keys && x.on).length; + if (keyed) document.getElementById("cEx").value = keyed; + calcRun(); +} +(function calcInit() { + let saved = {}; + try { saved = JSON.parse(localStorage.getItem("calc") || "{}"); } catch (e) {} + for (const id of CALC_IDS) { + const el = document.getElementById(id); + if (saved[id] != null) el.value = saved[id]; + el.addEventListener("input", calcRun); + } +})(); +function showTab(name) { + if (name === "arb") name = "basis"; // the old «Арбитраж» is gone: the one mode lives in «basis» + tab = name; localStorage.setItem("sim.tab", name); + document.getElementById("simView").style.display = name === "sim" ? "" : "none"; + document.getElementById("basisView").style.display = name === "basis" ? "" : "none"; + document.getElementById("realView").style.display = name === "real" ? "" : "none"; + document.getElementById("tabSim").classList.toggle("on", name === "sim"); + document.getElementById("tabArb").classList.toggle("on", name === "basis"); + document.getElementById("tabReal").classList.toggle("on", name === "real"); + if (name === "basis") poll(loadBasis); + if (name === "real") { realBuilt = false; poll(loadReal); } + if (name === "sim") refreshCenter(); + refreshConnection(); +} + +// --- real trading: keys, switches, journal ------------------------------------------------------- +let real = null, realBuilt = false; +async function loadReal() { + const request = ++realRequest, result = await api("/api/real"); + if (request < realApplied) return; + realApplied = request; real = result; + const s = real.simulator; + const tpsl = document.getElementById("simRealTpsl"); + if (document.activeElement !== tpsl) tpsl.checked = s.exchange_tpsl !== false; + const trBox = document.getElementById("simRealTransfer"); + if (document.activeElement !== trBox) trBox.checked = s.auto_transfer !== false; + const slBox = document.getElementById("simRealSl"); + if (document.activeElement !== slBox) slBox.value = s.sl_pct ?? 1.5; + const pingBox = document.getElementById("simRealPing"); + if (document.activeElement !== pingBox) pingBox.value = s.max_ping_ms ?? 400; + const fees = Object.entries(s.fees || {}).map(([e, p]) => `${e} ${p.toFixed(3)}%`).join(", "); + const lat = Object.entries(real.latency || {}).map(([h, ms]) => `${h.split(".").slice(0, -1).join(".")} ${ms.toFixed(0)} мс`).join(", "); + document.getElementById("simRealFees").textContent = (fees ? `· комиссия с биржи: ${fees}` : "") + (lat ? ` · задержка до бирж: ${lat}` : ""); + const realCoins = state ? state.coins.filter(c => c.real && c.real.enabled).map(c => c.symbol) : []; + document.getElementById("simReal").classList.toggle("on", realCoins.length > 0); + document.getElementById("simRealHint").innerHTML = realCoins.length + ? `РЕАЛЬНАЯ ТОРГОВЛЯ: ${realCoins.join(", ")} · остальные монеты — виртуальные сделки` + : "виртуальные сделки, ордера на биржи не отправляются"; + if (tab !== "real") return; + if (!realBuilt) { + document.getElementById("keyCards").innerHTML = Object.entries(real.keys).map(([ex, k]) => `
+ ${k.name} + + +
+ +
+
`).join(""); + realBuilt = true; + } + for (const [ex, k] of Object.entries(real.keys)) { + document.getElementById(`kst-${ex}`).innerHTML = k.set ? `ключ сохранён: ${k.key}` : 'ключей нет'; + } + document.getElementById("realJournal").innerHTML = real.journal.map(j => ` + ${mskFull(j.time)}${j.tab === "basis" ? "Арбитраж" : "Симулятор"}${j.exchange}${j.coin} + ${{open: "открытие", close: "закрытие", orphan: "закрытие осиротевшей", transfer: "перевод USDT"}[j.action] || j.action} + ${j.text}`).join("") + || 'Реальных ордеров ещё не было'; +} +async function keySave(ex) { + const key = document.getElementById(`kk-${ex}`), secret = document.getElementById(`ks-${ex}`); + const r = await api(`/api/real/keys/${ex}`, {api_key: key.value, api_secret: secret.value}); + document.getElementById(`kmsg-${ex}`).innerHTML = r.ok ? 'сохранено' : `${r.error}`; + if (r.ok) { key.value = ""; secret.value = ""; } + loadReal(); +} +async function keyCheck(ex) { + const msg = document.getElementById(`kmsg-${ex}`); + msg.textContent = "проверяю…"; + const r = await api(`/api/real/keys/${ex}/check`, {}); + msg.innerHTML = r.ok ? 'ключи работают: ' + Object.entries(r.balances).map(([k, v]) => + `${k} ${typeof v === "number" ? v.toFixed(2) : v}`).join(" · ") + "" : `${r.error}`; +} +async function keyDelete(ex) { + if (!confirm("Удалить сохранённые ключи этой биржи?")) return; + const r = await api(`/api/real/keys/${ex}/delete`, {}); + document.getElementById(`kmsg-${ex}`).textContent = r.ok ? "удалены" : r.error || r.message || "Удаление не подтверждено"; + loadReal(); +} +async function coinReal() { + if (!coinReady()) return; + const want = !(detail.real && detail.real.enabled); + if (want) { + const keys = real && real.keys[detail.exchange]; + if (!keys || !keys.set) { alert(`Сначала сохраните API-ключи ${detail.follower} во вкладке «Реальная торговля · API-ключи».`); return; } + if (!confirm(`Включить РЕАЛЬНУЮ торговлю для ${detail.symbol} (${detail.follower} ${detail.follow_ticker})?\n\n` + + "Каждая новая позиция этой монеты будет открываться настоящим рыночным ордером на фьючерсе " + + `(ставка × плечо из настроек)${real.simulator.exchange_tpsl !== false ? ", с TP и SL на бирже" : ""}. ` + + "Одна сделка за раз: следующая — только после подтверждённого закрытия.")) return; + } + const r = await api("/api/real/simulator", {coin: detail.key, enabled: want}); + document.getElementById("cMsg").textContent = r.ok ? (want ? "реальная торговля включена" : "реальная торговля выключена") : r.error; + await loadState(); await loadReal(); loadDetail(); +} +async function simRealTransfer() { + const r = await api("/api/real/simulator", {auto_transfer: document.getElementById("simRealTransfer").checked}); + document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error; + loadReal(); +} +async function simRealPing() { + const r = await api("/api/real/simulator", {max_ping_ms: document.getElementById("simRealPing").value}); + document.getElementById("simRealMsg").textContent = r.ok ? "порог пинга сохранён" : r.error; + loadReal(); +} +async function simRealSl() { + const r = await api("/api/real/simulator", {sl_pct: document.getElementById("simRealSl").value}); + document.getElementById("simRealMsg").textContent = r.ok ? "стоп-лосс сохранён" : r.error; + loadReal(); +} +async function simRealTpsl() { + const r = await api("/api/real/simulator", {exchange_tpsl: document.getElementById("simRealTpsl").checked}); + document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error; + loadReal(); +} +async function basisReal() { + if (!basisReady()) return; + const want = !bx.settings.real; + if (want && bx.mode === "cross") { + const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange); + if (ready.length < 2) { alert("Нужны API-ключи хотя бы двух включённых бирж (вкладка «Реальная торговля · API-ключи»)."); return; } + if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Между биржами»?\n\nБиржи с ключами: ${ready.join(", ")}.\n\nПри входе: шорт на бирже B, ` + + `затем покупка тех же монет на споте биржи A на ${bx.settings.amount} $; при возврате разницы к обычной — выкуп шорта и продажа ` + + "спота. Нужны USDT на споте A и на фьючерсах B. Одна сделка за раз; изменение баланса считается с момента «Старт».")) return; + } else if (want) { + const keys = (real && real.keys[bxVenue]) || {}; + if (!keys.set) { alert(`Сначала сохраните API-ключи ${bx.venue} во вкладке «Реальная торговля · API-ключи».`); return; } + if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Спот-фьюч» на ${bx.venue}?\n\nПри входе: покупка монеты на споте на ` + + `${bx.settings.amount} $ и шорт того же количества на фьючерсе; при схождении — выкуп шорта и продажа спота.`)) return; + } + const r = await api(`/api/basis/${bxVenue}/settings`, {real: want}); + document.getElementById("bxMsg").textContent = r.ok ? "" : r.error; + loadBasis(); +} + +// --- spot–futures tab -------------------------------------------------------------------------- +// «Арбитраж»: the simulation and real trading — two engines, each with its own Start / Stop, settings and trades +const BX_VENUES = [["cross", "Симуляция"], ["cross_real", "● Реальная торговля"]]; +const BX_READY = new Set(["cross", "cross_real"]); +// «between exchanges»: spot on A, perp on B — its own settings and tables +const CX_FIELDS = [ + ["amount", "Сумма сделки, $"], ["min_net_pct", "Мин. чистая прибыль для входа, %"], + ["max_gap_pct", "Макс. разница, %"], ["history_min", "Наблюдать пару не меньше, мин"], + ["exit_over_usual_pct", "Закрыть при разнице ≤ обычной + , %"], + ["exit_hold_s", "Выход: условие держится не меньше, с (0 — сразу)"], + ["stop_widen_pct", "Стоп: разница шире входа на, % (0 — нет)"], + ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["cooldown_s", "Пауза по монете, с"], + ["min_turnover", "Мин. оборот каждой ноги 24ч, $"], ["limit_hold_s", "Лимитный вход: ждать, с"], + ["negative_funding_before_minutes", "При отрицательном funding не входить за, мин"], + ["min_funding_pct", "Не входить, если funding ниже, %"], + ["simulation_entry_delay_ms", "Задержка открытия в симуляции, мс"], + ["simulation_exit_delay_ms", "Задержка закрытия в симуляции, мс"], + ["max_spread_pct", "Макс. спред каждой ноги, % (0 — нет)"], + ["confirm_ms", "Подтверждение по стакану: пауза между 2 проверками, мс"], + ["min_liq_pct", "Мин. запас до ликвидации шорта при входе, %"], + ["liq_close_pct", "Закрыть, если до ликвидации меньше, % (0 — нет)"]]; +const CX_CHECKS = [["search_sf", "Искать: спот → фьючерс между биржами"], ["search_in", "Искать: спот → фьючерс внутри биржи"], + ["search_ss", "Искать: спот → спот между биржами (реально — из запаса монеты на бирже продажи)"], + ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами внутри биржи (реальный режим)"], + ["entry_ioc", "Вход первой ногой лимитным IOC по подтверждённой цене: не исполнился — сделки нет (реальный режим)"], + ["entry_limit", "Вход лимитным шортом с ожиданием «Лимитный вход: ждать, с» (если IOC выключен)"], + ["block_negative_funding", "Не открывать сделку при отрицательном funding"], + ["fees_auto", "Комиссии сами корректируются по завершённым реальным сделкам"]]; +const CX_EX = ["Bybit", "Binance", "MEXC", "HTX", "Gate"]; +// the balances card: built once (the fee fields keep what is typed), its figures refreshed with every update +function cxBalBuild() { + document.getElementById("cxBal").innerHTML = CX_EX.map(e => ` + ${e}
+ + ————— + 0 / +
+
${e === "Bybit" + ? `
зона инноваций:
+
` : ""}`).join(""); + document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => el.addEventListener("input", () => { + el.dataset.dirty = "1"; document.getElementById("cxBalMsg").textContent = "есть изменения — нажмите «Сохранить комиссии и лимиты»"; })); +} +function cxBalRender() { + const b = bx.balances, s = bx.settings; + if (!b) return; + const money = v => v == null ? "—" : v.toFixed(2); + const chg = (p, usd) => p == null ? '—' + : `${pct(p, 2)}${usd != null ? ` (${dollars(usd)} $)` : ""}`; + for (const r of b.rows) { + const e = r.exchange, on = document.getElementById(`cxon-${e}`); + if (!on) continue; + on.checked = r.on; + // too little money for a trade of «Сумма»: red, out of the search until it is topped up (then back by itself) + const tr = document.getElementById(`cxrow-${e}`); + tr.style.background = r.low_funds ? "rgba(239, 68, 68, 0.16)" : ""; + tr.style.boxShadow = r.low_funds ? "inset 3px 0 0 #ef4444" : ""; + document.getElementById(`cxk-${e}`).innerHTML = (r.low_funds + ? `${r.low_funds} — не участвует в поиске, вернётся сама после пополнения
` : "") + + (!r.keys ? "нет API-ключей" + : r.error ? `ошибка чтения` + : r.age != null ? `${r.age.toFixed(0)} с назад` : ""); + document.getElementById(`cxs-${e}`).innerHTML = r.unified ? `${money(r.spot)} единый счёт` : money(r.spot); + document.getElementById(`cxf-${e}`).textContent = r.unified ? "—" : money(r.futures); + document.getElementById(`cxc-${e}`).textContent = r.coins ? money(r.coins) : r.keys ? "0.00" : "—"; + document.getElementById(`cxt-${e}`).innerHTML = `${money(r.total)}`; + document.getElementById(`cxd-${e}`).innerHTML = chg(r.change_pct, r.start != null && r.total != null ? r.total - r.start : null); + const oc = document.getElementById(`cxo-${e}`); + oc.textContent = r.open_count; oc.className = r.open_count >= r.limit ? "neg" : ""; + const li = document.querySelector(`#cxBal input[data-cxlimit="${e}"]`); + if (document.activeElement !== li && !li.dataset.dirty) li.value = r.limit; + for (const leg of ["spot", "fut", "fut_innovation"]) { + const el = document.querySelector(`#cxBal input[data-cxfee="${e}|${leg}"]`); + if (!el) continue; + if (document.activeElement !== el && !el.dataset.dirty) el.value = r[`fee_${leg}`]; + document.getElementById(`cxsrc-${e}-${leg}`).textContent = r[`fee_${leg}_src`] || "базовая"; + } + } + document.getElementById("cxBalTotal").innerHTML = `Всего на всех биржах с ключами` + + (b.start_time ? ` · отсчёт с запуска ${mskFull(b.start_time)} МСК${b.start_total != null ? ` (было ${money(b.start_total)} $)` : " — жду первые балансы после запуска"}` + : ' · изменение считается с момента запуска реальной торговли (кнопка «Старт»)') + + `${money(b.total)}${chg(b.change_pct, b.change_usd)}`; +} +async function crossToggle(ex, on) { + if (!basisReady()) return; + const r = await api(`/api/basis/${bxVenue}/settings`, {[`use_${ex.toLowerCase()}`]: on}); + document.getElementById("cxBalMsg").textContent = r.ok ? `${ex}: ${on ? "включена в поиск и торговлю" : "выключена из поиска и торговли"}` : r.error; + loadBasis(); +} +async function crossFeesSave() { + if (!basisReady()) return; + const venue = bxVenue, epoch = bxEpoch; + const fees = {}, limits = {}; + document.querySelectorAll("#cxBal input[data-cxfee]").forEach(el => { + const [e, leg] = el.dataset.cxfee.split("|"); (fees[e] = fees[e] || {})[leg] = el.value; }); + document.querySelectorAll("#cxBal input[data-cxlimit]").forEach(el => limits[el.dataset.cxlimit] = el.value); + const r = await api(`/api/basis/${venue}/settings`, {fees, limits}); + if (venue !== bxVenue || epoch !== bxEpoch) return; + document.getElementById("cxBalMsg").textContent = r.ok ? "комиссии и лимиты сделок сохранены" : r.error; + if (r.ok) { + document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => delete el.dataset.dirty); + rememberBasisDraft(); + } + loadBasis(); +} +const CX_ROWS_HEAD = `МонетаТипПокупка наПродажа / шорт на + Покупка (ask)Продажа (bid)Разница для входа + Обычная + Выше обычной + Чистая прибыль, % + Наблюдаем, минFunding (шорт)Объём по ценам, $ + Мин. вход, $ + Оборот 24ч`; +const CX_POS_HEAD = `Время (МСК)МонетаТип · биржиМонетКуплено (A)Продано / шорт (B) + Разница при входеОбычная (цель)Разница сейчас + До ликвидации, % + Funding $Комиссии $Если закрыть сейчас`; +let bxHeads = null; +let bxVenue = ["cross", "cross_real"].includes(localStorage.getItem("bx.venue")) ? localStorage.getItem("bx.venue") : "cross", bx = null, bxBuilt = false, bxDirty = false; +const basisDrafts = new Map(); +function rememberBasisDraft() { + if (!bxBuilt) return; + const fields = {}; + document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => { + if (!el.dataset.bx && !el.dataset.dirty) return; + if (el.dataset.bx && !bxDirty) return; + const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`; + fields[key] = el.type === "checkbox" ? el.checked : el.value; + }); + if (Object.keys(fields).length) basisDrafts.set(bxVenue, fields); else basisDrafts.delete(bxVenue); +} +function restoreBasisDraft() { + const draft = basisDrafts.get(bxVenue); + if (!draft) return; + document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => { + const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`; + if (!(key in draft)) return; + if (el.type === "checkbox") el.checked = draft[key]; else el.value = draft[key]; + if (el.dataset.bx) bxDirty = true; else el.dataset.dirty = "1"; + }); + document.getElementById("bxMsg").textContent = "Восстановлены несохранённые изменения этого режима"; +} +let bxSort = localStorage.getItem("bx.sort") || "entry_gap"; +const BX_FIELDS = [ + ["amount", "Сумма сделки, $"], ["min_gap_pct", "Мин. расхождение для входа, %"], ["max_gap_pct", "Макс. расхождение, %"], + ["exit_gap_pct", "Закрыть при разнице ≤, %"], ["stop_gap_pct", "Стоп: разница ≥, % (0 — нет)"], + ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["max_positions", "Макс. позиций"], ["cooldown_s", "Пауза по монете, с"], + ["min_turnover", "Мин. оборот 24ч, $"], ["min_depth", "Мин. объём по ценам, $"], ["new_days", "Новые: фьючерсу ≤ дней"], + ["limit_hold_s", "Лимитный вход: ждать, с"], ["max_real_positions", "Одновременно реальных позиций"], + ["spot_fee", "Комиссия спот, %"], ["fut_fee", "Комиссия фьюч, %"], + ["fut_fee_innovation", "Комиссия фьюч зоны инноваций, %", "bybit"]]; +const BX_CHECKS = [["use_new", "Новые монеты"], ["use_innovation", "Зона инноваций / метка «новая» биржи"], ["use_memes", "Мемкойны"], + ["all_coins", "Все монеты со спотом и фьючем"], + ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами (реальный режим)"], + ["entry_limit", "Вход лимитным шортом по цене сигнала, потом спот (реальный режим)"], + ["block_negative_funding", "Не открывать сделку при отрицательном funding"]]; +function bxTabs() { + document.getElementById("bxTabs").innerHTML = BX_VENUES.map(([k, n]) => BX_READY.has(k) + ? `` + : ``).join(" "); +} +function bxSelect(k) { + rememberBasisDraft(); + invalidateRead(`/api/basis?ex=${k}`); pendingPolls.delete(loadBasis); + bxEpoch++; bx = null; bxDataVenue = null; bxDirty = false; + setBasisReady(false); + document.getElementById("bxPos").innerHTML = ""; + document.getElementById("bxMsg").textContent = "Загрузка выбранного режима…"; + bxVenue = k; localStorage.setItem("bx.venue", k); bxBuilt = false; + bxSort = "net_pct"; // the net profit decides the entry — sorted by it + bxTabs(); poll(loadBasis); refreshConnection(); +} +function bxBuild(s) { + const cross = true; // «Арбитраж»: one mode, simulation or real + if (!bxHeads) bxHeads = {rows: document.getElementById("bxRowsHead").innerHTML, pos: document.getElementById("bxPosHead").innerHTML, + title: document.getElementById("bxTitle").textContent, help: document.getElementById("bxHelp").innerHTML}; + document.getElementById("bxRowsHead").innerHTML = cross ? CX_ROWS_HEAD : bxHeads.rows; + document.getElementById("bxPosHead").innerHTML = cross ? CX_POS_HEAD : bxHeads.pos; + document.getElementById("bxTitle").textContent = (bxVenue === "cross_real" ? "Арбитраж · РЕАЛЬНАЯ торговля" : "Арбитраж · симуляция") + + ": купить там, где дешевле, продать там, где дороже, закрыть при возврате разницы к обычной"; + document.getElementById("bxHelp").innerHTML = + "Связки трёх типов (включаются галочками ниже): спот → фьючерс между биржами (покупка на споте A, шорт на фьючерсе B), " + + "спот → фьючерс внутри биржи (обе ноги на одной бирже) и спот → спот (покупка на споте A, продажа тех же монет на " + + "споте B из запаса, который лежит на B; при закрытии — продажа на A и выкуп запаса на B). Для каждой связки программа следит за " + + "обычной разницей (~30 мин). Вход — по «Чистой прибыли, %»: сколько останется, если разница вернётся к обычной, за вычетом запаса " + + "выхода и 4 комиссий (из таблицы бирж). Биржи, их лимиты сделок и комиссии — в карточке «Биржи». Симуляция и реальная торговля — " + + "отдельные вкладки: у каждой свой «Старт», свои настройки и сделки. Деньги между биржами программа не переводит."; + document.getElementById("bxReal").style.display = "none"; // the tab decides paper or real + document.getElementById("bxAdoptBox").style.display = cross ? "none" : ""; + document.getElementById("cxBalCard").style.display = cross ? "" : "none"; + if (cross) cxBalBuild(); + const fieldsList = cross ? CX_FIELDS : BX_FIELDS, checks = cross ? CX_CHECKS : BX_CHECKS; + document.getElementById("bxSettings").innerHTML = + fieldsList.filter(([, , only]) => !only || only === bxVenue) // a field of one exchange only + .map(([k, l]) => `
`).join("") + + checks.map(([k, l]) => ``).join(""); + document.querySelectorAll("#bxSettings input").forEach(el => el.addEventListener("input", () => { + bxDirty = true; document.getElementById("bxMsg").textContent = "есть несохранённые изменения"; })); + document.querySelectorAll("#basisView th[data-b]").forEach(th => th.onclick = () => { + bxSort = th.dataset.b; localStorage.setItem("bx.sort", bxSort); renderBasis(); }); + bxBuilt = true; bxDirty = false; + restoreBasisDraft(); + if (typeof applyHelpHints === "function") applyHelpHints(); +} +async function basisSave() { + if (!basisReady()) return; + const body = {}; + document.querySelectorAll("#bxSettings input").forEach(el => body[el.dataset.bx] = el.type === "checkbox" ? el.checked : el.value); + const venue = bxVenue, epoch = bxEpoch; + const r = await api(`/api/basis/${venue}/settings`, body); + if (venue !== bxVenue || epoch !== bxEpoch) return; + document.getElementById("bxMsg").textContent = r.ok ? "сохранено" : r.error; + if (r.ok) { + bxDirty = false; + rememberBasisDraft(); // Fee/limit drafts belong to their separate Save button. + bxBuilt = false; await loadBasis(); + } +} +async function basisRun() { + if (!basisReady()) return; + if (bxVenue === "cross_real" && !bx.settings.running) { + const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange); + if (!ready.length) { alert("Нет включённых бирж с API-ключами (вкладка «Реальная торговля · API-ключи»)."); return; } + const s = bx.settings, kinds = [s.search_sf && "спот → фьючерс между биржами", s.search_in && "спот → фьючерс внутри биржи", + s.search_ss && "спот → спот (из запаса монет)"].filter(Boolean).join(", "); + if (!confirm(`Запустить РЕАЛЬНУЮ торговлю?\n\nБиржи: ${ready.join(", ")}.\nСвязки: ${kinds || "ни одной не включено"}.\n` + + `Сумма сделки: ${s.amount} $. Настоящие ордера с вашими API-ключами; одна сделка за раз, лимиты сделок по биржам.\n` + + "Изменение баланса считается с этого момента.")) return; + } + const r = await api(`/api/basis/${bxVenue}/settings`, {running: !bx.settings.running}); + document.getElementById("bxMsg").textContent = r.ok ? "" : r.error; + loadBasis(); +} +async function basisClose(uid, venue = bxDataVenue) { + if (!basisReady() || venue !== bxVenue) return; + const r = await api(`/api/basis/${venue}/close${uid ? "/" + uid : ""}`, {}); + if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || ""; + loadBasis(); +} +async function basisAdopt() { + if (!basisReady()) return; + const base = document.getElementById("bxAdopt").value.trim(); + if (!base) return; + const r = await api(`/api/basis/${bxVenue}/adopt`, {base, price: document.getElementById("bxAdoptPrice").value.trim()}); + document.getElementById("bxAdoptMsg").innerHTML = `${r.message || r.error}`; + loadBasis(); +} +async function basisReset() { + if (!basisReady()) return; + if (!confirm("Сбросить статистику этого режима? История закрытых сделок будет очищена. Общий виртуальный счёт не меняется; при открытых позициях сброс недоступен.")) return; + const venue = bxVenue, r = await api(`/api/basis/${venue}/reset`, {}); + if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || (r.ok ? "Статистика сброшена" : "Сброс отклонён"); + await loadBasis(); +} +function basisReady() { return !!bx && bxDataVenue === bxVenue; } +function setBasisReady(ready) { + document.querySelectorAll("#basisView button, #basisView input").forEach(el => { + if (!el.closest("#bxTabs")) setControlDisabled(el, !ready); + }); +} +async function loadBasis() { + if (tab !== "basis") return; + bxTabs(); + const venue = bxVenue, epoch = bxEpoch, request = ++bxRequest; + const r = await api(`/api/basis?ex=${venue}`); + if (venue !== bxVenue || epoch !== bxEpoch || request < bxApplied) return; + bxApplied = request; + if (r.error) { document.getElementById("bxStatus").textContent = r.error; return; } + bx = r; bxDataVenue = venue; + renderAccount(r.paper_account); + if (!bxBuilt) bxBuild(bx.settings); + renderBasis(); + setBasisReady(true); + refreshConnection(); +} +const dollars = v => v == null ? "—" : (v >= 0 ? "+" : "−") + Math.abs(v).toFixed(2); +const hold = s => s < 60 ? `${s.toFixed(0)} с` : s < 3600 ? `${(s / 60).toFixed(1)} мин` : `${(s / 3600).toFixed(1)} ч`; +const kusd = v => v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(0) + "K" : v.toFixed(0); +// how fresh the prices of an open position are (the fast watch looks several times a second) +const freshness = p => p.price_age == null ? '
жду быстрые цены…
' + : `
цены ${(p.price_age * 1000).toFixed(0)} мс назад · опрос ${p.fast_ms} мс
`; +// the smallest amount both legs accept; red when «Сумма сделки» is below it (then not traded, paper or real) +function minEntryCell(r, s) { + if (r.min_entry == null) return '?'; + const parts = [r.min_spot != null ? `спот ≥ ${r.min_spot.toFixed(2)} $` : "", r.min_fut != null ? `фьюч ≥ ${r.min_fut.toFixed(2)} $` : ""] + .filter(Boolean).join(", "); + return `${r.min_entry.toFixed(2)}`; +} +function renderCross() { + const s = bx.settings; + const bad = Object.entries(bx.ex_status || {}).map(([k, v]) => `${k}: ${v}`).join("; "); + document.getElementById("bxStatus").textContent = (bx.status === "ok" + ? `связок «спот на A → шорт на B»: ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (цикл ${(bx.cycle_ms / 1000).toFixed(1)} с)` + : bx.status) + ` · ${s.running ? `новые ${s.real ? "РЕАЛЬНЫЕ" : "бумажные"} сделки открываются` : "остановлено — новые сделки не открываются"}` + + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : "") + (bad ? ` · ${bad}` : ""); + cxBalRender(); + document.getElementById("bxPos").innerHTML = bx.positions.map(p => ` + ${mskFull(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.error ? `
${p.error}` : ""}${p.base} спот · фьюч + ${p.spot_ex} → ${p.fut_ex}
${p.kind_name}
${p.qty.toPrecision(5)} + ${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)}` : ""} + ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)}` : ""} + ${pct(p.entry_gap)}${p.exit_level != null && p.exit_level > p.usual + ? `${pct(p.exit_level)} (+${s.exit_over_usual_pct})
сместилась: при входе ${pct(p.usual)}
` + : `${pct(p.usual)} (+${s.exit_over_usual_pct})${p.usual_now != null ? `
сейчас обычная ${pct(p.usual_now)}
` : ""}`} + ${pct(p.gap_now)}${freshness(p)}${p.exit_held != null + ? `
у обычной ${p.exit_held.toFixed(1)} из ${s.exit_hold_s} с — закрытие, если удержится
` : ""} + ${p.liq_pct == null ? "—" + : `${p.liq_pct.toFixed(1)}%
${price(p.liq_price)} · ${p.liq_src}${ + p.liq_src === "биржа" && p.liq_calc ? ` (расчёт ${price(p.liq_calc)})` : ""}
`} + ${dollars(p.funding)}${(p.fees_total ?? p.fees).toFixed(3)} + ${dollars(p.net)} + `).join("") + || 'Нет открытых позиций'; + const key = bxSort, val = r => r[key]; + const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9)); + document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key)); + document.getElementById("bxCount").textContent = `Связки: лучшие для ${rows.length} монет (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`; + const open = new Set(bx.positions.map(p => p.base)); + document.getElementById("bxRows").innerHTML = rows.map(r => ` + ${r.base}${r.kind_name}${r.spot_ex} + ${r.fut_ex}${r.innovation ? ' иннов.' : ""} + ${price(r.spot_ask)} + ${price(r.fut_bid)} + ${pct(r.entry_gap)}${r.usual == null ? "—" : pct(r.usual)} + ${r.excess == null ? "—" : pct(r.excess)} + ${r.net_pct == null ? "—" : pct(r.net_pct)}${r.hot + ? `
⚡ ${r.price_age == null ? "" : (r.price_age < 1 ? (r.price_age * 1000).toFixed(0) + " мс" : r.price_age.toFixed(1) + " с")}
` : ""} + ${r.history.toFixed(0)} + ${pct(r.funding_pct, 4)} / ${r.interval_h} ч + ${r.depth == null ? '?' : kusd(r.depth)} + ${minEntryCell(r, s)}${kusd(r.turnover)} + ${open.has(r.base) ? 'в позиции' + : r.fits && !r.why ? 'подходит' + : r.fits ? `подходит — но ${r.why}` : `${r.why}`}`).join("") + || 'Нет связок под фильтры'; + document.getElementById("bxTrades").innerHTML = bx.trades.map(t => ` + ${mskFull(t.closed)}${t.base} ${t.spot_ex} → ${t.fut_ex} · ${({sf: "спот → фьюч", in: "внутри биржи", ss: "спот → спот"})[t.kind] || ""}${hold(t.closed - t.opened)} + ${pct(t.entry_gap)} → ${pct(t.exit_gap)} (обычная ${pct(t.usual)})${dollars(t.spot_pnl)} + ${dollars(t.fut_pnl)}${t.fees.toFixed(3)}${dollars(t.funding)} + ${dollars(t.net)}${t.amount ? pct(t.net / t.amount * 100, 2) : "—"} + ${t.reason}`).join("") || 'Сделок пока нет'; +} +function renderBasis() { + const s = bx.settings, st = bx.stats; + const run = document.getElementById("bxRun"); + run.textContent = s.running ? "■ Стоп" : "▶ Старт"; run.className = s.running ? "stop" : "start"; + const rb = document.getElementById("bxReal"); + rb.textContent = s.real ? "● РЕАЛЬНАЯ торговля — выключить" : "Бумажная торговля (включить реальную)"; + rb.className = s.real ? "realon" : ""; + document.getElementById("bxStatus").textContent = (bx.status === "ok" + ? `${bx.venue}: монет со спотом и фьючем ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (${bx.cycle_ms} мс)` + : bx.status) + ` · мемкойны: ${bx.memes_source} · ${s.running ? "новые сделки открываются" : "остановлено — новые сделки не открываются"}` + + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : ""); + const wr = st.trades ? `${(st.wins / st.trades * 100).toFixed(0)}% · ${st.wins} из ${st.trades}` : "—"; + const ex = st.real ? " (биржа)" : ""; + const tiles = [ + ["Итог закрытых, $" + ex, dollars(st.net), cls(st.net)], ["Итог, % от вложенного" + ex, st.net_pct == null ? "—" : pct(st.net_pct, 3), cls(st.net_pct || 0)], + ["Открыто", st.open, ""], ["Если закрыть открытые, $", dollars(st.unrealized), cls(st.unrealized)], + ["Сделок" + ex, st.trades, ""], ["Винрейт", wr, ""], ["Комиссии, $" + ex, st.fees.toFixed(4), "neg"], + ["Funding, $ (оценка)", dollars(st.funding), cls(st.funding)], ["Среднее удержание", st.avg_hold_min == null ? "—" : hold(st.avg_hold_min * 60), ""]]; + if (st.real && bx.mode === "cross") { + const b = bx.balances || {}; + tiles.unshift(["Баланс всех бирж, $", b.total == null ? "—" : b.total.toFixed(2), ""], + ["С запуска", b.change_pct == null ? 'жду балансы' + : `${pct(b.change_pct, 2)} (${dollars(b.change_usd)} $)`, cls(b.change_pct || 0)]); + if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные', "neg"]); + } else if (st.real) { + const bal = real && real.balances && real.balances[bxVenue]; + tiles.unshift(["Баланс на бирже", !bal ? "нет ключей" : bal.error ? `${bal.error}` + : Object.entries(bal.values).map(([k, v]) => `
${k}: ${typeof v === "number" ? v.toFixed(2) : v}
`).join(""), ""]); + if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные', "neg"]); + } + document.getElementById("bxStats").innerHTML = tiles + .map(([k, v, c]) => `
${k}
${v}
`).join(""); + if (bx.mode === "cross") { renderCross(); return; } + document.getElementById("bxPos").innerHTML = bx.positions.map(p => ` + ${mskFull(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.tp_order ? `
TP на бирже: ${price(p.tp_price)}` : ""}${p.error ? `
${p.error}` : ""}${p.base} спот · фьюч + ${p.qty.toPrecision(5)}${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)}` : ""} + ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)}` : ""} + ${pct(p.entry_gap)}${pct(p.gap_now)}${freshness(p)} + ${dollars(p.funding)}${(p.fees_total ?? p.fees).toFixed(3)} + ${dollars(p.net)} + `).join("") + || 'Нет открытых позиций'; + const key = bxSort, val = r => key === "depth" ? r.depth + : key === "turnover" ? Math.min(r.spot_turnover, r.fut_turnover) : r[key]; + const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9)); + document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key)); + document.getElementById("bxCount").textContent = `Монеты: ${rows.length} (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`; + const open = new Set(bx.positions.map(p => p.base)); + document.getElementById("bxRows").innerHTML = rows.map(r => { + const groups = [r.age_days != null && r.age_days <= s.new_days ? "новая" : "", r.innovation ? "инновации" : "", r.meme ? "мем" : ""].filter(Boolean).join(", "); + return ` + ${r.base}${r.mult > 1 ? ` фьюч ×${r.mult}` : ""} + ${price(r.spot_ask)} + ${price(r.fut_bid)} + ${pct(r.entry_gap)}${pct(r.exit_gap)} + ${pct(r.net_if_closed_pct)} + ${pct(r.funding_pct, 4)} / ${r.interval_h} ч + ${r.depth == null ? '?' : kusd(r.depth)} + ${minEntryCell(r, s)}${kusd(Math.min(r.spot_turnover, r.fut_turnover))} + ${r.age_days == null ? "—" : r.age_days.toFixed(0)}${groups} + ${open.has(r.base) ? 'в позиции' + : r.real_block ? `реально нельзя: ${r.real_block}` + : r.fits && !r.why ? 'подходит' + : r.fits ? `подходит — но ${r.why}` + : `${r.why || ""}`}`; + }).join("") || 'Нет монет под фильтры'; + document.getElementById("bxTrades").innerHTML = bx.trades.map(t => ` + ${mskFull(t.closed)}${t.base}${hold(t.closed - t.opened)} + ${pct(t.entry_gap)} → ${pct(t.exit_gap)}${dollars(t.spot_pnl)} + ${dollars(t.fut_pnl)}${t.fees.toFixed(3)}${dollars(t.funding)} + ${dollars(t.net)}${t.amount ? pct(t.net / t.amount * 100, 2) : "—"} + ${t.reason}`).join("") || 'Сделок пока нет'; +} +function setMarket(m) { + arbMarket = m; localStorage.setItem("arb.market", m); arb = null; feesFor = null; arbOpen.clear(); + document.getElementById("arbRows").innerHTML = 'загружаю цены…'; + loadArb(); +} +// spot always means moving the coin; futures only when asked +function transferOn() { return isSpot() || document.getElementById("afTransfer").checked; } +function fee(ex) { + const el = document.querySelector(`#afFees input[data-fee="${ex}"]`); + const v = el ? parseFloat(el.value) : NaN; + return isNaN(v) ? (arb?.taker?.[ex] ?? 0.1) : v; +} +function buildFees() { + const saved = JSON.parse(localStorage.getItem("arb.fees." + arbMarket) || "{}"); + document.getElementById("afFees").innerHTML = `Комиссия по рынку (${isSpot() ? "спот" : "фьючерсы"}), %:` + + Object.keys(arb.taker).map(e => `
`).join("") + + 'базовый уровень без скидок — поправьте под свой'; + document.querySelectorAll("#afFees input").forEach(el => el.addEventListener("input", () => { + const f = {}; document.querySelectorAll("#afFees input").forEach(i => f[i.dataset.fee] = i.value); + localStorage.setItem("arb.fees." + arbMarket, JSON.stringify(f)); renderArb(); })); + feesFor = arbMarket; +} +// filters, transfer time, amount… are remembered in this browser, so they survive reloads and restarts +const ARB_FIELDS = ["afCoin", "afVol", "afDepth", "afGross", "afNet", "afSuspect", "afTransfer", "afClosed", + "afTMin", "afAmount", "afTFee"]; +(function restoreArbSettings() { + let saved = {}; + try { saved = JSON.parse(localStorage.getItem("arb.settings") || "{}"); } catch (e) {} + for (const id of ARB_FIELDS) { + const el = document.getElementById(id); + if (!el || !(id in saved)) continue; + if (el.type === "checkbox") el.checked = !!saved[id]; else el.value = saved[id]; + } + const save = () => { + const out = {}; + for (const id of ARB_FIELDS) { const el = document.getElementById(id); if (el) out[id] = el.type === "checkbox" ? el.checked : el.value; } + try { localStorage.setItem("arb.settings", JSON.stringify(out)); } catch (e) {} + }; + ARB_FIELDS.forEach(id => { const el = document.getElementById(id); if (el) { el.addEventListener("input", save); el.addEventListener("change", save); } }); +})(); +async function arbRun() { + await api(`/api/arb/${arbMarket}/${arb && arb.paused ? "start" : "stop"}`, {}); + loadArb(); +} +async function loadArb() { + if (tab !== "arb") return; + const tmin = val("afTMin", 15); + arb = await api(`/api/arb?market=${arbMarket}` + (transferOn() ? `&transfer=${tmin}` : "")); + document.getElementById("mkSpot").classList.toggle("on", isSpot()); + document.getElementById("mkFut").classList.toggle("on", !isSpot()); + document.getElementById("afTransferBox").style.display = isSpot() ? "none" : ""; + document.getElementById("afClosedBox").style.display = isSpot() ? "" : "none"; + if (!arbExBuilt && arb.taker) { + const saved = JSON.parse(localStorage.getItem("arb.ex") || "null"); + document.getElementById("afEx").innerHTML = 'Биржи:' + Object.keys(arb.taker).map(e => + ``).join(""); + document.querySelectorAll("#afEx input, #arbView .controls input").forEach(el => el.addEventListener("input", renderArb)); + ["afTransfer", "afTMin"].forEach(id => document.getElementById(id).addEventListener("change", loadArb)); + document.querySelectorAll("#arbView th[data-s]").forEach(th => th.addEventListener("click", () => { + arbSort = th.dataset.s; localStorage.setItem("arb.sort", arbSort); renderArb(); })); + arbExBuilt = true; + } + if (arb.taker && feesFor !== arbMarket) buildFees(); + const run = document.getElementById("arbRun"); + run.textContent = arb.paused ? "▶ Старт сканирования" : "■ Стоп сканирования"; + run.className = arb.paused ? "start" : "stop"; + const unit = isSpot() ? "пар USDT" : "фьюч."; + const st = Object.entries(arb.status || {}).map(([e, s]) => `${e}: ${s === "ok" ? arb.counts[e] + " " + unit : s}`).join(" · "); + document.getElementById("arbStatus").textContent = (arb.paused ? "Сканирование остановлено — цены ниже последние полученные. " : "") + (arb.updated + ? `${st} · обновлено ${msk(arb.updated)} МСК (цикл ${(arb.cycle_ms / 1000).toFixed(1)} с, каждые ${arb.cycle_s} с)` : arb.paused ? "данных ещё нет" : "загружаю цены со всех бирж…"); + document.getElementById("arbTitle").textContent = `Арбитраж ${isSpot() ? "на споте" : "на фьючерсах"}: Bybit · Binance · MEXC · HTX · Gate`; + document.getElementById("arbFees").textContent = isSpot() + ? "спот: купить на одной бирже → вывести монету → продать на другой" : "фьючерсы: лонг на одной + шорт на другой, закрыть при схождении"; + renderArb(); +} +// What is left of the trade amount at current prices after every fee and the transfer, in $ (same sums as the plan). +function arbProfit(amount, buyPrice, sellPrice, feeA, feeB, transferFee) { + const coins = amount / buyPrice; + if (isSpot()) { + // buy fee comes out of the coins bought, the withdrawal fee too; the sell fee out of the USDT received + const arrive = Math.max(0, coins * (1 - feeA / 100) - transferFee / buyPrice); + return arrive * sellPrice * (1 - feeB / 100) - amount; + } + const fees = 2 * amount * feeA / 100 + amount * feeB / 100 + coins * sellPrice * feeB / 100 + transferFee; + return coins * (sellPrice - buyPrice) - fees; +} +function arbPairs() { + const ex = [...document.querySelectorAll("#afEx input:checked")].map(i => i.dataset.ex); + localStorage.setItem("arb.ex", JSON.stringify(ex)); + const amount = val("afAmount", 1000), tmin = val("afTMin", 15), userFee = val("afTFee", 1); + const out = []; + for (const r of arb.rows || []) { + const ps = Object.entries(r.prices).filter(([e]) => ex.includes(e)); + if (ps.length < 2) continue; + let best = null; + for (const [a, pa] of ps) for (const [b, pb] of ps) { + if (a === b) continue; + const gross = (pb.bid / pa.ask - 1) * 100; + if (!best || gross > best.gross) best = {gross, a, b, pa, pb}; + } + const fa_ = fee(best.a), fb_ = fee(best.b); + const cost = isSpot() ? fa_ + fb_ : 2 * (fa_ + fb_); // spot: two trades; futures: open + close + const same = best.a === r.buy && best.b === r.sell; + const usual = same ? r.usual : null; + const fa = best.pa.funding_8h, fb = best.pb.funding_8h; + const t = same ? r.transfer : null; + // transfer fee: the exchange's own withdrawal fee where it is public (HTX), otherwise the field value + const tfee = t && t.fee_usd != null ? t.fee_usd : userFee; + const feePct = transferOn() ? tfee / amount * 100 : 0; + const low = same ? r.window_low : null, enough = same && r.history_min != null && r.history_min >= tmin; + const closed = !!t && (t.withdraw === false || t.deposit === false); + const profit = arbProfit(amount, best.pa.ask, best.pb.bid, fa_, fb_, transferOn() ? tfee : 0); + out.push({profit_usd: profit, profit_pct: profit / amount * 100,...r, buy: best.a, sell: best.b, buy_price: best.pa.ask, sell_price: best.pb.bid, + buy_url: best.pa.url, sell_url: best.pb.url, gross: best.gross, round_cost: cost, net_now: best.gross - cost, + usual, expected: usual == null ? null : best.gross - Math.max(usual, 0) - cost, + funding_buy: fa, funding_sell: fb, carry_8h: fa == null || fb == null ? null : fb - fa, + depth_usd: same ? r.depth_usd : null, suspect: best.gross > 10 || (same && r.suspect), pa: best.pa, pb: best.pb, + fee_a: fa_, fee_b: fb_, held_min: same ? r.held_min : null, window_low: low, history_ok: enough, + history_have: same ? r.history_min : null, fee_pct: feePct, tfee, tfee_known: !!(t && t.fee_usd != null), + transfer: t, closed, + net_transfer: low == null || !enough ? null : low - cost - feePct}); + } + return out; +} +const usd = v => v == null ? "—" : v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(1) + "K" : v.toFixed(0); +const pct = (v, d = 3) => v == null ? "—" : (v >= 0 ? "+" : "") + v.toFixed(d) + "%"; +const yesno = (v, yes, no) => v === true ? `${yes}` : v === false ? `${no}` : 'неизвестно'; +function transferCell(r) { + const t = r.transfer; + if (!t) return '—'; + const nets = t.networks.length ? t.networks.slice(0, 4).join(", ") : 'сеть не известна'; + return `вывод ${r.buy}: ${yesno(t.withdraw, "открыт", "закрыт")}
ввод ${r.sell}: ${yesno(t.deposit, "открыт", "закрыт")}
` + + `сети: ${nets}${t.fee_usd != null ? `
комиссия вывода ≈ ${t.fee_usd.toFixed(2)} $ (${t.fee_net})` : ""}`; +} +// Step-by-step plan for one row, in dollars for the trade amount, every fee included. +function arbPlan(r) { + const amount = val("afAmount", 1000), tr = transferOn(), tmin = val("afTMin", 15); + const money = v => (v >= 0 ? "" : "−") + Math.abs(v).toFixed(2) + " $"; + const coins = amount / r.buy_price; + const steps = []; + const depthWarn = r.depth_usd != null && r.depth_usd < amount + ? `
  • По лучшим ценам доступно только ${r.depth_usd.toFixed(0)} $ из ${amount} $ — остальное исполнится хуже, уменьшите сумму
  • ` : ""; + const spreadUsed = tr && r.window_low != null && r.history_ok ? r.window_low : r.gross; + const holdNote = tr ? (r.history_ok ? ` Разница за последние ${tmin} мин не опускалась ниже ${pct(r.window_low)}.` + : ` Сканер видит связку меньше ${tmin} мин — неизвестно, продержится ли разница весь перевод.`) : ""; + if (isSpot()) { + const feeBuy = amount * r.fee_a / 100; // the fee is usually taken from the coins bought + const coinsNet = coins * (1 - r.fee_a / 100); + const tCoins = r.tfee / r.buy_price; // withdrawal fee in coins + const arrive = Math.max(0, coinsNet - tCoins); + const sellValue = arrive * r.sell_price, feeSell = sellValue * r.fee_b / 100; + const result$ = sellValue - feeSell - amount; + const resultAtLow$ = arrive * r.buy_price * (1 + spreadUsed / 100) * (1 - r.fee_b / 100) - amount; + const t = r.transfer || {}; + const nets = t.networks && t.networks.length ? t.networks.join(", ") : "общую сеть проверить на обеих биржах"; + steps.push(`На ${r.buy} иметь ${amount} USDT на спотовом счёте; на ${r.sell} узнать адрес пополнения ${r.coin} (сеть: ${nets}).` + + (t.withdraw === false || t.deposit === false ? ' Сейчас ввод или вывод закрыт — перевод невозможен.' + : (t.withdraw == null || t.deposit == null ? ' Статус ввода/вывода этой биржи не публикуется — проверьте на сайте.' : ""))); + steps.push(`${r.buy} ${r.pa.symbol}: купить по рынку ≈ ${price(r.buy_price)} на ${amount} $ ≈ ${coins.toPrecision(5)} ${r.coin}. Комиссия ${money(feeBuy)} (${r.fee_a}%) → на счёте ≈ ${coinsNet.toPrecision(5)} ${r.coin}.`); + steps.push(`Вывести ${r.coin} с ${r.buy} на ${r.sell}: комиссия вывода ≈ ${money(r.tfee)}${r.tfee_known ? "" : " (из поля «Комиссия перевода»)"}, дойдёт ≈ ${arrive.toPrecision(5)} ${r.coin}, ждать ≈ ${tmin} мин.${holdNote}`); + steps.push(`${r.sell} ${r.pb.symbol}: продать по рынку ≈ ${price(r.sell_price)} → ≈ ${money(sellValue)}, комиссия ${money(feeSell)} (${r.fee_b}%).`); + steps.push(`Итог по текущим ценам: ${money(sellValue - feeSell)} − ${money(amount)} = ${money(result$)}` + + (tr && r.history_ok ? `; если разница сожмётся до минимума за ${tmin} мин: ${money(resultAtLow$)}` : "") + + `. Все расходы: ${money(feeBuy + r.tfee + feeSell)}, безубыток при разнице ≥ ${((feeBuy + r.tfee + feeSell) / amount * 100).toFixed(3)}%.`); + return `
      ${steps.map(s => `
    1. ${s}
    2. `).join("")}${depthWarn}
    `; + } + const tfee = tr ? r.tfee : 0; + const unitsA = coins / (r.pa.mult || 1), unitsB = coins / (r.pb.mult || 1); + const qty = (u, m) => `${u >= 100 ? u.toFixed(0) : u.toPrecision(4)} ${m > 1 ? `ед. (×${m} монет)` : "монет"}`; + const feeInA = amount * r.fee_a / 100, feeInB = amount * r.fee_b / 100; + const feeOutA = amount * r.fee_a / 100, feeOutB = coins * r.sell_price * r.fee_b / 100; + const fees = feeInA + feeInB + feeOutA + feeOutB + tfee; + const usual = Math.max(r.usual ?? 0, 0), toUsual$ = amount * (r.gross - usual) / 100; + const carry$ = r.carry_8h == null ? null : amount * r.carry_8h / 100; + const result$ = amount * spreadUsed / 100 - fees; + if (tr) steps.push(`Перевести маржу: на ${r.buy} и ${r.sell} должно быть по ${amount} $ (плечо 1). Перевод ≈ ${tmin} мин, плата ${money(tfee)}.${holdNote}`); + else steps.push(`Проверить маржу: на ${r.buy} и на ${r.sell} заранее по ${amount} $ USDT на фьючерсном счёте (плечо 1).`); + steps.push(`${r.buy} ${r.pa.symbol}: открыть LONG по рынку ≈ ${price(r.buy_price)}, ${qty(unitsA, r.pa.mult || 1)} на ${amount} $. Комиссия ${money(feeInA)} (${r.fee_a}%).`); + steps.push(`Сразу же ${r.sell} ${r.pb.symbol}: открыть SHORT по рынку ≈ ${price(r.sell_price)}, ${qty(unitsB, r.pb.mult || 1)}. Комиссия ${money(feeInB)} (${r.fee_b}%).`); + steps.push(`Держать, пока разница не сузится${r.usual != null ? ` до обычной ${pct(usual)}` : " к нулю"}. Funding за 8 ч: ${carry$ == null ? "нет данных" : (carry$ >= 0 ? "получите " : "заплатите ") + money(Math.abs(carry$))} (лонг ${pct(r.funding_buy, 4)}, шорт ${pct(r.funding_sell, 4)}).`); + steps.push(`Закрыть обе позиции одновременно по рынку. Комиссии выхода ≈ ${money(feeOutA + feeOutB)}.`); + steps.push(`Итог при схождении к нулю: ${money(amount * spreadUsed / 100)} разницы − ${money(fees)} комиссий${tfee ? " и перевода" : ""} = ${money(result$)}` + + (r.usual != null ? `; к обычной: ${money(toUsual$ - fees)}` : "") + `. Безубыток при разнице ≥ ${(fees / amount * 100).toFixed(3)}%.`); + return `
      ${steps.map(s => `
    1. ${s}
    2. `).join("")}${depthWarn}
    `; +} +function renderArb() { + if (!arb || !arb.rows) return; + const q = document.getElementById("afCoin").value.trim().toUpperCase(); + const minVol = val("afVol", 0), minDepth = val("afDepth", 0), minGross = val("afGross", 0); + const onlyNet = document.getElementById("afNet").checked, hideSuspect = document.getElementById("afSuspect").checked; + const hideClosed = isSpot() && document.getElementById("afClosed").checked; + const tr = transferOn(), spot = isSpot(); + document.querySelectorAll("#arbView .tcol").forEach(el => el.style.display = tr ? "" : "none"); + document.querySelectorAll("#arbView .futcol").forEach(el => el.style.display = spot ? "none" : ""); + document.querySelectorAll("#arbView .spotcol").forEach(el => el.style.display = spot ? "" : "none"); + let rows = arbPairs().filter(r => (!q || r.coin.includes(q)) && r.volume_usd >= minVol && r.gross >= minGross + && (!minDepth || (r.depth_usd ?? 0) >= minDepth) && (!hideSuspect || !r.suspect) && (!hideClosed || !r.closed) + && (!onlyNet || (tr ? (r.net_transfer ?? r.net_now - r.fee_pct) > 0 : r.net_now > 0))); + const key = arbSort, num = v => v == null ? -Infinity : v; + rows.sort((a, b) => typeof a[key] === "string" ? a[key].localeCompare(b[key]) : num(b[key]) - num(a[key])); + document.querySelectorAll("#arbView th[data-s]").forEach(th => th.classList.toggle("sorted", th.dataset.s === key)); + document.getElementById("arbCount").textContent = `Пары: ${rows.length} (монет на 2+ биржах: ${arb.rows.length})`; + const cols = 14 + (tr ? 2 : 0); + const html = []; + for (const r of rows.slice(0, 300)) { + html.push(` 0 ? "leadrow" : ""}" onclick="toggleArb('${r.coin}')"> + + ${r.coin}${r.suspect ? ' разные монеты?' : ""}${r.closed ? ' перевод закрыт' : ""} + ${r.buy} ${price(r.buy_price)} + ${r.sell} ${price(r.sell_price)} + ${pct(r.gross)}${pct(r.net_now)} (−${r.round_cost.toFixed(2)}) + ${pct(r.profit_pct, 2)}
    ${r.profit_usd >= 0 ? "+" : "−"}${Math.abs(r.profit_usd).toFixed(2)} $ + ${pct(r.usual)}${pct(r.expected)} + ${spot ? `${transferCell(r)}` + : `${pct(r.carry_8h, 4)}`} + ${usd(r.depth_usd)}${usd(r.volume_usd)} + ${r.held_min == null ? '—' : r.held_min < 1 ? "<1 мин" : r.held_min.toFixed(0) + " мин"} + ${tr ? `${r.history_ok ? pct(r.window_low) : `мало истории ${(r.history_have ?? 0).toFixed(0)} из ${val("afTMin", 15)} мин`} + ${pct(r.net_transfer)}` : ""} + ${r.exchanges.length}`); + if (arbOpen.has(r.coin)) { + const cells = Object.entries(r.prices).map(([e, p]) => + `${e} bid ${price(p.bid)} / ask ${price(p.ask)}` + + (spot ? "" : ` · funding/8ч ${pct(p.funding_8h, 4)}`)).join("
    "); + html.push(`
    Что сделать (на сумму сделки, все комиссии): + ${arbPlan(r)}
    Цены на всех биржах:
    ${cells}
    `); + } + } + document.getElementById("arbRows").innerHTML = html.join("") || `Нет пар под фильтры`; +} +function toggleArb(coin) { arbOpen.has(coin) ? arbOpen.delete(coin) : arbOpen.add(coin); renderArb(); } +window.addEventListener("resize", drawChart); +window.addEventListener("unhandledrejection", event => { + commandNotice(event.reason?.userMessage || event.reason?.message || "Не удалось выполнить действие. Проверьте связь и состояние сервера.", true); + event.preventDefault(); +}); +window.addEventListener("beforeunload", event => { + rememberBasisDraft(); + if (settingsDirty || basisDrafts.size) { event.preventDefault(); event.returnValue = ""; } +}); +function startApplication() { + // Register recovery before the first request: a failed initial GET must never stop polling. + setInterval(() => poll(loadState), 2000); + setInterval(() => poll(loadDetail), 1000); + setInterval(() => poll(loadBasis), 500); + setInterval(() => poll(loadReal), 3000); + setInterval(() => poll(loadAccount), 2000); + setInterval(() => { if (selected === SCANNER) poll(loadScanner); }, 5000); + setInterval(refreshConnection, 1000); + poll(async () => { await loadState(true); await refreshCenter(); }); + poll(loadReal); poll(loadAccount); showTab(tab); +} +(async () => { + startApplication(); +})(); diff --git a/web/help-data.js b/web/help-data.js new file mode 100644 index 0000000..c594f74 --- /dev/null +++ b/web/help-data.js @@ -0,0 +1,148 @@ +// 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.", + min_target_pct: "Минимальная цель движения цены для тейк-профита, в процентах. Это процент изменения цены, а не гарантированная доходность счёта. При авто-TP используется вместе с прогнозом.", + stop_loss_pct: "Допустимое движение цены против позиции, в процентах, после которого стратегия запрашивает закрытие. Значение больше 0. Рыночное исполнение может отличаться от порога.", + max_hold_seconds: "Максимальная продолжительность позиции в секундах. По истечении этого времени стратегия закрывает её, даже если цель ещё не достигнута.", + max_positions: "Максимум одновременно открытых виртуальных позиций одной монеты. Целое число от 1. Общий виртуальный счёт дополнительно ограничивает все монеты доступными средствами.", + entry_gap_seconds: "Минимальный интервал между новыми входами одной монеты, в секундах. 0 отключает дополнительную задержку.", + min_confidence: "Минимальный внутренний показатель уверенности сигнала от 0 до 1; 0 отключает фильтр. Это оценка стратегии, а не вероятность прибыли.", + auto_stop_pct: "Порог автоматической остановки новых входов, когда биржа фьючерса начинает опережать выбранную ведущую. Задаётся в процентах показателя лидерства; 0 отключает автостоп.", + auto_tp: "Вычислять цель тейк-профита по прогнозу движения догоняющей цены. Доля догоняния и горизонт прогноза задаются в дополнительных настройках.", + require_leader: "Разрешать вход только когда измерения подтверждают, что выбранная ведущая биржа действительно ведёт. Проверка использует минимальный перевес ведущей.", + cooldown_ms: "Пауза после закрытия сделки этой монеты, в миллисекундах. Не путать с интервалом между входами. 0 означает без дополнительной паузы.", + lead_threshold_pct: "Минимальное отставание фьючерса от движения ведущей для входа в режиме «Ведущая биржа», в процентах.", + lead_window_ms: "Длина окна сравнения движения двух цен в режиме ведущей биржи, в миллисекундах. Не меньше 50 мс. Меньше окно — быстрее реакция и больше влияние шума.", + vector_window_seconds: "За сколько секунд измерять направление и величину движения ведущей в режиме «Вектор».", + vector_min_move_pct: "Минимальное движение ведущей за окно вектора для входа, в процентах. Отсекает слишком слабые движения; 0 убирает этот порог.", + auto_tp_share_pct: "Какую долю прогнозируемого догоняния использовать для автоматической цели. 100% — весь прогноз, 50% — половина. Допустимо больше 0 и до 300%.", + auto_tp_horizon_seconds: "На сколько секунд вперёд рассчитывается прогноз движения для автоматического тейк-профита. Значение больше 0.", + cut_loss_ticks: "Сколько неблагоприятных шагов цены должно пройти для раннего закрытия, когда включено «Сразу закрывать в минусе». Целое число от 1.", + max_data_age_ms: "Максимальный возраст цен для входа, в миллисекундах. Устаревшие котировки блокируют новые сделки; этот фильтр относится к рынку, а индикатор связи сверху — к связи браузера с программой.", + leader_min_edge: "Минимальная разница показателей направленной корреляции в пользу ведущей. Используется фильтром «Входить, только если ведущая правда ведёт».", + basis_window_seconds: "Окно в секундах для расчёта обычного разрыва между ведущей ценой и фьючерсом в режиме «Разрыв цен».", + basis_entry_z: "Насколько далеко разрыв должен уйти от среднего для входа: величина в стандартных отклонениях (σ). Больше порог — реже входы.", + basis_exit_z: "Порог возврата разрыва к обычному уровню, в стандартных отклонениях, при котором режим «Разрыв цен» закрывает позицию.", + basis_min_gap_pct: "Минимальный абсолютный разрыв цен в процентах для входа в режиме «Разрыв цен». Работает вместе с порогом σ.", + auto_tp_learn: "Оценивать долю догоняния на накопленной истории. Полученная оценка влияет на прогноз; прошлые наблюдения не гарантируют будущего движения.", + one_per_tick: "Не открывать повторную позицию на том же шаге цены. Ограничение уменьшает повторные входы по одному ценовому событию.", + cut_loss: "Дополнительно закрывать позицию при небольшом неблагоприятном движении, заданном числом шагов цены. Может приводить к частым закрытиям и расходам на комиссии." + }, + cross: { + 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: "Минимальная расчётная чистая прибыль для входа: превышение разницы над обычной минус запас выхода и комиссии обеих ног. Проценты от суммы одной ноги; фактический результат может отличаться.", + max_gap_pct: "Максимально допустимое расхождение цен, в процентах. Слишком большой разрыв может означать разные инструменты под похожим тикером или плохие котировки.", + history_min: "Минимальное время наблюдения связки перед входом, в минутах. Нужно для оценки обычной разницы цен.", + exit_over_usual_pct: "Добавка в процентных пунктах к обычной разнице для целевого выхода. Например, обычная 0,20% и добавка 0,05 дают условие выхода 0,25%.", + exit_hold_s: "Сколько секунд условие выхода должно выполняться непрерывно перед закрытием. 0 означает закрытие сразу при выполнении условия.", + stop_widen_pct: "Закрывать, если разница расширилась относительно входа на указанное число процентных пунктов. 0 отключает этот стоп.", + max_hold_hours: "Максимальное время удержания арбитражной позиции в часах; 0 отключает лимит времени.", + cooldown_s: "Пауза в секундах после закрытия сделки по монете перед следующим входом.", + min_turnover: "Минимальный торговый оборот за 24 часа в долларах для каждой ноги. Это фильтр ликвидности, а не доступный объём по текущей цене.", + limit_hold_s: "Сколько секунд ждать исполнения лимитной первой ноги, когда включён лимитный вход с ожиданием и выключен IOC.", + max_spread_pct: "Максимальная разница bid/ask каждой ноги, в процентах. 0 отключает этот фильтр. Широкий спред увеличивает стоимость входа и выхода.", + confirm_ms: "Пауза в миллисекундах между двумя проверками стакана перед входом. Помогает отсеивать кратковременные или исчезнувшие цены.", + min_liq_pct: "Минимальный запас роста цены до расчётной ликвидации шорта, в процентах, при входе. Чем выше запас, тем больше средств резервируется под фьючерсную ногу.", + liq_close_pct: "Закрывать позицию, когда оставшийся запас до ликвидации меньше указанного процента. 0 отключает дополнительное закрытие.", + search_sf: "Искать связки «покупка спота на бирже A + шорт фьючерса на бирже B». Средства нужны на обеих биржах; монеты между биржами программа не переводит.", + search_in: "Искать связки «покупка спота + шорт фьючерса» внутри одной биржи.", + search_ss: "Искать связки «покупка спота на A + продажа спота на B». Для реальной продажи на B нужен заранее размещённый запас монет; при закрытии запас выкупается обратно.", + auto_transfer: "Разрешать автоматический перевод USDT между спотовым и фьючерсным счетами внутри одной биржи в реальном режиме. Переводов между разными биржами нет.", + entry_ioc: "Первая нога входит лимитным IOC по подтверждённой цене: немедленно исполняется доступный объём, остаток отменяется. Имеет приоритет над лимитным входом с ожиданием.", + entry_limit: "Если IOC выключен, выставлять первую ногу лимитно и ждать не больше «Лимитный вход: ждать». Вторая нога зависит от подтверждённого исполнения первой.", + fees_auto: "Уточнять значения комиссии по данным завершённых реальных сделок. В таблице бирж виден источник комиссии." + }, + basis: { + block_negative_funding: "Запрещает новые входы при отрицательном funding.", + amount: "Номинальная сумма сделки спот-фьючерс в долларах.", + min_gap_pct: "Минимальная разница между фьючерсным bid и спотовым ask для входа, в процентах.", + max_gap_pct: "Максимально допустимая разница для входа, в процентах.", + exit_gap_pct: "Целевая разница фьючерсного ask и спотового bid для закрытия обеих ног, в процентах.", + stop_gap_pct: "Абсолютная разница цен, при достижении которой позиция закрывается по стопу. 0 отключает.", + max_hold_hours: "Максимальное удержание позиции в часах; 0 — без лимита времени.", + max_positions: "Максимальное число одновременно открытых позиций данного движка.", + cooldown_s: "Пауза после закрытия сделки по монете, в секундах.", + min_turnover: "Минимальный оборот за 24 часа каждой ноги, в долларах.", + min_depth: "Минимальная доступная сумма по лучшим ценам стакана, в долларах.", + new_days: "Сколько дней после появления фьючерса инструмент считается новым.", + limit_hold_s: "Сколько секунд ждать исполнения лимитной первой ноги.", + max_real_positions: "Максимальное число одновременных реальных позиций данного движка.", + spot_fee: "Тейкер-комиссия спота за одну операцию, в процентах от её объёма.", + fut_fee: "Тейкер-комиссия фьючерса за одну операцию, в процентах от её объёма.", + fut_fee_innovation: "Отдельная тейкер-комиссия фьючерсов зоны инноваций Bybit, в процентах.", + use_new: "Включать новые фьючерсы в список кандидатов.", + use_innovation: "Включать инструменты зоны инноваций или с меткой новой монеты.", + use_memes: "Включать монеты из списка мемкойнов.", + all_coins: "Рассматривать все монеты, у которых есть подходящий спот и фьючерс.", + auto_transfer: "Разрешать внутренний перевод USDT спот → фьючерсы в реальном режиме.", + entry_limit: "Входить первой ногой лимитно, вторую открывать после подтверждённого исполнения." + } +}; +const HELP_MODES = { + lead: "Сравнивает движение ведущей и фьючерса за выбранное окно. Вход появляется, когда фьючерс отстал достаточно сильно; ставка делается на догоняющее движение. Связанные поля: отставание для входа и окно сравнения.", + vector: "Измеряет направление движения ведущей за окно вектора и ищет вход в ту же сторону. Связанные поля: окно вектора и минимальное движение ведущей.", + basis: "Измеряет отклонение разрыва между ведущей и фьючерсом от его обычного уровня и делает ставку на возврат. Связанные поля: окно разрыва, пороги входа/выхода в σ и минимальный разрыв. Это отдельный режим монеты, а не двухногая вкладка «Арбитраж»." +}; +const HELP_EXTRA = [ + ["Как пользоваться", "workflow", "Симуляция и реальная торговля", "Сначала выберите вкладку и режим. Верхняя строка всегда показывает текущий режим и свежесть связи. В симуляции все монеты и бумажный арбитраж используют один виртуальный счёт. Реальная торговля использует счета бирж. Входы запускаются кнопкой «Старт» отдельно для монеты или режима арбитража; «Стоп» останавливает новые входы, но не является командой закрыть все позиции."], + ["Как пользоваться", "saving", "Применение настроек", "В симуляторе изменения отправляются кнопкой «Применить ко всем монетам». В арбитраже основные настройки и комиссии/лимиты имеют отдельные кнопки сохранения. До сохранения действует прежняя конфигурация. Черновики симуляции и реального арбитража сохраняются отдельно при переключении режима в этой вкладке браузера."], + ["Как пользоваться", "connection", "Нет связи / устарели данные", "Индикатор сверху относится к связи браузера с программой. При ошибке или отсутствии свежих данных больше 10 секунд команды блокируются; чтение автоматически восстанавливается. Отправленные торговые команды автоматически не повторяются: при потере ответа проверьте журнал и позиции. Возраст рыночных котировок показывается отдельно."], + ["Как пользоваться", "block_reason", "Почему нет входа", "Смотрите статус монеты, сообщение о ведущей и последнюю колонку таблицы связок. Причины включают остановленные входы, недостаточную историю, устаревшие котировки, фильтры прибыли/спреда, минимальный ордер, занятые лимиты и нехватку свободных средств общего счёта."], + ["Как пользоваться", "reset", "Сбросить статистику", "Очищает статистику выбранного режима только когда нет открытых позиций. У монеты сброс также блокируется при незавершённых реальных ордерах, восстановлении или ошибке хранения реального состояния. Не пополняет и не обнуляет общий виртуальный счёт. Для изменения виртуальных денег используйте «Пополнить» или «Списать»."], + ["Виртуальный счёт", "balance", "Баланс", "Проведённые пополнения и списания, закрытый торговый результат, комиссии и учтённый funding. Общий для всех виртуальных сделок; бюджет не копируется заново для каждой монеты. Историческая статистика сделок и баланс счёта — разные показатели."], + ["Виртуальный счёт", "equity", "Капитал (Equity)", "Баланс плюс текущий нереализованный результат открытых виртуальных позиций. Это оценка по последним доступным котировкам; при устаревших ценах помечается отдельно."], + ["Виртуальный счёт", "reserved", "Зарезервировано", "Для монеты резервируется маржа при входе (номинал / плечо). Для арбитража спот-фьючерс — стоимость спота и резерв под фьючерс, не меньше 103% номинала фьючерса либо больше для заданного запаса до ликвидации. Для спот-спот консервативно резервируются средства обеих ног. Резерв освобождается после закрытия."], + ["Виртуальный счёт", "free", "Свободно", "max(0, min(баланс, капитал) − резерв). Открытая прибыль не финансирует новые входы, а открытый убыток уменьшает доступные средства. Вход разрешён, только если хватает на резерв и комиссии."], + ["Виртуальный счёт", "accountDelta", "Сумма изменения / Пополнить / Списать", "Введите положительную сумму в долларах (точка или запятая, до 8 знаков после разделителя). «Пополнить» прибавляет её к общему виртуальному счёту; «Списать» вычитает в пределах свободных средств. При отсутствии оценки открытой позиции или её возрасте больше 30 секунд списание и новые входы блокируются. Пополнение при рабочей связи остаётся доступным. Эти операции не меняют торговую прибыль и не переводят реальные деньги."], + ["Виртуальный счёт", "accountJournal", "Журнал и повтор операции", "В журнале видны время, причина, сумма изменения и баланс после операции. Отображаются последние 100 записей, новые сверху. Если ответ о пополнении или списании потерян, повтор той же суммы в текущей открытой странице использует прежний идентификатор и не проводит операцию второй раз. После перезагрузки страницы сначала сверьте журнал: незавершённый запрос в браузере уже не сохранён."], + ["Виртуальный счёт", "migration", "Первый запуск общего счёта", "Начальный депозит переносится один раз из прежнего общего бюджета (по умолчанию 300 $). Начальные балансы отдельных монет не складываются. Старые закрытые сделки остаются в статистике; для перенесённых открытых позиций учитываются резерв и комиссия входа."], + ["Биржи и лимиты", "use_exchange", "Искать и торговать", "Галочка каждой биржи включает её в поиск и новые входы выбранного режима. Выключение не прекращает сопровождение уже открытых позиций. Изменение применяется сразу."], + ["Биржи и лимиты", "limits", "Сделок открыто / макс.", "Открытое число и максимальный лимит по каждой бирже. Сделка учитывается на участвующих биржах; новый вход требует свободного лимита у обеих ног. После редактирования нажмите «Сохранить комиссии и лимиты»."], + ["Биржи и лимиты", "fees.spot", "Комиссия спот, %", "Тейкер-комиссия одной рыночной операции на споте в процентах. Открытие и закрытие считаются отдельно. Значение участвует в расчёте ожидаемого и виртуального результата."], + ["Биржи и лимиты", "fees.fut", "Комиссия фьючерса, %", "Тейкер-комиссия одной операции фьючерсной ноги в процентах. Для Bybit ниже может задаваться отдельная комиссия зоны инноваций (fut_innovation)."], + ["Биржи и лимиты", "fees.fut_innovation", "Зона инноваций Bybit, %", "Отдельная ставка комиссии фьючерсов зоны инноваций. Источник значения отображается под полем; при включённой автокоррекции данные завершённых сделок уточняют ставку."], + ["Биржи и лимиты", "exchange_balance", "Балансы и «С запуска»", "Спот USDT и фьючерсы USDT — свободные денежные счета биржи; монеты в позициях показаны отдельно. Единый счёт не суммируется дважды. «С запуска» сравнивает оценку с запуском реального режима и может включать внешние изменения счёта, а не только результат программы."], + ["Реальная торговля", "api_key", "API key / API secret", "Ключ и секрет для выбранной биржи. «Сохранить» записывает их локально в защищённое хранилище; секрет не возвращается в браузер. «Проверить (баланс)» проверяет доступ чтением баланса, «Удалить» удаляет сохранённые ключи. Нужны права торговли; разрешение вывода средств для программы не требуется."], + ["Реальная торговля", "coinReal", "Включить реальную торговлю монеты", "Включается отдельно у каждой монеты после подтверждения. Перед переключением нужно завершить её текущие виртуальные и реальные позиции, включая сохранённые позиции выбранного режима; незавершённые ордера, восстановление и ошибки сохранения блокируют переход. Новые позиции повторяются реальными рыночными ордерами: номинал = ставка × плечо. Реальная позиция одна за раз, следующая — после подтверждённого закрытия предыдущей. Общий виртуальный счёт и его пополнения не меняют реальные средства, размер ордеров или разрешение реальных входов. Сохранение ключей само по себе торговлю не запускает."], + ["Реальная торговля", "simRealTpsl", "TP/SL на бирже", "Отправлять защитные ордера на поддерживаемые биржи (Bybit, Binance, MEXC). SL сопровождает вход, TP выставляется как reduce-only от фактической цены исполнения. Проверяйте подтверждение ордеров в журнале: сама включённая галочка не означает, что биржа приняла защиту."], + ["Реальная торговля", "simRealTransfer", "Автоперевод USDT спот → фьючерсы", "При нехватке фьючерсного баланса разрешать перевод со спотового счёта той же биржи. Меняет реальные счета внутри биржи; включается отдельно от арбитражной настройки автоперевода."], + ["Реальная торговля", "simRealSl", "Стоп-лосс на бирже, %", "Расстояние биржевого стоп-лосса от входа в процентах цены. Это отдельная защита реального ордера, отличная от общего стоп-лосса стратегии. Сохраняется после изменения поля."], + ["Реальная торговля", "simRealPing", "Макс. пинг до биржи, мс", "Блокировать новые виртуальные и реальные входы монеты, если измеренная задержка биржи выше порога. 0 отключает проверку. Это задержка до биржи, а не возраст котировки или связь браузера."], + ["Реальная торговля", "real_start", "Арбитраж → Реальная торговля → Старт", "Отдельный движок со своими настройками, лимитами и сделками. Перед запуском подтверждаются биржи, типы связок и сумма сделки. Работа бумажного арбитража не включает реальный режим."], + ["Сканер", "scMin", "Минут на цикл", "Длительность сбора цен одной группы монет в минутах. Результаты появляются после полного цикла, а не сразу после старта; подготовка может увеличить ожидание."], + ["Сканер", "scCoins", "Монет за цикл", "Размер группы проверяемых монет, до 13. Следующие группы проверяются по кругу."], + ["Сканер", "scAuto", "Добавлять найденные автоматически", "Автоматически переносить найденные подходящие монеты в список наблюдения. Добавление в список и разрешение реальной торговли — отдельные действия."], + ["Сканер", "scanner_add", "Добавить / Добавить для теста", "Переносит монету в левую панель остановленной. «Для теста» означает, что убедительного опережения DEX пока нет. Старт сделок выполняется на странице монеты."], + ["Калькулятор бюджета", "cStake", "Ставка (сумма сделки), $", "Номинал одной ноги спот-фьючерсной сделки. Калькулятор оценивает потребность в средствах; он не меняет ставку стратегии и не пополняет счёт."], + ["Калькулятор бюджета", "cCount", "Сделок одновременно на бирже", "Число позиций, под которые рассчитывается запас на каждой бирже. В калькуляторе используется целая часть введённого числа, минимум 1."], + ["Калькулятор бюджета", "cLiq", "Желаемый рост цены до ликвидации, %", "На какой рост цены против шорта рассчитывается запас. Это приближённая оценка, зависящая от поддерживающей маржи; реальная биржа может применять уровни маржи и дополнительные условия."], + ["Калькулятор бюджета", "cEx", "Бирж с деньгами", "Число бирж, между которыми распределён капитал. Используется целое число от 1 для оценки общей потребности."], + ["Калькулятор бюджета", "cMmr", "Поддерж. маржа, %", "Предполагаемая ставка поддерживающей маржи биржи. При расчёте берётся значение в процентах; его нужно сопоставить с условиями конкретного инструмента."], + ["Калькулятор бюджета", "cFee", "Запас на комиссии спота, %", "Дополнительная доля к стоимости покупки спота в расчёте бюджета. Не меняет таблицу торговых комиссий программы."], + ["Калькулятор бюджета", "calcFromSettings", "Взять из настроек реальной торговли", "Копирует сумму сделки, запас до ликвидации, максимальный лимит сделок и число активных бирж с ключами из реального арбитража только в калькулятор."], + ["Термины", "spot", "Спот", "Покупка или продажа самой монеты. В спот-фьючерсной связке купленная монета образует одну из двух ног."], + ["Термины", "futures", "Фьючерс / бессрочный контракт", "Производный инструмент на цену монеты. Бессрочный контракт не имеет даты погашения и может включать периодические платежи funding."], + ["Термины", "long_short", "LONG / SHORT", "LONG выигрывает от роста цены, SHORT — от снижения. В арбитраже позиции ног рассматриваются вместе: прибыль одной ноги может компенсироваться убытком другой."], + ["Термины", "bid_ask", "Bid / Ask / спред", "Bid — лучшая доступная цена продажи в рынок, ask — покупки. Спред — разница между ними. Покупка и немедленная продажа обычно теряют спред и комиссии."], + ["Термины", "dex_cex", "DEX / CEX / ведущая", "DEX — децентрализованная площадка, CEX — централизованная биржа. «Ведущая» — выбранный источник сигнала; факт опережения проверяется по истории и может измениться."], + ["Термины", "gap", "Разница / обычная / выше обычной", "Разница — наблюдаемое расхождение цен ног. Обычная — исторический базовый уровень связки. Выше обычной — превышение текущей разницы над этим уровнем. Возврат к среднему возможен, но не гарантирован."], + ["Термины", "pnl", "PNL / чистый результат / винрейт", "PNL — прибыль или убыток. Чистый результат учитывает комиссии и указанные в отчёте платежи; открытый PNL ещё не зафиксирован. Винрейт — доля прибыльных закрытых сделок, сам по себе не показывает общую доходность."], + ["Термины", "funding", "Funding", "Периодический платёж между держателями фьючерсных позиций. При положительной ставке шорт обычно получает, при отрицательной платит. Ставка может меняться, а расчётный funding в таблице может быть оценочным."], + ["Термины", "margin_liquidation", "Маржа / ликвидация", "Маржа — средства обеспечения позиции. Ликвидация — принудительное закрытие биржей при недостаточном обеспечении. Спот на другой бирже автоматически не защищает фьючерсную маржу."], + ["Термины", "ioc_reduce_only", "IOC / reduce-only / лимитный ордер", "Лимитный ордер ограничивает цену исполнения. IOC исполняет доступную часть сразу и отменяет остаток. Reduce-only разрешает только уменьшение существующей позиции, чтобы закрывающий ордер не открыл обратную."], + ["Термины", "depth_minorder", "Глубина / оборот / минимальный вход", "Глубина — доступный объём по рассматриваемым ценам, оборот — сумма торгов за период. Минимальный вход определяется требованиями обеих ног к сумме и шагу количества. Это разные ограничения."], + ["Термины", "sigma_corr", "σ / корреляция / уверенность", "σ — стандартное отклонение, мера разброса. Корреляция описывает совместное движение рядов. Уверенность и перевес ведущей — внутренние оценки алгоритма; они не равны вероятности будущей прибыли."], + ["Термины", "scanner_metrics", "Лаг / t+1→t+5 / попадания / t", "Лаг — измеренный сдвиг между движениями цен, в секундах. t+1→t+5 — наблюдаемое движение на указанном горизонте после сигнала; попадания — доля наблюдений нужного направления, t — статистический показатель силы эффекта. Эти метрики относятся к проверенному циклу сканера."], + ["Термины", "chart", "График и время", "Линии показывают изменение каждой цены в процентах от начала выбранного окна, а не абсолютный ценовой разрыв. ▲/▼ обозначают входы, ● — выходы. Переключатели 1/5/10 минут меняют только окно графика. Время на странице — московское (МСК)."] +]; diff --git a/web/help.js b/web/help.js new file mode 100644 index 0000000..368293f --- /dev/null +++ b/web/help.js @@ -0,0 +1,78 @@ +let helpReturnFocus = null; +let helpFieldCounter = 0; +function helpEntries() { + const entries = HELP_EXTRA.map(([group, key, label, text]) => ({group, key, label, text})); + const groups = [ + ["Симулятор — настройки монет", "sim", [...MAIN_FIELDS, ...MORE_FIELDS]], + ["Арбитраж — симуляция и реальная торговля", "cross", [...CX_FIELDS, ...CX_CHECKS]], + ["Движок спот-фьюч — дополнительные параметры", "basis", [...BX_FIELDS, ...BX_CHECKS]] + ]; + for (const [group, scope, fields] of groups) { + for (const [key, label] of fields) entries.push({group, key, label, text: HELP_SETTINGS[scope][key] || "Описание этого нового параметра ещё не добавлено."}); + } + const modes = state?.modes || {lead: "Ведущая биржа", vector: "Вектор", basis: "Разрыв цен"}; + for (const [key, label] of Object.entries(modes)) entries.push({group: "Режимы симулятора", key, label, text: HELP_MODES[key] || "Режим предоставлен сервером. Условия входа, выхода и текущая причина блокировки показываются в карточке выбранной монеты."}); + return entries; +} +function filterHelp(entries, query) { + const normalize = value => String(value).toLocaleLowerCase("ru").replace(/ё/g, "е"); + const words = normalize(query).trim().split(/\s+/).filter(Boolean); + return entries.filter(entry => words.every(word => normalize(`${entry.group} ${entry.key} ${entry.label} ${entry.text}`).includes(word))); +} +function renderHelp() { + const search = document.getElementById("helpSearch"), content = document.getElementById("helpContent"); + if (!search || !content) return; + const entries = filterHelp(helpEntries(), search.value); + const fragment = document.createDocumentFragment(), groups = new Map(); + for (const entry of entries) { + if (!groups.has(entry.group)) { + const section = document.createElement("section"), heading = document.createElement("h3"); + heading.textContent = entry.group; section.append(heading); groups.set(entry.group, section); fragment.append(section); + } + const article = document.createElement("article"), heading = document.createElement("h4"), key = document.createElement("code"), body = document.createElement("p"); + article.className = "help-entry"; heading.textContent = entry.label; key.textContent = entry.key; body.textContent = entry.text; + heading.append(key); article.append(heading, body); groups.get(entry.group).append(article); + } + content.replaceChildren(fragment); + document.getElementById("helpCount").textContent = entries.length ? `Найдено разделов и параметров: ${entries.length}` : "Ничего не найдено. Попробуйте короткое название или ключ настройки."; +} +function helpOpen(query = "") { + const dialog = document.getElementById("helpDialog"); + helpReturnFocus = document.activeElement; + document.getElementById("helpSearch").value = query; + renderHelp(); + if (!dialog.open) dialog.showModal(); + document.getElementById("helpSearch").focus(); +} +function helpClose() { document.getElementById("helpDialog").close(); } +function applyHelpHints() { + document.querySelectorAll("[data-k], [data-bx]").forEach(el => { + const key = el.dataset.k || el.dataset.bx, scope = el.dataset.k ? "sim" : "cross"; + const text = HELP_SETTINGS[scope][key]; + if (text) el.title = text; + if (!el.id) el.id = `setting-${scope}-${key}`; + const label = el.closest(".field")?.querySelector("label"); + if (label) label.htmlFor = el.id; + if (el.tagName === "INPUT" && el.type !== "checkbox") el.inputMode = "decimal"; + }); + document.querySelectorAll("[data-cxfee], [data-cxlimit]").forEach(el => { + el.setAttribute("aria-label", el.dataset.cxfee ? `Комиссия ${el.dataset.cxfee}` : `Лимит сделок ${el.dataset.cxlimit}`); + el.inputMode = "decimal"; + }); + document.querySelectorAll(".field").forEach(field => { + const label = field.querySelector("label"), input = field.querySelector("input, select"); + if (!label || !input) return; + if (!input.id) input.id = `field-auto-${++helpFieldCounter}`; + label.htmlFor = input.id; + }); +} +const helpDialog = document.getElementById("helpDialog"); +if (helpDialog) { + helpDialog.addEventListener("close", () => { if (helpReturnFocus?.isConnected) helpReturnFocus.focus(); }); + // Native handles Escape and keeps keyboard focus inside the modal. + helpDialog.addEventListener("click", event => { + if (event.target !== helpDialog) return; + const bounds = helpDialog.getBoundingClientRect(); + if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) helpClose(); + }); +} diff --git a/web_proxy.py b/web_proxy.py index 0f7d5df..0f74cf9 100644 --- a/web_proxy.py +++ b/web_proxy.py @@ -11,6 +11,7 @@ program than the engine's python.exe) and add pythonw.exe to the VPN's app exclu from __future__ import annotations import sys +from request_security import trusted_request import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -26,12 +27,14 @@ class Proxy(BaseHTTPRequestHandler): pass def _forward(self, method: str) -> None: - if not self.client_address[0].startswith("127.") and self.client_address[0] != "::1": + if not trusted_request(self, command=method == "POST"): self.send_error(403, "only from this computer") return length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else None headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_HEADERS} + # Preserve the validated authority so the engine can compare the browser Origin. + headers["Host"] = self.headers["Host"] req = urllib.request.Request(ENGINE + self.path, data=body, method=method, headers=headers) try: with urllib.request.urlopen(req, timeout=30) as resp: diff --git a/web_sim.html b/web_sim.html index 8e0d77b..a25b951 100644 --- a/web_sim.html +++ b/web_sim.html @@ -4,147 +4,47 @@ Симулятор опережения - + +
    + СИМУЛЯЦИЯ · общий виртуальный счёт + Подключение к серверу… +
    + + + +

    Справка

    Термины, режимы и все настройки интерфейса

    + + +

    +
    +
    +
    @@ -263,1196 +163,8 @@ button.realon { background: rgba(255, 92, 92, 0.18); border-color: var(--red); c
    Выберите монету слева
    - + + + diff --git a/web_sim.py b/web_sim.py index 8fa9a07..41d5fda 100644 --- a/web_sim.py +++ b/web_sim.py @@ -4,10 +4,11 @@ * Common trade settings at the top apply to every coin (web_sim_data/settings.json). * Each coin (a connection from lead_connections.json: leader = KuCoin futures/spot or a Solana DEX pool, follower = - Bybit/Binance/MEXC futures) has its own feeds, its own paper account and journal (web_sim_data/.json/.csv) + Bybit/Binance/MEXC futures) has its own feeds and journal (web_sim_data/.json/.csv) and its own Start/Stop. Stop only forbids new entries: prices, the comparison and the forecast learning go on. +* Paper coins and paper arbitrage share one durable virtual account. Real signal ledgers are separate; + explicitly enabled real trading submits orders through the configured exchange clients. * Coins added later to lead_connections.json (e.g. by meme_matcher/autoscan.py) appear within 30 s. -Nothing is ever sent to an exchange. """ from __future__ import annotations @@ -24,6 +25,11 @@ from dataclasses import fields from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path +from request_security import trusted_request +from persistence import atomic_write_json +from pending_removals import PendingRemovals +from virtual_account import VirtualAccount, AccountError +from runtime_lock import RuntimeLock import keystore import lead_window as lw import live @@ -111,6 +117,12 @@ def scanner_add(symbol: str, connections: list[dict]) -> tuple[dict | None, str] DATA_DIR = ROOT / "web_sim_data" SETTINGS_FILE = DATA_DIR / "settings.json" PAGE = ROOT / "web_sim.html" +STATIC_ASSETS = { + "/static/app.js": (ROOT / "web" / "app.js", "text/javascript"), + "/static/app.css": (ROOT / "web" / "app.css", "text/css"), + "/static/help.js": (ROOT / "web" / "help.js", "text/javascript"), + "/static/help-data.js": (ROOT / "web" / "help-data.js", "text/javascript"), +} PORT = 8765 CONNECTION_FIELDS = set(lw.CONNECTION_KEYS) COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings) @@ -120,10 +132,20 @@ 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 +ACCOUNT: VirtualAccount | None = None +ACCOUNT_LOCK = threading.Lock() + + +def paper_account() -> VirtualAccount: + global ACCOUNT + with ACCOUNT_LOCK: + if ACCOUNT is None: + ACCOUNT = VirtualAccount(DATA_DIR / "virtual_account.json", load_common().get("budget", 300.0)) + return ACCOUNT def coin_key(conn: dict) -> str: @@ -185,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: @@ -216,16 +247,21 @@ def check_common(values: dict) -> tuple[dict, str]: class Engine: """One coin: leader + follower feeds, a paper trader and a price history for the chart.""" - def __init__(self, conn: dict, common: dict) -> None: + def __init__(self, conn: dict, common: dict, account: VirtualAccount | None = None) -> None: self.conn = dict(conn) self.key = coin_key(conn) self.symbol = coin_symbol(conn) self.name = lw.connection_name(conn) + self.common = dict(common) + self.account = account + self.signal_mode = bool(account is not None and + real_mirror.load_settings().get("coins", {}).get(self.key, {}).get("on")) DATA_DIR.mkdir(exist_ok=True) settings = sp.PaperSettings(mode=common.get("mode", "lead"), enabled=False) - state_file = DATA_DIR / f"{self.key}.json" + state_file = DATA_DIR / f"{'signal_' if self.signal_mode else ''}{self.key}.json" new_account = not state_file.exists() - self.paper = sp.PaperTrader(settings, sh.HintSettings(), state_file, DATA_DIR / f"{self.key}.csv") + self.paper = sp.PaperTrader(settings, sh.HintSettings(), state_file, + DATA_DIR / f"{'signal_' if self.signal_mode else ''}{self.key}.csv") enabled = self.paper.settings.enabled # the coin's own Start/Stop survives restarts self.apply(common, initial=True) self.paper.settings.enabled = enabled @@ -234,11 +270,21 @@ class Engine: for k in CONNECTION_FIELDS: setattr(self.paper.settings, k, conn[k]) self.paper.policy = self.paper._make_policy() + self.paper._restore_policy() + if account is not None and not self.signal_mode: + try: + self.paper.bind_account(account, "coin:" + self.key) + except (OSError, ValueError, TypeError, KeyError) as exc: + # Keep the diagnostics page available; never silently fall back to + # an independent account when the shared recovery source is broken. + led = self.paper.ledger + led.account, led.account_owner = account, "coin:" + self.key + led.storage_error = led._recovery_error = f"Счёт не восстановлен: {exc}" + self.paper.settings.enabled = False # real trading: the same orders on the coin's futures exchange while the tab's real mode is on ps = self.paper.settings self.mirror = real_mirror.FuturesMirror(self.key, self.symbol, ps.follow_exchange, ps.follow_ticker) - self.paper.ledger.hooks.append(self.mirror.hook) - self.paper.gate = self.mirror.gate # one real trade at a time, confirmed closed + self._connect_trader() self.mirror.on_failed_open = lambda uid: self.close(uid, "реальный ордер не прошёл") self.mirror.ping = lambda ex=ps.follow_exchange: ping_for(ex) # no entry while the ping is above the limit self.lock = threading.RLock() @@ -254,14 +300,71 @@ class Engine: self.lead_status = "подключаюсь…" self.follow_status = "подключаюсь…" self.message = "" + self.close_error = "" + self.removing = False self.auto_stop = "" # why the pair was stopped automatically (cleared by Start) self.checked_at = None # time of the last leader measurement looked at self.feeds: list = [] self.stopped = threading.Event() self.thread = threading.Thread(target=self._pump, daemon=True) + def _connect_trader(self) -> None: + # Pure paper operations never call the real mirror, even if a virtual + # deposit makes a previously unaffordable paper entry possible. + real_signals = self.signal_mode or self.account is None + 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.""" + with self.lock: + if self.removing: + return "Подключение ожидает удаления" + if self.paper.ledger.positions or not self.mirror.ready_to_remove(): + return "Перед сменой режима закройте бумажные и реальные позиции этой монеты" + if self.signal_mode == enabled: + return real_mirror.save_settings({"coin": self.key, "enabled": enabled}) + prefix = "signal_" if enabled else "" + settings = sp.PaperSettings(mode=self.common.get("mode", "lead"), enabled=False) + trader = sp.PaperTrader(settings, sh.HintSettings(), DATA_DIR / f"{prefix}{self.key}.json", + DATA_DIR / f"{prefix}{self.key}.csv") + new_ledger = not (DATA_DIR / f"{prefix}{self.key}.json").exists() + try: + if not enabled and self.account is not None: + trader.bind_account(self.account, "coin:" + self.key) + if trader.ledger.positions: + return "В выбранном режиме сохранены открытые позиции; сначала завершите их сопровождение" + if trader.ledger.storage_error: + return trader.ledger.storage_error + for key, value in self.common.items(): + setattr(trader.settings, key, value) + if enabled and new_ledger: + trader.ledger.balance = trader.settings.budget + for key in CONNECTION_FIELDS: + setattr(trader.settings, key, self.conn[key]) + trader.policy = trader._make_policy() + trader._restore_policy() + trader.settings.enabled = self.paper.settings.enabled + if not trader.ledger.save(): + return trader.ledger.storage_error + problem = real_mirror.save_settings({"coin": self.key, "enabled": enabled}) + if problem: + return problem + except (OSError, ValueError, TypeError, KeyError) as exc: + return f"Режим не переключён: {exc}" + self.paper, self.signal_mode = trader, enabled + self._connect_trader() + self.message = "Реальная торговля" if enabled else "Симуляция: общий виртуальный счёт" + return "" + # --- 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) @@ -289,10 +392,16 @@ class Engine: self.paper.ledger.save() def apply(self, common: dict, initial: bool = False) -> None: + self.common.update(common) ps = self.paper.settings lock = self.lock if not initial else threading.RLock() with lock: mode = common.get("mode", ps.mode) + if initial and self.paper.ledger.positions: + # A recovered position keeps the policy that opened it. In + # particular, private real-signal ledgers have no shared-wallet + # restore step that could undo an initial global-mode override. + mode = ps.mode for k, v in common.items(): if k != "mode": setattr(ps, k, v) @@ -304,6 +413,9 @@ class Engine: def set_trading(self, on: bool) -> None: with self.lock: + if on and self.removing: + self.message = "Подключение ожидает закрытия позиций и удаления" + return self.paper.settings.enabled = on self.paper.ledger.save() if on: @@ -312,12 +424,17 @@ class Engine: "Стоп: новые сделки не открываются; открытые закроются по тейку, стопу или времени") def reset(self) -> str: - """Clear this coin's statistics: open positions dropped, journal emptied, balance back to the budget. - Start/Stop, prices, the leader check and the forecast learning are kept.""" + """Clear statistics only while both the paper/signal ledger and the real mirror are flat.""" with self.lock: + if self.paper.ledger.positions or not self.mirror.ready_to_remove(): + self.message = "Сначала закройте бумажные и реальные позиции этой монеты" + return self.message enabled = self.paper.settings.enabled - self.paper.ledger.reset() # positions, trades, CSV; balance = budget - self.mirror.reset_stats() # real figures start again from now too + if self.paper.ledger.reset() is False: + self.message = self.paper.ledger.storage_error + return self.message + if self.signal_mode or self.account is None: + self.mirror.reset_stats() self.paper.settings.enabled = enabled self.paper.ledger.save() self.paper.message = "" @@ -327,14 +444,26 @@ class Engine: def close(self, uid: int | None, reason: str = "вручную") -> str: """Close one position (uid) or all of them at the follower's current best price.""" with self.lock: + self.close_error = "" best_bid, best_ask = self.book.best() closed = 0 for pos in list(self.paper.ledger.positions): if uid is not None and pos.uid != uid: continue - price = (best_bid if pos.side == "LONG" else best_ask) or pos.entry + price = best_bid if pos.side == "LONG" else best_ask + if not price or (self.last_follower and time.time() - self.last_follower > + self.paper.settings.max_data_age_ms / 1000): + self.close_error = "Нет свежей цены для закрытия; позиция и резерв сохранены" + self.message = self.close_error + return self.close_error self.paper.close(price, time.time(), reason, self.paper.policy.taker, pos=pos) - closed += 1 + if pos not in self.paper.ledger.positions: + closed += 1 + 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: @@ -413,13 +542,14 @@ class Engine: return { "key": self.key, "symbol": self.symbol, "name": self.name, "leader": pol.L, "follower": pol.F, "follow_ticker": self.conn["follow_ticker"], - "running": self.paper.settings.enabled, + "running": self.paper.settings.enabled, "removing": self.removing, "price": (bid + ask) / 2 if bid and ask else None, "lead_price": sum(self.leader) / 2 if self.leader else None, "signal": getattr(pol, "signal", 0.0), "confidence": getattr(pol, "conf", 0.0), "open": len(led.positions), "trades": len(trades), "wins": wins, "net": sum(t.net_usd for t in trades), "fees": sum(t.fee_usd for t in trades), "unrealized": self.paper.unrealized(self.book), "balance": led.balance, + "account_error": getattr(led, "storage_error", ""), "leadership": getattr(pol, "leadership", {}), "leader_block": pol.leader_block() if hasattr(pol, "leader_block") else "", "min_edge": self.paper.settings.leader_min_edge, "now": now, "auto_stop": self.auto_stop, @@ -464,62 +594,120 @@ class Engine: class Simulator: - def __init__(self) -> None: + def __init__(self, account: VirtualAccount | None = None, start: bool = True) -> None: self.common = load_common() + self.account = account if account is not None else paper_account() self.engines: dict[str, Engine] = {} self.lock = threading.Lock() + self.removals = PendingRemovals(DATA_DIR / "pending_removals.json") + self.error = self.removals.error + self.start_feeds = start self.sync_connections() - threading.Thread(target=self._watch, daemon=True).start() + if start: + threading.Thread(target=self._watch, daemon=True).start() def sync_connections(self) -> None: """Start an engine for every connection in the list (new ones appear; removal is only via remove()).""" - for conn in lw.load_connections(): - key = coin_key(conn) + pending = self.removals.connections() + connections = {coin_key(c): c for c in lw.load_connections()} + connections.update(pending) # survives a crash between connection deletion and final acknowledgement + for key, conn in connections.items(): with self.lock: if key in self.engines: continue - engine = Engine(conn, self.common) + engine = Engine(conn, self.common, self.account) + engine.removing = key in pending + if engine.removing: + engine.set_trading(False) self.engines[key] = engine - engine.start() + if self.start_feeds: + engine.start() + if engine.removing: + engine.close(None) + engine.mirror.request_close() def remove(self, key: str) -> str: - """Delete a pair: close its open positions, stop all its data feeds and forget the connection.""" + """Keep the connection recoverable until both paper and real exposure is closed.""" with self.lock: engine = self.engines.get(key) if engine is None: return "нет такой монеты" - lw.remove_connection(engine.conn) - del self.engines[key] + try: + self.removals.schedule(key, engine.conn) + except (OSError, ValueError) as exc: + return f"Удаление не начато: {exc}" with engine.lock: - engine.paper.settings.enabled = False + engine.removing = True + engine.set_trading(False) closed = len(engine.paper.ledger.positions) engine.close(None) # open positions at the current price - engine.shutdown() # feeds (exchange + DEX/KuCoin) and the pump thread stop - return f"{engine.name} удалена, сбор данных остановлен" + (f", закрыто позиций: {closed}" if closed else "") + engine.mirror.request_close() + if self._finish_removal(key): + return f"{engine.name} удалена, сбор данных остановлен" + (f", закрыто позиций: {closed}" if closed else "") + engine.message = "Удаление ожидает подтверждённого закрытия всех позиций; подключение сохранено" + return engine.message + + def _finish_removal(self, key: str) -> bool: + with self.lock: + engine = self.engines.get(key) + if engine is None: + return False + with engine.lock: + if engine.paper.ledger.positions or not engine.mirror.ready_to_remove(): + return False + try: + lw.remove_connection(engine.conn) + self.removals.complete(key) + except (OSError, ValueError) as exc: + engine.message = f"Не удалось завершить удаление: {exc}" + return False + del self.engines[key] + engine.shutdown() + return True def _watch(self) -> None: + next_sync = 0.0 while True: - time.sleep(30) + time.sleep(1) try: - self.sync_connections() - except Exception: - pass + if time.time() >= next_sync: + self.sync_connections() + next_sync = time.time() + 30 + for key in self.removals.connections(): + with self.lock: + engine = self.engines.get(key) + if engine is not None and engine.paper.ledger.positions: + engine.close(None) + self._finish_removal(key) + except Exception as exc: + self.error = f"Обновление подключений: {exc}" def save_common(self, values: dict) -> str: + if "budget" in values and getattr(self, "account", None) is not None: + return "Изменяйте баланс через «Виртуальный счёт»: Пополнить / Списать" clean, problem = check_common(values) if problem: return problem - self.common.update(clean) - DATA_DIR.mkdir(exist_ok=True) - SETTINGS_FILE.write_text(json.dumps(self.common, ensure_ascii=False, indent=2), encoding="utf-8") - for engine in list(self.engines.values()): + updated = {**self.common, **clean} + try: + atomic_write_json(SETTINGS_FILE, updated) + except (OSError, ValueError) as exc: + return f"Настройки не сохранены: {exc}" + self.common = updated + with self.lock: + engines = list(self.engines.values()) + for engine in engines: engine.apply(clean) return "" def state(self) -> dict: + with self.lock: + engines = list(self.engines.values()) return {"settings": self.common, "modes": lw.MODES, + "account": self.account.view() if getattr(self, "account", None) else None, + "error": getattr(self, "error", ""), # pairs enabled for trades first, then by name - "coins": sorted((e.summary() for e in self.engines.values()), + "coins": sorted((e.summary() for e in engines), key=lambda c: (not c["running"], c["symbol"], c["name"]))} @@ -615,7 +803,7 @@ def basis_engine(venue: str): with BASIS_LOCK: if "cross" not in BASIS: import cross - BASIS["cross"] = cross.CrossEngine() + BASIS["cross"] = cross.CrossEngine(account=paper_account()) BASIS["cross"].balances = BALANCES # the accounts of every exchange with keys (read every 10 s) if venue == "cross_real" and "cross_real" not in BASIS: import cross @@ -640,11 +828,19 @@ class Handler(BaseHTTPRequestHandler): self._send(code, json.dumps(data, ensure_ascii=False).encode("utf-8")) def do_GET(self) -> None: + if not trusted_request(self): + self._json({"error": "недоверенный адрес страницы"}, 403) + return path, _, query = self.path.partition("?") if path in ("/", "/index.html"): self._send(200, PAGE.read_bytes(), "text/html") + elif path in STATIC_ASSETS: + asset, kind = STATIC_ASSETS[path] + self._send(200, asset.read_bytes(), kind) elif path == "/api/state": self._json(SIM.state()) + elif path == "/api/account": + self._json(paper_account().view()) elif path == "/api/arb": m = re.search(r"transfer=([0-9.]+)", query) mk = re.search(r"market=(spot|futures)", query) @@ -660,7 +856,10 @@ class Handler(BaseHTTPRequestHandler): if engine is None: self._json({"error": "эта биржа пока не подключена"}, 404) else: - self._json(engine.view()) + payload = engine.view() + if not getattr(engine, "is_real", False): + payload["paper_account"] = paper_account().view() + self._json(payload) elif path == "/api/scanner": try: self._json(scanner_view(lw.load_connections())) @@ -683,18 +882,43 @@ class Handler(BaseHTTPRequestHandler): if not local_request(self): self._json({"error": "команды принимаются только со страницы симулятора на этом компьютере"}, 403) return - length = int(self.headers.get("Content-Length") or 0) try: + length = int(self.headers.get("Content-Length") or 0) + if not 0 <= length <= 65536: + self._json({"ok": False, "error": "Слишком большой запрос"}, 413) + return body = json.loads(self.rfile.read(length) or b"{}") - except ValueError: - body = {} + if not isinstance(body, dict): + raise ValueError("ожидается объект JSON") + except (ValueError, UnicodeError): + self._json({"ok": False, "error": "Некорректный JSON запроса"}, 400) + return parts = self.path.strip("/").split("/") + try: + self._command(parts, body) + except AccountError as exc: + self._json({"ok": False, "error": str(exc), "account": paper_account().view()}) + except (ValueError, TypeError, KeyError) as exc: + self._json({"ok": False, "error": f"Некорректная команда: {exc}"}, 400) + except OSError as exc: + self._json({"ok": False, "error": f"Операция не сохранена: {exc}"}, 500) + + def _command(self, parts: list[str], body: dict) -> None: + if parts == ["api", "account", "adjust"]: + account = paper_account().adjust(body.get("amount"), body.get("request_id")) + self._json({"ok": True, "account": account}) + return if parts == ["api", "settings"]: problem = SIM.save_common(body) self._json({"ok": not problem, "error": problem}) return if parts[:3] == ["api", "real", "simulator"]: - problem = real_mirror.save_settings(body) + coin = body.get("coin") + if coin and "enabled" in body: + engine = SIM.engines.get(str(coin)) + problem = engine.switch_real(body["enabled"] in (True, "true", 1, "1")) if engine else "нет такой монеты" + else: + problem = real_mirror.save_settings(body) self._json({"ok": not problem, "error": problem}) return if parts[:3] == ["api", "real", "keys"] and len(parts) >= 4: @@ -732,7 +956,9 @@ class Handler(BaseHTTPRequestHandler): uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None self._json({"ok": True, "message": engine.close(uid)}) elif parts[3] == "reset": - self._json({"ok": True, "message": engine.reset()}) + message = engine.reset() + self._json({"ok": message.lower() == "статистика сброшена", "message": message, + "error": "" if message.lower() == "статистика сброшена" else message}) elif parts[3] == "adopt": try: price = float(body["price"]) if body.get("price") not in (None, "") else None @@ -781,17 +1007,22 @@ class Handler(BaseHTTPRequestHandler): action = parts[3] if action == "start": engine.set_trading(True) - self._json({"ok": True}) + self._json({"ok": not engine.removing, + "error": engine.message if engine.removing else ""}) elif action == "stop": engine.set_trading(False) self._json({"ok": True}) elif action == "reset": - self._json({"ok": True, "message": engine.reset()}) + message = engine.reset() + self._json({"ok": message.lower() == "статистика сброшена", "message": message, + "error": "" if message.lower() == "статистика сброшена" else message}) elif action == "remove": self._json({"ok": True, "message": SIM.remove(parts[2])}) elif action == "close": uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None - self._json({"ok": True, "message": engine.close(uid)}) + message = engine.close(uid) + error = engine.close_error or engine.paper.ledger.storage_error + self._json({"ok": not bool(error), "message": message, "error": error}) else: self._json({"error": "unknown action"}, 404) return @@ -804,14 +1035,15 @@ LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"} def local_request(handler) -> bool: - """A command from this simulator's own page: the Host is the local address (no DNS rebinding) and the request - carries the X-Sim header — another web site open in the browser cannot add it without a CORS preflight, which - this server never allows, so it cannot press buttons here (real trading, keys).""" - host = (handler.headers.get("Host") or "").rsplit(":", 1)[0].lower() - return host in LOCAL_HOSTS and handler.headers.get("X-Sim") == "1" + return trusted_request(handler, command=True) def main() -> None: + with RuntimeLock(DATA_DIR / "engine.lock"): + _serve() + + +def _serve() -> None: import sys global SIM # --backend: only for this PC on BACKEND_PORT, the public page is served by web_proxy.py (outside the VPN) @@ -819,6 +1051,8 @@ def main() -> None: host, port = "127.0.0.1", BACKEND_PORT else: host, port = ("127.0.0.1" if "--local" in sys.argv else HOST), PORT + # Claim the port before starting recovery workers or exchange connections. + server = ThreadingHTTPServer((host, port), Handler) real_mirror.load_recent() import minorder minorder.AUTOLOAD = True # the exchanges' smallest orders (spot and perp), loaded and renewed hourly @@ -832,7 +1066,6 @@ def main() -> None: # «Арбитраж»: the simulation and the real engine run from the start (open real positions are watched at once) basis_engine("cross") basis_engine("cross_real") - server = ThreadingHTTPServer((host, port), Handler) url = f"http://127.0.0.1:{PORT}" print(f"Симулятор: {url} (движок слушает {host}:{port}, монет: {len(SIM.engines)})", flush=True) threading.Timer(1.0, lambda: webbrowser.open(url)).start() @@ -841,6 +1074,7 @@ def main() -> None: except KeyboardInterrupt: pass finally: + server.server_close() for engine in SIM.engines.values(): engine.shutdown()