Fix trade recovery, local web isolation and backtest risk accounting

This commit is contained in:
Igol committed 2026-10-22 21:49:20 +03:00
1 parent 5c6b0dc54a
commit 6aa76064dc
29 files changed
+2657 -1688

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
name: Offline regression tests
on:
push:
pull_request:
permissions:
contents: read
jobs:
windows:
runs-on: windows-latest
strategy:
matrix:
python-version: ['3.11', '3.12', '3.13']
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: pip
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: python -m pip install -r requirements.txt
- run: python -B scripts/run_tests.py
- run: node --test tests/web_context.test.cjs
- run: python -B -c "import main, websocket, numpy"
+23
View File
@@ -0,0 +1,23 @@
__pycache__/
*.py[cod]
.venv/
*.log
*.tmp
web_sim_data/
scalp_recordings/
historical_reports/
*.sqlite3*
settings.json
account_state.json
*credentials*.json
*credentials*.bin
*keys*.bin
lead_connections.json
lead_paper_state.json
lead_paper_trades.csv
scalp_hint_journal.csv
scalp_paper_state.json
scalp_paper_trades.csv
meme_matcher/autoscan_state.json
meme_matcher/autoscan_history.csv
meme_matcher/autoscan_config.json
+7 -6
View File
@@ -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
+159 -32
View File
@@ -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:
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,10 +1846,38 @@ 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} → "
self._pending_problem(base, f"незавершённый вход спот-спот {l.spot_ex} → "
f"{l.fut_ex} — проверьте {base} на обеих биржах вручную")
return
try:
@@ -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
+201
View File
@@ -0,0 +1,201 @@
"""Tk chart rendering and viewport interaction for the desktop simulator."""
from __future__ import annotations
from datetime import datetime
import tkinter as tk
import strategy
class ChartView:
def _draw_chart(self) -> None:
if not hasattr(self, "canvas"):
return
c = self.canvas
c.delete("all")
width, height = c.winfo_width(), c.winfo_height()
if width < 80 or height < 80:
return
left, right, top, bottom = 58, width - 82, 22, height - 34
c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей")
candles = list(self.candles)
if not candles:
c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…")
return
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
low -= pad
high += pad
t0 = candles[0][0]
t1 = max(candles[-1][0] + 60, t0 + 60)
view_end = self.chart_view_end if self.chart_view_end is not None else t1
view_start = view_end - self.chart_visible_seconds
visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end]
visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end]
if visible_candles:
candles = visible_candles
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
base_span = high - low
pad = base_span * .08 if base_span else max(high * .001, 1e-8)
natural_low, natural_high = low - pad, high + pad
if self.chart_price_center is None or self.chart_price_span is None:
low, high = natural_low, natural_high
if self.chart_price_center is not None and self.chart_price_span is not None:
span = self.chart_price_span
low = self.chart_price_center - span / 2
high = self.chart_price_center + span / 2
t0 = view_start
t1 = view_end
if t1 <= t0:
return
for i in range(5):
y = top + i * (bottom - top) / 4
value = high - i * (high - low) / 4
c.create_line(left, y, right, y, fill="#263746")
c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value))
c.create_line(left, bottom, right, bottom, fill="#6c7e8c")
candle_seconds = self.interval_minutes * 60
slot = (right - left) * candle_seconds / (t1 - t0)
body_width = max(2.0, min(16.0, slot * .62))
for candle in candles:
t, open_price, high_price, low_price, close_price = candle
if t < t0 - candle_seconds or t > t1:
continue
x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left)
y_high = bottom - (high_price - low) / (high - low) * (bottom - top)
y_low = bottom - (low_price - low) / (high - low) * (bottom - top)
y_open = bottom - (open_price - low) / (high - low) * (bottom - top)
y_close = bottom - (close_price - low) / (high - low) * (bottom - top)
color = "#38d996" if close_price >= open_price else "#ef5965"
c.create_line(x, y_high, x, y_low, fill=color, width=1)
body_top, body_bottom = sorted((y_open, y_close))
if body_bottom - body_top < 1:
body_bottom = body_top + 1
c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color)
for marker_time, marker_price, trade_id in visible_markers:
if not t0 <= marker_time <= t1:
continue
x = left + (marker_time - t0) / (t1 - t0) * (right - left)
y = bottom - (marker_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1)
c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}")
position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position
if position and position.mode != strategy.STRATEGY_CLASSIC:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom,
f"Вход {position.side.upper()}", "#63a8ff")
self._draw_level(c, position.stop_price, low, high, left, right, top, bottom,
"Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42")
if position.partial_target > 0 and not position.partial_done:
self._draw_level(c, position.partial_target, low, high, left, right, top, bottom,
"Частичная фиксация", "#40d6b0")
if position.final_target > 0:
self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0")
liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side)
if liquidation is not None:
self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d")
elif position:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff")
s = self.applied_settings or self._safe_read_settings()
if s["add_step"] > 0 and position.add_count < s["max_adds"]:
next_add = position.last_add_price * (1 - s["add_step"] / 100)
self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff")
if s["stop_loss"] > 0:
stop_price = position.entry_price * (1 - s["stop_loss"] / 100)
self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42")
if s["take_profit"] > 0:
effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"]))
take_profit_price = position.entry_price * (1 + effective_tp_pct / 100)
self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0")
if self.last_price:
y = bottom - (self.last_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3))
c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M"))
c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M"))
def _chart_bounds(self) -> tuple[int, int, int, int]:
width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
return 58, width - 82, 22, height - 34
def _on_chart_wheel(self, event: tk.Event) -> None:
direction = 1 if event.delta > 0 else -1
self._zoom_chart(event.x, event.y, direction)
def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None:
self._zoom_chart(event.x, event.y, direction)
def _zoom_chart(self, x: int, y: int, direction: int) -> None:
if not self.candles:
return
old_span = self.chart_visible_seconds
factor = 0.8 if direction > 0 else 1.25
self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor))
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
left, right, top, bottom = self._chart_bounds()
fraction_x = min(1, max(0, (x - left) / max(1, right - left)))
old_start = self.chart_view_end - old_span
anchor_time = old_start + fraction_x * old_span
self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
center = (max(prices) + min(prices)) / 2
self.chart_price_center = center
self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8)
fraction_y = min(1, max(0, (y - top) / max(1, bottom - top)))
anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span
self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor)
self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span
self._draw_chart()
def _on_chart_press(self, event: tk.Event) -> None:
if not self.candles:
return
left, right, top, bottom = self._chart_bounds()
if not left <= event.x <= right or not top <= event.y <= bottom:
return
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
self.chart_price_center = (high + low) / 2
self.chart_price_span = high - low + 2 * pad
self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center,
self.chart_price_span, self.chart_visible_seconds)
self.canvas.configure(cursor="fleur")
def _on_chart_drag(self, event: tk.Event) -> None:
if not self._drag_anchor:
return
x0, y0, end0, center0, price_span, time_span = self._drag_anchor
left, right, top, bottom = self._chart_bounds()
self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span
self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span
self.chart_price_span = price_span
self._draw_chart()
def _on_chart_release(self, _event: tk.Event) -> None:
self._drag_anchor = None
self.canvas.configure(cursor="")
def _reset_chart_view(self, _event: tk.Event | None = None) -> None:
self.chart_visible_seconds = self.interval_minutes * 60 * 30
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._drag_anchor = None
self._draw_chart()
def _go_to_live(self) -> None:
"""Return the chart's right edge to the newest market candle."""
if self.candles:
self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60
else:
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._draw_chart()
+74
View File
@@ -0,0 +1,74 @@
"""Desktop account and per-symbol state, independent of Tk widgets."""
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
import strategy
@dataclass
class Position:
trade_id: int
symbol: str
entry_price: float
qty: float
stake: float
entry_fee: float
opened_at: float
last_add_price: float
add_count: int = 0
# Strategy-mode fields; classic positions keep the defaults.
side: str = "long"
mode: str = strategy.STRATEGY_CLASSIC
leverage: float = 1.0
stop_price: float = 0.0
initial_stop: float = 0.0
atr: float = 0.0
extreme: float = 0.0
partial_target: float = 0.0 # 0 = none
final_target: float = 0.0 # 0 = none
partial_done: bool = False
realized_gross: float = 0.0
realized_fees: float = 0.0
opened_stake: float = 0.0
@dataclass
class ClosedTrade:
trade_id: int
symbol: str
entry_price: float
exit_price: float
qty: float
gross_pnl: float
fees: float
net_pnl: float
roi_pct: float
opened_at: float
closed_at: float
reason: str
@dataclass
class CurrencyState:
"""Independent market and position state for one concurrently traded symbol."""
prices: deque = field(default_factory=deque)
candles: deque = field(default_factory=deque)
entry_markers: deque = field(default_factory=deque)
last_price: float | None = None
baseline_close: float | None = None
last_signal_pct: float | None = None
last_signal_ready: bool = False
previous_entry_signal_pct: float | None = None
live_minute_prices: deque = field(default_factory=deque)
last_ws_message: float = 0.0
position: Position | None = None
live_position: Position | None = None
live_position_info: dict | None = None
live_order_busy: bool = False
live_transition_pending: bool = False
live_halted: bool = False
# Strategy modes A/B: last evaluated signal candle and the signal valid until the next close.
mode_signal: dict | None = None
mode_signal_bucket: int = 0
mode_eval_busy: bool = False
+65
View File
@@ -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.
+35 -24
View File
@@ -495,6 +495,24 @@ def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_
return windows, sorted(failed)
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:
+6 -1
View File
@@ -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]}")
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("нет связи")
+8 -271
View File
@@ -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
+27
View File
@@ -0,0 +1,27 @@
"""Atomic local JSON snapshots; callers must handle write failures explicitly."""
from __future__ import annotations
import json
import os
import tempfile
from pathlib import Path
def atomic_write_json(path: Path, payload) -> None:
"""Flush a new snapshot before replacing the old file, or leave the old file intact."""
path = Path(path)
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(fd, "wb") as stream:
stream.write(encoded)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
try:
os.unlink(temporary)
except FileNotFoundError:
pass
+101 -22
View File
@@ -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.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"),
+43
View File
@@ -0,0 +1,43 @@
"""Validate the original browser request before proxying or executing local commands."""
from __future__ import annotations
import ipaddress
from urllib.parse import urlsplit
LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"}
def _authority(value: str):
try:
url = urlsplit("http://" + value)
if (url.hostname not in LOCAL_HOSTS or url.username is not None or url.password is not None
or url.path or url.query or url.fragment or any(c.isspace() for c in value)):
return None
return url.hostname, url.port or 80
except ValueError:
return None
def trusted_request(handler, *, command: bool = False) -> bool:
try:
if not ipaddress.ip_address(handler.client_address[0]).is_loopback:
return False
except ValueError:
return False
hosts = handler.headers.get_all("Host", [])
if len(hosts) != 1 or (host := _authority(hosts[0])) is None:
return False
origins = handler.headers.get_all("Origin", [])
if len(origins) > 1:
return False
if origins:
try:
origin = urlsplit(origins[0])
if (origin.scheme != "http" or origin.path or origin.query or origin.fragment
or _authority(origin.netloc) != host):
return False
except ValueError:
return False
if handler.headers.get("Sec-Fetch-Site") == "cross-site":
return False
return not command or handler.headers.get("X-Sim") == "1"
+3 -2
View File
@@ -1,2 +1,3 @@
websocket-client>=1.8,<2
numpy>=1.26
# Python 3.11+
websocket-client==1.8.0
numpy==2.3.5
+34
View File
@@ -0,0 +1,34 @@
"""Run offline tests. Loopback HTTP fixtures are allowed; exchange connections are forbidden."""
from pathlib import Path
import os
import subprocess
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.dont_write_bytecode = True
def offline(event, args):
if event == 'socket.connect':
host = args[1][0]
elif event == 'socket.getaddrinfo':
host = args[0]
else:
return
if host not in (None, 'localhost', '::1') and not str(host).startswith('127.'):
raise RuntimeError('External network is disabled during tests')
if __name__ == '__main__':
if len(sys.argv) == 1:
for suite in ('tests', 'meme_matcher/tests'):
result = subprocess.run([sys.executable, '-B', __file__, suite], cwd=ROOT)
if result.returncode:
sys.exit(result.returncode)
else:
os.chdir(ROOT)
sys.path.insert(0, str(ROOT))
sys.addaudithook(offline)
suite = unittest.defaultTestLoader.discover(str(ROOT / sys.argv[1]))
sys.exit(not unittest.TextTestRunner(verbosity=1).run(suite).wasSuccessful())
+8 -4
View File
@@ -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) {
+42
View File
@@ -310,5 +310,47 @@ class CacheTests(unittest.TestCase):
self.assertEqual(len(hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path)[0]), 5)
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()
+95
View File
@@ -0,0 +1,95 @@
"""Durable recovery of rejected/partial rollback and uncertain entry cancellation."""
import json
import sys
import time
import unittest
from pathlib import Path
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import cross
import live
import test_cross_real
class RecoveryTests(unittest.TestCase):
def setUp(self):
self.fixture = test_cross_real.CrossRealTests()
self.fixture.setUp()
self.addCleanup(self.fixture.tearDown)
self.e, self.a, self.b = self.fixture.e, self.fixture.a, self.fixture.b
def open(self):
self.e.step(1000)
self.fixture.run_jobs()
def recover(self):
info = self.e.recover['XYZ']
info['retry_at'] = 0
self.e.step(1001)
self.fixture.run_jobs()
def test_failed_and_partial_rollback_remain_durable_until_confirmed_flat(self):
self.a.spot_buy = mock.Mock(side_effect=live.LiveError('rejected'))
self.b.fail_close = 1
self.open()
self.assertEqual(self.b.position, -99)
self.assertEqual(self.e.recover['XYZ']['phase'], 'rollback')
saved = json.loads(self.e.file.read_text(encoding='utf-8'))
self.assertEqual(saved['pending']['XYZ']['phase'], 'rollback')
self.b.partial_close = 5
self.recover()
self.assertEqual(self.b.position, -5)
self.assertIn('XYZ', self.e.recover)
self.recover()
self.assertEqual(self.b.position, 0)
self.assertEqual(self.e.recover, {})
self.assertEqual(self.e.pending, {})
def test_failed_cancel_blocks_entries_and_late_fill_is_closed_after_restart(self):
self.e.settings.entry_limit, self.e.settings.limit_hold_s = True, 0
self.b.limit_fill = 0
cancel = self.b.fut_cancel
self.b.fut_cancel = mock.Mock(side_effect=live.LiveError('timeout', sent=True))
self.open()
self.assertTrue(self.b.limits['L1']['open'])
self.assertEqual(self.e.recover['XYZ']['order_id'], 'L1')
self.assertEqual(self.a.orders, [])
self.e.step(2000)
self.assertTrue(self.e.jobs.empty())
self.b.fill_take_profit('L1') # fake exchange fills the still-working short
self.b.fut_cancel = cancel
again = cross.CrossEngine(Path(self.fixture.dir.name), start=False, real=True)
again.client_for = self.e.client_for
again.recover['XYZ']['retry_at'] = 0
# No current listing is needed: the intent contains its instrument snapshot.
again.step(2001)
while not again.jobs.empty():
again.do_job(again.jobs.get())
self.assertEqual(self.b.position, 0)
self.assertEqual(again.recover, {})
self.assertEqual(again.pending, {})
def test_unknown_submit_without_id_is_not_declared_absent_when_flat(self):
self.e.settings.entry_limit = True
self.b.fut_limit = mock.Mock(side_effect=live.LiveError('lost response', sent=True))
self.open()
self.assertIn('XYZ', self.e.recover)
self.recover()
self.assertIn('XYZ', self.e.recover)
self.assertEqual(self.b.fut_limit.call_count, 1)
self.assertIn('сверка', self.e.view()['real_pause'])
def test_no_order_when_intent_cannot_be_saved(self):
with mock.patch.object(cross, 'atomic_write_json', side_effect=OSError('disk full')):
# Queue directly: failing the pre-order durable intent must prevent every order.
self.e.do_job(('open', next(iter(self.e.links.values())), 0.5, 100))
self.assertEqual(self.a.orders + self.b.orders, [])
def test_successful_entry_is_handed_off_without_pending_recovery(self):
self.open()
self.assertEqual(len(self.e.positions), 1)
self.assertEqual(self.e.recover, {})
saved = json.loads(self.e.file.read_text(encoding='utf-8'))
self.assertEqual(saved['pending'], {})
self.assertEqual(len(saved['positions']), 1)
+30
View File
@@ -0,0 +1,30 @@
"""Ambiguous mutating HTTP responses must trigger reconciliation, not a fresh entry."""
import sys
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import live
class UncertainResponseTests(unittest.TestCase):
def request(self, method, status, body):
response = mock.Mock(status=status, will_close=True)
response.read.return_value = body
response.getheader.return_value = 'close'
connection = mock.Mock()
connection.getresponse.return_value = response
with mock.patch.object(live, '_take', return_value=(connection, False)):
with self.assertRaises(live.LiveError) as error:
live._http(method, 'https://exchange.invalid/order')
return error.exception
def test_server_error_on_submit_is_uncertain(self):
self.assertTrue(self.request('POST', 503, b'unavailable').sent)
self.assertTrue(self.request('DELETE', 500, b'error').sent)
self.assertFalse(self.request('GET', 503, b'unavailable').sent)
self.assertFalse(self.request('POST', 400, b'rejected').sent)
def test_unreadable_success_response_is_uncertain(self):
self.assertTrue(self.request('POST', 200, b'{truncated').sent)
+96
View File
@@ -0,0 +1,96 @@
"""Crash windows and filesystem failures must never cause a second entry."""
import json
import sys
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import real_mirror
from test_real import FakeClient
class MirrorRecoveryTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.client = FakeClient(price=1)
self.settings = {'coins': {'k': {'on': True}}, 'exchange_tpsl': True}
self.threads = mock.patch.object(real_mirror.threading.Thread, 'start')
self.threads.start()
self.addCleanup(self.threads.stop)
self.journal = mock.patch.object(real_mirror, 'journal')
self.journal.start()
self.addCleanup(self.journal.stop)
def mirror(self):
return real_mirror.FuturesMirror('k', 'X', 'bybit', 'XUSDT', Path(self.tmp.name),
client_for=lambda ex: self.client, settings=lambda: self.settings)
def prepare(self, m):
m.hook('open', SimpleNamespace(uid=1, side='LONG', qty=10, entry=1, target=1.02))
def test_restart_before_submission_never_replays_entry(self):
m = self.mirror()
self.prepare(m)
self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'prepared')
again = self.mirror()
again._recover_open()
self.assertEqual(self.client.orders, [])
self.assertIsNone(again.position)
def test_crash_after_exchange_accepts_is_contained_and_never_replayed(self):
m = self.mirror()
self.prepare(m)
order = self.client.fut_order
def crash(*args, **kwargs):
self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'submitted')
order(*args, **kwargs)
raise SystemExit('power loss')
with mock.patch.object(self.client, 'fut_order', side_effect=crash):
with self.assertRaises(SystemExit):
m._open()
again = self.mirror()
again._recover_open()
self.assertEqual(self.client.position, 0)
self.assertTrue(again.gate())
again._close('paper closed')
self.assertEqual(again.state, 'recover')
self.prepare(again)
self.assertEqual(sum(not o[3] for o in self.client.orders), 1)
def test_accepted_fill_is_saved_before_take_profit_request(self):
m = self.mirror()
self.prepare(m)
def crash(*args):
saved = json.loads(m.file.read_text())['position']
self.assertEqual(saved['phase'], 'filled')
self.assertEqual(saved['coins'], 10)
raise SystemExit('power loss')
with mock.patch.object(self.client, 'fut_take_profit', side_effect=crash):
with self.assertRaises(SystemExit):
m._open()
again = self.mirror()
again._close('restart')
self.assertEqual(self.client.position, 0)
self.assertIsNone(again.position)
def test_failed_persistence_blocks_order_and_is_visible(self):
m = self.mirror()
with mock.patch.object(real_mirror, 'atomic_write_json', side_effect=OSError('disk full')):
self.prepare(m)
self.assertEqual(self.client.orders, [])
self.assertTrue(m.jobs.empty())
self.assertIn('disk full', m.gate())
m._watch()
self.assertIsNone(m.position)
def test_corrupt_saved_state_blocks_new_entries(self):
Path(self.tmp.name, 'real_positions_k.json').write_text('{broken', encoding='utf-8')
m = self.mirror()
self.prepare(m)
self.assertEqual(m.state, 'blocked')
self.assertTrue(m.gate())
self.assertEqual(self.client.orders, [])
+29
View File
@@ -0,0 +1,29 @@
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import persistence
class AtomicSnapshotTests(unittest.TestCase):
def test_failed_replace_keeps_previous_snapshot_and_cleans_temporary_file(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'state.json'
persistence.atomic_write_json(path, {'position': 1})
with mock.patch.object(persistence.os, 'replace', side_effect=OSError('disk error')):
with self.assertRaises(OSError):
persistence.atomic_write_json(path, {'position': 2})
self.assertEqual(json.loads(path.read_text()), {'position': 1})
self.assertEqual(list(Path(directory).iterdir()), [path])
def test_invalid_numbers_do_not_destroy_existing_snapshot(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'state.json'
persistence.atomic_write_json(path, {'balance': 100})
with self.assertRaises(ValueError):
persistence.atomic_write_json(path, {'balance': float('nan')})
self.assertEqual(json.loads(path.read_text()), {'balance': 100})
+83
View File
@@ -0,0 +1,83 @@
"""Requests retain their original authority through the local proxy."""
import json
import sys
import unittest
import urllib.error
import urllib.request
from email.message import Message
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import request_security as security
import test_web_proxy as fixtures
import web_proxy
import web_sim
class AuthorityTests(unittest.TestCase):
def request(self, host='localhost:8765', origin=None, peer='127.0.0.1'):
headers = Message()
headers['Host'] = host
headers['X-Sim'] = '1'
if origin is not None:
headers['Origin'] = origin
return SimpleNamespace(headers=headers, client_address=(peer, 1000))
def test_only_local_authorities_and_same_origin_are_accepted(self):
for host, origin in [('localhost:8765', 'http://localhost:8765'),
('127.0.0.1:8765', None), ('[::1]:8765', 'http://[::1]:8765')]:
self.assertTrue(security.trusted_request(self.request(host, origin), command=True))
for host in ['attacker.example:8765', 'localhost.attacker.example', 'attacker@localhost:8765',
'localhost:bad', 'localhost:8765/path', 'localhost:8765#x', 'localhost:8765,evil']:
self.assertFalse(security.trusted_request(self.request(host)))
for origin in ['null', 'http://attacker.example', 'http://localhost:1234', 'http://evil@localhost:8765']:
self.assertFalse(security.trusted_request(self.request(origin=origin), command=True))
self.assertFalse(security.trusted_request(self.request(peer='192.168.1.1')))
def test_duplicate_host_and_missing_command_header_are_rejected(self):
req = self.request()
req.headers['Host'] = 'evil.example'
self.assertFalse(security.trusted_request(req))
req = self.request()
del req.headers['X-Sim']
self.assertFalse(security.trusted_request(req, command=True))
class ProxyIntegrationTests(unittest.TestCase):
def setUp(self):
self.sim = mock.patch.object(web_sim, 'SIM', SimpleNamespace(state=lambda: {'ok': True}), create=True)
self.sim.start()
self.addCleanup(self.sim.stop)
self.engine = fixtures.serve(web_sim.Handler)
self.backend = mock.patch.object(web_proxy, 'ENGINE', f'http://127.0.0.1:{self.engine.server_port}')
self.backend.start()
self.addCleanup(self.backend.stop)
self.proxy = fixtures.serve(web_proxy.Proxy)
for server in (self.engine, self.proxy):
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
def test_host_is_checked_at_both_boundaries(self):
for server in (self.proxy, self.engine):
for method in ('GET', 'POST'):
req = urllib.request.Request(f'http://127.0.0.1:{server.server_port}/api/state',
data=b'{}' if method == 'POST' else None, method=method,
headers={'Host': 'attacker.example', 'X-Sim': '1'})
with self.assertRaises(urllib.error.HTTPError) as error:
urllib.request.urlopen(req)
self.assertEqual(error.exception.code, 403)
def test_proxy_preserves_browser_origin_and_static_assets_are_allowlisted(self):
base = f'http://127.0.0.1:{self.proxy.server_port}'
req = urllib.request.Request(base + '/api/state', headers={'Origin': base})
with urllib.request.urlopen(req) as response:
self.assertEqual(json.load(response), {'ok': True})
for asset, kind in [('app.js', 'text/javascript'), ('app.css', 'text/css')]:
with urllib.request.urlopen(base + '/static/' + asset) as response:
self.assertIn(kind, response.headers['Content-Type'])
self.assertGreater(len(response.read()), 10)
with self.assertRaises(urllib.error.HTTPError) as error:
urllib.request.urlopen(base + '/static/../keystore.py')
self.assertEqual(error.exception.code, 404)
+1 -1
View File
@@ -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:
+89
View File
@@ -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');
});
+131
View File
@@ -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; } }
+1224
View File
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -11,6 +11,7 @@ program than the engine's python.exe) and add pythonw.exe to the VPN's app exclu
from __future__ import annotations
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:
+2 -1319
View File
File diff suppressed because it is too large. Load diff
+12 -5
View File
@@ -24,6 +24,7 @@ from dataclasses import fields
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from request_security import trusted_request
import keystore
import lead_window as lw
import live
@@ -111,6 +112,10 @@ def scanner_add(symbol: str, connections: list[dict]) -> tuple[dict | None, str]
DATA_DIR = ROOT / "web_sim_data"
SETTINGS_FILE = DATA_DIR / "settings.json"
PAGE = ROOT / "web_sim.html"
STATIC_ASSETS = {
"/static/app.js": (ROOT / "web" / "app.js", "text/javascript"),
"/static/app.css": (ROOT / "web" / "app.css", "text/css"),
}
PORT = 8765
CONNECTION_FIELDS = set(lw.CONNECTION_KEYS)
COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings)
@@ -640,9 +645,15 @@ class Handler(BaseHTTPRequestHandler):
self._send(code, json.dumps(data, ensure_ascii=False).encode("utf-8"))
def do_GET(self) -> None:
if not trusted_request(self):
self._json({"error": "недоверенный адрес страницы"}, 403)
return
path, _, query = self.path.partition("?")
if path in ("/", "/index.html"):
self._send(200, PAGE.read_bytes(), "text/html")
elif path in STATIC_ASSETS:
asset, kind = STATIC_ASSETS[path]
self._send(200, asset.read_bytes(), kind)
elif path == "/api/state":
self._json(SIM.state())
elif path == "/api/arb":
@@ -804,11 +815,7 @@ LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"}
def local_request(handler) -> bool:
"""A command from this simulator's own page: the Host is the local address (no DNS rebinding) and the request
carries the X-Sim header — another web site open in the browser cannot add it without a CORS preflight, which
this server never allows, so it cannot press buttons here (real trading, keys)."""
host = (handler.headers.get("Host") or "").rsplit(":", 1)[0].lower()
return host in LOCAL_HOSTS and handler.headers.get("X-Sim") == "1"
return trusted_request(handler, command=True)
def main() -> None: