diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000..ff2ddd5
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,25 @@
+name: Offline regression tests
+on:
+ push:
+ pull_request:
+permissions:
+ contents: read
+jobs:
+ windows:
+ runs-on: windows-latest
+ strategy:
+ matrix:
+ python-version: ['3.11', '3.12', '3.13']
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ cache: pip
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+ - run: python -m pip install -r requirements.txt
+ - run: python -B scripts/run_tests.py
+ - run: node --test tests/web_context.test.cjs
+ - run: python -B -c "import main, websocket, numpy"
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..48496e9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,23 @@
+__pycache__/
+*.py[cod]
+.venv/
+*.log
+*.tmp
+web_sim_data/
+scalp_recordings/
+historical_reports/
+*.sqlite3*
+settings.json
+account_state.json
+*credentials*.json
+*credentials*.bin
+*keys*.bin
+lead_connections.json
+lead_paper_state.json
+lead_paper_trades.csv
+scalp_hint_journal.csv
+scalp_paper_state.json
+scalp_paper_trades.csv
+meme_matcher/autoscan_state.json
+meme_matcher/autoscan_history.csv
+meme_matcher/autoscan_config.json
diff --git a/README.md b/README.md
index ddcd8b3..018e13c 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,8 @@ Standalone real-time simulator and optional Bybit USDT-perpetual trading bot.
## Run on Windows
+Python 3.11+; dependencies are pinned in `requirements.txt`. Recovery semantics, module layout and offline tests: [docs/reliability.md](docs/reliability.md).
+
```powershell
cd C:\arb\RealtimePaperSimulator
py -3 -m pip install -r requirements.txt
@@ -142,12 +144,11 @@ the SHORT leg, funding per 8 h in $, the exit fees, a warning when the best pric
and the result in $ if the spread closes to zero / to its usual level, with the break-even spread (all fees: entry
and exit on both exchanges, plus the transfer fee when the transfer is taken into account).
-**Access from outside with a VPN on**: `run_web_sim.bat` starts two processes — the engine
-`py -3 web_sim.py --backend` (python.exe, 127.0.0.1:8766, needs the VPN for the exchanges) and the public page
-`pyw -3 web_proxy.py` (pythonw.exe, 0.0.0.0:8765, forwards everything to the engine). Add
-`…\Python312\pythonw.exe` to the VPN's app exclusions so answers to outside visitors leave through the home
-connection; forward TCP 8765 in the router and allow it in Windows Firewall. `py -3 web_sim.py` alone still serves
-the page itself on 0.0.0.0:8765 (`--local`: 127.0.0.1 only).
+**Local proxy with a VPN on**: `run_web_sim.bat` starts the engine on `127.0.0.1:8766`
+(`python.exe`) and the page proxy on `127.0.0.1:8765` (`pythonw.exe`). The page remains local even when
+`pythonw.exe` is excluded from the VPN. Both processes validate the original local Host and browser Origin;
+POST commands require the page's `X-Sim` header. The app is not configured for public internet hosting.
+`py -3 web_sim.py` serves the page directly on `127.0.0.1:8765`.
**Saved connections** («Подключение»): every leader + follower combination used is kept in `lead_connections.json`
(coin, KuCoin market/ticker or DEX pool, follower exchange and ticker) and can be picked again from the list; a new one
diff --git a/cross.py b/cross.py
index 82a1472..1ae3506 100644
--- a/cross.py
+++ b/cross.py
@@ -27,6 +27,7 @@ after each real trade they are replaced by what the exchanges actually charged,
from __future__ import annotations
import json
+from persistence import atomic_write_json
import queue
import threading
import time
@@ -595,9 +596,7 @@ class CrossEngine:
"trades": [asdict(t) for t in self.trades[-KEEP_TRADES:]], "next_uid": self.next_uid,
"fees": self.fees, "limits": self.limits, "baseline": self.baseline, "migrated": self.migrated,
"pending": {**self.recover, **self.pending}}
- tmp = self.file.with_suffix(".tmp")
- tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
- tmp.replace(self.file)
+ atomic_write_json(self.file, data)
def set_settings(self, values: dict) -> str:
with self.lock:
@@ -923,8 +922,9 @@ class CrossEngine:
s = self.settings
for base, info in list(self.recover.items()):
# an entry cut off by a stop of the program: whatever was opened becomes a position again
- if info.get("key") in self.links and base not in self.opening:
+ if (info.get("key") in self.links or info.get("link")) and base not in self.opening and time.time() >= info.get("retry_at", 0):
self.opening.add(base)
+ self.pending[base] = info
del self.recover[base]
self.jobs.put(("recover", base, info))
if s.real:
@@ -934,7 +934,7 @@ class CrossEngine:
# links itself); the hot links are refreshed in between by the hot watch
rows = self.candidates(now)
self.cand, self.cand_time = {r["key"]: r for r in rows}, now
- real_busy = s.real and (self.opening or now < self.real_pause_until)
+ real_busy = s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until)
if s.running and not real_busy: # real: the next trade only after the previous is confirmed
changed = self._entries(now, rows) or changed
if changed:
@@ -947,7 +947,7 @@ class CrossEngine:
for r in rows:
self.cand[r["key"]] = r
s = self.settings
- if s.running and not (s.real and (self.opening or now < self.real_pause_until)):
+ if s.running and not (s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until)):
if self._entries(now, rows):
self.save()
@@ -1226,8 +1226,91 @@ class CrossEngine:
elif kind in ("open", "recover"):
base = args[0].base if kind == "open" else args[0]
self.opening.discard(base)
- if self.pending.pop(base, None) is not None:
- self.save()
+ info = self.pending.pop(base, None)
+ if info is not None:
+ # Only preparation is certainly unsent. Every later stage survives errors and restart.
+ if info.get("phase") != "prepared":
+ info["retry_at"] = time.time() + 5
+ self.recover[base] = info
+ try:
+ self.save()
+ except (OSError, ValueError) as exc:
+ self.real_pause_until = time.time() + 60
+ self.real_pause_reason = f"не удалось сохранить восстановление: {exc}"
+
+ def _pending_update(self, base: str, **values) -> None:
+ with self.lock:
+ before = dict(self.pending[base])
+ self.pending[base].update(values)
+ try:
+ self.save()
+ except Exception:
+ self.pending[base] = before
+ raise
+
+ def _pending_done(self, base: str) -> None:
+ with self.lock:
+ pending, recovering = self.pending.pop(base, None), self.recover.pop(base, None)
+ self.last_close[base] = time.time()
+ try:
+ self.save()
+ except Exception:
+ if pending is not None:
+ self.pending[base] = pending
+ if recovering is not None:
+ self.recover[base] = recovering
+ raise
+
+ def _pending_problem(self, base: str, text: str) -> None:
+ with self.lock:
+ info = self.pending[base]
+ changed = info.get("error") != text
+ info["error"] = text
+ self.save()
+ if changed:
+ self._journal(base, "recover", False, text + "; новые реальные входы заблокированы")
+
+ def _cancel_entry(self, l: Link, cb, oid: str) -> dict | None:
+ """A cancel acknowledgement is not terminal confirmation; never hedge a still-working entry."""
+ import live
+ try:
+ state = cb.fut_order_status(l.fut_symbol, oid)
+ if state["final"]:
+ return state
+ except live.LiveError:
+ pass
+ try:
+ cb.fut_cancel(l.fut_symbol, oid)
+ except live.LiveError:
+ pass
+ try:
+ state = cb.fut_order_status(l.fut_symbol, oid)
+ if state["final"]:
+ return state
+ except live.LiveError:
+ pass
+ self._pending_problem(l.base, f"не подтверждена отмена входа {oid} на {l.fut_ex}; повторяю сверку")
+ return None
+
+ def _rollback_entry(self, l: Link, cb) -> None:
+ """Retain the durable entry until the exchange confirms the short has actually gone."""
+ import live
+ try:
+ held = cb.fut_position(l.fut_symbol)
+ if held < -1e-12:
+ try:
+ cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True)
+ except live.LiveError as exc:
+ if not exc.sent:
+ raise
+ held = cb.fut_position(l.fut_symbol)
+ if abs(held) > 1e-12:
+ raise live.LiveError(f"на фьючерсе осталось {held:+g} {l.base}")
+ except live.LiveError as exc:
+ self._pending_problem(l.base, f"откат входа не завершён: {exc}; повторяю закрытие")
+ return
+ self._pending_done(l.base)
+ self._journal(l.base, "recover", True, "откат входа завершён: биржа подтвердила отсутствие позиции")
@staticmethod
def _api_closed(error: str) -> bool:
@@ -1290,7 +1373,7 @@ class CrossEngine:
if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l):
return
self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual,
- "amount": amount}
+ "amount": amount, "link": asdict(l), "phase": "prepared"}
self.save()
notional = coins * l.fut_bid
fut_need = max(notional * self.FUT_NEED, equity_for(s.min_liq_pct, notional))
@@ -1330,14 +1413,21 @@ class CrossEngine:
# leaves nothing filled and nothing is bought on A; otherwise it waits «Лимитный вход: ждать, с»
hold = 0.0 if s.entry_ioc else max(0.0, s.limit_hold_s)
name = "IOC-шорт" if s.entry_ioc else "лимитный шорт"
+ self._pending_update(l.base, phase="limit_submitted")
try:
oid = cb.fut_limit(l.fut_symbol, "sell", coins, l.fut_bid)
except (live.LiveError, AttributeError) as exc:
+ if getattr(exc, "sent", False):
+ self._pending_update(l.base, order_id=getattr(exc, "order_id", ""))
+ self._pending_problem(l.base, f"результат лимитного входа неизвестен: {exc}")
+ return
+ self._pending_done(l.base)
self._journal(l.base, "open", False, f"{name} на {l.fut_ex} не выставлен: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
self._pause_if_balance(str(exc), l.fut_ex)
return
+ self._pending_update(l.base, order_id=oid)
st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False}
end = time.time() + hold
while True: # one look a second: the exchange's request limit
@@ -1349,25 +1439,19 @@ class CrossEngine:
break
time.sleep(1.0)
if not st["final"]:
- try:
- cb.fut_cancel(l.fut_symbol, oid)
- except live.LiveError:
- pass
- try:
- st = cb.fut_order_status(l.fut_symbol, oid)
- except live.LiveError:
- try:
- st = {**st, "coins": max(0.0, -cb.fut_position(l.fut_symbol))}
- except live.LiveError:
- pass
+ st = self._cancel_entry(l, cb, oid)
+ if st is None:
+ return
shorted, fut_price, fut_fee_usd = st["coins"], st["price"] or l.fut_bid, st["fee"]
if shorted <= 0:
+ self._pending_done(l.base)
self._journal(l.base, "open", False, f"{name} на {l.fut_ex} по {l.fut_bid:.10g} не исполнился"
f"{'' if s.entry_ioc else f' за {hold:g} с'} — снят, на {l.spot_ex} ничего не покупалось")
with self.lock:
self.last_close[l.base] = time.time()
return
else:
+ self._pending_update(l.base, phase="market_submitted")
try:
fut = cb.fut_order(l.fut_symbol, "sell", coins, reduce_only=False)
shorted, fut_price, fut_fee_usd, fut_exact = fut.coins, fut.price, fut.fee_usd, fut.exact
@@ -1379,6 +1463,11 @@ class CrossEngine:
except live.LiveError:
held = coins # unknown: assume open — the close is reduce-only
if held <= 0:
+ if getattr(exc, "sent", False):
+ self._pending_update(l.base, order_id=exc.order_id)
+ self._pending_problem(l.base, f"результат рыночного входа неизвестен: {exc}")
+ return
+ self._pending_done(l.base)
self._journal(l.base, "open", False, f"шорт на {l.fut_ex} не открыт: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
@@ -1386,6 +1475,7 @@ class CrossEngine:
return
shorted, fut_price = held, l.fut_bid
fut_fee_usd, fut_exact = held * l.fut_bid * fut_fee(l.fut_ex, self.fees, l.innovation) / 100, False
+ self._pending_update(l.base, phase="hedge_submitted", shorted=shorted)
# 2) the hedge: the same coins on spot on A (the buy fee is taken in coins: a little more USDT)
try:
buy = ca.spot_buy(l.base, shorted * l.spot_ask * (1 + a_fee / 100) * 1.003)
@@ -1397,20 +1487,18 @@ class CrossEngine:
except live.LiveError:
bought = 0.0
if bought <= 0:
- try:
- cb.fut_order(l.fut_symbol, "buy", shorted, reduce_only=True)
- text = f"шорт {shorted:g} на {l.fut_ex} открыт, но спот на {l.spot_ex} не куплен ({exc}); шорт закрыт"
- except live.LiveError as exc2:
- text = (f"шорт {shorted:g} на {l.fut_ex} открыт, спот на {l.spot_ex} не куплен ({exc}); ШОРТ НЕ "
- f"ЗАКРЫТ ({exc2}) — закройте вручную")
- self._journal(l.base, "open", False, text)
- with self.lock:
- self.last_close[l.base] = time.time()
- if self._api_closed(str(exc)): # PTB: tried 7 times, fees paid each time
+ if getattr(exc, "sent", False):
+ self._pending_problem(l.base, f"результат покупки спота неизвестен: {exc}; требуется сверка")
+ return
+ self._pending_update(l.base, phase="rollback")
+ self._rollback_entry(l, cb)
+ if self._api_closed(str(exc)):
self._not_tradable(l.base, f"биржа {l.spot_ex} не даёт торговать {l.base} через API: {exc}", 86400)
self._pause_if_balance(str(exc), l.spot_ex)
return
buy = live.Fill(bought, l.spot_ask, bought * l.spot_ask * a_fee / 100, exc.order_id, exact=False)
+ self._pending_update(l.base, phase="hedge_confirmed", buy=asdict(buy), shorted=shorted,
+ fut_price=fut_price, fut_fee=fut_fee_usd)
try:
free = ca.spot_free(l.base)
except live.LiveError:
@@ -1430,6 +1518,7 @@ class CrossEngine:
[l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]])
self.next_uid += 1
self.positions.append(pos)
+ self.pending.pop(l.base, None)
self.save()
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}%), "
@@ -1510,7 +1599,7 @@ class CrossEngine:
if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l):
return
self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual,
- "amount": amount}
+ "amount": amount, "link": asdict(l), "phase": "prepared"}
self.save()
if s.auto_transfer:
try:
@@ -1524,10 +1613,12 @@ class CrossEngine:
return
self._journal(l.base, "transfer", False, f"{l.spot_ex}: перевод не удался: {exc} — пробую без него")
# 1) sell the stock on B
+ self._pending_update(l.base, phase="spot_submitted", stock_before=have)
try:
sold = cb.spot_sell(l.base, coins)
except live.LiveError as exc:
if not getattr(exc, "sent", False):
+ self._pending_done(l.base)
self._journal(l.base, "open", False, f"продажа {l.base} на споте {l.fut_ex} не прошла: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
@@ -1543,6 +1634,8 @@ class CrossEngine:
else:
try:
cb.spot_buy(l.base, sold.coins * l.fut_ask * (1 + b_fee_pct / 100) * 1.003)
+ if cb.spot_free(l.base) >= have - 1e-9:
+ self._pending_done(l.base)
text = (f"{l.base} продан на {l.fut_ex}, но на {l.spot_ex} не куплен ({exc}); запас на "
f"{l.fut_ex} выкуплен обратно")
except live.LiveError as exc2:
@@ -1568,6 +1661,7 @@ class CrossEngine:
[l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]])
self.next_uid += 1
self.positions.append(pos)
+ self.pending.pop(l.base, None)
self.save()
self._journal(l.base, "open", True, f"спот-спот: продано {sold.coins:g} на {l.fut_ex} по {sold.price:.10g}, "
f"куплено {got:g} на {l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% "
@@ -1752,11 +1846,39 @@ class CrossEngine:
import live
with self.lock:
l = self.links.get(info.get("key", ""))
+ if l is None and info.get("link"):
+ l = Link(**info["link"])
+ already_owned = any(p.real and p.base == base for p in self.positions)
+ if already_owned or info.get("phase") == "prepared":
+ self._pending_done(base)
+ return
if l is None:
+ self._pending_problem(base, "нет сохранённых параметров незавершённой сделки")
+ return
+ phase = info.get("phase")
+ if not l.ss and phase in ("limit_submitted", "market_submitted", "rollback"):
+ cb = self.client_for(l.fut_ex)
+ if phase != "rollback":
+ oid = info.get("order_id")
+ if not oid:
+ self._pending_problem(base, "отправленный вход без ID: требуется ручная сверка ордеров биржи")
+ # Retain the intent even when flat; a delayed fill must not permit another entry.
+ held = cb.fut_position(l.fut_symbol)
+ if held < -1e-12:
+ cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True)
+ return
+ if self._cancel_entry(l, cb, oid) is None:
+ return
+ self._pending_update(base, phase="rollback")
+ self._rollback_entry(l, cb)
+ return
+ if phase == "hedge_submitted":
+ # Without an exchange order id, an unchanged spot balance does not prove rejection.
+ self._pending_problem(base, "незавершённая покупка спота: требуется ручная сверка обеих ног")
return
if l.ss: # a spot sale cannot be told apart from the user's own trades: say so, no guess
- self._journal(base, "open", False, f"после перезапуска: незавершённый вход спот-спот {l.spot_ex} → "
- f"{l.fut_ex} — проверьте {base} на обеих биржах вручную")
+ self._pending_problem(base, f"незавершённый вход спот-спот {l.spot_ex} → "
+ f"{l.fut_ex} — проверьте {base} на обеих биржах вручную")
return
try:
ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex)
@@ -1768,6 +1890,7 @@ class CrossEngine:
self._journal(base, "open", False, f"после перезапуска: не удалось проверить незавершённый вход: {exc}")
return
if short <= 0 and coins * l.spot_bid < 1.0:
+ self._pending_done(base)
self._journal(base, "open", True, "после перезапуска: незавершённый вход — на биржах ничего не открыто")
return
with self.lock:
@@ -1782,6 +1905,8 @@ class CrossEngine:
pos.retry_at, pos.usual = 0.0, 1e9
self.next_uid += 1
self.positions.append(pos)
+ self.pending.pop(base, None)
+ self.recover.pop(base, None)
self.save()
self._journal(base, "open", True, f"после перезапуска: найден незавершённый вход — шорт {short:g} на "
f"{l.fut_ex}, спот {coins:g} на {l.spot_ex}; ведётся программой")
@@ -1944,7 +2069,9 @@ class CrossEngine:
"cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.links),
"memes_source": "", "rows": rows[:300], "positions": positions,
"trades": [asdict(t) for t in reversed(closed[-200:])], "stats": stats,
- "real_pause": (f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)"
+ "recovery": {base: dict(info) for base, info in {**self.recover, **self.pending}.items()},
+ "real_pause": ("сверка незавершённых ордеров: " + ", ".join({**self.recover, **self.pending})
+ if s.real and (self.pending or self.recover) else f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)"
if s.real and now < self.real_pause_until else "")}
out["balances"] = self.balance_view(now)
return out
diff --git a/desktop_chart.py b/desktop_chart.py
new file mode 100644
index 0000000..6a0e813
--- /dev/null
+++ b/desktop_chart.py
@@ -0,0 +1,201 @@
+"""Tk chart rendering and viewport interaction for the desktop simulator."""
+from __future__ import annotations
+from datetime import datetime
+import tkinter as tk
+import strategy
+
+
+class ChartView:
+ def _draw_chart(self) -> None:
+ if not hasattr(self, "canvas"):
+ return
+ c = self.canvas
+ c.delete("all")
+ width, height = c.winfo_width(), c.winfo_height()
+ if width < 80 or height < 80:
+ return
+ left, right, top, bottom = 58, width - 82, 22, height - 34
+ c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей")
+ candles = list(self.candles)
+ if not candles:
+ c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…")
+ return
+ prices = [p for candle in candles for p in (candle[2], candle[3])]
+ low, high = min(prices), max(prices)
+ pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
+ low -= pad
+ high += pad
+ t0 = candles[0][0]
+ t1 = max(candles[-1][0] + 60, t0 + 60)
+ view_end = self.chart_view_end if self.chart_view_end is not None else t1
+ view_start = view_end - self.chart_visible_seconds
+ visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end]
+ visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end]
+ if visible_candles:
+ candles = visible_candles
+ prices = [p for candle in candles for p in (candle[2], candle[3])]
+ low, high = min(prices), max(prices)
+ base_span = high - low
+ pad = base_span * .08 if base_span else max(high * .001, 1e-8)
+ natural_low, natural_high = low - pad, high + pad
+ if self.chart_price_center is None or self.chart_price_span is None:
+ low, high = natural_low, natural_high
+ if self.chart_price_center is not None and self.chart_price_span is not None:
+ span = self.chart_price_span
+ low = self.chart_price_center - span / 2
+ high = self.chart_price_center + span / 2
+ t0 = view_start
+ t1 = view_end
+ if t1 <= t0:
+ return
+ for i in range(5):
+ y = top + i * (bottom - top) / 4
+ value = high - i * (high - low) / 4
+ c.create_line(left, y, right, y, fill="#263746")
+ c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value))
+ c.create_line(left, bottom, right, bottom, fill="#6c7e8c")
+ candle_seconds = self.interval_minutes * 60
+ slot = (right - left) * candle_seconds / (t1 - t0)
+ body_width = max(2.0, min(16.0, slot * .62))
+ for candle in candles:
+ t, open_price, high_price, low_price, close_price = candle
+ if t < t0 - candle_seconds or t > t1:
+ continue
+ x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left)
+ y_high = bottom - (high_price - low) / (high - low) * (bottom - top)
+ y_low = bottom - (low_price - low) / (high - low) * (bottom - top)
+ y_open = bottom - (open_price - low) / (high - low) * (bottom - top)
+ y_close = bottom - (close_price - low) / (high - low) * (bottom - top)
+ color = "#38d996" if close_price >= open_price else "#ef5965"
+ c.create_line(x, y_high, x, y_low, fill=color, width=1)
+ body_top, body_bottom = sorted((y_open, y_close))
+ if body_bottom - body_top < 1:
+ body_bottom = body_top + 1
+ c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color)
+ for marker_time, marker_price, trade_id in visible_markers:
+ if not t0 <= marker_time <= t1:
+ continue
+ x = left + (marker_time - t0) / (t1 - t0) * (right - left)
+ y = bottom - (marker_price - low) / (high - low) * (bottom - top)
+ if top <= y <= bottom:
+ c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1)
+ c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}")
+ position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position
+ if position and position.mode != strategy.STRATEGY_CLASSIC:
+ self._draw_level(c, position.entry_price, low, high, left, right, top, bottom,
+ f"Вход {position.side.upper()}", "#63a8ff")
+ self._draw_level(c, position.stop_price, low, high, left, right, top, bottom,
+ "Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42")
+ if position.partial_target > 0 and not position.partial_done:
+ self._draw_level(c, position.partial_target, low, high, left, right, top, bottom,
+ "Частичная фиксация", "#40d6b0")
+ if position.final_target > 0:
+ self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0")
+ liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side)
+ if liquidation is not None:
+ self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d")
+ elif position:
+ self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff")
+ s = self.applied_settings or self._safe_read_settings()
+ if s["add_step"] > 0 and position.add_count < s["max_adds"]:
+ next_add = position.last_add_price * (1 - s["add_step"] / 100)
+ self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff")
+ if s["stop_loss"] > 0:
+ stop_price = position.entry_price * (1 - s["stop_loss"] / 100)
+ self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42")
+ if s["take_profit"] > 0:
+ effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"]))
+ take_profit_price = position.entry_price * (1 + effective_tp_pct / 100)
+ self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0")
+ if self.last_price:
+ y = bottom - (self.last_price - low) / (high - low) * (bottom - top)
+ if top <= y <= bottom:
+ c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3))
+ c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M"))
+ c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M"))
+
+ def _chart_bounds(self) -> tuple[int, int, int, int]:
+ width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
+ return 58, width - 82, 22, height - 34
+
+ def _on_chart_wheel(self, event: tk.Event) -> None:
+ direction = 1 if event.delta > 0 else -1
+ self._zoom_chart(event.x, event.y, direction)
+
+ def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None:
+ self._zoom_chart(event.x, event.y, direction)
+
+ def _zoom_chart(self, x: int, y: int, direction: int) -> None:
+ if not self.candles:
+ return
+ old_span = self.chart_visible_seconds
+ factor = 0.8 if direction > 0 else 1.25
+ self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor))
+ if self.chart_view_end is None:
+ self.chart_view_end = self.candles[-1][0] + 60
+ left, right, top, bottom = self._chart_bounds()
+ fraction_x = min(1, max(0, (x - left) / max(1, right - left)))
+ old_start = self.chart_view_end - old_span
+ anchor_time = old_start + fraction_x * old_span
+ self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds
+ if self.chart_price_center is None or self.chart_price_span is None:
+ prices = [p for candle in self.candles for p in (candle[2], candle[3])]
+ center = (max(prices) + min(prices)) / 2
+ self.chart_price_center = center
+ self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8)
+ fraction_y = min(1, max(0, (y - top) / max(1, bottom - top)))
+ anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span
+ self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor)
+ self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span
+ self._draw_chart()
+
+ def _on_chart_press(self, event: tk.Event) -> None:
+ if not self.candles:
+ return
+ left, right, top, bottom = self._chart_bounds()
+ if not left <= event.x <= right or not top <= event.y <= bottom:
+ return
+ if self.chart_view_end is None:
+ self.chart_view_end = self.candles[-1][0] + 60
+ if self.chart_price_center is None or self.chart_price_span is None:
+ prices = [p for candle in self.candles for p in (candle[2], candle[3])]
+ low, high = min(prices), max(prices)
+ pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
+ self.chart_price_center = (high + low) / 2
+ self.chart_price_span = high - low + 2 * pad
+ self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center,
+ self.chart_price_span, self.chart_visible_seconds)
+ self.canvas.configure(cursor="fleur")
+
+ def _on_chart_drag(self, event: tk.Event) -> None:
+ if not self._drag_anchor:
+ return
+ x0, y0, end0, center0, price_span, time_span = self._drag_anchor
+ left, right, top, bottom = self._chart_bounds()
+ self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span
+ self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span
+ self.chart_price_span = price_span
+ self._draw_chart()
+
+ def _on_chart_release(self, _event: tk.Event) -> None:
+ self._drag_anchor = None
+ self.canvas.configure(cursor="")
+
+ def _reset_chart_view(self, _event: tk.Event | None = None) -> None:
+ self.chart_visible_seconds = self.interval_minutes * 60 * 30
+ self.chart_view_end = None
+ self.chart_price_center = None
+ self.chart_price_span = None
+ self._drag_anchor = None
+ self._draw_chart()
+
+ def _go_to_live(self) -> None:
+ """Return the chart's right edge to the newest market candle."""
+ if self.candles:
+ self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60
+ else:
+ self.chart_view_end = None
+ self.chart_price_center = None
+ self.chart_price_span = None
+ self._draw_chart()
+
diff --git a/desktop_models.py b/desktop_models.py
new file mode 100644
index 0000000..b9ef352
--- /dev/null
+++ b/desktop_models.py
@@ -0,0 +1,74 @@
+"""Desktop account and per-symbol state, independent of Tk widgets."""
+from __future__ import annotations
+from collections import deque
+from dataclasses import dataclass, field
+import strategy
+
+@dataclass
+class Position:
+ trade_id: int
+ symbol: str
+ entry_price: float
+ qty: float
+ stake: float
+ entry_fee: float
+ opened_at: float
+ last_add_price: float
+ add_count: int = 0
+ # Strategy-mode fields; classic positions keep the defaults.
+ side: str = "long"
+ mode: str = strategy.STRATEGY_CLASSIC
+ leverage: float = 1.0
+ stop_price: float = 0.0
+ initial_stop: float = 0.0
+ atr: float = 0.0
+ extreme: float = 0.0
+ partial_target: float = 0.0 # 0 = none
+ final_target: float = 0.0 # 0 = none
+ partial_done: bool = False
+ realized_gross: float = 0.0
+ realized_fees: float = 0.0
+ opened_stake: float = 0.0
+
+
+@dataclass
+class ClosedTrade:
+ trade_id: int
+ symbol: str
+ entry_price: float
+ exit_price: float
+ qty: float
+ gross_pnl: float
+ fees: float
+ net_pnl: float
+ roi_pct: float
+ opened_at: float
+ closed_at: float
+ reason: str
+
+
+@dataclass
+class CurrencyState:
+ """Independent market and position state for one concurrently traded symbol."""
+ prices: deque = field(default_factory=deque)
+ candles: deque = field(default_factory=deque)
+ entry_markers: deque = field(default_factory=deque)
+ last_price: float | None = None
+ baseline_close: float | None = None
+ last_signal_pct: float | None = None
+ last_signal_ready: bool = False
+ previous_entry_signal_pct: float | None = None
+ live_minute_prices: deque = field(default_factory=deque)
+ last_ws_message: float = 0.0
+ position: Position | None = None
+ live_position: Position | None = None
+ live_position_info: dict | None = None
+ live_order_busy: bool = False
+ live_transition_pending: bool = False
+ live_halted: bool = False
+ # Strategy modes A/B: last evaluated signal candle and the signal valid until the next close.
+ mode_signal: dict | None = None
+ mode_signal_bucket: int = 0
+ mode_eval_busy: bool = False
+
+
diff --git a/docs/reliability.md b/docs/reliability.md
new file mode 100644
index 0000000..1ed619c
--- /dev/null
+++ b/docs/reliability.md
@@ -0,0 +1,65 @@
+# Recovery and development
+
+## Real orders
+
+`cross.py` records an entry intent before sending its first order. A working limit order stays pending until
+the exchange reports a terminal status; a cancel acknowledgement alone is insufficient. If the spot hedge is
+rejected, the remaining short is closed with reduce-only orders and the actual position is checked again.
+Failed and partial rollbacks survive restart and block further real entries while recovery is in progress.
+The saved instrument snapshot allows cancellation/rollback even before the market scanner rediscovers the pair.
+
+`real_mirror.py` records prepared, submitted and filled stages. A prepared entry is never replayed on restart.
+A confirmed fill is saved before requesting a take-profit. Saved positions are closed after restart, consistent
+with the previous simulator behaviour. Atomic JSON writes are shared through `persistence.py`; persistence
+failures block new entries and appear in the UI.
+
+An accepted submission whose response was lost may have no exchange order ID. A flat position snapshot does
+not prove that such an order cannot fill later. These intents remain blocked; the futures recovery path checks
+and reduces any remaining position without submitting another entry. Unknown spot submissions and interrupted
+spot-to-spot entries require manual reconciliation on the exchanges. The application does not provide a blind
+“forget pending order” button. The `/api/basis?ex=cross_real` response includes `recovery` details; the UI displays
+the reason for pausing. A supervised resolution must verify the exchange's open orders and fills, not just its
+current position. Automatic resolution by client order ID across every exchange is not implemented.
+
+## Browser boundary
+
+Both the proxy and the engine validate the original loopback Host on GET and POST. A browser Origin, if present,
+must match that authority; POST also requires `X-Sim: 1`. The proxy preserves the validated Host when forwarding.
+Both listeners remain bound to loopback. This is local-app isolation, not user authentication for internet hosting.
+Static assets are served from an explicit allowlist.
+
+Responses for an earlier venue/coin selection cannot replace the current screen. Commands are disabled until
+the selected context has loaded, and row close actions carry their original venue or coin. Poll responses also
+have sequence numbers so a slower old response cannot overwrite a newer completed response.
+
+## Code boundaries
+
+| Responsibility | Files |
+| --- | --- |
+| Web layout, styles, behaviour | `web_sim.html`, `web/app.css`, `web/app.js` |
+| HTTP routing and local browser policy | `web_sim.py`, `web_proxy.py`, `request_security.py` |
+| Desktop account models and chart | `desktop_models.py`, `desktop_chart.py` |
+| Desktop coordination | `main.py` |
+| Order execution and recovery | `cross.py`, `real_mirror.py` |
+| Exchange adapters | `live.py`, `bybit_live.py` |
+| Atomic snapshots | `persistence.py` |
+| Historical execution and risk metrics | `historical_backtest.py`, `strategy.py` |
+
+## Verification
+
+Python 3.11+ is supported by the pinned dependencies in `requirements.txt`; the primary local validation uses
+Python 3.12. JavaScript regression tests use Node.js 22+ and its built-in test runner, with no npm dependencies.
+
+```powershell
+python -m pip install -r requirements.txt
+python -B scripts/run_tests.py
+node --test tests/web_context.test.cjs
+```
+
+The Python runner blocks external connections and DNS while permitting loopback HTTP fixtures. Exchange orders
+are tested using fake clients. CI runs these suites on Windows with Python 3.11, 3.12 and 3.13; configuring the
+workflow does not imply that a remote CI run or a real exchange integration has been performed.
+
+Regression cases cover refused/partial rollback, uncertain cancellation and submission, restart before and
+after order acceptance, failed disk writes, hostile Host/Origin, response ordering, percentage drawdown and
+capital-floor ordering for long/short backtests including fees.
diff --git a/historical_backtest.py b/historical_backtest.py
index 3a59efc..024483d 100644
--- a/historical_backtest.py
+++ b/historical_backtest.py
@@ -495,6 +495,24 @@ def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_
return windows, sorted(failed)
+def _track_risk(risk: dict[str, float], equity: float) -> None:
+ risk["peak"] = max(risk["peak"], equity)
+ drawdown = risk["peak"] - equity
+ drawdown_pct = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
+ # The largest dollar loss and largest percentage loss may follow different peaks.
+ risk["max_dd_usdt"] = max(risk["max_dd_usdt"], drawdown)
+ risk["max_dd_pct"] = max(risk["max_dd_pct"], drawdown_pct)
+ risk["min_equity"] = min(risk["min_equity"], equity)
+
+
+def _equity_floor_crossing(start: float, end: float, start_equity: float,
+ end_equity: float, floor: float) -> float | None:
+ """Price where linearly marked equity first reaches the floor on this segment."""
+ if start_equity > floor >= end_equity:
+ return start + (end - start) * (floor - start_equity) / (end_equity - start_equity)
+ return None
+
+
def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
strategies: dict[str, dict[str, float]], initial_capital: float,
fee_pct: float = TAKER_FEE_PCT,
@@ -560,21 +578,12 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
equity += unrealized - estimated_exit_fee
return equity
- def track_risk(equity: float) -> None:
- if equity > risk["peak"]:
- risk["peak"] = equity
- drawdown = risk["peak"] - equity
- if drawdown > risk["max_dd_usdt"]:
- risk["max_dd_usdt"] = drawdown
- risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
- risk["min_equity"] = min(risk["min_equity"], equity)
-
def mark_and_check_stop(symbol: str, price: float, stamp: int) -> bool:
if equity_stop["triggered"]:
return True
marks[symbol] = price
equity = equity_at()
- track_risk(equity)
+ _track_risk(risk, equity)
if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12):
equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
return True
@@ -742,12 +751,10 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
# Add the precise capital-floor crossing as an event so a later rebound
# inside the same candle cannot hide a drawdown breach.
if min_equity_pct > 0 and end < current:
- current_equity = equity_at(symbol, current)
- end_equity = equity_at(symbol, end)
- if current_equity > equity_floor >= end_equity and current_equity != end_equity:
- stop_level = current + (end - current) * (
- (equity_floor - current_equity) / (end_equity - current_equity)
- )
+ stop_level = _equity_floor_crossing(
+ current, end, equity_at(symbol, current), equity_at(symbol, end), equity_floor,
+ )
+ if stop_level is not None:
candidates.append((stop_level, "EQUITY_STOP"))
_tp, stop_level, liq_level = exit_levels(symbol, pos)
if stop_level is not None and end <= stop_level < current:
@@ -1118,10 +1125,11 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
def iso(stamp: int) -> str:
return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat()
- def equity_at() -> float:
+ def equity_at(symbol: str | None = None, price: float | None = None) -> float:
equity = cash
for position_symbol, pos in positions.items():
- mark = marks.get(position_symbol, pos.entry_price)
+ mark = (price if position_symbol == symbol and price is not None
+ else marks.get(position_symbol, pos.entry_price))
equity += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty)
- mark * pos.qty * fee_pct / 100)
return equity
@@ -1131,13 +1139,7 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
return True
marks[symbol] = price
equity = equity_at()
- if equity > risk["peak"]:
- risk["peak"] = equity
- drawdown = risk["peak"] - equity
- if drawdown > risk["max_dd_usdt"]:
- risk["max_dd_usdt"] = drawdown
- risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
- risk["min_equity"] = min(risk["min_equity"], equity)
+ _track_risk(risk, equity)
if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12):
equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
return True
@@ -1296,6 +1298,12 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
return
liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side)
candidates = []
+ if min_equity_pct > 0:
+ floor_price = _equity_floor_crossing(
+ start, end, equity_at(symbol, start), equity_at(symbol, end), equity_floor,
+ )
+ if floor_price is not None:
+ candidates.append((floor_price, "EQUITY_STOP"))
lo, hi = min(start, end), max(start, end)
if lo <= pos.stop <= hi:
candidates.append((pos.stop, "STOP"))
@@ -1307,6 +1315,9 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
# The first level crossed on the way from ``start`` is the nearest one.
level, event = min(candidates, key=lambda item: abs(item[0] - start))
marks[symbol] = level
+ if event == "EQUITY_STOP":
+ mark_and_check_stop(symbol, level, stamp)
+ return
if event == "LIQ":
close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True)
else:
diff --git a/live.py b/live.py
index 43ba67e..c9db10b 100644
--- a/live.py
+++ b/live.py
@@ -167,8 +167,13 @@ def _http(method: str, url: str, headers: dict | None = None, body: bytes | None
else:
_give_back(parts.scheme, parts.netloc, conn)
if resp.status >= 400:
- raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}")
- return json.loads(data or b"{}")
+ raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}",
+ sent=method in ("POST", "DELETE") and resp.status >= 500)
+ try:
+ return json.loads(data or b"{}")
+ except (ValueError, UnicodeDecodeError) as exc:
+ raise LiveError(f"не удалось прочитать ответ биржи: {exc}",
+ sent=method in ("POST", "DELETE")) from None
raise LiveError("нет связи")
diff --git a/main.py b/main.py
index ac594ad..5fad405 100644
--- a/main.py
+++ b/main.py
@@ -12,7 +12,6 @@ import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import deque
-from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
import tkinter as tk
@@ -22,6 +21,9 @@ from credential_store import CredentialStoreError, delete_credentials, load_cred
from historical_backtest import (fetch_funding_history, fetch_klines, prepare_universe, run_backtest,
run_mode_backtest, save_report)
import strategy
+from desktop_models import Position, ClosedTrade, CurrencyState
+from desktop_chart import ChartView
+from persistence import atomic_write_json
try:
import websocket
@@ -59,75 +61,7 @@ MAX_EVENTS_PER_POLL = 2000
MANUAL_CLOSE_CONFIRM_SECONDS = 15
-@dataclass
-class Position:
- trade_id: int
- symbol: str
- entry_price: float
- qty: float
- stake: float
- entry_fee: float
- opened_at: float
- last_add_price: float
- add_count: int = 0
- # Strategy-mode fields; classic positions keep the defaults.
- side: str = "long"
- mode: str = strategy.STRATEGY_CLASSIC
- leverage: float = 1.0
- stop_price: float = 0.0
- initial_stop: float = 0.0
- atr: float = 0.0
- extreme: float = 0.0
- partial_target: float = 0.0 # 0 = none
- final_target: float = 0.0 # 0 = none
- partial_done: bool = False
- realized_gross: float = 0.0
- realized_fees: float = 0.0
- opened_stake: float = 0.0
-
-
-@dataclass
-class ClosedTrade:
- trade_id: int
- symbol: str
- entry_price: float
- exit_price: float
- qty: float
- gross_pnl: float
- fees: float
- net_pnl: float
- roi_pct: float
- opened_at: float
- closed_at: float
- reason: str
-
-
-@dataclass
-class CurrencyState:
- """Independent market and position state for one concurrently traded symbol."""
- prices: deque = field(default_factory=deque)
- candles: deque = field(default_factory=deque)
- entry_markers: deque = field(default_factory=deque)
- last_price: float | None = None
- baseline_close: float | None = None
- last_signal_pct: float | None = None
- last_signal_ready: bool = False
- previous_entry_signal_pct: float | None = None
- live_minute_prices: deque = field(default_factory=deque)
- last_ws_message: float = 0.0
- position: Position | None = None
- live_position: Position | None = None
- live_position_info: dict | None = None
- live_order_busy: bool = False
- live_transition_pending: bool = False
- live_halted: bool = False
- # Strategy modes A/B: last evaluated signal candle and the signal valid until the next close.
- mode_signal: dict | None = None
- mode_signal_bucket: int = 0
- mode_eval_busy: bool = False
-
-
-class PaperSimulator:
+class PaperSimulator(ChartView):
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.root.title("Bybit — симулятор сделок в реальном времени")
@@ -2134,10 +2068,8 @@ class PaperSimulator:
"live_initial_deposits": self.live_initial_deposits,
}
try:
- temp_path = STATE_FILE.with_suffix(".json.tmp")
- temp_path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
- os.replace(temp_path, STATE_FILE)
- except OSError as exc:
+ atomic_write_json(STATE_FILE, state)
+ except (OSError, ValueError) as exc:
if hasattr(self, "status_var"):
self.status_var.set(f"Не удалось сохранить историю счёта: {exc}")
@@ -2154,10 +2086,8 @@ class PaperSimulator:
def _save_settings(self) -> None:
self._settings_save_job = None
try:
- temp_path = SETTINGS_FILE.with_suffix(".json.tmp")
- temp_path.write_text(json.dumps(self._settings_payload(), ensure_ascii=False, indent=2), encoding="utf-8")
- os.replace(temp_path, SETTINGS_FILE)
- except OSError as exc:
+ atomic_write_json(SETTINGS_FILE, self._settings_payload())
+ except (OSError, ValueError) as exc:
self.status_var.set(f"Не удалось сохранить настройки: {exc}")
@staticmethod
@@ -4513,199 +4443,6 @@ class PaperSimulator:
return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}"
return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}"
- def _draw_chart(self) -> None:
- if not hasattr(self, "canvas"):
- return
- c = self.canvas
- c.delete("all")
- width, height = c.winfo_width(), c.winfo_height()
- if width < 80 or height < 80:
- return
- left, right, top, bottom = 58, width - 82, 22, height - 34
- c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей")
- candles = list(self.candles)
- if not candles:
- c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…")
- return
- prices = [p for candle in candles for p in (candle[2], candle[3])]
- low, high = min(prices), max(prices)
- pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
- low -= pad
- high += pad
- t0 = candles[0][0]
- t1 = max(candles[-1][0] + 60, t0 + 60)
- view_end = self.chart_view_end if self.chart_view_end is not None else t1
- view_start = view_end - self.chart_visible_seconds
- visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end]
- visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end]
- if visible_candles:
- candles = visible_candles
- prices = [p for candle in candles for p in (candle[2], candle[3])]
- low, high = min(prices), max(prices)
- base_span = high - low
- pad = base_span * .08 if base_span else max(high * .001, 1e-8)
- natural_low, natural_high = low - pad, high + pad
- if self.chart_price_center is None or self.chart_price_span is None:
- low, high = natural_low, natural_high
- if self.chart_price_center is not None and self.chart_price_span is not None:
- span = self.chart_price_span
- low = self.chart_price_center - span / 2
- high = self.chart_price_center + span / 2
- t0 = view_start
- t1 = view_end
- if t1 <= t0:
- return
- for i in range(5):
- y = top + i * (bottom - top) / 4
- value = high - i * (high - low) / 4
- c.create_line(left, y, right, y, fill="#263746")
- c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value))
- c.create_line(left, bottom, right, bottom, fill="#6c7e8c")
- candle_seconds = self.interval_minutes * 60
- slot = (right - left) * candle_seconds / (t1 - t0)
- body_width = max(2.0, min(16.0, slot * .62))
- for candle in candles:
- t, open_price, high_price, low_price, close_price = candle
- if t < t0 - candle_seconds or t > t1:
- continue
- x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left)
- y_high = bottom - (high_price - low) / (high - low) * (bottom - top)
- y_low = bottom - (low_price - low) / (high - low) * (bottom - top)
- y_open = bottom - (open_price - low) / (high - low) * (bottom - top)
- y_close = bottom - (close_price - low) / (high - low) * (bottom - top)
- color = "#38d996" if close_price >= open_price else "#ef5965"
- c.create_line(x, y_high, x, y_low, fill=color, width=1)
- body_top, body_bottom = sorted((y_open, y_close))
- if body_bottom - body_top < 1:
- body_bottom = body_top + 1
- c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color)
- for marker_time, marker_price, trade_id in visible_markers:
- if not t0 <= marker_time <= t1:
- continue
- x = left + (marker_time - t0) / (t1 - t0) * (right - left)
- y = bottom - (marker_price - low) / (high - low) * (bottom - top)
- if top <= y <= bottom:
- c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1)
- c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}")
- position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position
- if position and position.mode != strategy.STRATEGY_CLASSIC:
- self._draw_level(c, position.entry_price, low, high, left, right, top, bottom,
- f"Вход {position.side.upper()}", "#63a8ff")
- self._draw_level(c, position.stop_price, low, high, left, right, top, bottom,
- "Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42")
- if position.partial_target > 0 and not position.partial_done:
- self._draw_level(c, position.partial_target, low, high, left, right, top, bottom,
- "Частичная фиксация", "#40d6b0")
- if position.final_target > 0:
- self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0")
- liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side)
- if liquidation is not None:
- self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d")
- elif position:
- self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff")
- s = self.applied_settings or self._safe_read_settings()
- if s["add_step"] > 0 and position.add_count < s["max_adds"]:
- next_add = position.last_add_price * (1 - s["add_step"] / 100)
- self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff")
- if s["stop_loss"] > 0:
- stop_price = position.entry_price * (1 - s["stop_loss"] / 100)
- self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42")
- if s["take_profit"] > 0:
- effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"]))
- take_profit_price = position.entry_price * (1 + effective_tp_pct / 100)
- self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0")
- if self.last_price:
- y = bottom - (self.last_price - low) / (high - low) * (bottom - top)
- if top <= y <= bottom:
- c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3))
- c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M"))
- c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M"))
-
- def _chart_bounds(self) -> tuple[int, int, int, int]:
- width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
- return 58, width - 82, 22, height - 34
-
- def _on_chart_wheel(self, event: tk.Event) -> None:
- direction = 1 if event.delta > 0 else -1
- self._zoom_chart(event.x, event.y, direction)
-
- def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None:
- self._zoom_chart(event.x, event.y, direction)
-
- def _zoom_chart(self, x: int, y: int, direction: int) -> None:
- if not self.candles:
- return
- old_span = self.chart_visible_seconds
- factor = 0.8 if direction > 0 else 1.25
- self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor))
- if self.chart_view_end is None:
- self.chart_view_end = self.candles[-1][0] + 60
- left, right, top, bottom = self._chart_bounds()
- fraction_x = min(1, max(0, (x - left) / max(1, right - left)))
- old_start = self.chart_view_end - old_span
- anchor_time = old_start + fraction_x * old_span
- self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds
- if self.chart_price_center is None or self.chart_price_span is None:
- prices = [p for candle in self.candles for p in (candle[2], candle[3])]
- center = (max(prices) + min(prices)) / 2
- self.chart_price_center = center
- self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8)
- fraction_y = min(1, max(0, (y - top) / max(1, bottom - top)))
- anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span
- self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor)
- self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span
- self._draw_chart()
-
- def _on_chart_press(self, event: tk.Event) -> None:
- if not self.candles:
- return
- left, right, top, bottom = self._chart_bounds()
- if not left <= event.x <= right or not top <= event.y <= bottom:
- return
- if self.chart_view_end is None:
- self.chart_view_end = self.candles[-1][0] + 60
- if self.chart_price_center is None or self.chart_price_span is None:
- prices = [p for candle in self.candles for p in (candle[2], candle[3])]
- low, high = min(prices), max(prices)
- pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
- self.chart_price_center = (high + low) / 2
- self.chart_price_span = high - low + 2 * pad
- self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center,
- self.chart_price_span, self.chart_visible_seconds)
- self.canvas.configure(cursor="fleur")
-
- def _on_chart_drag(self, event: tk.Event) -> None:
- if not self._drag_anchor:
- return
- x0, y0, end0, center0, price_span, time_span = self._drag_anchor
- left, right, top, bottom = self._chart_bounds()
- self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span
- self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span
- self.chart_price_span = price_span
- self._draw_chart()
-
- def _on_chart_release(self, _event: tk.Event) -> None:
- self._drag_anchor = None
- self.canvas.configure(cursor="")
-
- def _reset_chart_view(self, _event: tk.Event | None = None) -> None:
- self.chart_visible_seconds = self.interval_minutes * 60 * 30
- self.chart_view_end = None
- self.chart_price_center = None
- self.chart_price_span = None
- self._drag_anchor = None
- self._draw_chart()
-
- def _go_to_live(self) -> None:
- """Return the chart's right edge to the newest market candle."""
- if self.candles:
- self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60
- else:
- self.chart_view_end = None
- self.chart_price_center = None
- self.chart_price_span = None
- self._draw_chart()
-
def _update_candle(self, timestamp: float, price: float) -> None:
interval_seconds = self.interval_minutes * 60
candle_start = int(timestamp // interval_seconds) * interval_seconds
diff --git a/persistence.py b/persistence.py
new file mode 100644
index 0000000..0dbc4b3
--- /dev/null
+++ b/persistence.py
@@ -0,0 +1,27 @@
+"""Atomic local JSON snapshots; callers must handle write failures explicitly."""
+
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+from pathlib import Path
+
+
+def atomic_write_json(path: Path, payload) -> None:
+ """Flush a new snapshot before replacing the old file, or leave the old file intact."""
+ path = Path(path)
+ encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
+ try:
+ with os.fdopen(fd, "wb") as stream:
+ stream.write(encoded)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ finally:
+ try:
+ os.unlink(temporary)
+ except FileNotFoundError:
+ pass
diff --git a/real_mirror.py b/real_mirror.py
index 5898583..6f9830d 100644
--- a/real_mirror.py
+++ b/real_mirror.py
@@ -16,6 +16,7 @@ Results (prices, fees) are the exchange's own fills; `exact` is False where the
from __future__ import annotations
import json
+from persistence import atomic_write_json
import queue
import threading
import time
@@ -191,6 +192,7 @@ class FuturesMirror:
self.position: dict | None = None # the one real position (opening / open / closing)
self.trades: list[dict] = []
self.state = "" # "" idle · "opening" · "open" · "closing" · "check" (verify zero)
+ self.storage_error = ""
self.problem = "" # last error that keeps the coin blocked
self.on_failed_open = None # callback(uid): close the paper twin of a real order that failed
self.exchange_trades: list[dict] | None = None # rebuilt from the exchange's fills (None: not synced yet)
@@ -207,24 +209,67 @@ class FuturesMirror:
def _load(self) -> None:
try:
d = json.loads(self.file.read_text(encoding="utf-8"))
- except (OSError, ValueError):
+ except FileNotFoundError:
+ return
+ except (OSError, ValueError) as exc:
+ self.state, self.problem = "blocked", f"не прочитано состояние реальных ордеров: {exc}"
return
self.trades = d.get("trades", [])[-500:]
pos = d.get("position")
if pos:
- # paper positions do not survive a restart: the saved real one is closed at once
pos["uid"] = None
- self.position, self.state = pos, "closing"
- self.jobs.put(("close", "осиротевшая после перезапуска"))
+ self.position = pos
+ if pos.get("phase") in ("prepared", "submitted"):
+ self.state = "recover"
+ self.jobs.put(("recover", None))
+ else:
+ self.state = "closing"
+ self.jobs.put(("close", "осиротевшая после перезапуска"))
def _save(self) -> None:
try:
- self.file.parent.mkdir(exist_ok=True)
- pos = self.position if self.state in ("open", "closing", "check") else None
- self.file.write_text(json.dumps({"position": pos, "trades": self.trades[-500:]}, ensure_ascii=False),
- encoding="utf-8")
- except OSError:
- pass
+ atomic_write_json(self.file, {"version": 2, "state": self.state,
+ "position": self.position, "trades": self.trades[-500:]})
+ except (OSError, ValueError) as exc:
+ self.storage_error = f"не сохранено состояние ордеров: {exc}"
+ raise
+ self.storage_error = ""
+
+ def _recover_open(self) -> None:
+ """Never replay an entry after a crash. Resolve known orders; contain unknown submissions."""
+ pos = self.position
+ if not pos:
+ return
+ if pos.get("phase") == "prepared":
+ self._failed_open("перезапуск до отправки ордера")
+ return
+ c = self.client_for(self.exchange)
+ oid = pos.get("order_in")
+ if pos.get("phase") != "filled":
+ if not oid:
+ # A lost submit response cannot be declared absent from one flat position snapshot.
+ held = c.fut_position(self.symbol)
+ if abs(held) > self.VERIFY_TOLERANCE:
+ expected = 1 if pos["side"] == "LONG" else -1
+ if held * expected <= 0:
+ self.problem = "позиция другого направления — требуется ручная сверка"
+ return
+ c.fut_order(self.symbol, "sell" if held > 0 else "buy", abs(held), reduce_only=True)
+ self.problem = "результат входа без ID неизвестен; новые входы заблокированы, сверяю и закрываю остаток"
+ return
+ status = c.fut_order_status(self.symbol, oid)
+ if not status["final"]:
+ c.fut_cancel(self.symbol, oid)
+ status = c.fut_order_status(self.symbol, oid)
+ if not status["final"]:
+ self.problem = "ожидаю окончательный статус входа"
+ return
+ pos.update(phase="filled", coins=status["coins"], entry=status["price"] or pos["paper_entry"],
+ fee_in=status["fee"], exact=False)
+ with self.lock:
+ self.state = "closing"
+ self._save()
+ self._close("восстановление незавершённого входа")
# --- the simulator's side ----------------------------------------------------------------------------------
def coin_settings(self) -> dict:
@@ -238,6 +283,8 @@ class FuturesMirror:
if not self.enabled():
return ""
with self.lock:
+ if self.storage_error:
+ return self.storage_error
left = self.paused_until - time.time()
if self.state == "" and left > 0:
# the exchange refused the last entry: no new trade (paper or real) until the pause ends
@@ -258,7 +305,7 @@ class FuturesMirror:
"""Paper events, called under the engine's lock: only queue work here."""
with self.lock:
if event == "open":
- if not self.enabled() or self.state or time.time() < self.paused_until:
+ if not self.enabled() or self.state or self.storage_error or time.time() < self.paused_until:
return # real mode off, or a real trade still runs (gate was bypassed)
self.state = "opening"
units = symbol_units(self.symbol)
@@ -267,7 +314,12 @@ class FuturesMirror:
# the paper take-profit as a distance from the entry: the real TP is placed at
# the same distance from the REAL fill price, not at the paper price
"tp_pct": (pos.target / pos.entry - 1) * 100 if getattr(pos, "target", None) else None,
- "ping": self.ping()}
+ "ping": self.ping(), "phase": "prepared"}
+ try:
+ self._save()
+ except (OSError, ValueError):
+ self.state, self.problem = "recover", self.storage_error
+ return
self.jobs.put(("open", None))
elif event == "close" and self.position and self.position.get("uid") == pos.uid:
self.jobs.put(("close", "закрыта в симуляторе"))
@@ -286,11 +338,15 @@ class FuturesMirror:
self._open()
elif kind == "close":
self._close(arg)
+ elif kind == "recover":
+ self._recover_open()
elif kind == "watch":
self._watch()
except Exception as exc: # never let the worker die
with self.lock:
self.problem = f"сбой: {exc}"
+ if kind == "open" and self.position:
+ self.state = "recover"
journal("simulator", self.exchange, self.coin, kind, False, f"сбой: {exc}")
if kind == "close":
self._retry_close(arg)
@@ -331,6 +387,12 @@ class FuturesMirror:
def _watch(self) -> None:
"""An open real position may be closed by the exchange itself (its TP / SL): then record it now.
Every SYNC_S seconds (and right after a close) the trades are synced with the exchange's history."""
+ if self.storage_error and self.position is None:
+ with self.lock:
+ self._save()
+ if self.state == "recover":
+ self._recover_open()
+ return
if (self.state in ("", "open") and time.time() - self.last_sync >= self.SYNC_S
and (self.enabled() or self.exchange_trades is None)):
self.sync()
@@ -359,6 +421,15 @@ class FuturesMirror:
def _open(self) -> None:
pos = self.position
+ if pos is None or self.state != "opening":
+ return
+ with self.lock:
+ pos["phase"] = "submitted"
+ try:
+ self._save() # must complete before an exchange request is allowed
+ except (OSError, ValueError):
+ pos["phase"] = "prepared" # no request was sent
+ raise
side = "buy" if pos["side"] == "LONG" else "sell"
sign = 1 if side == "buy" else -1
c = None
@@ -374,23 +445,27 @@ class FuturesMirror:
else:
fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False)
except live.LiveError as exc:
- if getattr(exc, "sent", False) and c is not None:
- # accepted, fill not confirmed: the exchange's position decides
+ if getattr(exc, "sent", False):
+ with self.lock:
+ pos["order_in"] = exc.order_id
+ self.state, self.problem = "recover", str(exc)
+ self._save()
try:
- held = abs(c.fut_position(self.symbol))
+ held = c.fut_position(self.symbol)
except live.LiveError:
- held = pos["coins"] # cannot tell: treat as open, the close is reduce-only
- if held > self.VERIFY_TOLERANCE:
- fill = live.Fill(held, pos["paper_entry"], 0.0, exc.order_id, exact=False)
- journal("simulator", self.exchange, self.coin, "open", False,
- f"{exc} — позиция на бирже есть ({held:g}), веду её", side=pos["side"])
- else:
- self._failed_open(f"{exc}; позиции на бирже нет")
return
+ if held * sign <= self.VERIFY_TOLERANCE:
+ return
+ fill = live.Fill(abs(held), pos["paper_entry"], 0.0, exc.order_id, exact=False)
else:
self._top_up_futures(c, str(exc), pos["coins"] * pos["paper_entry"])
self._failed_open(str(exc))
return
+ # Persist the accepted fill before any additional network call (TP, fee sync, etc.).
+ with self.lock:
+ pos.update(phase="filled", coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd,
+ exact=fill.exact, order_in=fill.order_id)
+ self._save()
# the exchange's real fee rate (it decides how far the TP has to be, and the paper model uses it too)
fee_pct = fill.fee_usd / (fill.coins * fill.price) * 100 if fill.exact and fill.coins and fill.price else None
if fee_pct:
@@ -478,6 +553,10 @@ class FuturesMirror:
self.on_failed_open(uid)
def _close(self, reason: str) -> None:
+ if self.position and self.position.get("phase") in ("prepared", "submitted"):
+ self.state = "recover"
+ self._recover_open()
+ return
with self.lock:
pos = self.position
if pos is None or self.state == "":
@@ -566,7 +645,7 @@ class FuturesMirror:
t for t in self.trades if t.get("closed", 0) >= (self.coin_settings().get("since") or 0)]
stats = trade_stats(trades)
pos = dict(self.position) if self.position and self.state else None
- return {"open": 1 if pos else 0, "state": self.state, "problem": self.problem, "position": pos,
+ return {"open": 1 if pos else 0, "state": self.state, "problem": self.storage_error or self.problem, "position": pos,
**stats, "positions": [pos] if pos else [], "enabled": self.enabled(),
"source": "биржа" if self.exchange_trades is not None else "программа",
"synced": self.synced, "sync_error": self.sync_error, "since": self.coin_settings().get("since"),
diff --git a/request_security.py b/request_security.py
new file mode 100644
index 0000000..135de56
--- /dev/null
+++ b/request_security.py
@@ -0,0 +1,43 @@
+"""Validate the original browser request before proxying or executing local commands."""
+from __future__ import annotations
+
+import ipaddress
+from urllib.parse import urlsplit
+
+LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"}
+
+
+def _authority(value: str):
+ try:
+ url = urlsplit("http://" + value)
+ if (url.hostname not in LOCAL_HOSTS or url.username is not None or url.password is not None
+ or url.path or url.query or url.fragment or any(c.isspace() for c in value)):
+ return None
+ return url.hostname, url.port or 80
+ except ValueError:
+ return None
+
+
+def trusted_request(handler, *, command: bool = False) -> bool:
+ try:
+ if not ipaddress.ip_address(handler.client_address[0]).is_loopback:
+ return False
+ except ValueError:
+ return False
+ hosts = handler.headers.get_all("Host", [])
+ if len(hosts) != 1 or (host := _authority(hosts[0])) is None:
+ return False
+ origins = handler.headers.get_all("Origin", [])
+ if len(origins) > 1:
+ return False
+ if origins:
+ try:
+ origin = urlsplit(origins[0])
+ if (origin.scheme != "http" or origin.path or origin.query or origin.fragment
+ or _authority(origin.netloc) != host):
+ return False
+ except ValueError:
+ return False
+ if handler.headers.get("Sec-Fetch-Site") == "cross-site":
+ return False
+ return not command or handler.headers.get("X-Sim") == "1"
diff --git a/requirements.txt b/requirements.txt
index 7b39e8e..0ee383c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,2 +1,3 @@
-websocket-client>=1.8,<2
-numpy>=1.26
+# Python 3.11+
+websocket-client==1.8.0
+numpy==2.3.5
diff --git a/scripts/run_tests.py b/scripts/run_tests.py
new file mode 100644
index 0000000..cc07c46
--- /dev/null
+++ b/scripts/run_tests.py
@@ -0,0 +1,34 @@
+"""Run offline tests. Loopback HTTP fixtures are allowed; exchange connections are forbidden."""
+from pathlib import Path
+import os
+import subprocess
+import sys
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.dont_write_bytecode = True
+
+
+def offline(event, args):
+ if event == 'socket.connect':
+ host = args[1][0]
+ elif event == 'socket.getaddrinfo':
+ host = args[0]
+ else:
+ return
+ if host not in (None, 'localhost', '::1') and not str(host).startswith('127.'):
+ raise RuntimeError('External network is disabled during tests')
+
+
+if __name__ == '__main__':
+ if len(sys.argv) == 1:
+ for suite in ('tests', 'meme_matcher/tests'):
+ result = subprocess.run([sys.executable, '-B', __file__, suite], cwd=ROOT)
+ if result.returncode:
+ sys.exit(result.returncode)
+ else:
+ os.chdir(ROOT)
+ sys.path.insert(0, str(ROOT))
+ sys.addaudithook(offline)
+ suite = unittest.defaultTestLoader.discover(str(ROOT / sys.argv[1]))
+ sys.exit(not unittest.TextTestRunner(verbosity=1).run(suite).wasSuccessful())
diff --git a/setup.ps1 b/setup.ps1
index 877198c..ba8ad16 100644
--- a/setup.ps1
+++ b/setup.ps1
@@ -1,5 +1,5 @@
# Установка и запуск симулятора (вызывается из УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat).
-# 1) Python 3.10+: если нет — ставится через winget, только для текущего пользователя
+# 1) Python 3.11+: если нет — ставится через winget, только для текущего пользователя
# 2) библиотеки программы — в папку .venv рядом, в систему ничего не ставится
# 3) запуск: страница http://127.0.0.1:8765 открывается в браузере
# Параметр /install-only — только установить.
@@ -13,18 +13,18 @@ $VenvPy = Join-Path $Dir ".venv\Scripts\python.exe"
$VenvPyw = Join-Path $Dir ".venv\Scripts\pythonw.exe"
function Find-Python {
- foreach ($v in "3.13", "3.12", "3.11", "3.10") {
+ foreach ($v in "3.13", "3.12", "3.11") {
try {
$exe = & py "-$v" -c "import sys; print(sys.executable)" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() }
} catch {}
}
- foreach ($d in "Python313", "Python312", "Python311", "Python310") {
+ foreach ($d in "Python313", "Python312", "Python311") {
$p = Join-Path $env:LOCALAPPDATA "Programs\Python\$d\python.exe"
if (Test-Path $p) { return $p }
}
try {
- $exe = & python -c "import sys; assert sys.version_info >= (3, 10); 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() }
} catch {}
return $null
@@ -54,6 +54,10 @@ if (-not (Test-Path $VenvPy)) {
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 ($LASTEXITCODE -ne 0) {
+ Fail "Окружение .venv использует старый Python. Переименуйте .venv и повторите установку с Python 3.11 или новее."
+}
Write-Host "Проверяю библиотеки..."
& $VenvPy -m pip install --disable-pip-version-check -q -r (Join-Path $Dir "requirements.txt")
if ($LASTEXITCODE -ne 0) {
diff --git a/tests/test_backtest.py b/tests/test_backtest.py
index 4a5e61a..10d60a2 100644
--- a/tests/test_backtest.py
+++ b/tests/test_backtest.py
@@ -310,5 +310,47 @@ class CacheTests(unittest.TestCase):
self.assertEqual(len(hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path)[0]), 5)
+class RiskRegressionTests(unittest.TestCase):
+ def test_percentage_and_absolute_drawdown_have_independent_peaks(self):
+ rows = [[0, 90, 90, 90, 90], [MIN, 100, 100, 100, 100],
+ [2 * MIN, 100, 100, 80, 80], [3 * MIN, 80, 200, 80, 200],
+ [4 * MIN, 200, 200, 170, 170]]
+ result = run({'AAA': rows}, {'AAA': cfg(stake=100, take_profit=0, max_adds=0)})
+ self.assertAlmostEqual(result['summary']['max_drawdown_usdt'], 30)
+ self.assertAlmostEqual(result['summary']['max_drawdown_pct'], 20)
+
+ def test_mode_capital_floor_precedes_later_stop_with_fees(self):
+ fixture = ModeBacktestTests()
+ candles = fixture.breakout_rows([(102.5, 102.6, 90, 91, 10)])
+ params = fixture.params(stake_pct=50, leverage=10, partial_r=0, partial_pct=0)
+ for fee in (0, 0.055):
+ with self.subTest(fee=fee):
+ result = hb.run_mode_backtest(candles, strategy.STRATEGY_BREAKOUT, params,
+ 100, fee_pct=fee, min_equity_pct=95)
+ self.assertTrue(result['summary']['equity_stop_triggered'])
+ self.assertAlmostEqual(result['summary']['equity_at_stop_usdt'], 95)
+ self.assertTrue(any(t['status'] != 'CLOSED' for t in result['trades']))
+
+ def test_position_stop_before_capital_floor_is_not_skipped(self):
+ fixture = ModeBacktestTests()
+ result = fixture.run_mode(fixture.breakout_rows([(102.5, 102.6, 90, 91, 10)]),
+ fixture.params(stake_pct=50, leverage=10), min_equity_pct=80)
+ self.assertFalse(result['summary']['equity_stop_triggered'])
+ self.assertTrue(result['trades'][0]['reason'].startswith('Стоп'))
+
+ def test_short_floor_is_crossed_on_rising_price(self):
+ params = mode_params(strategy.STRATEGY_FADE, timeframe_min=60, min_growth_24h=30,
+ min_funding_pct=0, high_lookback_hours=6, pullback_pct=3, vwap_hours=6, atr_period=3,
+ stop_buffer_atr=0.5, max_stop_pct=30, trail_atr=0, take_profit_r=0,
+ partial_r=0, partial_pct=0, max_hold_hours=48, stake_pct=50, leverage=10)
+ rows = [(100, 101, 99, 100, 1)] * 20
+ rows += [(p - 2, p + 2, p - 4, p, 5) for p in (110, 125, 140, 150, 146)]
+ rows += [(146, 147, 128, 130, 5), (130, 160, 129, 155, 5)]
+ result = hb.run_mode_backtest({'AAA': minute_rows(rows, tf_min=60)}, strategy.STRATEGY_FADE,
+ params, 100, fee_pct=0.055, min_equity_pct=95)
+ self.assertEqual(result['trades'][0]['side'], 'SHORT')
+ self.assertAlmostEqual(result['summary']['equity_at_stop_usdt'], 95)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_cross_recovery.py b/tests/test_cross_recovery.py
new file mode 100644
index 0000000..4338dc8
--- /dev/null
+++ b/tests/test_cross_recovery.py
@@ -0,0 +1,95 @@
+"""Durable recovery of rejected/partial rollback and uncertain entry cancellation."""
+import json
+import sys
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
+import cross
+import live
+import test_cross_real
+
+
+class RecoveryTests(unittest.TestCase):
+ def setUp(self):
+ self.fixture = test_cross_real.CrossRealTests()
+ self.fixture.setUp()
+ self.addCleanup(self.fixture.tearDown)
+ self.e, self.a, self.b = self.fixture.e, self.fixture.a, self.fixture.b
+
+ def open(self):
+ self.e.step(1000)
+ self.fixture.run_jobs()
+
+ def recover(self):
+ info = self.e.recover['XYZ']
+ info['retry_at'] = 0
+ self.e.step(1001)
+ self.fixture.run_jobs()
+
+ def test_failed_and_partial_rollback_remain_durable_until_confirmed_flat(self):
+ self.a.spot_buy = mock.Mock(side_effect=live.LiveError('rejected'))
+ self.b.fail_close = 1
+ self.open()
+ self.assertEqual(self.b.position, -99)
+ self.assertEqual(self.e.recover['XYZ']['phase'], 'rollback')
+ saved = json.loads(self.e.file.read_text(encoding='utf-8'))
+ self.assertEqual(saved['pending']['XYZ']['phase'], 'rollback')
+ self.b.partial_close = 5
+ self.recover()
+ self.assertEqual(self.b.position, -5)
+ self.assertIn('XYZ', self.e.recover)
+ self.recover()
+ self.assertEqual(self.b.position, 0)
+ self.assertEqual(self.e.recover, {})
+ self.assertEqual(self.e.pending, {})
+
+ def test_failed_cancel_blocks_entries_and_late_fill_is_closed_after_restart(self):
+ self.e.settings.entry_limit, self.e.settings.limit_hold_s = True, 0
+ self.b.limit_fill = 0
+ cancel = self.b.fut_cancel
+ self.b.fut_cancel = mock.Mock(side_effect=live.LiveError('timeout', sent=True))
+ self.open()
+ self.assertTrue(self.b.limits['L1']['open'])
+ self.assertEqual(self.e.recover['XYZ']['order_id'], 'L1')
+ self.assertEqual(self.a.orders, [])
+ self.e.step(2000)
+ self.assertTrue(self.e.jobs.empty())
+ self.b.fill_take_profit('L1') # fake exchange fills the still-working short
+ self.b.fut_cancel = cancel
+ again = cross.CrossEngine(Path(self.fixture.dir.name), start=False, real=True)
+ again.client_for = self.e.client_for
+ again.recover['XYZ']['retry_at'] = 0
+ # No current listing is needed: the intent contains its instrument snapshot.
+ again.step(2001)
+ while not again.jobs.empty():
+ again.do_job(again.jobs.get())
+ self.assertEqual(self.b.position, 0)
+ self.assertEqual(again.recover, {})
+ self.assertEqual(again.pending, {})
+
+ def test_unknown_submit_without_id_is_not_declared_absent_when_flat(self):
+ self.e.settings.entry_limit = True
+ self.b.fut_limit = mock.Mock(side_effect=live.LiveError('lost response', sent=True))
+ self.open()
+ self.assertIn('XYZ', self.e.recover)
+ self.recover()
+ self.assertIn('XYZ', self.e.recover)
+ self.assertEqual(self.b.fut_limit.call_count, 1)
+ self.assertIn('сверка', self.e.view()['real_pause'])
+
+ def test_no_order_when_intent_cannot_be_saved(self):
+ with mock.patch.object(cross, 'atomic_write_json', side_effect=OSError('disk full')):
+ # Queue directly: failing the pre-order durable intent must prevent every order.
+ self.e.do_job(('open', next(iter(self.e.links.values())), 0.5, 100))
+ self.assertEqual(self.a.orders + self.b.orders, [])
+
+ def test_successful_entry_is_handed_off_without_pending_recovery(self):
+ self.open()
+ self.assertEqual(len(self.e.positions), 1)
+ self.assertEqual(self.e.recover, {})
+ saved = json.loads(self.e.file.read_text(encoding='utf-8'))
+ self.assertEqual(saved['pending'], {})
+ self.assertEqual(len(saved['positions']), 1)
diff --git a/tests/test_live_uncertainty.py b/tests/test_live_uncertainty.py
new file mode 100644
index 0000000..95d1fcb
--- /dev/null
+++ b/tests/test_live_uncertainty.py
@@ -0,0 +1,30 @@
+"""Ambiguous mutating HTTP responses must trigger reconciliation, not a fresh entry."""
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import live
+
+
+class UncertainResponseTests(unittest.TestCase):
+ def request(self, method, status, body):
+ response = mock.Mock(status=status, will_close=True)
+ response.read.return_value = body
+ response.getheader.return_value = 'close'
+ connection = mock.Mock()
+ connection.getresponse.return_value = response
+ with mock.patch.object(live, '_take', return_value=(connection, False)):
+ with self.assertRaises(live.LiveError) as error:
+ live._http(method, 'https://exchange.invalid/order')
+ return error.exception
+
+ def test_server_error_on_submit_is_uncertain(self):
+ self.assertTrue(self.request('POST', 503, b'unavailable').sent)
+ self.assertTrue(self.request('DELETE', 500, b'error').sent)
+ self.assertFalse(self.request('GET', 503, b'unavailable').sent)
+ self.assertFalse(self.request('POST', 400, b'rejected').sent)
+
+ def test_unreadable_success_response_is_uncertain(self):
+ self.assertTrue(self.request('POST', 200, b'{truncated').sent)
diff --git a/tests/test_mirror_recovery.py b/tests/test_mirror_recovery.py
new file mode 100644
index 0000000..b2486c8
--- /dev/null
+++ b/tests/test_mirror_recovery.py
@@ -0,0 +1,96 @@
+"""Crash windows and filesystem failures must never cause a second entry."""
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
+import real_mirror
+from test_real import FakeClient
+
+
+class MirrorRecoveryTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.client = FakeClient(price=1)
+ self.settings = {'coins': {'k': {'on': True}}, 'exchange_tpsl': True}
+ self.threads = mock.patch.object(real_mirror.threading.Thread, 'start')
+ self.threads.start()
+ self.addCleanup(self.threads.stop)
+ self.journal = mock.patch.object(real_mirror, 'journal')
+ self.journal.start()
+ self.addCleanup(self.journal.stop)
+
+ def mirror(self):
+ return real_mirror.FuturesMirror('k', 'X', 'bybit', 'XUSDT', Path(self.tmp.name),
+ client_for=lambda ex: self.client, settings=lambda: self.settings)
+
+ def prepare(self, m):
+ m.hook('open', SimpleNamespace(uid=1, side='LONG', qty=10, entry=1, target=1.02))
+
+ def test_restart_before_submission_never_replays_entry(self):
+ m = self.mirror()
+ self.prepare(m)
+ self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'prepared')
+ again = self.mirror()
+ again._recover_open()
+ self.assertEqual(self.client.orders, [])
+ self.assertIsNone(again.position)
+
+ def test_crash_after_exchange_accepts_is_contained_and_never_replayed(self):
+ m = self.mirror()
+ self.prepare(m)
+ order = self.client.fut_order
+ def crash(*args, **kwargs):
+ self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'submitted')
+ order(*args, **kwargs)
+ raise SystemExit('power loss')
+ with mock.patch.object(self.client, 'fut_order', side_effect=crash):
+ with self.assertRaises(SystemExit):
+ m._open()
+ again = self.mirror()
+ again._recover_open()
+ self.assertEqual(self.client.position, 0)
+ self.assertTrue(again.gate())
+ again._close('paper closed')
+ self.assertEqual(again.state, 'recover')
+ self.prepare(again)
+ self.assertEqual(sum(not o[3] for o in self.client.orders), 1)
+
+ def test_accepted_fill_is_saved_before_take_profit_request(self):
+ m = self.mirror()
+ self.prepare(m)
+ def crash(*args):
+ saved = json.loads(m.file.read_text())['position']
+ self.assertEqual(saved['phase'], 'filled')
+ self.assertEqual(saved['coins'], 10)
+ raise SystemExit('power loss')
+ with mock.patch.object(self.client, 'fut_take_profit', side_effect=crash):
+ with self.assertRaises(SystemExit):
+ m._open()
+ again = self.mirror()
+ again._close('restart')
+ self.assertEqual(self.client.position, 0)
+ self.assertIsNone(again.position)
+
+ def test_failed_persistence_blocks_order_and_is_visible(self):
+ m = self.mirror()
+ with mock.patch.object(real_mirror, 'atomic_write_json', side_effect=OSError('disk full')):
+ self.prepare(m)
+ self.assertEqual(self.client.orders, [])
+ self.assertTrue(m.jobs.empty())
+ self.assertIn('disk full', m.gate())
+ m._watch()
+ self.assertIsNone(m.position)
+
+ def test_corrupt_saved_state_blocks_new_entries(self):
+ Path(self.tmp.name, 'real_positions_k.json').write_text('{broken', encoding='utf-8')
+ m = self.mirror()
+ self.prepare(m)
+ self.assertEqual(m.state, 'blocked')
+ self.assertTrue(m.gate())
+ self.assertEqual(self.client.orders, [])
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
new file mode 100644
index 0000000..3183f1a
--- /dev/null
+++ b/tests/test_persistence.py
@@ -0,0 +1,29 @@
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import persistence
+
+
+class AtomicSnapshotTests(unittest.TestCase):
+ def test_failed_replace_keeps_previous_snapshot_and_cleans_temporary_file(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'state.json'
+ persistence.atomic_write_json(path, {'position': 1})
+ with mock.patch.object(persistence.os, 'replace', side_effect=OSError('disk error')):
+ with self.assertRaises(OSError):
+ persistence.atomic_write_json(path, {'position': 2})
+ self.assertEqual(json.loads(path.read_text()), {'position': 1})
+ self.assertEqual(list(Path(directory).iterdir()), [path])
+
+ def test_invalid_numbers_do_not_destroy_existing_snapshot(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'state.json'
+ persistence.atomic_write_json(path, {'balance': 100})
+ with self.assertRaises(ValueError):
+ persistence.atomic_write_json(path, {'balance': float('nan')})
+ self.assertEqual(json.loads(path.read_text()), {'balance': 100})
diff --git a/tests/test_request_security.py b/tests/test_request_security.py
new file mode 100644
index 0000000..b94d031
--- /dev/null
+++ b/tests/test_request_security.py
@@ -0,0 +1,83 @@
+"""Requests retain their original authority through the local proxy."""
+import json
+import sys
+import unittest
+import urllib.error
+import urllib.request
+from email.message import Message
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
+import request_security as security
+import test_web_proxy as fixtures
+import web_proxy
+import web_sim
+
+
+class AuthorityTests(unittest.TestCase):
+ def request(self, host='localhost:8765', origin=None, peer='127.0.0.1'):
+ headers = Message()
+ headers['Host'] = host
+ headers['X-Sim'] = '1'
+ if origin is not None:
+ headers['Origin'] = origin
+ return SimpleNamespace(headers=headers, client_address=(peer, 1000))
+
+ def test_only_local_authorities_and_same_origin_are_accepted(self):
+ for host, origin in [('localhost:8765', 'http://localhost:8765'),
+ ('127.0.0.1:8765', None), ('[::1]:8765', 'http://[::1]:8765')]:
+ self.assertTrue(security.trusted_request(self.request(host, origin), command=True))
+ for host in ['attacker.example:8765', 'localhost.attacker.example', 'attacker@localhost:8765',
+ 'localhost:bad', 'localhost:8765/path', 'localhost:8765#x', 'localhost:8765,evil']:
+ self.assertFalse(security.trusted_request(self.request(host)))
+ for origin in ['null', 'http://attacker.example', 'http://localhost:1234', 'http://evil@localhost:8765']:
+ self.assertFalse(security.trusted_request(self.request(origin=origin), command=True))
+ self.assertFalse(security.trusted_request(self.request(peer='192.168.1.1')))
+
+ def test_duplicate_host_and_missing_command_header_are_rejected(self):
+ req = self.request()
+ req.headers['Host'] = 'evil.example'
+ self.assertFalse(security.trusted_request(req))
+ req = self.request()
+ del req.headers['X-Sim']
+ self.assertFalse(security.trusted_request(req, command=True))
+
+
+class ProxyIntegrationTests(unittest.TestCase):
+ def setUp(self):
+ self.sim = mock.patch.object(web_sim, 'SIM', SimpleNamespace(state=lambda: {'ok': True}), create=True)
+ self.sim.start()
+ self.addCleanup(self.sim.stop)
+ self.engine = fixtures.serve(web_sim.Handler)
+ self.backend = mock.patch.object(web_proxy, 'ENGINE', f'http://127.0.0.1:{self.engine.server_port}')
+ self.backend.start()
+ self.addCleanup(self.backend.stop)
+ self.proxy = fixtures.serve(web_proxy.Proxy)
+ for server in (self.engine, self.proxy):
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+
+ def test_host_is_checked_at_both_boundaries(self):
+ for server in (self.proxy, self.engine):
+ for method in ('GET', 'POST'):
+ req = urllib.request.Request(f'http://127.0.0.1:{server.server_port}/api/state',
+ data=b'{}' if method == 'POST' else None, method=method,
+ headers={'Host': 'attacker.example', 'X-Sim': '1'})
+ with self.assertRaises(urllib.error.HTTPError) as error:
+ urllib.request.urlopen(req)
+ self.assertEqual(error.exception.code, 403)
+
+ def test_proxy_preserves_browser_origin_and_static_assets_are_allowlisted(self):
+ base = f'http://127.0.0.1:{self.proxy.server_port}'
+ req = urllib.request.Request(base + '/api/state', headers={'Origin': base})
+ with urllib.request.urlopen(req) as response:
+ self.assertEqual(json.load(response), {'ok': True})
+ for asset, kind in [('app.js', 'text/javascript'), ('app.css', 'text/css')]:
+ with urllib.request.urlopen(base + '/static/' + asset) as response:
+ self.assertIn(kind, response.headers['Content-Type'])
+ self.assertGreater(len(response.read()), 10)
+ with self.assertRaises(urllib.error.HTTPError) as error:
+ urllib.request.urlopen(base + '/static/../keystore.py')
+ self.assertEqual(error.exception.code, 404)
diff --git a/tests/test_web_proxy.py b/tests/test_web_proxy.py
index 891ae7b..9974b91 100644
--- a/tests/test_web_proxy.py
+++ b/tests/test_web_proxy.py
@@ -53,7 +53,7 @@ class ProxyTests(unittest.TestCase):
got = json.loads(urllib.request.urlopen(base + "/api/state?x=1").read())
self.assertEqual(got, {"method": "GET", "path": "/api/state?x=1"})
req = urllib.request.Request(base + "/api/coin/A/start", data=json.dumps({"a": 1}).encode(),
- method="POST", headers={"Content-Type": "application/json"})
+ method="POST", headers={"Content-Type": "application/json", "X-Sim": "1"})
got = json.loads(urllib.request.urlopen(req).read())
self.assertEqual(got["body"], {"a": 1})
finally:
diff --git a/tests/web_context.test.cjs b/tests/web_context.test.cjs
new file mode 100644
index 0000000..56914b3
--- /dev/null
+++ b/tests/web_context.test.cjs
@@ -0,0 +1,89 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const path = require('node:path');
+
+function page() {
+ // Load actual application functions; omit DOM bootstrap and periodic polling only.
+ let source = fs.readFileSync(path.join(__dirname, '../web/app.js'), 'utf8');
+ source = source.replace(/^\(function (calcInit|restoreArbSettings)\(\) \{[\s\S]*?^\}\)\(\);/gm, '');
+ source = source.slice(0, source.indexOf('\n(async () => {'));
+ const elements = new Map();
+ const context = vm.createContext({
+ console, Intl, localStorage: {getItem: () => null, setItem() {}},
+ document: {getElementById(id) {
+ if (!elements.has(id)) elements.set(id, {textContent: '', innerHTML: '', classList: {toggle() {}}});
+ return elements.get(id);
+ }, querySelectorAll: () => []},
+ window: {addEventListener() {}}, confirm: () => true,
+ });
+ vm.runInContext(source, context);
+ vm.runInContext(`
+ var pending = [], commands = [], rendered = [];
+ api = (url, body) => body === undefined
+ ? new Promise(resolve => pending.push({url, resolve}))
+ : (commands.push(url), Promise.resolve({ok: true, message: 'ok'}));
+ renderBasis = () => rendered.push({venue: bxVenue, source: bx.source});
+ bxBuild = () => { bxBuilt = true; };
+ renderTiles = () => {};
+ tab = 'basis'; bxVenue = 'cross';
+ `, context);
+ return {context, run: code => vm.runInContext(code, context)};
+}
+const tick = () => new Promise(resolve => setImmediate(resolve));
+
+test('late simulation response cannot populate real mode or send a real close', async () => {
+ const {context: c, run} = page();
+ const old = run('loadBasis()');
+ run("bxSelect('cross_real')");
+ await run("basisClose(1, 'cross')");
+ assert.equal(c.commands.length, 0);
+ c.pending[1].resolve({source: 'real', settings: {}, positions: [{uid: 1}]});
+ await tick();
+ c.pending[0].resolve({source: 'paper', settings: {}, positions: [{uid: 1}]});
+ await old;
+ assert.equal(run('bx.source'), 'real');
+ await run("basisClose(1, 'cross')");
+ assert.equal(c.commands.length, 0);
+ await run("basisClose(1, 'cross_real')");
+ assert.equal(c.commands[0], '/api/basis/cross_real/close/1');
+});
+
+test('responses from an earlier visit to the same venue are discarded', async () => {
+ const {context: c, run} = page();
+ const old = run('loadBasis()');
+ run("bxSelect('cross_real'); bxSelect('cross')");
+ c.pending[2].resolve({source: 'current', settings: {}});
+ await tick();
+ c.pending[0].resolve({source: 'old', settings: {}});
+ await old;
+ assert.equal(run('bx.source'), 'current');
+});
+
+test('older poll cannot overwrite a newer completed poll', async () => {
+ const {context: c, run} = page();
+ const old = run('loadBasis()'), fresh = run('loadBasis()');
+ c.pending[1].resolve({source: 'fresh', settings: {}});
+ await fresh;
+ c.pending[0].resolve({source: 'old', settings: {}});
+ await old;
+ assert.equal(run('bx.source'), 'fresh');
+});
+
+test('coin switch rejects stale details and stale row actions', async () => {
+ const {context: c, run} = page();
+ run("selected = 'A'; detail = {key: 'A'}");
+ const old = run('loadDetail()');
+ run("selectCoin('B')");
+ await run("closePos(1, 'A'); trade('start')");
+ assert.equal(c.commands.length, 0);
+ c.pending[0].resolve({key: 'A'});
+ await old;
+ assert.equal(run('detail'), null);
+ run("detail = {key: 'B'}");
+ await run("closePos(1, 'A')");
+ assert.equal(c.commands.length, 0);
+ await run("closePos(1, 'B')");
+ assert.equal(c.commands[0], '/api/coin/B/close/1');
+});
diff --git a/web/app.css b/web/app.css
new file mode 100644
index 0000000..f493e2f
--- /dev/null
+++ b/web/app.css
@@ -0,0 +1,131 @@
+:root {
+ --bg: #0f1218; --panel: #161b23; --panel2: #1c222c; --line: #2a3240; --text: #e6e9ef; --muted: #8b95a7;
+ --accent: #4c8dff; --green: #2ecc71; --red: #ff5c5c; --yellow: #f5c542; --yellow-bg: rgba(245, 197, 66, 0.14);
+ --lead: #ff9f43; --follow: #4c8dff;
+}
+* { box-sizing: border-box; }
+body { margin: 0; background: var(--bg); color: var(--text); font: 13px/1.4 "Segoe UI", system-ui, sans-serif; }
+header { background: var(--panel); border-bottom: 1px solid var(--line); padding: 10px 16px; }
+.title { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
+.title h1 { font-size: 16px; margin: 0; font-weight: 600; }
+.title .hint { color: var(--muted); }
+.settings { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: flex-end; }
+.field { display: flex; flex-direction: column; gap: 3px; }
+.field label { color: var(--muted); font-size: 11px; white-space: nowrap; }
+.field input, .field select { background: var(--panel2); border: 1px solid var(--line); color: var(--text); border-radius: 6px;
+ padding: 5px 7px; width: 92px; font: inherit; }
+.field select { width: 230px; }
+.check { display: flex; align-items: center; gap: 6px; color: var(--text); font-size: 12px; padding-bottom: 6px; white-space: nowrap; }
+.more { display: none; margin-top: 8px; }
+.more.open { display: flex; }
+button { background: var(--panel2); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 6px 12px;
+ font: inherit; cursor: pointer; }
+button:hover { border-color: var(--accent); }
+button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
+button.start { background: rgba(46, 204, 113, 0.15); border-color: var(--green); color: var(--green); font-weight: 600; }
+button.stop { background: rgba(255, 92, 92, 0.12); border-color: var(--red); color: var(--red); font-weight: 600; }
+button:disabled { opacity: 0.35; cursor: default; }
+#settingsMsg { color: var(--muted); margin-left: 8px; }
+main { display: grid; grid-template-columns: 270px 1fr; min-height: calc(100vh - 120px); }
+aside { border-right: 1px solid var(--line); padding: 12px; display: flex; flex-direction: column; gap: 8px; overflow-y: auto; }
+aside h2, section h2 { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; margin: 0 0 4px; }
+.tile { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; cursor: pointer; position: relative; }
+.tile:hover { border-color: #3a4558; }
+.tile.active { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
+.tile .sym { font-size: 16px; font-weight: 700; }
+.tabs { display: flex; gap: 4px; padding: 8px 16px 0; background: var(--bg); border-bottom: 1px solid var(--line); }
+.tab { border-radius: 8px 8px 0 0; border-bottom: none; padding: 8px 18px; font-weight: 600; color: var(--muted); }
+.tab.on { background: var(--panel); color: var(--text); border-color: var(--line); }
+#arbRows tr { cursor: pointer; }
+td.plancell { white-space: normal; min-width: 380px; max-width: 460px; vertical-align: top; cursor: default; }
+div.plancell { white-space: normal; padding: 4px 2px 6px; font-size: 12px; position: sticky; left: 0;
+ max-width: min(1200px, calc(100vw - 60px)); }
+div.plancell ol.plan { font-size: 12.5px; margin-top: 4px; }
+.planbtn { font-size: 11px; padding: 2px 8px; white-space: nowrap; cursor: pointer; }
+ol.plan { margin: 0; padding-left: 18px; font-size: 11.5px; line-height: 1.45; }
+ol.plan li { margin-bottom: 2px; }
+#arbRows tr.detail td { background: var(--panel2); cursor: default; }
+th[data-s] { cursor: pointer; }
+th[data-s].sorted { color: var(--accent); }
+.exname { font-weight: 600; }
+.links { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
+.links a { color: var(--accent); text-decoration: none; font-size: 12px; border: 1px solid var(--line); border-radius: 6px;
+ padding: 2px 8px; background: var(--panel2); }
+.links a:hover { border-color: var(--accent); }
+.cex { font-size: 11px; font-weight: 600; border-radius: 4px; padding: 1px 6px; vertical-align: middle;
+ background: rgba(76, 141, 255, 0.15); color: var(--accent); border: 1px solid rgba(76, 141, 255, 0.4); }
+.fit { font-size: 11px; border-radius: 6px; padding: 3px 7px; margin: 4px 0 6px; }
+.fit-check { color: var(--muted); background: rgba(139, 149, 167, 0.1); }
+.fit-no { color: var(--red); background: rgba(255, 92, 92, 0.1); }
+.fit-near { color: var(--yellow); background: var(--yellow-bg); }
+.fit-ok, .fit-new { color: var(--green); background: rgba(46, 204, 113, 0.14); font-weight: 600; }
+.tile.fit-ok, .tile.fit-new { border-color: rgba(46, 204, 113, 0.6); box-shadow: 0 0 10px rgba(46, 204, 113, 0.25); }
+.tile.fit-new { animation: pulse 1.6s ease-in-out infinite; }
+@keyframes pulse { 50% { box-shadow: 0 0 18px rgba(46, 204, 113, 0.65); } }
+.tile.fit-ok.active, .tile.fit-new.active { border-color: var(--accent); }
+.tile.plus { border-style: dashed; text-align: center; padding: 14px 12px 10px; }
+.tile.plus .plusicon { font-size: 30px; line-height: 30px; color: var(--accent); font-weight: 300; }
+button.add { background: rgba(76, 141, 255, 0.15); border-color: var(--accent); color: var(--accent); padding: 3px 10px; }
+tr.leadrow td { background: rgba(46, 204, 113, 0.07); }
+.tile .route { color: var(--muted); font-size: 11px; margin: 2px 0 6px; }
+.tile .row { display: flex; justify-content: space-between; font-size: 12px; }
+.dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; position: absolute; top: 12px; right: 34px; background: #555; }
+.tile .del { position: absolute; top: 5px; right: 6px; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 6px;
+ background: transparent; color: var(--muted); font-size: 16px; line-height: 22px; cursor: pointer; }
+.tile .del:hover { background: rgba(231, 76, 60, 0.18); color: var(--red, #e74c3c); }
+.dot.run { background: var(--green); box-shadow: 0 0 6px var(--green); }
+.badge { background: var(--yellow-bg); color: var(--yellow); border-radius: 10px; padding: 0 7px; font-size: 11px; }
+.pos { color: var(--green); } .neg { color: var(--red); } .mut { color: var(--muted); }
+section.center { padding: 14px 18px; display: flex; flex-direction: column; gap: 12px; min-width: 0; }
+.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; }
+.coinhead { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; }
+.coinhead .name { font-size: 18px; font-weight: 700; }
+.coinhead .feeds { color: var(--muted); font-size: 12px; }
+.chartbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; gap: 10px; flex-wrap: wrap; }
+.legend { display: flex; gap: 16px; font-size: 12px; }
+.legend i { display: inline-block; width: 14px; height: 3px; vertical-align: middle; margin-right: 6px; border-radius: 2px; }
+.range button { padding: 3px 9px; font-size: 12px; }
+.range button.on { border-color: var(--accent); color: var(--accent); }
+canvas { width: 100%; height: 240px; display: block; }
+.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 8px; }
+.stat { background: var(--panel2); border-radius: 8px; padding: 8px 10px; }
+.stat .k { color: var(--muted); font-size: 11px; }
+.stat .v { font-size: 17px; font-weight: 600; margin-top: 2px; }
+.controls { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+.statusline { color: var(--muted); font-size: 12px; }
+table { width: 100%; border-collapse: collapse; font-size: 12px; }
+th { text-align: left; color: var(--muted); font-weight: 500; padding: 6px 8px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel); }
+td { padding: 6px 8px; border-bottom: 1px solid #222a35; white-space: nowrap; }
+td.why { white-space: normal; color: var(--muted); max-width: 320px; }
+tr.open td { background: var(--yellow-bg); }
+tr.open td:first-child { border-left: 3px solid var(--yellow); }
+tr.flash td { animation: flash 1.5s ease-out; }
+@keyframes flash { from { background: rgba(245, 197, 66, 0.45); } }
+.x { background: transparent; border: 1px solid var(--red); color: var(--red); border-radius: 50%; width: 22px; height: 22px;
+ padding: 0; line-height: 18px; font-weight: 700; }
+.x:hover { background: var(--red); color: #fff; }
+.tablewrap { max-height: 46vh; overflow: auto; }
+.empty { color: var(--muted); padding: 30px; text-align: center; }
+.realbar { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: 8px; padding: 6px 10px;
+ border: 1px dashed var(--line); border-radius: 8px; }
+.realbar.on { border: 1px solid var(--red); background: rgba(255, 92, 92, 0.08); }
+.realtag { background: var(--red); color: #fff; border-radius: 4px; padding: 0 5px; font-size: 10px; font-weight: 700; }
+.keygrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 10px; }
+.keycard { background: var(--panel2); border-radius: 8px; padding: 10px 12px; display: flex; flex-direction: column; gap: 6px; }
+.keycard input { background: var(--panel); border: 1px solid var(--line); color: var(--text); border-radius: 6px; padding: 5px 8px; }
+button.realon { background: rgba(255, 92, 92, 0.18); border-color: var(--red); color: var(--red); font-weight: 700; }
+.calcbtn { margin-left: auto; align-self: center; margin-bottom: 6px; border-color: var(--accent); color: var(--accent);
+ background: rgba(76, 141, 255, 0.12); font-weight: 600; }
+.calcbtn.on { background: var(--accent); color: #fff; }
+.calcpanel { position: fixed; top: 52px; right: 16px; z-index: 50; width: min(460px, calc(100vw - 32px)); max-height: calc(100vh - 70px);
+ overflow-y: auto; background: var(--panel); border: 1px solid var(--accent); border-radius: 10px; padding: 12px 14px;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); }
+.calchead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; font-size: 14px; }
+.calcgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 8px; }
+.calcgrid .field input { width: 100%; }
+.calcout { margin-top: 10px; display: flex; flex-direction: column; gap: 6px; }
+.calcout .big { background: var(--panel2); border-radius: 8px; padding: 8px 10px; }
+.calcout .big b { font-size: 18px; color: var(--green); }
+.calcout .row2 { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; }
+.calcout .note { color: var(--muted); font-size: 11.5px; }
+@media (max-width: 800px) { main { grid-template-columns: 1fr; } aside { flex-direction: row; overflow-x: auto; border-right: 0; border-bottom: 1px solid var(--line); } .tile { min-width: 200px; } }
diff --git a/web/app.js b/web/app.js
new file mode 100644
index 0000000..dde4afe
--- /dev/null
+++ b/web/app.js
@@ -0,0 +1,1224 @@
+const MAIN_FIELDS = [
+ ["mode", "Режим", "select"], ["stake", "Ставка, $"], ["leverage", "Плечо"], ["min_target_pct", "Тейк-профит, %"],
+ ["stop_loss_pct", "Стоп-лосс, %"], ["max_hold_seconds", "Удержание, с"], ["max_positions", "Позиций одновременно"],
+ ["entry_gap_seconds", "Между входами, с"], ["min_confidence", "Мин. уверенность"],
+ ["auto_stop_pct", "Автостоп: CEX опережает на, %"],
+ ["auto_tp", "Авто тейк-профит по прогнозу", "check"], ["require_leader", "Входить, только если ведущая правда ведёт", "check"],
+];
+const MORE_FIELDS = [
+ ["budget", "Бюджет, $"], ["cooldown_ms", "Пауза после сделки, мс"], ["lead_threshold_pct", "Отставание для входа, %"],
+ ["lead_window_ms", "Окно сравнения, мс"], ["vector_window_seconds", "Вектор за, с"], ["vector_min_move_pct", "Мин. движение, %"],
+ ["auto_tp_share_pct", "Доля догоняния, %"], ["auto_tp_horizon_seconds", "Горизонт прогноза, с"],
+ ["cut_loss_ticks", "Минус для закрытия, шагов"], ["max_data_age_ms", "Данные не старше, мс"],
+ ["leader_min_edge", "Перевес ведущей (корр.)"], ["basis_window_seconds", "Разрыв: обычный за, с"],
+ ["basis_entry_z", "Разрыв: вход, σ"], ["basis_exit_z", "Разрыв: выход, σ"], ["basis_min_gap_pct", "Разрыв: мин., %"],
+ ["auto_tp_learn", "Учить долю на истории", "check"], ["one_per_tick", "Одна позиция на шаг цены", "check"],
+ ["cut_loss", "Сразу закрывать в минусе", "check"],
+];
+let state = null, selected = localStorage.getItem("sim.coin") || null, detail = null;
+let detailEpoch = 0, detailRequest = 0, detailApplied = 0;
+let bxEpoch = 0, bxRequest = 0, bxApplied = 0, bxDataVenue = null;
+let range = +(localStorage.getItem("sim.range") || 300), seenOpen = new Set(), seenClosed = 0, settingsDirty = false;
+
+// all times on the page are Moscow time, whatever the computer's time zone
+const MSK = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", hour: "2-digit", minute: "2-digit", second: "2-digit"});
+const MSK_DAY = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", day: "2-digit", month: "2-digit"});
+const msk = seconds => MSK.format(new Date(seconds * 1000));
+const mskFull = seconds => {
+ const d = new Date(seconds * 1000), today = MSK_DAY.format(new Date());
+ return (MSK_DAY.format(d) === today ? "" : MSK_DAY.format(d) + " ") + MSK.format(d);
+};
+const fmt = (v, d = 4) => v == null || isNaN(v) ? "—" : (+v).toFixed(d);
+const price = v => v == null ? "—" : (+v).toPrecision(6);
+const money = v => (v >= 0 ? "+" : "") + (+v).toFixed(4) + " $";
+const cls = v => v > 0 ? "pos" : v < 0 ? "neg" : "mut";
+async function api(path, body) {
+ const r = await fetch(path, body === undefined ? {} : {method: "POST",
+ headers: {"Content-Type": "application/json", "X-Sim": "1"}, body: JSON.stringify(body)});
+ return r.json();
+}
+
+function buildSettings() {
+ const s = state.settings;
+ const make = (box, list) => {
+ box.innerHTML = "";
+ for (const [key, label, kind] of list) {
+ if (kind === "check") {
+ box.insertAdjacentHTML("beforeend", ` ${label} `);
+ } else if (kind === "select") {
+ const opts = Object.entries(state.modes).map(([k, v]) => `${v} `).join("");
+ box.insertAdjacentHTML("beforeend", `
${label} ${opts}
`);
+ } else {
+ box.insertAdjacentHTML("beforeend", `${label}
`);
+ }
+ }
+ };
+ make(document.getElementById("settingsMain"), MAIN_FIELDS);
+ make(document.getElementById("settingsMore"), MORE_FIELDS);
+ document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => settingsDirty = true));
+}
+function toggleMore() {
+ const m = document.getElementById("settingsMore");
+ m.classList.toggle("open");
+ document.getElementById("moreBtn").textContent = m.classList.contains("open") ? "Скрыть ▴" : "Ещё настройки ▾";
+}
+async function saveSettings() {
+ const body = {};
+ document.querySelectorAll("header [data-k]").forEach(el => body[el.dataset.k] = el.type === "checkbox" ? el.checked : el.value);
+ const r = await api("/api/settings", body);
+ const msg = document.getElementById("settingsMsg");
+ msg.textContent = r.ok ? "Настройки применены ко всем монетам" : "Ошибка: " + r.error;
+ msg.style.color = r.ok ? "var(--green)" : "var(--red)";
+ if (r.ok) { settingsDirty = false; await loadState(true); }
+}
+
+function leaderBadge(c) {
+ const l = c.leadership || {};
+ if (l.edge == null) return 'проверяется… ';
+ const edge = l.edge, who = edge >= 0 ? c.leader : c.follower;
+ const ok = !c.leader_block;
+ return `${who} ${ok ? "✓" : "✗"} (${Math.abs(l.pct ?? 0).toFixed(0)}%) `;
+}
+// Is the coin suitable for trades now: does the leader (DEX / KuCoin) really move before the futures?
+function suitability(c) {
+ const l = c.leadership || {}, edge = l.edge, min = c.min_edge ?? 0.1;
+ const tip = l.edge == null ? "" : `${c.leader}→${c.follower} ${l.lead.toFixed(2)} / ${c.follower}→${c.leader} ${l.follow.toFixed(2)} · перевес ${edge >= 0 ? "+" : ""}${edge.toFixed(2)}, нужно ${min}`;
+ const pct = l.pct ?? 0;
+ let level, text;
+ if (edge == null) {
+ level = "check"; text = `◌ проверяю, кто ведёт (${(c.grid_minutes || 0).toFixed(1)} из 2 мин данных)`;
+ } else if (edge >= min) {
+ const mins = l.since ? (c.now - l.since) / 60 : 0;
+ const fresh = mins < 2;
+ level = fresh ? "new" : "ok";
+ text = `● подходит: ${c.leader} опережает ${c.follower} на ${pct.toFixed(0)}%` +
+ (l.since ? ` · ${fresh ? "только что" : "уже " + mins.toFixed(0) + " мин"}, с ${msk(l.since).slice(0, 5)}` : "");
+ } else if (edge > 0) {
+ level = "near"; text = `◐ почти: ${c.leader} впереди на ${pct.toFixed(0)}%, мало`;
+ } else {
+ level = "no"; text = `○ не подходит: ${c.follower} опережает ${c.leader} на ${(-pct).toFixed(0)}%`;
+ }
+ const stop = c.auto_stop ? `⏸ ${c.auto_stop}
` : "";
+ return {level, html: `${text}
${stop}`};
+}
+function renderTiles() {
+ const box = document.getElementById("tiles");
+ box.innerHTML = state.coins.map(c => {
+ const realOn = !!(c.real && c.real.enabled);
+ if (realOn) c = {...c, trades: c.real.trades, wins: c.real.wins, net: c.real.net, unrealized: 0}; // exchange figures
+ const pnl = c.net + c.unrealized;
+ const fit = suitability(c);
+ return `
+ ${realOn ? '
РЕАЛ ' : ""}
+
+
×
+
${c.symbol} ${c.follower}
+ ${c.open ? `${c.open} откр. ` : ""}
+
сигнал: ${c.leader} → фьючерс ${c.follower} ${c.follow_ticker}${c.live ? "" : " · нет данных"}
+ ${suitability(c).html}
+
цена ${price(c.price)}
+
сделок ${c.trades} ${money(pnl)}
+
винрейт ${c.trades
+ ? `${(c.wins / c.trades * 100).toFixed(0)}% · ${c.wins} из ${c.trades} `
+ : '— '}
+
`;
+ }).join("") + ``;
+}
+async function loadState(rebuild) {
+ state = await api("/api/state");
+ 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;
+ renderTiles();
+}
+function selectCoin(key) {
+ detailEpoch++;
+ selected = key; localStorage.setItem("sim.coin", key);
+ seenOpen = new Set(); seenClosed = 0; detail = null;
+ document.getElementById("center").textContent = "Загрузка выбранной монеты…";
+ renderTiles(); refreshCenter();
+}
+function refreshCenter() { if (selected === SCANNER) loadScanner(); else loadDetail(); }
+
+// --- scanner panel -------------------------------------------------------------------------------
+const SCANNER = "__scanner__";
+let scannerBuilt = false;
+function scannerSkeleton() {
+ document.getElementById("center").innerHTML = `
+ Сканер новых монет
+
ищет монеты, где цена на DEX опережает фьючерсы (запись 15 мин на цикл, по кругу)
+
+
+
Минут на цикл
+
Монет за цикл (до 13)
+
▶ Запустить сканер
+
■ Остановить
+
Добавлять найденные в левую панель автоматически
+
+
+
+
+
+
Проверенные монеты — «Добавить» переносит монету в левую панель (остановленной); зелёные — где DEX опережал
+
+ Монета Проверок DEX опережал Последний вывод Фьючерс Пул DEX
+ Лаг, с t+1→t+5 Попад. t Когда
+
+
+ `;
+ scannerBuilt = true;
+}
+async function loadScanner() {
+ if (!document.getElementById("scRows")) scannerSkeleton();
+ const s = await api("/api/scanner");
+ if (selected !== SCANNER || !document.getElementById("scRows")) return;
+ if (s.error) { document.getElementById("scMsg").textContent = s.error; return; }
+ document.getElementById("scStart").disabled = s.running;
+ document.getElementById("scStop").disabled = !s.running;
+ document.getElementById("scAuto").checked = s.auto_add;
+ document.getElementById("scState").innerHTML = s.running
+ ? `● сканер работает · циклов ${s.cycles}` : `■ сканер остановлен · циклов ${s.cycles}`;
+ document.getElementById("scLog").textContent = s.log.join("\n");
+ document.getElementById("scRows").innerHTML = s.coins.map(c => {
+ let action;
+ if (c.in_list) action = 'в левой панели ';
+ else if (c.addable && c.leads) action = `+ Добавить `;
+ else if (c.addable) action = `+ Добавить для теста `;
+ else action = `${c.unsupported || "нельзя добавить"} `;
+ return `${c.symbol} ${c.checks}
+ ${c.leads} ${c.verdict} ${c.futures} ${c.futures_symbol}
+ ${c.dex_pool} ${c.lag} ${c.follow}% ${c.hit}
+ ${c.t_stat} ${c.last_lead || c.last_time} ${action} `;
+ }).join("") || 'Пока нет результатов — запустите сканер; первый цикл ≈ 20 минут ';
+}
+async function scanner(action) {
+ const body = action === "config" ? {auto_add: document.getElementById("scAuto").checked}
+ : {minutes: document.getElementById("scMin").value, coins: document.getElementById("scCoins").value};
+ await api(`/api/scanner/${action}`, body);
+ setTimeout(loadScanner, 1200);
+}
+async function addCoin(symbol) {
+ const r = await api("/api/scanner/add", {symbol});
+ document.getElementById("scMsg").innerHTML = r.ok ? `${r.message} ` : `${r.error} `;
+ await loadState(); loadScanner();
+}
+
+function centerSkeleton() {
+ document.getElementById("center").innerHTML = `
+
+
+
+
+
+
${[60, 300, 600].map(s => `${s / 60} мин `).join(" ")}
+
+
+
изменение цены в % от начала окна · ▲▼ — входы, ● — выходы
+
+
+
+
+ ▶ Старт
+ ■ Стоп
+ Закрыть все позиции
+ ↺ Сбросить статистику
+ …
+
+
+
+
+
+
Сделки — открытые сверху (жёлтым), ✕ закрывает по текущей цене
+
+ Время (МСК) Напр. Объём, $ Вход Выход / сейчас % Итог, $
+ Комиссия Причина Сек. Почему вошли
+
+
`;
+ document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === range));
+}
+function setRange(s) { range = s; localStorage.setItem("sim.range", s); document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === s)); drawChart(); }
+async function trade(action) { if (!coinReady()) return; const key = detail.key; await api(`/api/coin/${key}/${action}`, {}); loadDetail(); loadState(); }
+async function resetCoin() {
+ if (!coinReady() || !confirm(`Сбросить статистику ${detail.symbol} (${detail.leader} → ${detail.follower})?\nСделки, баланс и открытые позиции этой пары будут обнулены.`)) return;
+ const r = await api(`/api/coin/${selected}/reset`, {});
+ document.getElementById("cMsg").textContent = r.message || "";
+ seenOpen = new Set(); seenClosed = 0;
+ loadDetail(); loadState();
+}
+async function removeCoin(key) {
+ const c = state.coins.find(x => x.key === key);
+ if (!c || !confirm(`Удалить ${c.name}?\n\nСбор цен и сравнение для этой пары остановятся` +
+ (c.open ? `, открытые позиции (${c.open}) закроются по текущей цене` : "") +
+ `.\nВернуть можно через «+» → сканер → «Добавить».`)) return;
+ const r = await api(`/api/coin/${key}/remove`, {});
+ const wasSelected = selected === key;
+ if (wasSelected) selected = null;
+ await loadState();
+ if (wasSelected) selectCoin(selected || SCANNER);
+ alert(r.message || r.error || "");
+}
+function coinReady() { return !!detail && detail.key === selected; }
+async function closePos(uid, key = detail?.key) {
+ if (!coinReady() || key !== selected) return;
+ const r = await api(`/api/coin/${key}/close${uid ? "/" + uid : ""}`, {});
+ if (key === selected && document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.message || "";
+ loadDetail();
+}
+
+async function loadDetail() {
+ if (!selected || selected === SCANNER) return;
+ const key = selected, epoch = detailEpoch, request = ++detailRequest;
+ const d = await api(`/api/coin/${key}`);
+ if (key !== selected || epoch !== detailEpoch || request < detailApplied) return;
+ detailApplied = request;
+ if (d.error) { document.getElementById("center").innerHTML = `${d.error}
`; return; }
+ if (!document.getElementById("chart") || !detail || detail.key !== d.key) centerSkeleton();
+ detail = d;
+ document.getElementById("cName").innerHTML = `${d.symbol} фьючерс на ${d.follower}
+ сигнал: ${d.leader} → ставки: ${d.follower} ${d.follow_ticker} `;
+ const lat = v => v == null ? "" : ` · ~${v.toFixed(0)} мс`;
+ const linksBox = document.getElementById("cLinks");
+ const linksHtml = (d.links || []).map(l => `${l.label} ↗ `).join("");
+ if (linksBox.innerHTML !== linksHtml) linksBox.innerHTML = linksHtml;
+ document.getElementById("cFeeds").textContent = `${d.lead_status}${lat(d.lead_latency)} | ${d.follow_status}${lat(d.follow_latency)}`;
+ document.getElementById("lgLead").textContent = `${d.leader}: ${price(d.lead_price)}`;
+ document.getElementById("lgFollow").textContent = `${d.follower} ${d.follow_ticker}: ${price(d.bid)} / ${price(d.ask)}`;
+ const winPct = d.trades ? (d.wins / d.trades * 100).toFixed(0) + "%" : "—";
+ const realOn = !!(d.real && d.real.enabled);
+ const rb = document.getElementById("btnReal");
+ rb.textContent = realOn ? "● РЕАЛЬНАЯ торговля — выключить" : "Включить реальную торговлю";
+ rb.className = realOn ? "realon" : "";
+ let stats;
+ if (realOn) {
+ // real mode: every figure is from the exchange (its fill history for this coin, the account's balance)
+ const r = d.real, bal = real && real.balances && real.balances[d.exchange];
+ const age = bal && bal.time ? Math.round(Date.now() / 1000 - bal.time) : null;
+ const balText = !bal ? "нет ключей" : !bal.values ? `${bal.error} `
+ : Object.entries(bal.values).map(([k, v]) => `${k}: ${typeof v === "number" ? v.toFixed(4) : v}
`).join("")
+ + `${bal.error ? 'не обновился: ' + bal.error + " · " : ""}${age} с назад
`;
+ const stateText = {"": "нет", opening: "открывается…", open: "открыта", closing: "закрывается…", check: "проверка закрытия…"}[r.state] || r.state;
+ const src = r.source === "биржа" ? `история биржи, ${Math.round(Date.now() / 1000 - r.synced)} с назад` +
+ (r.sync_error ? ` · ${r.sync_error} ` : "") : `жду историю биржи${r.sync_error ? ": " + r.sync_error : ""} `;
+ stats = [
+ ["Баланс на бирже", balText, ""], ["Реальных сделок", r.trades, ""],
+ ["В плюс", r.trades ? `${r.winrate.toFixed(0)}% · ${r.wins} из ${r.trades}` : "—", ""],
+ ["PNL биржи (до комиссий)", money(r.gross), cls(r.gross)], ["Комиссии биржи", "−" + r.fees.toFixed(4) + " $", "neg"],
+ ["Итог после комиссий", money(r.net), cls(r.net)], ["Итог, % от объёма", r.net_pct == null ? "—" : r.net_pct.toFixed(3) + "%", cls(r.net_pct || 0)],
+ ["Реальная позиция", stateText + (r.problem ? `${r.problem}
` : "")
+ + (r.paused_s > 0 ? `пауза ${Math.ceil(r.paused_s / 60)} мин: ${r.last_error}
` : ""),
+ r.state || r.paused_s > 0 ? "neg" : ""],
+ ["Откуда цифры", `${src} `, ""],
+ ];
+ } else {
+ stats = [
+ ["Баланс", d.balance.toFixed(2) + " $", ""], ["Сделок", d.trades, ""], ["В плюс", winPct, ""],
+ ["Итог", money(d.net), cls(d.net)], ["Комиссии", d.fees.toFixed(4) + " $", ""],
+ ["Открыто", `${d.open} · ${money(d.unrealized)}`, cls(d.unrealized)],
+ ];
+ }
+ stats.push(
+ ["Сигнал", `${d.signal >= 0 ? "+" : ""}${d.signal.toFixed(3)}%`, cls(d.signal)],
+ ["Уверенность", d.confidence.toFixed(2), ""],
+ ["Кто ведёт", leaderBadge(d), ""],
+ ["Подходит для сделок", suitability(d).html, ""]);
+ if (state && state.settings.auto_tp) stats.push(["Прогноз", `${d.forecast.toFixed(3)}%`, ""]);
+ document.getElementById("stats").innerHTML = stats.map(([k, v, c]) => ``).join("");
+ document.getElementById("btnStart").disabled = d.running;
+ document.getElementById("btnStop").disabled = !d.running;
+ document.getElementById("cStatus").textContent = (d.running ? "● сделки открываются · " : "■ новые сделки остановлены (цены и прогноз работают) · ") + d.status;
+ if (d.message) document.getElementById("cMsg").textContent = d.message;
+ renderRows(d);
+ drawChart();
+}
+
+function renderRows(d) {
+ const t = mskFull;
+ const open = d.positions.map(p => {
+ const fresh = !seenOpen.has(p.uid); seenOpen.add(p.uid);
+ return `${t(p.opened)}${p.real ? ' РЕАЛ ' : ""} ${p.side} ${p.usd.toFixed(2)}
+ ${price(p.entry)} ${price(p.side === "LONG" ? d.bid : d.ask)} ${p.pct.toFixed(3)}%
+ ${money(p.pnl)} тейк ${price(p.target)} · стоп ${price(p.stop)}
+ открыта ${p.age.toFixed(0)} ${p.why}
+ ✕ `;
+ }).join("");
+ if (d.real && d.real.enabled) {
+ // real mode: closed trades are the real ones, rebuilt from the exchange's own fills
+ const rows = (d.real_trades || []).map(c => `
+ ${mskFull(c.closed)} РЕАЛ ${c.side} ${(c.entry * c.coins).toFixed(2)}
+ ${price(c.entry)} ${price(c.exit)} ${c.pct.toFixed(3)}%
+ ${money(c.net)}
+ ${c.fees.toFixed(4)}${c.exact ? "" : ' ≈ '}
+ PNL биржи ${money(c.gross)} ${(c.closed - c.opened).toFixed(0)} ${c.reason} `).join("");
+ document.getElementById("rows").innerHTML = open + rows || 'Реальных сделок пока нет ';
+ return;
+ }
+ const freshClosed = d.closed.length - seenClosed; seenClosed = d.closed.length;
+ const closed = d.closed.map((c, i) => `
+ ${mskFull(Date.parse(c.closed) / 1000)} ${c.side} ${c.usd.toFixed(2)} ${price(c.entry)} ${price(c.exit)}
+ ${c.pct.toFixed(3)}% ${money(c.net)} ${c.fee.toFixed(4)}
+ ${c.reason} ${c.hold.toFixed(0)} ${c.why} `).join("");
+ document.getElementById("rows").innerHTML = open + closed || 'Сделок пока нет ';
+}
+
+function drawChart() {
+ const cv = document.getElementById("chart"); if (!cv || !detail) return;
+ const dpr = window.devicePixelRatio || 1, w = cv.clientWidth, h = cv.clientHeight;
+ cv.width = w * dpr; cv.height = h * dpr;
+ const g = cv.getContext("2d"); g.scale(dpr, dpr); g.clearRect(0, 0, w, h);
+ const t1 = detail.now, t0 = t1 - range, pad = {l: 52, r: 10, t: 10, b: 22};
+ const norm = s => { const pts = s.filter(p => p[0] >= t0); if (!pts.length) return []; const b = pts[0][1]; return pts.map(p => [p[0], (p[1] / b - 1) * 100]); };
+ const L = norm(detail.lead_series), F = norm(detail.follow_series);
+ const all = L.concat(F).map(p => p[1]);
+ let lo = Math.min(-0.05, ...all), hi = Math.max(0.05, ...all); const span = hi - lo; lo -= span * 0.08; hi += span * 0.08;
+ const X = t => pad.l + (t - t0) / (t1 - t0) * (w - pad.l - pad.r), Y = v => pad.t + (hi - v) / (hi - lo) * (h - pad.t - pad.b);
+ g.strokeStyle = "#2a3240"; g.fillStyle = "#8b95a7"; g.font = "11px Segoe UI"; g.lineWidth = 1;
+ const raw = (hi - lo) / 5, mag = Math.pow(10, Math.floor(Math.log10(raw)));
+ const step = [1, 2, 5, 10].map(k => k * mag).find(s => s >= raw);
+ for (let v = Math.ceil(lo / step) * step; v <= hi; v += step) {
+ g.beginPath(); g.moveTo(pad.l, Y(v)); g.lineTo(w - pad.r, Y(v)); g.stroke();
+ g.fillText(v.toFixed(step < 0.01 ? 3 : 2) + "%", 4, Y(v) + 4);
+ }
+ for (let k = 0; k <= 4; k++) { const t = t0 + k * range / 4; g.fillText(msk(t), X(t) - 22, h - 6); }
+ const line = (pts, color, stepped) => {
+ if (!pts.length) return; g.strokeStyle = color; g.lineWidth = 1.8; g.beginPath();
+ pts.forEach((p, i) => { const x = X(p[0]), y = Y(p[1]); if (!i) g.moveTo(x, y); else { if (stepped) g.lineTo(x, Y(pts[i - 1][1])); g.lineTo(x, y); } });
+ g.lineTo(X(t1), Y(pts[pts.length - 1][1])); g.stroke();
+ };
+ line(L, getComputedStyle(document.body).getPropertyValue("--lead"), true);
+ line(F, getComputedStyle(document.body).getPropertyValue("--follow"), false);
+ // trade markers on the futures line
+ const at = t => { let best = null; for (const p of F) { if (p[0] <= t) best = p; else break; } return best || F[0]; };
+ const mark = (t, up, color, circle) => {
+ if (t < t0 || !F.length) return; const p = at(t); if (!p) return; const x = X(t), y = Y(p[1]);
+ g.fillStyle = color; g.beginPath();
+ if (circle) g.arc(x, y, 3.5, 0, 7); else if (up) { g.moveTo(x, y - 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); } else { g.moveTo(x, y + 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); }
+ g.fill();
+ };
+ for (const c of detail.closed) {
+ const tc = Date.parse(c.closed) / 1000; if (tc < t0) continue;
+ mark(tc - c.hold, c.side === "LONG", "#8b95a7"); mark(tc, false, c.net > 0 ? "#2ecc71" : "#ff5c5c", true);
+ }
+ for (const p of detail.positions) mark(p.opened, p.side === "LONG", "#f5c542");
+ if (!L.length && !F.length) { g.fillStyle = "#8b95a7"; g.fillText("копятся цены…", w / 2 - 40, h / 2); }
+}
+
+// --- arbitrage tab -------------------------------------------------------------------------------
+let tab = localStorage.getItem("sim.tab") || "sim", arb = null, arbSort = localStorage.getItem("arb.sort") || "net_transfer";
+let arbMarket = localStorage.getItem("arb.market") || "spot";
+let arbOpen = new Set(), arbExBuilt = false, feesFor = null;
+const isSpot = () => arbMarket === "spot";
+const val = (id, d) => { const v = parseFloat(document.getElementById(id).value); return isNaN(v) ? d : v; };
+// --- budget calculator (top of the page, every tab) -----------------------------------------------------------
+// One spot–futures trade of «stake» $: the coins bought on spot (stake + fees) and the short's futures money. With
+// E $ behind a short of N $ the short is liquidated at a rise of x = (E/N − mmr)/(1 + mmr), so for a wanted x:
+// E = N·((1 + mmr)·x + mmr) — the same formula the program checks before every short.
+const CALC_IDS = ["cStake", "cCount", "cLiq", "cEx", "cMmr", "cFee"];
+function calcToggle() {
+ const p = document.getElementById("calcPanel"), open = p.style.display === "none";
+ p.style.display = open ? "" : "none";
+ document.getElementById("calcBtn").classList.toggle("on", open);
+ if (open) calcRun();
+}
+function calcRun() {
+ const v = id => { const x = parseFloat(String(document.getElementById(id).value).replace(",", ".")); return isFinite(x) ? x : NaN; };
+ const stake = v("cStake"), n = Math.floor(v("cCount")), liq = v("cLiq"), ex = Math.floor(v("cEx")), mmr = v("cMmr") / 100,
+ fee = v("cFee") / 100;
+ const out = document.getElementById("calcOut");
+ try { localStorage.setItem("calc", JSON.stringify(Object.fromEntries(CALC_IDS.map(i => [i, document.getElementById(i).value])))); } catch (e) {}
+ if (![stake, n, liq, ex, mmr, fee].every(isFinite) || stake <= 0 || n < 1 || liq <= 0 || ex < 1 || mmr < 0 || fee < 0) {
+ out.innerHTML = 'Заполните поля положительными числами
'; return;
+ }
+ const spot = stake * (1 + fee); // the coins bought on spot, with the buy fee
+ const futFor = x => stake * ((1 + mmr) * x / 100 + mmr); // futures money for a liquidation x % above the entry
+ const fut = futFor(liq), money = x => x.toFixed(2) + " $";
+ const back = stake * (liq / 100); // what the short loses at the liquidation price
+ // what the program itself requires before an entry (cross.py: SPOT_NEED 1.01, FUT_NEED 1.03 or more for the
+ // liquidation reserve): spot of A ≥ 101 % of the stake, futures of B ≥ max(103 %, the reserve's money)
+ const pSpot = stake * 1.01, pFut = Math.max(stake * 1.03, fut);
+ const progLiq = ((pFut / stake) - mmr) / (1 + mmr) * 100;
+ // money on the accounts for the wanted move to the liquidation: the futures account carries the shorts, the spot
+ // account buys the coins; between exchanges every trade has its spot on one exchange and its short on another
+ const trades = Math.max(1, Math.floor(n * ex / 2)); // n per exchange, each trade takes two exchanges
+ const steps = [...new Set([25, 50, 100, 150, 200, Math.round(liq)])].sort((a, b) => a - b);
+ out.innerHTML = `
+ Цена может вырасти на
${liq}% до ликвидации шорта — для этого на счетах каждой биржи:
+
Фьючерсный счёт (${n} шорт.) ${money(n * fut)}
+
Спотовый счёт (${n} покупок монет) ${money(n * spot)}
+
С автопереводом между спотом и фьючерсами биржи ${money(n * Math.max(spot, fut))}
+
Под шорты: ${n} × ${money(fut)}; ликвидация при росте монеты на ${liq}% (шорт теряет ≈ ${money(back)} на сделку).
+ Сделки одной биржи: шорты на её фьючерсах, покупки — на её споте.
+ Всего на ${ex} ${ex === 1 ? "бирже" : "биржах"}:
${money(n * Math.max(spot, fut) * ex)}
+
чтобы каждая биржа могла быть и стороной спота, и стороной шорта в ${n} сделках. Минимум, если
+ все ${trades} сделок в одну сторону (спот на одних биржах, шорт на других): ${money(trades * (spot + fut))}
+ Одна сделка: спот / фьючерсы / обе ноги ${money(spot)} / ${money(fut)} / ${money(spot + fut)}
+ Спот-фьюч на одной бирже (обе ноги там же), ${n} сделок ${money(n * (spot + fut))}
+ До ликвидации Фьючерсы на 1 шорт Фьючерсы на ${n} шорт.
+ ${steps.map(x => `+${x}%
+ ${money(futFor(x))} ${money(n * futFor(x))} `).join("")}
+ По текущей логике программы на каждой бирже:
${money(n * Math.max(pSpot, pFut))} ,
+ всего на ${ex}:
${money(n * Math.max(pSpot, pFut) * ex)}
+
Фьючерсный / спотовый счёт ${money(n * pFut)} / ${money(n * pSpot)}
+ ${liq < progLiq - 0.5 ? `
Желаемые ${liq}% меньше, чем держит программа:
+ на фьючерсах будет ${money(n * pFut)} и ликвидация ≈ +${progLiq.toFixed(0)}% — дальше, чем вы просили.
` : ""}
+
Перед входом программа требует на споте биржи A 101% ставки, а на фьючерсах биржи B — не меньше
+ 103% ставки (ликвидация ≈ +${progLiq.toFixed(0)}%) или больше, если «Мин. запас до ликвидации» выше. Меньше — биржа
+ краснеет и не участвует в поиске.
`;
+}
+async function calcFromSettings() {
+ const r = await api("/api/basis?ex=cross_real");
+ if (!r || r.error) return;
+ const limits = ((r.balances || {}).rows || []).map(x => x.limit).filter(x => x != null);
+ document.getElementById("cStake").value = r.settings.amount;
+ document.getElementById("cLiq").value = r.settings.min_liq_pct;
+ if (limits.length) document.getElementById("cCount").value = Math.max(...limits);
+ const keyed = ((r.balances || {}).rows || []).filter(x => x.keys && x.on).length;
+ if (keyed) document.getElementById("cEx").value = keyed;
+ calcRun();
+}
+(function calcInit() {
+ let saved = {};
+ try { saved = JSON.parse(localStorage.getItem("calc") || "{}"); } catch (e) {}
+ for (const id of CALC_IDS) {
+ const el = document.getElementById(id);
+ if (saved[id] != null) el.value = saved[id];
+ el.addEventListener("input", calcRun);
+ }
+})();
+function showTab(name) {
+ if (name === "arb") name = "basis"; // the old «Арбитраж» is gone: the one mode lives in «basis»
+ tab = name; localStorage.setItem("sim.tab", name);
+ document.getElementById("simView").style.display = name === "sim" ? "" : "none";
+ document.getElementById("basisView").style.display = name === "basis" ? "" : "none";
+ document.getElementById("realView").style.display = name === "real" ? "" : "none";
+ document.getElementById("tabSim").classList.toggle("on", name === "sim");
+ document.getElementById("tabArb").classList.toggle("on", name === "basis");
+ document.getElementById("tabReal").classList.toggle("on", name === "real");
+ if (name === "basis") loadBasis();
+ if (name === "real") { realBuilt = false; loadReal(); }
+}
+
+// --- real trading: keys, switches, journal -------------------------------------------------------
+let real = null, realBuilt = false;
+async function loadReal() {
+ real = await api("/api/real");
+ const s = real.simulator;
+ const tpsl = document.getElementById("simRealTpsl");
+ if (document.activeElement !== tpsl) tpsl.checked = s.exchange_tpsl !== false;
+ const trBox = document.getElementById("simRealTransfer");
+ if (document.activeElement !== trBox) trBox.checked = s.auto_transfer !== false;
+ const slBox = document.getElementById("simRealSl");
+ if (document.activeElement !== slBox) slBox.value = s.sl_pct ?? 1.5;
+ const pingBox = document.getElementById("simRealPing");
+ if (document.activeElement !== pingBox) pingBox.value = s.max_ping_ms ?? 400;
+ const fees = Object.entries(s.fees || {}).map(([e, p]) => `${e} ${p.toFixed(3)}%`).join(", ");
+ const lat = Object.entries(real.latency || {}).map(([h, ms]) => `${h.split(".").slice(0, -1).join(".")} ${ms.toFixed(0)} мс`).join(", ");
+ document.getElementById("simRealFees").textContent = (fees ? `· комиссия с биржи: ${fees}` : "") + (lat ? ` · задержка до бирж: ${lat}` : "");
+ const realCoins = state ? state.coins.filter(c => c.real && c.real.enabled).map(c => c.symbol) : [];
+ document.getElementById("simReal").classList.toggle("on", realCoins.length > 0);
+ document.getElementById("simRealHint").innerHTML = realCoins.length
+ ? `РЕАЛЬНАЯ ТОРГОВЛЯ: ${realCoins.join(", ")} · остальные монеты — виртуальные сделки`
+ : "виртуальные сделки, ордера на биржи не отправляются";
+ if (tab !== "real") return;
+ if (!realBuilt) {
+ document.getElementById("keyCards").innerHTML = Object.entries(real.keys).map(([ex, k]) => `
+
${k.name}
+
+
+
Сохранить
+ Проверить (баланс)
+ Удалить
+
`).join("");
+ realBuilt = true;
+ }
+ for (const [ex, k] of Object.entries(real.keys)) {
+ document.getElementById(`kst-${ex}`).innerHTML = k.set ? `ключ сохранён: ${k.key} ` : 'ключей нет ';
+ }
+ document.getElementById("realJournal").innerHTML = real.journal.map(j => `
+ ${mskFull(j.time)} ${j.tab === "basis" ? "Арбитраж" : "Симулятор"} ${j.exchange} ${j.coin}
+ ${{open: "открытие", close: "закрытие", orphan: "закрытие осиротевшей", transfer: "перевод USDT"}[j.action] || j.action}
+ ${j.text} `).join("")
+ || 'Реальных ордеров ещё не было ';
+}
+async function keySave(ex) {
+ const key = document.getElementById(`kk-${ex}`), secret = document.getElementById(`ks-${ex}`);
+ const r = await api(`/api/real/keys/${ex}`, {api_key: key.value, api_secret: secret.value});
+ document.getElementById(`kmsg-${ex}`).innerHTML = r.ok ? 'сохранено ' : `${r.error} `;
+ if (r.ok) { key.value = ""; secret.value = ""; }
+ loadReal();
+}
+async function keyCheck(ex) {
+ const msg = document.getElementById(`kmsg-${ex}`);
+ msg.textContent = "проверяю…";
+ const r = await api(`/api/real/keys/${ex}/check`, {});
+ msg.innerHTML = r.ok ? 'ключи работают: ' + Object.entries(r.balances).map(([k, v]) =>
+ `${k} ${typeof v === "number" ? v.toFixed(2) : v}`).join(" · ") + " " : `${r.error} `;
+}
+async function keyDelete(ex) {
+ if (!confirm("Удалить сохранённые ключи этой биржи?")) return;
+ await api(`/api/real/keys/${ex}/delete`, {});
+ document.getElementById(`kmsg-${ex}`).textContent = "удалены";
+ loadReal();
+}
+async function coinReal() {
+ if (!coinReady()) return;
+ const want = !(detail.real && detail.real.enabled);
+ if (want) {
+ const keys = real && real.keys[detail.exchange];
+ if (!keys || !keys.set) { alert(`Сначала сохраните API-ключи ${detail.follower} во вкладке «Реальная торговля · API-ключи».`); return; }
+ if (!confirm(`Включить РЕАЛЬНУЮ торговлю для ${detail.symbol} (${detail.follower} ${detail.follow_ticker})?\n\n` +
+ "Каждая новая позиция этой монеты будет открываться настоящим рыночным ордером на фьючерсе " +
+ `(ставка × плечо из настроек)${real.simulator.exchange_tpsl !== false ? ", с TP и SL на бирже" : ""}. ` +
+ "Одна сделка за раз: следующая — только после подтверждённого закрытия.")) return;
+ }
+ const r = await api("/api/real/simulator", {coin: detail.key, enabled: want});
+ document.getElementById("cMsg").textContent = r.ok ? (want ? "реальная торговля включена" : "реальная торговля выключена") : r.error;
+ await loadState(); await loadReal(); loadDetail();
+}
+async function simRealTransfer() {
+ const r = await api("/api/real/simulator", {auto_transfer: document.getElementById("simRealTransfer").checked});
+ document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error;
+ loadReal();
+}
+async function simRealPing() {
+ const r = await api("/api/real/simulator", {max_ping_ms: document.getElementById("simRealPing").value});
+ document.getElementById("simRealMsg").textContent = r.ok ? "порог пинга сохранён" : r.error;
+ loadReal();
+}
+async function simRealSl() {
+ const r = await api("/api/real/simulator", {sl_pct: document.getElementById("simRealSl").value});
+ document.getElementById("simRealMsg").textContent = r.ok ? "стоп-лосс сохранён" : r.error;
+ loadReal();
+}
+async function simRealTpsl() {
+ const r = await api("/api/real/simulator", {exchange_tpsl: document.getElementById("simRealTpsl").checked});
+ document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error;
+ loadReal();
+}
+async function basisReal() {
+ if (!basisReady()) return;
+ const want = !bx.settings.real;
+ if (want && bx.mode === "cross") {
+ const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange);
+ if (ready.length < 2) { alert("Нужны API-ключи хотя бы двух включённых бирж (вкладка «Реальная торговля · API-ключи»)."); return; }
+ if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Между биржами»?\n\nБиржи с ключами: ${ready.join(", ")}.\n\nПри входе: шорт на бирже B, ` +
+ `затем покупка тех же монет на споте биржи A на ${bx.settings.amount} $; при возврате разницы к обычной — выкуп шорта и продажа ` +
+ "спота. Нужны USDT на споте A и на фьючерсах B. Одна сделка за раз; изменение баланса считается с момента «Старт».")) return;
+ } else if (want) {
+ const keys = (real && real.keys[bxVenue]) || {};
+ if (!keys.set) { alert(`Сначала сохраните API-ключи ${bx.venue} во вкладке «Реальная торговля · API-ключи».`); return; }
+ if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Спот-фьюч» на ${bx.venue}?\n\nПри входе: покупка монеты на споте на ` +
+ `${bx.settings.amount} $ и шорт того же количества на фьючерсе; при схождении — выкуп шорта и продажа спота.`)) return;
+ }
+ const r = await api(`/api/basis/${bxVenue}/settings`, {real: want});
+ document.getElementById("bxMsg").textContent = r.ok ? "" : r.error;
+ loadBasis();
+}
+
+// --- spot–futures tab --------------------------------------------------------------------------
+// «Арбитраж»: the simulation and real trading — two engines, each with its own Start / Stop, settings and trades
+const BX_VENUES = [["cross", "Симуляция"], ["cross_real", "● Реальная торговля"]];
+const BX_READY = new Set(["cross", "cross_real"]);
+// «between exchanges»: spot on A, perp on B — its own settings and tables
+const CX_FIELDS = [
+ ["amount", "Сумма сделки, $"], ["min_net_pct", "Мин. чистая прибыль для входа, %"],
+ ["max_gap_pct", "Макс. разница, %"], ["history_min", "Наблюдать пару не меньше, мин"],
+ ["exit_over_usual_pct", "Закрыть при разнице ≤ обычной + , %"],
+ ["exit_hold_s", "Выход: условие держится не меньше, с (0 — сразу)"],
+ ["stop_widen_pct", "Стоп: разница шире входа на, % (0 — нет)"],
+ ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["cooldown_s", "Пауза по монете, с"],
+ ["min_turnover", "Мин. оборот каждой ноги 24ч, $"], ["limit_hold_s", "Лимитный вход: ждать, с"],
+ ["max_spread_pct", "Макс. спред каждой ноги, % (0 — нет)"],
+ ["confirm_ms", "Подтверждение по стакану: пауза между 2 проверками, мс"],
+ ["min_liq_pct", "Мин. запас до ликвидации шорта при входе, %"],
+ ["liq_close_pct", "Закрыть, если до ликвидации меньше, % (0 — нет)"]];
+const CX_CHECKS = [["search_sf", "Искать: спот → фьючерс между биржами"], ["search_in", "Искать: спот → фьючерс внутри биржи"],
+ ["search_ss", "Искать: спот → спот между биржами (реально — из запаса монеты на бирже продажи)"],
+ ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами внутри биржи (реальный режим)"],
+ ["entry_ioc", "Вход первой ногой лимитным IOC по подтверждённой цене: не исполнился — сделки нет (реальный режим)"],
+ ["entry_limit", "Вход лимитным шортом с ожиданием «Лимитный вход: ждать, с» (если IOC выключен)"],
+ ["fees_auto", "Комиссии сами корректируются по завершённым реальным сделкам"]];
+const CX_EX = ["Bybit", "Binance", "MEXC", "HTX", "Gate"];
+// the balances card: built once (the fee fields keep what is typed), its figures refreshed with every update
+function cxBalBuild() {
+ document.getElementById("cxBal").innerHTML = CX_EX.map(e => `
+ ${e}
+ вкл
+ — — — — —
+ 0 /
+
+
${e === "Bybit"
+ ? `` : ""} `).join("");
+ document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => el.addEventListener("input", () => {
+ el.dataset.dirty = "1"; document.getElementById("cxBalMsg").textContent = "есть изменения — нажмите «Сохранить комиссии и лимиты»"; }));
+}
+function cxBalRender() {
+ const b = bx.balances, s = bx.settings;
+ if (!b) return;
+ const money = v => v == null ? "—" : v.toFixed(2);
+ const chg = (p, usd) => p == null ? '— '
+ : `${pct(p, 2)}${usd != null ? ` (${dollars(usd)} $) ` : ""} `;
+ for (const r of b.rows) {
+ const e = r.exchange, on = document.getElementById(`cxon-${e}`);
+ if (!on) continue;
+ on.checked = r.on;
+ // too little money for a trade of «Сумма»: red, out of the search until it is topped up (then back by itself)
+ const tr = document.getElementById(`cxrow-${e}`);
+ tr.style.background = r.low_funds ? "rgba(239, 68, 68, 0.16)" : "";
+ tr.style.boxShadow = r.low_funds ? "inset 3px 0 0 #ef4444" : "";
+ document.getElementById(`cxk-${e}`).innerHTML = (r.low_funds
+ ? `${r.low_funds} — не участвует в поиске, вернётся сама после пополнения ` : "") +
+ (!r.keys ? "нет API-ключей"
+ : r.error ? `ошибка чтения `
+ : r.age != null ? `${r.age.toFixed(0)} с назад` : "");
+ document.getElementById(`cxs-${e}`).innerHTML = r.unified ? `${money(r.spot)} единый счёт ` : money(r.spot);
+ document.getElementById(`cxf-${e}`).textContent = r.unified ? "—" : money(r.futures);
+ document.getElementById(`cxc-${e}`).textContent = r.coins ? money(r.coins) : r.keys ? "0.00" : "—";
+ document.getElementById(`cxt-${e}`).innerHTML = `${money(r.total)} `;
+ document.getElementById(`cxd-${e}`).innerHTML = chg(r.change_pct, r.start != null && r.total != null ? r.total - r.start : null);
+ const oc = document.getElementById(`cxo-${e}`);
+ oc.textContent = r.open_count; oc.className = r.open_count >= r.limit ? "neg" : "";
+ const li = document.querySelector(`#cxBal input[data-cxlimit="${e}"]`);
+ if (document.activeElement !== li && !li.dataset.dirty) li.value = r.limit;
+ for (const leg of ["spot", "fut", "fut_innovation"]) {
+ const el = document.querySelector(`#cxBal input[data-cxfee="${e}|${leg}"]`);
+ if (!el) continue;
+ if (document.activeElement !== el && !el.dataset.dirty) el.value = r[`fee_${leg}`];
+ document.getElementById(`cxsrc-${e}-${leg}`).textContent = r[`fee_${leg}_src`] || "базовая";
+ }
+ }
+ document.getElementById("cxBalTotal").innerHTML = `Всего на всех биржах с ключами ` +
+ (b.start_time ? ` · отсчёт с запуска ${mskFull(b.start_time)} МСК${b.start_total != null ? ` (было ${money(b.start_total)} $)` : " — жду первые балансы после запуска"} `
+ : ' · изменение считается с момента запуска реальной торговли (кнопка «Старт») ') +
+ `${money(b.total)} ${chg(b.change_pct, b.change_usd)} `;
+}
+async function crossToggle(ex, on) {
+ if (!basisReady()) return;
+ const r = await api(`/api/basis/${bxVenue}/settings`, {[`use_${ex.toLowerCase()}`]: on});
+ document.getElementById("cxBalMsg").textContent = r.ok ? `${ex}: ${on ? "включена в поиск и торговлю" : "выключена из поиска и торговли"}` : r.error;
+ loadBasis();
+}
+async function crossFeesSave() {
+ if (!basisReady()) return;
+ const fees = {}, limits = {};
+ document.querySelectorAll("#cxBal input[data-cxfee]").forEach(el => {
+ const [e, leg] = el.dataset.cxfee.split("|"); (fees[e] = fees[e] || {})[leg] = el.value; });
+ document.querySelectorAll("#cxBal input[data-cxlimit]").forEach(el => limits[el.dataset.cxlimit] = el.value);
+ const r = await api(`/api/basis/${bxVenue}/settings`, {fees, limits});
+ 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);
+ loadBasis();
+}
+const CX_ROWS_HEAD = `Монета Тип Покупка на Продажа / шорт на
+ Покупка (ask) Продажа (bid) Разница для входа
+ Обычная
+ Выше обычной
+ Чистая прибыль, %
+ Наблюдаем, мин Funding (шорт) Объём по ценам, $
+ Мин. вход, $
+ Оборот 24ч `;
+const CX_POS_HEAD = `Время (МСК) Монета Тип · биржи Монет Куплено (A) Продано / шорт (B)
+ Разница при входе Обычная (цель) Разница сейчас
+ До ликвидации, %
+ Funding $ Комиссии $ Если закрыть сейчас `;
+let bxHeads = null;
+let bxVenue = ["cross", "cross_real"].includes(localStorage.getItem("bx.venue")) ? localStorage.getItem("bx.venue") : "cross", bx = null, bxBuilt = false, bxDirty = false;
+let bxSort = localStorage.getItem("bx.sort") || "entry_gap";
+const BX_FIELDS = [
+ ["amount", "Сумма сделки, $"], ["min_gap_pct", "Мин. расхождение для входа, %"], ["max_gap_pct", "Макс. расхождение, %"],
+ ["exit_gap_pct", "Закрыть при разнице ≤, %"], ["stop_gap_pct", "Стоп: разница ≥, % (0 — нет)"],
+ ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["max_positions", "Макс. позиций"], ["cooldown_s", "Пауза по монете, с"],
+ ["min_turnover", "Мин. оборот 24ч, $"], ["min_depth", "Мин. объём по ценам, $"], ["new_days", "Новые: фьючерсу ≤ дней"],
+ ["limit_hold_s", "Лимитный вход: ждать, с"], ["max_real_positions", "Одновременно реальных позиций"],
+ ["spot_fee", "Комиссия спот, %"], ["fut_fee", "Комиссия фьюч, %"],
+ ["fut_fee_innovation", "Комиссия фьюч зоны инноваций, %", "bybit"]];
+const BX_CHECKS = [["use_new", "Новые монеты"], ["use_innovation", "Зона инноваций / метка «новая» биржи"], ["use_memes", "Мемкойны"],
+ ["all_coins", "Все монеты со спотом и фьючем"],
+ ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами (реальный режим)"],
+ ["entry_limit", "Вход лимитным шортом по цене сигнала, потом спот (реальный режим)"]];
+function bxTabs() {
+ document.getElementById("bxTabs").innerHTML = BX_VENUES.map(([k, n]) => BX_READY.has(k)
+ ? `${n} `
+ : `${n} · скоро `).join(" ");
+}
+function bxSelect(k) {
+ bxEpoch++; bx = null; bxDataVenue = null; bxDirty = false;
+ setBasisReady(false);
+ document.getElementById("bxPos").innerHTML = "";
+ document.getElementById("bxMsg").textContent = "Загрузка выбранного режима…";
+ bxVenue = k; localStorage.setItem("bx.venue", k); bxBuilt = false;
+ bxSort = "net_pct"; // the net profit decides the entry — sorted by it
+ bxTabs(); loadBasis();
+}
+function bxBuild(s) {
+ const cross = true; // «Арбитраж»: one mode, simulation or real
+ if (!bxHeads) bxHeads = {rows: document.getElementById("bxRowsHead").innerHTML, pos: document.getElementById("bxPosHead").innerHTML,
+ title: document.getElementById("bxTitle").textContent, help: document.getElementById("bxHelp").innerHTML};
+ document.getElementById("bxRowsHead").innerHTML = cross ? CX_ROWS_HEAD : bxHeads.rows;
+ document.getElementById("bxPosHead").innerHTML = cross ? CX_POS_HEAD : bxHeads.pos;
+ document.getElementById("bxTitle").textContent = (bxVenue === "cross_real" ? "Арбитраж · РЕАЛЬНАЯ торговля" : "Арбитраж · симуляция") +
+ ": купить там, где дешевле, продать там, где дороже, закрыть при возврате разницы к обычной";
+ document.getElementById("bxHelp").innerHTML =
+ "Связки трёх типов (включаются галочками ниже): спот → фьючерс между биржами (покупка на споте A, шорт на фьючерсе B), " +
+ "спот → фьючерс внутри биржи (обе ноги на одной бирже) и спот → спот (покупка на споте A, продажа тех же монет на " +
+ "споте B из запаса, который лежит на B; при закрытии — продажа на A и выкуп запаса на B). Для каждой связки программа следит за " +
+ "обычной разницей (~30 мин). Вход — по «Чистой прибыли, %»: сколько останется, если разница вернётся к обычной, за вычетом запаса " +
+ "выхода и 4 комиссий (из таблицы бирж). Биржи, их лимиты сделок и комиссии — в карточке «Биржи». Симуляция и реальная торговля — " +
+ "отдельные вкладки: у каждой свой «Старт», свои настройки и сделки. Деньги между биржами программа не переводит.";
+ document.getElementById("bxReal").style.display = "none"; // the tab decides paper or real
+ document.getElementById("bxAdoptBox").style.display = cross ? "none" : "";
+ document.getElementById("cxBalCard").style.display = cross ? "" : "none";
+ if (cross) cxBalBuild();
+ const fieldsList = cross ? CX_FIELDS : BX_FIELDS, checks = cross ? CX_CHECKS : BX_CHECKS;
+ document.getElementById("bxSettings").innerHTML =
+ fieldsList.filter(([, , only]) => !only || only === bxVenue) // a field of one exchange only
+ .map(([k, l]) => `${l}
`).join("") +
+ checks.map(([k, l]) => ` ${l} `).join("");
+ document.querySelectorAll("#bxSettings input").forEach(el => el.addEventListener("input", () => {
+ bxDirty = true; document.getElementById("bxMsg").textContent = "есть несохранённые изменения"; }));
+ document.querySelectorAll("#basisView th[data-b]").forEach(th => th.onclick = () => {
+ bxSort = th.dataset.b; localStorage.setItem("bx.sort", bxSort); renderBasis(); });
+ bxBuilt = true; bxDirty = false;
+}
+async function basisSave() {
+ if (!basisReady()) return;
+ const body = {};
+ document.querySelectorAll("#bxSettings input").forEach(el => body[el.dataset.bx] = el.type === "checkbox" ? el.checked : el.value);
+ const r = await api(`/api/basis/${bxVenue}/settings`, body);
+ document.getElementById("bxMsg").textContent = r.ok ? "сохранено" : r.error;
+ if (r.ok) { bxBuilt = false; loadBasis(); }
+}
+async function basisRun() {
+ if (!basisReady()) return;
+ if (bxVenue === "cross_real" && !bx.settings.running) {
+ const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange);
+ if (!ready.length) { alert("Нет включённых бирж с API-ключами (вкладка «Реальная торговля · API-ключи»)."); return; }
+ const s = bx.settings, kinds = [s.search_sf && "спот → фьючерс между биржами", s.search_in && "спот → фьючерс внутри биржи",
+ s.search_ss && "спот → спот (из запаса монет)"].filter(Boolean).join(", ");
+ if (!confirm(`Запустить РЕАЛЬНУЮ торговлю?\n\nБиржи: ${ready.join(", ")}.\nСвязки: ${kinds || "ни одной не включено"}.\n` +
+ `Сумма сделки: ${s.amount} $. Настоящие ордера с вашими API-ключами; одна сделка за раз, лимиты сделок по биржам.\n` +
+ "Изменение баланса считается с этого момента.")) return;
+ }
+ const r = await api(`/api/basis/${bxVenue}/settings`, {running: !bx.settings.running});
+ document.getElementById("bxMsg").textContent = r.ok ? "" : r.error;
+ loadBasis();
+}
+async function basisClose(uid, venue = bxDataVenue) {
+ if (!basisReady() || venue !== bxVenue) return;
+ const r = await api(`/api/basis/${venue}/close${uid ? "/" + uid : ""}`, {});
+ if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.message || "";
+ loadBasis();
+}
+async function basisAdopt() {
+ if (!basisReady()) return;
+ const base = document.getElementById("bxAdopt").value.trim();
+ if (!base) return;
+ const r = await api(`/api/basis/${bxVenue}/adopt`, {base, price: document.getElementById("bxAdoptPrice").value.trim()});
+ document.getElementById("bxAdoptMsg").innerHTML = `${r.message || r.error} `;
+ loadBasis();
+}
+async function basisReset() {
+ if (!basisReady()) return;
+ if (!confirm("Сбросить статистику спот-фьюч? Сделки и открытые позиции будут удалены.")) return;
+ await api(`/api/basis/${bxVenue}/reset`, {}); loadBasis();
+}
+function basisReady() { return !!bx && bxDataVenue === bxVenue; }
+function setBasisReady(ready) {
+ document.querySelectorAll("#basisView button, #basisView input").forEach(el => {
+ if (!el.closest("#bxTabs")) el.disabled = !ready;
+ });
+}
+async function loadBasis() {
+ if (tab !== "basis") return;
+ bxTabs();
+ const venue = bxVenue, epoch = bxEpoch, request = ++bxRequest;
+ const r = await api(`/api/basis?ex=${venue}`);
+ if (venue !== bxVenue || epoch !== bxEpoch || request < bxApplied) return;
+ bxApplied = request;
+ if (r.error) { document.getElementById("bxStatus").textContent = r.error; return; }
+ bx = r; bxDataVenue = venue;
+ if (!bxBuilt) bxBuild(bx.settings);
+ renderBasis();
+ setBasisReady(true);
+}
+const dollars = v => v == null ? "—" : (v >= 0 ? "+" : "−") + Math.abs(v).toFixed(2);
+const hold = s => s < 60 ? `${s.toFixed(0)} с` : s < 3600 ? `${(s / 60).toFixed(1)} мин` : `${(s / 3600).toFixed(1)} ч`;
+const kusd = v => v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(0) + "K" : v.toFixed(0);
+// how fresh the prices of an open position are (the fast watch looks several times a second)
+const freshness = p => p.price_age == null ? 'жду быстрые цены…
'
+ : `цены ${(p.price_age * 1000).toFixed(0)} мс назад · опрос ${p.fast_ms} мс
`;
+// the smallest amount both legs accept; red when «Сумма сделки» is below it (then not traded, paper or real)
+function minEntryCell(r, s) {
+ if (r.min_entry == null) return '? ';
+ const parts = [r.min_spot != null ? `спот ≥ ${r.min_spot.toFixed(2)} $` : "", r.min_fut != null ? `фьюч ≥ ${r.min_fut.toFixed(2)} $` : ""]
+ .filter(Boolean).join(", ");
+ return `${r.min_entry.toFixed(2)} `;
+}
+function renderCross() {
+ const s = bx.settings;
+ const bad = Object.entries(bx.ex_status || {}).map(([k, v]) => `${k}: ${v}`).join("; ");
+ document.getElementById("bxStatus").textContent = (bx.status === "ok"
+ ? `связок «спот на A → шорт на B»: ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (цикл ${(bx.cycle_ms / 1000).toFixed(1)} с)`
+ : bx.status) + ` · ${s.running ? `новые ${s.real ? "РЕАЛЬНЫЕ" : "бумажные"} сделки открываются` : "остановлено — новые сделки не открываются"}`
+ + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : "") + (bad ? ` · ${bad}` : "");
+ cxBalRender();
+ document.getElementById("bxPos").innerHTML = bx.positions.map(p => `
+ ${mskFull(p.opened)}${p.real ? ' РЕАЛ ' : ""}${p.error ? `${p.error} ` : ""} ${p.base} спот · фьюч
+ ${p.spot_ex} → ${p.fut_ex}${p.kind_name}
${p.qty.toPrecision(5)}
+ ${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)} ` : ""}
+ ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)} ` : ""}
+ ${pct(p.entry_gap)} ${p.exit_level != null && p.exit_level > p.usual
+ ? `${pct(p.exit_level)} (+${s.exit_over_usual_pct})сместилась: при входе ${pct(p.usual)}
`
+ : `${pct(p.usual)} (+${s.exit_over_usual_pct})${p.usual_now != null ? `сейчас обычная ${pct(p.usual_now)}
` : ""}`}
+ ${pct(p.gap_now)}${freshness(p)}${p.exit_held != null
+ ? `у обычной ${p.exit_held.toFixed(1)} из ${s.exit_hold_s} с — закрытие, если удержится
` : ""}
+ ${p.liq_pct == null ? "—"
+ : `${p.liq_pct.toFixed(1)}% ${price(p.liq_price)} · ${p.liq_src}${
+ p.liq_src === "биржа" && p.liq_calc ? ` (расчёт ${price(p.liq_calc)})` : ""}
`}
+ ${dollars(p.funding)} ${(p.fees_total ?? p.fees).toFixed(3)}
+ ${dollars(p.net)}
+ × `).join("")
+ || 'Нет открытых позиций ';
+ const key = bxSort, val = r => r[key];
+ const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9));
+ document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key));
+ document.getElementById("bxCount").textContent = `Связки: лучшие для ${rows.length} монет (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`;
+ const open = new Set(bx.positions.map(p => p.base));
+ document.getElementById("bxRows").innerHTML = rows.map(r => `
+ ${r.base} ${r.kind_name} ${r.spot_ex}
+ ${r.fut_ex}${r.innovation ? ' иннов. ' : ""}
+ ${price(r.spot_ask)}
+ ${price(r.fut_bid)}
+ ${pct(r.entry_gap)} ${r.usual == null ? "—" : pct(r.usual)}
+ ${r.excess == null ? "—" : pct(r.excess)}
+ ${r.net_pct == null ? "—" : pct(r.net_pct)} ${r.hot
+ ? `⚡ ${r.price_age == null ? "" : (r.price_age < 1 ? (r.price_age * 1000).toFixed(0) + " мс" : r.price_age.toFixed(1) + " с")}
` : ""}
+ ${r.history.toFixed(0)}
+ ${pct(r.funding_pct, 4)} / ${r.interval_h} ч
+ ${r.depth == null ? '? ' : kusd(r.depth)}
+ ${minEntryCell(r, s)}${kusd(r.turnover)}
+ ${open.has(r.base) ? 'в позиции '
+ : r.fits && !r.why ? 'подходит '
+ : r.fits ? `подходит — но ${r.why} ` : `${r.why} `} `).join("")
+ || 'Нет связок под фильтры ';
+ document.getElementById("bxTrades").innerHTML = bx.trades.map(t => `
+ ${mskFull(t.closed)} ${t.base} ${t.spot_ex} → ${t.fut_ex} · ${({sf: "спот → фьюч", in: "внутри биржи", ss: "спот → спот"})[t.kind] || ""} ${hold(t.closed - t.opened)}
+ ${pct(t.entry_gap)} → ${pct(t.exit_gap)} (обычная ${pct(t.usual)}) ${dollars(t.spot_pnl)}
+ ${dollars(t.fut_pnl)} ${t.fees.toFixed(3)} ${dollars(t.funding)}
+ ${dollars(t.net)} ${t.amount ? pct(t.net / t.amount * 100, 2) : "—"}
+ ${t.reason} `).join("") || 'Сделок пока нет ';
+}
+function renderBasis() {
+ const s = bx.settings, st = bx.stats;
+ const run = document.getElementById("bxRun");
+ run.textContent = s.running ? "■ Стоп" : "▶ Старт"; run.className = s.running ? "stop" : "start";
+ const rb = document.getElementById("bxReal");
+ rb.textContent = s.real ? "● РЕАЛЬНАЯ торговля — выключить" : "Бумажная торговля (включить реальную)";
+ rb.className = s.real ? "realon" : "";
+ document.getElementById("bxStatus").textContent = (bx.status === "ok"
+ ? `${bx.venue}: монет со спотом и фьючем ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (${bx.cycle_ms} мс)`
+ : bx.status) + ` · мемкойны: ${bx.memes_source} · ${s.running ? "новые сделки открываются" : "остановлено — новые сделки не открываются"}`
+ + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : "");
+ const wr = st.trades ? `${(st.wins / st.trades * 100).toFixed(0)}% · ${st.wins} из ${st.trades}` : "—";
+ const ex = st.real ? " (биржа)" : "";
+ const tiles = [
+ ["Итог закрытых, $" + ex, dollars(st.net), cls(st.net)], ["Итог, % от вложенного" + ex, st.net_pct == null ? "—" : pct(st.net_pct, 3), cls(st.net_pct || 0)],
+ ["Открыто", st.open, ""], ["Если закрыть открытые, $", dollars(st.unrealized), cls(st.unrealized)],
+ ["Сделок" + ex, st.trades, ""], ["Винрейт", wr, ""], ["Комиссии, $" + ex, st.fees.toFixed(4), "neg"],
+ ["Funding, $ (оценка)", dollars(st.funding), cls(st.funding)], ["Среднее удержание", st.avg_hold_min == null ? "—" : hold(st.avg_hold_min * 60), ""]];
+ if (st.real && bx.mode === "cross") {
+ const b = bx.balances || {};
+ tiles.unshift(["Баланс всех бирж, $", b.total == null ? "—" : b.total.toFixed(2), ""],
+ ["С запуска", b.change_pct == null ? 'жду балансы '
+ : `${pct(b.change_pct, 2)} (${dollars(b.change_usd)} $) `, cls(b.change_pct || 0)]);
+ if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные ', "neg"]);
+ } else if (st.real) {
+ const bal = real && real.balances && real.balances[bxVenue];
+ tiles.unshift(["Баланс на бирже", !bal ? "нет ключей" : bal.error ? `${bal.error} `
+ : Object.entries(bal.values).map(([k, v]) => `${k}: ${typeof v === "number" ? v.toFixed(2) : v}
`).join(""), ""]);
+ if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные ', "neg"]);
+ }
+ document.getElementById("bxStats").innerHTML = tiles
+ .map(([k, v, c]) => ``).join("");
+ if (bx.mode === "cross") { renderCross(); return; }
+ document.getElementById("bxPos").innerHTML = bx.positions.map(p => `
+ ${mskFull(p.opened)}${p.real ? ' РЕАЛ ' : ""}${p.tp_order ? `TP на бирже: ${price(p.tp_price)} ` : ""}${p.error ? `${p.error} ` : ""} ${p.base} спот · фьюч
+ ${p.qty.toPrecision(5)} ${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)} ` : ""}
+ ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)} ` : ""}
+ ${pct(p.entry_gap)} ${pct(p.gap_now)}${freshness(p)}
+ ${dollars(p.funding)} ${(p.fees_total ?? p.fees).toFixed(3)}
+ ${dollars(p.net)}
+ × `).join("")
+ || 'Нет открытых позиций ';
+ const key = bxSort, val = r => key === "depth" ? r.depth
+ : key === "turnover" ? Math.min(r.spot_turnover, r.fut_turnover) : r[key];
+ const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9));
+ document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key));
+ document.getElementById("bxCount").textContent = `Монеты: ${rows.length} (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`;
+ const open = new Set(bx.positions.map(p => p.base));
+ document.getElementById("bxRows").innerHTML = rows.map(r => {
+ const groups = [r.age_days != null && r.age_days <= s.new_days ? "новая" : "", r.innovation ? "инновации" : "", r.meme ? "мем" : ""].filter(Boolean).join(", ");
+ return `
+ ${r.base} ${r.mult > 1 ? ` фьюч ×${r.mult} ` : ""}
+ ${price(r.spot_ask)}
+ ${price(r.fut_bid)}
+ ${pct(r.entry_gap)} ${pct(r.exit_gap)}
+ ${pct(r.net_if_closed_pct)}
+ ${pct(r.funding_pct, 4)} / ${r.interval_h} ч
+ ${r.depth == null ? '? ' : kusd(r.depth)}
+ ${minEntryCell(r, s)}${kusd(Math.min(r.spot_turnover, r.fut_turnover))}
+ ${r.age_days == null ? "—" : r.age_days.toFixed(0)} ${groups}
+ ${open.has(r.base) ? 'в позиции '
+ : r.real_block ? `реально нельзя: ${r.real_block} `
+ : r.fits && !r.why ? 'подходит '
+ : r.fits ? `подходит — но ${r.why} `
+ : `${r.why || ""} `} `;
+ }).join("") || 'Нет монет под фильтры ';
+ document.getElementById("bxTrades").innerHTML = bx.trades.map(t => `
+ ${mskFull(t.closed)} ${t.base} ${hold(t.closed - t.opened)}
+ ${pct(t.entry_gap)} → ${pct(t.exit_gap)} ${dollars(t.spot_pnl)}
+ ${dollars(t.fut_pnl)} ${t.fees.toFixed(3)} ${dollars(t.funding)}
+ ${dollars(t.net)} ${t.amount ? pct(t.net / t.amount * 100, 2) : "—"}
+ ${t.reason} `).join("") || 'Сделок пока нет ';
+}
+function setMarket(m) {
+ arbMarket = m; localStorage.setItem("arb.market", m); arb = null; feesFor = null; arbOpen.clear();
+ document.getElementById("arbRows").innerHTML = 'загружаю цены… ';
+ loadArb();
+}
+// spot always means moving the coin; futures only when asked
+function transferOn() { return isSpot() || document.getElementById("afTransfer").checked; }
+function fee(ex) {
+ const el = document.querySelector(`#afFees input[data-fee="${ex}"]`);
+ const v = el ? parseFloat(el.value) : NaN;
+ return isNaN(v) ? (arb?.taker?.[ex] ?? 0.1) : v;
+}
+function buildFees() {
+ const saved = JSON.parse(localStorage.getItem("arb.fees." + arbMarket) || "{}");
+ document.getElementById("afFees").innerHTML = `Комиссия по рынку (${isSpot() ? "спот" : "фьючерсы"}), %: ` +
+ Object.keys(arb.taker).map(e => `${e}
`).join("") +
+ 'базовый уровень без скидок — поправьте под свой ';
+ document.querySelectorAll("#afFees input").forEach(el => el.addEventListener("input", () => {
+ const f = {}; document.querySelectorAll("#afFees input").forEach(i => f[i.dataset.fee] = i.value);
+ localStorage.setItem("arb.fees." + arbMarket, JSON.stringify(f)); renderArb(); }));
+ feesFor = arbMarket;
+}
+// filters, transfer time, amount… are remembered in this browser, so they survive reloads and restarts
+const ARB_FIELDS = ["afCoin", "afVol", "afDepth", "afGross", "afNet", "afSuspect", "afTransfer", "afClosed",
+ "afTMin", "afAmount", "afTFee"];
+(function restoreArbSettings() {
+ let saved = {};
+ try { saved = JSON.parse(localStorage.getItem("arb.settings") || "{}"); } catch (e) {}
+ for (const id of ARB_FIELDS) {
+ const el = document.getElementById(id);
+ if (!el || !(id in saved)) continue;
+ if (el.type === "checkbox") el.checked = !!saved[id]; else el.value = saved[id];
+ }
+ const save = () => {
+ const out = {};
+ for (const id of ARB_FIELDS) { const el = document.getElementById(id); if (el) out[id] = el.type === "checkbox" ? el.checked : el.value; }
+ try { localStorage.setItem("arb.settings", JSON.stringify(out)); } catch (e) {}
+ };
+ ARB_FIELDS.forEach(id => { const el = document.getElementById(id); if (el) { el.addEventListener("input", save); el.addEventListener("change", save); } });
+})();
+async function arbRun() {
+ await api(`/api/arb/${arbMarket}/${arb && arb.paused ? "start" : "stop"}`, {});
+ loadArb();
+}
+async function loadArb() {
+ if (tab !== "arb") return;
+ const tmin = val("afTMin", 15);
+ arb = await api(`/api/arb?market=${arbMarket}` + (transferOn() ? `&transfer=${tmin}` : ""));
+ document.getElementById("mkSpot").classList.toggle("on", isSpot());
+ document.getElementById("mkFut").classList.toggle("on", !isSpot());
+ document.getElementById("afTransferBox").style.display = isSpot() ? "none" : "";
+ document.getElementById("afClosedBox").style.display = isSpot() ? "" : "none";
+ if (!arbExBuilt && arb.taker) {
+ const saved = JSON.parse(localStorage.getItem("arb.ex") || "null");
+ document.getElementById("afEx").innerHTML = 'Биржи: ' + Object.keys(arb.taker).map(e =>
+ ` ${e} `).join("");
+ document.querySelectorAll("#afEx input, #arbView .controls input").forEach(el => el.addEventListener("input", renderArb));
+ ["afTransfer", "afTMin"].forEach(id => document.getElementById(id).addEventListener("change", loadArb));
+ document.querySelectorAll("#arbView th[data-s]").forEach(th => th.addEventListener("click", () => {
+ arbSort = th.dataset.s; localStorage.setItem("arb.sort", arbSort); renderArb(); }));
+ arbExBuilt = true;
+ }
+ if (arb.taker && feesFor !== arbMarket) buildFees();
+ const run = document.getElementById("arbRun");
+ run.textContent = arb.paused ? "▶ Старт сканирования" : "■ Стоп сканирования";
+ run.className = arb.paused ? "start" : "stop";
+ const unit = isSpot() ? "пар USDT" : "фьюч.";
+ const st = Object.entries(arb.status || {}).map(([e, s]) => `${e}: ${s === "ok" ? arb.counts[e] + " " + unit : s}`).join(" · ");
+ document.getElementById("arbStatus").textContent = (arb.paused ? "Сканирование остановлено — цены ниже последние полученные. " : "") + (arb.updated
+ ? `${st} · обновлено ${msk(arb.updated)} МСК (цикл ${(arb.cycle_ms / 1000).toFixed(1)} с, каждые ${arb.cycle_s} с)` : arb.paused ? "данных ещё нет" : "загружаю цены со всех бирж…");
+ document.getElementById("arbTitle").textContent = `Арбитраж ${isSpot() ? "на споте" : "на фьючерсах"}: Bybit · Binance · MEXC · HTX · Gate`;
+ document.getElementById("arbFees").textContent = isSpot()
+ ? "спот: купить на одной бирже → вывести монету → продать на другой" : "фьючерсы: лонг на одной + шорт на другой, закрыть при схождении";
+ renderArb();
+}
+// What is left of the trade amount at current prices after every fee and the transfer, in $ (same sums as the plan).
+function arbProfit(amount, buyPrice, sellPrice, feeA, feeB, transferFee) {
+ const coins = amount / buyPrice;
+ if (isSpot()) {
+ // buy fee comes out of the coins bought, the withdrawal fee too; the sell fee out of the USDT received
+ const arrive = Math.max(0, coins * (1 - feeA / 100) - transferFee / buyPrice);
+ return arrive * sellPrice * (1 - feeB / 100) - amount;
+ }
+ const fees = 2 * amount * feeA / 100 + amount * feeB / 100 + coins * sellPrice * feeB / 100 + transferFee;
+ return coins * (sellPrice - buyPrice) - fees;
+}
+function arbPairs() {
+ const ex = [...document.querySelectorAll("#afEx input:checked")].map(i => i.dataset.ex);
+ localStorage.setItem("arb.ex", JSON.stringify(ex));
+ const amount = val("afAmount", 1000), tmin = val("afTMin", 15), userFee = val("afTFee", 1);
+ const out = [];
+ for (const r of arb.rows || []) {
+ const ps = Object.entries(r.prices).filter(([e]) => ex.includes(e));
+ if (ps.length < 2) continue;
+ let best = null;
+ for (const [a, pa] of ps) for (const [b, pb] of ps) {
+ if (a === b) continue;
+ const gross = (pb.bid / pa.ask - 1) * 100;
+ if (!best || gross > best.gross) best = {gross, a, b, pa, pb};
+ }
+ const fa_ = fee(best.a), fb_ = fee(best.b);
+ const cost = isSpot() ? fa_ + fb_ : 2 * (fa_ + fb_); // spot: two trades; futures: open + close
+ const same = best.a === r.buy && best.b === r.sell;
+ const usual = same ? r.usual : null;
+ const fa = best.pa.funding_8h, fb = best.pb.funding_8h;
+ const t = same ? r.transfer : null;
+ // transfer fee: the exchange's own withdrawal fee where it is public (HTX), otherwise the field value
+ const tfee = t && t.fee_usd != null ? t.fee_usd : userFee;
+ const feePct = transferOn() ? tfee / amount * 100 : 0;
+ const low = same ? r.window_low : null, enough = same && r.history_min != null && r.history_min >= tmin;
+ const closed = !!t && (t.withdraw === false || t.deposit === false);
+ const profit = arbProfit(amount, best.pa.ask, best.pb.bid, fa_, fb_, transferOn() ? tfee : 0);
+ out.push({profit_usd: profit, profit_pct: profit / amount * 100,...r, buy: best.a, sell: best.b, buy_price: best.pa.ask, sell_price: best.pb.bid,
+ buy_url: best.pa.url, sell_url: best.pb.url, gross: best.gross, round_cost: cost, net_now: best.gross - cost,
+ usual, expected: usual == null ? null : best.gross - Math.max(usual, 0) - cost,
+ funding_buy: fa, funding_sell: fb, carry_8h: fa == null || fb == null ? null : fb - fa,
+ depth_usd: same ? r.depth_usd : null, suspect: best.gross > 10 || (same && r.suspect), pa: best.pa, pb: best.pb,
+ fee_a: fa_, fee_b: fb_, held_min: same ? r.held_min : null, window_low: low, history_ok: enough,
+ history_have: same ? r.history_min : null, fee_pct: feePct, tfee, tfee_known: !!(t && t.fee_usd != null),
+ transfer: t, closed,
+ net_transfer: low == null || !enough ? null : low - cost - feePct});
+ }
+ return out;
+}
+const usd = v => v == null ? "—" : v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(1) + "K" : v.toFixed(0);
+const pct = (v, d = 3) => v == null ? "—" : (v >= 0 ? "+" : "") + v.toFixed(d) + "%";
+const yesno = (v, yes, no) => v === true ? `${yes} ` : v === false ? `${no} ` : 'неизвестно ';
+function transferCell(r) {
+ const t = r.transfer;
+ if (!t) return '— ';
+ const nets = t.networks.length ? t.networks.slice(0, 4).join(", ") : 'сеть не известна ';
+ return `вывод ${r.buy}: ${yesno(t.withdraw, "открыт", "закрыт")} ввод ${r.sell}: ${yesno(t.deposit, "открыт", "закрыт")} ` +
+ `сети: ${nets}${t.fee_usd != null ? ` комиссия вывода ≈ ${t.fee_usd.toFixed(2)} $ (${t.fee_net})` : ""}`;
+}
+// Step-by-step plan for one row, in dollars for the trade amount, every fee included.
+function arbPlan(r) {
+ const amount = val("afAmount", 1000), tr = transferOn(), tmin = val("afTMin", 15);
+ const money = v => (v >= 0 ? "" : "−") + Math.abs(v).toFixed(2) + " $";
+ const coins = amount / r.buy_price;
+ const steps = [];
+ const depthWarn = r.depth_usd != null && r.depth_usd < amount
+ ? `По лучшим ценам доступно только ${r.depth_usd.toFixed(0)} $ из ${amount} $ — остальное исполнится хуже, уменьшите сумму ` : "";
+ const spreadUsed = tr && r.window_low != null && r.history_ok ? r.window_low : r.gross;
+ const holdNote = tr ? (r.history_ok ? ` Разница за последние ${tmin} мин не опускалась ниже ${pct(r.window_low)}.`
+ : ` Сканер видит связку меньше ${tmin} мин — неизвестно, продержится ли разница весь перевод. `) : "";
+ if (isSpot()) {
+ const feeBuy = amount * r.fee_a / 100; // the fee is usually taken from the coins bought
+ const coinsNet = coins * (1 - r.fee_a / 100);
+ const tCoins = r.tfee / r.buy_price; // withdrawal fee in coins
+ const arrive = Math.max(0, coinsNet - tCoins);
+ const sellValue = arrive * r.sell_price, feeSell = sellValue * r.fee_b / 100;
+ const result$ = sellValue - feeSell - amount;
+ const resultAtLow$ = arrive * r.buy_price * (1 + spreadUsed / 100) * (1 - r.fee_b / 100) - amount;
+ const t = r.transfer || {};
+ const nets = t.networks && t.networks.length ? t.networks.join(", ") : "общую сеть проверить на обеих биржах";
+ steps.push(`На ${r.buy} иметь ${amount} USDT на спотовом счёте; на ${r.sell} узнать адрес пополнения ${r.coin} (сеть: ${nets}).` +
+ (t.withdraw === false || t.deposit === false ? ' Сейчас ввод или вывод закрыт — перевод невозможен. '
+ : (t.withdraw == null || t.deposit == null ? ' Статус ввода/вывода этой биржи не публикуется — проверьте на сайте. ' : "")));
+ steps.push(`${r.buy} ${r.pa.symbol}: купить по рынку ≈ ${price(r.buy_price)} на ${amount} $ ≈ ${coins.toPrecision(5)} ${r.coin}. Комиссия ${money(feeBuy)} (${r.fee_a}%) → на счёте ≈ ${coinsNet.toPrecision(5)} ${r.coin}.`);
+ steps.push(`Вывести ${r.coin} с ${r.buy} на ${r.sell}: комиссия вывода ≈ ${money(r.tfee)}${r.tfee_known ? "" : " (из поля «Комиссия перевода»)"}, дойдёт ≈ ${arrive.toPrecision(5)} ${r.coin}, ждать ≈ ${tmin} мин.${holdNote}`);
+ steps.push(`${r.sell} ${r.pb.symbol}: продать по рынку ≈ ${price(r.sell_price)} → ≈ ${money(sellValue)}, комиссия ${money(feeSell)} (${r.fee_b}%).`);
+ steps.push(`Итог по текущим ценам: ${money(sellValue - feeSell)} − ${money(amount)} = ${money(result$)} ` +
+ (tr && r.history_ok ? `; если разница сожмётся до минимума за ${tmin} мин: ${money(resultAtLow$)} ` : "") +
+ `. Все расходы: ${money(feeBuy + r.tfee + feeSell)}, безубыток при разнице ≥ ${((feeBuy + r.tfee + feeSell) / amount * 100).toFixed(3)}%.`);
+ return `${steps.map(s => `${s} `).join("")}${depthWarn} `;
+ }
+ const tfee = tr ? r.tfee : 0;
+ const unitsA = coins / (r.pa.mult || 1), unitsB = coins / (r.pb.mult || 1);
+ const qty = (u, m) => `${u >= 100 ? u.toFixed(0) : u.toPrecision(4)} ${m > 1 ? `ед. (×${m} монет)` : "монет"}`;
+ const feeInA = amount * r.fee_a / 100, feeInB = amount * r.fee_b / 100;
+ const feeOutA = amount * r.fee_a / 100, feeOutB = coins * r.sell_price * r.fee_b / 100;
+ const fees = feeInA + feeInB + feeOutA + feeOutB + tfee;
+ const usual = Math.max(r.usual ?? 0, 0), toUsual$ = amount * (r.gross - usual) / 100;
+ const carry$ = r.carry_8h == null ? null : amount * r.carry_8h / 100;
+ const result$ = amount * spreadUsed / 100 - fees;
+ if (tr) steps.push(`Перевести маржу: на ${r.buy} и ${r.sell} должно быть по ${amount} $ (плечо 1). Перевод ≈ ${tmin} мин, плата ${money(tfee)}.${holdNote}`);
+ else steps.push(`Проверить маржу: на ${r.buy} и на ${r.sell} заранее по ${amount} $ USDT на фьючерсном счёте (плечо 1).`);
+ steps.push(`${r.buy} ${r.pa.symbol}: открыть LONG по рынку ≈ ${price(r.buy_price)}, ${qty(unitsA, r.pa.mult || 1)} на ${amount} $. Комиссия ${money(feeInA)} (${r.fee_a}%).`);
+ steps.push(`Сразу же ${r.sell} ${r.pb.symbol}: открыть SHORT по рынку ≈ ${price(r.sell_price)}, ${qty(unitsB, r.pb.mult || 1)}. Комиссия ${money(feeInB)} (${r.fee_b}%).`);
+ steps.push(`Держать, пока разница не сузится${r.usual != null ? ` до обычной ${pct(usual)}` : " к нулю"}. Funding за 8 ч: ${carry$ == null ? "нет данных" : (carry$ >= 0 ? "получите " : "заплатите ") + money(Math.abs(carry$))} (лонг ${pct(r.funding_buy, 4)}, шорт ${pct(r.funding_sell, 4)}).`);
+ steps.push(`Закрыть обе позиции одновременно по рынку. Комиссии выхода ≈ ${money(feeOutA + feeOutB)}.`);
+ steps.push(`Итог при схождении к нулю: ${money(amount * spreadUsed / 100)} разницы − ${money(fees)} комиссий${tfee ? " и перевода" : ""} = ${money(result$)} ` +
+ (r.usual != null ? `; к обычной: ${money(toUsual$ - fees)} ` : "") + `. Безубыток при разнице ≥ ${(fees / amount * 100).toFixed(3)}%.`);
+ return `${steps.map(s => `${s} `).join("")}${depthWarn} `;
+}
+function renderArb() {
+ if (!arb || !arb.rows) return;
+ const q = document.getElementById("afCoin").value.trim().toUpperCase();
+ const minVol = val("afVol", 0), minDepth = val("afDepth", 0), minGross = val("afGross", 0);
+ const onlyNet = document.getElementById("afNet").checked, hideSuspect = document.getElementById("afSuspect").checked;
+ const hideClosed = isSpot() && document.getElementById("afClosed").checked;
+ const tr = transferOn(), spot = isSpot();
+ document.querySelectorAll("#arbView .tcol").forEach(el => el.style.display = tr ? "" : "none");
+ document.querySelectorAll("#arbView .futcol").forEach(el => el.style.display = spot ? "none" : "");
+ document.querySelectorAll("#arbView .spotcol").forEach(el => el.style.display = spot ? "" : "none");
+ let rows = arbPairs().filter(r => (!q || r.coin.includes(q)) && r.volume_usd >= minVol && r.gross >= minGross
+ && (!minDepth || (r.depth_usd ?? 0) >= minDepth) && (!hideSuspect || !r.suspect) && (!hideClosed || !r.closed)
+ && (!onlyNet || (tr ? (r.net_transfer ?? r.net_now - r.fee_pct) > 0 : r.net_now > 0)));
+ const key = arbSort, num = v => v == null ? -Infinity : v;
+ rows.sort((a, b) => typeof a[key] === "string" ? a[key].localeCompare(b[key]) : num(b[key]) - num(a[key]));
+ document.querySelectorAll("#arbView th[data-s]").forEach(th => th.classList.toggle("sorted", th.dataset.s === key));
+ document.getElementById("arbCount").textContent = `Пары: ${rows.length} (монет на 2+ биржах: ${arb.rows.length})`;
+ const cols = 14 + (tr ? 2 : 0);
+ const html = [];
+ for (const r of rows.slice(0, 300)) {
+ html.push(` 0 ? "leadrow" : ""}" onclick="toggleArb('${r.coin}')">
+ ${arbOpen.has(r.coin) ? "▾ скрыть" : "▸ план"}
+ ${r.coin} ${r.suspect ? ' разные монеты? ' : ""}${r.closed ? ' перевод закрыт ' : ""}
+ ${r.buy} ${price(r.buy_price)}
+ ${r.sell} ${price(r.sell_price)}
+ ${pct(r.gross)} ${pct(r.net_now)} (−${r.round_cost.toFixed(2)})
+ ${pct(r.profit_pct, 2)} ${r.profit_usd >= 0 ? "+" : "−"}${Math.abs(r.profit_usd).toFixed(2)} $
+ ${pct(r.usual)} ${pct(r.expected)}
+ ${spot ? `${transferCell(r)} `
+ : `${pct(r.carry_8h, 4)} `}
+ ${usd(r.depth_usd)} ${usd(r.volume_usd)}
+ ${r.held_min == null ? '— ' : r.held_min < 1 ? "<1 мин" : r.held_min.toFixed(0) + " мин"}
+ ${tr ? `${r.history_ok ? pct(r.window_low) : `мало истории ${(r.history_have ?? 0).toFixed(0)} из ${val("afTMin", 15)} мин `}
+ ${pct(r.net_transfer)} ` : ""}
+ ${r.exchanges.length} `);
+ if (arbOpen.has(r.coin)) {
+ const cells = Object.entries(r.prices).map(([e, p]) =>
+ `${e} bid ${price(p.bid)} / ask ${price(p.ask)}` +
+ (spot ? "" : ` · funding/8ч ${pct(p.funding_8h, 4)}`)).join(" ");
+ html.push(`Что сделать (на сумму сделки, все комиссии):
+ ${arbPlan(r)}
Цены на всех биржах: ${cells}
`);
+ }
+ }
+ document.getElementById("arbRows").innerHTML = html.join("") || `Нет пар под фильтры `;
+}
+function toggleArb(coin) { arbOpen.has(coin) ? arbOpen.delete(coin) : arbOpen.add(coin); renderArb(); }
+window.addEventListener("resize", drawChart);
+(async () => {
+ await loadState(true); refreshCenter(); showTab(tab);
+ 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);
+})();
diff --git a/web_proxy.py b/web_proxy.py
index 0f7d5df..0f74cf9 100644
--- a/web_proxy.py
+++ b/web_proxy.py
@@ -11,6 +11,7 @@ program than the engine's python.exe) and add pythonw.exe to the VPN's app exclu
from __future__ import annotations
import sys
+from request_security import trusted_request
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -26,12 +27,14 @@ class Proxy(BaseHTTPRequestHandler):
pass
def _forward(self, method: str) -> None:
- if not self.client_address[0].startswith("127.") and self.client_address[0] != "::1":
+ if not trusted_request(self, command=method == "POST"):
self.send_error(403, "only from this computer")
return
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else None
headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_HEADERS}
+ # Preserve the validated authority so the engine can compare the browser Origin.
+ headers["Host"] = self.headers["Host"]
req = urllib.request.Request(ENGINE + self.path, data=body, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
diff --git a/web_sim.html b/web_sim.html
index 439acec..88c63f7 100644
--- a/web_sim.html
+++ b/web_sim.html
@@ -4,139 +4,7 @@
Симулятор опережения
-
+
@@ -263,1191 +131,6 @@ button.realon { background: rgba(255, 92, 92, 0.18); border-color: var(--red); c
-
+