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