feat: добавить общий виртуальный счёт, справку и восстановление позиций
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s

This commit is contained in:
Igol committed 2026-10-22 23:07:50 +03:00
1 parent 6aa76064dc
commit c5aed5b970
29 files changed
+3589 -213

No files matched your search

+42 -13
View File
@@ -88,19 +88,48 @@ real time (well under a second), unlike GeckoTerminal's 1–2 minute delay. «С
USDⓈ-M `bookTicker` (`fstream…/public/stream`) as a one-level book and `aggTrade` (`…/market/stream`) as trades; the USDⓈ-M `bookTicker` (`fstream…/public/stream`) as a one-level book and `aggTrade` (`…/market/stream`) as trades; the
paper fees stay Bybit's (0.055% taker / 0.02% maker; Binance's are 0.05% / 0.02%). paper fees stay Bybit's (0.055% taker / 0.02% maker; Binance's are 0.05% / 0.02%).
**Web interface** (`py -3 web_sim.py` or `run_web_sim.bat` → http://127.0.0.1:8765, opens in the browser): every **Web interface** (`py -3 web_sim.py` or `run_web_sim.bat` → [local page](http://127.0.0.1:8765), opens in the
coin of the connection list runs at the same time with its own feeds, its own paper account and journal browser): every coin has its own feeds, trade history and Start/Stop. A new coin starts stopped; Stop forbids
(`web_sim_data/<coin>.json/.csv`) and its own Start/Stop (a new coin starts stopped; Stop only forbids new entries). new entries while existing positions remain managed. All paper coins in «Симулятор» and «Арбитраж → Симуляция»
Top: the common trade settings («Применить ко всем монетам», saved in `web_sim_data/settings.json`; the first start use **one virtual account**, persisted in `web_sim_data/virtual_account.json`. The Tk window
copies the Tk window's). Left: coin tiles (green dot = trading, open positions, price, result). Centre: a chart of both (`py -3 scalp_hint.py`) and the main desktop application keep their separate accounts.
exchanges' prices as % change over the last 1/5/10 minutes with entry/exit markers, the coin's statistics, Start/Stop,
«Закрыть все позиции», and the trade table — open positions on top in yellow with ✕ (close that one at the current The «Общий виртуальный счёт» panel shows balance, equity, reserved capital and free capital. Enter a positive
price), then closed trades, newest first. Tiles also show the win rate. The last tile «+» opens the **scanner panel**: amount and click «Пополнить» to add it or «Списать» to subtract it; the journal shows recent operations newest
start/stop of the autonomous search (meme_matcher/autoscan.py, runs in the background), its log, and the coins it first. These are virtual adjustments, not exchange transfers, and do not change the recorded trading result.
checked (how often the DEX led, the latest figures); «+ Добавить» puts a coin where the DEX led into the left panel Free capital is `max(0, min(balance, equity) - reserved)`: unrealized profits cannot fund another entry, while
(stopped, ready to test) when its pool and futures are supported. «Добавлять найденные автоматически» lets the search unrealized losses reduce the available amount. Every paper entry must fit the shared capital limit, including
add them by itself (off by default; meme_matcher/autoscan_config.json). Coins added to the list appear within 30 s. The Tk window its reserve and fees. Withdrawals cannot exceed free capital and are refused if an open position's valuation
(`py -3 scalp_hint.py`) keeps its own separate account. 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.
**Live leader check** (`require_leader`, on by default, all lead modes): the policy samples both prices every 0.5 s **Live leader check** (`require_leader`, on by default, all lead modes): the policy samples both prices every 0.5 s
and every 10 s measures, over up to the last 20 minutes, the positive correlations of price changes with the follower and every 10 s measures, over up to the last 20 minutes, the positive correlations of price changes with the follower
+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:
+249 -37
View File
@@ -214,6 +214,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:
@@ -397,8 +400,12 @@ class CrossEngine:
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] = []
@@ -454,6 +461,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()
@@ -465,10 +488,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:
@@ -486,11 +522,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)."""
@@ -546,7 +587,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:
@@ -590,13 +635,81 @@ 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}
if self.account is not None:
data["cash_total"] = self.cash_total
return data
def _position_reserve(self, pos: CrossPosition) -> float:
notional = pos.qty * pos.fut_entry
return pos.qty * pos.spot_entry + (notional if pos.ss else
max(notional * self.FUT_NEED, equity_for(self.settings.min_liq_pct, notional)))
def _reserved(self) -> float:
total = 0.0
for pos in self.positions:
if pos.real:
continue
if pos.paper_reserve <= 0:
pos.paper_reserve = self._position_reserve(pos)
total += pos.paper_reserve
return total
def _unrealized(self) -> float:
total = 0.0
for pos in self.positions:
if pos.real:
continue
link = self.links.get(pos.key)
if link is not None or pos.paper_unrealized is None:
bid, ask = (link.spot_bid, link.fut_ask) if link else (pos.spot_entry, pos.fut_entry)
_, _, _, net = close_result(pos, bid, ask, self.fees)
# entry fees/funding already changed cash; quote loss must survive outages/settings/restarts.
pos.paper_unrealized = net + pos.fees - pos.funding
total += pos.paper_unrealized
return total
def _mark_account(self, snapshot_fresh: bool = False) -> None:
now = time.time()
if self.account is not None and all(
p.key in self.links and (snapshot_fresh or now - max(self.updated, self.fast_seen.get(p.key, 0)) <= 30)
for p in self.positions if not p.real):
self.account.mark("cross", self._unrealized())
def save(self, event: str = "") -> bool:
unrealized = self._unrealized() if self.account is not None else 0.0
data = self._state()
shared = self.account is not None and not self._account_initializing
if shared:
from virtual_account import AccountError
try:
self.account.commit("cross", data, cash_total=self.cash_total,
reserved=self._reserved(), unrealized=unrealized, event=event)
except AccountError as exc:
try:
saved = self.account.restore("cross")
if saved is not None:
self._load_state(saved)
except AccountError:
pass
self.account_error = str(exc)
self.settings.running = False
return False
try:
self.file.parent.mkdir(exist_ok=True)
atomic_write_json(self.file, data) 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:
with self.lock: with self.lock:
@@ -634,7 +747,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:
@@ -920,6 +1035,7 @@ 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 or info.get("link")) and base not in self.opening and time.time() >= info.get("retry_at", 0): 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):
@@ -938,7 +1054,7 @@ class CrossEngine:
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")
def hot_step(self, keys: list[str], now: float) -> None: def hot_step(self, keys: list[str], now: float) -> None:
"""The hot links have fresh prices: their rows again, and an entry if one of them fits now.""" """The hot links have fresh prices: their rows again, and an entry if one of them fits now."""
@@ -964,10 +1080,18 @@ class CrossEngine:
changed = False changed = False
for pos in list(self.positions): for pos in list(self.positions):
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
@@ -1008,13 +1132,18 @@ class CrossEngine:
pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap] pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap]
self.jobs.put(("close", pos.uid, reason)) self.jobs.put(("close", pos.uid, reason))
else: else:
self._close(pos, l, now, reason) if not self._close(pos, l, now, reason):
return False
changed = True changed = True
return changed return changed
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 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 busy = {p.base for p in self.positions} | self.opening
best: dict[str, dict] = {} best: dict[str, dict] = {}
@@ -1046,7 +1175,12 @@ 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, r["usual"], fee_in, 0.0 if l.ss else (now // step + 1) * step, l.fut_bid, l.entry_gap, r["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
if self.account is not None:
self.cash_total -= fee_in
if not self.save(event=f"Арбитраж: вход {l.base}"):
break
busy.add(l.base) busy.add(l.base)
changed = True changed = True
return changed return changed
@@ -1089,8 +1223,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 ---------
@@ -1156,7 +1291,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,
@@ -1164,6 +1299,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:
@@ -1181,18 +1320,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._close(pos, l, time.time(), "вручную") if self._close(pos, l, time.time(), "вручную"):
n += 1 n += 1
self.save() else:
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) ------------------
@@ -1370,7 +1515,8 @@ 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, "link": asdict(l), "phase": "prepared"} "amount": amount, "link": asdict(l), "phase": "prepared"}
@@ -1504,6 +1650,7 @@ class CrossEngine:
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()
@@ -1516,10 +1663,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.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)
@@ -1596,7 +1751,8 @@ 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, "link": asdict(l), "phase": "prepared"} "amount": amount, "link": asdict(l), "phase": "prepared"}
@@ -1691,6 +1847,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
@@ -1702,23 +1914,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:
@@ -1883,7 +2080,9 @@ class CrossEngine:
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
@@ -1897,12 +2096,17 @@ class CrossEngine:
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.pending.pop(base, None)
@@ -1910,6 +2114,8 @@ class CrossEngine:
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:
@@ -2065,13 +2271,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,
"recovery": {base: dict(info) for base, info in {**self.recover, **self.pending}.items()}, "recovery": {base: dict(info) for base, info in {**self.recover, **self.pending}.items()},
"real_pause": ("сверка незавершённых ордеров: " + ", ".join({**self.recover, **self.pending}) "real_pause": ("сверка незавершённых ордеров: " + ", ".join({**self.recover, **self.pending})
if s.real and (self.pending or self.recover) else f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)" 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
+117 -6
View File
@@ -1,5 +1,84 @@
# Recovery and development # 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 ## Real orders
`cross.py` records an entry intent before sending its first order. A working limit order stays pending until `cross.py` records an entry intent before sending its first order. A working limit order stays pending until
@@ -21,6 +100,13 @@ spot-to-spot entries require manual reconciliation on the exchanges. The applica
the reason for pausing. A supervised resolution must verify the exchange's open orders and fills, not just its 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. 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 ## Browser boundary
Both the proxy and the engine validate the original loopback Host on GET and POST. A browser Origin, if present, Both the proxy and the engine validate the original loopback Host on GET and POST. A browser Origin, if present,
@@ -28,16 +114,35 @@ must match that authority; POST also requires `X-Sim: 1`. The proxy preserves th
Both listeners remain bound to loopback. This is local-app isolation, not user authentication for internet hosting. 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. Static assets are served from an explicit allowlist.
Responses for an earlier venue/coin selection cannot replace the current screen. Commands are disabled until Read timers are registered before the initial request, so a failed first fetch cannot permanently prevent
the selected context has loaded, and row close actions carry their original venue or coin. Poll responses also startup. GET requests have bounded timeouts and share one in-flight request per endpoint within the same
have sequence numbers so a slower old response cannot overwrite a newer completed response. 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 ## Code boundaries
| Responsibility | Files | | Responsibility | Files |
| --- | --- | | --- | --- |
| Web layout, styles, behaviour | `web_sim.html`, `web/app.css`, `web/app.js` | | 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` | | 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 account models and chart | `desktop_models.py`, `desktop_chart.py` |
| Desktop coordination | `main.py` | | Desktop coordination | `main.py` |
| Order execution and recovery | `cross.py`, `real_mirror.py` | | Order execution and recovery | `cross.py`, `real_mirror.py` |
@@ -57,9 +162,15 @@ node --test tests/web_context.test.cjs
``` ```
The Python runner blocks external connections and DNS while permitting loopback HTTP fixtures. Exchange orders The Python runner blocks external connections and DNS while permitting loopback HTTP fixtures. Exchange orders
are tested using fake clients. CI runs these suites on Windows with Python 3.11, 3.12 and 3.13; configuring the are tested using fake clients. The CI workflow is configured for Windows with Python 3.11, 3.12 and 3.13;
workflow does not imply that a remote CI run or a real exchange integration has been performed. 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 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 after order acceptance, failed disk writes, hostile Host/Origin, response ordering, percentage drawdown and
capital-floor ordering for long/short backtests including fees. 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.
+9
View File
@@ -0,0 +1,9 @@
[
{
"lead_market": "raydium",
"lead_ticker": "CLAUDIAUSDTM",
"lead_pool": "Fe7bpDYCs74GqiCUF14HwgUMToPKV1d9mDYVX5BTohFr",
"follow_exchange": "mexc",
"follow_ticker": "CLAUDIA_USDT"
}
]
+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
+13 -3
View File
@@ -8,8 +8,8 @@ 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).
""" """
@@ -108,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 ""
@@ -324,6 +324,16 @@ class FuturesMirror:
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
+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
+224 -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"
@@ -137,6 +138,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 +180,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 +261,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 +378,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 +396,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 +417,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 +459,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 +548,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 +692,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 +793,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 +1104,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 +1282,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 +1355,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 +1381,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 +1413,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 +1426,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)
+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) {
+23 -10
View File
@@ -12,20 +12,27 @@ $Host.UI.RawUI.WindowTitle = "Симулятор"
$VenvPy = Join-Path $Dir ".venv\Scripts\python.exe" $VenvPy = Join-Path $Dir ".venv\Scripts\python.exe"
$VenvPyw = Join-Path $Dir ".venv\Scripts\pythonw.exe" $VenvPyw = Join-Path $Dir ".venv\Scripts\pythonw.exe"
function Test-Python($Executable) {
try {
& $Executable -c "import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)" 2>$null
return $LASTEXITCODE -eq 0
} catch { return $false }
}
function Find-Python { function Find-Python {
foreach ($v in "3.13", "3.12", "3.11") { foreach ($v in "3.13", "3.12", "3.11") {
try { try {
$exe = & py "-$v" -c "import sys; print(sys.executable)" 2>$null $exe = & py "-$v" -c "import sys; print(sys.executable)" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() } if ($LASTEXITCODE -eq 0 -and $exe -and (Test-Python $exe.Trim())) { return $exe.Trim() }
} catch {} } catch {}
} }
foreach ($d in "Python313", "Python312", "Python311") { foreach ($d in "Python313", "Python312", "Python311") {
$p = Join-Path $env:LOCALAPPDATA "Programs\Python\$d\python.exe" $p = Join-Path $env:LOCALAPPDATA "Programs\Python\$d\python.exe"
if (Test-Path $p) { return $p } if ((Test-Path $p) -and (Test-Python $p)) { return $p }
} }
try { try {
$exe = & python -c "import sys; assert sys.version_info >= (3, 11); print(sys.executable)" 2>$null $exe = & python -c "import sys; assert sys.version_info >= (3, 11); print(sys.executable)" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() } if ($LASTEXITCODE -eq 0 -and $exe -and (Test-Python $exe.Trim())) { return $exe.Trim() }
} catch {} } catch {}
return $null return $null
} }
@@ -36,7 +43,8 @@ function Fail($text) {
exit 1 exit 1
} }
if (-not (Test-Path $VenvPy)) { if (-not (Test-Python $VenvPy)) {
Write-Host "Окружение отсутствует или не работает. Подбираю Python 3.11+..." -ForegroundColor Yellow
$py = Find-Python $py = Find-Python
if (-not $py) { if (-not $py) {
Write-Host "Python не найден. Ставлю Python 3.12 через winget..." -ForegroundColor Yellow Write-Host "Python не найден. Ставлю Python 3.12 через winget..." -ForegroundColor Yellow
@@ -48,18 +56,23 @@ if (-not (Test-Path $VenvPy)) {
$py = Find-Python $py = Find-Python
if (-not $py) { Fail "Python установлен, но ещё не виден. Закройте окно и запустите файл ещё раз." } if (-not $py) { Fail "Python установлен, но ещё не виден. Закройте окно и запустите файл ещё раз." }
} }
$VenvDir = Join-Path $Dir ".venv"
if (Test-Path $VenvDir) {
$Backup = ".venv.backup-" + [Guid]::NewGuid().ToString("N")
Rename-Item -LiteralPath $VenvDir -NewName $Backup
Write-Host "Старое окружение сохранено: $Backup"
}
Write-Host "Python: $py" Write-Host "Python: $py"
Write-Host "Создаю окружение программы (.venv)..." Write-Host "Создаю окружение программы (.venv)..."
& $py -m venv (Join-Path $Dir ".venv") & $py -m venv (Join-Path $Dir ".venv")
if ($LASTEXITCODE -ne 0 -or -not (Test-Path $VenvPy)) { Fail "Не удалось создать .venv" } if ($LASTEXITCODE -ne 0 -or -not (Test-Path $VenvPy)) { Fail "Не удалось создать .venv" }
} }
& $VenvPy -c "import sys; assert sys.version_info >= (3, 11), 'Python 3.11+ required'" if (-not (Test-Python $VenvPy)) {
if ($LASTEXITCODE -ne 0) { Fail "Не удалось запустить Python из нового окружения .venv."
Fail "Окружение .venv использует старый Python. Переименуйте .venv и повторите установку с Python 3.11 или новее."
} }
Write-Host "Проверяю библиотеки..." Write-Host "Проверяю библиотеки. Ниже отображается ход установки; для загрузки нужен интернет..."
& $VenvPy -m pip install --disable-pip-version-check -q -r (Join-Path $Dir "requirements.txt") & $VenvPy -m pip install --disable-pip-version-check --timeout 30 --retries 2 -r (Join-Path $Dir "requirements.txt")
if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -ne 0) {
Fail "Не удалось установить библиотеки. Проверьте интернет (и VPN, если сайты у вас заблокированы) и запустите ещё раз." Fail "Не удалось установить библиотеки. Проверьте интернет (и VPN, если сайты у вас заблокированы) и запустите ещё раз."
} }
@@ -72,6 +85,6 @@ Write-Host ""
Write-Host "Запускаю симулятор. Страница: http://127.0.0.1:8765" -ForegroundColor Green Write-Host "Запускаю симулятор. Страница: http://127.0.0.1:8765" -ForegroundColor Green
Write-Host "Это окно — движок программы: не закрывайте его, пока пользуетесь симулятором." Write-Host "Это окно — движок программы: не закрывайте его, пока пользуетесь симулятором."
Write-Host "" Write-Host ""
Start-Process -FilePath $VenvPyw -ArgumentList "web_proxy.py" -WorkingDirectory $Dir Start-Process -FilePath $VenvPyw -ArgumentList "web_proxy.py" -WorkingDirectory $Dir -WindowStyle Hidden
Start-Process "http://127.0.0.1:8765" Start-Process "http://127.0.0.1:8765"
& $VenvPy web_sim.py --backend & $VenvPy web_sim.py --backend
+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()
+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"), "нет такой монеты")
+181
View File
@@ -0,0 +1,181 @@
"""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_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()
+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()
+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()
+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()
+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)
+236 -5
View File
@@ -10,17 +10,19 @@ function page() {
source = source.replace(/^\(function (calcInit|restoreArbSettings)\(\) \{[\s\S]*?^\}\)\(\);/gm, ''); source = source.replace(/^\(function (calcInit|restoreArbSettings)\(\) \{[\s\S]*?^\}\)\(\);/gm, '');
source = source.slice(0, source.indexOf('\n(async () => {')); source = source.slice(0, source.indexOf('\n(async () => {'));
const elements = new Map(); const elements = new Map();
const intervals = [];
const context = vm.createContext({ const context = vm.createContext({
console, Intl, localStorage: {getItem: () => null, setItem() {}}, console, Intl, localStorage: {getItem: () => null, setItem() {}},
AbortController, setTimeout, clearTimeout, setInterval(fn, ms) { intervals.push({fn, ms}); },
document: {getElementById(id) { document: {getElementById(id) {
if (!elements.has(id)) elements.set(id, {textContent: '', innerHTML: '', classList: {toggle() {}}}); if (!elements.has(id)) elements.set(id, {textContent: '', innerHTML: '', value: '', dataset: {}, style: {}, disabled: false, classList: {toggle() {}}, addEventListener() {}, getAttribute() { return ''; }});
return elements.get(id); return elements.get(id);
}, querySelectorAll: () => []}, }, querySelectorAll: () => [], querySelector: () => null},
window: {addEventListener() {}}, confirm: () => true, window: {addEventListener() {}}, confirm: () => true,
}); });
vm.runInContext(source, context); vm.runInContext(source, context);
vm.runInContext(` vm.runInContext(`
var pending = [], commands = [], rendered = []; var originalApi = api, pending = [], commands = [], rendered = [];
api = (url, body) => body === undefined api = (url, body) => body === undefined
? new Promise(resolve => pending.push({url, resolve})) ? new Promise(resolve => pending.push({url, resolve}))
: (commands.push(url), Promise.resolve({ok: true, message: 'ok'})); : (commands.push(url), Promise.resolve({ok: true, message: 'ok'}));
@@ -29,7 +31,7 @@ function page() {
renderTiles = () => {}; renderTiles = () => {};
tab = 'basis'; bxVenue = 'cross'; tab = 'basis'; bxVenue = 'cross';
`, context); `, context);
return {context, run: code => vm.runInContext(code, context)}; return {context, elements, intervals, run: code => vm.runInContext(code, context)};
} }
const tick = () => new Promise(resolve => setImmediate(resolve)); const tick = () => new Promise(resolve => setImmediate(resolve));
@@ -73,7 +75,7 @@ test('older poll cannot overwrite a newer completed poll', async () => {
test('coin switch rejects stale details and stale row actions', async () => { test('coin switch rejects stale details and stale row actions', async () => {
const {context: c, run} = page(); const {context: c, run} = page();
run("selected = 'A'; detail = {key: 'A'}"); run("tab = 'sim'; selected = 'A'; detail = {key: 'A'}");
const old = run('loadDetail()'); const old = run('loadDetail()');
run("selectCoin('B')"); run("selectCoin('B')");
await run("closePos(1, 'A'); trade('start')"); await run("closePos(1, 'A'); trade('start')");
@@ -87,3 +89,232 @@ test('coin switch rejects stale details and stale row actions', async () => {
await run("closePos(1, 'B')"); await run("closePos(1, 'B')");
assert.equal(c.commands[0], '/api/coin/B/close/1'); 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()
+48
View File
@@ -4,6 +4,7 @@
--lead: #ff9f43; --follow: #4c8dff; --lead: #ff9f43; --follow: #4c8dff;
} }
* { box-sizing: border-box; } * { 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; } 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; } 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 { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
@@ -129,3 +130,50 @@ button.realon { background: rgba(255, 92, 92, 0.18); border-color: var(--red); c
.calcout .row2 { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; } .calcout .row2 { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; }
.calcout .note { color: var(--muted); font-size: 11.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; } } @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; } }
+310 -43
View File
@@ -6,7 +6,7 @@ const MAIN_FIELDS = [
["auto_tp", "Авто тейк-профит по прогнозу", "check"], ["require_leader", "Входить, только если ведущая правда ведёт", "check"], ["auto_tp", "Авто тейк-профит по прогнозу", "check"], ["require_leader", "Входить, только если ведущая правда ведёт", "check"],
]; ];
const MORE_FIELDS = [ const MORE_FIELDS = [
["budget", "Бюджет, $"], ["cooldown_ms", "Пауза после сделки, мс"], ["lead_threshold_pct", "Отставание для входа, %"], ["cooldown_ms", "Пауза после сделки, мс"], ["lead_threshold_pct", "Отставание для входа, %"],
["lead_window_ms", "Окно сравнения, мс"], ["vector_window_seconds", "Вектор за, с"], ["vector_min_move_pct", "Мин. движение, %"], ["lead_window_ms", "Окно сравнения, мс"], ["vector_window_seconds", "Вектор за, с"], ["vector_min_move_pct", "Мин. движение, %"],
["auto_tp_share_pct", "Доля догоняния, %"], ["auto_tp_horizon_seconds", "Горизонт прогноза, с"], ["auto_tp_share_pct", "Доля догоняния, %"], ["auto_tp_horizon_seconds", "Горизонт прогноза, с"],
["cut_loss_ticks", "Минус для закрытия, шагов"], ["max_data_age_ms", "Данные не старше, мс"], ["cut_loss_ticks", "Минус для закрытия, шагов"], ["max_data_age_ms", "Данные не старше, мс"],
@@ -19,6 +19,12 @@ let state = null, selected = localStorage.getItem("sim.coin") || null, detail =
let detailEpoch = 0, detailRequest = 0, detailApplied = 0; let detailEpoch = 0, detailRequest = 0, detailApplied = 0;
let bxEpoch = 0, bxRequest = 0, bxApplied = 0, bxDataVenue = null; let bxEpoch = 0, bxRequest = 0, bxApplied = 0, bxDataVenue = null;
let range = +(localStorage.getItem("sim.range") || 300), seenOpen = new Set(), seenClosed = 0, settingsDirty = false; let range = +(localStorage.getItem("sim.range") || 300), seenOpen = new Set(), seenClosed = 0, settingsDirty = false;
let stateRequest = 0, stateApplied = 0, realRequest = 0, realApplied = 0;
const readHealth = new Map(), pendingReads = new Map(), pendingCommands = new Set(), pendingPolls = new Map(), readGenerations = new Map();
const FRESH_MS = 10000;
let accountData = null, accountBusy = false, pendingAccountAdjustment = null;
const accountIsStale = account => Array.isArray(account?.stale) ? account.stale.length > 0 : !!account?.stale;
const escapeHtml = value => String(value ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":"&#39;"}[c]));
// all times on the page are Moscow time, whatever the computer's time zone // all times on the page are Moscow time, whatever the computer's time zone
const MSK = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", hour: "2-digit", minute: "2-digit", second: "2-digit"}); const MSK = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", hour: "2-digit", minute: "2-digit", second: "2-digit"});
@@ -32,10 +38,183 @@ const fmt = (v, d = 4) => v == null || isNaN(v) ? "—" : (+v).toFixed(d);
const price = v => v == null ? "—" : (+v).toPrecision(6); const price = v => v == null ? "—" : (+v).toPrecision(6);
const money = v => (v >= 0 ? "+" : "") + (+v).toFixed(4) + " $"; const money = v => (v >= 0 ? "+" : "") + (+v).toFixed(4) + " $";
const cls = v => v > 0 ? "pos" : v < 0 ? "neg" : "mut"; const cls = v => v > 0 ? "pos" : v < 0 ? "neg" : "mut";
function commandNotice(message, bad = false) {
const el = document.getElementById("commandNotice");
if (!el) return;
el.textContent = message; el.hidden = !message; el.className = bad ? "command-notice neg" : "command-notice pos";
}
function freshRead(path) {
const h = readHealth.get(path);
return !!h && !h.error && Date.now() - h.time < FRESH_MS;
}
function invalidateRead(path) {
readGenerations.set(path, (readGenerations.get(path) || 0) + 1);
pendingReads.delete(path); readHealth.delete(path);
}
function commandRead(path) {
if (path.startsWith("/api/account/")) return "/api/account";
if (/^\/api\/coin\/[^/]+\/remove$/.test(path)) return "/api/state";
if (path.startsWith("/api/coin/")) return path.split("/").slice(0, 4).join("/");
if (path.startsWith("/api/basis/")) return `/api/basis?ex=${path.split("/")[3]}`;
if (path.startsWith("/api/scanner/")) return "/api/scanner";
if (path.startsWith("/api/real/")) return "/api/real";
return "/api/state";
}
function activeRead() {
if (tab === "basis") return `/api/basis?ex=${bxVenue}`;
if (tab === "real") return "/api/real";
return selected === SCANNER ? "/api/scanner" : selected ? `/api/coin/${selected}` : "/api/state";
}
function connectionLabel(path) {
const h = readHealth.get(path);
if (!h) return "Подключение к серверу…";
const age = h.time ? Math.max(0, Math.floor((Date.now() - h.time) / 1000)) : null;
if (!freshRead(path)) return `Связь потеряна или данные устарели${age == null ? "" : ` · последние данные ${age} с назад`}. ${h.error || "Жду обновления"}. Команды заблокированы до восстановления связи.`;
return `Связь с сервером есть · получено ${age} с назад`;
}
function refreshConnection() {
const path = activeRead(), fresh = freshRead(path);
const el = document.getElementById("connectionStatus");
if (el) { el.textContent = connectionLabel(path); el.className = fresh ? "connection-status connected" : "connection-status disconnected"; }
const mode = document.getElementById("modeStatus");
if (mode) {
const selectedCoin = detail?.key === selected ? detail : state?.coins?.find(c => c.key === selected);
const live = tab === "basis" ? bxVenue === "cross_real" : tab === "sim" && !!selectedCoin?.real?.enabled;
mode.textContent = tab === "real" ? "API-ключи и журнал бирж" : tab === "sim" && selected && selected !== SCANNER && !selectedCoin ? "Режим выбранной монеты загружается…" : live ? "РЕАЛЬНАЯ ТОРГОВЛЯ · средства биржи" : "СИМУЛЯЦИЯ · общий виртуальный счёт";
mode.className = live ? "mode-status mode-live" : "mode-status";
}
document.querySelectorAll("button[onclick], input[onchange]").forEach(control => {
const handler = control.getAttribute("onclick") || control.getAttribute("onchange") || "";
if (/\b(saveSettings|trade|resetCoin|removeCoin|closePos|scanner|addCoin|keySave|keyCheck|keyDelete|coinReal|simRealTransfer|simRealPing|simRealSl|simRealTpsl|basisReal|crossToggle|crossFeesSave|basisSave|basisRun|basisClose|basisAdopt|basisReset)\s*\(/.test(handler)) {
control.dataset.command = /\b(saveSettings|removeCoin)\b/.test(handler) ? "state" : /\b(keySave|keyCheck|keyDelete|simRealTransfer|simRealPing|simRealSl|simRealTpsl)\b/.test(handler) ? "real" : "active";
}
});
document.querySelectorAll("[data-command]").forEach(control => {
const source = control.dataset.command === "account" ? "/api/account" : control.dataset.command === "state" ? "/api/state" : control.dataset.command === "real" ? "/api/real" : path;
const blocked = !freshRead(source) || (source === "/api/account" && (accountBusy || accountData?.error || (accountIsStale(accountData) && control.dataset.accountDirection === "-1")));
if (blocked && !control.dataset.connectionDisabled) {
control.dataset.wasDisabled = control.disabled ? "1" : "0"; control.dataset.connectionDisabled = "1"; control.disabled = true;
} else if (!blocked && control.dataset.connectionDisabled) {
control.disabled = control.dataset.wasDisabled === "1";
delete control.dataset.connectionDisabled; delete control.dataset.wasDisabled;
} else if (blocked) control.disabled = true;
});
updateAccountVisibility();
}
function setControlDisabled(control, disabled) {
if (control.dataset?.connectionDisabled) control.dataset.wasDisabled = disabled ? "1" : "0";
else control.disabled = disabled;
}
async function api(path, body) { async function api(path, body) {
const r = await fetch(path, body === undefined ? {} : {method: "POST", const reading = body === undefined;
if (reading && pendingReads.has(path)) return pendingReads.get(path);
const generation = readGenerations.get(path) || 0;
if (!reading && (!freshRead(commandRead(path)) || (path === "/api/real/simulator" && body.coin && !freshRead(`/api/coin/${body.coin}`)))) {
const error = new Error("Команда не отправлена: сначала дождитесь свежих данных сервера.");
commandNotice(error.message, true); throw error;
}
if (!reading && pendingCommands.has(path)) {
const error = new Error("Эта команда уже выполняется. Дождитесь ответа сервера.");
commandNotice(error.message, true); throw error;
}
const request = (async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), reading ? 8000 : 20000);
if (!reading) pendingCommands.add(path);
try {
const response = await fetch(path, reading ? {signal: controller.signal, cache: "no-store"} : {method: "POST", signal: controller.signal,
headers: {"Content-Type": "application/json", "X-Sim": "1"}, body: JSON.stringify(body)}); headers: {"Content-Type": "application/json", "X-Sim": "1"}, body: JSON.stringify(body)});
return r.json(); let data;
try { data = await response.json(); } catch (_) { throw new Error(`Сервер вернул некорректный ответ (HTTP ${response.status})`); }
if (!response.ok) throw new Error(data.error || `Ошибка сервера HTTP ${response.status}`);
if (reading && data.error && !(path === "/api/account" && data.balance != null)) throw new Error(data.error);
if (reading) {
if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: Date.now(), error: data.error || ""});
}
else if (data.ok === false || data.error) commandNotice(data.error || data.message || "Команда отклонена сервером", true);
else commandNotice(data.message || "Команда подтверждена сервером");
return data;
} catch (cause) {
const reason = cause.name === "AbortError" ? "Сервер не ответил вовремя" : cause.message || "Нет связи с сервером";
if (reading) {
if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: readHealth.get(path)?.time || 0, error: reason});
}
else {
cause.userMessage = `Результат команды не подтверждён: ${reason}. Проверьте состояние перед повтором. Автоматического повтора нет.`;
commandNotice(cause.userMessage, true);
}
cause.apiHandled = true;
throw cause;
} finally {
clearTimeout(timeout);
if (!reading) pendingCommands.delete(path);
refreshConnection();
}
})();
if (reading) {
pendingReads.set(path, request);
try { return await request; } finally { if (pendingReads.get(path) === request) pendingReads.delete(path); }
}
return request;
}
async function poll(task) {
if (pendingPolls.has(task)) return pendingPolls.get(task);
const work = (async () => {
try { await task(); } catch (error) {
if (!error.apiHandled) commandNotice(`Не удалось обновить интерфейс: ${error.message || "неожиданная ошибка"}`, true);
// api() records connectivity; the next scheduled read recovers.
}
})();
pendingPolls.set(task, work);
try { await work; } finally { if (pendingPolls.get(task) === work) pendingPolls.delete(task); }
}
function updateAccountVisibility() {
const panel = document.getElementById("paperAccount");
if (panel) panel.hidden = !(tab === "sim" || (tab === "basis" && bxVenue === "cross"));
}
function renderAccount(account) {
if (!account) return;
if (accountData && account.version != null && accountData.version != null && account.version < accountData.version) return;
if (accountData && account.version === accountData.version && account.updated_at != null && accountData.updated_at != null && account.updated_at < accountData.updated_at) return;
accountData = account;
const health = document.getElementById("accountHealth");
if (health) { health.textContent = account.error || (accountIsStale(account) ? "Оценка открытых позиций устарела. Дождитесь свежих котировок." : "Один счёт для всех виртуальных сделок. Реальные деньги бирж учитываются отдельно."); health.className = account.error || accountIsStale(account) ? "statusline neg" : "statusline"; }
for (const key of ["balance", "equity", "reserved", "free"]) {
const el = document.getElementById(`account-${key}`);
if (el) el.textContent = account[key] == null ? "—" : `${Number(account[key]).toFixed(2)} $`;
}
const rows = document.getElementById("accountJournal");
if (rows) rows.innerHTML = (account.journal || []).slice(0, 100).map(entry => `<tr><td>${entry.time ? mskFull(entry.time) : "—"}</td><td>${escapeHtml(entry.reason || entry.type || entry.action || "Операция")}</td><td class="${cls(Number(entry.amount || 0))}">${entry.amount == null ? "—" : money(entry.amount)}</td><td>${entry.balance == null ? "—" : Number(entry.balance).toFixed(2)}</td></tr>`).join("") || '<tr><td colspan="4" class="empty">Операций пока нет</td></tr>';
}
async function loadAccount() { renderAccount(await api("/api/account")); }
async function adjustAccount(direction) {
if (accountBusy) return;
const input = document.getElementById("accountDelta"), msg = document.getElementById("accountMsg");
const value = input.value.trim().replace(",", ".");
if (!/^\d+(?:\.\d{1,8})?$/.test(value) || !Number.isFinite(Number(value)) || Number(value) <= 0) {
msg.textContent = "Введите сумму больше 0, до 8 знаков после запятой."; return;
}
const [whole, fraction = ""] = value.split("."), decimals = fraction.replace(/0+$/, "");
const amount = `${direction < 0 ? "-" : ""}${whole.replace(/^0+(?=\d)/, "")}${decimals ? "." + decimals : ""}`;
if (accountData?.error || (direction < 0 && accountIsStale(accountData))) { msg.textContent = accountData.error || "Оценка открытых позиций устарела. Списание доступно после обновления котировок."; return; }
if (pendingAccountAdjustment && pendingAccountAdjustment.amount !== amount) {
msg.textContent = `Прошлая операция (${pendingAccountAdjustment.amount} $) не подтверждена. Повторите её с той же суммой: повторное списание или пополнение исключено по идентификатору.`; return;
}
const request = pendingAccountAdjustment || {amount, request_id: globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}`};
accountBusy = true; refreshConnection(); msg.textContent = "Сохраняю операцию…";
try {
// Keep the identifier only after freshness checks: a blocked command has not been sent.
if (!freshRead("/api/account")) { msg.textContent = "Нет свежих данных счёта. Дождитесь восстановления связи."; return; }
pendingAccountAdjustment = request;
const result = await api("/api/account/adjust", request);
pendingAccountAdjustment = null;
if (result.account) renderAccount(result.account);
msg.textContent = result.ok ? `${direction > 0 ? "Пополнено" : "Списано"}: ${Number(value).toFixed(2)} $. Виртуальные деньги.` : result.error || result.message || "Операция отклонена";
if (result.ok) input.value = "";
await poll(loadAccount);
} catch (_) {
msg.textContent = "Ответ не получен. Проверьте журнал. Повтор этой суммы использует тот же идентификатор и не проведёт операцию дважды.";
} finally { accountBusy = false; refreshConnection(); }
} }
function buildSettings() { function buildSettings() {
@@ -55,7 +234,12 @@ function buildSettings() {
}; };
make(document.getElementById("settingsMain"), MAIN_FIELDS); make(document.getElementById("settingsMain"), MAIN_FIELDS);
make(document.getElementById("settingsMore"), MORE_FIELDS); make(document.getElementById("settingsMore"), MORE_FIELDS);
document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => settingsDirty = true)); document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => {
settingsDirty = true;
document.getElementById("settingsMsg").textContent = "Есть несохранённые изменения — нажмите «Применить ко всем монетам»";
}));
if (typeof applyHelpHints === "function") applyHelpHints();
refreshConnection();
} }
function toggleMore() { function toggleMore() {
const m = document.getElementById("settingsMore"); const m = document.getElementById("settingsMore");
@@ -126,19 +310,27 @@ function renderTiles() {
<div class="plusicon">+</div><div class="route" style="text-align:center">сканер новых монет</div></div>`; <div class="plusicon">+</div><div class="route" style="text-align:center">сканер новых монет</div></div>`;
} }
async function loadState(rebuild) { async function loadState(rebuild) {
state = await api("/api/state"); const request = ++stateRequest, result = await api("/api/state");
if (request < stateApplied) return;
stateApplied = request; state = result;
renderAccount(state.account);
if (rebuild || !document.querySelector("header [data-k]")) buildSettings(); if (rebuild || !document.querySelector("header [data-k]")) buildSettings();
if ((!selected || (selected !== SCANNER && !state.coins.some(c => c.key === selected))) && state.coins.length) selected = state.coins[0].key; if ((!selected || (selected !== SCANNER && !state.coins.some(c => c.key === selected))) && state.coins.length) {
detailEpoch++; detail = null; selected = state.coins[0].key;
}
renderTiles(); renderTiles();
refreshConnection();
} }
function selectCoin(key) { function selectCoin(key) {
detailEpoch++; detailEpoch++;
invalidateRead(key === SCANNER ? "/api/scanner" : `/api/coin/${key}`);
pendingPolls.delete(loadDetail); pendingPolls.delete(loadScanner);
selected = key; localStorage.setItem("sim.coin", key); selected = key; localStorage.setItem("sim.coin", key);
seenOpen = new Set(); seenClosed = 0; detail = null; seenOpen = new Set(); seenClosed = 0; detail = null;
document.getElementById("center").textContent = "Загрузка выбранной монеты…"; document.getElementById("center").textContent = "Загрузка выбранной монеты…";
renderTiles(); refreshCenter(); if (state) renderTiles(); refreshCenter(); refreshConnection();
} }
function refreshCenter() { if (selected === SCANNER) loadScanner(); else loadDetail(); } function refreshCenter() { return poll(selected === SCANNER ? loadScanner : loadDetail); }
// --- scanner panel ------------------------------------------------------------------------------- // --- scanner panel -------------------------------------------------------------------------------
const SCANNER = "__scanner__"; const SCANNER = "__scanner__";
@@ -169,12 +361,14 @@ function scannerSkeleton() {
scannerBuilt = true; scannerBuilt = true;
} }
async function loadScanner() { async function loadScanner() {
if (selected !== SCANNER || tab !== "sim") return;
const epoch = detailEpoch;
if (!document.getElementById("scRows")) scannerSkeleton(); if (!document.getElementById("scRows")) scannerSkeleton();
const s = await api("/api/scanner"); const s = await api("/api/scanner");
if (selected !== SCANNER || !document.getElementById("scRows")) return; if (selected !== SCANNER || epoch !== detailEpoch || tab !== "sim" || !document.getElementById("scRows")) return;
if (s.error) { document.getElementById("scMsg").textContent = s.error; return; } if (s.error) { document.getElementById("scMsg").textContent = s.error; return; }
document.getElementById("scStart").disabled = s.running; setControlDisabled(document.getElementById("scStart"), s.running);
document.getElementById("scStop").disabled = !s.running; setControlDisabled(document.getElementById("scStop"), !s.running);
document.getElementById("scAuto").checked = s.auto_add; document.getElementById("scAuto").checked = s.auto_add;
document.getElementById("scState").innerHTML = s.running document.getElementById("scState").innerHTML = s.running
? `<span class="pos">● сканер работает</span> · циклов ${s.cycles}` : `<span class="mut">■ сканер остановлен</span> · циклов ${s.cycles}`; ? `<span class="pos">● сканер работает</span> · циклов ${s.cycles}` : `<span class="mut">■ сканер остановлен</span> · циклов ${s.cycles}`;
@@ -190,17 +384,27 @@ async function loadScanner() {
<td>${c.dex_pool}</td><td>${c.lag}</td><td class="${cls(parseFloat(c.follow))}">${c.follow}%</td><td>${c.hit}</td> <td>${c.dex_pool}</td><td>${c.lag}</td><td class="${cls(parseFloat(c.follow))}">${c.follow}%</td><td>${c.hit}</td>
<td>${c.t_stat}</td><td class="mut">${c.last_lead || c.last_time}</td><td>${action}</td></tr>`; <td>${c.t_stat}</td><td class="mut">${c.last_lead || c.last_time}</td><td>${action}</td></tr>`;
}).join("") || '<tr><td colspan="12" class="empty">Пока нет результатов — запустите сканер; первый цикл ≈ 20 минут</td></tr>'; }).join("") || '<tr><td colspan="12" class="empty">Пока нет результатов — запустите сканер; первый цикл ≈ 20 минут</td></tr>';
refreshConnection();
} }
async function scanner(action) { async function scanner(action) {
const body = action === "config" ? {auto_add: document.getElementById("scAuto").checked} const body = action === "config" ? {auto_add: document.getElementById("scAuto").checked}
: {minutes: document.getElementById("scMin").value, coins: document.getElementById("scCoins").value}; : {minutes: document.getElementById("scMin").value, coins: document.getElementById("scCoins").value};
await api(`/api/scanner/${action}`, body); if (action === "start") {
setTimeout(loadScanner, 1200); body.minutes = Number(String(body.minutes).replace(",", ".")); body.coins = Number(body.coins);
if (!Number.isFinite(body.minutes) || body.minutes <= 0 || !Number.isInteger(body.coins) || body.coins < 1 || body.coins > 13) {
document.getElementById("scMsg").textContent = "Минут на цикл — число больше 0; монет за цикл — целое число от 1 до 13."; return;
}
}
const epoch = detailEpoch;
const result = await api(`/api/scanner/${action}`, body);
if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = result.error || result.message || "Команда подтверждена";
setTimeout(() => { if (selected === SCANNER && epoch === detailEpoch) poll(loadScanner); }, 1200);
} }
async function addCoin(symbol) { async function addCoin(symbol) {
const epoch = detailEpoch;
const r = await api("/api/scanner/add", {symbol}); const r = await api("/api/scanner/add", {symbol});
document.getElementById("scMsg").innerHTML = r.ok ? `<span class="pos">${r.message}</span>` : `<span class="neg">${r.error}</span>`; if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = r.message || r.error || "";
await loadState(); loadScanner(); await loadState(); if (selected === SCANNER && epoch === detailEpoch) await loadScanner();
} }
function centerSkeleton() { function centerSkeleton() {
@@ -222,7 +426,7 @@ function centerSkeleton() {
<button class="start" id="btnStart" onclick="trade('start')">▶ Старт</button> <button class="start" id="btnStart" onclick="trade('start')">▶ Старт</button>
<button class="stop" id="btnStop" onclick="trade('stop')">■ Стоп</button> <button class="stop" id="btnStop" onclick="trade('stop')">■ Стоп</button>
<button onclick="closePos()">Закрыть все позиции</button> <button onclick="closePos()">Закрыть все позиции</button>
<button onclick="resetCoin()" title="Обнулить сделки, баланс и открытые позиции этой пары">↺ Сбросить статистику</button> <button onclick="resetCoin()" title="Очистить статистику пары без изменения общего виртуального счёта; открытые позиции блокируют сброс">↺ Сбросить статистику</button>
<button id="btnReal" onclick="coinReal()" title="Настоящие ордера по этой монете с API-ключами её биржи">…</button> <button id="btnReal" onclick="coinReal()" title="Настоящие ордера по этой монете с API-ключами её биржи">…</button>
<span class="statusline" id="cMsg"></span> <span class="statusline" id="cMsg"></span>
</div> </div>
@@ -240,10 +444,10 @@ function centerSkeleton() {
function setRange(s) { range = s; localStorage.setItem("sim.range", s); document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === s)); drawChart(); } function setRange(s) { range = s; localStorage.setItem("sim.range", s); document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === s)); drawChart(); }
async function trade(action) { if (!coinReady()) return; const key = detail.key; await api(`/api/coin/${key}/${action}`, {}); loadDetail(); loadState(); } async function trade(action) { if (!coinReady()) return; const key = detail.key; await api(`/api/coin/${key}/${action}`, {}); loadDetail(); loadState(); }
async function resetCoin() { async function resetCoin() {
if (!coinReady() || !confirm(`Сбросить статистику ${detail.symbol} (${detail.leader} → ${detail.follower})?\nСделки, баланс и открытые позиции этой пары будут обнулены.`)) return; if (!coinReady() || !confirm(`Сбросить статистику ${detail.symbol} (${detail.leader} → ${detail.follower})?\nИстория этой пары будет очищена. Общий виртуальный счёт не меняется. При открытых позициях сброс недоступен.`)) return;
const r = await api(`/api/coin/${selected}/reset`, {}); const r = await api(`/api/coin/${selected}/reset`, {});
document.getElementById("cMsg").textContent = r.message || ""; if (document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || "";
seenOpen = new Set(); seenClosed = 0; if (r.ok) { seenOpen = new Set(); seenClosed = 0; }
loadDetail(); loadState(); loadDetail(); loadState();
} }
async function removeCoin(key) { async function removeCoin(key) {
@@ -262,12 +466,12 @@ function coinReady() { return !!detail && detail.key === selected; }
async function closePos(uid, key = detail?.key) { async function closePos(uid, key = detail?.key) {
if (!coinReady() || key !== selected) return; if (!coinReady() || key !== selected) return;
const r = await api(`/api/coin/${key}/close${uid ? "/" + uid : ""}`, {}); const r = await api(`/api/coin/${key}/close${uid ? "/" + uid : ""}`, {});
if (key === selected && document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.message || ""; if (key === selected && document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || "";
loadDetail(); loadDetail();
} }
async function loadDetail() { async function loadDetail() {
if (!selected || selected === SCANNER) return; if (tab !== "sim" || !selected || selected === SCANNER) return;
const key = selected, epoch = detailEpoch, request = ++detailRequest; const key = selected, epoch = detailEpoch, request = ++detailRequest;
const d = await api(`/api/coin/${key}`); const d = await api(`/api/coin/${key}`);
if (key !== selected || epoch !== detailEpoch || request < detailApplied) return; if (key !== selected || epoch !== detailEpoch || request < detailApplied) return;
@@ -312,7 +516,7 @@ async function loadDetail() {
]; ];
} else { } else {
stats = [ stats = [
["Баланс", d.balance.toFixed(2) + " $", ""], ["Сделок", d.trades, ""], ["В плюс", winPct, ""], ["Общий виртуальный баланс", accountData ? Number(accountData.balance).toFixed(2) + " $" : "—", ""], ["Сделок", d.trades, ""], ["В плюс", winPct, ""],
["Итог", money(d.net), cls(d.net)], ["Комиссии", d.fees.toFixed(4) + " $", ""], ["Итог", money(d.net), cls(d.net)], ["Комиссии", d.fees.toFixed(4) + " $", ""],
["Открыто", `${d.open} · ${money(d.unrealized)}`, cls(d.unrealized)], ["Открыто", `${d.open} · ${money(d.unrealized)}`, cls(d.unrealized)],
]; ];
@@ -324,12 +528,13 @@ async function loadDetail() {
["Подходит для сделок", suitability(d).html, ""]); ["Подходит для сделок", suitability(d).html, ""]);
if (state && state.settings.auto_tp) stats.push(["Прогноз", `${d.forecast.toFixed(3)}%`, ""]); if (state && state.settings.auto_tp) stats.push(["Прогноз", `${d.forecast.toFixed(3)}%`, ""]);
document.getElementById("stats").innerHTML = stats.map(([k, v, c]) => `<div class="stat"><div class="k">${k}</div><div class="v ${c}">${v}</div></div>`).join(""); document.getElementById("stats").innerHTML = stats.map(([k, v, c]) => `<div class="stat"><div class="k">${k}</div><div class="v ${c}">${v}</div></div>`).join("");
document.getElementById("btnStart").disabled = d.running; setControlDisabled(document.getElementById("btnStart"), d.running);
document.getElementById("btnStop").disabled = !d.running; setControlDisabled(document.getElementById("btnStop"), !d.running);
document.getElementById("cStatus").textContent = (d.running ? "● сделки открываются · " : "■ новые сделки остановлены (цены и прогноз работают) · ") + d.status; document.getElementById("cStatus").textContent = (d.running ? "● сделки открываются · " : "■ новые сделки остановлены (цены и прогноз работают) · ") + d.status;
if (d.message) document.getElementById("cMsg").textContent = d.message; if (d.message) document.getElementById("cMsg").textContent = d.message;
renderRows(d); renderRows(d);
drawChart(); drawChart();
refreshConnection();
} }
function renderRows(d) { function renderRows(d) {
@@ -494,14 +699,18 @@ function showTab(name) {
document.getElementById("tabSim").classList.toggle("on", name === "sim"); document.getElementById("tabSim").classList.toggle("on", name === "sim");
document.getElementById("tabArb").classList.toggle("on", name === "basis"); document.getElementById("tabArb").classList.toggle("on", name === "basis");
document.getElementById("tabReal").classList.toggle("on", name === "real"); document.getElementById("tabReal").classList.toggle("on", name === "real");
if (name === "basis") loadBasis(); if (name === "basis") poll(loadBasis);
if (name === "real") { realBuilt = false; loadReal(); } if (name === "real") { realBuilt = false; poll(loadReal); }
if (name === "sim") refreshCenter();
refreshConnection();
} }
// --- real trading: keys, switches, journal ------------------------------------------------------- // --- real trading: keys, switches, journal -------------------------------------------------------
let real = null, realBuilt = false; let real = null, realBuilt = false;
async function loadReal() { async function loadReal() {
real = await api("/api/real"); const request = ++realRequest, result = await api("/api/real");
if (request < realApplied) return;
realApplied = request; real = result;
const s = real.simulator; const s = real.simulator;
const tpsl = document.getElementById("simRealTpsl"); const tpsl = document.getElementById("simRealTpsl");
if (document.activeElement !== tpsl) tpsl.checked = s.exchange_tpsl !== false; if (document.activeElement !== tpsl) tpsl.checked = s.exchange_tpsl !== false;
@@ -556,8 +765,8 @@ async function keyCheck(ex) {
} }
async function keyDelete(ex) { async function keyDelete(ex) {
if (!confirm("Удалить сохранённые ключи этой биржи?")) return; if (!confirm("Удалить сохранённые ключи этой биржи?")) return;
await api(`/api/real/keys/${ex}/delete`, {}); const r = await api(`/api/real/keys/${ex}/delete`, {});
document.getElementById(`kmsg-${ex}`).textContent = "удалены"; document.getElementById(`kmsg-${ex}`).textContent = r.ok ? "удалены" : r.error || r.message || "Удаление не подтверждено";
loadReal(); loadReal();
} }
async function coinReal() { async function coinReal() {
@@ -701,13 +910,18 @@ async function crossToggle(ex, on) {
} }
async function crossFeesSave() { async function crossFeesSave() {
if (!basisReady()) return; if (!basisReady()) return;
const venue = bxVenue, epoch = bxEpoch;
const fees = {}, limits = {}; const fees = {}, limits = {};
document.querySelectorAll("#cxBal input[data-cxfee]").forEach(el => { document.querySelectorAll("#cxBal input[data-cxfee]").forEach(el => {
const [e, leg] = el.dataset.cxfee.split("|"); (fees[e] = fees[e] || {})[leg] = el.value; }); const [e, leg] = el.dataset.cxfee.split("|"); (fees[e] = fees[e] || {})[leg] = el.value; });
document.querySelectorAll("#cxBal input[data-cxlimit]").forEach(el => limits[el.dataset.cxlimit] = el.value); document.querySelectorAll("#cxBal input[data-cxlimit]").forEach(el => limits[el.dataset.cxlimit] = el.value);
const r = await api(`/api/basis/${bxVenue}/settings`, {fees, limits}); const r = await api(`/api/basis/${venue}/settings`, {fees, limits});
if (venue !== bxVenue || epoch !== bxEpoch) return;
document.getElementById("cxBalMsg").textContent = r.ok ? "комиссии и лимиты сделок сохранены" : r.error; document.getElementById("cxBalMsg").textContent = r.ok ? "комиссии и лимиты сделок сохранены" : r.error;
if (r.ok) document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => delete el.dataset.dirty); if (r.ok) {
document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => delete el.dataset.dirty);
rememberBasisDraft();
}
loadBasis(); loadBasis();
} }
const CX_ROWS_HEAD = `<tr><th data-b="base">Монета</th><th data-b="kind_name">Тип</th><th data-b="spot_ex">Покупка на</th><th data-b="fut_ex">Продажа / шорт на</th> const CX_ROWS_HEAD = `<tr><th data-b="base">Монета</th><th data-b="kind_name">Тип</th><th data-b="spot_ex">Покупка на</th><th data-b="fut_ex">Продажа / шорт на</th>
@@ -724,6 +938,29 @@ const CX_POS_HEAD = `<tr><th>Время (МСК)</th><th>Монета</th><th>Т
<th>Funding $</th><th>Комиссии $</th><th>Если закрыть сейчас</th><th></th></tr>`; <th>Funding $</th><th>Комиссии $</th><th>Если закрыть сейчас</th><th></th></tr>`;
let bxHeads = null; let bxHeads = null;
let bxVenue = ["cross", "cross_real"].includes(localStorage.getItem("bx.venue")) ? localStorage.getItem("bx.venue") : "cross", bx = null, bxBuilt = false, bxDirty = false; let bxVenue = ["cross", "cross_real"].includes(localStorage.getItem("bx.venue")) ? localStorage.getItem("bx.venue") : "cross", bx = null, bxBuilt = false, bxDirty = false;
const basisDrafts = new Map();
function rememberBasisDraft() {
if (!bxBuilt) return;
const fields = {};
document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => {
if (!el.dataset.bx && !el.dataset.dirty) return;
if (el.dataset.bx && !bxDirty) return;
const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`;
fields[key] = el.type === "checkbox" ? el.checked : el.value;
});
if (Object.keys(fields).length) basisDrafts.set(bxVenue, fields); else basisDrafts.delete(bxVenue);
}
function restoreBasisDraft() {
const draft = basisDrafts.get(bxVenue);
if (!draft) return;
document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => {
const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`;
if (!(key in draft)) return;
if (el.type === "checkbox") el.checked = draft[key]; else el.value = draft[key];
if (el.dataset.bx) bxDirty = true; else el.dataset.dirty = "1";
});
document.getElementById("bxMsg").textContent = "Восстановлены несохранённые изменения этого режима";
}
let bxSort = localStorage.getItem("bx.sort") || "entry_gap"; let bxSort = localStorage.getItem("bx.sort") || "entry_gap";
const BX_FIELDS = [ const BX_FIELDS = [
["amount", "Сумма сделки, $"], ["min_gap_pct", "Мин. расхождение для входа, %"], ["max_gap_pct", "Макс. расхождение, %"], ["amount", "Сумма сделки, $"], ["min_gap_pct", "Мин. расхождение для входа, %"], ["max_gap_pct", "Макс. расхождение, %"],
@@ -743,13 +980,15 @@ function bxTabs() {
: `<button disabled title="пока не подключена">${n} · скоро</button>`).join(" "); : `<button disabled title="пока не подключена">${n} · скоро</button>`).join(" ");
} }
function bxSelect(k) { function bxSelect(k) {
rememberBasisDraft();
invalidateRead(`/api/basis?ex=${k}`); pendingPolls.delete(loadBasis);
bxEpoch++; bx = null; bxDataVenue = null; bxDirty = false; bxEpoch++; bx = null; bxDataVenue = null; bxDirty = false;
setBasisReady(false); setBasisReady(false);
document.getElementById("bxPos").innerHTML = ""; document.getElementById("bxPos").innerHTML = "";
document.getElementById("bxMsg").textContent = "Загрузка выбранного режима…"; document.getElementById("bxMsg").textContent = "Загрузка выбранного режима…";
bxVenue = k; localStorage.setItem("bx.venue", k); bxBuilt = false; bxVenue = k; localStorage.setItem("bx.venue", k); bxBuilt = false;
bxSort = "net_pct"; // the net profit decides the entry — sorted by it bxSort = "net_pct"; // the net profit decides the entry — sorted by it
bxTabs(); loadBasis(); bxTabs(); poll(loadBasis); refreshConnection();
} }
function bxBuild(s) { function bxBuild(s) {
const cross = true; // «Арбитраж»: one mode, simulation or real const cross = true; // «Арбитраж»: one mode, simulation or real
@@ -780,14 +1019,22 @@ function bxBuild(s) {
document.querySelectorAll("#basisView th[data-b]").forEach(th => th.onclick = () => { document.querySelectorAll("#basisView th[data-b]").forEach(th => th.onclick = () => {
bxSort = th.dataset.b; localStorage.setItem("bx.sort", bxSort); renderBasis(); }); bxSort = th.dataset.b; localStorage.setItem("bx.sort", bxSort); renderBasis(); });
bxBuilt = true; bxDirty = false; bxBuilt = true; bxDirty = false;
restoreBasisDraft();
if (typeof applyHelpHints === "function") applyHelpHints();
} }
async function basisSave() { async function basisSave() {
if (!basisReady()) return; if (!basisReady()) return;
const body = {}; const body = {};
document.querySelectorAll("#bxSettings input").forEach(el => body[el.dataset.bx] = el.type === "checkbox" ? el.checked : el.value); document.querySelectorAll("#bxSettings input").forEach(el => body[el.dataset.bx] = el.type === "checkbox" ? el.checked : el.value);
const r = await api(`/api/basis/${bxVenue}/settings`, body); const venue = bxVenue, epoch = bxEpoch;
const r = await api(`/api/basis/${venue}/settings`, body);
if (venue !== bxVenue || epoch !== bxEpoch) return;
document.getElementById("bxMsg").textContent = r.ok ? "сохранено" : r.error; document.getElementById("bxMsg").textContent = r.ok ? "сохранено" : r.error;
if (r.ok) { bxBuilt = false; loadBasis(); } if (r.ok) {
bxDirty = false;
rememberBasisDraft(); // Fee/limit drafts belong to their separate Save button.
bxBuilt = false; await loadBasis();
}
} }
async function basisRun() { async function basisRun() {
if (!basisReady()) return; if (!basisReady()) return;
@@ -807,7 +1054,7 @@ async function basisRun() {
async function basisClose(uid, venue = bxDataVenue) { async function basisClose(uid, venue = bxDataVenue) {
if (!basisReady() || venue !== bxVenue) return; if (!basisReady() || venue !== bxVenue) return;
const r = await api(`/api/basis/${venue}/close${uid ? "/" + uid : ""}`, {}); const r = await api(`/api/basis/${venue}/close${uid ? "/" + uid : ""}`, {});
if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.message || ""; if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || "";
loadBasis(); loadBasis();
} }
async function basisAdopt() { async function basisAdopt() {
@@ -820,13 +1067,15 @@ async function basisAdopt() {
} }
async function basisReset() { async function basisReset() {
if (!basisReady()) return; if (!basisReady()) return;
if (!confirm("Сбросить статистику спот-фьюч? Сделки и открытые позиции будут удалены.")) return; if (!confirm("Сбросить статистику этого режима? История закрытых сделок будет очищена. Общий виртуальный счёт не меняется; при открытых позициях сброс недоступен.")) return;
await api(`/api/basis/${bxVenue}/reset`, {}); loadBasis(); const venue = bxVenue, r = await api(`/api/basis/${venue}/reset`, {});
if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || (r.ok ? "Статистика сброшена" : "Сброс отклонён");
await loadBasis();
} }
function basisReady() { return !!bx && bxDataVenue === bxVenue; } function basisReady() { return !!bx && bxDataVenue === bxVenue; }
function setBasisReady(ready) { function setBasisReady(ready) {
document.querySelectorAll("#basisView button, #basisView input").forEach(el => { document.querySelectorAll("#basisView button, #basisView input").forEach(el => {
if (!el.closest("#bxTabs")) el.disabled = !ready; if (!el.closest("#bxTabs")) setControlDisabled(el, !ready);
}); });
} }
async function loadBasis() { async function loadBasis() {
@@ -838,9 +1087,11 @@ async function loadBasis() {
bxApplied = request; bxApplied = request;
if (r.error) { document.getElementById("bxStatus").textContent = r.error; return; } if (r.error) { document.getElementById("bxStatus").textContent = r.error; return; }
bx = r; bxDataVenue = venue; bx = r; bxDataVenue = venue;
renderAccount(r.paper_account);
if (!bxBuilt) bxBuild(bx.settings); if (!bxBuilt) bxBuild(bx.settings);
renderBasis(); renderBasis();
setBasisReady(true); setBasisReady(true);
refreshConnection();
} }
const dollars = v => v == null ? "—" : (v >= 0 ? "+" : "−") + Math.abs(v).toFixed(2); const dollars = v => v == null ? "—" : (v >= 0 ? "+" : "−") + Math.abs(v).toFixed(2);
const hold = s => s < 60 ? `${s.toFixed(0)} с` : s < 3600 ? `${(s / 60).toFixed(1)} мин` : `${(s / 3600).toFixed(1)} ч`; const hold = s => s < 60 ? `${s.toFixed(0)} с` : s < 3600 ? `${(s / 60).toFixed(1)} мин` : `${(s / 3600).toFixed(1)} ч`;
@@ -1215,10 +1466,26 @@ function renderArb() {
} }
function toggleArb(coin) { arbOpen.has(coin) ? arbOpen.delete(coin) : arbOpen.add(coin); renderArb(); } function toggleArb(coin) { arbOpen.has(coin) ? arbOpen.delete(coin) : arbOpen.add(coin); renderArb(); }
window.addEventListener("resize", drawChart); window.addEventListener("resize", drawChart);
window.addEventListener("unhandledrejection", event => {
commandNotice(event.reason?.userMessage || event.reason?.message || "Не удалось выполнить действие. Проверьте связь и состояние сервера.", true);
event.preventDefault();
});
window.addEventListener("beforeunload", event => {
rememberBasisDraft();
if (settingsDirty || basisDrafts.size) { event.preventDefault(); event.returnValue = ""; }
});
function startApplication() {
// Register recovery before the first request: a failed initial GET must never stop polling.
setInterval(() => poll(loadState), 2000);
setInterval(() => poll(loadDetail), 1000);
setInterval(() => poll(loadBasis), 500);
setInterval(() => poll(loadReal), 3000);
setInterval(() => poll(loadAccount), 2000);
setInterval(() => { if (selected === SCANNER) poll(loadScanner); }, 5000);
setInterval(refreshConnection, 1000);
poll(async () => { await loadState(true); await refreshCenter(); });
poll(loadReal); poll(loadAccount); showTab(tab);
}
(async () => { (async () => {
await loadState(true); refreshCenter(); showTab(tab); startApplication();
setInterval(loadBasis, 500); // the hot links change every 0.5 s
loadReal(); setInterval(loadReal, 3000);
setInterval(loadState, 2000); setInterval(loadDetail, 1000);
setInterval(() => { if (selected === SCANNER) loadScanner(); }, 5000);
})(); })();
+139
View File
@@ -0,0 +1,139 @@
// Local reference content. Keys are checked against the controls in web_context.test.cjs.
const HELP_SETTINGS = {
sim: {
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: {
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: {
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();
});
}
+35 -1
View File
@@ -11,8 +11,40 @@
<button id="tabSim" class="tab on" onclick="showTab('sim')">Симулятор</button> <button id="tabSim" class="tab on" onclick="showTab('sim')">Симулятор</button>
<button id="tabArb" class="tab" onclick="showTab('basis')">Арбитраж</button> <button id="tabArb" class="tab" onclick="showTab('basis')">Арбитраж</button>
<button id="tabReal" class="tab" onclick="showTab('real')">Реальная торговля · API-ключи</button> <button id="tabReal" class="tab" onclick="showTab('real')">Реальная торговля · API-ключи</button>
<button id="helpBtn" class="help-btn" onclick="helpOpen()" aria-haspopup="dialog" aria-controls="helpDialog">Справка</button>
<button id="calcBtn" class="calcbtn" onclick="calcToggle()" title="Сколько денег нужно на бирже под ставку, число сделок и запас до ликвидации">🧮 Калькулятор бюджета</button> <button id="calcBtn" class="calcbtn" onclick="calcToggle()" title="Сколько денег нужно на бирже под ставку, число сделок и запас до ликвидации">🧮 Калькулятор бюджета</button>
</nav> </nav>
<div class="system-status" aria-live="polite">
<strong id="modeStatus" class="mode-status">СИМУЛЯЦИЯ · общий виртуальный счёт</strong>
<span id="connectionStatus" class="connection-status disconnected">Подключение к серверу…</span>
</div>
<div id="commandNotice" class="command-notice" role="status" hidden></div>
<section id="paperAccount" class="paper-account" aria-labelledby="accountTitle">
<div class="account-heading"><h2 id="accountTitle">Общий виртуальный счёт</h2><span class="paper-badge">ВИРТУАЛЬНЫЕ ДЕНЬГИ</span></div>
<div class="account-metrics">
<div><span>Баланс</span><strong id="account-balance">—</strong><small>Проведённые операции и результат</small></div>
<div><span>Капитал (Equity)</span><strong id="account-equity">—</strong><small>Баланс + результат открытых позиций</small></div>
<div><span>Зарезервировано</span><strong id="account-reserved">—</strong><small>Средства под открытые сделки</small></div>
<div><span>Свободно</span><strong id="account-free">—</strong><small>Доступно для следующих входов</small></div>
</div>
<p id="accountHealth" class="statusline">Один счёт для всех виртуальных сделок. Реальные деньги бирж учитываются отдельно.</p>
<div class="controls">
<div class="field"><label for="accountDelta">Сумма изменения, $</label><input id="accountDelta" inputmode="decimal" placeholder="Например 100" autocomplete="off"></div>
<button class="primary" data-command="account" data-account-direction="1" onclick="adjustAccount(1)">Пополнить</button>
<button data-command="account" data-account-direction="-1" onclick="adjustAccount(-1)">Списать</button>
<span id="accountMsg" class="statusline" role="status"></span>
</div>
<details class="account-journal"><summary>Журнал виртуального счёта</summary>
<div class="tablewrap"><table><thead><tr><th>Время (МСК)</th><th>Операция</th><th>Изменение, $</th><th>Баланс, $</th></tr></thead><tbody id="accountJournal"><tr><td colspan="4" class="empty">Загрузка…</td></tr></tbody></table></div>
</details>
</section>
<dialog id="helpDialog" class="help-dialog" aria-labelledby="helpTitle">
<div class="help-heading"><div><h2 id="helpTitle">Справка</h2><p>Термины, режимы и все настройки интерфейса</p></div><button class="help-close" onclick="helpClose()" aria-label="Закрыть справку">×</button></div>
<label for="helpSearch" class="help-search-label">Поиск по названию, термину или ключу настройки</label>
<input id="helpSearch" class="help-search" type="search" placeholder="Например: плечо, свободно, IOC, stop_loss_pct" autocomplete="off" oninput="renderHelp()">
<p id="helpCount" class="statusline" role="status"></p>
<div id="helpContent" class="help-content"></div>
</dialog>
<div id="calcPanel" class="calcpanel" style="display:none"> <div id="calcPanel" class="calcpanel" style="display:none">
<div class="calchead"><b>Калькулятор бюджета</b><button class="x" onclick="calcToggle()" title="Закрыть">×</button></div> <div class="calchead"><b>Калькулятор бюджета</b><button class="x" onclick="calcToggle()" title="Закрыть">×</button></div>
<div class="calcgrid"> <div class="calcgrid">
@@ -49,7 +81,7 @@
<div class="statusline" id="bxStatus" style="margin-top:6px">загружаю…</div></div> <div class="statusline" id="bxStatus" style="margin-top:6px">загружаю…</div></div>
<div class="controls"><button id="bxRun" onclick="basisRun()">…</button> <div class="controls"><button id="bxRun" onclick="basisRun()">…</button>
<button id="bxReal" onclick="basisReal()" title="Настоящие ордера с API-ключами этой биржи">…</button> <button id="bxReal" onclick="basisReal()" title="Настоящие ордера с API-ключами этой биржи">…</button>
<button onclick="basisReset()" title="Удалить сделки и открытые позиции">↺ Сбросить статистику</button></div></div> <button onclick="basisReset()" title="Очистить историю закрытых сделок; общий виртуальный счёт не меняется">↺ Сбросить статистику</button></div></div>
<div class="card"> <div class="card">
<div class="controls" id="bxSettings"></div> <div class="controls" id="bxSettings"></div>
<div class="controls" style="margin-top:8px"> <div class="controls" style="margin-top:8px">
@@ -131,6 +163,8 @@
<section class="center" id="center"><div class="empty">Выберите монету слева</div></section> <section class="center" id="center"><div class="empty">Выберите монету слева</div></section>
</main> </main>
</div> </div>
<script src="/static/help-data.js"></script>
<script src="/static/help.js"></script>
<script src="/static/app.js"></script> <script src="/static/app.js"></script>
</body> </body>
</html> </html>
+251 -40
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
@@ -25,6 +26,10 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from request_security import trusted_request 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
@@ -115,6 +120,8 @@ PAGE = ROOT / "web_sim.html"
STATIC_ASSETS = { STATIC_ASSETS = {
"/static/app.js": (ROOT / "web" / "app.js", "text/javascript"), "/static/app.js": (ROOT / "web" / "app.js", "text/javascript"),
"/static/app.css": (ROOT / "web" / "app.css", "text/css"), "/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)
@@ -129,6 +136,16 @@ COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings)
"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:
@@ -221,16 +238,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
@@ -239,11 +261,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()
@@ -259,12 +291,64 @@ 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
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:
ps = self.paper.settings ps = self.paper.settings
@@ -294,10 +378,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)
@@ -309,6 +399,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:
@@ -317,12 +410,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 = ""
@@ -332,14 +430,24 @@ 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}"
return f"закрыто позиций: {closed}" return f"закрыто позиций: {closed}"
def _auto_stop(self, now: float) -> None: def _auto_stop(self, now: float) -> None:
@@ -418,13 +526,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,
@@ -469,62 +578,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"]))}
@@ -620,7 +787,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
@@ -656,6 +823,8 @@ class Handler(BaseHTTPRequestHandler):
self._send(200, asset.read_bytes(), kind) 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)
@@ -671,7 +840,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()))
@@ -694,17 +866,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
@@ -743,7 +940,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
@@ -792,17 +991,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
@@ -819,6 +1023,11 @@ def local_request(handler) -> bool:
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)
@@ -826,6 +1035,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
@@ -839,7 +1050,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()
@@ -848,6 +1058,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()