"""Web interface of the lead/vector paper simulator: every coin of the connection list runs at the same time. py -3 web_sim.py → http://127.0.0.1:8765 (opens the browser) * 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/.json/.csv) and its own Start/Stop. Stop only forbids new entries: prices, the comparison and the forecast learning go on. * 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 import json import queue import re import statistics import threading import time import webbrowser from collections import deque 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 import real_mirror import scalp_hint as sh import scalp_paper as sp ROOT = Path(__file__).resolve().parent MEME_DIR = ROOT / "meme_matcher" def autoscan_module(): """meme_matcher/autoscan.py (imported on first use: it pulls numpy and the matcher).""" import sys if str(MEME_DIR) not in sys.path: sys.path.insert(0, str(MEME_DIR)) import autoscan return autoscan def scanner_view(connections: list[dict]) -> dict: """Autoscan state and its findings, one row per coin (latest check first), with what can be added.""" au = autoscan_module() import csv try: with au.HISTORY_CSV.open(encoding="utf-8-sig") as f: rows = list(csv.DictReader(f, delimiter=";")) except OSError: rows = [] coins: dict[str, dict] = {} for r in rows: c = coins.setdefault(r["symbol"], {"symbol": r["symbol"], "checks": 0, "leads": 0}) c["checks"] += 1 lead = r["verdict"] == au.LEAD_VERDICT c["leads"] += lead c["last_time"], c["verdict"] = r["time"], r["verdict"] # latest check if lead or "last_lead" not in c: # the figures shown: of the latest check where the DEX led (or of the latest check at all) c.update(futures=r["futures"], futures_symbol=r["futures_symbol"], dex_pool=r["dex_pool"], pool=r["pool_address"], follow=r["follow_t1_t5_pct"], hit=r["hit_t5"], t_stat=r["t_stat"], lag=r["best_lag_s"], note=r["added_to_simulator"]) # pool types learned later (Orca, PancakeSwap CLMM…): the old verdict is re-checked on «Добавить» if "тип пула не читается" in c["note"]: c["note"] = "" if lead: c["last_lead"] = r["time"] out = [] for c in coins.values(): target_like = type("T", (), {"chain": c["dex_pool"].split("/")[0], "cex": c["futures"], "symbol": c["symbol"], "pool": c["pool"], "cex_symbol": c["futures_symbol"]}) conn = au.simulator_connection(target_like) c["in_list"] = bool(conn and any(au.same_connection(conn, x) for x in connections)) # any coin the simulator can read and trade may be added for a test, not only where the DEX led c["addable"] = bool(conn) and not c["in_list"] and not c["note"].startswith("нет:") c["unsupported"] = c["note"] if c["note"].startswith("нет:") else ("" if conn else "фьючерс или сеть не поддерживаются") out.append(c) out.sort(key=lambda c: (-c["leads"], c.get("last_lead", "") == "", c["symbol"])) try: log_lines = au.LOG_FILE.read_text(encoding="utf-8").splitlines()[-6:] except OSError: log_lines = [] pid = au.running_pid() return {"running": bool(pid), "pid": pid, "auto_add": au.load_config()["auto_add"], "coins": out, "log": log_lines, "cycles": max((int(r["cycle"]) for r in rows), default=0)} def scanner_add(symbol: str, connections: list[dict]) -> tuple[dict | None, str]: """Connection for a coin the autoscan found leading; added to lead_connections.json.""" au = autoscan_module() row = next((c for c in scanner_view(connections)["coins"] if c["symbol"] == symbol), None) if row is None: return None, "монета не найдена в истории сканера" if not row["addable"]: return None, "уже в списке" if row["in_list"] else (row["unsupported"] or "нельзя добавить") owner = au.pool_owner(row["pool"]) if owner not in au.SUPPORTED_OWNERS: return None, "тип пула не читается симулятором вживую" target_like = type("T", (), {"chain": "solana", "cex": row["futures"], "symbol": symbol, "pool": row["pool"], "cex_symbol": row["futures_symbol"]}) conn = au.simulator_connection(target_like) lw.unremove_connection(conn) # deleted earlier and now added again by hand au.add_connection(conn, lw.CONNECTIONS_FILE) return conn, f"{symbol} добавлена ({au.SUPPORTED_OWNERS[owner]}) — монета остановлена, нажмите «Старт»" 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) if f.name in {"mode", "budget", "stake", "leverage", "min_target_pct", "stop_loss_pct", "max_hold_seconds", "cooldown_ms", "max_positions", "entry_gap_seconds", "min_confidence", "lead_threshold_pct", "lead_window_ms", "vector_window_seconds", "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_entry_z", "basis_exit_z", "basis_min_gap_pct"}] SERIES_STEP = 0.5 # chart sampling, s SERIES_KEEP = 1200 # 10 minutes def coin_key(conn: dict) -> str: lead = conn["lead_pool"][:8] if conn["lead_market"] == "raydium" else conn["lead_ticker"] raw = f"{conn['follow_exchange']}_{conn['follow_ticker']}_{conn['lead_market']}_{lead}" return re.sub(r"[^A-Za-z0-9_]", "", raw) def exchange_links(conn: dict) -> list[dict]: """Pages of this pair on the exchanges the data comes from: the leader (DEX pool / KuCoin) and the futures.""" links = [] if conn["lead_market"] == "raydium": pool = conn["lead_pool"] links.append({"label": "DEX пул · DexScreener", "url": f"https://dexscreener.com/solana/{pool}"}) links.append({"label": "пул · Solscan", "url": f"https://solscan.io/account/{pool}"}) elif conn["lead_market"] == "spot": links.append({"label": f"KuCoin спот {conn['lead_ticker']}", "url": f"https://www.kucoin.com/trade/{conn['lead_ticker']}"}) else: links.append({"label": f"KuCoin фьючерс {conn['lead_ticker']}", "url": f"https://www.kucoin.com/futures/trade/{conn['lead_ticker']}"}) ticker, exchange = conn["follow_ticker"], conn["follow_exchange"] url = {"bybit": f"https://www.bybit.com/trade/usdt/{ticker}", "binance": f"https://www.binance.com/en/futures/{ticker}", "mexc": f"https://futures.mexc.com/exchange/{ticker}"}.get(exchange) if url: name = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC"}[exchange] links.append({"label": f"{name} фьючерс {ticker}", "url": url}) return links def coin_symbol(conn: dict) -> str: return conn["follow_ticker"].replace("_USDT", "").removesuffix("USDT") def load_common() -> dict: defaults = {k: getattr(sp.PaperSettings(), k) for k in COMMON_FIELDS} defaults["mode"] = "lead" try: saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) except (OSError, ValueError): # first start: take the Tk window's settings try: saved = json.loads(lw.STATE_FILE.read_text(encoding="utf-8")).get("settings", {}) except (OSError, ValueError): saved = {} if "cooldown_ms" not in saved and "cooldown_seconds" in saved: saved["cooldown_ms"] = float(saved["cooldown_seconds"]) * 1000 # the pause used to be in seconds for k in COMMON_FIELDS: if k in saved: try: defaults[k] = type(defaults[k])(saved[k]) except (TypeError, ValueError): pass if defaults["mode"] not in lw.MODES: defaults["mode"] = "lead" return defaults def check_common(values: dict) -> tuple[dict, str]: """Cast and validate settings coming from the page.""" out = {} defaults = sp.PaperSettings() for k in COMMON_FIELDS: if k not in values: continue kind = type(getattr(defaults, k)) try: if kind is bool: out[k] = bool(values[k]) elif kind is str: out[k] = str(values[k]) else: out[k] = kind(float(str(values[k]).replace(",", "."))) except (TypeError, ValueError): return {}, f"поле {k}: нужно число" merged = dict(load_common(), **out) numbers = {k: float(v) for k, v in merged.items() if not isinstance(v, (bool, str))} numbers.setdefault("min_confidence", 0.0) problem = lw.validate(numbers) if not problem and merged.get("mode") not in lw.MODES: problem = "неизвестный режим" if not problem and int(merged.get("cut_loss_ticks", 1)) < 1: problem = "минус для закрытия — не меньше 1 шага" if not problem and not 0 <= float(merged.get("auto_stop_pct", 20)) <= 100: problem = "автостоп — от 0 до 100% (0 — выключен)" return (out, "") if not problem else ({}, problem) 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: self.conn = dict(conn) self.key = coin_key(conn) self.symbol = coin_symbol(conn) self.name = lw.connection_name(conn) DATA_DIR.mkdir(exist_ok=True) settings = sp.PaperSettings(mode=common.get("mode", "lead"), enabled=False) state_file = DATA_DIR / f"{self.key}.json" new_account = not state_file.exists() self.paper = sp.PaperTrader(settings, sh.HintSettings(), state_file, DATA_DIR / f"{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 if new_account: self.paper.ledger.balance = self.paper.settings.budget for k in CONNECTION_FIELDS: setattr(self.paper.settings, k, conn[k]) self.paper.policy = self.paper._make_policy() # 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.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() self.events: queue.Queue = queue.Queue() self.book = sh.OrderBook() self.tick = 0.0 self.leader: tuple[float, float] | None = None self.last_leader = self.last_follower = 0.0 self.lead_series: deque[tuple[float, float]] = deque(maxlen=SERIES_KEEP) self.follow_series: deque[tuple[float, float]] = deque(maxlen=SERIES_KEEP) self.lat_lead: deque[float] = deque(maxlen=200) self.lat_follow: deque[float] = deque(maxlen=200) self.lead_status = "подключаюсь…" self.follow_status = "подключаюсь…" self.message = "" 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) # --- lifecycle --------------------------------------------------------------------------- def start(self) -> None: ps = self.paper.settings if ps.follow_exchange == "mexc": self.tick, size = sh.mexc_contract(ps.follow_ticker) follower = sh.MexcFeed(ps.follow_ticker, self.events, size) elif ps.follow_exchange == "binance": self.tick = sh.binance_tick(ps.follow_ticker) follower = sh.BinanceFeed(ps.follow_ticker, self.events) else: self.tick = sh.bybit_tick(ps.follow_ticker) follower = sh.BybitFeed(ps.follow_ticker, self.events) if ps.lead_market == "raydium": leader = sh.RaydiumFeed(ps.lead_pool, self.events) else: leader = sh.KucoinFeed(ps.lead_ticker, self.events, spot=ps.lead_market == "spot") self.feeds = [follower, leader] for feed in self.feeds: feed.start() self.thread.start() def shutdown(self) -> None: self.stopped.set() for feed in self.feeds: feed.stop() with self.lock: self.paper.ledger.save() def apply(self, common: dict, initial: bool = False) -> None: ps = self.paper.settings lock = self.lock if not initial else threading.RLock() with lock: mode = common.get("mode", ps.mode) for k, v in common.items(): if k != "mode": setattr(ps, k, v) if mode != ps.mode: if not initial: self.paper.close_now(self.book, time.time(), "смена режима") self.paper.set_mode(mode) self.paper.ledger.save() def set_trading(self, on: bool) -> None: with self.lock: self.paper.settings.enabled = on self.paper.ledger.save() if on: self.auto_stop = "" self.message = ("Старт: новые сделки открываются" if on else "Стоп: новые сделки не открываются; открытые закроются по тейку, стопу или времени") 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.""" with self.lock: 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 self.paper.settings.enabled = enabled self.paper.ledger.save() self.paper.message = "" self.message = "Статистика сброшена" return self.message 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: 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 self.paper.close(price, time.time(), reason, self.paper.policy.taker, pos=pos) closed += 1 return f"закрыто позиций: {closed}" def _auto_stop(self, now: float) -> None: """On every new leader measurement: stop the pair when the futures (CEX) lead the leader by `auto_stop_pct` % or more. Prices, the comparison and open positions' exits go on.""" pol, ps = self.paper.policy, self.paper.settings lead = getattr(pol, "leadership", {}) at = lead.get("at") if at is None or at == self.checked_at: return self.checked_at = at pct = lead.get("pct") if not ps.enabled or ps.auto_stop_pct <= 0 or pct is None or -pct < ps.auto_stop_pct: return ps.enabled = False self.paper.ledger.save() self.auto_stop = (f"автостоп в {time.strftime('%H:%M:%S', time.gmtime(now + 3 * 3600))} МСК: " f"{pol.F} опережает {pol.L} на {-pct:.0f}% (порог {ps.auto_stop_pct:g}%)") self.message = self.auto_stop + " — новые сделки остановлены, открытые закроются сами" # --- data -------------------------------------------------------------------------------- def _pump(self) -> None: next_sample = 0.0 while not self.stopped.is_set(): try: kind, data = self.events.get(timeout=0.1) except queue.Empty: kind, data = None, None now = time.time() with self.lock: if kind == "book_snapshot": self.book.apply_snapshot(data) self.last_follower = now self.paper.on_book(now, self.book, self.tick) elif kind == "book_update": self.book.apply_updates(data) self.last_follower = now self.paper.on_book(now, self.book, self.tick) elif kind == "trades": for raw in data: try: trade = sh.Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) except (KeyError, TypeError, ValueError): continue self.paper.on_trade(trade) elif kind == "leader": self.leader = data self.last_leader = now self.paper.on_leader(now, data[0], data[1]) elif kind == "latency": self.lat_follow.append(float(data)) elif kind == "leader_latency": self.lat_lead.append(float(data)) elif kind == "status": self.follow_status = data elif kind == "leader_status": self.lead_status = data self._auto_stop(now) if now >= next_sample: next_sample = now + SERIES_STEP bid, ask = self.book.best() if bid and ask: self.follow_series.append((round(now, 2), (bid + ask) / 2)) if self.leader: self.lead_series.append((round(now, 2), (self.leader[0] + self.leader[1]) / 2)) # --- views ------------------------------------------------------------------------------- def summary(self) -> dict: with self.lock: led = self.paper.ledger trades = led.trades wins = sum(t.net_usd > 0 for t in trades) bid, ask = self.book.best() pol = self.paper.policy now = time.time() 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, "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, "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, "grid_minutes": len(getattr(pol, "grid", ())) * 0.5 / 60, "live": (now - self.last_follower) < 5 and (now - self.last_leader) < 120, "real": {k: v for k, v in self.mirror.view().items() if k != "trade_list"}, "exchange": self.paper.settings.follow_exchange, } def detail(self, since: float = 0.0) -> dict: with self.lock: d = self.summary() pol = self.paper.policy bid, ask = self.book.best() now = time.time() positions = [] for pos in reversed(self.paper.ledger.positions): price = bid if pos.side == "LONG" else ask pnl = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty if price else 0.0 positions.append({"uid": pos.uid, "side": pos.side, "qty": pos.qty, "usd": pos.entry * pos.qty, "entry": pos.entry, "target": pos.target, "stop": pos.stop, "age": now - pos.opened, "pnl": pnl, "pct": pnl / (pos.entry * pos.qty) * 100, "why": pos.regime, "opened": pos.opened}) trades = [{"closed": t.closed_utc, "side": t.side, "usd": t.notional_usd, "entry": t.entry, "exit": t.exit, "pct": t.pct, "net": t.net_usd, "fee": t.fee_usd, "reason": t.reason, "hold": t.hold_seconds, "why": t.regime} for t in reversed(self.paper.ledger.trades[-300:])] real_uids = {p["uid"] for p in d["real"]["positions"]} for p in positions: p["real"] = p["uid"] in real_uids d.update({ "real_trades": self.mirror.view()["trade_list"], "status": pol.status, "message": self.paper.message or self.message, "lead_status": self.lead_status, "follow_status": self.follow_status, "lead_latency": statistics.median(self.lat_lead) if len(self.lat_lead) >= 5 else None, "follow_latency": statistics.median(self.lat_follow) if len(self.lat_follow) >= 5 else None, "bid": bid, "ask": ask, "forecast": getattr(pol, "forecast", 0.0), "lead_series": [p for p in self.lead_series if p[0] > since], "follow_series": [p for p in self.follow_series if p[0] > since], "positions": positions, "closed": trades, "now": now, "links": exchange_links(self.conn), }) return d class Simulator: def __init__(self) -> None: self.common = load_common() self.engines: dict[str, Engine] = {} self.lock = threading.Lock() self.sync_connections() 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) with self.lock: if key in self.engines: continue engine = Engine(conn, self.common) self.engines[key] = engine engine.start() def remove(self, key: str) -> str: """Delete a pair: close its open positions, stop all its data feeds and forget the connection.""" with self.lock: engine = self.engines.get(key) if engine is None: return "нет такой монеты" lw.remove_connection(engine.conn) del self.engines[key] with engine.lock: engine.paper.settings.enabled = 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 "") def _watch(self) -> None: while True: time.sleep(30) try: self.sync_connections() except Exception: pass def save_common(self, values: dict) -> str: 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()): engine.apply(clean) return "" def state(self) -> dict: return {"settings": self.common, "modes": lw.MODES, # pairs enabled for trades first, then by name "coins": sorted((e.summary() for e in self.engines.values()), key=lambda c: (not c["running"], c["symbol"], c["name"]))} SIM: Simulator | None = None ARB: dict = {} # market ("spot" / "futures") → arb.ArbScanner, started on the first request for it def arb_view(transfer_min: float | None = None, market: str = "spot") -> dict: market = market if market in ("spot", "futures") else "spot" if market not in ARB: import arb ARB[market] = arb.ArbScanner(market) return ARB[market].view(transfer_min) BALANCES: dict = {} # exchange → {"values": {...}, "time": t} or {"error": ..., "time": t}: from the account itself LATENCY: dict = {} # API host → last round trip, ms (warm-up pings) def apply_real_fee(exchange: str, pct: float) -> None: """The exchange's measured taker rate replaces the paper one (entry and exit) for all its coins.""" if exchange in sp.FOLLOW_FEES and pct > 0: sp.FOLLOW_FEES[exchange] = (round(pct, 5), round(pct, 5)) PING_SAMPLES: dict = {} # host → deque of (time, ms) FUTURES_HOST = {"bybit": "api.bybit.com", "binance": "fapi.binance.com", "mexc": "contract.mexc.com", "htx": "api.hbdm.com", "gate": "api.gateio.ws"} def ping_for(exchange: str) -> float | None: """Current round trip to the exchange's futures API: median of the last three pings, None when stale.""" samples = PING_SAMPLES.get(FUTURES_HOST.get(exchange, "")) if not samples or time.time() - samples[-1][0] > 10: return None return statistics.median(ms for _, ms in samples) def warm_loop() -> None: """Keeps a ready HTTPS connection to every exchange with keys (a real order skips the handshake) and measures the ping every 2 s — the entry check uses it.""" while True: try: for host, ms in live.warm_up([ex for ex in keystore.EXCHANGES if keystore.get(ex) is not None]).items(): PING_SAMPLES.setdefault(host, deque(maxlen=3)).append((time.time(), ms)) LATENCY[host] = statistics.median(v for _, v in PING_SAMPLES[host]) except Exception: pass time.sleep(2) def balances_loop() -> None: """Account balances of every exchange with saved keys, every 10 s (shown next to the real trading figures); a failed read keeps the last good figures and says how old they are.""" while True: for ex in keystore.EXCHANGES: if keystore.get(ex) is None: BALANCES.pop(ex, None) continue try: c = live.client(ex) values = c.balances() try: # what is free for a new trade (the spot–futures tabs check the trade amount against it) free = c.usdt_free() except Exception: free = (BALANCES.get(ex) or {}).get("free") try: # the coins on spot: the stock a spot–spot trade sells from coins = c.spot_coins() except Exception: coins = (BALANCES.get(ex) or {}).get("coins") BALANCES[ex] = {"values": values, "free": free, "coins": coins, "unified": bool(getattr(c, "unified", False)), "time": time.time()} except Exception as exc: old = BALANCES.get(ex) or {} BALANCES[ex] = {**({"values": old["values"], "time": old["time"]} if "values" in old else {"time": 0}), "free": old.get("free"), "coins": old.get("coins"), "unified": old.get("unified", False), "error": str(exc)} time.sleep(10) BASIS: dict = {} # venue ("bybit") → basis.BasisEngine (spot–futures), started on the first request for it BASIS_LOCK = threading.Lock() def basis_engine(venue: str): """«Арбитраж»: "cross" — the simulation, "cross_real" — real trading; both search every link (between the exchanges, inside one exchange, spot–spot), each is started and stopped by itself. The real one takes the simulation's prices. (The single-exchange spot–futures engines are gone: their positions moved here.)""" if venue not in ("cross", "cross_real"): return None with BASIS_LOCK: if "cross" not in BASIS: import cross BASIS["cross"] = cross.CrossEngine() 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 BASIS["cross_real"] = cross.CrossEngine(real=True, leader=BASIS["cross"]) BASIS["cross_real"].balances = BALANCES return BASIS[venue] class Handler(BaseHTTPRequestHandler): def log_message(self, *args) -> None: # quiet pass def _send(self, code: int, body: bytes, kind: str = "application/json") -> None: self.send_response(code) self.send_header("Content-Type", f"{kind}; charset=utf-8") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def _json(self, data, code: int = 200) -> None: 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": m = re.search(r"transfer=([0-9.]+)", query) mk = re.search(r"market=(spot|futures)", query) self._json(arb_view(float(m.group(1)) if m else None, mk.group(1) if mk else "spot")) elif path == "/api/real": basis_real = {k: getattr(e.settings, "real", False) for k, e in BASIS.items()} self._json({"keys": keystore.summary(), "simulator": real_mirror.load_settings(), "basis": basis_real, "balances": BALANCES, "latency": LATENCY, "journal": list(reversed(real_mirror.RECENT[-150:]))}) elif path == "/api/basis": m = re.search(r"ex=([a-z_]+)", query) engine = basis_engine(m.group(1) if m else "cross") if engine is None: self._json({"error": "эта биржа пока не подключена"}, 404) else: self._json(engine.view()) elif path == "/api/scanner": try: self._json(scanner_view(lw.load_connections())) except Exception as exc: self._json({"error": f"сканер недоступен: {exc}"}, 500) elif path.startswith("/api/coin/"): engine = SIM.engines.get(path.split("/")[3]) if engine is None: self._json({"error": "нет такой монеты"}, 404) return since = 0.0 m = re.search(r"since=([0-9.]+)", query) if m: since = float(m.group(1)) self._json(engine.detail(since)) else: self._json({"error": "not found"}, 404) def do_POST(self) -> None: if not local_request(self): self._json({"error": "команды принимаются только со страницы симулятора на этом компьютере"}, 403) return length = int(self.headers.get("Content-Length") or 0) try: body = json.loads(self.rfile.read(length) or b"{}") except ValueError: body = {} parts = self.path.strip("/").split("/") 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) self._json({"ok": not problem, "error": problem}) return if parts[:3] == ["api", "real", "keys"] and len(parts) >= 4: ex = parts[3] if ex not in keystore.EXCHANGES: self._json({"ok": False, "error": "неизвестная биржа"}, 404) elif len(parts) == 4: problem = keystore.set_keys(ex, str(body.get("api_key", "")), str(body.get("api_secret", ""))) self._json({"ok": not problem, "error": problem}) elif parts[4] == "delete": keystore.delete_keys(ex) self._json({"ok": True}) elif parts[4] == "check": try: self._json({"ok": True, "balances": live.client(ex).balances()}) except live.LiveError as exc: self._json({"ok": False, "error": str(exc)}) else: self._json({"error": "unknown action"}, 404) return if parts[:2] == ["api", "arb"] and len(parts) == 4 and parts[3] in ("start", "stop"): market = parts[2] if parts[2] in ("spot", "futures") else "spot" arb_view(None, market) # make sure the scanner exists ARB[market].set_paused(parts[3] == "stop") self._json({"ok": True, "paused": ARB[market].paused}) return if parts[:2] == ["api", "basis"] and len(parts) >= 4: engine = basis_engine(parts[2]) if engine is None: self._json({"error": "эта биржа пока не подключена"}, 404) elif parts[3] == "settings": problem = engine.set_settings(body) self._json({"ok": not problem, "error": problem}) elif parts[3] == "close": 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()}) elif parts[3] == "adopt": try: price = float(body["price"]) if body.get("price") not in (None, "") else None fee = float(body["fee"]) if body.get("fee") not in (None, "") else None except (TypeError, ValueError): self._json({"ok": False, "error": "неверная цена или комиссия"}) return if not hasattr(engine, "adopt"): self._json({"ok": False, "message": "в этом режиме нельзя"}) return message = engine.adopt(str(body.get("base", "")), price, fee) self._json({"ok": "подхвачено" in message, "message": message}) else: self._json({"error": "unknown action"}, 404) return if parts[:2] == ["api", "scanner"] and len(parts) == 3: au = autoscan_module() action = parts[2] if action == "start": if not au.running_pid(): au.start_background(float(body.get("minutes", 15)), int(body.get("coins", 12))) self._json({"ok": True}) elif action == "stop": au.stop_background() self._json({"ok": True}) elif action == "config": cfg = au.load_config() cfg["auto_add"] = bool(body.get("auto_add", cfg["auto_add"])) au.save_config(cfg) self._json({"ok": True}) elif action == "add": conn, message = scanner_add(str(body.get("symbol", "")), lw.load_connections()) if conn: SIM.sync_connections() self._json({"ok": True, "message": message, "key": coin_key(conn)}) else: self._json({"ok": False, "error": message}) else: self._json({"error": "unknown action"}, 404) return if len(parts) >= 4 and parts[:2] == ["api", "coin"]: engine = SIM.engines.get(parts[2]) if engine is None: self._json({"error": "нет такой монеты"}, 404) return action = parts[3] if action == "start": engine.set_trading(True) self._json({"ok": True}) elif action == "stop": engine.set_trading(False) self._json({"ok": True}) elif action == "reset": self._json({"ok": True, "message": engine.reset()}) 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)}) else: self._json({"error": "unknown action"}, 404) return self._json({"error": "not found"}, 404) HOST = "127.0.0.1" # this PC only: the page switches real trading and holds exchange API keys BACKEND_PORT = 8766 # --backend: engine on 127.0.0.1:8766 behind web_proxy.py (127.0.0.1:8765, VPN-excluded) LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"} def local_request(handler) -> bool: return trusted_request(handler, command=True) def main() -> 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) if "--backend" in sys.argv: host, port = "127.0.0.1", BACKEND_PORT else: host, port = ("127.0.0.1" if "--local" in sys.argv else HOST), PORT real_mirror.load_recent() import minorder minorder.AUTOLOAD = True # the exchanges' smallest orders (spot and perp), loaded and renewed hourly # the paper model pays what the exchange really charges (measured from the real fills), not the textbook rate real_mirror.FEE_LISTENERS.append(apply_real_fee) for ex, pct in (real_mirror.load_settings().get("fees") or {}).items(): apply_real_fee(ex, pct) threading.Thread(target=balances_loop, daemon=True).start() threading.Thread(target=warm_loop, daemon=True).start() SIM = Simulator() # «Арбитраж»: 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() try: server.serve_forever() except KeyboardInterrupt: pass finally: for engine in SIM.engines.values(): engine.shutdown() if __name__ == "__main__": main()