1
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s

This commit is contained in:
listik committed 2026-10-23 20:49:12 +03:00
1 parent 2ea1a79bda
commit 85425483c0
50 files changed
+6454 -1840

No files matched your search

+25
View File
@@ -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"
+23
View File
@@ -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
+55
View File
@@ -28,6 +28,8 @@
### Установка вручную через PowerShell ### Установка вручную через PowerShell
Python 3.11+; dependencies are pinned in `requirements.txt`. Recovery semantics, module layout and offline tests: [docs/reliability.md](docs/reliability.md).
```powershell ```powershell
cd C:\Crypto_Scam cd C:\Crypto_Scam
py -3 -m venv .venv py -3 -m venv .venv
@@ -88,7 +90,52 @@ py -3 -m venv .venv
`scalp_paper.py` и `algo_hunter.py` содержат экспериментальные модели по стакану, imbalance, микроцене и повторяющимся заявкам. Они предназначены для dry-run и анализа: видимый агрегированный стакан не позволяет надёжно доказать наличие конкретного маркет-мейкера или реальную очередь исполнения. `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-ключи ## Реальная торговля и API-ключи
>>>>>>> main
Используйте реальную торговлю только после проверки в симуляции и на Testnet. Используйте реальную торговлю только после проверки в симуляции и на Testnet.
@@ -102,7 +149,15 @@ py -3 -m venv .venv
В проекте предусмотрены отдельные состояния виртуального и реального счёта. Они не смешиваются. Для реального режима учитывайте funding, проскальзывание, минимальный размер ордера, задержку сети и риск ликвидации при усреднении или плече. В проекте предусмотрены отдельные состояния виртуального и реального счёта. Они не смешиваются. Для реального режима учитывайте 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, внешний доступ и безопасность ## VPN, внешний доступ и безопасность
>>>>>>> main
- Если биржи не отдают цены, проверьте VPN и доступ к публичным API. - Если биржи не отдают цены, проверьте VPN и доступ к публичным API.
- По умолчанию страница доступна только локально через `127.0.0.1`; это безопаснее, чем открывать её в интернет. - По умолчанию страница доступна только локально через `127.0.0.1`; это безопаснее, чем открывать её в интернет.
+62 -8
View File
@@ -527,6 +527,38 @@ class AlgoHunterPolicy:
self.status_reason = "" self.status_reason = ""
# --- helpers ------------------------------------------------------------------------ # --- 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: def _latency(self, trader) -> float | None:
"""Effective delay of our view of the book: measured data latency, or the source cadence at least.""" """Effective delay of our view of the book: measured data latency, or the source cadence at least."""
measured = getattr(trader, "data_latency_ms", None) measured = getattr(trader, "data_latency_ms", None)
@@ -669,6 +701,9 @@ class AlgoHunterPolicy:
self.status_reason = "волатильность за 1 с выше порога" self.status_reason = "волатильность за 1 с выше порога"
return None return None
notional = self.s.stake * self.s.leverage 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)) allowed, reason = self.guard.allow(now, notional, self._latency(trader))
if not allowed: if not allowed:
if reason != self.warned: if reason != self.warned:
@@ -767,13 +802,14 @@ class AlgoHunterPolicy:
long = order.side == "LONG" long = order.side == "LONG"
hits_us = (trade.side == "Sell") if long else (trade.side == "Buy") hits_us = (trade.side == "Sell") if long else (trade.side == "Buy")
if (trade.price < order.price) if long else (trade.price > order.price): 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: elif hits_us and abs(trade.price - order.price) < self.tick / 2:
consumed = min(order.ahead, trade.size) consumed = min(order.ahead, trade.size)
order.ahead -= consumed order.ahead -= consumed
order.algo_ahead = max(0.0, order.algo_ahead - consumed) order.algo_ahead = max(0.0, order.algo_ahead - consumed)
if trade.size > consumed or order.ahead <= 0: available = max(0.0, trade.size - consumed)
self._fill(trader, trade.ts) if available > 0:
self._fill(trader, trade.ts, available)
return return
pos = trader.ledger.position pos = trader.ledger.position
if pos is None: 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 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): 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) 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): if (trade.price <= self.stop) if long else (trade.price >= self.stop):
slip = self.tick slip = self.tick
self._close(trader, self.stop - slip if long else self.stop + slip, trade.ts, 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): elif (trade.price > self.target) if long else (trade.price < self.target):
self._close(trader, self.target, trade.ts, "цель", sh.MAKER_FEE_PCT) 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 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 self.order = None
long = order.side == "LONG" long = order.side == "LONG"
trader.ledger.open(self.ticker, order.side, order.price, now, sh.MAKER_FEE_PCT, 0.0, None, order.price, target = order.price + (1 if long else -1) * self.cfg.tp_ticks * self.tick
order.scenario) 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.entry_order = order
self.filled_at = now self.filled_at = now
self.target = order.price + (1 if long else -1) * self.cfg.tp_ticks * self.tick self.target, self.stop = target, stop
self.stop = order.price - (1 if long else -1) * self.cfg.sl_ticks * self.tick
trader.ledger.position.target = self.target trader.ledger.position.target = self.target
trader.ledger.position.stop = self.stop trader.ledger.position.stop = self.stop
self.guard.on_entry(now) self.guard.on_entry(now)
@@ -815,6 +862,7 @@ class AlgoHunterPolicy:
self.stats["front_run"] += 1 self.stats["front_run"] += 1
trader.message = f"Algo Hunter: исполнена {order.side} {order.price:.10g} ({order.scenario})" 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) 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: def _cancel(self, trader, now: float, reason: str, quiet: bool = False) -> None:
if self.order is not None: if self.order is not None:
@@ -828,7 +876,10 @@ class AlgoHunterPolicy:
if pos is None: if pos is None:
return return
order = self.entry_order order = self.entry_order
before = len(trader.ledger.trades)
trader.close(price, now, reason, fee_pct) trader.close(price, now, reason, fee_pct)
if len(trader.ledger.trades) == before:
return
trade = trader.ledger.trades[-1] trade = trader.ledger.trades[-1]
pnl_ticks = (price - pos.entry) / self.tick * (1 if pos.side == "LONG" else -1) pnl_ticks = (price - pos.entry) / self.tick * (1 if pos.side == "LONG" else -1)
self.stats["pnl_ticks"] += pnl_ticks self.stats["pnl_ticks"] += pnl_ticks
@@ -855,6 +906,7 @@ class AlgoHunterPolicy:
except OSError: except OSError:
pass pass
self.entry_order = None self.entry_order = None
trader.ledger.save()
def rearm(self) -> None: def rearm(self) -> None:
"""Switch the mode back on after an 'algo adapted' shutdown (user pressed Apply, or a new ticker).""" """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("тестовые сделки выключены") out.append("тестовые сделки выключены")
if self.guard.disabled_reason: if self.guard.disabled_reason:
out.append(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 sig = self.sig
n = len(sig.signals) if sig else 0 n = len(sig.signals) if sig else 0
if cfg.fallback: if cfg.fallback:
+487 -85
View File
@@ -27,6 +27,7 @@ after each real trade they are replaced by what the exchanges actually charged,
from __future__ import annotations from __future__ import annotations
import json import json
from persistence import atomic_write_json
import queue import queue
import threading import threading
import time import time
@@ -175,6 +176,8 @@ class CrossSettings:
negative_funding_before_minutes: float = 60.0 # block negative funding only this long before settlement 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 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_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 @dataclass
@@ -217,6 +220,9 @@ class CrossPosition:
entry_signal: list = field(default_factory=list) # A ask, B bid confirmed right before the entry orders 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_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) 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 @property
def kind(self) -> str: def kind(self) -> str:
@@ -394,14 +400,27 @@ def _quote_now(l: "Link", usd: float) -> tuple[float, float, float, float, float
b["spread_pct"]) 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: class CrossEngine:
"""One engine per kind of trading: paper (simulation) or real — each started and stopped by itself. The real """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).""" one follows the paper one: it is handed the same prices and usual gaps every cycle (no second set of requests)."""
mode = "cross" mode = "cross"
def __init__(self, data_dir: Path = DATA_DIR, start: bool = True, real: bool = False, 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.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.key = "cross_real" if real else "cross"
self.file = data_dir / ("basis_cross_real.json" if real else "basis_cross.json") self.file = data_dir / ("basis_cross_real.json" if real else "basis_cross.json")
self.followers: list[CrossEngine] = [] self.followers: list[CrossEngine] = []
@@ -431,6 +450,7 @@ class CrossEngine:
# real trading # real trading
self.client_for = _client self.client_for = _client
self.quote_now = _quote_now if start else None # fresh prices right before a real entry (tests: none) 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.balances: dict = {} # web_sim's BALANCES (exchange key → account figures)
self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"} self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"}
self.opening: set[str] = set() # coins with a real entry in progress 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.usual, self.seen_since, self.last_seen = leader.usual, leader.seen_since, leader.last_seen
self.innovation = leader.innovation self.innovation = leader.innovation
leader.followers.append(self) 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 start:
if leader is None: if leader is None:
threading.Thread(target=self._loop, daemon=True).start() threading.Thread(target=self._loop, daemon=True).start()
@@ -470,10 +506,23 @@ class CrossEngine:
# --- persistence ----------------------------------------------------------------------------------------- # --- persistence -----------------------------------------------------------------------------------------
def _load(self) -> None: def _load(self) -> None:
d = None
if self.account is not None:
from virtual_account import AccountError
try: try:
d = self.account.restore("cross")
except AccountError as exc:
self.account_error = str(exc)
try:
if d is None:
d = json.loads(self.file.read_text(encoding="utf-8")) d = json.loads(self.file.read_text(encoding="utf-8"))
except (OSError, ValueError): except (OSError, ValueError):
return 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)} known = {f.name for f in fields(CrossSettings)}
for k, v in (d.get("settings") or {}).items(): for k, v in (d.get("settings") or {}).items():
if k in known: if k in known:
@@ -491,11 +540,16 @@ class CrossEngine:
if v is not None: if v is not None:
self.limits[ex] = int(v) self.limits[ex] = int(v)
self.positions = [CrossPosition(**p) for p in d.get("positions", [])] 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.trades = [CrossTrade(**t) for t in d.get("trades", [])]
self.next_uid = d.get("next_uid", 1) self.next_uid = d.get("next_uid", 1)
self.baseline = d.get("baseline") or {} self.baseline = d.get("baseline") or {}
self.recover = dict(d.get("pending") or {}) self.recover = dict(d.get("pending") or {})
self.migrated = list(d.get("migrated") 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: def _seed_from(self, paper_file: Path) -> None:
"""The real engine's first settings, fee table and limits: those of the simulation (stopped).""" """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), sold_fees=p.get("sold_fees", 0.0), exact=p.get("exact", True),
innovation=p.get("innovation", False)) innovation=p.get("innovation", False))
self.next_uid += 1 self.next_uid += 1
if not pos.real:
pos.paper_reserve = self._position_reserve(pos)
self.positions.append(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 ''})") moved.append(f"{p['base']} ({ex}{', реальная' if pos.real else ''})")
for t in d.get("trades", []): for t in d.get("trades", []):
if bool(t.get("real", False)) != self.is_real: if bool(t.get("real", False)) != self.is_real:
@@ -595,17 +653,92 @@ class CrossEngine:
except OSError: except OSError:
pass pass
def save(self) -> None: def _state(self) -> dict:
self.file.parent.mkdir(exist_ok=True) # 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], 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, "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, "fees": self.fees, "limits": self.limits, "baseline": self.baseline, "migrated": self.migrated,
"pending": {**self.recover, **self.pending}} "pending": {**self.recover, **self.pending}, "last_close": self.last_close}
tmp = self.file.with_suffix(".tmp") if self.account is not None:
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") data["cash_total"] = self.cash_total
tmp.replace(self.file) 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: 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: with self.lock:
was = (self.settings.running, self.settings.real) was = (self.settings.running, self.settings.real)
for f in fields(CrossSettings): for f in fields(CrossSettings):
@@ -641,7 +774,9 @@ class CrossEngine:
self.save() self.save()
return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под " return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под "
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 "" return ""
def _set_fees(self, given) -> str: def _set_fees(self, given) -> str:
@@ -938,10 +1073,12 @@ class CrossEngine:
def step(self, now: float) -> None: def step(self, now: float) -> None:
s = self.settings s = self.settings
self._mark_account(snapshot_fresh=True)
for base, info in list(self.recover.items()): 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 # 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.opening.add(base)
self.pending[base] = info
del self.recover[base] del self.recover[base]
self.jobs.put(("recover", base, info)) self.jobs.put(("recover", base, info))
if s.real: if s.real:
@@ -951,11 +1088,12 @@ class CrossEngine:
# links itself); the hot links are refreshed in between by the hot watch # links itself); the hot links are refreshed in between by the hot watch
rows = self.candidates(now) rows = self.candidates(now)
self.cand, self.cand_time = {r["key"]: r for r in rows}, 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 if s.running and not real_busy: # real: the next trade only after the previous is confirmed
changed = self._entries(now, rows) or changed changed = self._entries(now, rows) or changed
if changed: if changed:
self.save() self.save(event="Арбитраж: обновление позиций и funding")
BASELINE_WAIT_S = 60.0 BASELINE_WAIT_S = 60.0
@@ -977,8 +1115,8 @@ class CrossEngine:
for r in rows: for r in rows:
self.cand[r["key"]] = r self.cand[r["key"]] = r
s = self.settings s = self.settings
if s.running and not (s.real and (self.opening or now < self.real_pause_until if s.running and not (s.real and (self.opening or self.pending or self.recover
or self.waiting_baseline(now))): or now < self.real_pause_until or self.waiting_baseline(now))):
if self._entries(now, rows): if self._entries(now, rows):
self.save() self.save()
@@ -997,10 +1135,18 @@ class CrossEngine:
if not pos.real and pos.uid in self.paper_closing: if not pos.real and pos.uid in self.paper_closing:
continue continue
l = self.links.get(pos.key) 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: if l is None:
continue continue
while pos.next_funding and now >= pos.next_funding: 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 step = l.interval_h * 3600
pos.next_funding += step pos.next_funding += step
changed = True changed = True
@@ -1043,48 +1189,85 @@ class CrossEngine:
else: else:
if self._schedule_paper_close(pos.uid, reason): if self._schedule_paper_close(pos.uid, reason):
changed = True changed = True
elif self.account_error:
return False
return changed 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.""" """Delay used only by the simulator; tests without a running loop stay synchronous."""
if self.quote_now is None: if self.quote_now is None:
return 0.0 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: def _schedule_paper_close(self, uid: int, reason: str) -> bool:
if uid in self.paper_closing: if uid in self.paper_closing:
return False return False
self.paper_closing.add(uid) self.paper_closing.add(uid)
delay = self._paper_delay() delay = self._paper_delay(closing=True)
if delay <= 0: if delay <= 0:
self._paper_close(uid, reason) return self._paper_close(uid, reason)
else: else:
timer = threading.Timer(delay, self._paper_close, args=(uid, reason)) timer = threading.Timer(delay, self._paper_close, args=(uid, reason))
timer.daemon = True timer.daemon = True
timer.start() timer.start()
return True 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: with self.lock:
self.paper_closing.discard(uid) self.paper_closing.discard(uid)
pos = next((p for p in self.positions if p.uid == uid), None) pos = next((p for p in self.positions if p.uid == uid), None)
if pos is None: if pos is None:
return return False
l = self.links.get(pos.key) l = self.links.get(pos.key)
if l is None: if l is None:
return return False
self._close(pos, l, time.time(), reason) now = time.time()
self.save() 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: with self.lock:
self.paper_opening.discard(base) 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): if any(p.base == base for p in self.positions) or self.elsewhere(base):
return return False
l = self.links.get(key) l = self.links.get(key)
if l is None or l.spot_ask <= 0 or l.fut_bid <= 0: if l is None or l.spot_ask <= 0 or l.fut_bid <= 0 or self.full(l):
return return False
now = time.time() now = time.time() if self._paper_delay() > 0 else signal_time
qty = amount / l.spot_ask qty = amount / l.spot_ask
fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \ 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 + 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, 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, 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)) 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.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: def _entries(self, now: float, rows: list[dict] | None = None) -> bool:
import basis import basis
s = self.settings 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 changed = False
busy = {p.base for p in self.positions} | self.opening | self.paper_opening busy = {p.base for p in self.positions} | self.opening | self.paper_opening
best: dict[str, dict] = {} best: dict[str, dict] = {}
@@ -1113,6 +1305,8 @@ class CrossEngine:
continue continue
if l.base in busy or now - self.last_close.get(l.base, 0.0) < s.cooldown_s: if l.base in busy or now - self.last_close.get(l.base, 0.0) < s.cooldown_s:
continue continue
if self.real_block.get(l.base, ("", 0.0))[1] > now:
continue
if self.elsewhere(l.base): if self.elsewhere(l.base):
continue # the coin is already in a trade on a spot–futures tab continue # the coin is already in a trade on a spot–futures tab
if s.real: if s.real:
@@ -1124,12 +1318,15 @@ class CrossEngine:
self.paper_opening.add(l.base) self.paper_opening.add(l.base)
delay = self._paper_delay() delay = self._paper_delay()
if delay <= 0: 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: else:
timer = threading.Timer(delay, self._paper_open, timer = threading.Timer(delay, self._paper_open,
args=(l.base, l.key, r["usual"], s.amount, now)) args=(l.base, l.key, r["usual"], s.amount, now))
timer.daemon = True timer.daemon = True
timer.start() timer.start()
changed = True
break
busy.add(l.base) busy.add(l.base)
changed = True changed = True
return changed return changed
@@ -1172,8 +1369,9 @@ class CrossEngine:
for k in fresh: for k in fresh:
self.fast_seen[k] = now self.fast_seen[k] = now
self.fast_ms = int((now - start) * 1000) self.fast_ms = int((now - start) * 1000)
self._mark_account()
if self._check_exits(now): if self._check_exits(now):
self.save() self.save(event="Арбитраж: обновление позиций и funding")
time.sleep(max(0.05, self.FAST_S - (time.time() - start))) 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 --------- # --- 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) e.hot_step(done or keys, now)
time.sleep(max(0.05, self.HOT_S - (time.time() - start))) 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) 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, 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, 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)) pos.qty * pos.spot_entry, kind=pos.kind))
self.positions.remove(pos) self.positions.remove(pos)
self.last_close[pos.base] = now 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: def close(self, uid: int | None) -> str:
with self.lock: with self.lock:
@@ -1264,18 +1466,24 @@ class CrossEngine:
l = self.links.get(pos.key) l = self.links.get(pos.key)
if l is None: if l is None:
continue continue
self._schedule_paper_close(pos.uid, "вручную") if self._schedule_paper_close(pos.uid, "вручную"):
n += 1 n += 1
self.save() elif self.account_error:
return self.account_error
if not self.save():
return self.account_error
return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "") return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "")
def reset(self) -> str: def reset(self) -> str:
with self.lock: with self.lock:
if any(p.real for p in self.positions): if any(p.real for p in self.positions):
return "есть открытые реальные позиции — сначала закройте их" return "есть открытые реальные позиции — сначала закройте их"
if self.account is not None and self.positions:
return "есть открытые бумажные позиции — сначала закройте их, затем сбросьте статистику"
self.positions, self.trades, self.last_close = [], [], {} self.positions, self.trades, self.last_close = [], [], {}
self.baseline = {"time": time.time(), "total": None, "by_ex": {}} if self.settings.real else {} 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 "статистика сброшена" return "статистика сброшена"
# --- real orders (worker thread; never under the engine lock while waiting for an exchange) ------------------ # --- 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"): elif kind in ("open", "recover"):
base = args[0].base if kind == "open" else args[0] base = args[0].base if kind == "open" else args[0]
self.opening.discard(base) self.opening.discard(base)
if self.pending.pop(base, None) is not None: 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() 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 @staticmethod
def _api_closed(error: str) -> bool: def _api_closed(error: str) -> bool:
@@ -1370,10 +1661,11 @@ class CrossEngine:
with self.lock: with self.lock:
# last check right before money is spent # last check right before money is spent
held = [x.base for x in self.positions if x.real] 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 return
self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, 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() self.save()
notional = coins * l.fut_bid notional = coins * l.fut_bid
fut_need = max(notional * self.FUT_NEED, equity_for(s.min_liq_pct, notional)) 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 «Лимитный вход: ждать, с» # 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) hold = 0.0 if s.entry_ioc else max(0.0, s.limit_hold_s)
name = "IOC-шорт" if s.entry_ioc else "лимитный шорт" name = "IOC-шорт" if s.entry_ioc else "лимитный шорт"
self._pending_update(l.base, phase="limit_submitted")
try: try:
oid = cb.fut_limit(l.fut_symbol, "sell", coins, l.fut_bid) oid = cb.fut_limit(l.fut_symbol, "sell", coins, l.fut_bid)
except (live.LiveError, AttributeError) as exc: 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}") self._journal(l.base, "open", False, f"{name} на {l.fut_ex} не выставлен: {exc}")
with self.lock: with self.lock:
self.last_close[l.base] = time.time() self.last_close[l.base] = time.time()
self._pause_if_balance(str(exc), l.fut_ex) self._pause_if_balance(str(exc), l.fut_ex)
return return
self._pending_update(l.base, order_id=oid)
st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False} st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False}
end = time.time() + hold end = time.time() + hold
while True: # one look a second: the exchange's request limit while True: # one look a second: the exchange's request limit
@@ -1432,25 +1731,19 @@ class CrossEngine:
break break
time.sleep(1.0) time.sleep(1.0)
if not st["final"]: if not st["final"]:
try: st = self._cancel_entry(l, cb, oid)
cb.fut_cancel(l.fut_symbol, oid) if st is None:
except live.LiveError: return
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
shorted, fut_price, fut_fee_usd = st["coins"], st["price"] or l.fut_bid, st["fee"] shorted, fut_price, fut_fee_usd = st["coins"], st["price"] or l.fut_bid, st["fee"]
if shorted <= 0: if shorted <= 0:
self._pending_done(l.base)
self._journal(l.base, "open", False, f"{name} на {l.fut_ex} по {l.fut_bid:.10g} не исполнился" 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} ничего не покупалось") f"{'' if s.entry_ioc else f' за {hold:g} с'} — снят, на {l.spot_ex} ничего не покупалось")
with self.lock: with self.lock:
self.last_close[l.base] = time.time() self.last_close[l.base] = time.time()
return return
else: else:
self._pending_update(l.base, phase="market_submitted")
try: try:
fut = cb.fut_order(l.fut_symbol, "sell", coins, reduce_only=False) 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 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: except live.LiveError:
held = coins # unknown: assume open — the close is reduce-only held = coins # unknown: assume open — the close is reduce-only
if held <= 0: 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}") self._journal(l.base, "open", False, f"шорт на {l.fut_ex} не открыт: {exc}")
with self.lock: with self.lock:
self.last_close[l.base] = time.time() self.last_close[l.base] = time.time()
@@ -1469,6 +1767,7 @@ class CrossEngine:
return return
shorted, fut_price = held, l.fut_bid 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 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) # 2) the hedge: the same coins on spot on A (the buy fee is taken in coins: a little more USDT)
try: try:
buy = ca.spot_buy(l.base, shorted * l.spot_ask * (1 + a_fee / 100) * 1.003) 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: except live.LiveError:
bought = 0.0 bought = 0.0
if bought <= 0: if bought <= 0:
try: if getattr(exc, "sent", False):
cb.fut_order(l.fut_symbol, "buy", shorted, reduce_only=True) self._pending_problem(l.base, f"результат покупки спота неизвестен: {exc}; требуется сверка")
text = f"шорт {shorted:g} на {l.fut_ex} открыт, но спот на {l.spot_ex} не куплен ({exc}); шорт закрыт" return
except live.LiveError as exc2: self._pending_update(l.base, phase="rollback")
text = (f"шорт {shorted:g} на {l.fut_ex} открыт, спот на {l.spot_ex} не куплен ({exc}); ШОРТ НЕ " self._rollback_entry(l, cb)
f"ЗАКРЫТ ({exc2}) — закройте вручную") if self._api_closed(str(exc)):
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
self._not_tradable(l.base, f"биржа {l.spot_ex} не даёт торговать {l.base} через API: {exc}", 86400) self._not_tradable(l.base, f"биржа {l.spot_ex} не даёт торговать {l.base} через API: {exc}", 86400)
self._pause_if_balance(str(exc), l.spot_ex) self._pause_if_balance(str(exc), l.spot_ex)
return return
buy = live.Fill(bought, l.spot_ask, bought * l.spot_ask * a_fee / 100, exc.order_id, exact=False) 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: try:
free = ca.spot_free(l.base) free = ca.spot_free(l.base)
except live.LiveError: except live.LiveError:
free = 0.0 free = 0.0
held = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100) 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: with self.lock:
step = l.interval_h * 3600 step = l.interval_h * 3600
now = time.time() now = time.time()
@@ -1511,9 +1809,18 @@ class CrossEngine:
entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], 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], 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]]) [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.next_uid += 1
self.positions.append(pos) self.positions.append(pos)
self.pending.pop(l.base, None)
self.save() 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} на " 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"{l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% (обычная {usual:+.3f}%), "
f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount) f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount)
@@ -1590,10 +1897,11 @@ class CrossEngine:
return return
with self.lock: with self.lock:
held = [x.base for x in self.positions if x.real] 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 return
self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, 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() self.save()
if s.auto_transfer: if s.auto_transfer:
try: try:
@@ -1607,10 +1915,12 @@ class CrossEngine:
return return
self._journal(l.base, "transfer", False, f"{l.spot_ex}: перевод не удался: {exc} — пробую без него") self._journal(l.base, "transfer", False, f"{l.spot_ex}: перевод не удался: {exc} — пробую без него")
# 1) sell the stock on B # 1) sell the stock on B
self._pending_update(l.base, phase="spot_submitted", stock_before=have)
try: try:
sold = cb.spot_sell(l.base, coins) sold = cb.spot_sell(l.base, coins)
except live.LiveError as exc: except live.LiveError as exc:
if not getattr(exc, "sent", False): if not getattr(exc, "sent", False):
self._pending_done(l.base)
self._journal(l.base, "open", False, f"продажа {l.base} на споте {l.fut_ex} не прошла: {exc}") self._journal(l.base, "open", False, f"продажа {l.base} на споте {l.fut_ex} не прошла: {exc}")
with self.lock: with self.lock:
self.last_close[l.base] = time.time() self.last_close[l.base] = time.time()
@@ -1626,6 +1936,8 @@ class CrossEngine:
else: else:
try: try:
cb.spot_buy(l.base, sold.coins * l.fut_ask * (1 + b_fee_pct / 100) * 1.003) 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}); запас на " text = (f"{l.base} продан на {l.fut_ex}, но на {l.spot_ex} не куплен ({exc}); запас на "
f"{l.fut_ex} выкуплен обратно") f"{l.fut_ex} выкуплен обратно")
except live.LiveError as exc2: except live.LiveError as exc2:
@@ -1651,6 +1963,7 @@ class CrossEngine:
[l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]]) [l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]])
self.next_uid += 1 self.next_uid += 1
self.positions.append(pos) self.positions.append(pos)
self.pending.pop(l.base, None)
self.save() self.save()
self._journal(l.base, "open", True, f"спот-спот: продано {sold.coins:g} на {l.fut_ex} по {sold.price:.10g}, " 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}% " 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"(+{(liq / pos.fut_entry - 1) * 100:.0f}% от входа), расчёт {pos.liq_calc:.10g} — "
f"расхождение {diff:+.1f}%") 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: 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.""" """Buy the short back on B (reduce-only), make sure B shows no short left, then sell the coins on A."""
import live import live
@@ -1691,7 +2060,7 @@ class CrossEngine:
# Refresh both executable sides immediately before the first close order. The fast watcher normally # 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. # 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. # 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: try:
l0 = self.links.get(pos.key) l0 = self.links.get(pos.key)
if l0 is not None: if l0 is not None:
@@ -1727,23 +2096,8 @@ class CrossEngine:
try: try:
ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex) ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex)
if pos.ss and pos.closing != "fut_done": 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}" stage = f"выкуп монет на споте {pos.fut_ex}"
l = self.links.get(pos.key) self._restore_stock(pos, cb)
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()
if pos.closing != "fut_done": if pos.closing != "fut_done":
fut_coins, fut_price, fee, exact = 0.0, 0.0, 0.0, True fut_coins, fut_price, fee, exact = 0.0, 0.0, 0.0, True
if pos.qty > 0: if pos.qty > 0:
@@ -1871,39 +2225,79 @@ class CrossEngine:
import live import live
with self.lock: with self.lock:
l = self.links.get(info.get("key", "")) 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: 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 return
if l.ss: # a spot sale cannot be told apart from the user's own trades: say so, no guess 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} → " self._pending_problem(base, f"незавершённый вход спот-спот {l.spot_ex} → "
f"{l.fut_ex} — проверьте {base} на обеих биржах вручную") f"{l.fut_ex} — проверьте {base} на обеих биржах вручную")
return return
try: try:
ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex)
short = max(0.0, -cb.fut_position(l.fut_symbol)) 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: except live.LiveError as exc:
with self.lock: with self.lock:
self.recover[base] = info # tried again on the next cycle self.recover[base] = info # tried again on the next cycle
self._journal(base, "open", False, f"после перезапуска: не удалось проверить незавершённый вход: {exc}") self._journal(base, "open", False, f"после перезапуска: не удалось проверить незавершённый вход: {exc}")
return return
if short <= 0 and coins * l.spot_bid < 1.0: if short <= 0 and coins * l.spot_bid < 1.0:
self._pending_done(base)
self._journal(base, "open", True, "после перезапуска: незавершённый вход — на биржах ничего не открыто") self._journal(base, "open", True, "после перезапуска: незавершённый вход — на биржах ничего не открыто")
return return
with self.lock: with self.lock:
now = time.time() now = time.time()
step = l.interval_h * 3600 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, 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), float(bought.get("price") or l.spot_ask),
0.0, (now // step + 1) * step, real=True, spot_qty=coins, exact=False, 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, innovation=l.innovation,
error="подхвачено после перезапуска — цены оценочные") error="подхвачено после перезапуска — цены оценочные")
if short <= 0 or coins * l.spot_bid < 1.0: # one leg only: close what there is at once unwind = short <= 0 or short > coins + max(1e-12, short * 1e-8)
pos.retry_at, pos.usual = 0.0, 1e9 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.next_uid += 1
self.positions.append(pos) self.positions.append(pos)
self.pending.pop(base, None)
self.recover.pop(base, None)
self.save() self.save()
self._journal(base, "open", True, f"после перезапуска: найден незавершённый вход — шорт {short:g} на " self._journal(base, "open", True, f"после перезапуска: найден незавершённый вход — шорт {short:g} на "
f"{l.fut_ex}, спот {coins:g} на {l.spot_ex}; ведётся программой") f"{l.fut_ex}, спот {coins:g} на {l.spot_ex}; ведётся программой")
if unwind:
self._real_close(pos.uid, "восстановление частичного хеджа")
# --- balances -------------------------------------------------------------------------------------------- # --- balances --------------------------------------------------------------------------------------------
def coins_value(self, exchange: str) -> float: def coins_value(self, exchange: str) -> float:
@@ -2061,11 +2455,19 @@ class CrossEngine:
"real": s.real, "exact": all(t.exact for t in closed), "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} "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), 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, "status": self.status, "ex_status": self.ex_status, "updated": self.updated,
"cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.links), "cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.links),
"memes_source": "", "rows": rows[:300], "positions": positions, "memes_source": "", "rows": rows[:300], "positions": positions,
"trades": [asdict(t) for t in reversed(closed[-200:])], "stats": stats, "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 "")} if s.real and now < self.real_pause_until else "")}
out["balances"] = self.balance_view(now) out["balances"] = self.balance_view(now)
if self.account is not None:
out["virtual_account"] = self.account.view()
return out return out
+201
View File
@@ -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()
+74
View File
@@ -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
+176
View File
@@ -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:<key>`;
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_<coin>.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.
+35 -24
View File
@@ -495,6 +495,24 @@ def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_
return windows, sorted(failed) 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]]], def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
strategies: dict[str, dict[str, float]], initial_capital: float, strategies: dict[str, dict[str, float]], initial_capital: float,
fee_pct: float = TAKER_FEE_PCT, 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 equity += unrealized - estimated_exit_fee
return equity 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: def mark_and_check_stop(symbol: str, price: float, stamp: int) -> bool:
if equity_stop["triggered"]: if equity_stop["triggered"]:
return True return True
marks[symbol] = price marks[symbol] = price
equity = equity_at() 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): 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) equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
return True 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 # Add the precise capital-floor crossing as an event so a later rebound
# inside the same candle cannot hide a drawdown breach. # inside the same candle cannot hide a drawdown breach.
if min_equity_pct > 0 and end < current: if min_equity_pct > 0 and end < current:
current_equity = equity_at(symbol, current) stop_level = _equity_floor_crossing(
end_equity = equity_at(symbol, end) current, end, equity_at(symbol, current), equity_at(symbol, end), equity_floor,
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)
) )
if stop_level is not None:
candidates.append((stop_level, "EQUITY_STOP")) candidates.append((stop_level, "EQUITY_STOP"))
_tp, stop_level, liq_level = exit_levels(symbol, pos) _tp, stop_level, liq_level = exit_levels(symbol, pos)
if stop_level is not None and end <= stop_level < current: 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: def iso(stamp: int) -> str:
return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat() 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 equity = cash
for position_symbol, pos in positions.items(): 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) equity += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty)
- mark * pos.qty * fee_pct / 100) - mark * pos.qty * fee_pct / 100)
return equity return equity
@@ -1131,13 +1139,7 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
return True return True
marks[symbol] = price marks[symbol] = price
equity = equity_at() equity = equity_at()
if equity > risk["peak"]: _track_risk(risk, equity)
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)
if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12): 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) equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
return True return True
@@ -1296,6 +1298,12 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
return return
liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side) liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side)
candidates = [] 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) lo, hi = min(start, end), max(start, end)
if lo <= pos.stop <= hi: if lo <= pos.stop <= hi:
candidates.append((pos.stop, "STOP")) 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. # The first level crossed on the way from ``start`` is the nearest one.
level, event = min(candidates, key=lambda item: abs(item[0] - start)) level, event = min(candidates, key=lambda item: abs(item[0] - start))
marks[symbol] = level marks[symbol] = level
if event == "EQUITY_STOP":
mark_and_check_stop(symbol, level, stamp)
return
if event == "LIQ": if event == "LIQ":
close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True) close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True)
else: else:
+9
View File
@@ -0,0 +1,9 @@
[
{
"lead_market": "raydium",
"lead_ticker": "CLAUDIAUSDTM",
"lead_pool": "Fe7bpDYCs74GqiCUF14HwgUMToPKV1d9mDYVX5BTohFr",
"follow_exchange": "mexc",
"follow_ticker": "CLAUDIA_USDT"
}
]
+6 -1
View File
@@ -167,8 +167,13 @@ def _http(method: str, url: str, headers: dict | None = None, body: bytes | None
else: else:
_give_back(parts.scheme, parts.netloc, conn) _give_back(parts.scheme, parts.netloc, conn)
if resp.status >= 400: if resp.status >= 400:
raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}") 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"{}") return json.loads(data or b"{}")
except (ValueError, UnicodeDecodeError) as exc:
raise LiveError(f"не удалось прочитать ответ биржи: {exc}",
sent=method in ("POST", "DELETE")) from None
raise LiveError("нет связи") raise LiveError("нет связи")
+8 -271
View File
@@ -12,7 +12,6 @@ import urllib.parse
import urllib.request import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import deque from collections import deque
from dataclasses import dataclass, field
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
import tkinter as tk 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, from historical_backtest import (fetch_funding_history, fetch_klines, prepare_universe, run_backtest,
run_mode_backtest, save_report) run_mode_backtest, save_report)
import strategy import strategy
from desktop_models import Position, ClosedTrade, CurrencyState
from desktop_chart import ChartView
from persistence import atomic_write_json
try: try:
import websocket import websocket
@@ -59,75 +61,7 @@ MAX_EVENTS_PER_POLL = 2000
MANUAL_CLOSE_CONFIRM_SECONDS = 15 MANUAL_CLOSE_CONFIRM_SECONDS = 15
@dataclass class PaperSimulator(ChartView):
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:
def __init__(self, root: tk.Tk) -> None: def __init__(self, root: tk.Tk) -> None:
self.root = root self.root = root
self.root.title("Bybit — симулятор сделок в реальном времени") self.root.title("Bybit — симулятор сделок в реальном времени")
@@ -2134,10 +2068,8 @@ class PaperSimulator:
"live_initial_deposits": self.live_initial_deposits, "live_initial_deposits": self.live_initial_deposits,
} }
try: try:
temp_path = STATE_FILE.with_suffix(".json.tmp") atomic_write_json(STATE_FILE, state)
temp_path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8") except (OSError, ValueError) as exc:
os.replace(temp_path, STATE_FILE)
except OSError as exc:
if hasattr(self, "status_var"): if hasattr(self, "status_var"):
self.status_var.set(f"Не удалось сохранить историю счёта: {exc}") self.status_var.set(f"Не удалось сохранить историю счёта: {exc}")
@@ -2154,10 +2086,8 @@ class PaperSimulator:
def _save_settings(self) -> None: def _save_settings(self) -> None:
self._settings_save_job = None self._settings_save_job = None
try: try:
temp_path = SETTINGS_FILE.with_suffix(".json.tmp") atomic_write_json(SETTINGS_FILE, self._settings_payload())
temp_path.write_text(json.dumps(self._settings_payload(), ensure_ascii=False, indent=2), encoding="utf-8") except (OSError, ValueError) as exc:
os.replace(temp_path, SETTINGS_FILE)
except OSError as exc:
self.status_var.set(f"Не удалось сохранить настройки: {exc}") self.status_var.set(f"Не удалось сохранить настройки: {exc}")
@staticmethod @staticmethod
@@ -4513,199 +4443,6 @@ class PaperSimulator:
return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}" return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}"
return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}" 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: def _update_candle(self, timestamp: float, price: float) -> None:
interval_seconds = self.interval_minutes * 60 interval_seconds = self.interval_minutes * 60
candle_start = int(timestamp // interval_seconds) * interval_seconds candle_start = int(timestamp // interval_seconds) * interval_seconds
+72
View File
@@ -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)
+45
View File
@@ -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
+27
View File
@@ -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
+114 -25
View File
@@ -8,14 +8,15 @@ whose real order did not go through is closed at once, so paper and real trades
Results (prices, fees) are the exchange's own fills; `exact` is False where the exchange did not report a figure. 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 - 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; always closed with its paper twin;
- real positions are saved (web_sim_data/real_positions_<coin>.json); paper positions do not survive a restart, so - real positions are saved (web_sim_data/real_positions_<coin>.json); a saved real position is conservatively
a saved real position is closed right after a restart («осиротевшая»); 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). - every order and every error goes to web_sim_data/real_orders.jsonl (journal on the page).
""" """
from __future__ import annotations from __future__ import annotations
import json import json
from persistence import atomic_write_json
import queue import queue
import threading import threading
import time import time
@@ -107,7 +108,7 @@ def save_settings(values: dict) -> str:
if values.get("reset_stats"): if values.get("reset_stats"):
c["since"] = time.time() c["since"] = time.time()
DATA_DIR.mkdir(exist_ok=True) DATA_DIR.mkdir(exist_ok=True)
SETTINGS_FILE.write_text(json.dumps(s), encoding="utf-8") atomic_write_json(SETTINGS_FILE, s)
return "" return ""
@@ -191,6 +192,7 @@ class FuturesMirror:
self.position: dict | None = None # the one real position (opening / open / closing) self.position: dict | None = None # the one real position (opening / open / closing)
self.trades: list[dict] = [] self.trades: list[dict] = []
self.state = "" # "" idle · "opening" · "open" · "closing" · "check" (verify zero) self.state = "" # "" idle · "opening" · "open" · "closing" · "check" (verify zero)
self.storage_error = ""
self.problem = "" # last error that keeps the coin blocked 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.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) 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: def _load(self) -> None:
try: try:
d = json.loads(self.file.read_text(encoding="utf-8")) 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 return
self.trades = d.get("trades", [])[-500:] self.trades = d.get("trades", [])[-500:]
pos = d.get("position") pos = d.get("position")
if pos: if pos:
# paper positions do not survive a restart: the saved real one is closed at once
pos["uid"] = None pos["uid"] = None
self.position, self.state = pos, "closing" 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", "осиротевшая после перезапуска")) self.jobs.put(("close", "осиротевшая после перезапуска"))
def _save(self) -> None: def _save(self) -> None:
try: try:
self.file.parent.mkdir(exist_ok=True) atomic_write_json(self.file, {"version": 2, "state": self.state,
pos = self.position if self.state in ("open", "closing", "check") else None "position": self.position, "trades": self.trades[-500:]})
self.file.write_text(json.dumps({"position": pos, "trades": self.trades[-500:]}, ensure_ascii=False), except (OSError, ValueError) as exc:
encoding="utf-8") self.storage_error = f"не сохранено состояние ордеров: {exc}"
except OSError: raise
pass 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 ---------------------------------------------------------------------------------- # --- the simulator's side ----------------------------------------------------------------------------------
def coin_settings(self) -> dict: def coin_settings(self) -> dict:
@@ -238,6 +283,8 @@ class FuturesMirror:
if not self.enabled(): if not self.enabled():
return "" return ""
with self.lock: with self.lock:
if self.storage_error:
return self.storage_error
left = self.paused_until - time.time() left = self.paused_until - time.time()
if self.state == "" and left > 0: if self.state == "" and left > 0:
# the exchange refused the last entry: no new trade (paper or real) until the pause ends # 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.""" """Paper events, called under the engine's lock: only queue work here."""
with self.lock: with self.lock:
if event == "open": 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) return # real mode off, or a real trade still runs (gate was bypassed)
self.state = "opening" self.state = "opening"
units = symbol_units(self.symbol) 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 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 # 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, "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)) self.jobs.put(("open", None))
elif event == "close" and self.position and self.position.get("uid") == pos.uid: elif event == "close" and self.position and self.position.get("uid") == pos.uid:
self.jobs.put(("close", "закрыта в симуляторе")) 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 ------------------------------------------------------------------------------------------------ # --- worker ------------------------------------------------------------------------------------------------
WATCH_S = 1.0 # while a real position is open: how often to ask the exchange whether TP/SL closed it 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() self._open()
elif kind == "close": elif kind == "close":
self._close(arg) self._close(arg)
elif kind == "recover":
self._recover_open()
elif kind == "watch": elif kind == "watch":
self._watch() self._watch()
except Exception as exc: # never let the worker die except Exception as exc: # never let the worker die
with self.lock: with self.lock:
self.problem = f"сбой: {exc}" self.problem = f"сбой: {exc}"
if kind == "open" and self.position:
self.state = "recover"
journal("simulator", self.exchange, self.coin, kind, False, f"сбой: {exc}") journal("simulator", self.exchange, self.coin, kind, False, f"сбой: {exc}")
if kind == "close": if kind == "close":
self._retry_close(arg) self._retry_close(arg)
@@ -331,6 +397,12 @@ class FuturesMirror:
def _watch(self) -> None: def _watch(self) -> None:
"""An open real position may be closed by the exchange itself (its TP / SL): then record it now. """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.""" 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 if (self.state in ("", "open") and time.time() - self.last_sync >= self.SYNC_S
and (self.enabled() or self.exchange_trades is None)): and (self.enabled() or self.exchange_trades is None)):
self.sync() self.sync()
@@ -359,6 +431,15 @@ class FuturesMirror:
def _open(self) -> None: def _open(self) -> None:
pos = self.position 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" side = "buy" if pos["side"] == "LONG" else "sell"
sign = 1 if side == "buy" else -1 sign = 1 if side == "buy" else -1
c = None c = None
@@ -374,23 +455,27 @@ class FuturesMirror:
else: else:
fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False) fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False)
except live.LiveError as exc: except live.LiveError as exc:
if getattr(exc, "sent", False) and c is not None: if getattr(exc, "sent", False):
# accepted, fill not confirmed: the exchange's position decides with self.lock:
pos["order_in"] = exc.order_id
self.state, self.problem = "recover", str(exc)
self._save()
try: try:
held = abs(c.fut_position(self.symbol)) held = c.fut_position(self.symbol)
except live.LiveError: 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 return
if held * sign <= self.VERIFY_TOLERANCE:
return
fill = live.Fill(abs(held), pos["paper_entry"], 0.0, exc.order_id, exact=False)
else: else:
self._top_up_futures(c, str(exc), pos["coins"] * pos["paper_entry"]) self._top_up_futures(c, str(exc), pos["coins"] * pos["paper_entry"])
self._failed_open(str(exc)) self._failed_open(str(exc))
return 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) # 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 fee_pct = fill.fee_usd / (fill.coins * fill.price) * 100 if fill.exact and fill.coins and fill.price else None
if fee_pct: if fee_pct:
@@ -478,6 +563,10 @@ class FuturesMirror:
self.on_failed_open(uid) self.on_failed_open(uid)
def _close(self, reason: str) -> None: 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: with self.lock:
pos = self.position pos = self.position
if pos is None or self.state == "": 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)] t for t in self.trades if t.get("closed", 0) >= (self.coin_settings().get("since") or 0)]
stats = trade_stats(trades) stats = trade_stats(trades)
pos = dict(self.position) if self.position and self.state else None 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(), **stats, "positions": [pos] if pos else [], "enabled": self.enabled(),
"source": "биржа" if self.exchange_trades is not None else "программа", "source": "биржа" if self.exchange_trades is not None else "программа",
"synced": self.synced, "sync_error": self.sync_error, "since": self.coin_settings().get("since"), "synced": self.synced, "sync_error": self.sync_error, "since": self.coin_settings().get("since"),
+43
View File
@@ -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"
+3 -2
View File
@@ -1,2 +1,3 @@
websocket-client>=1.8,<2 # Python 3.11+
numpy>=1.26 websocket-client==1.8.0
numpy==2.3.5
+3 -7
View File
@@ -1,9 +1,5 @@
@echo off @echo off
rem Web simulator in two parts: rem Validate/repair the environment, then start the local proxy and engine.
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)
cd /d "%~dp0" cd /d "%~dp0"
start "web_proxy" pyw -3 web_proxy.py powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0server_control.ps1" start
start "" http://127.0.0.1:8765 if errorlevel 1 pause
py -3 web_sim.py --backend
pause
+45
View File
@@ -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
+226 -33
View File
@@ -26,11 +26,12 @@ import statistics
import sys import sys
import time import time
from collections import deque from collections import deque
from dataclasses import dataclass, field from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
import scalp_hint as sh import scalp_hint as sh
from persistence import atomic_write_json
ROOT = Path(__file__).resolve().parent ROOT = Path(__file__).resolve().parent
STATE_FILE = ROOT / "scalp_paper_state.json" STATE_FILE = ROOT / "scalp_paper_state.json"
@@ -53,6 +54,8 @@ MODES = {"simple": "Простая (вход по рынку, выход при
@dataclass @dataclass
class PaperSettings: class PaperSettings:
simulation_entry_delay_ms: float = 600.0
simulation_exit_delay_ms: float = 600.0
enabled: bool = True enabled: bool = True
mode: str = "adaptive" mode: str = "adaptive"
data_source: str = "metascalp" # "metascalp" or "bybit" (direct public WebSocket, Bybit pairs only) data_source: str = "metascalp" # "metascalp" or "bybit" (direct public WebSocket, Bybit pairs only)
@@ -137,6 +140,7 @@ class Position:
regime: str = "" regime: str = ""
features: dict = field(default_factory=dict) features: dict = field(default_factory=dict)
uid: int = 0 # unique per ledger, so one of several open positions can be closed by hand 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 @dataclass
@@ -178,20 +182,59 @@ class Ledger:
self.balance = settings.budget self.balance = settings.budget
self.positions: list[Position] = [] self.positions: list[Position] = []
self.trades: list[PaperTrade] = [] 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.hooks: list = [] # hook(event, pos): "open" / "close" — real trading mirrors the paper positions
self._load() self._load()
def _load(self) -> None: def _load(self) -> None:
snapshot_trades = False
if self.state_path: if self.state_path:
try: try:
state = json.loads(self.state_path.read_text(encoding="utf-8")) 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(): for key, value in state.get("settings", {}).items():
if hasattr(self.settings, key): if hasattr(settings, key):
setattr(self.settings, key, type(getattr(self.settings, key))(value)) setattr(settings, key, type(getattr(settings, key))(value))
except (OSError, ValueError, TypeError): 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 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] = [] header: list[str] = []
try: try:
with self.trades_path.open(encoding="utf-8-sig") as file: with self.trades_path.open(encoding="utf-8-sig") as file:
@@ -220,38 +263,109 @@ class Ledger:
except OSError: except OSError:
pass pass
def save(self) -> None: def snapshot(self) -> dict:
if self.state_path: state = self.state_provider() if self.state_provider else self.policy_state
try: return {"version": 2, "balance": self.balance, "settings": vars(self.settings).copy(),
self.state_path.write_text(json.dumps({"balance": self.balance, "settings": vars(self.settings)}, "positions": [asdict(pos) for pos in self.positions], "next_uid": self._uid,
ensure_ascii=False, indent=2), encoding="utf-8") "policy_state": state, "account_origin": self.account_origin,
except OSError: "position_marks": dict(self._position_marks), "unrealized": self._unrealized,
pass "trades": [asdict(trade) for trade in self.trades]}
def reset(self) -> None: @property
for pos in list(self.positions): # positions dropped by a reset are closed for real too def available(self) -> float:
for hook in self.hooks: """Free common collateral when bound; retain standalone balance semantics otherwise."""
hook("close", pos) 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.balance = self.settings.budget
self.position = None self.position = None
self.trades = [] 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: if self.trades_path:
try: try:
self.trades_path.unlink() self.trades_path.unlink()
except OSError: except OSError:
pass pass
self.save() return True
def open(self, ticker: str, side: str, price: float, now: float, fee_pct: float, target: float, 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: stop: float | None, entry_mid: float, regime: str = "", features: dict | None = None,
notional = self.settings.stake * self.settings.leverage 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 qty = notional / price
fee = notional * fee_pct / 100 fee = notional * fee_pct / 100
old_balance, old_uid = self.balance, self._uid
self.balance -= fee self.balance -= fee
self._uid = getattr(self, "_uid", 0) + 1 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.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: for hook in self.hooks:
hook("open", pos) hook("open", pos)
return pos return pos
@@ -266,12 +380,15 @@ class Ledger:
self.positions = [] if value is None else [value] self.positions = [] if value is None else [value]
def close(self, price: float, now: float, reason: str, fee_pct: float, utc: str | None = None, 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 pos = pos or self.position
assert pos is not None assert pos is not None
old_balance, old_unrealized = self.balance, self._unrealized
index = self.positions.index(pos)
self.positions.remove(pos) self.positions.remove(pos)
for hook in self.hooks: # The next quote will remark any remaining positions; do not retain a closed position's P&L.
hook("close", pos) previous_mark = self._position_marks.pop(pos.uid, 0.0)
self._unrealized -= previous_mark
sign = 1 if pos.side == "LONG" else -1 sign = 1 if pos.side == "LONG" else -1
gross = sign * (price - pos.entry) * pos.qty gross = sign * (price - pos.entry) * pos.qty
fee_out = price * pos.qty * fee_pct / 100 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, 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) reason, max(0.0, now - pos.opened), pos.regime)
self.trades.append(trade) 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: if self.trades_path:
new_file = not self.trades_path.exists() new_file = not self.trades_path.exists()
try: try:
@@ -294,7 +419,6 @@ class Ledger:
trade.reason, f"{trade.hold_seconds:.1f}", trade.regime]) trade.reason, f"{trade.hold_seconds:.1f}", trade.regime])
except OSError: except OSError:
pass pass
self.save()
return trade return trade
@@ -337,7 +461,7 @@ class SimplePolicy:
trader.message = (f"Сигнал {hint.side}, но до цели {target_pct:.2f}% < {self.s.min_target_pct:g}% — " trader.message = (f"Сигнал {hint.side}, но до цели {target_pct:.2f}% < {self.s.min_target_pct:g}% — "
"сделка не открыта") "сделка не открыта")
return return
if led.balance < self.s.stake: if led.available < self.s.stake:
trader.message = "Баланс меньше ставки — сделки остановлены" trader.message = "Баланс меньше ставки — сделки остановлены"
return return
led.open(ticker, hint.side, entry, now, TAKER, hint.target, None, mid) led.open(ticker, hint.side, entry, now, TAKER, hint.target, None, mid)
@@ -426,7 +550,7 @@ class AdaptivePolicy:
trader.message = f"Лимитка {order.side} снята: перевес сменился" trader.message = f"Лимитка {order.side} снята: перевес сменился"
return return
if (not self.s.enabled or now < self.pause_until or now - trader.last_close < self.s.cooldown_seconds 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 return
spread = best_ask - best_bid spread = best_ask - best_bid
min_risk = max(self.s.noise_mult * state["noise"], 2 * spread, mid * 0.001, 2 * tick) 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 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: if not self.s.enabled or self.book is None or self.hint is None or trader.ledger.position is not None:
return return
if trader.ledger.balance < self.s.stake: if trader.ledger.available < self.s.stake:
self.status = "Баланс меньше ставки — сделки остановлены" self.status = "Баланс меньше ставки — сделки остановлены"
return return
best_bid, best_ask = self.book.best() 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, self.order = Order(ticker, self.order.side, touch, self._target(touch, direction, tick), 0.0, now,
"суммы", {}) # follow the best price "суммы", {}) # follow the best price
return 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 return
price = best_bid if signal > 0 else best_ask 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, 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} мс)" reason = f"данные устарели ({stale:.0f} мс)"
elif (now - trader.last_close) * 1000 < self.s.cooldown_ms and not self.skip_pause: 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} мс" 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 = "баланса не хватает ещё на одну ставку" reason = "баланса не хватает ещё на одну ставку"
elif direction == 0: elif direction == 0:
reason = wait reason = wait
@@ -1160,6 +1284,45 @@ class PaperTrader:
import algo_hunter import algo_hunter
self.algo_config = algo_hunter.AlgoHunterConfig.load() if state_path else algo_hunter.AlgoHunterConfig() self.algo_config = algo_hunter.AlgoHunterConfig.load() if state_path else algo_hunter.AlgoHunterConfig()
self.policy = self._make_policy() 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): def _make_policy(self):
if self.settings.mode == "adaptive": if self.settings.mode == "adaptive":
@@ -1194,6 +1357,8 @@ class PaperTrader:
handler = getattr(self.policy, "on_book", None) handler = getattr(self.policy, "on_book", None)
if handler is not None: if handler is not None:
handler(self, now, book, tick) handler(self, now, book, tick)
self.mark_account(book)
self._checkpoint(now)
def on_leader(self, now: float, bid: float, ask: float) -> None: def on_leader(self, now: float, bid: float, ask: float) -> None:
"""Best quotes of the leader exchange (lead mode only).""" """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: 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.policy.on_tick(self, now, ticker, hint, book, tick)
self._checkpoint(now)
def on_trade(self, trade: sh.Trade) -> None: 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) 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, def close(self, price: float, now: float, reason: str, fee_pct: float, utc: str | None = None,
pos: Position | None = None) -> None: pos: Position | None = None) -> None:
target = pos or self.ledger.position target = pos or self.ledger.position
features = target.features if target else {} features = target.features if target else {}
trade = self.ledger.close(price, now, reason, fee_pct, utc, pos) 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.last_close = now
self.message = f"Закрыта {trade.side} {trade.ticker}: {reason}, итог {trade.net_usd:+.4f}$" self.message = f"Закрыта {trade.side} {trade.ticker}: {reason}, итог {trade.net_usd:+.4f}$"
if isinstance(self.policy, AdaptivePolicy): if isinstance(self.policy, AdaptivePolicy):
self.policy.on_close(trade, features, now) self.policy.on_close(trade, features, now)
self.ledger.save()
def close_now(self, book: sh.OrderBook, now: float, reason: str) -> None: def close_now(self, book: sh.OrderBook, now: float, reason: str) -> None:
if hasattr(self.policy, "order"): if hasattr(self.policy, "order"):
@@ -1241,9 +1415,12 @@ class PaperTrader:
self.close(price, now, reason, TAKER, pos=pos) self.close(price, now, reason, TAKER, pos=pos)
def reset(self) -> None: 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.policy = self._make_policy()
self.hint_settings.weights = dict(sh.DEFAULT_WEIGHTS) self.hint_settings.weights = dict(sh.DEFAULT_WEIGHTS)
self.ledger.save()
def unrealized(self, book: sh.OrderBook) -> float: def unrealized(self, book: sh.OrderBook) -> float:
best_bid, best_ask = book.best() best_bid, best_ask = book.best()
@@ -1251,9 +1428,25 @@ class PaperTrader:
for pos in self.ledger.positions: for pos in self.ledger.positions:
price = best_bid if pos.side == "LONG" else best_ask price = best_bid if pos.side == "LONG" else best_ask
if price is not None: 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 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: def summary(self) -> str:
trades = self.ledger.trades trades = self.ledger.trades
n = len(trades) n = len(trades)
+34
View File
@@ -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())
+11 -5
View File
@@ -64,15 +64,21 @@ if ((Server-Processes) -and (Answers)) {
Start-Process $Url Start-Process $Url
exit 0 exit 0
} }
$haveVenv = Test-Path (Join-Path $Dir ".venv\Scripts\pythonw.exe") $VenvPython = Join-Path $Dir ".venv\Scripts\python.exe"
$havePy = [bool](Get-Command py -ErrorAction SilentlyContinue) $haveVenv = $false
if (-not $haveVenv -and -not $havePy) { if (Test-Path -LiteralPath $VenvPython) {
Write-Host "Python и библиотеки ещё не установлены — устанавливаю..." 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 & powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Dir "setup.ps1") /install-only
if ($LASTEXITCODE -ne 0) { exit 1 } if ($LASTEXITCODE -ne 0) { exit 1 }
} }
Write-Host "Запускаю сервер в фоне (без окон)..." 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 Set-Watchdog $true
foreach ($i in 1..45) { foreach ($i in 1..45) {
if (Answers) { if (Answers) {
+10 -4
View File
@@ -15,8 +15,11 @@ $VenvPyw = Join-Path $Dir ".venv\Scripts\pythonw.exe"
function Find-Python { function Find-Python {
foreach ($v in "3.13", "3.12", "3.11", "3.10") { foreach ($v in "3.13", "3.12", "3.11", "3.10") {
try { try {
$exe = & py "-$v" -c "import sys; print(sys.executable)" 2>$null $exe = & py "-$v" -c "import sys, json; print(json.dumps(sys.executable, ensure_ascii=True))" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() } if ($LASTEXITCODE -eq 0 -and $exe) {
$path = $exe | ConvertFrom-Json
if (Test-Path -LiteralPath $path -PathType Leaf) { return $path }
}
} catch {} } catch {}
} }
foreach ($d in "Python313", "Python312", "Python311", "Python310") { foreach ($d in "Python313", "Python312", "Python311", "Python310") {
@@ -24,8 +27,11 @@ function Find-Python {
if (Test-Path $p) { return $p } if (Test-Path $p) { return $p }
} }
try { try {
$exe = & python -c "import sys; assert sys.version_info >= (3, 10); print(sys.executable)" 2>$null $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) { return $exe.Trim() } if ($LASTEXITCODE -eq 0 -and $exe) {
$path = $exe | ConvertFrom-Json
if (Test-Path -LiteralPath $path -PathType Leaf) { return $path }
}
} catch {} } catch {}
return $null return $null
} }
+83
View File
@@ -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()
+42
View File
@@ -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) 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__": if __name__ == "__main__":
unittest.main() unittest.main()
+7 -2
View File
@@ -56,16 +56,21 @@ class SimulatorRemoveTests(unittest.TestCase):
engine = mock.Mock(conn={"x": 1}, lock=threading.RLock()) engine = mock.Mock(conn={"x": 1}, lock=threading.RLock())
engine.name = "TRUMP: test" engine.name = "TRUMP: test"
engine.paper.ledger.positions = [object(), object()] 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") engine.shutdown.side_effect = lambda: calls.append("shutdown")
sim = ws.Simulator.__new__(ws.Simulator) sim = ws.Simulator.__new__(ws.Simulator)
sim.engines, sim.lock = {"k": engine}, threading.Lock() sim.engines, sim.lock = {"k": engine}, threading.Lock()
sim.removals = mock.Mock()
with mock.patch.object(ws.lw, "remove_connection") as removed: with mock.patch.object(ws.lw, "remove_connection") as removed:
message = sim.remove("k") message = sim.remove("k")
removed.assert_called_once_with({"x": 1}) removed.assert_called_once_with({"x": 1})
self.assertEqual(calls, [("close", None), "shutdown"]) self.assertEqual(calls, [("close", None), "shutdown"])
self.assertNotIn("k", sim.engines) self.assertNotIn("k", sim.engines)
self.assertFalse(engine.paper.settings.enabled) engine.set_trading.assert_called_once_with(False)
self.assertIn("закрыто позиций: 2", message) self.assertIn("закрыто позиций: 2", message)
self.assertEqual(sim.remove("k"), "нет такой монеты") self.assertEqual(sim.remove("k"), "нет такой монеты")
+217
View File
@@ -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()
+203
View File
@@ -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()
+95
View File
@@ -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)
+30
View File
@@ -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)
+96
View File
@@ -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, [])
+54
View File
@@ -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, [])
+224
View File
@@ -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()
+29
View File
@@ -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})
+81
View File
@@ -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()
+83
View File
@@ -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)
+173
View File
@@ -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()
+445
View File
@@ -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()
+1 -1
View File
@@ -53,7 +53,7 @@ class ProxyTests(unittest.TestCase):
got = json.loads(urllib.request.urlopen(base + "/api/state?x=1").read()) got = json.loads(urllib.request.urlopen(base + "/api/state?x=1").read())
self.assertEqual(got, {"method": "GET", "path": "/api/state?x=1"}) 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(), 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()) got = json.loads(urllib.request.urlopen(req).read())
self.assertEqual(got["body"], {"a": 1}) self.assertEqual(got["body"], {"a": 1})
finally: finally:
+7
View File
@@ -37,6 +37,9 @@ class _NoReal:
def reset_stats(self): def reset_stats(self):
pass pass
def ready_to_remove(self):
return True
def view(self): def view(self):
return {"open": 0, "trades": 0, "net": 0.0, "wins": 0, "positions": [], "state": "", "problem": "", return {"open": 0, "trades": 0, "net": 0.0, "wins": 0, "positions": [], "state": "", "problem": "",
"enabled": False, "trade_list": []} "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.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) 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.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() e.reset()
self.assertEqual((e.paper.trades, e.paper.ledger.positions), ([], [])) self.assertEqual((e.paper.trades, e.paper.ledger.positions), ([], []))
self.assertEqual(e.paper.ledger.balance, 1000.0) self.assertEqual(e.paper.ledger.balance, 1000.0)
@@ -167,6 +173,7 @@ class WebSimTests(unittest.TestCase):
def test_trading_pairs_are_listed_first(self): def test_trading_pairs_are_listed_first(self):
sim = ws.Simulator.__new__(ws.Simulator) sim = ws.Simulator.__new__(ws.Simulator)
sim.lock = threading.Lock()
sim.common = ws.load_common() sim.common = ws.load_common()
a = ws.Engine(dict(CONN, follow_ticker="AAA_USDT"), sim.common) a = ws.Engine(dict(CONN, follow_ticker="AAA_USDT"), sim.common)
z = ws.Engine(dict(CONN, follow_ticker="ZZZ_USDT"), sim.common) z = ws.Engine(dict(CONN, follow_ticker="ZZZ_USDT"), sim.common)
+320
View File
@@ -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);
});
+245
View File
@@ -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()
+179
View File
@@ -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; } }
+1499
View File
File diff suppressed because it is too large. Load diff
+148
View File
@@ -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 минут меняют только окно графика. Время на странице — московское (МСК)."]
];
+78
View File
@@ -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 <dialog> 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();
});
}
+4 -1
View File
@@ -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 from __future__ import annotations
import sys import sys
from request_security import trusted_request
import urllib.error import urllib.error
import urllib.request import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -26,12 +27,14 @@ class Proxy(BaseHTTPRequestHandler):
pass pass
def _forward(self, method: str) -> None: 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") self.send_error(403, "only from this computer")
return return
length = int(self.headers.get("Content-Length") or 0) length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else None 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} 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) req = urllib.request.Request(ENGINE + self.path, data=body, method=method, headers=headers)
try: try:
with urllib.request.urlopen(req, timeout=30) as resp: with urllib.request.urlopen(req, timeout=30) as resp:
+37 -1325
View File
File diff suppressed because it is too large. Load diff
+280 -46
View File
@@ -4,10 +4,11 @@
* Common trade settings at the top apply to every coin (web_sim_data/settings.json). * 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 = * 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/<coin>.json/.csv) Bybit/Binance/MEXC futures) has its own feeds and journal (web_sim_data/<coin>.json/.csv)
and its own Start/Stop. Stop only forbids new entries: prices, the comparison and the forecast learning go on. 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. * 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 from __future__ import annotations
@@ -24,6 +25,11 @@ from dataclasses import fields
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path 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 keystore
import lead_window as lw import lead_window as lw
import live import live
@@ -111,6 +117,12 @@ def scanner_add(symbol: str, connections: list[dict]) -> tuple[dict | None, str]
DATA_DIR = ROOT / "web_sim_data" DATA_DIR = ROOT / "web_sim_data"
SETTINGS_FILE = DATA_DIR / "settings.json" SETTINGS_FILE = DATA_DIR / "settings.json"
PAGE = ROOT / "web_sim.html" 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 PORT = 8765
CONNECTION_FIELDS = set(lw.CONNECTION_KEYS) CONNECTION_FIELDS = set(lw.CONNECTION_KEYS)
COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings) 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", "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", "auto_tp_horizon_seconds", "one_per_tick", "cut_loss", "cut_loss_ticks",
"max_data_age_ms", "require_leader", "leader_min_edge", "auto_stop_pct", "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"}] "basis_entry_z", "basis_exit_z", "basis_min_gap_pct"}]
SERIES_STEP = 0.5 # chart sampling, s SERIES_STEP = 0.5 # chart sampling, s
SERIES_KEEP = 1200 # 10 minutes 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: def coin_key(conn: dict) -> str:
@@ -185,6 +207,15 @@ def load_common() -> dict:
def check_common(values: dict) -> tuple[dict, str]: def check_common(values: dict) -> tuple[dict, str]:
"""Cast and validate settings coming from the page.""" """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 = {} out = {}
defaults = sp.PaperSettings() defaults = sp.PaperSettings()
for k in COMMON_FIELDS: for k in COMMON_FIELDS:
@@ -216,16 +247,21 @@ def check_common(values: dict) -> tuple[dict, str]:
class Engine: class Engine:
"""One coin: leader + follower feeds, a paper trader and a price history for the chart.""" """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.conn = dict(conn)
self.key = coin_key(conn) self.key = coin_key(conn)
self.symbol = coin_symbol(conn) self.symbol = coin_symbol(conn)
self.name = lw.connection_name(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) DATA_DIR.mkdir(exist_ok=True)
settings = sp.PaperSettings(mode=common.get("mode", "lead"), enabled=False) 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() 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 enabled = self.paper.settings.enabled # the coin's own Start/Stop survives restarts
self.apply(common, initial=True) self.apply(common, initial=True)
self.paper.settings.enabled = enabled self.paper.settings.enabled = enabled
@@ -234,11 +270,21 @@ class Engine:
for k in CONNECTION_FIELDS: for k in CONNECTION_FIELDS:
setattr(self.paper.settings, k, conn[k]) setattr(self.paper.settings, k, conn[k])
self.paper.policy = self.paper._make_policy() 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 # real trading: the same orders on the coin's futures exchange while the tab's real mode is on
ps = self.paper.settings ps = self.paper.settings
self.mirror = real_mirror.FuturesMirror(self.key, self.symbol, ps.follow_exchange, ps.follow_ticker) self.mirror = real_mirror.FuturesMirror(self.key, self.symbol, ps.follow_exchange, ps.follow_ticker)
self.paper.ledger.hooks.append(self.mirror.hook) self._connect_trader()
self.paper.gate = self.mirror.gate # one real trade at a time, confirmed closed
self.mirror.on_failed_open = lambda uid: self.close(uid, "реальный ордер не прошёл") 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.mirror.ping = lambda ex=ps.follow_exchange: ping_for(ex) # no entry while the ping is above the limit
self.lock = threading.RLock() self.lock = threading.RLock()
@@ -254,14 +300,71 @@ class Engine:
self.lead_status = "подключаюсь…" self.lead_status = "подключаюсь…"
self.follow_status = "подключаюсь…" self.follow_status = "подключаюсь…"
self.message = "" self.message = ""
self.close_error = ""
self.removing = False
self.auto_stop = "" # why the pair was stopped automatically (cleared by Start) 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.checked_at = None # time of the last leader measurement looked at
self.feeds: list = [] self.feeds: list = []
self.stopped = threading.Event() self.stopped = threading.Event()
self.thread = threading.Thread(target=self._pump, daemon=True) 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 --------------------------------------------------------------------------- # --- lifecycle ---------------------------------------------------------------------------
def start(self) -> None: def start(self) -> None:
self.execution_live = True
self._connect_trader()
ps = self.paper.settings ps = self.paper.settings
if ps.follow_exchange == "mexc": if ps.follow_exchange == "mexc":
self.tick, size = sh.mexc_contract(ps.follow_ticker) self.tick, size = sh.mexc_contract(ps.follow_ticker)
@@ -289,10 +392,16 @@ class Engine:
self.paper.ledger.save() self.paper.ledger.save()
def apply(self, common: dict, initial: bool = False) -> None: def apply(self, common: dict, initial: bool = False) -> None:
self.common.update(common)
ps = self.paper.settings ps = self.paper.settings
lock = self.lock if not initial else threading.RLock() lock = self.lock if not initial else threading.RLock()
with lock: with lock:
mode = common.get("mode", ps.mode) 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(): for k, v in common.items():
if k != "mode": if k != "mode":
setattr(ps, k, v) setattr(ps, k, v)
@@ -304,6 +413,9 @@ class Engine:
def set_trading(self, on: bool) -> None: def set_trading(self, on: bool) -> None:
with self.lock: with self.lock:
if on and self.removing:
self.message = "Подключение ожидает закрытия позиций и удаления"
return
self.paper.settings.enabled = on self.paper.settings.enabled = on
self.paper.ledger.save() self.paper.ledger.save()
if on: if on:
@@ -312,12 +424,17 @@ class Engine:
"Стоп: новые сделки не открываются; открытые закроются по тейку, стопу или времени") "Стоп: новые сделки не открываются; открытые закроются по тейку, стопу или времени")
def reset(self) -> str: def reset(self) -> str:
"""Clear this coin's statistics: open positions dropped, journal emptied, balance back to the budget. """Clear statistics only while both the paper/signal ledger and the real mirror are flat."""
Start/Stop, prices, the leader check and the forecast learning are kept."""
with self.lock: 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 enabled = self.paper.settings.enabled
self.paper.ledger.reset() # positions, trades, CSV; balance = budget if self.paper.ledger.reset() is False:
self.mirror.reset_stats() # real figures start again from now too 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.settings.enabled = enabled
self.paper.ledger.save() self.paper.ledger.save()
self.paper.message = "" self.paper.message = ""
@@ -327,14 +444,26 @@ class Engine:
def close(self, uid: int | None, reason: str = "вручную") -> str: def close(self, uid: int | None, reason: str = "вручную") -> str:
"""Close one position (uid) or all of them at the follower's current best price.""" """Close one position (uid) or all of them at the follower's current best price."""
with self.lock: with self.lock:
self.close_error = ""
best_bid, best_ask = self.book.best() best_bid, best_ask = self.book.best()
closed = 0 closed = 0
for pos in list(self.paper.ledger.positions): for pos in list(self.paper.ledger.positions):
if uid is not None and pos.uid != uid: if uid is not None and pos.uid != uid:
continue 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) self.paper.close(price, time.time(), reason, self.paper.policy.taker, pos=pos)
if pos not in self.paper.ledger.positions:
closed += 1 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}" return f"закрыто позиций: {closed}"
def _auto_stop(self, now: float) -> None: def _auto_stop(self, now: float) -> None:
@@ -413,13 +542,14 @@ class Engine:
return { return {
"key": self.key, "symbol": self.symbol, "name": self.name, "key": self.key, "symbol": self.symbol, "name": self.name,
"leader": pol.L, "follower": pol.F, "follow_ticker": self.conn["follow_ticker"], "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, "price": (bid + ask) / 2 if bid and ask else None,
"lead_price": sum(self.leader) / 2 if self.leader 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), "signal": getattr(pol, "signal", 0.0), "confidence": getattr(pol, "conf", 0.0),
"open": len(led.positions), "trades": len(trades), "wins": wins, "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), "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, "unrealized": self.paper.unrealized(self.book), "balance": led.balance,
"account_error": getattr(led, "storage_error", ""),
"leadership": getattr(pol, "leadership", {}), "leader_block": pol.leader_block() "leadership": getattr(pol, "leadership", {}), "leader_block": pol.leader_block()
if hasattr(pol, "leader_block") else "", "min_edge": self.paper.settings.leader_min_edge, if hasattr(pol, "leader_block") else "", "min_edge": self.paper.settings.leader_min_edge,
"now": now, "auto_stop": self.auto_stop, "now": now, "auto_stop": self.auto_stop,
@@ -464,62 +594,120 @@ class Engine:
class Simulator: class Simulator:
def __init__(self) -> None: def __init__(self, account: VirtualAccount | None = None, start: bool = True) -> None:
self.common = load_common() self.common = load_common()
self.account = account if account is not None else paper_account()
self.engines: dict[str, Engine] = {} self.engines: dict[str, Engine] = {}
self.lock = threading.Lock() self.lock = threading.Lock()
self.removals = PendingRemovals(DATA_DIR / "pending_removals.json")
self.error = self.removals.error
self.start_feeds = start
self.sync_connections() self.sync_connections()
if start:
threading.Thread(target=self._watch, daemon=True).start() threading.Thread(target=self._watch, daemon=True).start()
def sync_connections(self) -> None: def sync_connections(self) -> None:
"""Start an engine for every connection in the list (new ones appear; removal is only via remove()).""" """Start an engine for every connection in the list (new ones appear; removal is only via remove())."""
for conn in lw.load_connections(): pending = self.removals.connections()
key = coin_key(conn) 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: with self.lock:
if key in self.engines: if key in self.engines:
continue 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 self.engines[key] = engine
if self.start_feeds:
engine.start() engine.start()
if engine.removing:
engine.close(None)
engine.mirror.request_close()
def remove(self, key: str) -> str: 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: with self.lock:
engine = self.engines.get(key) engine = self.engines.get(key)
if engine is None: if engine is None:
return "нет такой монеты" return "нет такой монеты"
lw.remove_connection(engine.conn) try:
del self.engines[key] self.removals.schedule(key, engine.conn)
except (OSError, ValueError) as exc:
return f"Удаление не начато: {exc}"
with engine.lock: with engine.lock:
engine.paper.settings.enabled = False engine.removing = True
engine.set_trading(False)
closed = len(engine.paper.ledger.positions) closed = len(engine.paper.ledger.positions)
engine.close(None) # open positions at the current price engine.close(None) # open positions at the current price
engine.shutdown() # feeds (exchange + DEX/KuCoin) and the pump thread stop engine.mirror.request_close()
if self._finish_removal(key):
return f"{engine.name} удалена, сбор данных остановлен" + (f", закрыто позиций: {closed}" if closed else "") 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: def _watch(self) -> None:
next_sync = 0.0
while True: while True:
time.sleep(30) time.sleep(1)
try: try:
if time.time() >= next_sync:
self.sync_connections() self.sync_connections()
except Exception: next_sync = time.time() + 30
pass 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: 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) clean, problem = check_common(values)
if problem: if problem:
return problem return problem
self.common.update(clean) updated = {**self.common, **clean}
DATA_DIR.mkdir(exist_ok=True) try:
SETTINGS_FILE.write_text(json.dumps(self.common, ensure_ascii=False, indent=2), encoding="utf-8") atomic_write_json(SETTINGS_FILE, updated)
for engine in list(self.engines.values()): 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) engine.apply(clean)
return "" return ""
def state(self) -> dict: def state(self) -> dict:
with self.lock:
engines = list(self.engines.values())
return {"settings": self.common, "modes": lw.MODES, 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 # 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"]))} key=lambda c: (not c["running"], c["symbol"], c["name"]))}
@@ -615,7 +803,7 @@ def basis_engine(venue: str):
with BASIS_LOCK: with BASIS_LOCK:
if "cross" not in BASIS: if "cross" not in BASIS:
import cross 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) 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: if venue == "cross_real" and "cross_real" not in BASIS:
import cross import cross
@@ -640,11 +828,19 @@ class Handler(BaseHTTPRequestHandler):
self._send(code, json.dumps(data, ensure_ascii=False).encode("utf-8")) self._send(code, json.dumps(data, ensure_ascii=False).encode("utf-8"))
def do_GET(self) -> None: def do_GET(self) -> None:
if not trusted_request(self):
self._json({"error": "недоверенный адрес страницы"}, 403)
return
path, _, query = self.path.partition("?") path, _, query = self.path.partition("?")
if path in ("/", "/index.html"): if path in ("/", "/index.html"):
self._send(200, PAGE.read_bytes(), "text/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": elif path == "/api/state":
self._json(SIM.state()) self._json(SIM.state())
elif path == "/api/account":
self._json(paper_account().view())
elif path == "/api/arb": elif path == "/api/arb":
m = re.search(r"transfer=([0-9.]+)", query) m = re.search(r"transfer=([0-9.]+)", query)
mk = re.search(r"market=(spot|futures)", query) mk = re.search(r"market=(spot|futures)", query)
@@ -660,7 +856,10 @@ class Handler(BaseHTTPRequestHandler):
if engine is None: if engine is None:
self._json({"error": "эта биржа пока не подключена"}, 404) self._json({"error": "эта биржа пока не подключена"}, 404)
else: 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": elif path == "/api/scanner":
try: try:
self._json(scanner_view(lw.load_connections())) self._json(scanner_view(lw.load_connections()))
@@ -683,17 +882,42 @@ class Handler(BaseHTTPRequestHandler):
if not local_request(self): if not local_request(self):
self._json({"error": "команды принимаются только со страницы симулятора на этом компьютере"}, 403) self._json({"error": "команды принимаются только со страницы симулятора на этом компьютере"}, 403)
return return
length = int(self.headers.get("Content-Length") or 0)
try: 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"{}") body = json.loads(self.rfile.read(length) or b"{}")
except ValueError: if not isinstance(body, dict):
body = {} raise ValueError("ожидается объект JSON")
except (ValueError, UnicodeError):
self._json({"ok": False, "error": "Некорректный JSON запроса"}, 400)
return
parts = self.path.strip("/").split("/") 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"]: if parts == ["api", "settings"]:
problem = SIM.save_common(body) problem = SIM.save_common(body)
self._json({"ok": not problem, "error": problem}) self._json({"ok": not problem, "error": problem})
return return
if parts[:3] == ["api", "real", "simulator"]: if parts[:3] == ["api", "real", "simulator"]:
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) problem = real_mirror.save_settings(body)
self._json({"ok": not problem, "error": problem}) self._json({"ok": not problem, "error": problem})
return return
@@ -732,7 +956,9 @@ class Handler(BaseHTTPRequestHandler):
uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None
self._json({"ok": True, "message": engine.close(uid)}) self._json({"ok": True, "message": engine.close(uid)})
elif parts[3] == "reset": 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": elif parts[3] == "adopt":
try: try:
price = float(body["price"]) if body.get("price") not in (None, "") else None price = float(body["price"]) if body.get("price") not in (None, "") else None
@@ -781,17 +1007,22 @@ class Handler(BaseHTTPRequestHandler):
action = parts[3] action = parts[3]
if action == "start": if action == "start":
engine.set_trading(True) engine.set_trading(True)
self._json({"ok": True}) self._json({"ok": not engine.removing,
"error": engine.message if engine.removing else ""})
elif action == "stop": elif action == "stop":
engine.set_trading(False) engine.set_trading(False)
self._json({"ok": True}) self._json({"ok": True})
elif action == "reset": 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": elif action == "remove":
self._json({"ok": True, "message": SIM.remove(parts[2])}) self._json({"ok": True, "message": SIM.remove(parts[2])})
elif action == "close": elif action == "close":
uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None 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: else:
self._json({"error": "unknown action"}, 404) self._json({"error": "unknown action"}, 404)
return return
@@ -804,14 +1035,15 @@ LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"}
def local_request(handler) -> bool: 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 return trusted_request(handler, command=True)
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"
def main() -> None: def main() -> None:
with RuntimeLock(DATA_DIR / "engine.lock"):
_serve()
def _serve() -> None:
import sys import sys
global SIM global SIM
# --backend: only for this PC on BACKEND_PORT, the public page is served by web_proxy.py (outside the VPN) # --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 host, port = "127.0.0.1", BACKEND_PORT
else: else:
host, port = ("127.0.0.1" if "--local" in sys.argv else HOST), PORT 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() real_mirror.load_recent()
import minorder import minorder
minorder.AUTOLOAD = True # the exchanges' smallest orders (spot and perp), loaded and renewed hourly 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) # «Арбитраж»: the simulation and the real engine run from the start (open real positions are watched at once)
basis_engine("cross") basis_engine("cross")
basis_engine("cross_real") basis_engine("cross_real")
server = ThreadingHTTPServer((host, port), Handler)
url = f"http://127.0.0.1:{PORT}" url = f"http://127.0.0.1:{PORT}"
print(f"Симулятор: {url} (движок слушает {host}:{port}, монет: {len(SIM.engines)})", flush=True) print(f"Симулятор: {url} (движок слушает {host}:{port}, монет: {len(SIM.engines)})", flush=True)
threading.Timer(1.0, lambda: webbrowser.open(url)).start() threading.Timer(1.0, lambda: webbrowser.open(url)).start()
@@ -841,6 +1074,7 @@ def main() -> None:
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
finally: finally:
server.server_close()
for engine in SIM.engines.values(): for engine in SIM.engines.values():
engine.shutdown() engine.shutdown()