diff --git a/LinuxServer/.gitignore b/LinuxServer/.gitignore new file mode 100644 index 0000000..48496e9 --- /dev/null +++ b/LinuxServer/.gitignore @@ -0,0 +1,23 @@ +__pycache__/ +*.py[cod] +.venv/ +*.log +*.tmp +web_sim_data/ +scalp_recordings/ +historical_reports/ +*.sqlite3* +settings.json +account_state.json +*credentials*.json +*credentials*.bin +*keys*.bin +lead_connections.json +lead_paper_state.json +lead_paper_trades.csv +scalp_hint_journal.csv +scalp_paper_state.json +scalp_paper_trades.csv +meme_matcher/autoscan_state.json +meme_matcher/autoscan_history.csv +meme_matcher/autoscan_config.json diff --git a/LinuxServer/README.md b/LinuxServer/README.md new file mode 100644 index 0000000..fb5555e --- /dev/null +++ b/LinuxServer/README.md @@ -0,0 +1,59 @@ +# Crypto Scam для Ubuntu 24.04 + +Эта папка — отдельный комплект для развёртывания веб-приложения на Linux. Windows-скрипты запуска сюда не входят. Приложение слушает только `127.0.0.1:8765`; наружу публикуется Nginx с HTTPS, а не Python-сервер. + +## Что требуется заранее + +- Чистый или подготовленный Ubuntu Server 24.04 с доступом `sudo`. +- Домен или поддомен, например `trade.example.com`, и DNS `A`-запись на публичный IPv4 сервера. Если добавлена `AAAA`-запись, IPv6 тоже должен вести на этот сервер и принимать 80/443. +- В сетевом firewall хостинга разрешить входящие TCP 22 (SSH), 80 и 443. Порт 8765 наружу не открывать. +- Исходящий доступ сервера к публичным API Bybit, Gate, MEXC и HTX. Binance в этом варианте не используется. +- Подключение к серверу по SSH. Не отключайте текущую SSH-сессию во время настройки firewall. + +## Развёртывание + +Скопируйте весь каталог `LinuxServer` на Ubuntu (например, через `scp -r`) и выполните: + +```bash +cd LinuxServer +chmod +x deploy.sh +sudo ./deploy.sh trade.example.com admin@example.com +``` + +Замените домен и email на свои. Скрипт установит Python-зависимости, Nginx и Certbot, запросит общий пароль внешнего шлюза, получит TLS-сертификат Let's Encrypt и создаст systemd-сервис `crypto-scam`. После успешного завершения откройте `https://trade.example.com`. + +Браузер сначала запросит общий HTTP Basic Auth логин/пароль сервера, затем приложение покажет собственную регистрацию и вход. Второй слой намеренный: он защищает публичную форму регистрации и снижает нежелательные запросы; каждому человеку всё равно нужен собственный логин/пароль приложения. Пароль Basic Auth можно сменить командой `sudo htpasswd -B /etc/nginx/crypto-scam/htpasswd ИМЯ` и затем `sudo systemctl reload nginx`. + +## Учётные записи, данные и API-ключи + +- Общая БД аккаунтов и хешей паролей, а также пользовательские хранилища расположены в `/var/lib/crypto-scam/`. Для каждого аккаунта создаётся отдельный движок. +- Первый зарегистрировавшийся аккаунт получает копию старых данных, если они находились в переносимом `web_sim_data`; исходники не удаляются. Остальные аккаунты изолированы. +- История рыночных данных сейчас отдельная для каждого пользователя. Сканеры Bybit, Gate, MEXC и HTX запускаются для каждого существующего аккаунта при старте сервиса, в том числе без открытой вкладки. +- API-ключи на Linux шифруются AES-256-GCM ключом сервера `/etc/crypto-scam/master.key`; доступ к нему есть у системной службы. Для реальной торговли нужны новые ключи: Windows DPAPI-файлы расшифровать на Linux нельзя. +- Включайте на бирже только необходимые права, запрещайте вывод средств и сначала проверяйте в симуляции. Публичный HTTPS сам по себе не делает стратегию или реальные ордера безопасными. + +## Управление + +```bash +sudo systemctl status crypto-scam nginx +sudo systemctl restart crypto-scam +sudo systemctl restart nginx +sudo journalctl -u crypto-scam -f +sudo tail -f /var/log/nginx/error.log +``` + +Сертификаты обновляет системный таймер Certbot. Проверка: `sudo certbot renew --dry-run`. + +## Резервное копирование и безопасность + +Остановите службу перед согласованной резервной копией данных: `sudo systemctl stop crypto-scam`. Сохраните `/var/lib/crypto-scam/` и `/etc/crypto-scam/master.key`; без master key сохранённые API-ключи восстановить нельзя. Master key храните отдельно, зашифрованно и с ограниченным доступом. После копирования запустите службу снова. Не добавляйте данные и master key в Git или публичные архивы. + +Не публикуйте порт `8765`, не удаляйте общий Basic Auth-шлюз без дополнительной защиты и не пересылайте настройки/логи с секретами. Настройте firewall у хостинг-провайдера; при использовании UFW сначала разрешите ваш фактический SSH-порт, иначе можно потерять доступ. + +## Ограничения этого пакета + +- Рекомендуемый путь — один узел Ubuntu 24.04, Nginx + HTTPS reverse proxy, один systemd-сервис. +- Пользовательские разделы изолированы в приложении и файловой системе; это не полноценный контейнерный sandbox между недоверенными пользователями одного сервера. +- Не открывайте сайт широкой аудитории без оценки нагрузки: для каждого аккаунта запускается собственный сборщик рыночных данных, поэтому нагрузка на API растёт вместе с числом пользователей. +- Перед миграцией с работающей Windows-версии проверьте и закройте либо отдельно обеспечьте наблюдение за реальными позициями. При переносе DPAPI-ключи не работают; создайте ключи заново на сервере. +- Автоматические тесты здесь не запускались; сначала разверните на тестовом сервере и проверьте регистрацию, вход/выход, изоляцию двух аккаунтов, сканеры и HTTPS до включения реальных ключей. diff --git a/LinuxServer/algo_hunter.py b/LinuxServer/algo_hunter.py new file mode 100644 index 0000000..37001fd --- /dev/null +++ b/LinuxServer/algo_hunter.py @@ -0,0 +1,999 @@ +"""Algo Hunter: detect market-maker / HFT quoting patterns in the order book and trade them virtually. + +Layers +* AlgoDetector - recognises an algorithm from level-size patterns (only aggregated levels are visible: + neither Bybit nor MetaScalp publish individual orders, so "the algo's order" is a level whose size and + behaviour match the pattern). +* AlgoTracker - follows those levels over time: lifetime, replace frequency, typical offset from the touch, + where it re-quotes next; flags adaptation (confidence falling below adaptive_exit_threshold). +* Executor - virtual limit orders only (no market entries): front-run the algo's level or pre-place on + its predicted re-quote; queue position is modelled from the visible level size; TP/SL/trailing/time/ + emergency exits. +* RiskGuard - daily loss, trades per minute, losing streak pause, latency limits, cool-down after exit. + +Nothing is ever sent to an exchange. dry_run=True only detects and logs. All events go to algo_hunter.log +with the [ALGO_HUNTER] tag; every trade goes to algo_hunter_trades.csv. +""" + +from __future__ import annotations + +import csv +import json +import logging +import statistics +import time +from collections import deque +from dataclasses import asdict, dataclass, field, fields +from datetime import datetime, timezone +from logging.handlers import RotatingFileHandler +from pathlib import Path + +import scalp_hint as sh + +ROOT = Path(__file__).resolve().parent +CONFIG_FILE = ROOT / "algo_hunter_config.json" +LOG_FILE = ROOT / "algo_hunter.log" +TRADES_FILE = ROOT / "algo_hunter_trades.csv" +TRADE_COLUMNS = ["closed_utc", "ticker", "side", "scenario", "confidence", "signals", "algo_side", "algo_levels", + "algo_volumes", "order_price", "order_size_usd", "ts_sent", "ts_ack", "queue_ahead_usd", + "front_run_success", "entry", "exit", "pnl_ticks", "net_usd", "hold_ms", "exit_reason"] +SIZE_TOLERANCE = 0.02 # two sizes are "the same" within 2% +GROUP_TOLERANCE = 0.25 # sizes within ±25% of the dominant size belong to the candidate group + + +@dataclass +class AlgoHunterConfig: + # detector + detection_window_ms: float = 2000 + min_interval_ms: float = 80 + max_interval_ms: float = 500 + max_spread_ticks: int = 3 + min_levels_cluster: int = 2 + max_volume_cv: float = 0.15 + batch_size_threshold: int = 3 + reaction_latency_ms: float = 150 + min_signals_to_confirm: int = 3 + depth_levels: int = 10 + size_tolerance: float = 0.02 # orders within this share of each other count as the algo's "same size" + # tracker + adaptive_exit_threshold: float = 0.3 + adaptive_exit_ms: float = 4000 # confidence must stay below the threshold this long to count as adapted + rearm_after_ms: float = 0 # >0: switch back on by itself once the algo is confirmed again this long + prediction_confidence: float = 0.75 + # executor + dry_run: bool = True + min_confidence: float = 0.7 + entry_tape_window_ms: float = 1000 + max_entry_spread_ticks: int = 2 + min_entry_spread_ticks: int = 0 # no entries while the spread is narrower than this (0 = off) + vol_cap_ticks: float = 4 # mid range over the last second, in ticks + tp_ticks: int = 2 + sl_ticks: int = 3 + trailing: bool = False + tp_partial_ticks: int = 1 + max_hold_ms: float = 2000 + order_ttl_ms: float = 2000 # an unfilled order is cancelled after this + quick_exit: bool = False # close at the next trade at another price, in profit or not (no TP/SL/time) + requote: bool = False # re-place the order on every book update instead of cancelling and waiting + require_tape_pressure: bool = True # False: an empty tape does not block the entry + front_run_max_ticks: int = 2 # front-run an algo level at most this far behind the touch + fallback: bool = False # no confirmed algo: direction from microprice + who moved the spread + fallback_window_ms: float = 2000 # how far back best-price moves count for the fallback + # risk guard + max_position_usd: float = 50.0 # 0 = no limit + max_daily_loss_usd: float = 5.0 # 0 = no limit + max_trades_per_minute: int = 20 + max_consecutive_losses: int = 3 + pause_minutes: float = 5.0 + max_order_latency_ms: float = 100 + max_data_latency_ms: float = 50 + cooldown_after_exit_ms: float = 1000 + + @classmethod + def load(cls, path: Path = CONFIG_FILE) -> "AlgoHunterConfig": + cfg = cls() + try: + data = json.loads(path.read_text(encoding="utf-8")) + section = data.get("algo_hunter", data) + for f in fields(cls): + if f.name in section: + setattr(cfg, f.name, type(getattr(cfg, f.name))(section[f.name])) + except (OSError, ValueError, TypeError): + pass + return cfg + + def save(self, path: Path = CONFIG_FILE) -> None: + try: + path.write_text(json.dumps({"algo_hunter": asdict(self)}, ensure_ascii=False, indent=2), encoding="utf-8") + except OSError: + pass + + +def _logger() -> logging.Logger: + log = logging.getLogger("algo_hunter") + if not log.handlers: + log.setLevel(logging.INFO) + try: + handler = RotatingFileHandler(LOG_FILE, maxBytes=5_000_000, backupCount=3, encoding="utf-8") + handler.setFormatter(logging.Formatter("%(asctime)s [ALGO_HUNTER] %(message)s")) + log.addHandler(handler) + except OSError: + log.addHandler(logging.NullHandler()) + log.propagate = False + return log + + +def _same(a: float, b: float, tol: float = SIZE_TOLERANCE) -> bool: + return a > 0 and b > 0 and abs(a - b) <= tol * max(a, b) + + +# -------------------------------------------------------------------------------------------- +# Detector +# -------------------------------------------------------------------------------------------- + +@dataclass +class LevelEvent: + ts: float + side: str # "bid" / "ask" + price: float + size: float # size after the change (add/increase) or the removed size (cancel/fill) + action: str # add / cancel / fill + offset: int # distance from the best price on that side, ticks + + +@dataclass +class AlgoSignature: + side: str # "bid", "ask" or "both" + price_levels: list[float] + volumes: list[float] + confidence: float + detected_at: float + signals: list[str] = field(default_factory=list) + size: float = 0.0 # the algo's typical order size + batch_cancel_side: str = "" # side where the algo just pulled several levels at once + + +class AlgoDetector: + def __init__(self, cfg: AlgoHunterConfig) -> None: + self.cfg = cfg + self.prev: dict[str, dict[float, float]] = {"bid": {}, "ask": {}} + self.events: deque[LevelEvent] = deque() + self.updates: deque[tuple[float, list[LevelEvent]]] = deque() + self.trades: deque[sh.Trade] = deque() + self.update_times: deque[float] = deque(maxlen=200) + self.last: AlgoSignature | None = None + + # cadence of the data source: an algo reacting faster than this is invisible + def cadence_ms(self) -> float: + if len(self.update_times) < 10: + return 0.0 + times = list(self.update_times) + return statistics.median(b - a for a, b in zip(times, times[1:])) * 1000 + + def effective_reaction_ms(self) -> float: + return max(self.cfg.reaction_latency_ms, 1.2 * self.cadence_ms()) + + def on_trade(self, trade: sh.Trade) -> None: + self.trades.append(trade) + + def _top(self, book: sh.OrderBook) -> dict[str, dict[float, float]]: + k = self.cfg.depth_levels + return {"bid": dict(sorted(book.bids.items(), reverse=True)[:k]), "ask": dict(sorted(book.asks.items())[:k])} + + def on_book(self, now: float, book: sh.OrderBook, tick: float) -> tuple[AlgoSignature | None, list[LevelEvent]]: + cur = self._top(book) + self.update_times.append(now) + if not self.prev["bid"] and not self.prev["ask"]: + self.prev = cur # the first book is the baseline, not a burst of new orders + return None, [] + window = self.cfg.detection_window_ms / 1000 + while self.trades and self.trades[0].ts < now - window: + self.trades.popleft() + recent_trades = [t for t in self.trades if t.ts >= (self.update_times[-2] if len(self.update_times) > 1 else now - 1)] + events: list[LevelEvent] = [] + for side in ("bid", "ask"): + best = max(cur[side]) if side == "bid" and cur[side] else min(cur[side]) if cur[side] else None + if best is None or tick <= 0: + continue + old, new = self.prev[side], cur[side] + # Only compare inside the overlapping price range: levels sliding out of the top-K are not cancels. + edge = min(new) if side == "bid" else max(new) + for price in set(old) | set(new): + if (side == "bid" and price < edge) or (side == "ask" and price > edge): + continue + before, after = old.get(price, 0.0), new.get(price, 0.0) + if after > before * (1 + SIZE_TOLERANCE): + offset = int(round(abs(best - price) / tick)) + events.append(LevelEvent(now, side, price, after - before if before else after, "add", offset)) + elif after < before * (1 - SIZE_TOLERANCE): + traded = sum(t.size for t in recent_trades if abs(t.price - price) < tick / 2) + action = "fill" if traded >= 0.5 * (before - after) else "cancel" + offset = int(round(abs(best - price) / tick)) + events.append(LevelEvent(now, side, price, before - after, action, offset)) + self.prev = cur + self.updates.append((now, events)) + self.events.extend(events) + while self.events and self.events[0].ts < now - window: + self.events.popleft() + while self.updates and self.updates[0][0] < now - window: + self.updates.popleft() + sig = self._evaluate(now, cur, book, tick, events) + self.last = sig + return sig, events + + def _dominant_size(self) -> tuple[float, list[LevelEvent]] | None: + adds = [e for e in self.events if e.action == "add"] + if len(adds) < 3: + return None + best_size, best_group = 0.0, [] + for candidate in adds: + group = [e for e in adds if _same(e.size, candidate.size, self.cfg.size_tolerance)] + if len(group) > len(best_group): + best_size, best_group = candidate.size, group + if len(best_group) < 3: + return None + return statistics.median(e.size for e in best_group), best_group + + def _evaluate(self, now: float, cur: dict, book: sh.OrderBook, tick: float, + events: list[LevelEvent]) -> AlgoSignature | None: + cfg = self.cfg + signals: list[str] = [] + side_votes = {"bid": 0, "ask": 0} + dominant = self._dominant_size() + size = dominant[0] if dominant else 0.0 + group = dominant[1] if dominant else [] + for e in group: + side_votes[e.side] += 1 + # 1) periodicity: the same size re-appears at regular intervals for most of the window + if len(group) >= 3: + times = sorted({round(e.ts, 3) for e in group}) + gaps = [(b - a) * 1000 for a, b in zip(times, times[1:])] + span = (times[-1] - times[0]) * 1000 + in_range = [g for g in gaps if cfg.min_interval_ms <= g <= cfg.max_interval_ms] + if gaps and len(in_range) / len(gaps) >= 0.6 and span >= 0.5 * cfg.detection_window_ms: + signals.append("периодичность") + # 2) volume stability: most new orders near the touch carry the same size, and that group barely varies + near_adds = [e for e in self.events if e.action == "add" and e.offset <= cfg.max_spread_ticks + 2] + if len(group) >= 3 and near_adds: + share = sum(1 for e in group if e.offset <= cfg.max_spread_ticks + 2) / len(near_adds) + sizes = [e.size for e in group] + cv = statistics.pstdev(sizes) / statistics.mean(sizes) + if share >= 0.5 and cv < cfg.max_volume_cv: + signals.append("стабильный объём") + # 3) cluster: consecutive best levels holding the same size + cluster_side, cluster_levels = "", [] + for side in ("bid", "ask"): + levels = sorted(cur[side].items(), reverse=(side == "bid"))[:5] + run = [levels[0]] if levels else [] + for prev_level, level in zip(levels, levels[1:]): + if _same(prev_level[1], level[1], cfg.size_tolerance): + run.append(level) + else: + if len(run) >= cfg.min_levels_cluster: + break + run = [level] + if len(run) >= cfg.min_levels_cluster and len(run) > len(cluster_levels): + cluster_side, cluster_levels = side, run + if cluster_levels: + signals.append("кластер уровней") + side_votes[cluster_side] += 2 + if not size: + size = cluster_levels[0][1] + # 4) symmetry: bid and ask quoted together at the same distance from the touch + symmetric = 0 + for _ts, evs in self.updates: + bids = [e for e in evs if e.side == "bid" and e.action == "add" and e.offset <= cfg.max_spread_ticks] + asks = [e for e in evs if e.side == "ask" and e.action == "add" and e.offset <= cfg.max_spread_ticks] + if any(abs(b.offset - a.offset) <= 1 and _same(b.size, a.size, 0.2) for b in bids for a in asks): + symmetric += 1 + if symmetric >= 2: + signals.append("симметрия bid/ask") + # 5) reactivity: the same-size level is restored right after a market order hit it + reaction = self.effective_reaction_ms() / 1000 + reactive = 0 + for trade in self.trades: + passive = "bid" if trade.side == "Sell" else "ask" + if any(e.side == passive and e.action == "add" and 0 <= e.ts - trade.ts <= reaction + and abs(e.price - trade.price) <= 2 * tick and (not size or abs(e.size - size) <= GROUP_TOLERANCE * size) + for e in self.events): + reactive += 1 + if reactive >= 2: + signals.append("реакция на сделки") + # 6) batch: several levels of exactly the algo's size added or pulled in one update, making up most of + # that update (data sources that bundle many changes per message would otherwise always look "batched") + batch_side = "" + if size: + for ts, evs in self.updates: + for side in ("bid", "ask"): + side_events = [e for e in evs if e.side == side and e.action in ("add", "cancel")] + same_size = [e for e in side_events if _same(e.size, size, max(0.05, cfg.size_tolerance))] + if len(same_size) >= cfg.batch_size_threshold and len(same_size) >= 0.6 * len(side_events): + if "пачка снятий/постановок" not in signals: + signals.append("пачка снятий/постановок") + if ts == now and sum(e.action == "cancel" for e in same_size) >= cfg.batch_size_threshold: + batch_side = side + if not signals: + return None + n = len(signals) + confidence = min(1.0, 0.25 + 0.15 * n) if n >= 1 else 0.0 + if n < cfg.min_signals_to_confirm: + confidence = min(confidence, cfg.min_confidence - 0.01) + if symmetric >= 2 and abs(side_votes["bid"] - side_votes["ask"]) <= 1: + side = "both" + else: + side = "bid" if side_votes["bid"] >= side_votes["ask"] else "ask" + # The algo's levels: prices where an order of its size was added recently and still rests + # (its order sits on top of the crowd, so the level total is at least ~its size). + levels = [] + sides = ("bid", "ask") if side == "both" else (side,) + seen = set() + for e in reversed(group): + if e.side in sides and e.price not in seen and cur[e.side].get(e.price, 0.0) >= 0.8 * size: + seen.add(e.price) + levels.append((e.price, cur[e.side][e.price])) + if not levels and cluster_levels: + levels = cluster_levels + levels.sort(key=lambda pv: pv[0], reverse=True) + return AlgoSignature(side, [p for p, _ in levels], [v for _, v in levels], confidence, now, signals, size, + batch_side) + + +# -------------------------------------------------------------------------------------------- +# Tracker +# -------------------------------------------------------------------------------------------- + +class AlgoTracker: + def __init__(self, cfg: AlgoHunterConfig) -> None: + self.cfg = cfg + self.history: deque[LevelEvent] = deque(maxlen=2000) + self.live: dict[tuple[str, float], float] = {} + self.lifetimes: deque[float] = deque(maxlen=200) + self.offsets: dict[str, deque[int]] = {"bid": deque(maxlen=50), "ask": deque(maxlen=50)} + self.replaces: deque[float] = deque(maxlen=500) + self.peak_confidence = 0.0 + self.adapted = False + self.low_since: float | None = None + + def update(self, now: float, sig: AlgoSignature | None, events: list[LevelEvent]) -> None: + confidence = sig.confidence if sig else 0.0 + if confidence >= self.cfg.min_confidence: + self.peak_confidence = max(self.peak_confidence, confidence) + # Adapted = after a confirmed algo, confidence stays below the threshold for adaptive_exit_ms in a row. + if self.peak_confidence >= self.cfg.min_confidence and confidence < self.cfg.adaptive_exit_threshold: + if self.low_since is None: + self.low_since = now + if (now - self.low_since) * 1000 >= self.cfg.adaptive_exit_ms: + self.adapted = True + else: + self.low_since = None + if not sig or not sig.size: + return + mine = [e for e in events if abs(e.size - sig.size) <= GROUP_TOLERANCE * sig.size] + for side in ("bid", "ask"): + adds = [e for e in mine if e.side == side and e.action == "add"] + cancels = [e for e in mine if e.side == side and e.action == "cancel"] + if adds and cancels: + self.replaces.append(now) + for e in mine: + self.history.append(e) + key = (e.side, e.price) + if e.action == "add": + self.live[key] = e.ts + self.offsets[e.side].append(e.offset) + elif key in self.live: + self.lifetimes.append((e.ts - self.live.pop(key)) * 1000) + + def reset_adaptation(self) -> None: + self.adapted = False + self.peak_confidence = 0.0 + + @property + def avg_lifetime_ms(self) -> float: + return statistics.mean(self.lifetimes) if self.lifetimes else 0.0 + + def replace_frequency(self, now: float, seconds: float = 10.0) -> float: + return sum(1 for t in self.replaces if t >= now - seconds) / seconds + + def typical_offset_ticks(self, side: str) -> int | None: + offsets = self.offsets[side] + return int(statistics.median(offsets)) if len(offsets) >= 3 else None + + def prediction(self, side: str, book: sh.OrderBook, tick: float) -> tuple[float, float] | None: + """Where the algo re-quotes next on `side` and how consistent that has been (share of recent adds).""" + offset = self.typical_offset_ticks(side) + best_bid, best_ask = book.best() + if offset is None or best_bid is None or best_ask is None: + return None + recent = list(self.offsets[side])[-10:] + share = sum(o == offset for o in recent) / len(recent) + price = best_bid - offset * tick if side == "bid" else best_ask + offset * tick + return sh._to_tick(price, tick, None), share + + +# -------------------------------------------------------------------------------------------- +# Risk guard +# -------------------------------------------------------------------------------------------- + +class RiskGuard: + def __init__(self, cfg: AlgoHunterConfig) -> None: + self.cfg = cfg + self.day = "" + self.daily_pnl = 0.0 + self.trade_times: deque[float] = deque() + self.losses = 0 + self.pause_until = 0.0 + self.last_exit = 0.0 + self.disabled_reason = "" + + def _roll_day(self, now: float) -> None: + day = datetime.fromtimestamp(now, timezone.utc).strftime("%Y-%m-%d") + if day != self.day: + self.day, self.daily_pnl = day, 0.0 + if self.disabled_reason.startswith("дневной убыток"): + self.disabled_reason = "" + + def latency_problem(self, latency_ms: float | None) -> str: + if latency_ms is None: + return "" + if latency_ms > self.cfg.max_order_latency_ms: + return (f"задержка {latency_ms:.0f} мс > {self.cfg.max_order_latency_ms:g} мс — гонку за очередь с " + "алгосом не выиграть, виртуальные входы отключены") + return "" + + def allow(self, now: float, notional: float, latency_ms: float | None) -> tuple[bool, str]: + self._roll_day(now) + cfg = self.cfg + if self.disabled_reason: + return False, self.disabled_reason + problem = self.latency_problem(latency_ms) + if problem: + return False, problem + if cfg.max_position_usd > 0 and notional > cfg.max_position_usd: + return False, f"позиция {notional:.2f}$ больше лимита {cfg.max_position_usd:g}$" + if now < self.pause_until: + return False, f"пауза после {cfg.max_consecutive_losses} убытков подряд ещё {self.pause_until - now:.0f} с" + if (now - self.last_exit) * 1000 < cfg.cooldown_after_exit_ms: + return False, "пауза после выхода" + while self.trade_times and self.trade_times[0] < now - 60: + self.trade_times.popleft() + if len(self.trade_times) >= cfg.max_trades_per_minute: + return False, f"лимит {cfg.max_trades_per_minute} сделок в минуту" + return True, "" + + def on_entry(self, now: float) -> None: + self.trade_times.append(now) + + def on_close(self, now: float, pnl: float) -> None: + self._roll_day(now) + self.last_exit = now + self.daily_pnl += pnl + self.losses = self.losses + 1 if pnl < 0 else 0 + if self.losses >= self.cfg.max_consecutive_losses: + self.pause_until = now + self.cfg.pause_minutes * 60 + self.losses = 0 + if self.cfg.max_daily_loss_usd > 0 and self.daily_pnl <= -self.cfg.max_daily_loss_usd: + self.disabled_reason = (f"дневной убыток {self.daily_pnl:.2f}$ достиг лимита {self.cfg.max_daily_loss_usd:g}$ — " + "режим выключен до следующего дня (UTC)") + + +# -------------------------------------------------------------------------------------------- +# Executor (paper policy plugged into scalp_paper.PaperTrader) +# -------------------------------------------------------------------------------------------- + +@dataclass +class HunterOrder: + side: str # LONG / SHORT + price: float + size_usd: float + sent: float + ack: float + scenario: str + signature: AlgoSignature + ahead: float | None = None # queue volume in front of us (USD), set at ack + algo_ahead: float = 0.0 # part of `ahead` that belongs to the algo's level + front_run: bool = False + + +class AlgoHunterPolicy: + name = "algo_hunter" + + def __init__(self, settings, cfg: AlgoHunterConfig | None = None, trades_path: Path | None = TRADES_FILE) -> None: + self.s = settings + self.cfg = cfg or AlgoHunterConfig.load() + self.detector = AlgoDetector(self.cfg) + self.tracker = AlgoTracker(self.cfg) + self.guard = RiskGuard(self.cfg) + self.trades_path = trades_path + self.log = _logger() + self.order: HunterOrder | None = None + self.entry_order: HunterOrder | None = None + self.filled_at = 0.0 + self.stop = 0.0 + self.target = 0.0 + self.tick = 0.0 + self.ticker = "" + self.sig: AlgoSignature | None = None + self.mids: deque[tuple[float, float]] = deque() + self.status = "Algo Hunter: жду стакан…" + self.stats = {"entries": 0, "wins": 0, "pnl_ticks": 0.0, "front_run": 0, "detections": 0, "orders": 0, + "requotes": 0} + self.best: tuple[float | None, float | None] = (None, None) + self.spread_moves: deque[tuple[float, int]] = deque() # (ts, +1 bid up / ask up, -1 bid down / ask down) + self.fallback_info = "" + self.last_direction = "LONG" + self.was_confirmed = False + self.confirmed_since: float | None = None + self.warned = "" + self.status_reason = "" + + # --- helpers ------------------------------------------------------------------------ + def export_state(self) -> dict: + return {"cfg": asdict(self.cfg), "filled_at": self.filled_at, "stop": self.stop, + "target": self.target, "tick": self.tick, "ticker": self.ticker, + "entry_order": asdict(self.entry_order) if self.entry_order else None, + "stats": dict(self.stats), "guard": { + name: getattr(self.guard, name) for name in + ("day", "daily_pnl", "losses", "pause_until", "last_exit", "disabled_reason")}, + "trade_times": list(self.guard.trade_times)} + + def restore_state(self, state: dict, position=None) -> None: + if state.get("cfg"): + self.cfg = AlgoHunterConfig(**state["cfg"]) + self.detector.cfg = self.tracker.cfg = self.guard.cfg = self.cfg + for name in ("filled_at", "stop", "target", "tick", "ticker"): + if name in state: + setattr(self, name, state[name]) + self.stats.update(state.get("stats", {})) + for name, value in state.get("guard", {}).items(): + if name in ("day", "daily_pnl", "losses", "pause_until", "last_exit", "disabled_reason"): + setattr(self.guard, name, value) + self.guard.trade_times = deque(state.get("trade_times", [])) + row = state.get("entry_order") + if row is not None and position is not None: + row = dict(row) + row["signature"] = AlgoSignature(**row["signature"]) + self.entry_order = HunterOrder(**row) + if position is not None: + # The persisted position is authoritative even if the last policy checkpoint was interrupted. + self.ticker, self.filled_at = position.ticker, position.opened + self.target = position.target + self.stop = position.stop if position.stop is not None else self.stop + + def _latency(self, trader) -> float | None: + """Effective delay of our view of the book: measured data latency, or the source cadence at least.""" + measured = getattr(trader, "data_latency_ms", None) + cadence = self.detector.cadence_ms() or None + values = [v for v in (measured, cadence) if v is not None] + return max(values) if values else None + + def _vol_ticks(self, now: float) -> float: + recent = [m for t, m in self.mids if t >= now - 1.0] + if len(recent) < 2 or self.tick <= 0: + return 0.0 + return (max(recent) - min(recent)) / self.tick + + def _tape_pressure(self, now: float, side: str) -> bool: + window = self.cfg.entry_tape_window_ms / 1000 + recent = [t for t in self.detector.trades if t.ts >= now - window] + buy = sum(t.size for t in recent if t.side == "Buy") + sell = sum(t.size for t in recent if t.side == "Sell") + if not self.cfg.require_tape_pressure and buy == sell: + return True + return buy > sell if side == "LONG" else sell > buy + + # --- book updates: detection, queue model, emergency exit, new orders ----------------- + def on_book(self, trader, now: float, book: sh.OrderBook, tick: float) -> None: + if tick > 0: + self.tick = tick + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None or self.tick <= 0: + return + prev_bid, prev_ask = self.best + if prev_bid is not None and prev_ask is not None: + # A bid stepping into the spread / an ask pulled away push the price up; the opposite pushes it down. + for moved in (best_bid - prev_bid, best_ask - prev_ask): + if abs(moved) >= self.tick / 2: + self.spread_moves.append((now, 1 if moved > 0 else -1)) + while self.spread_moves and self.spread_moves[0][0] < now - self.cfg.fallback_window_ms / 1000: + self.spread_moves.popleft() + self.best = (best_bid, best_ask) + self.mids.append((now, (best_bid + best_ask) / 2)) + while self.mids and self.mids[0][0] < now - 5: + self.mids.popleft() + sig, events = self.detector.on_book(now, book, self.tick) + self.sig = sig + self.tracker.update(now, sig, events) + confirmed = bool(sig and sig.confidence >= self.cfg.min_confidence + and len(sig.signals) >= self.cfg.min_signals_to_confirm) + if confirmed and not self.was_confirmed: + self.stats["detections"] += 1 + self.log.info("detect %s side=%s conf=%.2f signals=%s size=%.2f levels=%s", self.ticker, sig.side, + sig.confidence, ",".join(sig.signals), sig.size, + ",".join(f"{p:.10g}x{v:.0f}" for p, v in zip(sig.price_levels, sig.volumes))) + self.was_confirmed = confirmed + if not confirmed: + self.confirmed_since = None + elif self.confirmed_since is None: + self.confirmed_since = now + if (self.cfg.rearm_after_ms > 0 and self.guard.disabled_reason.startswith("алгос адаптировался") + and self.confirmed_since is not None + and (now - self.confirmed_since) * 1000 >= self.cfg.rearm_after_ms): + self.rearm() + if self.tracker.adapted and not self.guard.disabled_reason and not self.cfg.fallback: + self.guard.disabled_reason = "алгос адаптировался (уверенность ниже порога) — режим выключен" + self.log.info("adapted: confidence fell below %.2f, mode disabled", self.cfg.adaptive_exit_threshold) + self._cancel(trader, now, "алгос адаптировался") + self._update_queue(book, events) + led = trader.ledger + pos = led.position + if pos is not None: + our_side = "bid" if pos.side == "LONG" else "ask" + if sig and sig.batch_cancel_side == our_side: + self._close(trader, best_bid if pos.side == "LONG" else best_ask, now, "алгос снял пачку — экстренный выход", + sh.TAKER_FEE_PCT) + return + if not self.cfg.quick_exit and (now - self.filled_at) * 1000 >= self.cfg.max_hold_ms: + self._close(trader, best_bid if pos.side == "LONG" else best_ask, now, "время", sh.TAKER_FEE_PCT) + return + if self.order is not None and self.cfg.requote: + # Re-quote: follow the book every update; the order goes only when there is no candidate at all. + order = self.order + if now < order.ack: + return # still on its way to the exchange + cand = self._candidate(trader, now, book, sig, confirmed) + if cand is None: + self._cancel(trader, now, self.status_reason or "условия входа пропали", quiet=True) + elif (cand[0], cand[1]) != (order.side, order.price): + self.stats["requotes"] += 1 + self.order = None + self._place(trader, now, sig, cand, log=False) + return + if self.order is not None: + order = self.order + spread_ticks = (best_ask - best_bid) / self.tick + if (now - order.sent) * 1000 > self.cfg.order_ttl_ms: + self._cancel(trader, now, "не исполнилась за отведённое время") + elif (not confirmed and not self.cfg.fallback) or spread_ticks > self.cfg.max_entry_spread_ticks: + self._cancel(trader, now, "алгос пропал или спред расширился") + elif spread_ticks < self.cfg.min_entry_spread_ticks - 1e-9: + self._cancel(trader, now, "спред сузился") + return + self._maybe_enter(trader, now, book, sig, confirmed) + + def _update_queue(self, book: sh.OrderBook, events: list[LevelEvent]) -> None: + order = self.order + if order is None or order.ahead is None: + return + side = "bid" if order.side == "LONG" else "ask" + for e in events: + if e.side != side or abs(e.price - order.price) > self.tick / 2 or e.action != "cancel": + continue + # Cancels are assumed to come from behind us, except when the algo pulls its whole level: + # then its size leaves the queue in front of us and its re-quote lands behind us. + if order.algo_ahead and e.size >= 0.8 * order.algo_ahead: + order.ahead = max(0.0, order.ahead - order.algo_ahead) + order.algo_ahead = 0.0 + order.front_run = True + self.log.info("queue: algo pulled its level %.10g, we are ahead now (ahead %.0f$)", order.price, + order.ahead) + + def _maybe_enter(self, trader, now: float, book: sh.OrderBook, sig: AlgoSignature | None, confirmed: bool) -> None: + cand = self._candidate(trader, now, book, sig, confirmed) + if cand is not None: + self._place(trader, now, sig, cand) + + def _candidate(self, trader, now: float, book: sh.OrderBook, sig: AlgoSignature | None, + confirmed: bool) -> tuple[str, float, str, float] | None: + """(direction, price, scenario, algo volume in front) of the order to place now, or None (reason in status).""" + cfg = self.cfg + self.status_reason = "" + if not self.s.enabled or ((not confirmed or sig is None) and not cfg.fallback): + return None + best_bid, best_ask = book.best() + spread_ticks = (best_ask - best_bid) / self.tick + if spread_ticks > cfg.max_entry_spread_ticks: + self.status_reason = f"спред {spread_ticks:.0f} шаг. > {cfg.max_entry_spread_ticks}" + return None + if spread_ticks < cfg.min_entry_spread_ticks - 1e-9: + self.status_reason = f"спред {spread_ticks:.0f} шаг. < {cfg.min_entry_spread_ticks}" + return None + if self._vol_ticks(now) > cfg.vol_cap_ticks: + self.status_reason = "волатильность за 1 с выше порога" + return None + notional = self.s.stake * self.s.leverage + if trader.ledger.account is not None and trader.ledger.available < self.s.stake: + self.status_reason = "Недостаточно свободных виртуальных средств" + return None + allowed, reason = self.guard.allow(now, notional, self._latency(trader)) + if not allowed: + if reason != self.warned: + self.log.info("risk: %s", reason) + self.warned = reason + self.status_reason = reason + return None + candidates = [] + algo_sides = () if not confirmed or sig is None else ("bid", "ask") if sig.side == "both" else (sig.side,) + for side in algo_sides: + direction = "LONG" if side == "bid" else "SHORT" + if not self._tape_pressure(now, direction): + continue + best = best_bid if side == "bid" else best_ask + algo_levels = [(p, v) for p, v in zip(sig.price_levels, sig.volumes) + if (p <= best if side == "bid" else p >= best)] + # Scenario 1: front-run the algo's level that is 0..front_run_max_ticks behind the touch. + for price, vol in sorted(algo_levels, key=lambda pv: abs(pv[0] - best)): + k = round(abs(best - price) / self.tick) + if 0 <= k <= cfg.front_run_max_ticks: + better = price + self.tick if side == "bid" else price - self.tick + crosses = better >= best_ask if side == "bid" else better <= best_bid + candidates.append((direction, price if crosses else better, "встать перед алгосом", + vol if crosses else 0.0)) + break + # Scenario 2: pre-place on the level where the algo re-quotes next. + pred = self.tracker.prediction(side, book, self.tick) + if pred and pred[1] >= cfg.prediction_confidence: + candidates.append((direction, pred[0], "перестановка алгоса", 0.0)) + if not candidates and cfg.fallback: + return self._fallback_candidate(book) + if not candidates: + self.status_reason = "нет давления в ленте в сторону алгоса" + return None + return candidates[0] + + def _fallback_candidate(self, book: sh.OrderBook) -> tuple[str, float, str, float]: + """No usable algo: direction from the microprice tilt plus which side moved the spread lately; always + returns an order one tick inside the spread on that side (or at the touch when the spread is 1 tick).""" + best_bid, best_ask = book.best() + bid_size, ask_size = book.bids.get(best_bid, 0.0), book.asks.get(best_ask, 0.0) + # Microprice tilt in [-1, 1]: a heavy bid queue (> 0) pulls the microprice towards the ask. + tilt = (bid_size - ask_size) / (bid_size + ask_size) if bid_size + ask_size > 0 else 0.0 + flow = sum(sign for _, sign in self.spread_moves) + score = tilt + max(-1.0, min(1.0, flow / 3)) + if score > 0: + direction = "LONG" + elif score < 0: + direction = "SHORT" + else: + direction = self.last_direction + self.last_direction = direction + inside = (best_ask - best_bid) / self.tick >= 2 + if direction == "LONG": + price = best_bid + self.tick if inside else best_bid + else: + price = best_ask - self.tick if inside else best_ask + price = sh._to_tick(price, self.tick, None) + self.fallback_info = (f"без алгоса: микроцена {tilt:+.2f}, сдвиги спреда {flow:+d} → {direction}") + return direction, price, "микроцена + спред", 0.0 + + def _place(self, trader, now: float, sig: AlgoSignature, cand: tuple[str, float, str, float], + log: bool = True) -> None: + cfg = self.cfg + direction, price, scenario, algo_vol = cand + notional = self.s.stake * self.s.leverage + latency = (self._latency(trader) or 0.0) / 1000 + if sig is None: + sig_copy = AlgoSignature("none", [], [], 0.0, now, [self.fallback_info], 0.0) + else: + sig_copy = AlgoSignature(sig.side, list(sig.price_levels), list(sig.volumes), sig.confidence, + sig.detected_at, list(sig.signals), sig.size) + self.order = HunterOrder(direction, price, notional, now, now + latency, scenario, sig_copy, + algo_ahead=algo_vol) + self.stats["orders"] += 1 + if log: + self.log.info("order %s %s %.10g size=%.2f$ scenario=%s conf=%.2f dry_run=%s", self.ticker, direction, + price, notional, scenario, sig_copy.confidence, cfg.dry_run) + if cfg.dry_run: + # Dry run: the decision is logged, no virtual order is kept. + self.order = None + self.status_reason = f"dry-run: был бы вход {direction} {price:.10g} ({scenario})" + + # --- trades: queue progress, fills, TP/SL --------------------------------------------- + def on_trade(self, trader, trade: sh.Trade) -> None: + self.detector.on_trade(trade) + order = self.order + if order is not None: + if trade.ts < order.ack: + return # not at the exchange yet + if order.ahead is None: + book_side = self.detector.prev["bid" if order.side == "LONG" else "ask"] + order.ahead = book_side.get(order.price, 0.0) + order.algo_ahead = min(order.algo_ahead, order.ahead) + order.front_run = order.front_run or order.algo_ahead == 0.0 + long = order.side == "LONG" + hits_us = (trade.side == "Sell") if long else (trade.side == "Buy") + if (trade.price < order.price) if long else (trade.price > order.price): + self._fill(trader, trade.ts, trade.size) + elif hits_us and abs(trade.price - order.price) < self.tick / 2: + consumed = min(order.ahead, trade.size) + order.ahead -= consumed + order.algo_ahead = max(0.0, order.algo_ahead - consumed) + available = max(0.0, trade.size - consumed) + if available > 0: + self._fill(trader, trade.ts, available) + return + pos = trader.ledger.position + if pos is None: + return + long = pos.side == "LONG" + if self.cfg.quick_exit: + # The next trade at another price closes the position at market, in profit or not. + if abs(trade.price - pos.entry) >= self.tick / 2: + best_bid, best_ask = self.best + exit_price = (best_bid if long else best_ask) or trade.price + way = "вверх" if trade.price > pos.entry else "вниз" + self._close(trader, exit_price, trade.ts, f"следующий тик: цена {way}", sh.TAKER_FEE_PCT) + return + if self.cfg.trailing and (trade.price >= pos.entry + self.cfg.tp_partial_ticks * self.tick if long + else trade.price <= pos.entry - self.cfg.tp_partial_ticks * self.tick): + self.stop = max(self.stop, pos.entry) if long else min(self.stop, pos.entry) + pos.stop = self.stop + if (trade.price <= self.stop) if long else (trade.price >= self.stop): + slip = self.tick + self._close(trader, self.stop - slip if long else self.stop + slip, trade.ts, + "стоп (безубыток)" if self.stop == pos.entry else "стоп", sh.TAKER_FEE_PCT) + elif (trade.price > self.target) if long else (trade.price < self.target): + self._close(trader, self.target, trade.ts, "цель", sh.MAKER_FEE_PCT) + + def _fill(self, trader, now: float, available_usd: float | None = None) -> None: + """Fill only observed executable volume; cancel the unfilled remainder after a partial fill.""" + order = self.order + filled_usd = min(order.size_usd, available_usd) if available_usd is not None else order.size_usd + if filled_usd <= 0: + return + self.order = None + long = order.side == "LONG" + target = order.price + (1 if long else -1) * self.cfg.tp_ticks * self.tick + stop = order.price - (1 if long else -1) * self.cfg.sl_ticks * self.tick + pos = trader.ledger.open(self.ticker, order.side, order.price, now, sh.MAKER_FEE_PCT, + target, stop, order.price, order.scenario, notional_usd=filled_usd) + if pos is None: + trader.message = trader.ledger.storage_error + self.status_reason = trader.message + return + order.size_usd = filled_usd + self.entry_order = order + self.filled_at = now + self.target, self.stop = target, stop + trader.ledger.position.target = self.target + trader.ledger.position.stop = self.stop + self.guard.on_entry(now) + self.stats["entries"] += 1 + if order.front_run: + self.stats["front_run"] += 1 + trader.message = f"Algo Hunter: исполнена {order.side} {order.price:.10g} ({order.scenario})" + self.log.info("fill %s %s %.10g front_run=%s", self.ticker, order.side, order.price, order.front_run) + trader.ledger.save() + + def _cancel(self, trader, now: float, reason: str, quiet: bool = False) -> None: + if self.order is not None: + if not quiet: + self.log.info("cancel %s %s %.10g: %s", self.ticker, self.order.side, self.order.price, reason) + trader.message = f"Algo Hunter: заявка снята — {reason}" + self.order = None + + def _close(self, trader, price: float, now: float, reason: str, fee_pct: float) -> None: + pos = trader.ledger.position + if pos is None: + return + order = self.entry_order + before = len(trader.ledger.trades) + trader.close(price, now, reason, fee_pct) + if len(trader.ledger.trades) == before: + return + trade = trader.ledger.trades[-1] + pnl_ticks = (price - pos.entry) / self.tick * (1 if pos.side == "LONG" else -1) + self.stats["pnl_ticks"] += pnl_ticks + if trade.net_usd > 0: + self.stats["wins"] += 1 + self.guard.on_close(now, trade.net_usd) + self.log.info("exit %s %s entry=%.10g exit=%.10g pnl_ticks=%.1f net=%.4f$ hold_ms=%.0f reason=%s", self.ticker, + pos.side, pos.entry, price, pnl_ticks, trade.net_usd, (now - self.filled_at) * 1000, reason) + if self.trades_path and order is not None: + new = not self.trades_path.exists() + try: + with self.trades_path.open("a", encoding="utf-8-sig", newline="") as file: + writer = csv.writer(file) + if new: + writer.writerow(TRADE_COLUMNS) + sig = order.signature + writer.writerow([trade.closed_utc, self.ticker, pos.side, order.scenario, f"{sig.confidence:.2f}", + "|".join(sig.signals), sig.side, "|".join(f"{p:.10g}" for p in sig.price_levels), + "|".join(f"{v:.0f}" for v in sig.volumes), f"{order.price:.10g}", + f"{order.size_usd:.2f}", f"{order.sent:.3f}", f"{order.ack:.3f}", + f"{order.ahead if order.ahead is not None else 0:.0f}", order.front_run, + f"{pos.entry:.10g}", f"{price:.10g}", f"{pnl_ticks:.1f}", f"{trade.net_usd:.6f}", + f"{(now - self.filled_at) * 1000:.0f}", reason]) + except OSError: + pass + self.entry_order = None + trader.ledger.save() + + def rearm(self) -> None: + """Switch the mode back on after an 'algo adapted' shutdown (user pressed Apply, or a new ticker).""" + self.tracker.reset_adaptation() + self.tracker.low_since = None + if self.guard.disabled_reason.startswith("алгос адаптировался"): + self.guard.disabled_reason = "" + self.log.info("rearmed after adaptation") + + def entry_blockers(self, trader, now: float, book: sh.OrderBook) -> list[str]: + """Every condition that currently prevents an entry (all of them, not only the first).""" + cfg = self.cfg + out = [] + if cfg.dry_run: + out.append("включена «Только проверка»") + if not self.s.enabled: + out.append("тестовые сделки выключены") + if self.guard.disabled_reason: + out.append(self.guard.disabled_reason) + if trader.ledger.account is not None and trader.ledger.available < self.s.stake: + out.append("Недостаточно свободных виртуальных средств") + sig = self.sig + n = len(sig.signals) if sig else 0 + if cfg.fallback: + pass # without a confirmed algo the microprice + spread fallback places the order + elif n < cfg.min_signals_to_confirm: + out.append(f"алгос не подтверждён: признаков {n} из {cfg.min_signals_to_confirm}") + elif sig.confidence < cfg.min_confidence: + out.append(f"уверенность {sig.confidence:.2f} < {cfg.min_confidence:g}") + best_bid, best_ask = book.best() + if best_bid is not None and best_ask is not None and self.tick > 0: + spread = (best_ask - best_bid) / self.tick + if spread > cfg.max_entry_spread_ticks + 1e-9: + out.append(f"спред {spread:.0f} шаг. > {cfg.max_entry_spread_ticks}") + if spread < cfg.min_entry_spread_ticks - 1e-9: + out.append(f"спред {spread:.0f} шаг. < {cfg.min_entry_spread_ticks}") + if self._vol_ticks(now) > cfg.vol_cap_ticks: + out.append(f"волатильность за 1 с {self._vol_ticks(now):.0f} шаг. > {cfg.vol_cap_ticks:g}") + problem = self.guard.latency_problem(self._latency(trader)) + if problem: + out.append(problem.split(" — ")[0]) + allowed, reason = self.guard.allow(now, self.s.stake * self.s.leverage, None) + if not allowed and reason not in out: + out.append(reason) + return out + + # --- periodic: status for the window ---------------------------------------------------- + def on_tick(self, trader, now: float, ticker: str, hint, book: sh.OrderBook, tick: float) -> None: + if ticker != self.ticker and self.ticker: + self.detector = AlgoDetector(self.cfg) + self.tracker = AlgoTracker(self.cfg) + self.rearm() + self.ticker = ticker + if tick > 0: + self.tick = tick + sig = self.sig + latency = self._latency(trader) + parts = [] + if latency is not None: + parts.append(f"задержка данных ~{latency:.0f} мс" + (" (больше 50 мс: гонку за очередь не выиграть)" + if latency > self.cfg.max_data_latency_ms else "")) + if sig: + parts.append(f"уверенность {sig.confidence:.2f} ({', '.join(sig.signals)})") + if sig.price_levels: + shown = ", ".join(f"{p:.10g}×{v:,.0f}$" for p, v in list(zip(sig.price_levels, sig.volumes))[:4]) + parts.append(f"уровни алгоса [{sig.side}]: {shown}") + else: + parts.append("алгос не найден") + if self.order is not None and self.order.scenario == "микроцена + спред": + parts.append(self.fallback_info) + lifetime = self.tracker.avg_lifetime_ms + if lifetime: + offset_b = self.tracker.typical_offset_ticks("bid") + offset_a = self.tracker.typical_offset_ticks("ask") + parts.append(f"живёт {lifetime:.0f} мс · перестановок {self.tracker.replace_frequency(now):.1f}/с · отступ " + f"bid {offset_b if offset_b is not None else '—'} / ask {offset_a if offset_a is not None else '—'} шаг.") + e = self.stats["entries"] + parts.append(f"находок {self.stats['detections']} · заявок {self.stats['orders']} · входов {e} · в плюс " + f"{(self.stats['wins'] / e * 100 if e else 0):.0f}% · ср. {self.stats['pnl_ticks'] / e if e else 0:+.2f} шаг. · " + f"впереди алгоса {(self.stats['front_run'] / e * 100 if e else 0):.0f}%") + if self.cfg.dry_run: + parts.append("ПРОВЕРОЧНЫЙ РЕЖИМ: только детект и лог") + status = " · ".join(parts) + if trader.ledger.position is None and self.order is None: + blockers = self.entry_blockers(trader, now, book) + if not blockers and self.status_reason: + blockers = [self.status_reason] + if blockers: + status += "\nПочему нет входа: " + " · ".join(f"✗ {b}" for b in blockers) + self.status = status diff --git a/LinuxServer/arb.py b/LinuxServer/arb.py new file mode 100644 index 0000000..cf25927 --- /dev/null +++ b/LinuxServer/arb.py @@ -0,0 +1,569 @@ +"""Cross-exchange arbitrage scanner for USDT perpetuals on Bybit, Binance, MEXC, HTX and Gate. + +Every cycle (10 s) the best bid/ask of every perpetual on each exchange is fetched with one public request per +exchange; coins are matched by base ticker (contract-size prefixes such as 1000PEPE are converted to one coin). For +each coin listed on at least two exchanges the best pair "buy at the ask of A, sell at the bid of B" is taken: + +* gross spread = bid_B / ask_A − 1 (what an instant entry would capture); +* costs = taker fees of both legs, on entry and on exit (round trip); +* usual spread of that pair = exponential average over ~30 min of this scanner's own readings; +* expected = gross − usual − round-trip costs: the profit if the gap goes back to its usual size; +* funding per 8 h: short leg receives its rate, long leg pays its rate (sign as each exchange quotes it); +* depth = USD available at those best prices (where the exchange reports it), 24 h turnover. + +A spread above 10 % is flagged «разные монеты?» (the same ticker often means different tokens). Nothing is traded. +""" + +from __future__ import annotations + +import json +import os +import re +import threading +import time +import urllib.request +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass + +EXCHANGES = ["Bybit", "MEXC", "HTX", "Gate"] +TAKER = {"Bybit": 0.055, "MEXC": 0.02, "HTX": 0.05, "Gate": 0.05} # % per market order, futures +# spot market-order fees at the base level (no VIP, no fee-token discount) — editable on the page +SPOT_TAKER = {"Bybit": 0.1, "MEXC": 0.05, "HTX": 0.2, "Gate": 0.1} +LEVERAGED = re.compile(r"(\d+[LS]|UP|DOWN|BULL|BEAR)$") # leveraged tokens, not the coin itself +CYCLE_S = 10.0 +USUAL_WINDOW_S = 1800.0 +DIFFERENT_COIN_PCT = 10.0 +_PREFIX = re.compile(r"^(1000000|100000|10000|1000|100|1M)(?=[A-Z])") +_SUFFIX = re.compile(r"^([A-Z][A-Z0-9]*?)(1000000|10000|1000)$") + + +def split_base(raw: str) -> tuple[str, float]: + """'1000PEPE' -> ('PEPE', 1000); 'SHIB1000' -> ('SHIB', 1000); '1INCH' stays.""" + raw = raw.upper() + m = _PREFIX.match(raw) + if m: + return raw[m.end():], (1_000_000.0 if m.group(1) == "1M" else float(m.group(1))) + m = _SUFFIX.match(raw) + if m and len(m.group(1)) >= 2: + return m.group(1), float(m.group(2)) + return raw, 1.0 + + +def _f(v, default=0.0) -> float: + try: + return float(v) + except (TypeError, ValueError): + return default + + +def _get(url: str, timeout: float = 20): + # gzip: whole-market lists are megabytes of JSON; compressed they come several times faster + req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json", + "Accept-Encoding": "gzip"}) + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read() + if resp.headers.get("Content-Encoding", "").lower() == "gzip": + import gzip + raw = gzip.decompress(raw) + return json.loads(raw) + + +@dataclass +class Quote: + exchange: str + symbol: str # exchange's own symbol + base: str + mult: float # coins per quoted unit (1000PEPE -> 1000) + bid: float # per coin + ask: float + bid_usd: float | None # money at the best bid / ask (None: not reported) + ask_usd: float | None + funding: float | None # current rate, fraction per period + interval_h: float # funding period, hours + volume_usd: float + + +def _quote(exchange, symbol, raw_base, bid, ask, bid_coins, ask_coins, funding, interval_h, volume, + split: bool = True) -> Quote | None: + # spot tickers are the token's own name (1000SATS, 1INCH): no contract-size prefixes there + base, mult = split_base(raw_base) if split else (raw_base.upper(), 1.0) + bid, ask = _f(bid), _f(ask) + if not base or bid <= 0 or ask <= 0 or ask < bid: + return None + bid_c = None if bid_coins is None else _f(bid_coins) + ask_c = None if ask_coins is None else _f(ask_coins) + return Quote(exchange, symbol, base, mult, bid / mult, ask / mult, + None if bid_c is None else bid_c * bid, None if ask_c is None else ask_c * ask, + None if funding in (None, "") else _f(funding), interval_h or 8.0, _f(volume)) + + +# --- per-exchange fetchers (all public, one request for the whole market + rare reference data) ----------------- + +class Fetchers: + def __init__(self) -> None: + self.ref: dict[str, dict] = {} # slowly changing reference data, refreshed hourly + self.ref_time = 0.0 + self.binance_volume: dict[str, float] = {} + self.binance_volume_time = 0.0 + + def refresh_reference(self) -> None: + if time.time() - self.ref_time < 3600 and self.ref: + return + ref: dict[str, dict] = {"bybit_interval": {}, "htx_size": {}, "htx_interval": {}, + "gate_interval": {}, "mexc_size": {}} + try: + for it in _get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000")["result"]["list"]: + ref["bybit_interval"][it["symbol"]] = _f(it.get("fundingInterval"), 480) / 60 + except Exception: + pass + try: + for it in _get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]: + ref["htx_size"][it["contract_code"]] = _f(it.get("contract_size"), 1) + ref["htx_interval"][it["contract_code"]] = _f(it.get("settlement_period"), 8) + except Exception: + pass + try: + for it in _get("https://api.gateio.ws/api/v4/futures/usdt/contracts"): + ref["gate_interval"][it["name"]] = _f(it.get("funding_interval"), 28800) / 3600 + except Exception: + pass + try: + for it in _get("https://contract.mexc.com/api/v1/contract/detail")["data"]: + ref["mexc_size"][it["symbol"]] = _f(it.get("contractSize"), 1) + except Exception: + pass + self.ref, self.ref_time = ref, time.time() + + def bybit(self) -> list[Quote]: + out = [] + for t in _get("https://api.bybit.com/v5/market/tickers?category=linear")["result"]["list"]: + s = t["symbol"] + if s.endswith("USDT"): + out.append(_quote("Bybit", s, s[:-4], t.get("bid1Price"), t.get("ask1Price"), t.get("bid1Size"), + t.get("ask1Size"), t.get("fundingRate"), + self.ref.get("bybit_interval", {}).get(s, 8), t.get("turnover24h"))) + return [q for q in out if q] + + def binance(self) -> list[Quote]: + books = _get("https://fapi.binance.com/fapi/v1/ticker/bookTicker") + prem = {p["symbol"]: p for p in _get("https://fapi.binance.com/fapi/v1/premiumIndex")} + if time.time() - self.binance_volume_time > 60: + self.binance_volume = {t["symbol"]: _f(t.get("quoteVolume")) + for t in _get("https://fapi.binance.com/fapi/v1/ticker/24hr")} + self.binance_volume_time = time.time() + out = [] + for t in books: + s = t["symbol"] + if s.endswith("USDT") and "_" not in s: + out.append(_quote("Binance", s, s[:-4], t.get("bidPrice"), t.get("askPrice"), t.get("bidQty"), + t.get("askQty"), prem.get(s, {}).get("lastFundingRate"), + self.ref.get("binance_interval", {}).get(s, 8), self.binance_volume.get(s))) + return [q for q in out if q] + + def mexc(self) -> list[Quote]: + out = [] + for t in _get("https://contract.mexc.com/api/v1/contract/ticker")["data"]: + s = t["symbol"] + if s.endswith("_USDT"): + out.append(_quote("MEXC", s, s[:-5], t.get("bid1"), t.get("ask1"), None, None, t.get("fundingRate"), + 8, t.get("amount24"))) + return [q for q in out if q] + + def htx(self) -> list[Quote]: + funding = {} + try: + for f in _get("https://api.hbdm.com/linear-swap-api/v1/swap_batch_funding_rate")["data"]: + funding[f["contract_code"]] = f.get("funding_rate") + except Exception: + pass + out = [] + sizes = self.ref.get("htx_size", {}) + for t in _get("https://api.hbdm.com/linear-swap-ex/market/detail/batch_merged?business_type=swap")["ticks"]: + code = t.get("contract_code", "") + if not code.endswith("-USDT") or not t.get("bid") or not t.get("ask"): + continue + size = sizes.get(code) + out.append(_quote("HTX", code, code[:-5], t["bid"][0], t["ask"][0], + None if size is None else _f(t["bid"][1]) * size, + None if size is None else _f(t["ask"][1]) * size, funding.get(code), + self.ref.get("htx_interval", {}).get(code, 8), t.get("trade_turnover"))) + return [q for q in out if q] + + def gate(self) -> list[Quote]: + out = [] + for t in _get("https://api.gateio.ws/api/v4/futures/usdt/tickers"): + s = t["contract"] + if s.endswith("_USDT"): + mult = _f(t.get("quanto_multiplier"), 0) or None + out.append(_quote("Gate", s, s[:-5], t.get("highest_bid"), t.get("lowest_ask"), + None if mult is None else _f(t.get("highest_size")) * mult, + None if mult is None else _f(t.get("lowest_size")) * mult, t.get("funding_rate"), + self.ref.get("gate_interval", {}).get(s, 8), t.get("volume_24h_quote"))) + return [q for q in out if q] + + +def norm_chain(name: str) -> str: + """Rough common name of a network across exchanges (ERC20 → ETH, BEP20 → BSC, TRC20 → TRX …).""" + n = (name or "").upper().replace("-", "").replace("_", "").replace(" ", "") + for key, value in (("ERC20", "ETH"), ("ETHEREUM", "ETH"), ("BEP20", "BSC"), ("BNBSMARTCHAIN", "BSC"), + ("BSC", "BSC"), ("TRC20", "TRX"), ("TRON", "TRX"), ("SOLANA", "SOL"), ("SPL", "SOL"), + ("ARBITRUM", "ARB"), ("ARBONE", "ARB"), ("OPTIMISM", "OP"), ("POLYGON", "MATIC"), + ("MATIC", "MATIC"), ("BASE", "BASE"), ("TON", "TON"), ("AVAXC", "AVAX")): + if n.startswith(key) or n == key: + return value + return n + + +class SpotFetchers: + """USDT spot pairs of the five exchanges; wallet status (deposit / withdraw per network) where public.""" + + def __init__(self) -> None: + self.volume: dict[str, dict[str, float]] = {} + self.volume_time = 0.0 + self.wallet: dict[str, dict[str, dict]] = {} # exchange → coin → {"chains": {net: {...}}, ...} + self.wallet_time = 0.0 + + def refresh_volume(self) -> None: + if time.time() - self.volume_time < 60 and self.volume: + return + vol = {} + try: + vol["MEXC"] = {t["symbol"]: _f(t.get("quoteVolume")) for t in _get("https://api.mexc.com/api/v3/ticker/24hr")} + except Exception: + pass + self.volume, self.volume_time = vol, time.time() + + def refresh_wallet(self) -> None: + """HTX and Gate publish deposit/withdraw status per network (HTX also the withdrawal fee); hourly.""" + if time.time() - self.wallet_time < 3600 and self.wallet: + return + wallet: dict[str, dict[str, dict]] = {"HTX": {}, "Gate": {}} + try: + for c in _get("https://api.huobi.pro/v2/reference/currencies")["data"]: + chains = {} + for ch in c.get("chains", []): + net = norm_chain(ch.get("baseChainProtocol") or ch.get("baseChain") or ch.get("displayName") or "") + chains[net] = {"deposit": ch.get("depositStatus") == "allowed", + "withdraw": ch.get("withdrawStatus") == "allowed", + "fee": _f(ch.get("transactFeeWithdraw"), None) if ch.get("transactFeeWithdraw") + not in (None, "") else None, + "addr": (ch.get("contractAddress") or "").lower(), "name": ch.get("displayName")} + wallet["HTX"][c["currency"].upper()] = {"chains": chains} + except Exception: + pass + try: + for c in _get("https://api.gateio.ws/api/v4/spot/currencies"): + chains = {} + for ch in c.get("chains") or []: + chains[norm_chain(ch.get("name", ""))] = { + "deposit": not ch.get("deposit_disabled"), "withdraw": not ch.get("withdraw_disabled"), + "fee": None, "addr": (ch.get("addr") or "").lower(), "name": ch.get("name")} + coin = c["currency"].upper() + if coin not in wallet["Gate"] or not c.get("delisted"): + wallet["Gate"][coin] = {"chains": chains, "delisted": bool(c.get("delisted"))} + except Exception: + pass + self.wallet, self.wallet_time = wallet, time.time() + + def bybit(self) -> list[Quote]: + out = [] + for t in _get("https://api.bybit.com/v5/market/tickers?category=spot")["result"]["list"]: + s = t["symbol"] + if s.endswith("USDT"): + out.append(_quote("Bybit", s, s[:-4], t.get("bid1Price"), t.get("ask1Price"), t.get("bid1Size"), + t.get("ask1Size"), None, 8, t.get("turnover24h"), split=False)) + return [q for q in out if q] + + def binance(self) -> list[Quote]: + vol = self.volume.get("Binance", {}) + out = [] + for t in _get("https://api.binance.com/api/v3/ticker/bookTicker"): + s = t["symbol"] + if s.endswith("USDT"): + out.append(_quote("Binance", s, s[:-4], t.get("bidPrice"), t.get("askPrice"), t.get("bidQty"), + t.get("askQty"), None, 8, vol.get(s), split=False)) + return [q for q in out if q] + + def mexc(self) -> list[Quote]: + vol = self.volume.get("MEXC", {}) + out = [] + for t in _get("https://api.mexc.com/api/v3/ticker/bookTicker"): + s = t["symbol"] + if s.endswith("USDT"): + out.append(_quote("MEXC", s, s[:-4], t.get("bidPrice"), t.get("askPrice"), t.get("bidQty"), + t.get("askQty"), None, 8, vol.get(s), split=False)) + return [q for q in out if q] + + def htx(self) -> list[Quote]: + out = [] + for t in _get("https://api.huobi.pro/market/tickers")["data"]: + s = t["symbol"] + if s.endswith("usdt"): + out.append(_quote("HTX", s, s[:-4], t.get("bid"), t.get("ask"), t.get("bidSize"), t.get("askSize"), + None, 8, t.get("vol"), split=False)) + return [q for q in out if q] + + def gate(self) -> list[Quote]: + out = [] + for t in _get("https://api.gateio.ws/api/v4/spot/tickers"): + s = t["currency_pair"] + if s.endswith("_USDT"): + out.append(_quote("Gate", s, s[:-5], t.get("highest_bid"), t.get("lowest_ask"), None, None, None, 8, + t.get("quote_volume"), split=False)) + return [q for q in out if q] + + +def spot_url(exchange: str, symbol: str, base: str) -> str: + return {"Bybit": f"https://www.bybit.com/trade/spot/{base}/USDT", + "Binance": f"https://www.binance.com/en/trade/{base}_USDT?type=spot", + "MEXC": f"https://www.mexc.com/exchange/{base}_USDT", + "HTX": f"https://www.htx.com/trade/{base.lower()}_usdt", + "Gate": f"https://www.gate.com/trade/{base}_USDT"}.get(exchange, "") + + +def transfer_info(wallet: dict, base: str, src: str, dst: str, price: float) -> dict: + """What is known about moving `base` from `src` (withdraw) to `dst` (deposit): status, common networks, + the cheapest known withdrawal fee in $, and a contract-address mismatch (= different tokens).""" + a = wallet.get(src, {}).get(base) + b = wallet.get(dst, {}).get(base) + info = {"withdraw": None, "deposit": None, "networks": [], "fee_usd": None, "fee_net": None, + "different_token": False} + if a: + info["withdraw"] = any(c["withdraw"] for c in a["chains"].values()) if a["chains"] else None + if b: + info["deposit"] = any(c["deposit"] for c in b["chains"].values()) if b["chains"] else None + if b.get("delisted"): + info["deposit"] = False + if a and b: + common = [n for n in a["chains"] if n in b["chains"]] + usable = [n for n in common if a["chains"][n]["withdraw"] and b["chains"][n]["deposit"]] + info["networks"] = usable + if common and not usable: + info["withdraw"] = info["withdraw"] and False + for n in common: + x, y = a["chains"][n]["addr"], b["chains"][n]["addr"] + if x and y and x != y: + info["different_token"] = True + elif a: + info["networks"] = [n for n, c in a["chains"].items() if c["withdraw"]] + elif b: + info["networks"] = [n for n, c in b["chains"].items() if c["deposit"]] + if a: + # a fee above 500 $ is not a real withdrawal fee (another token on that network, or a unit mix-up) + fees = [(c["fee"] * price, n) for n, c in a["chains"].items() + if c["fee"] is not None and c["withdraw"] and (not info["networks"] or n in info["networks"]) + and c["fee"] * price < 500] + if fees: + info["fee_usd"], info["fee_net"] = min(fees) + return info + + +def exchange_url(exchange: str, symbol: str) -> str: + return {"Bybit": f"https://www.bybit.com/trade/usdt/{symbol}", + "Binance": f"https://www.binance.com/en/futures/{symbol}", + "MEXC": f"https://futures.mexc.com/exchange/{symbol}", + "HTX": f"https://www.htx.com/futures/exchange/{symbol.lower()}", + "Gate": f"https://www.gate.com/futures/USDT/{symbol}"}.get(exchange, "") + + +def funding_8h(q: Quote) -> float | None: + """Funding rate in % per 8 hours.""" + return None if q.funding is None else q.funding * 100 * 8 / max(q.interval_h, 0.1) + + +def best_pairs(quotes: list[Quote], usual: dict, taker: dict | None = None, market: str = "futures", + wallet: dict | None = None) -> list[dict]: + """Best buy/sell pair for every coin listed on two or more exchanges. + + futures: the spread is captured by opening and later closing both legs → fees ×2 (round trip); + spot: buy on one exchange, move the coin, sell on the other → fees of the two trades ×1, plus the transfer.""" + spot = market == "spot" + taker = taker or (SPOT_TAKER if spot else TAKER) + url = (lambda q: spot_url(q.exchange, q.symbol, q.base)) if spot else (lambda q: exchange_url(q.exchange, q.symbol)) + by_base: dict[str, list[Quote]] = {} + for q in quotes: + if spot and LEVERAGED.search(q.base) and len(q.base) > 3: + continue + by_base.setdefault(q.base, []).append(q) + rows = [] + for base, qs in by_base.items(): + if len({q.exchange for q in qs}) < 2: + continue + best = None + for a in qs: # buy at a.ask + for b in qs: # sell at b.bid + if a.exchange == b.exchange: + continue + gross = (b.bid / a.ask - 1) * 100 + if best is None or gross > best[0]: + best = (gross, a, b) + gross, a, b = best + entry = taker.get(a.exchange, 0.1) + taker.get(b.exchange, 0.1) + cost = entry if spot else 2 * entry + key = f"{base}|{a.exchange}|{b.exchange}" + u = usual.get(key) + depth = None if a.ask_usd is None or b.bid_usd is None else min(a.ask_usd, b.bid_usd) + fa, fb = funding_8h(a), funding_8h(b) + carry = None if fa is None or fb is None else fb - fa # short receives fb, long pays fa + transfer = transfer_info(wallet or {}, base, a.exchange, b.exchange, a.ask) if spot else None + rows.append({ + "coin": base, "key": key, "market": market, "buy": a.exchange, "buy_symbol": a.symbol, + "buy_price": a.ask, "sell": b.exchange, "sell_symbol": b.symbol, "sell_price": b.bid, "gross": gross, + "entry_cost": entry, "round_cost": cost, "usual": u, + "expected": None if u is None else gross - max(u, 0.0) - cost, + "net_now": gross - cost, "funding_buy": fa, "funding_sell": fb, "carry_8h": carry, + "depth_usd": depth, "volume_usd": min(a.volume_usd, b.volume_usd), + "exchanges": sorted({q.exchange for q in qs}), + "prices": {q.exchange: {"bid": q.bid, "ask": q.ask, "symbol": q.symbol, "funding_8h": funding_8h(q), + "funding": q.funding, "interval_h": q.interval_h, "mult": q.mult, + "bid_usd": q.bid_usd, "ask_usd": q.ask_usd, "url": url(q)} for q in qs}, + "buy_url": url(a), "sell_url": url(b), "transfer": transfer, + "suspect": gross > DIFFERENT_COIN_PCT or bool(transfer and transfer["different_token"]), + }) + rows.sort(key=lambda r: -r["gross"]) + return rows + + +PAUSED_FILE = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", Path(__file__).resolve().parent / "web_sim_data")) \\ + / "arb_paused.json" + + +def load_paused() -> dict: + try: + data = json.loads(PAUSED_FILE.read_text(encoding="utf-8")) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +class ArbScanner: + """Background loop: fetch all five exchanges every CYCLE_S seconds, keep the latest rows and the usual spreads.""" + + def __init__(self, market: str = "futures") -> None: + self.market = market + self.fetchers = SpotFetchers() if market == "spot" else Fetchers() + self.lock = threading.Lock() + self.rows: list[dict] = [] + self.usual: dict[str, float] = {} + # per pair (coin|buy|sell): minute → lowest spread seen in that minute (for «does it survive a transfer»), + # and since when it has been above the round-trip costs without a break + self.history: dict[str, dict[int, float]] = {} + self.profitable_since: dict[str, float] = {} + self.status: dict[str, str] = {e: "жду" for e in EXCHANGES} + self.counts: dict[str, int] = {} + self.updated = 0.0 + self.cycle_ms = 0 + self.thread: threading.Thread | None = None + self.paused = load_paused().get(market, False) # «Стоп» on the page: no requests to the exchanges + + def set_paused(self, paused: bool) -> None: + self.paused = paused + state = load_paused() + state[self.market] = paused + try: + PAUSED_FILE.parent.mkdir(exist_ok=True) + PAUSED_FILE.write_text(json.dumps(state), encoding="utf-8") + except OSError: + pass + + def ensure_running(self) -> None: + if self.thread is None: + self.thread = threading.Thread(target=self._loop, daemon=True) + self.thread.start() + + def _loop(self) -> None: + while True: + if self.paused: + time.sleep(0.5) + continue + start = time.time() + try: + self.scan_once() + except Exception: + pass + time.sleep(max(1.0, CYCLE_S - (time.time() - start))) + + def scan_once(self) -> None: + start = time.time() + for refresh in ("refresh_reference", "refresh_volume", "refresh_wallet"): + if hasattr(self.fetchers, refresh): + try: + getattr(self.fetchers, refresh)() + except Exception: + pass + calls = {"Bybit": self.fetchers.bybit, "MEXC": self.fetchers.mexc, + "HTX": self.fetchers.htx, "Gate": self.fetchers.gate} + quotes, status, counts = [], {}, {} + + def one(name): + try: + qs = calls[name]() + return name, qs, "ok" + except Exception as exc: + return name, [], f"ошибка: {str(exc)[:80]}" + + with ThreadPoolExecutor(max_workers=len(EXCHANGES)) as pool: + for name, qs, st in pool.map(one, EXCHANGES): + quotes += qs + status[name], counts[name] = st, len(qs) + rows = best_pairs(quotes, self.usual, market=self.market, wallet=getattr(self.fetchers, "wallet", None)) + alpha = min(1.0, CYCLE_S / USUAL_WINDOW_S) + now = time.time() + minute = int(now // 60) + for r in rows: # the usual spread of the chosen pair (updated after use) + prev = self.usual.get(r["key"]) + self.usual[r["key"]] = r["gross"] if prev is None else prev + alpha * (r["gross"] - prev) + self.record(r["key"], r["gross"], r["net_now"] > 0, now, minute) + self._prune(minute) + with self.lock: + self.rows, self.status, self.counts = rows, status, counts + self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000) + + HISTORY_MIN = 180 + + def record(self, key: str, gross: float, profitable: bool, now: float, minute: int) -> None: + h = self.history.setdefault(key, {}) + h[minute] = min(h.get(minute, gross), gross) + if profitable: + self.profitable_since.setdefault(key, now) + else: + self.profitable_since.pop(key, None) + + def _prune(self, minute: int) -> None: + if minute % 10: + return + for key in list(self.history): + h = self.history[key] + for m in [m for m in h if m < minute - self.HISTORY_MIN]: + del h[m] + if not h: + del self.history[key] + + def window_min(self, key: str, minutes: float, now: float) -> tuple[float | None, float]: + """(lowest spread over the last `minutes`, minutes of history actually available for this pair).""" + h = self.history.get(key, {}) + current = int(now // 60) + span = int(max(1, round(minutes))) + recent = [v for m, v in h.items() if m > current - span] + have = len([m for m in h if m > current - self.HISTORY_MIN]) + return (min(recent) if recent else None), float(have) + + def view(self, transfer_min: float | None = None) -> dict: + self.ensure_running() + with self.lock: + now = time.time() + rows = [] + for r in self.rows: + r = dict(r) + since = self.profitable_since.get(r["key"]) + r["held_min"] = None if since is None else (now - since) / 60 + if transfer_min: + low, have = self.window_min(r["key"], transfer_min, now) + r["window_low"] = low + r["history_min"] = have + rows.append(r) + return {"rows": rows, "status": self.status, "counts": self.counts, "updated": self.updated, + "cycle_ms": self.cycle_ms, "taker": SPOT_TAKER if self.market == "spot" else TAKER, + "market": self.market, "cycle_s": CYCLE_S, "paused": self.paused, + "usual_minutes": USUAL_WINDOW_S / 60, "transfer_min": transfer_min} diff --git a/LinuxServer/basis.py b/LinuxServer/basis.py new file mode 100644 index 0000000..2639765 --- /dev/null +++ b/LinuxServer/basis.py @@ -0,0 +1,1335 @@ +"""Spot–futures basis trades on one exchange (paper): buy the coin on spot while it is cheaper than the perpetual, +short the same amount of coins on the perpetual, close both legs when the gap has closed (≈ 0). + +Coins: new listings, the exchange's innovation zone and memecoins that have both a USDT spot pair and a USDT +perpetual. Only Bybit is implemented; other exchanges plug in as another Venue. + + entry gap = perp bid / spot ask − 1 (buy spot at the ask, short the perp at the bid) + exit gap = perp ask / spot bid − 1 (sell spot at the bid, buy the perp back at the ask) + +Result of one trade = spot leg + perp leg − 4 taker fees + funding the short received while it was open. +""" + +from __future__ import annotations + +import json +import os +import queue +import threading +import time +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from dataclasses import asdict, dataclass, field, fields +from pathlib import Path + +from arb import _f, _get, split_base + +ROOT = Path(__file__).resolve().parent +DATA_DIR = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT / "web_sim_data")).resolve() +POLL_S = 1.0 +INSTRUMENTS_S = 3600.0 +MEMES_S = 6 * 3600.0 +KEEP_TRADES = 500 + +# used when CoinGecko's meme-token list cannot be fetched (it rate-limits often) +MEME_FALLBACK = set("""DOGE SHIB PEPE FLOKI BONK WIF BOME MEW POPCAT BRETT MOG TURBO NEIRO NEIROCTO PNUT GOAT MOODENG ACT +CHILLGUY FARTCOIN TRUMP MELANIA PENGU SPX GIGA PONKE MYRO SLERF BABYDOGE DOGS NOT CAT MEME BAN AI16Z ZEREBRO +LADYS WEN SATS ORDI RATS COQ TOSHI MICHI BILLY DEGEN HIPPO SUNDOG HMSTR CATI MOTHER DADDY RETARDIO SIGMA LUCE +FWOG SC DOG BOOK BOOKOFMEME KEKIUS VINE TST BROCCOLI MUBARAK JELLYJELLY HOUSE USELESS PUMP TROLL ANSEM CLAUDIA +MANYU BUTTCOIN ELON KISHU BONE LEASH SNEK GME AIDOGE PEOPLE WOJAK HPOS10I APU MAGA LOBO QUBIC SHIB2""".split()) + + +@dataclass +class Pair: + """One coin with both a spot pair and a perpetual on the venue; prices per coin.""" + base: str + spot_symbol: str + fut_symbol: str + mult: float + spot_bid: float + spot_ask: float + fut_bid: float + fut_ask: float + spot_bid_usd: float | None # $ at the best price (None: the exchange does not report it) + spot_ask_usd: float | None + fut_bid_usd: float | None + fut_ask_usd: float | None + funding: float # per interval, fraction (0.0001 = 0.01%) + next_funding: float # unix seconds + interval_h: float + spot_turnover: float + fut_turnover: float + age_days: float | None + innovation: bool + meme: bool + + @property + def entry_gap(self) -> float: + return (self.fut_bid / self.spot_ask - 1) * 100 + + @property + def exit_gap(self) -> float: + return (self.fut_ask / self.spot_bid - 1) * 100 + + +class BybitVenue: + name = "Bybit" + spot_fee = 0.1 + fut_fee = 0.055 + innovation_fee = 0.11 # perps of the Innovation Zone: their own taker rate (bybit.com/fee, regular user) + + def __init__(self) -> None: + self.instruments: dict[str, dict] = {} # base → {fut_symbol, spot_symbol, mult, launch, innovation} + self.instruments_time = 0.0 + + @staticmethod + def spot_url(p: Pair) -> str: + return f"https://www.bybit.com/trade/spot/{p.base}/USDT" + + @staticmethod + def fut_url(p: Pair) -> str: + return f"https://www.bybit.com/trade/usdt/{p.fut_symbol}" + + def refresh_instruments(self) -> None: + if self.instruments and time.time() - self.instruments_time < INSTRUMENTS_S: + return + spot = {s["symbol"] for s in _get("https://api.bybit.com/v5/market/instruments-info?category=spot")["result"] + ["list"] if s.get("status") == "Trading" and s.get("quoteCoin") == "USDT" + and s.get("symbolType") in ("", "adventure")} + out = {} + cursor = "" + while True: + res = _get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000" + + (f"&cursor={cursor}" if cursor else ""))["result"] + for x in res["list"]: + # stock / ETF / commodity / forex perps are not the same thing as a spot coin + if (x.get("status") != "Trading" or x.get("contractType") != "LinearPerpetual" + or x.get("quoteCoin") != "USDT" or x.get("symbolType") not in ("", "innovation")): + continue + base, mult = split_base(x["baseCoin"]) + spot_symbol = f"{base}USDT" + if spot_symbol not in spot: + continue + out[base] = {"fut_symbol": x["symbol"], "spot_symbol": spot_symbol, "mult": mult, + "launch": int(x.get("launchTime") or 0) / 1000 or None, + "innovation": x.get("symbolType") == "innovation", + "interval_h": int(x.get("fundingInterval") or 480) / 60} + cursor = res.get("nextPageCursor") or "" + if not cursor or not res["list"]: + break + self.instruments, self.instruments_time = out, time.time() + + def pairs(self, memes: set[str]) -> list[Pair]: + self.refresh_instruments() + spot = {t["symbol"]: t for t in _get("https://api.bybit.com/v5/market/tickers?category=spot")["result"]["list"]} + fut = {t["symbol"]: t for t in _get("https://api.bybit.com/v5/market/tickers?category=linear")["result"]["list"]} + now = time.time() + out = [] + for base, ins in self.instruments.items(): + s, f = spot.get(ins["spot_symbol"]), fut.get(ins["fut_symbol"]) + if not s or not f: + continue + m = ins["mult"] + sb, sa, fb, fa = _f(s.get("bid1Price")), _f(s.get("ask1Price")), _f(f.get("bid1Price")), _f(f.get("ask1Price")) + if min(sb, sa, fb, fa) <= 0: + continue + out.append(Pair( + base, ins["spot_symbol"], ins["fut_symbol"], m, sb, sa, fb / m, fa / m, + sb * _f(s.get("bid1Size")), sa * _f(s.get("ask1Size")), fb * _f(f.get("bid1Size")), + fa * _f(f.get("ask1Size")), _f(f.get("fundingRate")), _f(f.get("nextFundingTime")) / 1000, + _f(f.get("fundingIntervalHour"), ins["interval_h"]) or ins["interval_h"], + _f(s.get("turnover24h")), _f(f.get("turnover24h")), + None if not ins["launch"] else (now - ins["launch"]) / 86400, ins["innovation"], base in memes)) + return out + + +def _listing_binance() -> dict[str, dict]: + out = {} + for s in _get("https://fapi.binance.com/fapi/v1/exchangeInfo")["symbols"]: + # TradFi perps (stocks, gold…) are not the spot coin of the same name + if (s.get("contractType") != "PERPETUAL" or s.get("status") != "TRADING" or s.get("quoteAsset") != "USDT" + or s.get("underlyingType") != "COIN" or "TradFi" in (s.get("underlyingSubType") or [])): + continue + out[s["symbol"]] = {"launch": _f(s.get("onboardDate")) / 1000 or None, + "meme": "Meme" in (s.get("underlyingSubType") or []), "innovation": False} + return out + + +def _listing_mexc() -> dict[str, dict]: + out = {} + for c in _get("https://contract.mexc.com/api/v1/contract/detail")["data"]: + if c.get("quoteCoin") != "USDT" or c.get("state") not in (0, None) or c.get("futureType") not in (1, None): + continue + zones = " ".join(c.get("conceptPlate") or []).lower() + out[c["symbol"]] = {"launch": _f(c.get("openingTime") or c.get("createTime")) / 1000 or None, + "meme": "meme" in zones, "innovation": bool(c.get("isNew"))} + return out + + +def _listing_htx() -> dict[str, dict]: + out = {} + for c in _get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]: + if c.get("contract_status") != 1 or not c["contract_code"].endswith("-USDT"): + continue + try: + launch = time.mktime(time.strptime(c.get("create_date", ""), "%Y%m%d")) + except ValueError: + launch = None + labels = [x.lower() for x in c.get("labels") or []] + out[c["contract_code"]] = {"launch": launch, "meme": "meme" in labels, "innovation": "new" in labels} + return out + + +def _listing_gate() -> dict[str, dict]: + out = {} + for c in _get("https://api.gateio.ws/api/v4/futures/usdt/contracts"): + if c.get("in_delisting") or (c.get("status") not in (None, "trading")): + continue + out[c["name"]] = {"launch": _f(c.get("launch_time") or c.get("create_time")) or None, "meme": False, + "innovation": False} + return out + + +class ArbVenue: + """Binance, MEXC, HTX, Gate: prices from the arbitrage scanner's fetchers (one request per market), listing + date / meme tag from the exchange's contract list (hourly). Funding is settled every `interval_h` hours on the + UTC grid. Where an exchange does not report the size at the best price (MEXC futures, Gate spot) the depth is + unknown (None) and not checked.""" + + innovation_fee = 0.0 # their «new» label is not a fee group + + SETUP = {"binance": ("Binance", 0.1, 0.05, _listing_binance), + "mexc": ("MEXC", 0.05, 0.02, _listing_mexc), + "htx": ("HTX", 0.2, 0.05, _listing_htx), + "gate": ("Gate", 0.1, 0.05, _listing_gate)} + + def __init__(self, key: str) -> None: + import arb + self.arb = arb + self.key = key + self.name, self.spot_fee, self.fut_fee, self._listing = self.SETUP[key] + self.fut, self.spot = arb.Fetchers(), arb.SpotFetchers() + self.listing: dict[str, dict] = {} + self.listing_time = 0.0 + + def spot_url(self, p: Pair) -> str: + return self.arb.spot_url(self.name, p.spot_symbol, p.base) + + def fut_url(self, p: Pair) -> str: + return self.arb.exchange_url(self.name, p.fut_symbol) + + def pairs(self, memes: set[str]) -> list[Pair]: + if not self.listing or time.time() - self.listing_time > INSTRUMENTS_S: + try: + self.listing, self.listing_time = self._listing(), time.time() + self.fut.refresh_reference() # funding intervals, contract sizes + except Exception: + if not self.listing: + raise + if self.key in ("binance", "mexc"): + self.spot.refresh_volume() + # both markets at once: a slow exchange (Gate) then costs one wait, not two + with ThreadPoolExecutor(max_workers=2) as pool: + fut_job = pool.submit(getattr(self.fut, self.key)) + spot_job = pool.submit(getattr(self.spot, self.key)) + futs = fut_job.result() + spots = {q.base: q for q in spot_job.result() if q.mult == 1} + now = time.time() + out = [] + for f in futs: + info = self.listing.get(f.symbol) + s = spots.get(f.base) + if info is None or s is None: + continue + interval = f.interval_h or 8.0 + step = interval * 3600 + out.append(Pair( + f.base, s.symbol, f.symbol, f.mult, s.bid, s.ask, f.bid, f.ask, s.bid_usd, s.ask_usd, f.bid_usd, + f.ask_usd, f.funding or 0.0, (now // step + 1) * step, interval, s.volume_usd, f.volume_usd, + None if not info["launch"] else (now - info["launch"]) / 86400, info["innovation"], + info["meme"] or f.base in memes)) + return out + + +VENUES = {"bybit": BybitVenue, "binance": lambda: ArbVenue("binance"), "mexc": lambda: ArbVenue("mexc"), + "htx": lambda: ArbVenue("htx"), "gate": lambda: ArbVenue("gate")} +PLANNED: list[str] = [] + + +@dataclass +class BasisSettings: + running: bool = False # open new trades (prices and exits go on when stopped) + amount: float = 100.0 # $ per trade: spent on spot, the same coins shorted on the perp + min_gap_pct: float = 0.6 # open when perp is at least this much above spot (after the spread) + max_gap_pct: float = 10.0 # …and not more (bigger = broken price, delisting, different coin) + exit_gap_pct: float = 0.05 # close both legs when the gap is back to this or below + stop_gap_pct: float = 0.0 # close at a loss when the gap widens to this (0 = off) + max_hold_hours: float = 0.0 # close after this long whatever the gap (0 = off) + max_positions: int = 10 + cooldown_s: float = 60.0 # no new entry on the same coin this soon after a close + new_days: float = 90.0 # «new coin»: perpetual listed within this many days + use_new: bool = True + use_innovation: bool = True + use_memes: bool = True + all_coins: bool = False # ignore the three above and take every coin with spot + perp + min_turnover: float = 200000.0 # 24h turnover of the thinner market, $ + min_depth: float = 0.0 # $ at the best prices on both legs (0 = only the trade amount itself) + spot_fee: float = 0.1 + fut_fee: float = 0.055 + fut_fee_innovation: float = 0.0 # perp taker rate of the Innovation Zone coins (Bybit 0.11); 0 = as «fut_fee» + real: bool = False # new trades as real orders with the exchange's API keys + auto_transfer: bool = True # move USDT between the spot and futures accounts when one of them is short + max_real_positions: int = 1 # real positions held at the same time (entries still go one after another) + entry_limit: bool = True # real entry: LIMIT short at the signal's perp bid first, then the spot hedge + limit_hold_s: float = 10.0 # …kept this long, then removed (nothing bought if it did not fill) + exchange_tp: bool = False # (off: the program watches the prices itself; kept for old settings files) + + +@dataclass +class Position: + uid: int + base: str + opened: float + qty: float # coins bought on spot = coins shorted + spot_entry: float + fut_entry: float + entry_gap: float + fees: float + next_funding: float + funding: float = 0.0 # $ received by the short (negative = paid) + # real positions: actual coins of each leg (the perp is rounded down to its lot), the perp symbol, and the + # close in progress (perp bought back first, then the spot sold; a failed spot sale is retried) + real: bool = False + spot_qty: float = 0.0 + fut_symbol: str = "" + closing: str = "" # "" / "fut_done" (perp bought back, spot still to sell) + fut_exit: float = 0.0 + exit_fees: float = 0.0 + retry_at: float = 0.0 + error: str = "" + sold_coins: float = 0.0 # spot sold so far by the close (from the exchange's fills) + sold_value: float = 0.0 + sold_fees: float = 0.0 + short_pending: bool = False # the spot leg is held but the perp short is not open yet (adopted coins…) + tp_order: str = "" # TP on the exchange (reduce-only limit buy of the short), "" = none + tp_price: float = 0.0 + exact: bool = True # all prices and fees are the exchange's own figures + innovation: bool = False # an Innovation Zone perp: its own fee rate + + +@dataclass +class Trade: + uid: int + base: str + opened: float + closed: float + qty: float + spot_entry: float + spot_exit: float + fut_entry: float + fut_exit: float + entry_gap: float + exit_gap: float + spot_pnl: float + fut_pnl: float + fees: float + funding: float + net: float + reason: str + amount: float = 0.0 + real: bool = False # done with real orders (figures from the exchange's fills) + exact: bool = True + + +def fut_rate(s: BasisSettings, innovation: bool) -> float: + """Perp taker rate, %: the Innovation Zone coins of Bybit have their own (higher) rate.""" + return s.fut_fee_innovation if innovation and s.fut_fee_innovation > 0 else s.fut_fee + + +def entry_fees(qty: float, spot_ask: float, fut_bid: float, s: BasisSettings, innovation: bool = False) -> float: + return qty * spot_ask * s.spot_fee / 100 + qty * fut_bid * fut_rate(s, innovation) / 100 + + +def close_result(pos: Position, spot_bid: float, fut_ask: float, s: BasisSettings) -> tuple[float, float, float, float]: + """(spot leg $, perp leg $, all fees $, net $) of closing `pos` at these prices.""" + spot_qty = pos.spot_qty or pos.qty # real: the spot leg can hold a little more than the perp's lot + if pos.closing == "fut_done": # real close half done: the perp is already bought back + fut_ask = pos.fut_exit + spot_pnl = spot_qty * (spot_bid - pos.spot_entry) + fut_pnl = pos.qty * (pos.fut_entry - fut_ask) + fees = pos.fees + spot_qty * spot_bid * s.spot_fee / 100 + pos.qty * fut_ask * fut_rate(s, pos.innovation) / 100 + return spot_pnl, fut_pnl, fees, spot_pnl + fut_pnl - fees + pos.funding + + +ENGINES: list = [] # every running spot–futures engine (each exchange and «between exchanges») +# A gap this large is not a premium but two different instruments under one ticker (MEXC EWT: spot 0.34 $, perp +# 104.84 $): never traded, whatever «Макс. расхождение» says. +HARD_MAX_GAP_PCT = 20.0 +# Right before an order: the perp leg may not be worth more than the trade amount × this (same coins on both legs). +MAX_LEG_RATIO = 1.25 + + +def busy_elsewhere(base: str, me) -> str: + """Name of another spot–futures engine where this coin is already in a trade (or being entered), "" if none: + one coin is never traded twice at the same time, whichever exchange or mode.""" + for e in list(ENGINES): + if e is me: + continue + if any(p.base == base for p in list(e.positions)) or base in getattr(e, "opening", set()): + return getattr(getattr(e, "venue", None), "name", None) or "Между биржами" + return "" + + +def live_client(exchange: str): + import live + return live.client(exchange) + + +def entry_depth(p: Pair) -> float | None: + """$ available at the entry prices on both legs (spot ask, perp bid); None when either is not reported.""" + known = [v for v in (p.spot_ask_usd, p.fut_bid_usd) if v is not None] + return min(known) if len(known) == 2 else None + + +def depth_ok(p: Pair, s: BasisSettings) -> bool: + need = max(s.amount, s.min_depth) + return all(v is None or v >= need for v in (p.spot_ask_usd, p.fut_bid_usd)) + + +def in_universe(p: Pair, s: BasisSettings) -> bool: + if s.all_coins: + return True + return ((s.use_new and p.age_days is not None and p.age_days <= s.new_days) + or (s.use_innovation and p.innovation) or (s.use_memes and p.meme)) + + +class BasisEngine: + def __init__(self, venue_key: str = "bybit", data_dir: Path = DATA_DIR, start: bool = True) -> None: + self.key = venue_key + self.venue = VENUES[venue_key]() + self.file = data_dir / f"basis_{venue_key}.json" + self.lock = threading.RLock() + self.settings = BasisSettings(spot_fee=self.venue.spot_fee, fut_fee=self.venue.fut_fee, + fut_fee_innovation=self.venue.innovation_fee) + self.positions: list[Position] = [] + self.trades: list[Trade] = [] + self.next_uid = 1 + self.last_close: dict[str, float] = {} + self.pairs: dict[str, Pair] = {} + self.memes: set[str] = set(MEME_FALLBACK) + self.memes_source = "встроенный список" + self.status, self.updated, self.cycle_ms = "загружаю…", 0.0, 0 + self.message = "" + self.opening: set[str] = set() # coins with a real entry in progress + self.jobs: queue.Queue = queue.Queue() # real orders, sent one by one from a worker thread + self.client_for = live_client + self.busy: set[int] = set() # real positions whose close is being sent right now + self.real_block: dict[str, tuple[str, float]] = {} # coin → (why it cannot be traded for real, until) + self.real_pause_until, self.real_pause_reason = 0.0, "" # the whole exchange (e.g. balance too small) + self.pending: dict[str, dict] = {} # coin → real entry in progress (written BEFORE the spot is bought) + self.recover: set[str] = set() # pending entries found after a restart: adopt what was bought + self.adopting: set[str] = set() # coins being taken over from the spot balance right now + self.tp_checked: dict[int, float] = {} # position → when its TP on the exchange was last looked at + self.tp_tried: set[int] = set() # positions a TP was tried for in this run + self.fast_seen: dict[str, float] = {} # coin → when the fast watch last priced it + self.fast_ms = 0 # how long the last fast look took + self._load() + if start: + threading.Thread(target=self._loop, daemon=True).start() + threading.Thread(target=self._memes_loop, daemon=True).start() + threading.Thread(target=self._worker, daemon=True).start() + threading.Thread(target=self._fast_loop, daemon=True).start() + ENGINES.append(self) + + # --- persistence --------------------------------------------------------------------------- + def _load(self) -> None: + try: + d = json.loads(self.file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + known = {f.name for f in fields(BasisSettings)} + for k, v in (d.get("settings") or {}).items(): + if k in known: + setattr(self.settings, k, type(getattr(self.settings, k))(v)) + self.settings.exchange_tp = False # no TP orders on the exchange any more: the program closes by itself + self.settings.max_gap_pct = min(self.settings.max_gap_pct, HARD_MAX_GAP_PCT) + self.positions = [Position(**p) for p in d.get("positions", [])] + self.trades = [Trade(**t) for t in d.get("trades", [])] + self.next_uid = d.get("next_uid", 1) + # entries that were in progress when the program stopped: the coins may be on the spot account now + self.recover = set(d.get("pending") or {}) + + def save(self) -> None: + self.file.parent.mkdir(exist_ok=True) + data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions], + "trades": [asdict(t) for t in self.trades[-KEEP_TRADES:]], "next_uid": self.next_uid, + "pending": 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) + + def set_settings(self, values: dict) -> str: + with self.lock: + for f in fields(BasisSettings): + if f.name not in values: + continue + try: + v = values[f.name] + v = (v in (True, "true", "1", 1, "on")) if f.type in ("bool", bool) else type(getattr(self.settings, f.name))(float(v)) + except (TypeError, ValueError): + return f"неверное значение: {f.name}" + setattr(self.settings, f.name, v) + s = self.settings + if s.amount <= 0 or s.max_positions < 0: + return "сумма и число позиций должны быть больше 0" + if s.max_gap_pct > HARD_MAX_GAP_PCT: + s.max_gap_pct = HARD_MAX_GAP_PCT + self.save() + return (f"«Макс. расхождение» не может быть больше {HARD_MAX_GAP_PCT:g}%: такая разница — это разные " + f"инструменты под одним тикером, а не премия. Установлено {HARD_MAX_GAP_PCT:g}%, остальное сохранено") + if s.min_gap_pct <= s.exit_gap_pct: + return "разница для входа должна быть больше разницы для выхода" + if set(values) - {"running"}: + # new settings (a bigger amount, a topped-up account…): coins and the exchange are checked anew + self.real_block.clear() + self.real_pause_until, self.real_pause_reason = 0.0, "" + self.save() + return "" + + # --- data ---------------------------------------------------------------------------------- + def _memes_loop(self) -> None: + while True: + got: set[str] = set() + try: + for page in (1, 2, 3, 4): + req = urllib.request.Request( + "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=meme-token" + f"&per_page=250&page={page}", headers={"User-Agent": "Mozilla/5.0"}) + with urllib.request.urlopen(req, timeout=30) as resp: + items = json.loads(resp.read()) + got |= {x["symbol"].upper() for x in items} + if len(items) < 250: + break + time.sleep(8) + except Exception: + pass + if len(got) > 100: + self.memes, self.memes_source = got | MEME_FALLBACK, f"CoinGecko meme-token ({len(got)})" + time.sleep(MEMES_S) + else: + time.sleep(600) + + def _loop(self) -> None: + while True: + start = time.time() + try: + pairs = self.venue.pairs(self.memes) + with self.lock: + fresh_now = time.time() + new = {p.base: p for p in pairs} + for b, seen in self.fast_seen.items(): # the fast watch's prices are newer than this list + if b in new and b in self.pairs and fresh_now - seen < 2.0: + new[b] = self.pairs[b] + self.pairs = new + self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000) + self.status = "ok" + self.step(self.updated) + except Exception as exc: + self.status = f"нет данных: {exc}" + time.sleep(max(0.2, POLL_S - (time.time() - start))) + + # --- trading ------------------------------------------------------------------------------- + def candidates(self) -> list[Pair]: + s = self.settings + return [p for p in self.pairs.values() if in_universe(p, s) + and min(p.spot_turnover, p.fut_turnover) >= s.min_turnover] + + def step(self, now: float) -> None: + """Exits first (gap closed, stop, time), funding on the shorts, then new entries.""" + s = self.settings + changed = False + for base in list(self.recover): + # an entry cut off by a stop of the program: whatever spot it bought becomes a position again + if base in self.pairs and base not in self.opening: + self.opening.add(base) + self.recover.discard(base) + self.jobs.put(("adopt", base)) + changed = self._check_exits(now) + # real: one entry at a time (never two buys in parallel), and no more open real positions than allowed + real_busy = s.real and (self.opening or self.adopting or now < self.real_pause_until + or sum(pos.real for pos in self.positions) >= max(1, s.max_real_positions)) + if s.running and not real_busy: # real: the next trade only after the previous is confirmed closed + changed = self._entries(now) or changed + if changed: + self.save() + + def _check_exits(self, now: float) -> bool: + """Every open position against the latest prices: funding, then the exit rules. Called by the market cycle + AND by the fast watch of open positions (several times a second) — the program, not a TP on the exchange, + decides the close, whichever way the gap converges.""" + s = self.settings + changed = False + for pos in list(self.positions): + p = self.pairs.get(pos.base) + if p is None: + continue + if pos.real and pos.short_pending: + # spot held without its hedge: open the short (retried while the exchange refuses); no auto exit — + # the gap logic needs both legs; «×» sells the spot + if pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + self.jobs.put(("short", pos.uid)) + continue + while pos.next_funding and now >= pos.next_funding: + pos.funding += pos.qty * (p.fut_bid + p.fut_ask) / 2 * p.funding # short receives positive funding + pos.next_funding = p.next_funding if p.next_funding > pos.next_funding else pos.next_funding + p.interval_h * 3600 + changed = True + gap = p.exit_gap + reason = ("разница сошлась" if gap <= s.exit_gap_pct + else "стоп: разница расширилась" if s.stop_gap_pct > 0 and gap >= s.stop_gap_pct + else "время удержания" if s.max_hold_hours > 0 and now - pos.opened >= s.max_hold_hours * 3600 + else "") + if pos.real and pos.closing == "fut_done" and now >= pos.retry_at: + reason = reason or "продажа спота после выкупа шорта" + if reason: + if pos.real: + if pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + self.jobs.put(("close", pos.uid, reason)) + else: + self._close(pos, p, now, reason) + changed = True + elif pos.real and pos.tp_order and not pos.closing and pos.uid not in self.busy: + self.busy.add(pos.uid) # a TP left on the exchange by the older version: remove it + self.jobs.put(("untp", pos.uid)) + return changed + + def _entries(self, now: float) -> bool: + s = self.settings + changed = False + if True: + busy = {pos.base for pos in self.positions} | self.opening + for p in sorted(self.candidates(), key=lambda p: -p.entry_gap): + if len(self.positions) + len(self.opening) >= s.max_positions: + break + if p.base in busy or now - self.last_close.get(p.base, 0) < s.cooldown_s: + continue + if busy_elsewhere(p.base, self): + continue # the same coin is already in a trade on another exchange / mode + if not (s.min_gap_pct <= p.entry_gap <= min(s.max_gap_pct, HARD_MAX_GAP_PCT)): + continue + if not depth_ok(p, s): + continue + if self._too_small(p): + continue # paper too: only trades the exchange would accept on both legs + if s.real and self.real_block.get(p.base, ("", 0.0))[1] > now: + continue # known: cannot be traded for real (lot too big for the amount…) + if s.real: + self.opening.add(p.base) + self.jobs.put(("open", p, s.amount)) + break # one real trade at a time + qty = s.amount / p.spot_ask + inno = self._innovation(p) + self.positions.append(Position(self.next_uid, p.base, now, qty, p.spot_ask, p.fut_bid, p.entry_gap, + entry_fees(qty, p.spot_ask, p.fut_bid, s, inno), p.next_funding, + innovation=inno)) + self.next_uid += 1 + busy.add(p.base) + changed = True + return changed + + # --- fast watch of open positions ------------------------------------------------------------------------ + FAST_S = 0.25 # target pause between two looks at the open positions' prices + + def _fast_loop(self) -> None: + """While positions are open: their spot and perp best prices, several times a second (one symbol each, + kept-alive connections), and the exit rules on those fresh prices.""" + import dataclasses + import fastquote + pool = ThreadPoolExecutor(max_workers=8) + while True: + start = time.time() + with self.lock: + watch = {pos.base: self.pairs[pos.base] for pos in self.positions + if pos.base in self.pairs and not pos.short_pending} + if not watch: + time.sleep(0.5) + continue + ex = self.venue.name + jobs = {b: (pool.submit(fastquote.spot_top, ex, p.spot_symbol), pool.submit(fastquote.fut_top, ex, p.fut_symbol)) + for b, p in watch.items()} + fresh = {} + for b, (sj, fj) in jobs.items(): + try: + sb, sa, sbu, sau = sj.result() + fb, fa, fbu, fau = fj.result() + except Exception: + continue + p, m = watch[b], watch[b].mult + if min(sb, sa, fb, fa) <= 0: + continue + fresh[b] = dataclasses.replace(p, spot_bid=sb, spot_ask=sa, fut_bid=fb / m, fut_ask=fa / m, + spot_bid_usd=sbu, spot_ask_usd=sau, + fut_bid_usd=fbu if fbu is not None else p.fut_bid_usd, + fut_ask_usd=fau if fau is not None else p.fut_ask_usd) + if fresh: + now = time.time() + with self.lock: + self.pairs.update(fresh) + for b in fresh: + self.fast_seen[b] = now + self.fast_ms = int((now - start) * 1000) + if self._check_exits(now): + self.save() + time.sleep(max(0.05, self.FAST_S - (time.time() - start))) + + def _min_entry(self, p: Pair) -> dict | None: + """The smallest amount both the spot buy and the perp short of this coin accept (exchange rules).""" + import minorder + return minorder.RULES.min_entry(self.venue.name, p.base, p.spot_ask, self.venue.name, p.fut_symbol, p.fut_bid, + self.settings.spot_fee) + + def _too_small(self, p: Pair) -> str: + import minorder + return minorder.too_small(self.settings.amount, self._min_entry(p), self.venue.name, self.venue.name) + + def _innovation(self, p: Pair) -> bool: + """The coin's perp pays the Innovation Zone rate (Bybit only: other exchanges' «new» label is no fee group).""" + return bool(p.innovation and self.venue.innovation_fee) + + def _fut_rate(self, p: Pair | None) -> float: + return fut_rate(self.settings, bool(p) and self._innovation(p)) + + def _close(self, pos: Position, p: Pair, now: float, reason: str) -> Trade: + spot_pnl, fut_pnl, fees, net = close_result(pos, p.spot_bid, p.fut_ask, self.settings) + t = Trade(pos.uid, pos.base, pos.opened, now, pos.qty, pos.spot_entry, p.spot_bid, pos.fut_entry, p.fut_ask, + pos.entry_gap, p.exit_gap, spot_pnl, fut_pnl, fees, pos.funding, net, reason, + pos.qty * pos.spot_entry) + self.positions.remove(pos) + self.trades.append(t) + self.last_close[pos.base] = now + return t + + def close(self, uid: int | None) -> str: + with self.lock: + n = real = 0 + for pos in list(self.positions): + if uid is not None and pos.uid != uid: + continue + if pos.real: + if pos.uid not in self.busy: + self.busy.add(pos.uid) + pos.retry_at = 0.0 + self.jobs.put(("close", pos.uid, "вручную")) + real += 1 + continue + p = self.pairs.get(pos.base) + if p is None: + continue + self._close(pos, p, time.time(), "вручную") + n += 1 + self.save() + return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "") + + # --- real orders (worker thread; never under the engine lock while waiting for the exchange) ----------------- + def _journal(self, coin: str, action: str, ok: bool, text: str, **extra) -> None: + import real_mirror + real_mirror.journal("basis", self.key, coin, action, ok, text, **extra) + + def _worker(self) -> None: + while True: + kind, *args = self.jobs.get() + try: + if kind == "open": + self._real_open(*args) + elif kind == "close": + self._real_close(*args) + elif kind == "short": + self._real_short(*args) + elif kind == "watch": + self._watch_tp(*args) + elif kind == "untp": + self._remove_tp(*args) + elif kind == "tp": + pos = next((x for x in self.positions if x.uid == args[0]), None) + if pos is not None and not pos.tp_order: + self._place_tp(self.client_for(self.key), pos) + elif kind == "adopt": + msg = self.adopt(args[0]) + if "подхвачено" not in msg: + self._journal(args[0], "open", True, f"после перезапуска: незавершённый вход — {msg}") + except Exception as exc: # the worker must survive anything + self._journal(getattr(args[0], "base", "?") if args else "?", kind, False, f"сбой: {exc}") + if kind == "open" and args: + with self.lock: + self.opening.discard(args[0].base) + finally: + if kind in ("close", "short", "watch", "tp", "untp") and args: + with self.lock: + self.busy.discard(args[0]) + if kind == "open" and args and args[0].base in self.pending: + with self.lock: # the entry is finished (position, sold back or refused) + self.pending.pop(args[0].base, None) + self.save() + if kind == "adopt" and args: + with self.lock: + self.recover.discard(args[0]) + self.opening.discard(args[0]) + self.pending.pop(args[0], None) + self.save() + + SHORT_RETRY_S = 300.0 + + def _real_short(self, uid: int) -> None: + """Open the missing perp short for a held spot leg (the same coins, rounded down to the lot).""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + p = self.pairs.get(pos.base) if pos else None + if pos is None or not pos.short_pending or p is None: + return + fut = None + try: + c = self.client_for(self.key) + coins = c.fut_round(pos.fut_symbol, pos.spot_qty) + if coins <= 0: + raise live.LiveError(f"монет {pos.spot_qty:g} меньше минимального лота фьючерса") + if coins * p.fut_bid > pos.spot_qty * pos.spot_entry * MAX_LEG_RATIO: + raise live.LiveError(f"шорт стоил бы {coins * p.fut_bid:.2f} $ при споте на " + f"{pos.spot_qty * pos.spot_entry:.2f} $ — разные инструменты под одним тикером") + if self.settings.auto_transfer: + try: # margin for the short, from the spot USDT if needed + moved = live.ensure_usdt(c, 0.0, coins * p.fut_bid * 1.03) + if moved: + self._journal(pos.base, "transfer", True, moved) + except (live.LiveError, AttributeError) as exc: + self._journal(pos.base, "transfer", False, f"перевод не удался: {exc}") + fut = c.fut_order(pos.fut_symbol, "sell", coins, reduce_only=False) + except live.LiveError as exc: + if getattr(exc, "sent", False): + fut = None # may be open: the position check decides + try: + held = -c.fut_position(pos.fut_symbol) + except live.LiveError: + held = 0.0 + if held > 0: + fut = live.Fill(held, p.fut_bid, held * p.fut_bid * self._fut_rate(p) / 100, exc.order_id, + exact=False) + if fut is None: + with self.lock: + changed = pos.error != f"шорт не открыт: {exc}" + pos.error, pos.retry_at = f"шорт не открыт: {exc}", time.time() + self.SHORT_RETRY_S + self.save() + if changed: + self._journal(pos.base, "open", False, f"шорт не открыт: {exc} — спот {pos.spot_qty:g} держится " + f"без хеджа, повтор через {self.SHORT_RETRY_S / 60:.0f} мин (× у позиции — продать спот)") + self._pause_if_balance(str(exc)) + return + with self.lock: + pos.qty, pos.fut_entry, pos.short_pending, pos.error = fut.coins, fut.price, False, "" + pos.fees += fut.fee_usd + pos.entry_gap = (fut.price / pos.spot_entry - 1) * 100 + pos.next_funding = p.next_funding + pos.exact = pos.exact and fut.exact + self.save() + self._journal(pos.base, "open", True, f"шорт к споту открыт: {fut.coins:g} по {fut.price:.10g}, разница к цене " + f"покупки спота {pos.entry_gap:+.3f}% — дальше обычное закрытие при схождении") + self._place_tp(c, pos) + + def adopt(self, base: str, price: float | None = None, fee_usd: float | None = None) -> str: + """Take coins that are on the spot account into the program as a real position (spot leg; the short is + opened next). `price` — what they were bought at (from the exchange's history), else the current ask.""" + import live + base = base.upper().strip() + with self.lock: + p = self.pairs.get(base) + if any(pos.base == base and pos.real for pos in self.positions): + return f"{base} уже ведётся программой" + if p is not None: + self.adopting.add(base) # «busy» for the entry logic while the balance is read + if p is None: + return f"{base}: нет пары спот + фьючерс на {self.venue.name}" + try: + free = self.client_for(self.key).spot_free(base) + except live.LiveError as exc: + with self.lock: + self.adopting.discard(base) + return f"не удалось прочитать баланс: {exc}" + if free * p.spot_bid < 1.0: + with self.lock: + self.adopting.discard(base) + return f"на споте нет {base} (свободно {free:g})" + price = price or p.spot_ask + fee = fee_usd if fee_usd is not None else free * price * self.settings.spot_fee / 100 + with self.lock: + pos = Position(self.next_uid, base, time.time(), 0.0, price, 0.0, 0.0, fee, p.next_funding, real=True, + spot_qty=free, fut_symbol=p.fut_symbol, short_pending=True, + error="подхвачена с баланса: шорт ещё не открыт", innovation=self._innovation(p)) + self.next_uid += 1 + self.positions.append(pos) + self.adopting.discard(base) + self.save() + self._journal(base, "open", True, f"подхвачено со спота {free:g} {base} по {price:.10g} — открываю шорт") + return f"{base}: подхвачено {free:g} монет, шорт откроется следующим шагом" + + def _real_open(self, p: Pair, amount: float) -> None: + import live + notes = [] + # BEFORE buying anything: can the perp be shorted for this amount at all (its minimum lot)? + try: + c = self.client_for(self.key) + min_coins = c.fut_min_coins(p.fut_symbol) + except (live.LiveError, AttributeError) as exc: + self._not_tradable(p.base, f"нет правил контракта: {exc}", 300) + return + coins_est = amount / p.spot_ask * (1 - self.settings.spot_fee / 100) + if not self._legs_match(p, coins_est, amount): + return + if coins_est < min_coins: + need = min_coins * p.spot_ask / (1 - self.settings.spot_fee / 100) * 1.02 + self._not_tradable(p.base, f"сумма {amount:g} $ меньше минимального лота фьючерса ({min_coins:g} монет ≈ " + f"{need:.2f} $)", 1800) + return + with self.lock: + # last check right before money is spent: no other entry in progress, the limit of real positions kept + held = [x.base for x in self.positions if x.real] + if (p.base in held or self.adopting or self.opening - {p.base} or busy_elsewhere(p.base, self) + or len(held) >= max(1, self.settings.max_real_positions)): + self.opening.discard(p.base) + return + self.pending[p.base] = {"time": time.time(), "amount": amount} # a stop now: found again at start + self.save() + # money where it is needed: the amount on spot for the buy, the same on futures for the short's margin + # (leverage 1 assumed — the safe side); moved from the other account when one of them is short + if self.settings.auto_transfer: + try: + moved = live.ensure_usdt(c, amount * 1.01, amount * 1.03) + if moved: + self._journal(p.base, "transfer", True, moved) + except (live.LiveError, AttributeError) as exc: + if "в сумме" in str(exc): + self._journal(p.base, "open", False, f"не открываю: {exc} — спот не покупался") + self._pause_if_balance(str(exc)) + with self.lock: + self.opening.discard(p.base) + return + self._journal(p.base, "transfer", False, f"перевод не удался: {exc} — пробую без него") + if self.settings.entry_limit: + self._open_limit_first(c, p, amount) + return + try: + buy = c.spot_buy(p.base, amount) + except live.LiveError as exc: + # accepted but not confirmed: what is on the account decides whether the coin was bought + bought = 0.0 + if getattr(exc, "sent", False): + try: + bought = min(c.spot_free(p.base), amount / p.spot_ask * 1.02) + except live.LiveError: + bought = 0.0 + if bought <= 0: + self._journal(p.base, "open", False, f"покупка на споте: {exc}") + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() # pause before trying this coin again + self._pause_if_balance(str(exc)) + return + buy = live.Fill(bought, p.spot_ask, amount * self.settings.spot_fee / 100, exc.order_id) + notes.append("покупка не подтверждена биржей — цена оценочная") + try: + free = c.spot_free(p.base) + except live.LiveError: + free = 0.0 + held = min(buy.coins, free) if free > 0 else buy.coins * (1 - self.settings.spot_fee / 100) + fut, failure, coins = None, "", 0.0 + try: + coins = c.fut_round(p.fut_symbol, held) + if coins <= 0: + raise live.LiveError("монет меньше минимального лота фьючерса") + fut = c.fut_order(p.fut_symbol, "sell", coins, reduce_only=False) + except live.LiveError as exc: + failure = str(exc) + if getattr(exc, "sent", False) and coins > 0: + # the short may be open: keep the position (estimated price) — closing it is reduce-only + fut = live.Fill(coins, p.fut_bid, coins * p.fut_bid * self._fut_rate(p) / 100, exc.order_id) + notes.append("шорт не подтверждён биржей — проверьте позицию, цена оценочная") + if fut is None: + # no hedge → sell the spot back at once + try: + back = c.spot_sell(p.base, held) + text = f"шорт не открылся ({failure}); спот продан обратно по {back.price:.10g}" + except live.LiveError as exc2: + text = f"шорт не открылся ({failure}); СПОТ НЕ ПРОДАН ({exc2}) — продайте {held:g} {p.base} вручную" + self._journal(p.base, "open", False, text) + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + self._pause_if_balance(failure) + return + with self.lock: + self.opening.discard(p.base) + pos = Position(self.next_uid, p.base, time.time(), fut.coins, buy.price, fut.price, + (fut.price / buy.price - 1) * 100, buy.fee_usd + fut.fee_usd, p.next_funding, + real=True, spot_qty=held, fut_symbol=p.fut_symbol, error="; ".join(notes), + exact=buy.exact and fut.exact and not notes, innovation=self._innovation(p)) + self.next_uid += 1 + self.positions.append(pos) + self.save() + self._journal(p.base, "open", True, f"куплено {held:g} по {buy.price:.10g}, шорт {fut.coins:g} по " + f"{fut.price:.10g}, разница {pos.entry_gap:+.3f}%" + (f" ({'; '.join(notes)})" if notes else ""), + amount=amount) + self._place_tp(c, pos) + + def _open_limit_first(self, c, p: Pair, amount: float) -> None: + """Entry with a LIMIT short at the signal's perp bid, kept up to `limit_hold_s` seconds; whatever part of it + fills is hedged at once by buying the same coins on spot. Nothing filled → the order is removed, no spot.""" + import live + s = self.settings + coins = c.fut_round(p.fut_symbol, amount / p.spot_ask * (1 - s.spot_fee / 100)) + if not self._legs_match(p, coins, amount): + return + try: + oid = c.fut_limit(p.fut_symbol, "sell", coins, p.fut_bid) + except (live.LiveError, AttributeError) as exc: + self._journal(p.base, "open", False, f"лимитный шорт не выставлен: {exc}") + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + self._pause_if_balance(str(exc)) + return + st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False} + end = time.time() + max(0.0, s.limit_hold_s) + while True: # one look a second: the exchange's request limit + try: + st = c.fut_order_status(p.fut_symbol, oid) + except live.LiveError: + pass + if st["final"] or st["coins"] >= coins * 0.999 or time.time() >= end: + break + time.sleep(1.0) + if not st["final"]: + try: + c.fut_cancel(p.fut_symbol, oid) + except live.LiveError: + pass + try: # what filled until the cancel + st = c.fut_order_status(p.fut_symbol, oid) + except live.LiveError: + try: + st = {**st, "coins": max(0.0, -c.fut_position(p.fut_symbol))} + except live.LiveError: + pass + shorted = st["coins"] + if shorted <= 0: + self._journal(p.base, "open", False, f"лимитный шорт по {p.fut_bid:.10g} не исполнился за " + f"{s.limit_hold_s:g} с — снят, спот не покупался") + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + return + fut_price = st["price"] or p.fut_bid + # hedge: the same coins on spot (the buy fee is taken in coins: a little more USDT) + try: + buy = c.spot_buy(p.base, shorted * p.spot_ask * (1 + s.spot_fee / 100) * 1.003) + except live.LiveError as exc: + try: + c.fut_order(p.fut_symbol, "buy", shorted, reduce_only=True) + text = f"шорт {shorted:g} исполнился, но спот не куплен ({exc}); шорт закрыт" + except live.LiveError as exc2: + text = f"шорт {shorted:g} исполнился, спот не куплен ({exc}); ШОРТ НЕ ЗАКРЫТ ({exc2}) — закройте вручную" + self._journal(p.base, "open", False, text) + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + self._pause_if_balance(str(exc)) + return + try: + free = c.spot_free(p.base) + except live.LiveError: + free = 0.0 + held = min(buy.coins, free) if free > 0 else buy.coins * (1 - s.spot_fee / 100) + with self.lock: + self.opening.discard(p.base) + pos = Position(self.next_uid, p.base, time.time(), shorted, buy.price, fut_price, + (fut_price / buy.price - 1) * 100, buy.fee_usd + st["fee"], p.next_funding, + real=True, spot_qty=held, fut_symbol=p.fut_symbol, exact=buy.exact, + innovation=self._innovation(p)) + self.next_uid += 1 + self.positions.append(pos) + self.save() + self._journal(p.base, "open", True, f"лимитный шорт {shorted:g} по {fut_price:.10g} (заявка {p.fut_bid:.10g}), " + f"спот куплен {held:g} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}%", amount=amount) + self._place_tp(c, pos) + + def _place_tp(self, c, pos: Position) -> None: + """TP on the exchange: a reduce-only LIMIT buy of the short at the price where the gap has closed against + the spot bought (perp = spot entry + «Закрыть при»). When it fills, the program sells the spot.""" + import live + if not self.settings.exchange_tp or pos.qty <= 0: + return + tp = pos.spot_entry * (1 + self.settings.exit_gap_pct / 100) + if tp >= pos.fut_entry: + return # the gap is already as small as the exit level + try: + oid = c.fut_take_profit(pos.fut_symbol, "buy", pos.qty, tp) + except (live.LiveError, AttributeError) as exc: + self._journal(pos.base, "open", False, f"TP на бирже не выставлен: {exc} — закрытие по схождению программой") + return + with self.lock: + pos.tp_order, pos.tp_price = str(oid), tp + self.save() + self._journal(pos.base, "open", True, f"TP на бирже: выкуп шорта лимитом по {tp:.10g} " + f"({(tp / pos.fut_entry - 1) * 100:+.3f}% от входа)") + + def _remove_tp(self, uid: int) -> None: + """Take a TP order off the exchange (the program watches the gap itself now). If it filled meanwhile, the + position is closed through the usual path, which counts what the TP bought back.""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or not pos.tp_order or pos.closing: + return + c = self.client_for(self.key) + try: + c.fut_cancel(pos.fut_symbol, pos.tp_order) + except (live.LiveError, AttributeError): + pass + try: + filled = c.fut_order_status(pos.fut_symbol, pos.tp_order)["coins"] + except (live.LiveError, AttributeError): + filled = 0.0 + if filled > 0: + self._real_close(uid, "TP на бирже исполнился до снятия") + return + with self.lock: + pos.tp_order, pos.tp_price = "", 0.0 + self.save() + self._journal(pos.base, "open", True, "TP на бирже снят — закрытие решает программа по свежим ценам") + + WATCH_TP_S = 3.0 + + def _watch_tp(self, uid: int) -> None: + """Has the TP on the exchange bought the short back? Then the spot is sold now (via the usual close).""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or not pos.tp_order or pos.closing: + return + try: + held = self.client_for(self.key).fut_position(pos.fut_symbol) + except live.LiveError: + return + if held > -pos.qty * 1e-6: # no short left: the TP has filled + self._real_close(uid, "TP на бирже") + + def _legs_match(self, p: Pair, coins: float, amount: float) -> bool: + """Last guard before an order: the same coins on spot and perp must be worth about the same. A perp leg + worth far more than the amount means two different instruments under one ticker — no order at all.""" + fut_value = coins * p.fut_bid + if p.entry_gap > HARD_MAX_GAP_PCT or fut_value > amount * MAX_LEG_RATIO: + self._not_tradable(p.base, f"шорт {coins:g} монет стоил бы {fut_value:.2f} $ при сумме {amount:g} $ — " + f"спот и фьючерс под этим тикером разные инструменты", 86400) + return False + return True + + def _not_tradable(self, base: str, why: str, seconds: float) -> None: + """The coin cannot be traded for real now: skip it (no spot bought) and say why in the table, once.""" + with self.lock: + known = self.real_block.get(base, ("", 0.0))[0] == why + self.real_block[base] = (why, time.time() + seconds) + self.opening.discard(base) + if not known: + self._journal(base, "open", False, f"не открываю: {why} — спот не покупался") + + BALANCE_PAUSE_S = 900.0 + + def _pause_if_balance(self, error: str) -> None: + """Not enough money on the account (MEXC 2005 «Balance insufficient», …): no real entries on this exchange + for a while — every new try would only buy the spot and sell it back.""" + if any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно", "не хватает")): + with self.lock: + self.real_pause_until = time.time() + self.BALANCE_PAUSE_S + self.real_pause_reason = ("не хватает баланса на бирже — пополните счёт (фьючерсы и спот) " + "или уменьшите «Сумму сделки»") + self._journal("—", "open", False, f"{self.real_pause_reason}; реальные входы на паузе 15 мин") + + def _real_close(self, uid: int, reason: str) -> None: + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None: + return + stage = "выкуп шорта" + try: + c = self.client_for(self.key) + if pos.qty <= 0 and pos.closing != "fut_done": + with self.lock: # no short was ever opened: only the spot is sold + pos.closing, pos.fut_exit = "fut_done", pos.fut_entry + self.save() + # 1) buy the short back (reduce-only: it can never open anything); what the TP on the exchange has + # already bought back counts, the rest is bought at market + if pos.closing != "fut_done": + tp_coins = tp_price = tp_fee = 0.0 + if pos.tp_order: + try: + c.fut_cancel(pos.fut_symbol, pos.tp_order) + except (live.LiveError, AttributeError): + pass # already filled or gone + try: + st = c.fut_order_status(pos.fut_symbol, pos.tp_order) + tp_coins, tp_price, tp_fee = st["coins"], st["price"], st["fee"] + except (live.LiveError, AttributeError): + pass + with self.lock: + pos.tp_order = "" + self.save() + rest = pos.qty - tp_coins + fut_coins, fut_price, fut_fee, exact = 0.0, 0.0, 0.0, True + if rest > pos.qty * 1e-6: + try: + fut = c.fut_order(pos.fut_symbol, "buy", rest, reduce_only=True) + fut_coins, fut_price, fut_fee, exact = fut.coins, fut.price, fut.fee_usd, fut.exact + except live.LiveError as exc: + if not getattr(exc, "sent", False): + raise + p = self.pairs.get(pos.base) # accepted, not confirmed: the position check decides + fut_coins, fut_price = rest, (p.fut_ask if p else pos.fut_entry) + fut_fee, exact = rest * fut_price * fut_rate(self.settings, pos.innovation) / 100, False + done = tp_coins + fut_coins + avg = (tp_coins * tp_price + fut_coins * fut_price) / done if done else pos.fut_entry + with self.lock: + pos.fut_exit, pos.exit_fees, pos.closing = avg, tp_fee + fut_fee, "fut_done" + pos.exact = pos.exact and exact + self.save() + # 2) the exchange must show no short left; a remainder is bought back too + stage = "проверка фьючерса" + held = c.fut_position(pos.fut_symbol) if pos.qty > 0 else 0.0 + if held < -1e-12: + c.fut_order(pos.fut_symbol, "buy", -held, reduce_only=True) + raise live.LiveError(f"на фьючерсе оставалось {held:+g} — докуплено, проверяю ещё раз") + # 3) sell the coins this trade bought (never more: other coins on the account are not ours) + stage = "продажа спота" + p = self.pairs.get(pos.base) + price_now = p.spot_bid if p else pos.spot_entry + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0: # more than dust left to sell + free = c.spot_free(pos.base) + if free * price_now > 1.0: + sell = c.spot_sell(pos.base, min(free, left)) + with self.lock: + pos.sold_coins += sell.coins + pos.sold_value += sell.coins * sell.price + pos.sold_fees += sell.fee_usd + pos.exact = pos.exact and sell.exact + self.save() + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0 and c.spot_free(pos.base) * price_now > 1.0: + raise live.LiveError(f"на споте ещё {left:g} {pos.base} — продам при следующей попытке") + if pos.sold_coins <= 0: + raise live.LiveError("спот не продан") + except live.LiveError as exc: + with self.lock: + pos.retry_at, pos.error = time.time() + 15, f"{stage}: {exc}" + self.save() + self._journal(pos.base, "close", False, f"{stage}: {exc} — следующая сделка не откроется, пока эта не " + f"закрыта; повтор через 15 с") + return + with self.lock: + now = time.time() + sell_price = pos.sold_value / pos.sold_coins + spot_pnl = pos.sold_value - pos.sold_coins * pos.spot_entry + fut_pnl = pos.qty * (pos.fut_entry - pos.fut_exit) + fees = pos.fees + pos.exit_fees + pos.sold_fees + net = spot_pnl + fut_pnl - fees + pos.funding + t = Trade(pos.uid, pos.base, pos.opened, now, pos.qty, pos.spot_entry, sell_price, pos.fut_entry, + pos.fut_exit, pos.entry_gap, (pos.fut_exit / sell_price - 1) * 100 if pos.qty > 0 else 0.0, + spot_pnl, fut_pnl, fees, + pos.funding, net, f"{reason} (реально{'' if pos.exact else ', часть цифр оценочная'})", + pos.spot_qty * pos.spot_entry, real=True, exact=pos.exact) + if pos in self.positions: + self.positions.remove(pos) + self.trades.append(t) + self.last_close[pos.base] = now + self.save() + self._journal(pos.base, "close", True, f"шорт выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет), спот " + f"продан по {sell_price:.10g}, итог {net:+.4f} $, комиссии {fees:.4f} $ ({reason})", net=net) + + def reset(self) -> str: + with self.lock: + if any(p.real for p in self.positions): + return "есть открытые реальные позиции — сначала закройте их" + self.positions, self.trades, self.last_close = [], [], {} + self.save() + return "статистика сброшена" + + # --- view ---------------------------------------------------------------------------------- + def view(self) -> dict: + with self.lock: + s = self.settings + now = time.time() + rows = [] + real_open = [x.base for x in self.positions if x.real] + for p in self.candidates(): + m = self._min_entry(p) + import minorder + small = minorder.too_small(s.amount, m, self.venue.name, self.venue.name) + fits = (s.min_gap_pct <= p.entry_gap <= min(s.max_gap_pct, HARD_MAX_GAP_PCT) and depth_ok(p, s) + and not small) + # why this coin is not entered now — shown in the table instead of an empty cell + elsewhere = busy_elsewhere(p.base, self) + why = (f"разница больше {HARD_MAX_GAP_PCT:g}% — это разные инструменты под одним тикером, не торгуется" + if p.entry_gap > HARD_MAX_GAP_PCT + else f"уже в сделке: {elsewhere}" if elsewhere + else "разница ниже «Мин. расхождения»" if p.entry_gap < s.min_gap_pct + else "разница выше «Макс.»" if p.entry_gap > s.max_gap_pct + else "мало объёма по лучшей цене" if not depth_ok(p, s) + else small if small + else "торговля остановлена (кнопка «Старт»)" if not s.running + else (f"открыто реальных позиций {len(real_open)} из {max(1, s.max_real_positions)} " + f"({', '.join(real_open)}) — ждёт закрытия" + if s.real and len(real_open) >= max(1, s.max_real_positions) and p.base not in real_open else + "сейчас открывается другая реальная сделка" if s.real and (self.opening - {p.base}) else + f"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until else + f"пауза по монете после закрытия ({s.cooldown_s:g} с)" + if now - self.last_close.get(p.base, 0) < s.cooldown_s else "")) + rows.append({**asdict(p), "entry_gap": p.entry_gap, "exit_gap": p.exit_gap, "why": why, + "funding_pct": p.funding * 100, "spot_url": self.venue.spot_url(p), + "fut_url": self.venue.fut_url(p), + "net_if_closed_pct": p.entry_gap - s.exit_gap_pct - 2 * (s.spot_fee + self._fut_rate(p)), + "fut_fee_pct": self._fut_rate(p), + "min_entry": m["usd"] if m else None, "min_spot": m["spot"] if m else None, + "min_fut": m["fut"] if m else None, + "depth": entry_depth(p), + "real_block": (self.real_block.get(p.base, ("", 0.0))[0] + if s.real and self.real_block.get(p.base, ("", 0.0))[1] > now else ""), + "fits": fits}) + rows.sort(key=lambda r: -r["entry_gap"]) + positions = [] + for pos in self.positions: + p = self.pairs.get(pos.base) + d = asdict(pos) + if p: + spot_pnl, fut_pnl, fees, net = close_result(pos, p.spot_bid, p.fut_ask, s) + seen = self.fast_seen.get(pos.base) + d.update(price_age=None if seen is None else now - seen, fast_ms=self.fast_ms) + d.update(gap_now=p.exit_gap, spot_now=p.spot_bid, fut_now=p.fut_ask, net=net, fees_total=fees, + spot_url=self.venue.spot_url(p), fut_url=self.venue.fut_url(p)) + positions.append(d) + # real mode: the figures are those of the real trades only (prices and fees from the exchange's fills) + closed = [t for t in self.trades if t.real] if s.real else self.trades + opened = [p for p in positions if p.get("real")] if s.real else positions + wins = sum(t.net > 0 for t in closed) + invested = sum(t.amount for t in closed) + stats = {"trades": len(closed), "wins": wins, "net": sum(t.net for t in closed), + "net_pct": sum(t.net for t in closed) / invested * 100 if invested else None, + "fees": sum(t.fees for t in closed), "funding": sum(t.funding for t in closed), + "open": len(opened), "unrealized": sum(p.get("net", 0) for p in opened), + "real": s.real, "exact": all(t.exact for t in closed), + "avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None} + return {"venue": self.venue.name, "key": self.key, "settings": asdict(s), "status": self.status, + "updated": self.updated, "cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.pairs), + "memes_source": self.memes_source, "rows": rows, "positions": positions, + "real_pause": (f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)" + if s.real and now < self.real_pause_until else ""), + "trades": [asdict(t) for t in reversed(closed[-200:])], "stats": stats, + "planned": PLANNED} diff --git a/LinuxServer/bybit_live.py b/LinuxServer/bybit_live.py new file mode 100644 index 0000000..da9ea91 --- /dev/null +++ b/LinuxServer/bybit_live.py @@ -0,0 +1,260 @@ +"""Small signed Bybit V5 client used by the optional live-trading mode. + +API credentials are held only in memory and are never written to disk or logs. +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from decimal import Decimal, ROUND_DOWN, ROUND_UP + + +class BybitAPIError(RuntimeError): + pass + + +class BybitLiveClient: + def __init__(self, api_key: str, api_secret: str, testnet: bool = True) -> None: + if not api_key.strip() or not api_secret.strip(): + raise ValueError("Введите API key и API secret") + self.api_key = api_key.strip() + self._secret = api_secret.strip().encode("utf-8") + self.testnet = testnet + self.base_url = "https://api-testnet.bybit.com" if testnet else "https://api.bybit.com" + self.recv_window = "5000" + + def _request(self, method: str, path: str, params: dict | None = None) -> dict: + params = params or {} + timestamp = str(int(time.time() * 1000)) + if method == "GET": + query = urllib.parse.urlencode(sorted((key, str(value)) for key, value in params.items())) + body = "" + payload = None + else: + query = "" + body = json.dumps(params, separators=(",", ":"), ensure_ascii=False) + payload = body.encode("utf-8") + signature_input = f"{timestamp}{self.api_key}{self.recv_window}{query or body}" + signature = hmac.new(self._secret, signature_input.encode("utf-8"), hashlib.sha256).hexdigest() + headers = { + "X-BAPI-API-KEY": self.api_key, + "X-BAPI-SIGN": signature, + "X-BAPI-TIMESTAMP": timestamp, + "X-BAPI-RECV-WINDOW": self.recv_window, + "Content-Type": "application/json", + "User-Agent": "RealtimePaperSimulator/1.0", + } + url = f"{self.base_url}{path}" + (f"?{query}" if query else "") + request = urllib.request.Request(url, data=payload, headers=headers, method=method) + try: + with urllib.request.urlopen(request, timeout=10) as response: + result = json.loads(response.read().decode("utf-8")) + except urllib.error.HTTPError as exc: + raw_details = exc.read() + try: + details = json.loads(raw_details.decode("utf-8")) + except Exception: + details = {} + + # Keep the useful Bybit error code and request context, but never + # include request headers, signatures, API keys, or secrets. + ret_code = details.get("retCode") if isinstance(details, dict) else None + ret_msg = details.get("retMsg") if isinstance(details, dict) else None + endpoint = "тестовой сети" if self.testnet else "основной сети" + context = f"{method} {path} ({endpoint})" + if ret_code is not None: + message = f"Bybit API HTTP {exc.code}, retCode {ret_code}: {ret_msg or 'ошибка запроса'}" + hints = { + 10002: "Проверьте синхронизацию часов Windows.", + 10003: "Ключ не подходит к выбранному домену: сверьте Testnet/Mainnet с сетью, где создан API-ключ.", + 10004: "Bybit отклонил подпись. Проверьте API Secret и отсутствие лишних пробелов при вставке.", + 10005: "Проверьте права API-ключа для чтения аккаунта и торговли контрактами.", + 10009: "Bybit ограничил доступ к API для региона аккаунта или подключения.", + 10010: "IP компьютера не совпадает с IP, разрешённым в настройках API-ключа.", + } + if ret_code in hints: + message += f" {hints[ret_code]}" + elif exc.code == 401: + message = ( + f"Bybit вернул HTTP 401 для {context}: запрос авторизации отклонён. " + "Проверьте, что API-ключ создан в выбранной сети (Testnet/Mainnet), " + "ключ и секрет скопированы полностью без пробелов, а IP компьютера " + "разрешён в настройках ключа. Секрет приложения не выводит." + ) + else: + message = f"Bybit API HTTP {exc.code} для {context}" + raise BybitAPIError(message) from None + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc: + raise BybitAPIError(f"Не удалось связаться с Bybit: {exc}") from None + if result.get("retCode") != 0: + raise BybitAPIError(f"Bybit API {result.get('retCode')}: {result.get('retMsg', 'ошибка запроса')}") + return result.get("result", {}) + + def get_wallet(self) -> dict[str, float]: + result = self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"}) + rows = result.get("list", []) + if not rows: + raise BybitAPIError("Bybit не вернул Unified USDT-баланс; проверьте тип аккаунта и права API") + row = rows[0] + available_raw = row.get("totalAvailableBalance") + if available_raw in (None, ""): + equity = float(row.get("totalEquity") or 0) + initial_margin = float(row.get("totalInitialMargin") or 0) + available = max(0.0, equity - initial_margin) + else: + available = float(available_raw) + return { + "wallet": float(row.get("totalWalletBalance") or 0), + "equity": float(row.get("totalEquity") or 0), + "available": available, + "unrealized_pnl": float(row.get("totalPerpUPL") or 0), + } + + def get_instrument(self, symbol: str) -> dict[str, str]: + result = self._request("GET", "/v5/market/instruments-info", {"category": "linear", "symbol": symbol}) + rows = result.get("list", []) + if not rows: + raise BybitAPIError(f"Контракт {symbol} не найден на Bybit linear") + row = rows[0] + lot = row.get("lotSizeFilter", {}) + if row.get("status") != "Trading": + raise BybitAPIError(f"Контракт {symbol} сейчас не торгуется") + return { + "qty_step": lot.get("qtyStep", "0"), + "min_qty": lot.get("minOrderQty", "0"), + "min_notional": lot.get("minNotionalValue", "0"), + "max_market_qty": lot.get("maxMktOrderQty", lot.get("maxMarketOrderQty", "0")), + "tick_size": row.get("priceFilter", {}).get("tickSize", "0"), + } + + def get_taker_fee_pct(self, symbol: str) -> float: + result = self._request("GET", "/v5/account/fee-rate", {"category": "linear", "symbol": symbol}) + rows = result.get("list", []) + if not rows: + raise BybitAPIError(f"Bybit не вернул комиссию для {symbol}") + return float(rows[0]["takerFeeRate"]) * 100 + + def get_positions(self, symbol: str) -> list[dict]: + result = self._request("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}) + return result.get("list", []) + + def get_open_positions(self) -> list[dict]: + """Return all open USDT-settled linear positions for account overview.""" + result = self._request("GET", "/v5/position/list", { + "category": "linear", "settleCoin": "USDT", "limit": 200, + }) + return [row for row in result.get("list", []) if float(row.get("size") or 0) > 0] + + def get_order_history(self, limit: int = 50) -> list[dict]: + """Return recent linear-contract order records (read-only).""" + result = self._request("GET", "/v5/order/history", { + "category": "linear", "settleCoin": "USDT", "limit": max(1, min(int(limit), 50)), + }) + return result.get("list", []) + + def get_closed_pnl_history(self, limit: int = 50) -> list[dict]: + """Return recent realized PnL records for linear contracts.""" + result = self._request("GET", "/v5/position/closed-pnl", { + "category": "linear", "limit": max(1, min(int(limit), 100)), + }) + return result.get("list", []) + + def get_open_position(self, symbol: str) -> dict | None: + for row in self.get_positions(symbol): + if float(row.get("size") or 0) > 0: + return row + return None + + def get_order(self, symbol: str, order_id: str) -> dict | None: + """Read the exchange state of an accepted order for safe reconciliation.""" + params = {"category": "linear", "symbol": symbol, "orderId": order_id} + for path in ("/v5/order/realtime", "/v5/order/history"): + result = self._request("GET", path, params) + rows = result.get("list", []) + if rows: + return rows[0] + return None + + def get_latest_closed_pnl(self, symbol: str, opened_at_ms: int) -> dict | None: + result = self._request("GET", "/v5/position/closed-pnl", { + "category": "linear", "symbol": symbol, "startTime": opened_at_ms, "limit": 50, + }) + rows = result.get("list", []) + return max(rows, key=lambda row: int(row.get("updatedTime", 0))) if rows else None + + def set_leverage(self, symbol: str, leverage: float) -> None: + try: + self._request("POST", "/v5/position/set-leverage", { + "category": "linear", "symbol": symbol, + "buyLeverage": str(leverage), "sellLeverage": str(leverage), + }) + except BybitAPIError as exc: + # Bybit returns 110043 if the requested leverage is already active. + if "110043" not in str(exc): + raise + + @staticmethod + def floor_qty(raw_qty: float, spec: dict[str, str]) -> str: + step = Decimal(spec["qty_step"]) + if step <= 0: + raise BybitAPIError("Bybit вернул некорректный шаг количества") + qty = (Decimal(str(raw_qty)) / step).to_integral_value(rounding=ROUND_DOWN) * step + if qty < Decimal(spec["min_qty"]): + raise BybitAPIError(f"Размер заявки меньше минимального: {spec['min_qty']}") + maximum = Decimal(spec.get("max_market_qty") or "0") + if maximum > 0 and qty > maximum: + raise BybitAPIError(f"Рыночная заявка превышает максимум {maximum}; уменьшите ставку или плечо") + return format(qty, "f") + + @staticmethod + def format_price(raw_price: float, tick_size: str) -> str: + tick = Decimal(tick_size) + if tick <= 0: + return format(Decimal(str(raw_price)), "f") + price = (Decimal(str(raw_price)) / tick).to_integral_value(rounding=ROUND_UP) * tick + return format(price, "f") + + def place_market_buy(self, symbol: str, qty: str, take_profit: float, stop_loss: float, + tick_size: str, order_id: str | None = None) -> str: + body = { + "category": "linear", "symbol": symbol, "side": "Buy", "orderType": "Market", + "qty": qty, "positionIdx": 0, "timeInForce": "IOC", + "tpslMode": "Full", "tpOrderType": "Market", "slOrderType": "Market", + "takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0", + "stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0", + "tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice", + "orderLinkId": order_id or f"rps-{uuid.uuid4().hex[:28]}", + } + result = self._request("POST", "/v5/order/create", body) + return result.get("orderId", "") + + def update_position_stops(self, symbol: str, take_profit: float, stop_loss: float, + tick_size: str) -> None: + try: + self._request("POST", "/v5/position/trading-stop", { + "category": "linear", "symbol": symbol, "tpslMode": "Full", "positionIdx": 0, + "takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0", + "stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0", + "tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice", + "tpOrderType": "Market", "slOrderType": "Market", + }) + except BybitAPIError as exc: + # Bybit's 34040 is an idempotent response: the requested TP/SL is + # already active (or no value changed), so there is nothing to do. + if "34040" not in str(exc): + raise + + def close_long_market(self, symbol: str, qty: str) -> str: + result = self._request("POST", "/v5/order/create", { + "category": "linear", "symbol": symbol, "side": "Sell", "orderType": "Market", + "qty": qty, "positionIdx": 0, "timeInForce": "IOC", "reduceOnly": True, + "closeOnTrigger": True, "orderLinkId": f"rps-close-{uuid.uuid4().hex[:24]}", + }) + return result.get("orderId", "") diff --git a/LinuxServer/credential_store.py b/LinuxServer/credential_store.py new file mode 100644 index 0000000..e3b7a37 --- /dev/null +++ b/LinuxServer/credential_store.py @@ -0,0 +1,119 @@ +"""Store Bybit credentials encrypted for the current Windows user with DPAPI.""" + +from __future__ import annotations + +import base64 +import ctypes +import json +import os +from ctypes import wintypes +from pathlib import Path + + +class CredentialStoreError(RuntimeError): + """Raised when credentials cannot be safely stored or loaded.""" + + +class _DataBlob(ctypes.Structure): + _fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_byte))] + + +def _default_path() -> Path: + local_app_data = os.environ.get("LOCALAPPDATA") + if not local_app_data: + raise CredentialStoreError("Не удалось определить папку профиля Windows для защищённого хранения") + return Path(local_app_data) / "RealtimePaperSimulator" / "bybit_credentials.dpapi" + + +def _protect(data: bytes) -> bytes: + if os.name != "nt": + raise CredentialStoreError("Защищённое хранение ключей доступно только в Windows") + crypt32 = ctypes.WinDLL("crypt32", use_last_error=True) + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + source_buffer = ctypes.create_string_buffer(data) + source = _DataBlob(len(data), ctypes.cast(source_buffer, ctypes.POINTER(ctypes.c_byte))) + encrypted = _DataBlob() + crypt32.CryptProtectData.argtypes = [ + ctypes.POINTER(_DataBlob), wintypes.LPCWSTR, ctypes.POINTER(_DataBlob), + ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob), + ] + crypt32.CryptProtectData.restype = wintypes.BOOL + kernel32.LocalFree.argtypes = [ctypes.c_void_p] + kernel32.LocalFree.restype = ctypes.c_void_p + if not crypt32.CryptProtectData(ctypes.byref(source), "Bybit API credentials", None, None, None, 1, + ctypes.byref(encrypted)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + return ctypes.string_at(encrypted.pbData, encrypted.cbData) + finally: + kernel32.LocalFree(encrypted.pbData) + + +def _unprotect(data: bytes) -> bytes: + if os.name != "nt": + raise CredentialStoreError("Защищённое хранение ключей доступно только в Windows") + crypt32 = ctypes.WinDLL("crypt32", use_last_error=True) + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + source_buffer = ctypes.create_string_buffer(data) + source = _DataBlob(len(data), ctypes.cast(source_buffer, ctypes.POINTER(ctypes.c_byte))) + decrypted = _DataBlob() + crypt32.CryptUnprotectData.argtypes = [ + ctypes.POINTER(_DataBlob), ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(_DataBlob), + ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob), + ] + crypt32.CryptUnprotectData.restype = wintypes.BOOL + kernel32.LocalFree.argtypes = [ctypes.c_void_p] + kernel32.LocalFree.restype = ctypes.c_void_p + if not crypt32.CryptUnprotectData(ctypes.byref(source), None, None, None, None, 1, + ctypes.byref(decrypted)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + return ctypes.string_at(decrypted.pbData, decrypted.cbData) + finally: + kernel32.LocalFree(decrypted.pbData) + + +def save_credentials(api_key: str, api_secret: str, path: Path | None = None) -> None: + api_key, api_secret = api_key.strip(), api_secret.strip() + if not api_key or not api_secret: + raise CredentialStoreError("Введите API key и API secret перед сохранением") + target = path or _default_path() + try: + encrypted = _protect(json.dumps( + {"api_key": api_key, "api_secret": api_secret}, separators=(",", ":") + ).encode("utf-8")) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(base64.b64encode(encrypted).decode("ascii"), encoding="ascii") + except CredentialStoreError: + raise + except (OSError, ValueError, TypeError) as exc: + raise CredentialStoreError(f"Не удалось сохранить API-ключи: {exc}") from None + + +def load_credentials(path: Path | None = None) -> dict[str, str] | None: + target = path or _default_path() + if not target.exists(): + return None + try: + encrypted = base64.b64decode(target.read_text(encoding="ascii"), validate=True) + payload = json.loads(_unprotect(encrypted).decode("utf-8")) + api_key = str(payload["api_key"]) + api_secret = str(payload["api_secret"]) + if not api_key or not api_secret: + raise ValueError("пустые ключи") + return {"api_key": api_key, "api_secret": api_secret} + except CredentialStoreError: + raise + except Exception: + raise CredentialStoreError( + "Не удалось расшифровать сохранённые ключи текущим пользователем Windows. " + "Сохраните ключи заново в окне API Bybit." + ) from None + + +def delete_credentials(path: Path | None = None) -> None: + target = path or _default_path() + try: + target.unlink(missing_ok=True) + except OSError as exc: + raise CredentialStoreError(f"Не удалось удалить сохранённые ключи: {exc}") from None diff --git a/LinuxServer/cross.py b/LinuxServer/cross.py new file mode 100644 index 0000000..61aa385 --- /dev/null +++ b/LinuxServer/cross.py @@ -0,0 +1,2475 @@ +"""The one arbitrage mode (paper or real): buy the coin on spot on exchange A where it is cheap and sell the same coins +where they are dear — close both legs when the gap is back to its usual level. Three kinds of link, each switched on +in the settings: + «sf» spot of A → perpetual of B (A ≠ B): the coins bought on A, the same coins shorted on B's perp; + «in» spot → perpetual inside one exchange (A = B): the classic spot–futures basis; + «ss» spot of A → spot of B: the coins bought on A, the same coins sold on B from a stock the user keeps there + (spot cannot be shorted); the close sells A and buys the stock back on B. + +Between two exchanges nothing ties the perp of B to the spot of A (within one exchange the funding/index does), so +the gap may stay wide for a long time: an offset between the exchanges, a coin whose deposits are closed on A, or a +different token under the same ticker. That is why the entry is not «gap above X» but «gap above its USUAL level by +X»: the usual gap of every (coin, spot exchange, perp exchange) is followed over the last ~30 minutes, and the +position is closed when the gap returns to the usual level it had at the entry. + + entry gap = perp bid (B) / spot ask (A) − 1 + exit gap = perp ask (B) / spot bid (A) − 1 + usual = average of the mid gap over the last USUAL_WINDOW_S seconds (EMA), per coin|A|B + +Result of a trade = spot leg (A) + perp leg (B) − the four taker fees of the two exchanges + funding on B. + +Real mode: the short is opened first on B (a limit order at the signal's bid, or at market), then the same coins are +bought on spot on A; the close buys the short back on B, checks that B shows no short left, then sells the coins on +A. One entry at a time, the next only after the previous is confirmed. The fee rates of every exchange are settings; +after each real trade they are replaced by what the exchanges actually charged, so the table counts with them. +""" + +from __future__ import annotations + +import json +import os +from persistence import atomic_write_json +import queue +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from dataclasses import asdict, dataclass, field, fields +from pathlib import Path + +import arb +import minorder + +ROOT = Path(__file__).resolve().parent +DATA_DIR = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT / "web_sim_data")).resolve() +POLL_S = 3.0 +USUAL_WINDOW_S = 1800.0 +KEEP_TRADES = 500 +SPOT_FEE = dict(arb.SPOT_TAKER) +FUT_FEE = {"Bybit": 0.055, "Binance": 0.05, "MEXC": 0.02, "HTX": 0.05, "Gate": 0.05} +# perps of an exchange's own fee group with a higher rate: Bybit's Innovation Zone (bybit.com/fee, regular user) +FUT_FEE_INNOVATION = {"Bybit": 0.11} +INNOVATION_S = 3600.0 +MAX_LEARNED_FEE = 1.0 # a «rate» above this from a fill is a misread, not a fee +# Liquidation of the short on B: nothing on B hedges it (the coins are on A), so B's futures money alone carries +# its loss when the coin rises. Cross margin, one short of N $ at P0 with E $ of futures money behind it: +# liquidation when E − N·x = mmr·N·(1 + x) → x = (E/N − mmr) / (1 + mmr) (x = price rise to liquidation) +DEFAULT_LIMIT = 3 # open trades per exchange (a trade counts on its spot exchange and its perp one) +LIQ_MMR_PCT = 1.0 # maintenance margin rate assumed, % (small coins' tiers: 0.5–1 %, safe side) +LIQ_CHECK_S = 30.0 # the exchange's own liquidation price of an open short is read this often + + +def liq_distance(equity: float, notional: float, mmr_pct: float = LIQ_MMR_PCT) -> float: + """Price rise, %, at which a short of `notional` $ backed by `equity` $ of futures money is liquidated.""" + if notional <= 0: + return float("inf") + mmr = mmr_pct / 100 + return (equity / notional - mmr) / (1 + mmr) * 100 + + +def equity_for(distance_pct: float, notional: float, mmr_pct: float = LIQ_MMR_PCT) -> float: + """Futures money, $, a short of `notional` $ needs to be liquidated only `distance_pct` % above the entry.""" + mmr = mmr_pct / 100 + return notional * ((1 + mmr) * distance_pct / 100 + mmr) + + +def bybit_innovation_symbols() -> set[str]: + """Bybit USDT perps of the Innovation Zone (symbolType «innovation»).""" + out, cursor = set(), "" + while True: + res = arb._get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000" + + (f"&cursor={cursor}" if cursor else ""))["result"] + out |= {x["symbol"] for x in res["list"] if x.get("symbolType") == "innovation"} + cursor = res.get("nextPageCursor") or "" + if not cursor or not res["list"]: + return out + + +def fut_fee(exchange: str, fees: dict | None = None, innovation: bool = False) -> float: + """The perp taker rate: the engine's table if given, else measured from the user's real fills where known + (MEXC charges them 0.08 %), else the exchange's base rate. `innovation`: the coin is in the exchange's + Innovation Zone, which has its own rate (Bybit 0.11 %).""" + if innovation: + if fees and "fut_innovation" in fees.get(exchange, {}): + return fees[exchange]["fut_innovation"] + if exchange in FUT_FEE_INNOVATION: + return FUT_FEE_INNOVATION[exchange] + if fees and exchange in fees: + return fees[exchange]["fut"] + try: + import real_mirror + return real_mirror.FEES.get(exchange.lower()) or FUT_FEE.get(exchange, 0.05) + except Exception: + return FUT_FEE.get(exchange, 0.05) + + +def spot_fee(exchange: str, fees: dict | None = None) -> float: + if fees and exchange in fees: + return fees[exchange]["spot"] + return SPOT_FEE.get(exchange, 0.1) + + +def b_fee(exchange: str, fees: dict | None = None, innovation: bool = False, ss: bool = False) -> float: + """Taker rate of the second leg: B's spot for a spot–spot link, B's perp otherwise.""" + return spot_fee(exchange, fees) if ss else fut_fee(exchange, fees, innovation) + + +def link_key(base: str, a: str, b: str, ss: bool = False) -> str: + return f"{base}|{a}|{b}" + ("|ss" if ss else "") + + +KIND_NAMES = {"sf": "спот → фьюч", "in": "внутри биржи", "ss": "спот → спот"} + + +def kind_of(a: str, b: str, ss: bool) -> str: + return "ss" if ss else "in" if a == b else "sf" + + +def default_fees() -> dict: + try: + import real_mirror + measured = set(real_mirror.FEES) + except Exception: + measured = set() + out = {ex: {"spot": spot_fee(ex), "fut": fut_fee(ex), "spot_src": "", + "fut_src": "по реальным сделкам" if ex.lower() in measured else ""} for ex in arb.EXCHANGES} + for ex, rate in FUT_FEE_INNOVATION.items(): + out[ex].update(fut_innovation=rate, fut_innovation_src="") + return out + + +FEE_LEGS = ("spot", "fut", "fut_innovation") + + +@dataclass +class CrossSettings: + running: bool = False + amount: float = 100.0 # $ spent on spot (A); the same coins shorted on the perp (B) + # THE entry criterion: net profit % if the gap returns to its usual level = + # (gap now − usual) − exit margin − the four taker fees of the two exchanges + min_net_pct: float = 0.2 + max_gap_pct: float = 10.0 # above: a broken price or a different token + history_min: float = 15.0 # minutes of watching the pair before its «usual» is trusted + exit_over_usual_pct: float = 0.05 # close when the gap is back to (usual at the entry + this) + stop_widen_pct: float = 2.0 # close at a loss when the gap widens this much over the entry (0 = off) + max_hold_hours: float = 24.0 # close after this long whatever the gap (0 = off) + cooldown_s: float = 300.0 + min_turnover: float = 200000.0 # 24h turnover of each leg, $ + use_bybit: bool = True # an exchange switched off is neither searched nor traded + use_binance: bool = False + use_mexc: bool = True + use_htx: bool = True + use_gate: bool = True + search_sf: bool = True # spot of A → perp of B between exchanges + search_in: bool = True # spot → perp inside one exchange + search_ss: bool = True # spot of A → spot of B (real: needs the coin's stock on B) + real: bool = False # new trades as real orders with the API keys of both exchanges + auto_transfer: bool = True # USDT moved between spot and futures WITHIN an exchange when one is short + entry_limit: bool = True # real entry: LIMIT short at the signal's perp bid on B first, then spot on A + limit_hold_s: float = 10.0 # …kept this long, then removed (nothing bought if it did not fill) + fees_auto: bool = True # after a real trade the fee rates become what the exchanges charged + exit_hold_s: float = 3.0 # «back to usual» closes only after the gap has stayed there this long (0 = at once) + max_spread_pct: float = 0.5 # a leg whose bid–ask spread is wider is not traded (0 = no check) + entry_ioc: bool = True # real: the first leg is a limit order at the confirmed price, the rest cancelled + confirm_ms: float = 400.0 # real: the signal is checked twice on the order books, this far apart + min_liq_pct: float = 50.0 # no short whose liquidation would be less than this % above the entry + liq_close_pct: float = 20.0 # close both legs when the price is this close to the liquidation, % (0 = off) + block_negative_funding: bool = True # do not open a short-futures hedge when funding is negative + negative_funding_before_minutes: float = 60.0 # block negative funding only this long before settlement + min_funding_pct: float = -1.0 # block entry when funding is below this rate, per funding interval + simulation_execution_delay_ms: float = 600.0 # paper orders fill this long after the signal + simulation_entry_delay_ms: float = 600.0 + simulation_exit_delay_ms: float = 600.0 + + +@dataclass +class CrossPosition: + uid: int + base: str + spot_ex: str + fut_ex: str + spot_symbol: str + fut_symbol: str + opened: float + qty: float # coins shorted on B (real: rounded to B's lot) + spot_entry: float + fut_entry: float + entry_gap: float + usual: float # the usual gap at the entry: the level the position waits for + fees: float + next_funding: float + funding: float = 0.0 + # real positions: the coins held on A, the close in progress (short bought back first, then the spot sold) + real: bool = False + spot_qty: float = 0.0 + closing: str = "" # "" / "fut_done" + fut_exit: float = 0.0 + exit_fees: float = 0.0 + retry_at: float = 0.0 + error: str = "" + sold_coins: float = 0.0 + sold_value: float = 0.0 + sold_fees: float = 0.0 + exact: bool = True + fills: list = field(default_factory=list) # [exchange, fee leg, fee $, value $, exact] of every order + innovation: bool = False # the perp is in B's Innovation Zone: its own fee rate + liq_price: float = 0.0 # liquidation price of the short on B, per coin (the exchange's when it reports one) + liq_calc: float = 0.0 # the program's own estimate at the entry + liq_src: str = "" # "биржа" / "расчёт" + liq_checked: float = 0.0 # when the exchange's figure was last read + ss: bool = False # spot–spot: the B leg is a sale of the stock on B's spot (fut_* = B's spot) + # the prices the decisions were taken at: [time, A price, B price, gap %] — to compare with the fills + entry_signal: list = field(default_factory=list) # A ask, B bid confirmed right before the entry orders + exit_signal: list = field(default_factory=list) # A bid, B ask when the close was decided + exit_since: float = 0.0 # when the gap last came back to the usual level (0 = it is not there now) + close_buy: dict = field(default_factory=dict) # durable spot-stock repurchase; never replay an unknown order + paper_reserve: float = 0.0 # collateral fixed at entry/import; later settings only affect new positions + paper_unrealized: float | None = None # last observed gross PnL minus exit fees; retained when a venue disappears + + @property + def kind(self) -> str: + return kind_of(self.spot_ex, self.fut_ex, self.ss) + + @property + def key(self) -> str: + return link_key(self.base, self.spot_ex, self.fut_ex, self.ss) + + +@dataclass +class CrossTrade: + uid: int + base: str + spot_ex: str + fut_ex: str + opened: float + closed: float + qty: float + spot_entry: float + spot_exit: float + fut_entry: float + fut_exit: float + entry_gap: float + exit_gap: float + usual: float + spot_pnl: float + fut_pnl: float + fees: float + funding: float + net: float + reason: str + amount: float + real: bool = False + exact: bool = True + kind: str = "sf" + entry_signal: list = field(default_factory=list) # [time, A ask, B bid, gap %] of the entry decision + exit_signal: list = field(default_factory=list) # [time, A bid, B ask, gap %] of the close decision + + +@dataclass +class Link: + """One coin, spot on A, perp on B (or B's spot for a spot–spot link), at this moment (prices per coin).""" + base: str + spot_ex: str + fut_ex: str + spot_symbol: str + fut_symbol: str + spot_bid: float + spot_ask: float + fut_bid: float + fut_ask: float + spot_depth: float | None # $ at the spot ask + fut_depth: float | None # $ at the perp bid + spot_turnover: float + fut_turnover: float + funding: float # per interval, fraction + interval_h: float + fut_mult: float = 1.0 # coins in one unit of the perp symbol (1000PEPE → 1000) + innovation: bool = False # the perp is in B's Innovation Zone (Bybit): a higher fee rate + ss: bool = False # spot–spot: fut_* are B's SPOT prices / symbol + + @property + def fut_leg(self) -> str: + """Which fee rate of B applies: B's spot (spot–spot), "fut_innovation" for an Innovation Zone coin, else + "fut".""" + return "spot" if self.ss else "fut_innovation" if self.innovation else "fut" + + @property + def kind(self) -> str: + return kind_of(self.spot_ex, self.fut_ex, self.ss) + + @property + def key(self) -> str: + return link_key(self.base, self.spot_ex, self.fut_ex, self.ss) + + @property + def entry_gap(self) -> float: + return (self.fut_bid / self.spot_ask - 1) * 100 + + @property + def exit_gap(self) -> float: + return (self.fut_ask / self.spot_bid - 1) * 100 + + @property + def mid_gap(self) -> float: + return ((self.fut_bid + self.fut_ask) / (self.spot_bid + self.spot_ask) - 1) * 100 + + +def build_links(spots: list, futs: list, exchanges: set[str], + innovation: set[str] | frozenset = frozenset(), kinds=("sf", "in", "ss")) -> dict[str, Link]: + """Every link of the five exchanges' quotes: spot on A with a perp on B (A ≠ B: «sf», A = B: «in») and spot on + A with spot on B (A ≠ B: «ss»). `innovation`: "exchange|perp symbol" of the Innovation Zone perps.""" + by_base_spot: dict[str, list] = {} + for q in spots: + # a ticker in other letters (龙虾…) cannot be put into the exchanges' signed requests: not traded + if q.exchange in exchanges and q.mult == 1 and q.base.isascii() and \ + not (arb.LEVERAGED.search(q.base) and len(q.base) > 3): + by_base_spot.setdefault(q.base, []).append(q) + by_base_fut: dict[str, list] = {} + for q in futs: + if q.exchange in exchanges: + by_base_fut.setdefault(q.base, []).append(q) + out = {} + for base, ss in by_base_spot.items(): + for s in ss: + if min(s.bid, s.ask) <= 0: + continue + for f in by_base_fut.get(base, []): + kind = "in" if s.exchange == f.exchange else "sf" + if kind not in kinds or min(f.bid, f.ask) <= 0: + continue + link = Link(base, s.exchange, f.exchange, s.symbol, f.symbol, s.bid, s.ask, f.bid, f.ask, s.ask_usd, + f.bid_usd, s.volume_usd or 0.0, f.volume_usd or 0.0, f.funding or 0.0, f.interval_h or 8.0, + f.mult or 1.0, f"{f.exchange}|{f.symbol}" in innovation) + out[link.key] = link + if "ss" not in kinds: + continue + for b in ss: # sold on B's spot from the stock kept there + if b.exchange == s.exchange or min(b.bid, b.ask) <= 0: + continue + link = Link(base, s.exchange, b.exchange, s.symbol, b.symbol, s.bid, s.ask, b.bid, b.ask, s.ask_usd, + b.bid_usd, s.volume_usd or 0.0, b.volume_usd or 0.0, 0.0, 8.0, 1.0, False, ss=True) + out[link.key] = link + return out + + +def close_result(pos: CrossPosition, spot_bid: float, fut_ask: float, + fees_table: dict | None = None) -> tuple[float, float, float, float]: + """(spot leg $, perp leg $, all fees $, net $) of closing at these prices.""" + spot_qty = pos.spot_qty or pos.qty # real: the spot leg can hold a little more than the perp's lot + if pos.closing == "fut_done": # real close half done: the short is already bought back + fut_ask = pos.fut_exit + spot_pnl = spot_qty * (spot_bid - pos.spot_entry) + fut_pnl = pos.qty * (pos.fut_entry - fut_ask) + fees = pos.fees + spot_qty * spot_bid * spot_fee(pos.spot_ex, fees_table) / 100 \ + + pos.qty * fut_ask * b_fee(pos.fut_ex, fees_table, pos.innovation, pos.ss) / 100 + return spot_pnl, fut_pnl, fees, spot_pnl + fut_pnl - fees + pos.funding + + +def round_trip_fee_pct(spot_ex: str, fut_ex: str, fees: dict | None = None, innovation: bool = False, + ss: bool = False) -> float: + return 2 * (spot_fee(spot_ex, fees) + b_fee(fut_ex, fees, innovation, ss)) + + +def net_pct(l: "Link", usual: float | None, s: "CrossSettings", fees: dict | None = None) -> float | None: + """Net profit, % of the amount, if the gap returns to its usual level: (entry gap − usual) − exit margin − + the four taker fees (spot of A in and out, perp of B in and out). None while the usual gap is unknown.""" + if usual is None: + return None + return l.entry_gap - usual - s.exit_over_usual_pct - round_trip_fee_pct(l.spot_ex, l.fut_ex, fees, l.innovation, + l.ss) + + +def _client(exchange: str): + import live + return live.client(exchange.lower()) + + +class ThinBook(Exception): + """The order book holds less than the trade amount at the moment.""" + + +def _quote_now(l: "Link", usd: float) -> tuple[float, float, float, float, float, float]: + """This link from the ORDER BOOKS right now, for a trade of `usd` $, per coin: (A best bid, A average buy price for + the amount, B average sale price for the amount, B best ask, A spread %, B spread %).""" + import fastquote + a = fastquote.execution(l.spot_ex, "spot", l.spot_symbol, usd) + b = fastquote.execution(l.fut_ex, "spot" if l.ss else "fut", l.fut_symbol, usd) + if a["ask"] is None: + raise ThinBook(f"на споте {l.spot_ex} в стакане меньше {usd:g} $") + if b["bid"] is None: + raise ThinBook(f"на {'споте' if l.ss else 'фьючерсе'} {l.fut_ex} в стакане меньше {usd:g} $") + return (a["best_bid"], a["ask"], b["bid"] / l.fut_mult, b["best_ask"] / l.fut_mult, a["spread_pct"], + b["spread_pct"]) + + +def _quote_close(l: Link, usd: float): + import fastquote + a = fastquote.execution(l.spot_ex, "spot", l.spot_symbol, usd) + b = fastquote.execution(l.fut_ex, "spot" if l.ss else "fut", l.fut_symbol, usd) + if a["bid"] is None or b["ask"] is None: + raise ThinBook("недостаточная глубина для закрытия") + return a["bid"], a["best_ask"], b["best_bid"] / l.fut_mult, b["ask"] / l.fut_mult, a["spread_pct"], b["spread_pct"] + + +class CrossEngine: + """One engine per kind of trading: paper (simulation) or real — each started and stopped by itself. The real + one follows the paper one: it is handed the same prices and usual gaps every cycle (no second set of requests).""" + mode = "cross" + + def __init__(self, data_dir: Path = DATA_DIR, start: bool = True, real: bool = False, + leader: "CrossEngine | None" = None, account=None) -> None: + self.is_real = real + self.account = account if not real else None + self.account_error = "" + self.cash_total = 0.0 + self._account_initializing = True + self.key = "cross_real" if real else "cross" + self.file = data_dir / ("basis_cross_real.json" if real else "basis_cross.json") + self.followers: list[CrossEngine] = [] + self.leader: CrossEngine | None = None + self.lock = threading.RLock() + self.settings = CrossSettings() + self.positions: list[CrossPosition] = [] + self.trades: list[CrossTrade] = [] + self.next_uid = 1 + self.last_close: dict[str, float] = {} + self.links: dict[str, Link] = {} + self.usual: dict[str, float] = {} # key → EMA of the mid gap + self.seen_since: dict[str, float] = {} # key → when the pair was first seen (for the history check) + self.last_seen: dict[str, float] = {} + self.status, self.updated, self.cycle_ms = "загружаю цены пяти бирж…", 0.0, 0 + self.ex_status: dict[str, str] = {} + self.fut, self.spot = arb.Fetchers(), arb.SpotFetchers() + self.usual_file = data_dir / "basis_cross_usual.json" + self.usual_saved = 0.0 + self.fast_seen: dict[str, float] = {} # link → when the fast watch last priced it + self.fast_ms = 0 + # fee rates of every exchange, %: {"MEXC": {"spot": .., "fut": .., "spot_src": "", "fut_src": ""}} + self.fees: dict[str, dict] = default_fees() + self.limits: dict[str, int] = {ex: DEFAULT_LIMIT for ex in arb.EXCHANGES} # open trades per exchange + self.innovation: set[str] = set() # "Bybit|SYMBOL" of the Innovation Zone perps + self.innovation_time = 0.0 + # real trading + self.client_for = _client + self.quote_now = _quote_now if start else None # fresh prices right before a real entry (tests: none) + self.quote_close = _quote_close if start else None + self.balances: dict = {} # web_sim's BALANCES (exchange key → account figures) + self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"} + self.opening: set[str] = set() # coins with a real entry in progress + self.paper_opening: set[str] = set() # paper entries waiting for simulated execution + self.paper_closing: set[int] = set() # paper exits waiting for simulated execution + self.jobs: queue.Queue = queue.Queue() + self.busy: set[int] = set() # real positions whose close is being sent right now + self.real_block: dict[str, tuple[str, float]] = {} # coin → (why it cannot be traded for real, until) + self.real_pause_until, self.real_pause_reason = 0.0, "" + self.pending: dict[str, dict] = {} # coin → real entry in progress (written BEFORE any order) + self.recover: dict[str, dict] = {} # pending entries found after a restart + self.funds_low: dict[str, str] = {} # exchange → why it is out of the search (too little money) + self.migrated: list[str] = [] # single-exchange tabs whose positions were taken over + self.cand: dict[str, dict] = {} # key → its row from the last cycle (+ hot refreshes) + self.cand_time = 0.0 + self.hot: list[str] = [] # links with a net profit > 0, priced every HOT_S + if real and not self.file.exists(): + self._seed_from(data_dir / "basis_cross.json") # the first real engine starts from the paper settings + self._load() + self.settings.real = real # fixed by the tab, not a setting + self._migrate_venues(data_dir) + if leader is None: + self._load_usual() + else: # the same learnt gaps, the same price list + self.leader = leader + self.usual, self.seen_since, self.last_seen = leader.usual, leader.seen_since, leader.last_seen + self.innovation = leader.innovation + leader.followers.append(self) + self._account_initializing = False + if self.account is not None and not self.account_error: + from virtual_account import AccountError + try: + registered = self.account.restore("cross") + if registered is None: + unrealized = self._unrealized() + self.account.commit("cross", self._state(), cash_total=self.cash_total, + reserved=self._reserved(), unrealized=unrealized, + allow_existing=True, event="Подключение бумажного арбитража") + elif self._state() != registered: + # Newly discovered legacy venues must reserve their exposure before any worker starts. + self.save(event="Арбитраж: импорт сохранённых позиций") + except AccountError as exc: + self.account_error = str(exc) + self.settings.running = False + if start: + if leader is None: + threading.Thread(target=self._loop, daemon=True).start() + threading.Thread(target=self._hot_loop, daemon=True).start() + threading.Thread(target=self._fast_loop, daemon=True).start() + threading.Thread(target=self._worker, daemon=True).start() + import basis + basis.ENGINES.append(self) + + # --- persistence ----------------------------------------------------------------------------------------- + def _load(self) -> None: + d = None + if self.account is not None: + from virtual_account import AccountError + try: + d = self.account.restore("cross") + except AccountError as exc: + self.account_error = str(exc) + try: + if d is None: + d = json.loads(self.file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + self._load_state(d) + if self.account_error: + self.settings.running = False + + def _load_state(self, d: dict) -> None: + known = {f.name for f in fields(CrossSettings)} + for k, v in (d.get("settings") or {}).items(): + if k in known: + setattr(self.settings, k, type(getattr(self.settings, k))(v)) + self.settings.use_binance = False + import basis + self.settings.max_gap_pct = min(self.settings.max_gap_pct, basis.HARD_MAX_GAP_PCT) + for ex, f in (d.get("fees") or {}).items(): + if ex in self.fees: + self.fees[ex].update({k: f[k] for leg in FEE_LEGS for k in (leg, f"{leg}_src") + if k in f and leg in self.fees[ex]}) + # open trades per exchange; before, one limit for all: it becomes the limit of every exchange + old = (d.get("settings") or {}).get("max_positions") + for ex in self.limits: + v = (d.get("limits") or {}).get(ex, old) + if v is not None: + self.limits[ex] = int(v) + self.positions = [CrossPosition(**p) for p in d.get("positions", [])] + for pos in self.positions: + if not pos.real and pos.paper_reserve <= 0: + pos.paper_reserve = self._position_reserve(pos) + self.trades = [CrossTrade(**t) for t in d.get("trades", [])] + self.next_uid = d.get("next_uid", 1) + self.baseline = d.get("baseline") or {} + self.recover = dict(d.get("pending") or {}) + self.migrated = list(d.get("migrated") or []) + self.last_close = dict(d.get("last_close") or {}) + self.cash_total = float(d.get("cash_total", sum(p.funding - p.fees for p in self.positions if not p.real))) + + def _seed_from(self, paper_file: Path) -> None: + """The real engine's first settings, fee table and limits: those of the simulation (stopped).""" + try: + d = json.loads(paper_file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + settings = {**(d.get("settings") or {}), "running": False, "real": True} + self.file.parent.mkdir(exist_ok=True) + self.file.write_text(json.dumps({"settings": settings, "fees": d.get("fees") or {}, + "limits": d.get("limits") or {}, "next_uid": d.get("next_uid", 1), + "migrated": []}, ensure_ascii=False, indent=1), encoding="utf-8") + + def elsewhere(self, base: str) -> str: + """Another engine of the same kind (paper / real) already trading this coin — "" if none. Paper and real + are independent of each other.""" + import basis + for e in list(basis.ENGINES): + if e is not self and getattr(e, "is_real", None) == self.is_real and \ + (any(p.base == base for p in list(e.positions)) or base in getattr(e, "opening", set())): + return "другой движок" + return "" + + VENUE_FILES = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC", "htx": "HTX", "gate": "Gate"} + + def _migrate_venues(self, data_dir: Path) -> None: + """The spot–futures tabs of single exchanges are now the «inside one exchange» links of this mode: their + open positions (real ones included — the program keeps closing them) and their closed trades move here, and + the old file is renamed so it is never read again.""" + moved, done = [], False + for key, ex in self.VENUE_FILES.items(): + f = data_dir / f"basis_{key}.json" + if key in self.migrated: + continue + try: + d = json.loads(f.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + done = True + self.migrated.append(key) + old_exit = float((d.get("settings") or {}).get("exit_gap_pct", 0.05)) + for p in d.get("positions", []): + if bool(p.get("real", False)) != self.is_real: # paper ones to the simulation, real ones here + continue + # the old rule closed at «gap ≤ exit_gap_pct»: the same level here (usual + exit margin) + pos = CrossPosition( + self.next_uid, p["base"], ex, ex, "", p.get("fut_symbol", ""), p["opened"], p["qty"], + p["spot_entry"], p["fut_entry"], p["entry_gap"], old_exit - self.settings.exit_over_usual_pct, + p.get("fees", 0.0), p.get("next_funding", 0.0), p.get("funding", 0.0), real=p.get("real", False), + spot_qty=p.get("spot_qty", 0.0), closing=p.get("closing", ""), fut_exit=p.get("fut_exit", 0.0), + exit_fees=p.get("exit_fees", 0.0), retry_at=p.get("retry_at", 0.0), error=p.get("error", ""), + sold_coins=p.get("sold_coins", 0.0), sold_value=p.get("sold_value", 0.0), + sold_fees=p.get("sold_fees", 0.0), exact=p.get("exact", True), + innovation=p.get("innovation", False)) + self.next_uid += 1 + if not pos.real: + pos.paper_reserve = self._position_reserve(pos) + self.positions.append(pos) + if self.account is not None: + self.cash_total += pos.funding - pos.fees + moved.append(f"{p['base']} ({ex}{', реальная' if pos.real else ''})") + for t in d.get("trades", []): + if bool(t.get("real", False)) != self.is_real: + continue + self.trades.append(CrossTrade( + self.next_uid, t["base"], ex, ex, t["opened"], t["closed"], t["qty"], t["spot_entry"], + t["spot_exit"], t["fut_entry"], t["fut_exit"], t["entry_gap"], t["exit_gap"], 0.0, t["spot_pnl"], + t["fut_pnl"], t["fees"], t["funding"], t["net"], t["reason"], t.get("amount", 0.0), + real=t.get("real", False), exact=t.get("exact", True), kind="in")) + self.next_uid += 1 + self.trades.sort(key=lambda t: t.closed) + if d.get("pending") and self.is_real: + self._journal("—", "open", False, f"{ex}: незавершённый вход из старой вкладки ({', '.join(d['pending'])})" + f" не перенесён — проверьте баланс монет на {ex}") + if done: + self.save() + if moved: + self._journal("—", "open", True, "позиции вкладок «Спот-фьюч» отдельных бирж перенесены в «Арбитраж · " + f"{'реальная торговля' if self.is_real else 'симуляция'}» (внутри биржи): " + ", ".join(moved)) + + def _load_usual(self) -> None: + """The usual gaps learnt before a restart, if they are recent (otherwise 15 min of watching again).""" + try: + d = json.loads(self.usual_file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + if time.time() - d.get("time", 0) > 600: + return + self.usual, self.seen_since, self.last_seen = d.get("usual", {}), d.get("since", {}), d.get("seen", {}) + + def _save_usual(self, now: float) -> None: + if now - self.usual_saved < 60: + return + self.usual_saved = now + try: + self.usual_file.parent.mkdir(exist_ok=True) + tmp = self.usual_file.with_suffix(".tmp") + tmp.write_text(json.dumps({"time": now, "usual": self.usual, "since": self.seen_since, + "seen": self.last_seen}), encoding="utf-8") + tmp.replace(self.usual_file) + except OSError: + pass + + def _state(self) -> dict: + # Legacy/manual paper positions acquire their fixed reserve before the recovery snapshot is serialized. + if self.account is not None: + self._reserved() + data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions], + "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}, "last_close": self.last_close} + if self.account is not None: + data["cash_total"] = self.cash_total + return data + + def _position_reserve(self, pos: CrossPosition) -> float: + notional = pos.qty * pos.fut_entry + return pos.qty * pos.spot_entry + (notional if pos.ss else + max(notional * self.FUT_NEED, equity_for(self.settings.min_liq_pct, notional))) + + def _reserved(self) -> float: + total = 0.0 + for pos in self.positions: + if pos.real: + continue + if pos.paper_reserve <= 0: + pos.paper_reserve = self._position_reserve(pos) + total += pos.paper_reserve + return total + + def _unrealized(self) -> float: + total = 0.0 + for pos in self.positions: + if pos.real: + continue + link = self.links.get(pos.key) + if link is not None or pos.paper_unrealized is None: + bid, ask = (link.spot_bid, link.fut_ask) if link else (pos.spot_entry, pos.fut_entry) + _, _, _, net = close_result(pos, bid, ask, self.fees) + # entry fees/funding already changed cash; quote loss must survive outages/settings/restarts. + pos.paper_unrealized = net + pos.fees - pos.funding + total += pos.paper_unrealized + return total + + def _mark_account(self, snapshot_fresh: bool = False) -> None: + now = time.time() + if self.account is not None and all( + p.key in self.links and (snapshot_fresh or now - max(self.updated, self.fast_seen.get(p.key, 0)) <= 30) + for p in self.positions if not p.real): + self.account.mark("cross", self._unrealized()) + + def save(self, event: str = "") -> bool: + unrealized = self._unrealized() if self.account is not None else 0.0 + data = self._state() + shared = self.account is not None and not self._account_initializing + if shared: + from virtual_account import AccountError + try: + self.account.commit("cross", data, cash_total=self.cash_total, + reserved=self._reserved(), unrealized=unrealized, event=event) + except AccountError as exc: + try: + saved = self.account.restore("cross") + if saved is not None: + self._load_state(saved) + except AccountError: + pass + self.account_error = str(exc) + self.settings.running = False + return False + try: + self.file.parent.mkdir(exist_ok=True) + atomic_write_json(self.file, data) + except (OSError, ValueError): + if not shared: + raise + # The account owns the authoritative snapshot; a failed compatibility copy cannot undo a commit. + return True + + def set_settings(self, values: dict) -> str: + import math + for name in ('simulation_entry_delay_ms', 'simulation_exit_delay_ms'): + if name in values: + try: + value = float(values[name]) + if not math.isfinite(value) or not 0 <= value <= 60000: + raise ValueError() + except (ValueError, TypeError): + return 'Задержка должна быть от 0 до 60000 мс' + with self.lock: + was = (self.settings.running, self.settings.real) + for f in fields(CrossSettings): + if f.name not in values: + continue + try: + v = values[f.name] + v = (v in (True, "true", "1", 1, "on")) if f.type in ("bool", bool) \ + else type(getattr(self.settings, f.name))(float(v)) + except (TypeError, ValueError): + return f"неверное значение: {f.name}" + setattr(self.settings, f.name, v) + self.settings.real = self.is_real # which tab it is, not a setting + if "fees" in values: + problem = self._set_fees(values["fees"]) + if problem: + return problem + if "limits" in values: + problem = self._set_limits(values["limits"]) + if problem: + return problem + s = self.settings + if s.amount <= 0: + return "сумма должна быть больше 0" + if s.running and s.real and (not was[0] or not was[1]): + self.baseline = {"time": time.time(), "total": None, "by_ex": {}} # «since the start» from here + if set(values) - {"running"}: + self.real_block.clear() # new settings: coins and exchanges are checked anew + self.real_pause_until, self.real_pause_reason = 0.0, "" + import basis + if s.max_gap_pct > basis.HARD_MAX_GAP_PCT: + s.max_gap_pct = basis.HARD_MAX_GAP_PCT + self.save() + return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под " + f"одним тикером). Установлено {basis.HARD_MAX_GAP_PCT:g}%, остальное сохранено") + if not self.save(): + return self.account_error + self.account_error = "" + return "" + + def _set_fees(self, given) -> str: + """Fee rates typed on the page: {"MEXC": {"spot": "0.05", "fut": "0.02"}, …}.""" + if not isinstance(given, dict): + return "неверные комиссии" + new = {} + for ex, legs in given.items(): + if ex not in self.fees or not isinstance(legs, dict): + continue + for leg in FEE_LEGS: + if leg not in legs or leg not in self.fees[ex]: + continue + try: + v = float(legs[leg]) + except (TypeError, ValueError): + return f"неверная комиссия: {ex} {leg}" + if not 0 <= v <= MAX_LEARNED_FEE: + return f"комиссия {ex} должна быть от 0 до {MAX_LEARNED_FEE:g}%" + new[(ex, leg)] = v + for (ex, leg), v in new.items(): + if abs(self.fees[ex][leg] - v) > 1e-9: + self.fees[ex][leg], self.fees[ex][f"{leg}_src"] = v, "вручную" + return "" + + def exchanges(self) -> set[str]: + s = self.settings + return {name for name, on in (("Bybit", s.use_bybit), ("MEXC", s.use_mexc), + ("HTX", s.use_htx), ("Gate", s.use_gate)) if on} + + def has_keys(self, exchange: str) -> bool: + """The exchange has API keys (the balance reader keeps an entry for exactly those exchanges).""" + return exchange.lower() in self.balances + + # --- open trades per exchange: a trade counts on both of its exchanges (spot on A, short on B) --------------- + def limit(self, exchange: str) -> int: + return int(self.limits.get(exchange, DEFAULT_LIMIT)) + + def open_on(self, exchange: str) -> list[str]: + """Coins of the open trades of this mode (real ones in real mode, paper ones otherwise) that use the + exchange, plus a real entry in progress there.""" + real = self.settings.real + out = [p.base for p in self.positions if p.real == real and exchange in (p.spot_ex, p.fut_ex)] + out += [b for b, info in self.pending.items() if exchange in str(info.get("key", "")).split("|")[1:]] + return out + + def full(self, l: Link) -> str: + """Why a new trade on this link must wait (one of its exchanges has its limit of open trades), "" if not.""" + for ex in (l.spot_ex, l.fut_ex): + held = self.open_on(ex) + if len(held) >= self.limit(ex): + return f"на {ex} открыто сделок {len(held)} из {self.limit(ex)} ({', '.join(held) or '—'}) — ждёт закрытия" + return "" + + def _set_limits(self, given) -> str: + if not isinstance(given, dict): + return "неверные лимиты" + new = {} + for ex, v in given.items(): + if ex not in self.limits: + continue + try: + n = int(float(v)) + except (TypeError, ValueError): + return f"неверный лимит сделок: {ex}" + if not 0 <= n <= 100: + return f"лимит сделок {ex} должен быть от 0 до 100" + new[ex] = n + self.limits.update(new) + return "" + + SPOT_NEED, FUT_NEED = 1.01, 1.03 # × the amount: the spot buy (+ fee) / the short's margin (leverage 1) + + def funds(self, exchange: str) -> dict | None: + """Can the exchange take a leg of a real trade of «Сумма» now? {"spot": bool (buy the coin, role A), + "fut": bool (short, role B), "free": $, "need": $}; None while its free USDT is not known. + With the auto-transfer (or one unified account) both accounts of the exchange count for either leg.""" + b = self.balances.get(exchange.lower()) + f = (b or {}).get("free") + if not isinstance(f, dict): + return None + s = self.settings + spot, fut = float(f.get("spot") or 0), float(f.get("futures") or 0) + unified = bool(b.get("unified")) + total = spot if unified else spot + fut + pool = unified or s.auto_transfer + need_spot, need_fut = s.amount * self.SPOT_NEED, s.amount * self.FUT_NEED + return {"spot": (total if pool else spot) >= need_spot, "fut": (total if pool else fut) >= need_fut, + "free": total, "free_spot": spot, "free_fut": fut, "need": min(need_spot, need_fut), + "need_spot": need_spot, "need_fut": need_fut, "pool": pool} + + def stock(self, exchange: str, base: str) -> float | None: + """Free coins of `base` on the exchange's spot account (from the balance reader), None when not known.""" + coins = (self.balances.get(exchange.lower()) or {}).get("coins") + return float(coins.get(base, 0.0)) if isinstance(coins, dict) else None + + def _short_of_money(self, l: Link, funds: dict) -> list[str]: + """What a real trade on this link lacks: USDT for the spot buy on A, money for the short on B (or both on + one exchange), or the coin's stock on B for a spot–spot sale.""" + s = self.settings + fa, fb = funds.get(l.spot_ex), funds.get(l.fut_ex) + out = [] + if l.kind == "in": # both legs on one exchange: both needs at once + if fa is not None: + both = fa["need_spot"] + fa["need_fut"] + if (fa["free"] < both) if fa["pool"] else not (fa["spot"] and fa["fut"]): + out.append(f"средств на {l.spot_ex} (обе ноги: нужно {both:.2f} $)") + return out + if fa is not None and not fa["spot"]: + out.append(f"средств на споте {l.spot_ex}") + if l.ss: + have = self.stock(l.fut_ex, l.base) + need = s.amount / l.spot_ask + if have is not None and have < need: + out.append(f"запаса {l.base} на {l.fut_ex} (есть {have:g}, нужно {need:.6g})") + elif fb is not None and not fb["fut"]: + out.append(f"средств на фьючерсах {l.fut_ex}") + return out + + def low_funds(self, exchange: str) -> str: + """Why the exchange is out of the search for now (it cannot take either leg), "" when it can.""" + f = self.funds(exchange) if self.settings.real else None + if f is None or f["spot"] or f["fut"]: + return "" + if f["pool"]: + return f"мало средств: свободно {f['free']:.2f} $, нужно от {f['need']:.2f} $" + return (f"мало средств: спот {f['free_spot']:.2f} $ (нужно {f['need_spot']:.2f}), фьючерсы " + f"{f['free_fut']:.2f} $ (нужно {f['need_fut']:.2f})") + + def _watch_funds(self) -> None: + """Journal when an exchange drops out for lack of money and when it is back (money arrived).""" + for ex in arb.EXCHANGES: + low = self.low_funds(ex) + if bool(low) != bool(self.funds_low.get(ex)): + self._journal("—", "funds", not low, f"{ex}: {low} — выключена из поиска и сделок до пополнения" + if low else f"{ex}: средств достаточно — снова в поиске и сделках") + if low: + self.funds_low[ex] = low + else: + self.funds_low.pop(ex, None) + + # --- data ------------------------------------------------------------------------------------------------ + def _fetch(self) -> tuple[list, list]: + for refresh in (self.fut.refresh_reference, self.spot.refresh_volume): + try: + refresh() + except Exception: + pass + jobs = {} + status = {} + with ThreadPoolExecutor(max_workers=10) as pool: + for ex in arb.EXCHANGES: + jobs[pool.submit(getattr(self.spot, ex.lower()))] = (ex, "спот") + jobs[pool.submit(getattr(self.fut, ex.lower()))] = (ex, "фьюч") + spots, futs = [], [] + for job, (ex, kind) in jobs.items(): + try: + (spots if kind == "спот" else futs).extend(job.result()) + except Exception as exc: + status[f"{ex} {kind}"] = f"нет данных: {str(exc)[:60]}" + self.ex_status = status + return spots, futs + + def _loop(self) -> None: + while True: + start = time.time() + try: + spots, futs = self._fetch() + if time.time() - self.innovation_time > INNOVATION_S: + try: # which Bybit perps pay the Innovation Zone rate + self.innovation = {f"Bybit|{s}" for s in bybit_innovation_symbols()} + self.innovation_time = time.time() + except Exception: + self.innovation_time = time.time() - INNOVATION_S + 300 # again in 5 min + links = build_links(spots, futs, set(arb.EXCHANGES), self.innovation) + with self.lock: + fresh_now = time.time() + for k, seen in self.fast_seen.items(): # the fast watch's prices are newer than this list + if k in links and k in self.links and fresh_now - seen < 2.0: + links[k] = self.links[k] + self.links = links + self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000) + self.status = "ok" + self.learn(self.updated) + self.step(self.updated) + self._save_usual(self.updated) + for e in self.followers: # the real engine: the same prices, its own trades + e.take_prices(links, self) + except Exception as exc: + self.status = f"нет данных: {exc}" + for e in self.followers: + e.status = self.status + time.sleep(max(0.5, POLL_S - (time.time() - start))) + + def take_prices(self, links: dict, leader: "CrossEngine") -> None: + """A follower's cycle: the leader's fresh price list (its own fast prices kept where newer), then its own + exits and entries.""" + with self.lock: + fresh = dict(links) + now = time.time() + for k, seen in self.fast_seen.items(): + if k in fresh and k in self.links and now - seen < 2.0: + fresh[k] = self.links[k] + self.links = fresh + self.innovation = leader.innovation + self.ex_status, self.updated, self.cycle_ms = leader.ex_status, leader.updated, leader.cycle_ms + self.status = "ok" + self.step(self.updated) + + def learn(self, now: float) -> None: + """The usual gap of every pair: an EMA over ~USUAL_WINDOW_S of the mid gap, updated each cycle.""" + alpha_base = POLL_S / USUAL_WINDOW_S + for key, link in self.links.items(): + gap = link.mid_gap + if abs(gap) > 50: # garbage (a different token, a dead book) + continue + prev = self.usual.get(key) + last = self.last_seen.get(key) + if prev is None or last is None or now - last > 600: + self.usual[key], self.seen_since[key] = gap, now # (re)start after a long absence + else: + alpha = min(1.0, alpha_base * max(1.0, (now - last) / POLL_S)) + self.usual[key] = prev + alpha * (gap - prev) + self.last_seen[key] = now + + def history_min(self, key: str, now: float) -> float: + return (now - self.seen_since[key]) / 60 if key in self.seen_since else 0.0 + + # --- trading --------------------------------------------------------------------------------------------- + def candidates(self, now: float, keys=None) -> list[dict]: + """Every link (or only `keys`) with what it would earn and why it is or is not entered now.""" + import basis + s = self.settings + on = self.exchanges() + if s.real: # an exchange without money for either leg: out until topped up + on -= {ex for ex in on if self.low_funds(ex)} + funds = {ex: self.funds(ex) for ex in on} if s.real else {} + kinds = {k for k, flag in (("sf", s.search_sf), ("in", s.search_in), ("ss", s.search_ss)) if flag} + hard_max = min(s.max_gap_pct, basis.HARD_MAX_GAP_PCT) + rows = [] + items = self.links.items() if keys is None else [(k, self.links[k]) for k in keys if k in self.links] + for key, l in items: + if l.spot_ex not in on or l.fut_ex not in on or l.kind not in kinds: + continue + if min(l.spot_turnover, l.fut_turnover) < s.min_turnover: + continue + short = self._short_of_money(l, funds) if s.real else [] + usual = self.usual.get(key) + hist = self.history_min(key, now) + excess = None if usual is None else l.entry_gap - usual + net = net_pct(l, usual, s, self.fees) + depth_ok = all(v is None or v >= s.amount for v in (l.spot_depth, l.fut_depth)) + elsewhere = self.elsewhere(l.base) + no_keys = [ex for ex in (l.spot_ex, l.fut_ex) if s.real and not self.has_keys(ex)] + # the smallest amount the spot of A and the perp of B both accept (paper too: only real-able trades) + m = (minorder.RULES.min_entry_ss(l.spot_ex, l.base, l.spot_ask, l.fut_ex, l.fut_bid, + spot_fee(l.spot_ex, self.fees)) if l.ss else + minorder.RULES.min_entry(l.spot_ex, l.base, l.spot_ask, l.fut_ex, l.fut_symbol, l.fut_bid, + spot_fee(l.spot_ex, self.fees))) + small = minorder.too_small(s.amount, m, l.spot_ex, l.fut_ex, "спот" if l.ss else "фьюч") + # a wide bid–ask spread: the quotes are thin and the fills land far from them (ZCAT 2.8 %, GSTOCKBSC 1.9 %) + spread_a = (l.spot_ask / l.spot_bid - 1) * 100 if l.spot_bid > 0 else 100.0 + spread_b = (l.fut_ask / l.fut_bid - 1) * 100 if l.fut_bid > 0 else 100.0 + wide = (f"широкий спред: {l.spot_ex} {spread_a:.2f}%, {l.fut_ex} {spread_b:.2f}% (макс. {s.max_spread_pct:g}%)" + if s.max_spread_pct > 0 and max(spread_a, spread_b) > s.max_spread_pct else "") + funding_period = max(1.0, l.interval_h * 3600.0) + funding_left = funding_period - (now % funding_period) + funding_pct = l.funding * 100.0 + funding_too_negative = funding_pct < s.min_funding_pct + bad_funding_window = (s.block_negative_funding and l.funding < 0 and + funding_left <= max(0.0, s.negative_funding_before_minutes) * 60.0) + bad_funding = funding_too_negative or bad_funding_window + # either way: −34 % (SIREN MEXC spot vs Gate perp) is as much «two different coins» as +30 000 % (EWT) + fits = (net is not None and hist >= s.history_min and abs(l.entry_gap) <= hard_max + and net >= s.min_net_pct and depth_ok and not elsewhere and not no_keys and not short + and not small and not wide and not bad_funding) + why = ("" if fits else f"уже в сделке: {elsewhere}" if elsewhere + else f"нет API-ключей {', '.join(no_keys)}" if no_keys + else wide if wide + else (f"funding {funding_pct:+.4f}% ниже порога {s.min_funding_pct:+g}%") + if funding_too_negative + else (f"отрицательный funding {funding_pct:+.4f}% — до выплаты " + f"{funding_left / 60:.0f} мин") if bad_funding_window + else small if small + else f"мало {' и '.join(short)} для суммы {s.amount:g} $" if short + else "мало истории" if hist < s.history_min + else f"разница больше ±{basis.HARD_MAX_GAP_PCT:g}% — разные инструменты под одним тикером" + if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT + else "разница больше максимальной (по модулю)" if abs(l.entry_gap) > hard_max + else "чистая прибыль ниже порога" if net is None or net < s.min_net_pct else "мало объёма") + rows.append({"key": key, "link": l, "usual": usual, "excess": excess, "net": net, "history": hist, + "fits": fits, "why": why, "min": m}) + return rows + + def step(self, now: float) -> None: + s = self.settings + self._mark_account(snapshot_fresh=True) + 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 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: + self._watch_funds() + changed = self._check_exits(now) + # every link once per cycle: the table and the entries both use this (the page never recomputes 17 000 + # 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 self.pending or self.recover + or now < self.real_pause_until or self.waiting_baseline(now)) + 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: + self.save(event="Арбитраж: обновление позиций и funding") + + BASELINE_WAIT_S = 60.0 + + def waiting_baseline(self, now: float) -> bool: + """Right after «Старт» of real trading: no entry before the balances of every exchange have been read once + (balances come every 10 s) — otherwise the first trade's fee and slippage land inside the «было» of «С + запуска» and are never counted (ALT, 2026-10-22: entered 7 s after the start, the reference read 10 s + later). An exchange that does not answer holds the entries a minute at most.""" + base = self.baseline + if not base or base.get("total") is not None or now - (base.get("time") or 0) > self.BASELINE_WAIT_S: + return False + self.balance_view(time.time()) # takes the reference as soon as the balances are all there + return base.get("total") is None + + def hot_step(self, keys: list[str], now: float) -> None: + """The hot links have fresh prices: their rows again, and an entry if one of them fits now.""" + with self.lock: + rows = self.candidates(now, keys) + for r in rows: + self.cand[r["key"]] = r + s = self.settings + if s.running and not (s.real and (self.opening or self.pending or self.recover + or now < self.real_pause_until or self.waiting_baseline(now))): + if self._entries(now, rows): + self.save() + + def exit_level(self, pos: CrossPosition) -> tuple[float, float | None]: + """(the usual gap the position closes at, the usual gap now). The usual of the entry, unless the market has + moved it UP since (a regime shift: the old level may never come back) — then the current one; a usual that + went down does not make the exit harder.""" + now_usual = self.usual.get(pos.key) + return (pos.usual if now_usual is None else max(pos.usual, now_usual)), now_usual + + def _check_exits(self, now: float) -> bool: + """Open positions against the latest prices (the market cycle and the fast watch both call this).""" + s = self.settings + changed = False + for pos in list(self.positions): + if not pos.real and pos.uid in self.paper_closing: + continue + l = self.links.get(pos.key) + # Once a real unwind has started it must not depend on a fresh listing or another exit signal. + if pos.real and pos.closing and pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + self.jobs.put(("close", pos.uid, "завершение начатого закрытия")) + continue + if l is None: + continue + while pos.next_funding and now >= pos.next_funding: + funding = pos.qty * (l.fut_bid + l.fut_ask) / 2 * l.funding + pos.funding += funding # the short receives positive funding + if self.account is not None and not pos.real: + self.cash_total += funding + step = l.interval_h * 3600 + pos.next_funding += step + changed = True + gap = l.exit_gap + # «back to usual» must hold `exit_hold_s` without a break: a one-tick spike of one leg (SHROOM: a burst + # of trades on MEXC that was gone 1.4 s later) does not close the position + back = False + level, now_usual = self.exit_level(pos) + if gap <= level + s.exit_over_usual_pct: + if not pos.exit_since: + pos.exit_since = now + back = now - pos.exit_since >= s.exit_hold_s + elif not pos.closing: + pos.exit_since = 0.0 + shifted = (f" (обычная сместилась: при входе {pos.usual:+.2f}%, сейчас {now_usual:+.2f}%)" + if level > pos.usual else "") + reason = ((f"разница вернулась к обычной и держалась {now - pos.exit_since:.1f} с{shifted}" + if s.exit_hold_s > 0 else f"разница вернулась к обычной{shifted}") if back + else "стоп: разница расширилась" if s.stop_widen_pct > 0 and gap >= pos.entry_gap + s.stop_widen_pct + else "время удержания" if s.max_hold_hours > 0 and now - pos.opened >= s.max_hold_hours * 3600 + else "") + if pos.real and pos.closing == "fut_done" and now >= pos.retry_at: + reason = reason or "продажа спота после выкупа шорта" + if pos.qty > 0 and not pos.closing and not pos.ss: # a spot sale on B has no liquidation + to_liq = (pos.liq_price / l.fut_ask - 1) * 100 if pos.liq_price > 0 else None + if to_liq is not None and s.liq_close_pct > 0 and to_liq < s.liq_close_pct: + # the coin has risen: B would liquidate the short and leave the spot on A naked — close now + reason = reason or f"до ликвидации шорта {to_liq:.1f}% < {s.liq_close_pct:g}%" + if pos.real and not reason and now - pos.liq_checked >= LIQ_CHECK_S: + pos.liq_checked = now # cross margin: it moves with B's whole account + self.jobs.put(("liq", pos.uid)) + if not reason: + continue + if pos.real: + if pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + if not pos.exit_signal: # the prices of the decision (a retry keeps the first) + pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap] + self.jobs.put(("close", pos.uid, reason)) + else: + if self._schedule_paper_close(pos.uid, reason): + changed = True + elif self.account_error: + return False + return changed + + def _paper_delay(self, closing: bool = False) -> float: + """Delay used only by the simulator; tests without a running loop stay synchronous.""" + if self.quote_now is None: + return 0.0 + value = self.settings.simulation_exit_delay_ms if closing else self.settings.simulation_entry_delay_ms + return max(0.0, float(value)) / 1000.0 + + def _schedule_paper_close(self, uid: int, reason: str) -> bool: + if uid in self.paper_closing: + return False + self.paper_closing.add(uid) + delay = self._paper_delay(closing=True) + if delay <= 0: + return self._paper_close(uid, reason) + else: + timer = threading.Timer(delay, self._paper_close, args=(uid, reason)) + timer.daemon = True + timer.start() + return True + + def _paper_close(self, uid: int, reason: str) -> bool: + # Fetch outside the engine lock so slow public APIs do not freeze the UI. + with self.lock: + pos = next((p for p in self.positions if p.uid == uid), None) + link = self.links.get(pos.key) if pos else None + if link is not None and self.quote_now is not None: + try: + import dataclasses + sb, sa, fb, fa, _, _ = (self.quote_close or self.quote_now)(link, pos.qty * max(link.spot_bid, link.fut_ask)) + if min(sb, sa, fb, fa) <= 0: + raise ValueError("пустой стакан") + with self.lock: + self.links[link.key] = dataclasses.replace(link, spot_bid=sb, spot_ask=sa, fut_bid=fb, fut_ask=fa) + except Exception: + with self.lock: + self.paper_closing.discard(uid) + return False + with self.lock: + self.paper_closing.discard(uid) + pos = next((p for p in self.positions if p.uid == uid), None) + if pos is None: + return False + l = self.links.get(pos.key) + if l is None: + return False + now = time.time() + if not self._close(pos, l, now, reason): + return False + return self.save() + + def _paper_open(self, base: str, key: str, usual: float, amount: float, signal_time: float) -> bool: + with self.lock: + link = self.links.get(key) + if link is not None and self.quote_now is not None: + link = self._still_good(link, usual, amount) + if link is None: + with self.lock: + self.paper_opening.discard(base) + return False + with self.lock: + self.paper_opening.discard(base) + if self.quote_now is not None: + if not self.settings.running or self.paper_closing: + return False + rows = self.candidates(time.time(), [key]) + if not rows or not rows[0]["fits"]: + return False + if self.account is not None and self.account_error: + return False + if any(p.base == base for p in self.positions) or self.elsewhere(base): + return False + l = self.links.get(key) + if l is None or l.spot_ask <= 0 or l.fut_bid <= 0 or self.full(l): + return False + now = time.time() if self._paper_delay() > 0 else signal_time + qty = amount / l.spot_ask + fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \ + + qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100 + step = l.interval_h * 3600 + liq = 0.0 if l.ss else l.fut_bid * (1 + liq_distance(self.FUT_NEED, 1.0) / 100) + self.positions.append(CrossPosition( + self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, qty, l.spot_ask, + l.fut_bid, l.entry_gap, usual, fee_in, 0.0 if l.ss else (now // step + 1) * step, + innovation=l.innovation, liq_price=liq, liq_calc=liq, liq_src="" if l.ss else "расчёт", ss=l.ss)) + self.positions[-1].paper_reserve = self._position_reserve(self.positions[-1]) + self.next_uid += 1 + if self.account is not None: + self.cash_total -= fee_in + return self.save(event=f"Арбитраж: вход {base}") + + def _entries(self, now: float, rows: list[dict] | None = None) -> bool: + import basis + s = self.settings + if not s.real and self.quote_now is not None and (self.paper_opening or self.paper_closing): + return False + if self.account is not None and self.account_error: + return False + if s.real and any(p.real and p.closing for p in self.positions): + return False + changed = False + busy = {p.base for p in self.positions} | self.opening | self.paper_opening + best: dict[str, dict] = {} + for r in (self.candidates(now) if rows is None else rows): # per coin: the link with the highest net + if r["fits"] and (r["link"].base not in best or r["net"] > best[r["link"].base]["net"]) \ + and not self.full(r["link"]): # a link whose exchange is full gives way to the next one + best[r["link"].base] = r + for r in sorted(best.values(), key=lambda r: -r["net"]): + l = r["link"] + if self.full(l): # filled by an entry made a moment ago in this loop + continue + if l.base in busy or now - self.last_close.get(l.base, 0.0) < s.cooldown_s: + continue + if self.real_block.get(l.base, ("", 0.0))[1] > now: + continue + if self.elsewhere(l.base): + continue # the coin is already in a trade on a spot–futures tab + if s.real: + if self.real_block.get(l.base, ("", 0.0))[1] > now: + continue # known: cannot be traded for real now (lot, instrument…) + self.opening.add(l.base) + self.jobs.put(("open", l, r["usual"], s.amount)) + break # one real entry at a time + self.paper_opening.add(l.base) + delay = self._paper_delay() + if delay <= 0: + if not self._paper_open(l.base, l.key, r["usual"], s.amount, now): + break + else: + timer = threading.Timer(delay, self._paper_open, + args=(l.base, l.key, r["usual"], s.amount, now)) + timer.daemon = True + timer.start() + changed = True + break + busy.add(l.base) + changed = True + return changed + + # --- fast watch of open positions ------------------------------------------------------------------------ + FAST_S = 0.25 + + def _fast_loop(self) -> None: + """While positions are open: spot of A and perp of B of each, several times a second, and the exit rules.""" + import dataclasses + import fastquote + pool = ThreadPoolExecutor(max_workers=8) + while True: + start = time.time() + with self.lock: + watch = {k: self.links[k] for k in (p.key for p in self.positions) + if k in self.links} + if not watch: + time.sleep(0.5) + continue + jobs = {k: (pool.submit(fastquote.spot_top, l.spot_ex, l.spot_symbol), + pool.submit(fastquote.spot_top if l.ss else fastquote.fut_top, l.fut_ex, l.fut_symbol)) + for k, l in watch.items()} + fresh = {} + for k, (sj, fj) in jobs.items(): + try: + sb, sa, _, sau = sj.result() + fb, fa, fbu, _ = fj.result() + except Exception: + continue + l = watch[k] + if min(sb, sa, fb, fa) <= 0: + continue + fresh[k] = dataclasses.replace(l, spot_bid=sb, spot_ask=sa, fut_bid=fb / l.fut_mult, + fut_ask=fa / l.fut_mult) + if fresh: + now = time.time() + with self.lock: + self.links.update(fresh) + for k in fresh: + self.fast_seen[k] = now + self.fast_ms = int((now - start) * 1000) + self._mark_account() + if self._check_exits(now): + self.save(event="Арбитраж: обновление позиций и funding") + time.sleep(max(0.05, self.FAST_S - (time.time() - start))) + + # --- hot watch: links already in profit on paper, priced every HOT_S so an entry point is not missed --------- + HOT_S = 0.5 + HOT_MAX = 8 # links at most (2 price requests each, legs shared are asked once): the exchanges' limits + + def pick_hot(self, engines: list) -> list[str]: + """The links with the highest net profit > 0 of the running engines (not those already in a position).""" + best: dict[str, float] = {} + now = time.time() + for e in engines: + if not e.settings.running: + continue + held = {p.key for p in e.positions} + for k, r in list(e.cand.items()): + if e.settings.real and e.real_block.get(r["link"].base, ("", 0.0))[1] > now: + continue # waiting after a failed book check: no slot for it + if r["net"] is not None and r["net"] > 0 and k not in held: + best[k] = max(best.get(k, -1e9), r["net"]) + return sorted(best, key=lambda k: -best[k])[:self.HOT_MAX] + + def _hot_loop(self) -> None: + import dataclasses + import fastquote + pool = ThreadPoolExecutor(max_workers=8) + while True: + start = time.time() + engines = [self] + self.followers + keys = [k for k in self.pick_hot(engines) if k in self.links] + self.hot = keys + if not keys: + time.sleep(1.0) + continue + legs = {} # (spot?, exchange, symbol) → job: each leg asked once + for k in keys: + l = self.links[k] + legs.setdefault((True, l.spot_ex, l.spot_symbol), None) + legs.setdefault((l.ss, l.fut_ex, l.fut_symbol), None) + jobs = {leg: pool.submit(fastquote.spot_top if leg[0] else fastquote.fut_top, leg[1], leg[2]) for leg in legs} + quotes = {} + for leg, job in jobs.items(): + try: + bid, ask, _, _ = job.result() + if min(bid, ask) > 0: + quotes[leg] = (bid, ask) + except Exception: + pass + now = time.time() + done = [] + for e in engines: + with e.lock: + for k in keys: + l = e.links.get(k) + a, b = quotes.get((True, l.spot_ex, l.spot_symbol)) if l else None, \ + quotes.get((l.ss, l.fut_ex, l.fut_symbol)) if l else None + if not a or not b: + continue + e.links[k] = dataclasses.replace(l, spot_bid=a[0], spot_ask=a[1], fut_bid=b[0] / l.fut_mult, + fut_ask=b[1] / l.fut_mult) + e.fast_seen[k] = now + if e is self: + done.append(k) + e.hot_step(done or keys, now) + time.sleep(max(0.05, self.HOT_S - (time.time() - start))) + + def _close(self, pos: CrossPosition, l: Link, now: float, reason: str) -> bool: + spot_pnl, fut_pnl, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees) + self.trades.append(CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty, + pos.spot_entry, l.spot_bid, pos.fut_entry, l.fut_ask, pos.entry_gap, l.exit_gap, + pos.usual, spot_pnl, fut_pnl, fees, pos.funding, net, reason, + pos.qty * pos.spot_entry, kind=pos.kind)) + self.positions.remove(pos) + self.last_close[pos.base] = now + if self.account is not None: + self.cash_total += net + pos.fees - pos.funding + return self.save(event=f"Арбитраж: закрытие {pos.base}") + return True + + def close(self, uid: int | None) -> str: + with self.lock: + n = real = 0 + for pos in list(self.positions): + if uid is not None and pos.uid != uid: + continue + if pos.real: + if pos.uid not in self.busy: + self.busy.add(pos.uid) + pos.retry_at = 0.0 + self.jobs.put(("close", pos.uid, "вручную")) + real += 1 + continue + l = self.links.get(pos.key) + if l is None: + continue + if self._schedule_paper_close(pos.uid, "вручную"): + n += 1 + elif self.account_error: + return self.account_error + if not self.save(): + return self.account_error + return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "") + + def reset(self) -> str: + with self.lock: + if any(p.real for p in self.positions): + return "есть открытые реальные позиции — сначала закройте их" + if self.account is not None and self.positions: + return "есть открытые бумажные позиции — сначала закройте их, затем сбросьте статистику" + self.positions, self.trades, self.last_close = [], [], {} + self.baseline = {"time": time.time(), "total": None, "by_ex": {}} if self.settings.real else {} + if not self.save(): + return self.account_error + return "статистика сброшена" + + # --- real orders (worker thread; never under the engine lock while waiting for an exchange) ------------------ + def _journal(self, coin: str, action: str, ok: bool, text: str, **extra) -> None: + import real_mirror + real_mirror.journal("basis", "cross", coin, action, ok, text, **extra) + + def _worker(self) -> None: + while True: + self.do_job(self.jobs.get()) + + def do_job(self, job: tuple) -> None: + kind, *args = job + if True: + try: + if kind == "open": + self._real_open(*args) + elif kind == "close": + self._real_close(*args) + elif kind == "recover": + self._recover(*args) + elif kind == "liq": + self._refresh_liq(*args) + except Exception as exc: # the worker must survive anything + base = args[0].base if kind == "open" else args[0] if kind == "recover" else "?" + self._journal(str(base), kind, False, f"сбой: {exc}") + finally: + with self.lock: + if kind == "close": + self.busy.discard(args[0]) + elif kind in ("open", "recover"): + base = args[0].base if kind == "open" else args[0] + self.opening.discard(base) + 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: + """The exchange refuses the symbol to API orders for good (not a passing problem): MEXC 10007 «symbol not + support api», «api trading is not enabled»…""" + e = error.lower() + return "not support api" in e or "10007" in e or "api trading" in e and "not" in e + + def _not_tradable(self, base: str, why: str, seconds: float) -> None: + with self.lock: + known = self.real_block.get(base, ("", 0.0))[0] == why + self.real_block[base] = (why, time.time() + seconds) + self.opening.discard(base) + if not known: + self._journal(base, "open", False, f"не открываю: {why} — ордеров не было") + + BALANCE_PAUSE_S = 900.0 + + def _pause_if_balance(self, error: str, exchange: str) -> None: + if any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно", "не хватает")): + with self.lock: + self.real_pause_until = time.time() + self.BALANCE_PAUSE_S + self.real_pause_reason = (f"не хватает баланса на {exchange} — пополните счёт или уменьшите " + f"«Сумму сделки»") + self._journal("—", "open", False, f"{self.real_pause_reason}; реальные входы на паузе 15 мин") + + def _real_open(self, l: Link, usual: float, amount: float) -> None: + """Short on B first (limit at the signal's bid, or at market), then the same coins bought on spot on A. + Nothing is bought on A when the short did not fill; the short is bought back when A's buy fails.""" + import basis + import live + l = self._still_good(l, usual, amount) + if l is None: + return + if l.ss: + self._real_open_ss(l, usual, amount) + return + s = self.settings + a_fee = spot_fee(l.spot_ex, self.fees) + try: + ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) + min_coins = cb.fut_min_coins(l.fut_symbol) + coins = cb.fut_round(l.fut_symbol, amount / l.spot_ask * (1 - a_fee / 100)) + except (live.LiveError, AttributeError) as exc: + self._not_tradable(l.base, f"нет правил контракта {l.fut_ex}: {exc}", 300) + return + # the same coins on both legs must be worth about the same: otherwise two different instruments + if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT or coins * l.fut_bid > amount * basis.MAX_LEG_RATIO: + self._not_tradable(l.base, f"шорт {coins:g} монет на {l.fut_ex} стоил бы {coins * l.fut_bid:.2f} $ при " + f"сумме {amount:g} $ — разные инструменты под одним тикером", 86400) + return + if coins <= 0 or coins < min_coins: + need = min_coins * l.spot_ask / (1 - a_fee / 100) * 1.02 + self._not_tradable(l.base, f"сумма {amount:g} $ меньше минимального лота фьючерса {l.fut_ex} " + f"({min_coins:g} монет ≈ {need:.2f} $)", 1800) + return + with self.lock: + # last check right before money is spent + held = [x.base for x in self.positions if x.real] + if (l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l) + or any(p.real and p.closing for p in self.positions)): + return + self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, + "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)) + if s.auto_transfer: + # one exchange for both legs: one transfer that leaves enough on spot AND on futures + plan = (((ca, l.spot_ex, amount * 1.01, fut_need),) if l.spot_ex == l.fut_ex else + ((ca, l.spot_ex, amount * 1.01, 0.0), (cb, l.fut_ex, 0.0, fut_need))) + for c, ex, spot_need, fut_need in plan: + try: + moved = live.ensure_usdt(c, spot_need, fut_need) + if moved: + self._journal(l.base, "transfer", True, f"{ex}: {moved}") + except (live.LiveError, AttributeError) as exc: + if "в сумме" in str(exc): + self._journal(l.base, "open", False, f"не открываю: {ex}: {exc} — ордеров не было") + self._pause_if_balance("не хватает", ex) + return + self._journal(l.base, "transfer", False, f"{ex}: перевод не удался: {exc} — пробую без него") + # the liquidation of the short, from B's futures money right before it: far enough above the entry? + try: + fut_money = float(cb.usdt_free()["futures"]) + except (live.LiveError, AttributeError, KeyError, TypeError, ValueError) as exc: + self._not_tradable(l.base, f"не прочитан фьючерсный баланс {l.fut_ex} для расчёта ликвидации: {exc}", 120) + return + to_liq = liq_distance(fut_money, notional) + if to_liq < s.min_liq_pct: + self._not_tradable(l.base, f"ликвидация шорта на {l.fut_ex} была бы всего на {to_liq:.0f}% выше входа " + f"(на фьючерсах {fut_money:.2f} $ при шорте {notional:.2f} $, нужно " + f"{equity_for(s.min_liq_pct, notional):.2f} $ для запаса " + f"{s.min_liq_pct:g}%)", 300) + return + # 1) the short on B + shorted, fut_price, fut_fee_usd, fut_exact = 0.0, 0.0, 0.0, True + if s.entry_limit or s.entry_ioc: + # a limit order at the confirmed price (the average sale price of the amount in B's book): it fills + # only at that price or better. IOC: looked at once, the rest cancelled at once — a gap that has gone + # 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 + try: + st = cb.fut_order_status(l.fut_symbol, oid) + except live.LiveError: + pass + if st["final"] or st["coins"] >= coins * 0.999 or time.time() >= end: + break + time.sleep(1.0) + if not st["final"]: + 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 + except live.LiveError as exc: + held = 0.0 + if getattr(exc, "sent", False): + try: + held = max(0.0, -cb.fut_position(l.fut_symbol)) + 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() + self._pause_if_balance(str(exc), l.fut_ex) + 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) + except live.LiveError as exc: + bought = 0.0 + if getattr(exc, "sent", False): + try: + bought = min(ca.spot_free(l.base), shorted * 1.02) + except live.LiveError: + bought = 0.0 + if bought <= 0: + 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: + free = 0.0 + held = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100) + mismatch = shorted > held + max(1e-12, shorted * 1e-8) + with self.lock: + step = l.interval_h * 3600 + now = time.time() + pos = CrossPosition(self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, shorted, + buy.price, fut_price, (fut_price / buy.price - 1) * 100, usual, + buy.fee_usd + fut_fee_usd, (now // step + 1) * step, real=True, spot_qty=held, + exact=buy.exact and fut_exact, innovation=l.innovation, + liq_price=fut_price * (1 + to_liq / 100), liq_calc=fut_price * (1 + to_liq / 100), + liq_src="расчёт", liq_checked=now, + entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], + fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact], + [l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]]) + if mismatch: + # Persist the unwind before any close request. A restart must never adopt an uncovered short. + pos.closing = "hedge_mismatch" + pos.error = f"частичный хедж: спот {held:g}, шорт {shorted:g}; закрываю обе ноги" + self.next_uid += 1 + self.positions.append(pos) + self.pending.pop(l.base, None) + self.save() + if mismatch: + self._journal(l.base, "open", False, pos.error) + self._real_close(pos.uid, "частичный хедж") + return + self._journal(l.base, "open", True, f"шорт {shorted:g} на {l.fut_ex} по {fut_price:.10g}, спот {held:g} на " + f"{l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% (обычная {usual:+.3f}%), " + f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount) + self._refresh_liq(pos.uid, first=True) + + CONFIRM_CHECKS = 2 + BOOK_BLOCK_S = 120.0 # a wide spread / thin book at the check: the coin is not tried again for this long + SIGNAL_BLOCK_S = 30.0 # the gap was gone at the check + + def _still_good(self, l: Link, usual: float, amount: float) -> Link | None: + """The signal came from the market cycle's list (tickers, seconds old): before real orders it is confirmed + on the ORDER BOOKS twice, `confirm_ms` apart — each time the whole amount priced through the book (the + average buy price on A, the average sale price on B), both spreads within «Макс. спред», and the net profit + above the threshold. A gap that is only a lagging ticker on a fast move does not survive this.""" + import dataclasses + if self.quote_now is None: + return l + s = self.settings + fresh = l + for check in range(1, self.CONFIRM_CHECKS + 1): + if check > 1: + time.sleep(max(0.0, s.confirm_ms) / 1000) + try: + sb, sa, fb, fa, spread_a, spread_b = self.quote_now(l, amount) + except ThinBook as exc: + why = f"{exc}" + except Exception as exc: + why = f"нет стакана: {str(exc)[:80]}" + else: + why = "" + if min(sb, sa, fb, fa) <= 0: + why = "пустой стакан" + elif s.max_spread_pct > 0 and max(spread_a, spread_b) > s.max_spread_pct: + why = (f"широкий спред: {l.spot_ex} {spread_a:.2f}%, {l.fut_ex} {spread_b:.2f}% " + f"(макс. {s.max_spread_pct:g}%)") + else: + fresh = dataclasses.replace(l, spot_bid=sb, spot_ask=sa, fut_bid=fb, fut_ask=fa) + net = net_pct(fresh, usual, s, self.fees) + if net is None or net < s.min_net_pct: + why = (f"по стакану разница {fresh.entry_gap:+.3f}% (в сигнале {l.entry_gap:+.3f}%), чистая " + f"прибыль {net if net is not None else 0:+.3f}% ниже порога {s.min_net_pct:g}%") + if why: + # the coin waits (the table shows why as «реально нельзя: …»): a wide or thin book does not change + # in a second — without this the next cycle would ask the books again and again + self._not_tradable(l.base, f"по стакану (проверка {check} из {self.CONFIRM_CHECKS}): {why}", + self.BOOK_BLOCK_S if "стакан" in why or "спред" in why else self.SIGNAL_BLOCK_S) + return None + with self.lock: + self.links[l.key] = fresh + self.fast_seen[l.key] = time.time() + return fresh + + def _real_open_ss(self, l: Link, usual: float, amount: float) -> None: + """Spot–spot: sell coins from the stock on B's spot first (they are there: nothing can fail half-way on a + missing coin), then buy the same coins on A's spot. A failed buy on A buys the stock back on B at once.""" + import basis + import live + s = self.settings + a_fee, b_fee_pct = spot_fee(l.spot_ex, self.fees), spot_fee(l.fut_ex, self.fees) + coins = amount / l.spot_ask * (1 - a_fee / 100) + if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT: + self._not_tradable(l.base, f"разница {l.entry_gap:.1f}% — разные монеты под одним тикером на " + f"{l.spot_ex} и {l.fut_ex}", 86400) + return + try: + ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) + have = cb.spot_free(l.base) + except (live.LiveError, AttributeError) as exc: + self._not_tradable(l.base, f"не прочитан запас {l.base} на {l.fut_ex}: {exc}", 120) + return + if have < coins: + self._not_tradable(l.base, f"на споте {l.fut_ex} {have:g} {l.base}, а для продажи нужно {coins:.6g} — " + f"положите монету на {l.fut_ex}", 300) + return + with self.lock: + held = [x.base for x in self.positions if x.real] + if (l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l) + or any(p.real and p.closing for p in self.positions)): + return + self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, + "amount": amount, "link": asdict(l), "phase": "prepared"} + self.save() + if s.auto_transfer: + try: + moved = live.ensure_usdt(ca, amount * 1.01, 0.0) + if moved: + self._journal(l.base, "transfer", True, f"{l.spot_ex}: {moved}") + except (live.LiveError, AttributeError) as exc: + if "в сумме" in str(exc): + self._journal(l.base, "open", False, f"не открываю: {l.spot_ex}: {exc} — ордеров не было") + self._pause_if_balance("не хватает", l.spot_ex) + 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() + return + sold = live.Fill(coins, l.fut_bid, coins * l.fut_bid * b_fee_pct / 100, exc.order_id, exact=False) + # 2) buy the same coins on A + try: + buy = ca.spot_buy(l.base, sold.coins * l.spot_ask * (1 + a_fee / 100) * 1.003) + except live.LiveError as exc: + if getattr(exc, "sent", False): + buy = live.Fill(sold.coins, l.spot_ask, sold.coins * l.spot_ask * a_fee / 100, exc.order_id, + exact=False) + 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: + text = (f"{l.base} продан на {l.fut_ex}, на {l.spot_ex} не куплен ({exc}); ЗАПАС НЕ ВЫКУПЛЕН " + f"({exc2}) — купите {sold.coins:g} {l.base} на {l.fut_ex} вручную") + self._journal(l.base, "open", False, text) + with self.lock: + self.last_close[l.base] = time.time() + self._pause_if_balance(str(exc), l.spot_ex) + return + try: + free = ca.spot_free(l.base) + except live.LiveError: + free = 0.0 + got = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100) + with self.lock: + now = time.time() + pos = CrossPosition(self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, + sold.coins, buy.price, sold.price, (sold.price / buy.price - 1) * 100, usual, + buy.fee_usd + sold.fee_usd, 0.0, real=True, spot_qty=got, ss=True, + exact=buy.exact and sold.exact, entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], + fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact], + [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}% " + f"(обычная {usual:+.3f}%)", amount=amount) + + def _refresh_liq(self, uid: int, first: bool = False) -> None: + """The exchange's own liquidation price of the short replaces the estimate (cross margin: it moves with + everything on B's futures account). The first look is compared with the program's estimate.""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or pos.qty <= 0 or pos.closing or pos.ss: + return + try: + liq = self.client_for(pos.fut_ex).fut_liq_price(pos.fut_symbol) + except (live.LiveError, AttributeError): + return + with self.lock: + pos.liq_checked = time.time() + if not liq or liq <= 0: + return + pos.liq_price, pos.liq_src = liq, "биржа" + self.save() + if first and pos.liq_calc: + diff = (liq / pos.liq_calc - 1) * 100 + self._journal(pos.base, "liq", abs(diff) < 10, f"ликвидация шорта на {pos.fut_ex}: биржа {liq:.10g} " + f"(+{(liq / pos.fut_entry - 1) * 100:.0f}% от входа), расчёт {pos.liq_calc:.10g} — " + f"расхождение {diff:+.1f}%") + + def _restore_stock(self, pos: CrossPosition, cb) -> None: + """Buy B's stock once, and release A only after a confirmed fill and the restored balance. + + Spot clients have no common order-status API. An unknown submission therefore remains durable and + requires manual reconciliation: a balance change alone cannot distinguish our order from another trade. + """ + import live + intent = pos.close_buy + if not intent: + l = self.links.get(pos.key) + ask = l.fut_ask if l else pos.fut_entry + usdt = pos.qty * ask * (1 + spot_fee(pos.fut_ex, self.fees) / 100) * 1.003 + before = cb.spot_free(pos.base) + with self.lock: + old_closing = pos.closing + pos.close_buy = {"phase": "submitted", "before": before, "usdt": usdt, + "required": pos.qty, "time": time.time()} + pos.closing = "spot_buy_submitted" + try: + self.save() # no buy unless its durable intent is on disk + except Exception: + pos.close_buy, pos.closing = {}, old_closing + raise + try: + back = cb.spot_buy(pos.base, usdt) + except live.LiveError as exc: + with self.lock: + if exc.sent: + pos.close_buy.update(phase="unknown", order_id=exc.order_id) + else: # certainly unsent: a later attempt is safe + pos.close_buy = {} + self.save() + raise + with self.lock: + pos.close_buy.update(phase="confirmed", fill=asdict(back)) + self.save() + intent = pos.close_buy + if intent.get("phase") != "confirmed": + raise live.LiveError("результат выкупа спота неизвестен; требуется ручная сверка ордера, " + "повторная покупка заблокирована") + back = live.Fill(**intent["fill"]) + required = float(intent["required"]) + restored = cb.spot_free(pos.base) - float(intent["before"]) + tolerance = max(1e-12, required * 1e-8) + if back.coins + tolerance < required: + raise live.LiveError(f"частичный выкуп спота: исполнено {back.coins:g} из {required:g}; " + "требуется ручная сверка, повторная покупка заблокирована") + if restored + tolerance < required: + raise live.LiveError(f"запас спота ещё не восстановлен: получено {max(0.0, restored):g} " + f"из {required:g}; проверяю баланс без повторного ордера") + with self.lock: + pos.fut_exit, pos.exit_fees, pos.closing = back.price, back.fee_usd, "fut_done" + pos.exact = pos.exact and back.exact + pos.fills.append([pos.fut_ex, "spot", back.fee_usd, back.coins * back.price, back.exact]) + self.save() + + def _real_close(self, uid: int, reason: str) -> None: + """Buy the short back on B (reduce-only), make sure B shows no short left, then sell the coins on A.""" + import live + import fastquote + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or not pos.real: + return + # Refresh both executable sides immediately before the first close order. The fast watcher normally + # updates every 250 ms, but its previous snapshot may have been taken before the close job reached here. + # A normal convergence close is postponed when the current executable prices are already losing after fees. + if not pos.closing and reason != "вручную" and "стоп:" not in reason and "ликвидац" not in reason: + try: + l0 = self.links.get(pos.key) + if l0 is not None: + with ThreadPoolExecutor(max_workers=2) as qpool: + sj = qpool.submit(fastquote.spot_top, l0.spot_ex, l0.spot_symbol) + fj = qpool.submit(fastquote.spot_top if l0.ss else fastquote.fut_top, + l0.fut_ex, l0.fut_symbol) + sb, sa, _, _ = sj.result(timeout=3) + fb, fa, _, _ = fj.result(timeout=3) + if min(sb, sa, fb, fa) <= 0: + raise RuntimeError("пустой стакан при повторной проверке закрытия") + l_now = __import__("dataclasses").replace(l0, spot_bid=sb, spot_ask=sa, + fut_bid=fb / l0.fut_mult, fut_ask=fa / l0.fut_mult) + with self.lock: + self.links[pos.key] = l_now + self.fast_seen[pos.key] = time.time() + _, _, _, current_net = close_result(pos, l_now.spot_bid, l_now.fut_ask, self.fees) + if current_net < 0: + with self.lock: + pos.retry_at = time.time() + 1.0 + pos.error = f"закрытие отложено: текущий расчётный net {current_net:+.4f} $" + self.busy.discard(pos.uid) + self.save() + self._journal(pos.base, "close", False, + f"закрытие отложено: по свежему стакану net {current_net:+.4f} $ — сделка остаётся открытой") + return + except Exception as exc: + # If a quote refresh is temporarily unavailable, keep the previous fast snapshot and let the + # existing exchange-side close/retry path handle it. This is also important for venues whose + # public order-book endpoint is unavailable while private order APIs are still reachable. + self._journal(pos.base, "close", False, f"свежий стакан не получен, используется последний снимок: {exc}") + stage = f"выкуп шорта на {pos.fut_ex}" + try: + ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex) + if pos.ss and pos.closing != "fut_done": + stage = f"выкуп монет на споте {pos.fut_ex}" + self._restore_stock(pos, cb) + if pos.closing != "fut_done": + fut_coins, fut_price, fee, exact = 0.0, 0.0, 0.0, True + if pos.qty > 0: + try: + fut = cb.fut_order(pos.fut_symbol, "buy", pos.qty, reduce_only=True) + fut_coins, fut_price, fee, exact = fut.coins, fut.price, fut.fee_usd, fut.exact + except live.LiveError as exc: + if not getattr(exc, "sent", False): + raise + l = self.links.get(pos.key) + fut_coins, fut_price = pos.qty, (l.fut_ask if l else pos.fut_entry) + fee, exact = pos.qty * fut_price * fut_fee(pos.fut_ex, self.fees, pos.innovation) / 100, False + with self.lock: + pos.fut_exit = fut_price if fut_coins else pos.fut_entry + pos.exit_fees, pos.closing = fee, "fut_done" + pos.exact = pos.exact and exact + if fut_coins: + pos.fills.append([pos.fut_ex, "fut_innovation" if pos.innovation else "fut", fee, + fut_coins * fut_price, exact]) + self.save() + stage = f"проверка фьючерса {pos.fut_ex}" + held = cb.fut_position(pos.fut_symbol) if pos.qty > 0 and not pos.ss else 0.0 + if held < -1e-12: + cb.fut_order(pos.fut_symbol, "buy", -held, reduce_only=True) + raise live.LiveError(f"на фьючерсе оставалось {held:+g} — докуплено, проверяю ещё раз") + stage = f"продажа спота на {pos.spot_ex}" + l = self.links.get(pos.key) + price_now = l.spot_bid if l else pos.spot_entry + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0: # more than dust left to sell + free = ca.spot_free(pos.base) + if free * price_now > 1.0: + sell = ca.spot_sell(pos.base, min(free, left)) + with self.lock: + pos.sold_coins += sell.coins + pos.sold_value += sell.coins * sell.price + pos.sold_fees += sell.fee_usd + pos.exact = pos.exact and sell.exact + pos.fills.append([pos.spot_ex, "spot", sell.fee_usd, sell.coins * sell.price, sell.exact]) + self.save() + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0 and ca.spot_free(pos.base) * price_now > 1.0: + raise live.LiveError(f"на споте ещё {left:g} {pos.base} — продам при следующей попытке") + if pos.sold_coins <= 0 and pos.spot_qty * price_now > 1.0: + raise live.LiveError("спот не продан") + except live.LiveError as exc: + with self.lock: + pos.retry_at, pos.error = time.time() + 15, f"{stage}: {exc}" + self.save() + self._journal(pos.base, "close", False, f"{stage}: {exc} — следующая сделка не откроется, пока эта не " + f"закрыта; повтор через 15 с") + return + with self.lock: + now = time.time() + sell_price = pos.sold_value / pos.sold_coins if pos.sold_coins else pos.spot_entry + spot_pnl = pos.sold_value - pos.sold_coins * pos.spot_entry + fut_pnl = pos.qty * (pos.fut_entry - pos.fut_exit) + fees = pos.fees + pos.exit_fees + pos.sold_fees + net = spot_pnl + fut_pnl - fees + pos.funding + exit_gap = (pos.fut_exit / sell_price - 1) * 100 if pos.qty > 0 and sell_price else 0.0 + t = CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty, pos.spot_entry, + sell_price, pos.fut_entry, pos.fut_exit, pos.entry_gap, exit_gap, pos.usual, spot_pnl, + fut_pnl, fees, pos.funding, net, + f"{reason} (реально{'' if pos.exact else ', часть цифр оценочная'})", + pos.spot_qty * pos.spot_entry, real=True, exact=pos.exact, kind=pos.kind, + entry_signal=list(pos.entry_signal), exit_signal=list(pos.exit_signal)) + if pos in self.positions: + self.positions.remove(pos) + self.trades.append(t) + self.last_close[pos.base] = now + learned = self._learn_fees(pos, now) if self.settings.fees_auto else [] + self.save() + first = (f"монеты на споте {pos.fut_ex} выкуплены по {pos.fut_exit:.10g}" if pos.ss else + f"шорт на {pos.fut_ex} выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет)") + self._journal(pos.base, "close", True, f"{first}, спот на {pos.spot_ex} продан по {sell_price:.10g}, итог " + f"{net:+.4f} $, комиссии {fees:.4f} $ ({reason}){self._slippage_text(t)}", net=net) + + @staticmethod + def _slippage_text(t: CrossTrade) -> str: + """The prices of the decisions against the fills: how much each leg lost or won on the way to the exchange.""" + def leg(name, want, got, sell): + if not want or not got: + return "" + d = (got / want - 1) * 100 * (1 if sell else -1) # + = better than decided, − = worse + return f"{name} {want:.8g} → {got:.8g} ({d:+.2f}%)" + parts = [] + if t.entry_signal: + _, a, b, gap = t.entry_signal + parts.append(f"вход: решение при разнице {gap:+.3f}%, факт {t.entry_gap:+.3f}% — " + f"{leg('покупка A', a, t.spot_entry, False)}, {leg('продажа B', b, t.fut_entry, True)}") + if t.exit_signal: + _, a, b, gap = t.exit_signal + parts.append(f"выход: решение при разнице {gap:+.3f}%, факт {t.exit_gap:+.3f}% — " + f"{leg('продажа A', a, t.spot_exit, True)}, {leg('выкуп B', b, t.fut_exit, False)}") + return ("; " + "; ".join(parts)) if parts else "" + if learned: + self._journal(pos.base, "fee", True, "комиссии по этой сделке: " + "; ".join(learned)) + + def _learn_fees(self, pos: CrossPosition, now: float) -> list[str]: + """The rates the exchanges really charged in this trade (fee $ / value $ of its orders, the exchange's own + figures only) become the rates of the table. A zero fee (paid in another token) is not taken: the table + would then promise more than is earned.""" + sums: dict[tuple[str, str], list[float]] = {} + for ex, leg, fee, value, exact in pos.fills: + if exact and value > 0 and fee > 0: + acc = sums.setdefault((ex, leg), [0.0, 0.0]) + acc[0] += fee + acc[1] += value + out = [] + stamp = time.strftime("%d.%m %H:%M", time.localtime(now)) + for (ex, leg), (fee, value) in sums.items(): + rate = fee / value * 100 + if ex not in self.fees or leg not in self.fees[ex] or not 0 < rate <= MAX_LEARNED_FEE: + continue + old = self.fees[ex][leg] + self.fees[ex][leg] = round(rate, 5) + self.fees[ex][f"{leg}_src"] = f"по сделке {pos.base} {stamp}" + name = {"spot": "спот", "fut": "фьюч", "fut_innovation": "фьюч зоны инноваций"}[leg] + out.append(f"{ex} {name} {old:g}% → {rate:.4f}%") + return out + + def _recover(self, base: str, info: dict) -> None: + """After a restart in the middle of an entry: the short on B and the coins on A that were opened become a + real position (estimated prices), which the usual close then takes care of.""" + 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._pending_problem(base, f"незавершённый вход спот-спот {l.spot_ex} → " + f"{l.fut_ex} — проверьте {base} на обеих биржах вручную") + return + try: + ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) + short = max(0.0, -cb.fut_position(l.fut_symbol)) + bought = info.get("buy") or {} + cap = float(bought.get("coins") or info.get("coins") or 0) + coins = min(ca.spot_free(l.base), cap if bought else cap * 1.05) + except live.LiveError as exc: + with self.lock: + self.recover[base] = info # tried again on the next cycle + 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: + now = time.time() + step = l.interval_h * 3600 + pos = CrossPosition(self.next_uid, base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, short, + float(bought.get("price") or l.spot_ask), + float(info.get("fut_price") or l.fut_bid) if short else 0.0, + l.entry_gap, float(info.get("usual") or 0.0), + float(bought.get("fee_usd") or 0) + float(info.get("fut_fee") or 0), + (now // step + 1) * step, real=True, spot_qty=coins, exact=False, + innovation=l.innovation, + error="подхвачено после перезапуска — цены оценочные") + unwind = short <= 0 or short > coins + max(1e-12, short * 1e-8) + if unwind: # one leg / partial hedge: close both legs immediately + pos.retry_at, pos.closing = 0.0, "hedge_mismatch" + pos.error = f"после перезапуска: неполный хедж (спот {coins:g}, шорт {short:g})" + self.next_uid += 1 + self.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}; ведётся программой") + if unwind: + self._real_close(pos.uid, "восстановление частичного хеджа") + + # --- balances -------------------------------------------------------------------------------------------- + def coins_value(self, exchange: str) -> float: + """$ of the coins that real positions of every spot–futures engine hold on this exchange's spot account + (the account figures count USDT only).""" + import basis + total = 0.0 + for e in list(basis.ENGINES) + ([] if self in basis.ENGINES else [self]): + for pos in list(e.positions): + if not getattr(pos, "real", False): + continue + if getattr(pos, "spot_ex", None) is not None: + if pos.spot_ex != exchange: + continue + l = e.links.get(pos.key) + price = l.spot_bid if l else pos.spot_entry + else: + if getattr(getattr(e, "venue", None), "name", "") != exchange: + continue + p = e.pairs.get(pos.base) + price = p.spot_bid if p else pos.spot_entry + total += max(0.0, pos.spot_qty - pos.sold_coins) * price + return total + + def balance_view(self, now: float) -> dict: + """Per exchange: spot USDT, futures USDT (equity), coins of open positions, total — and the change since + trading was started (the first balance read after the start is the reference).""" + on = self.exchanges() + rows, total, newest_ok = [], 0.0, True + for ex in arb.EXCHANGES: + k = ex.lower() + b = self.balances.get(k) + row = {"exchange": ex, "on": ex in on, "keys": b is not None, "spot": None, "futures": None, + "low_funds": self.low_funds(ex) if ex in on else "", + "limit": self.limit(ex), "open_count": len(self.open_on(ex)), + "coins": None, "total": None, "error": "", "age": None, + "fee_spot": self.fees[ex]["spot"], "fee_fut": self.fees[ex]["fut"], + "fee_spot_src": self.fees[ex]["spot_src"], "fee_fut_src": self.fees[ex]["fut_src"], + "fee_fut_innovation": self.fees[ex].get("fut_innovation"), + "fee_fut_innovation_src": self.fees[ex].get("fut_innovation_src", "")} + if b is not None: + vals = b.get("values") or {} + row["error"] = b.get("error", "") + row["age"] = now - b["time"] if b.get("time") else None + if not row["age"] or b["time"] <= (self.baseline.get("time") or 0): + newest_ok = False + unified = vals.get("Единый счёт USDT") + spot = unified if isinstance(unified, (int, float)) else vals.get("Спот USDT") + fut = None if isinstance(unified, (int, float)) else vals.get("Фьючерсы USDT") + row["unified"] = isinstance(unified, (int, float)) + row["spot"] = spot if isinstance(spot, (int, float)) else None + row["futures"] = fut if isinstance(fut, (int, float)) else None + if not row["error"] and isinstance(vals.get("Фьючерсы"), str): + row["error"] = vals["Фьючерсы"] + if row["spot"] is not None: + row["coins"] = self.coins_value(ex) + row["total"] = row["spot"] + (row["futures"] or 0.0) + row["coins"] + total += row["total"] + rows.append(row) + keyed = [r for r in rows if r["keys"]] + base = self.baseline + if base and base.get("total") is None and keyed and newest_ok and all(r["total"] is not None for r in keyed): + with self.lock: # the reference: first full read after the start + base["total"] = total + base["by_ex"] = {r["exchange"]: r["total"] for r in keyed} + base["read"] = now + self.save() + for r in rows: + ref = (base.get("by_ex") or {}).get(r["exchange"]) + r["start"] = ref + r["change_pct"] = (r["total"] - ref) / ref * 100 if ref and r["total"] is not None else None + ref_total = base.get("total") + return {"rows": rows, "total": total if keyed else None, "start_total": ref_total, + "start_time": base.get("time"), + "change_usd": total - ref_total if ref_total and keyed else None, + "change_pct": (total - ref_total) / ref_total * 100 if ref_total and keyed else None} + + # --- view ------------------------------------------------------------------------------------------------ + def view(self) -> dict: + with self.lock: + s, now = self.settings, time.time() + best: dict[str, dict] = {} + # the last cycle's rows (the hot links refreshed every HOT_S); computed here only before the first cycle + source = list(self.cand.values()) if now - self.cand_time < 60 else self.candidates(now) + for r in source: + b = r["link"].base + score = r["net"] if r["net"] is not None else -1e9 + if b not in best or score > best[b]["score"]: + best[b] = {**r, "score": score} + real_open = [p.base for p in self.positions if p.real] + wait_base = s.real and self.waiting_baseline(now) + rows = [] + for r in best.values(): + l = r["link"] + why = r["why"] + block = self.real_block.get(l.base, ("", 0.0)) + if r["fits"]: + full = self.full(l) if l.base not in real_open else "" + why = ("торговля остановлена (кнопка «Старт»)" if not s.running + else f"реально нельзя: {block[0]}" if s.real and block[1] > now + else full if full + else "жду балансы всех бирж после «Старт» — точка отсчёта «С запуска»" if wait_base + else "сейчас открывается другая реальная сделка" if s.real and (self.opening - {l.base}) + else f"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until + else f"пауза по монете после закрытия ({s.cooldown_s:g} с)" + if now - self.last_close.get(l.base, 0) < s.cooldown_s else "") + rows.append({"base": l.base, "spot_ex": l.spot_ex, "fut_ex": l.fut_ex, "kind": l.kind, + "kind_name": KIND_NAMES[l.kind], + "spot_ask": l.spot_ask, "fut_bid": l.fut_bid, "entry_gap": l.entry_gap, + "exit_gap": l.exit_gap, "usual": r["usual"], "excess": r["excess"], + "history": r["history"], "fits": r["fits"], "why": why, + "funding_pct": l.funding * 100, "interval_h": l.interval_h, + "depth": None if l.spot_depth is None or l.fut_depth is None else min(l.spot_depth, l.fut_depth), + "turnover": min(l.spot_turnover, l.fut_turnover), + "net_pct": r["net"], "innovation": l.innovation, + "hot": r["key"] in self.hot or r["key"] in getattr(self.leader, "hot", ()), + "price_age": (now - self.fast_seen[r["key"]]) if r["key"] in self.fast_seen else None, + "min_entry": r["min"]["usd"] if r["min"] else None, + "min_spot": r["min"]["spot"] if r["min"] else None, + "min_fut": r["min"]["fut"] if r["min"] else None, + "fees_pct": round_trip_fee_pct(l.spot_ex, l.fut_ex, self.fees, l.innovation, l.ss), + "spot_url": arb.spot_url(l.spot_ex, l.spot_symbol, l.base), + "fut_url": (arb.spot_url(l.fut_ex, l.fut_symbol, l.base) if l.ss + else arb.exchange_url(l.fut_ex, l.fut_symbol))}) + rows.sort(key=lambda r: -(r["net_pct"] if r["net_pct"] is not None else -1e9)) + positions = [] + for pos in self.positions: + d = asdict(pos) + d.pop("fills", None) + d.update(kind=pos.kind, kind_name=KIND_NAMES[pos.kind]) + level, now_usual = self.exit_level(pos) + d.update(exit_level=level, usual_now=now_usual, exit_target=level + s.exit_over_usual_pct) + l = self.links.get(pos.key) + if l: + _, _, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees) + seen = self.fast_seen.get(pos.key) + d.update(price_age=None if seen is None else now - seen, fast_ms=self.fast_ms) + d.update(liq_pct=(pos.liq_price / l.fut_ask - 1) * 100 if pos.liq_price > 0 else None) + if pos.exit_since and not pos.closing: # counting down to a «back to usual» close + d["exit_held"] = now - pos.exit_since + d.update(gap_now=l.exit_gap, spot_now=l.spot_bid, fut_now=l.fut_ask, net=net, fees_total=fees, + spot_url=arb.spot_url(l.spot_ex, l.spot_symbol, l.base), + fut_url=(arb.spot_url(l.fut_ex, l.fut_symbol, l.base) if l.ss + else arb.exchange_url(l.fut_ex, l.fut_symbol))) + positions.append(d) + # real mode: the figures are those of the real trades only (prices and fees from the exchanges' fills) + closed = [t for t in self.trades if t.real] if s.real else self.trades + opened = [p for p in positions if p.get("real")] if s.real else positions + wins = sum(t.net > 0 for t in closed) + invested = sum(t.amount for t in closed) + stats = {"trades": len(closed), "wins": wins, "net": sum(t.net for t in closed), + "net_pct": sum(t.net for t in closed) / invested * 100 if invested else None, + "fees": sum(t.fees for t in closed), "funding": sum(t.funding for t in closed), + "open": len(opened), "unrealized": sum(p.get("net", 0) for p in opened), + "real": s.real, "exact": all(t.exact for t in closed), + "avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None} + out = {"mode": "cross", "venue": "Арбитраж", "key": "cross", "settings": asdict(s), + "account_error": self.account_error, + "status": self.status, "ex_status": self.ex_status, "updated": self.updated, + "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, + "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 "завершение закрытия: " + ", ".join(p.base for p in self.positions if p.real and p.closing) + if s.real and any(p.real and p.closing for p in self.positions) + else f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)" + if s.real and now < self.real_pause_until else "")} + out["balances"] = self.balance_view(now) + if self.account is not None: + out["virtual_account"] = self.account.view() + return out diff --git a/LinuxServer/deploy.sh b/LinuxServer/deploy.sh new file mode 100644 index 0000000..98d542b --- /dev/null +++ b/LinuxServer/deploy.sh @@ -0,0 +1,192 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +if [[ $EUID -ne 0 ]]; then + echo "Запустите через sudo: sudo $0 example.com admin@example.com" >&2 + exit 1 +fi + +SOURCE_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +APP_DIR="/opt/crypto-scam" +DATA_DIR="/var/lib/crypto-scam" +SERVICE_USER="cryptosim" +NGINX_SITE="/etc/nginx/sites-available/crypto-scam-app" +NGINX_ENABLED="/etc/nginx/sites-enabled/crypto-scam-app" +SERVICE_FILE="/etc/systemd/system/crypto-scam.service" +DOMAIN="${1:-}" +EMAIL="${2:-}" + +if [[ ! "$DOMAIN" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then + echo "Укажите домен, уже направленный DNS-записями на этот сервер: $0 example.com admin@example.com" >&2 + exit 2 +fi +if [[ ! "$EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]]; then + echo "Укажите email для уведомлений Let's Encrypt: $0 example.com admin@example.com" >&2 + exit 2 +fi +if [[ -e "$NGINX_SITE" ]] && ! grep -q 'Managed by Crypto Scam deploy.sh' "$NGINX_SITE"; then + echo "$NGINX_SITE уже занят другой конфигурацией; не перезаписываю его." >&2 + exit 3 +fi +if [[ -e "$NGINX_ENABLED" && "$(readlink -f "$NGINX_ENABLED")" != "$(readlink -m "$NGINX_SITE")" ]]; then + echo "$NGINX_ENABLED уже занят другой конфигурацией; не перезаписываю его." >&2 + exit 3 +fi +if [[ -e "$SERVICE_FILE" ]] && ! grep -q 'Managed by Crypto Scam deploy.sh' "$SERVICE_FILE"; then + echo "$SERVICE_FILE уже занят другой службой; не перезаписываю его." >&2 + exit 3 +fi + +read -r -p "Общий HTTP Basic Auth логин для входа на сайт: " GATE_USER +if [[ -z "$GATE_USER" || "$GATE_USER" == *:* ]]; then + echo "Логин не должен быть пустым или содержать двоеточие." >&2 + exit 2 +fi +read -r -s -p "Общий пароль шлюза (не менее 16 символов): " GATE_PASSWORD +echo +if (( ${#GATE_PASSWORD} < 16 )); then + echo "Для публичного сервера нужен пароль шлюза длиной не менее 16 символов." >&2 + exit 2 +fi + +export DEBIAN_FRONTEND=noninteractive +apt-get update +apt-get install -y nginx certbot python3-certbot-nginx python3-venv python3-tk python3-cryptography rsync apache2-utils + +if ! id "$SERVICE_USER" >/dev/null 2>&1; then + useradd --system --home-dir "$DATA_DIR" --create-home --shell /usr/sbin/nologin "$SERVICE_USER" +fi +install -d -o root -g "$SERVICE_USER" -m 0750 "$APP_DIR" +install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 0700 "$DATA_DIR" +install -d -o root -g "$SERVICE_USER" -m 0750 /etc/crypto-scam + +systemctl stop crypto-scam.service 2>/dev/null || true +rsync -a --exclude '.venv/' --exclude 'web_sim_data/' --exclude '__pycache__/' "$SOURCE_DIR/" "$APP_DIR/" +if [[ -d "$APP_DIR/web_sim_data" && ! -L "$APP_DIR/web_sim_data" ]]; then + cp -a "$APP_DIR/web_sim_data/." "$DATA_DIR/" + mv "$APP_DIR/web_sim_data" "$APP_DIR/web_sim_data.pre-linux-$(date +%Y%m%d%H%M%S)" +fi +ln -sfn "$DATA_DIR" "$APP_DIR/web_sim_data" + +if [[ ! -f /etc/crypto-scam/master.key ]]; then + umask 077 + openssl rand 32 > /etc/crypto-scam/master.key +fi +chown root:"$SERVICE_USER" /etc/crypto-scam/master.key +chmod 0640 /etc/crypto-scam/master.key + +python3 -m venv --system-site-packages "$APP_DIR/.venv" +"$APP_DIR/.venv/bin/python" -m pip install --upgrade pip +"$APP_DIR/.venv/bin/python" -m pip install -r "$APP_DIR/requirements.txt" + +chown -R root:"$SERVICE_USER" "$APP_DIR" +chmod -R u=rwX,g=rX,o= "$APP_DIR" +chown -h root:"$SERVICE_USER" "$APP_DIR/web_sim_data" +chown -R "$SERVICE_USER":"$SERVICE_USER" "$DATA_DIR" +chmod -R u=rwX,g=,o= "$DATA_DIR" + +# Managed by Crypto Scam deploy.sh +cat > "$SERVICE_FILE" < "$NGINX_SITE" < "$NGINX_SITE" < None: + if not hasattr(self, "canvas"): + return + c = self.canvas + c.delete("all") + width, height = c.winfo_width(), c.winfo_height() + if width < 80 or height < 80: + return + left, right, top, bottom = 58, width - 82, 22, height - 34 + c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей") + candles = list(self.candles) + if not candles: + c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…") + return + prices = [p for candle in candles for p in (candle[2], candle[3])] + low, high = min(prices), max(prices) + pad = (high - low) * .08 if high != low else max(high * .001, 1e-8) + low -= pad + high += pad + t0 = candles[0][0] + t1 = max(candles[-1][0] + 60, t0 + 60) + view_end = self.chart_view_end if self.chart_view_end is not None else t1 + view_start = view_end - self.chart_visible_seconds + visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end] + visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end] + if visible_candles: + candles = visible_candles + prices = [p for candle in candles for p in (candle[2], candle[3])] + low, high = min(prices), max(prices) + base_span = high - low + pad = base_span * .08 if base_span else max(high * .001, 1e-8) + natural_low, natural_high = low - pad, high + pad + if self.chart_price_center is None or self.chart_price_span is None: + low, high = natural_low, natural_high + if self.chart_price_center is not None and self.chart_price_span is not None: + span = self.chart_price_span + low = self.chart_price_center - span / 2 + high = self.chart_price_center + span / 2 + t0 = view_start + t1 = view_end + if t1 <= t0: + return + for i in range(5): + y = top + i * (bottom - top) / 4 + value = high - i * (high - low) / 4 + c.create_line(left, y, right, y, fill="#263746") + c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value)) + c.create_line(left, bottom, right, bottom, fill="#6c7e8c") + candle_seconds = self.interval_minutes * 60 + slot = (right - left) * candle_seconds / (t1 - t0) + body_width = max(2.0, min(16.0, slot * .62)) + for candle in candles: + t, open_price, high_price, low_price, close_price = candle + if t < t0 - candle_seconds or t > t1: + continue + x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left) + y_high = bottom - (high_price - low) / (high - low) * (bottom - top) + y_low = bottom - (low_price - low) / (high - low) * (bottom - top) + y_open = bottom - (open_price - low) / (high - low) * (bottom - top) + y_close = bottom - (close_price - low) / (high - low) * (bottom - top) + color = "#38d996" if close_price >= open_price else "#ef5965" + c.create_line(x, y_high, x, y_low, fill=color, width=1) + body_top, body_bottom = sorted((y_open, y_close)) + if body_bottom - body_top < 1: + body_bottom = body_top + 1 + c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color) + for marker_time, marker_price, trade_id in visible_markers: + if not t0 <= marker_time <= t1: + continue + x = left + (marker_time - t0) / (t1 - t0) * (right - left) + y = bottom - (marker_price - low) / (high - low) * (bottom - top) + if top <= y <= bottom: + c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1) + c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}") + position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position + if position and position.mode != strategy.STRATEGY_CLASSIC: + self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, + f"Вход {position.side.upper()}", "#63a8ff") + self._draw_level(c, position.stop_price, low, high, left, right, top, bottom, + "Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42") + if position.partial_target > 0 and not position.partial_done: + self._draw_level(c, position.partial_target, low, high, left, right, top, bottom, + "Частичная фиксация", "#40d6b0") + if position.final_target > 0: + self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0") + liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side) + if liquidation is not None: + self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d") + elif position: + self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff") + s = self.applied_settings or self._safe_read_settings() + if s["add_step"] > 0 and position.add_count < s["max_adds"]: + next_add = position.last_add_price * (1 - s["add_step"] / 100) + self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff") + if s["stop_loss"] > 0: + stop_price = position.entry_price * (1 - s["stop_loss"] / 100) + self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42") + if s["take_profit"] > 0: + effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"])) + take_profit_price = position.entry_price * (1 + effective_tp_pct / 100) + self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0") + if self.last_price: + y = bottom - (self.last_price - low) / (high - low) * (bottom - top) + if top <= y <= bottom: + c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3)) + c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M")) + c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M")) + + def _chart_bounds(self) -> tuple[int, int, int, int]: + width, height = self.canvas.winfo_width(), self.canvas.winfo_height() + return 58, width - 82, 22, height - 34 + + def _on_chart_wheel(self, event: tk.Event) -> None: + direction = 1 if event.delta > 0 else -1 + self._zoom_chart(event.x, event.y, direction) + + def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None: + self._zoom_chart(event.x, event.y, direction) + + def _zoom_chart(self, x: int, y: int, direction: int) -> None: + if not self.candles: + return + old_span = self.chart_visible_seconds + factor = 0.8 if direction > 0 else 1.25 + self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor)) + if self.chart_view_end is None: + self.chart_view_end = self.candles[-1][0] + 60 + left, right, top, bottom = self._chart_bounds() + fraction_x = min(1, max(0, (x - left) / max(1, right - left))) + old_start = self.chart_view_end - old_span + anchor_time = old_start + fraction_x * old_span + self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds + if self.chart_price_center is None or self.chart_price_span is None: + prices = [p for candle in self.candles for p in (candle[2], candle[3])] + center = (max(prices) + min(prices)) / 2 + self.chart_price_center = center + self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8) + fraction_y = min(1, max(0, (y - top) / max(1, bottom - top))) + anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span + self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor) + self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span + self._draw_chart() + + def _on_chart_press(self, event: tk.Event) -> None: + if not self.candles: + return + left, right, top, bottom = self._chart_bounds() + if not left <= event.x <= right or not top <= event.y <= bottom: + return + if self.chart_view_end is None: + self.chart_view_end = self.candles[-1][0] + 60 + if self.chart_price_center is None or self.chart_price_span is None: + prices = [p for candle in self.candles for p in (candle[2], candle[3])] + low, high = min(prices), max(prices) + pad = (high - low) * .08 if high != low else max(high * .001, 1e-8) + self.chart_price_center = (high + low) / 2 + self.chart_price_span = high - low + 2 * pad + self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center, + self.chart_price_span, self.chart_visible_seconds) + self.canvas.configure(cursor="fleur") + + def _on_chart_drag(self, event: tk.Event) -> None: + if not self._drag_anchor: + return + x0, y0, end0, center0, price_span, time_span = self._drag_anchor + left, right, top, bottom = self._chart_bounds() + self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span + self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span + self.chart_price_span = price_span + self._draw_chart() + + def _on_chart_release(self, _event: tk.Event) -> None: + self._drag_anchor = None + self.canvas.configure(cursor="") + + def _reset_chart_view(self, _event: tk.Event | None = None) -> None: + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self.chart_view_end = None + self.chart_price_center = None + self.chart_price_span = None + self._drag_anchor = None + self._draw_chart() + + def _go_to_live(self) -> None: + """Return the chart's right edge to the newest market candle.""" + if self.candles: + self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60 + else: + self.chart_view_end = None + self.chart_price_center = None + self.chart_price_span = None + self._draw_chart() + diff --git a/LinuxServer/desktop_models.py b/LinuxServer/desktop_models.py new file mode 100644 index 0000000..b9ef352 --- /dev/null +++ b/LinuxServer/desktop_models.py @@ -0,0 +1,74 @@ +"""Desktop account and per-symbol state, independent of Tk widgets.""" +from __future__ import annotations +from collections import deque +from dataclasses import dataclass, field +import strategy + +@dataclass +class Position: + trade_id: int + symbol: str + entry_price: float + qty: float + stake: float + entry_fee: float + opened_at: float + last_add_price: float + add_count: int = 0 + # Strategy-mode fields; classic positions keep the defaults. + side: str = "long" + mode: str = strategy.STRATEGY_CLASSIC + leverage: float = 1.0 + stop_price: float = 0.0 + initial_stop: float = 0.0 + atr: float = 0.0 + extreme: float = 0.0 + partial_target: float = 0.0 # 0 = none + final_target: float = 0.0 # 0 = none + partial_done: bool = False + realized_gross: float = 0.0 + realized_fees: float = 0.0 + opened_stake: float = 0.0 + + +@dataclass +class ClosedTrade: + trade_id: int + symbol: str + entry_price: float + exit_price: float + qty: float + gross_pnl: float + fees: float + net_pnl: float + roi_pct: float + opened_at: float + closed_at: float + reason: str + + +@dataclass +class CurrencyState: + """Independent market and position state for one concurrently traded symbol.""" + prices: deque = field(default_factory=deque) + candles: deque = field(default_factory=deque) + entry_markers: deque = field(default_factory=deque) + last_price: float | None = None + baseline_close: float | None = None + last_signal_pct: float | None = None + last_signal_ready: bool = False + previous_entry_signal_pct: float | None = None + live_minute_prices: deque = field(default_factory=deque) + last_ws_message: float = 0.0 + position: Position | None = None + live_position: Position | None = None + live_position_info: dict | None = None + live_order_busy: bool = False + live_transition_pending: bool = False + live_halted: bool = False + # Strategy modes A/B: last evaluated signal candle and the signal valid until the next close. + mode_signal: dict | None = None + mode_signal_bucket: int = 0 + mode_eval_busy: bool = False + + diff --git a/LinuxServer/docs/reliability.md b/LinuxServer/docs/reliability.md new file mode 100644 index 0000000..1dc10eb --- /dev/null +++ b/LinuxServer/docs/reliability.md @@ -0,0 +1,176 @@ +# Recovery and development + +## Shared virtual capital and paper recovery + +`virtual_account.py` owns the web application's paper capital in +`web_sim_data/virtual_account.json`. All simulated coin engines use owners named `coin:`; +the paper arbitrage engine uses `cross`. Real arbitrage, real-signal ledgers, the Tk leader window +and the main desktop account do not draw on this wallet. + +An owner commit stores its complete recovery snapshot, cumulative cash movement and reserved capital +in the same account document. Only the difference from its previous cash total changes the balance. +This keeps a close, fee or funding payment from being credited again after restart. The account's owner +snapshot takes precedence over legacy per-engine files. Coin snapshots include open positions, IDs, +trade history and policy state needed to resume exits; paper arbitrage snapshots include both legs +and their fixed entry reserves. Restoring these positions does not emit a new entry. + +The initial balance is taken once from the old common budget, with a 300 $ default. Migration preserves +existing positions and their reserve even when that reserve exceeds the chosen initial deposit; free +capital then remains zero until the deficit is resolved. Individual legacy starting balances and old +closed profits are not summed into a new deposit. Open-position entry costs are brought into account +cash; the old closed trades remain statistical history. Reopening the same owner does not import it twice. + +| Account figure | Meaning | +| --- | --- | +| `balance` | Initial deposit + subsequent adjustments + settled trading cash movements | +| `equity` | Balance + current unrealized result | +| `reserved` | Total capital reserved by all paper owners | +| `free` | `max(0, min(balance, equity) - reserved)` | +| `realized` | Balance minus net deposits; deposits and withdrawals do not change this result | +| `stale` | Array of owners whose open-position marks are missing or older than 30 seconds | + +Coin reserve is the margin fixed at entry. Spot/futures arbitrage reserves the spot cost plus the greater +of 103% of futures notional and the capital required by the configured liquidation buffer. Spot/spot +arbitrage reserves the capital of both legs. Changing the settings does not release an existing position's +entry reserve. A new or increased reservation must fit the shared capital after fees. Unrealized losses +reduce free capital; unrealized profits do not fund new entries. + +Marks are refreshed only by market data. Saving settings or restoring a checkpoint does not make an old +quote fresh, and one current arbitrage link cannot refresh unrelated positions. If any open owner's mark +is stale, new reservations and withdrawals are refused. Deposits and reductions/settlement remain permitted +by the account, while the trading engine separately checks that it has a usable quote for a paper close. +A restart retains the last known unrealized result but treats its mark as stale until fresh data arrives. + +`GET /api/account`, `state.account` and the paper basis response's `paper_account` expose the same account. +`POST /api/account/adjust` accepts a signed `amount` and a `request_id`; the same ID and amount is idempotent, +including after server restart, while reuse for a different amount is refused. Numeric inputs must be finite; +zero adjustments, booleans and out-of-range amounts are rejected. The API journal returns the newest 100 +entries first. `version` orders persisted changes; `updated_at` also reflects newer in-memory market marks. +The browser uses both to reject older account snapshots arriving through different endpoints. Its pending +adjustment ID is retained in the currently open page for an explicit retry; after reloading the page, inspect +the journal before starting another adjustment. + +Statistics reset cannot erase open shared positions or replenish the account. A coin's web reset is also +refused while real execution is unfinished. Paper and real modes of a coin use separate ledgers: +`signal_.json/.csv` is the private real-signal state, with no shared-account funding gate or paper +entry hooks. Switching modes requires the current exposure, the destination ledger's saved positions and +real pending/recovery work to be clear. The saved mode and active trader are changed only after the new +ledger and mode settings have been saved successfully. + +## Persistence and concurrency + +`persistence.atomic_write_json` writes a unique temporary file in the destination directory, flushes and +fsyncs it, then replaces the old JSON file. Account operations prepare a new document and publish it only +after this write succeeds. Failed account writes leave both account cash and the authoritative owner +snapshot unchanged; the engine restores its previous position/history state instead of reporting a fill. +Unreadable or malformed recovery data is surfaced as an error and blocks entries, rather than silently +starting an independent empty paper account. CSV histories are exports, not the recovery authority for +an owner attached to the shared account. + +`runtime_lock.py` holds an OS file lock on `web_sim_data/engine.lock` for the entire engine lifetime. +It prevents a second engine using the same data directory even if a different HTTP port is requested. +The OS releases the lock when the process exits; the existence of the lock file alone does not mean a +process still owns it. The HTTP port is bound before recovery workers or exchange connections start. + +Within one process, account instances resolving to the same path share an `RLock`; a commit or adjustment +refreshes the latest persisted version while holding that lock before applying its change. Per-engine locks +protect their position/state transitions, and a separate registry lock protects engine lookup and removal. +The account stores snapshots and performs no exchange calls or callbacks into engines while its lock is held. +Atomic replacement does not substitute for these locks: it protects a single file replacement, not two +independent read/modify/write operations. + +## Real orders + +`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. + +Coin removal is a durable workflow in `pending_removals.py`, not an immediate deletion of the connection. +The intent and connection are saved first, new entries stop, and paper/real closes are requested. The engine +and its feeds remain available until paper positions are gone and the real mirror reports no position, +pending state, queued job or storage error. Only then are the connection and removal intent removed and +the engine stopped. Restart merges pending-removal connections back into the managed list, so a crash +between deleting the normal connection and completing the intent does not forget unfinished exposure. + +## Browser boundary + +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. + +Read timers are registered before the initial request, so a failed first fetch cannot permanently prevent +startup. GET requests have bounded timeouts and share one in-flight request per endpoint within the same +context; slow periodic tasks do not queue duplicate rendering work. Switching a coin or venue invalidates +the old read generation and starts a fresh request. Old responses, including old connection failures, cannot +replace the new context. Row close actions carry their original venue or coin. Sequence numbers also reject +older completed poll responses. The scanner checks the selected context before changing the DOM and again +after awaiting its response. + +An error or more than 10 seconds without a successful relevant read disables browser commands and displays +the last-data age. This is distinct from the account's 30-second market-mark rule. GET polling reconnects +automatically; POST commands are never automatically replayed. A lost command response is shown as an +unconfirmed result, requiring inspection of positions/state before an explicit repeat. Business refusals, +including statistics-reset refusals, are displayed instead of discarded. The selected mode and account +scope remain visible. Main arbitrage settings and fee/limit edits have separate Save buttons; switching +between paper and real views keeps their unsaved drafts separate in the current browser page. + +`web/help-data.js` contains the local reference descriptions; `web/help.js` builds a searchable native dialog +from them and the actual settings/modes used by the page. It supports keyboard focus, Escape and returning +focus to the opener. A regression test checks that all declared settings and static controls have help text. + +## Code boundaries + +| Responsibility | Files | +| --- | --- | +| Web layout, styles, behaviour | `web_sim.html`, `web/app.css`, `web/app.js` | +| Searchable help and field descriptions | `web/help.js`, `web/help-data.js` | +| HTTP routing and local browser policy | `web_sim.py`, `web_proxy.py`, `request_security.py` | +| Shared paper cash, owner snapshots and reservations | `virtual_account.py`, `scalp_paper.py`, `cross.py` | +| Single-engine ownership and deferred removal | `runtime_lock.py`, `pending_removals.py` | +| Desktop account models and chart | `desktop_models.py`, `desktop_chart.py` | +| Desktop 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. The CI workflow is configured for Windows with Python 3.11, 3.12 and 3.13; +configuration does not imply that a remote CI run or a real exchange integration has been performed. Browser +preview checks use a separate mocked local API, not a running trading backend. + +Regression cases cover refused/partial rollback, uncertain cancellation and submission, restart before and +after order acceptance, failed disk writes, hostile Host/Origin, response ordering, percentage drawdown and +capital-floor ordering for long/short backtests including fees. Shared-account cases additionally cover +competing coins/arbitrage for one reserve limit, idempotent adjustments and settlement, migration/restart, +stale marks and retained unrealized losses, entry/close rollback on write failure, fixed collateral after +settings changes, reset without creating money, and separation of real signal execution from virtual funding. +Browser tests cover first-fetch recovery, single-flight reads, context invalidation, stale controls, scanner +navigation, refused reset, account snapshot ordering, signed adjustments, retry IDs and help coverage. diff --git a/LinuxServer/fastquote.py b/LinuxServer/fastquote.py new file mode 100644 index 0000000..b1478bf --- /dev/null +++ b/LinuxServer/fastquote.py @@ -0,0 +1,159 @@ +"""Best bid / ask of ONE symbol, fast (public REST, kept-alive connections): used to watch open positions several +times a second, instead of the whole-market lists that take 1–20 s per cycle. + + spot_top(exchange, symbol) -> (bid, ask, bid $ size or None, ask $ size or None) + fut_top(exchange, symbol) -> the same for the USDT perpetual, prices per the symbol's unit (1000PEPE…) + +`exchange` is "Bybit" / "Binance" / "MEXC" / "HTX" / "Gate"; symbols are the exchange's own (as the scanners have them). +""" + +from __future__ import annotations + +import urllib.parse + +from live import LiveError, _http + + +def _f(v) -> float: + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _q(s: str) -> str: + return urllib.parse.quote(s, safe="") + + +def spot_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]: + if exchange == "Bybit": + t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=spot&symbol={_q(symbol)}")["result"]["list"][0] + b, a = _f(t["bid1Price"]), _f(t["ask1Price"]) + return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size")) + if exchange in ("Binance", "MEXC"): + host = "https://api.binance.com" if exchange == "Binance" else "https://api.mexc.com" + t = _http("GET", f"{host}/api/v3/ticker/bookTicker?symbol={_q(symbol)}") + b, a = _f(t["bidPrice"]), _f(t["askPrice"]) + return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty")) + if exchange == "HTX": + t = _http("GET", f"https://api.huobi.pro/market/detail/merged?symbol={_q(symbol.lower())}")["tick"] + return _f(t["bid"][0]), _f(t["ask"][0]), _f(t["bid"][0]) * _f(t["bid"][1]), _f(t["ask"][0]) * _f(t["ask"][1]) + if exchange == "Gate": + t = _http("GET", f"https://api.gateio.ws/api/v4/spot/tickers?currency_pair={_q(symbol)}")[0] + return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None + raise LiveError(f"нет быстрых цен для {exchange}") + + +def fut_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]: + if exchange == "Bybit": + t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=linear&symbol={_q(symbol)}")["result"]["list"][0] + b, a = _f(t["bid1Price"]), _f(t["ask1Price"]) + return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size")) + if exchange == "Binance": + t = _http("GET", f"https://fapi.binance.com/fapi/v1/ticker/bookTicker?symbol={_q(symbol)}") + b, a = _f(t["bidPrice"]), _f(t["askPrice"]) + return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty")) + if exchange == "MEXC": + t = _http("GET", f"https://contract.mexc.com/api/v1/contract/ticker?symbol={_q(symbol)}")["data"] + return _f(t["bid1"]), _f(t["ask1"]), None, None + if exchange == "HTX": + t = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/detail/merged?contract_code={_q(symbol)}")["tick"] + return _f(t["bid"][0]), _f(t["ask"][0]), None, None + if exchange == "Gate": + t = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/tickers?contract={_q(symbol)}")[0] + return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None + raise LiveError(f"нет быстрых цен для {exchange}") + + +# --- order books: what an order of N $ would really get -------------------------------------------------------------- +# The tickers above can lag the book by a second or two on a fast move (seen on Gate: a «gap» that was gone when the +# orders arrived). Before a real entry the program reads the books themselves and prices the whole trade amount. +_SIZES: dict[tuple[str, str], float] = {} # (exchange, perp symbol) → coins (of the symbol's unit) per contract + + +def _contract_size(exchange: str, symbol: str) -> float: + key = (exchange, symbol) + if key not in _SIZES: + if exchange == "MEXC": + d = _http("GET", f"https://contract.mexc.com/api/v1/contract/detail?symbol={_q(symbol)}")["data"] + _SIZES[key] = _f(d.get("contractSize")) or 1.0 + elif exchange == "HTX": + d = _http("GET", f"https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?contract_code={_q(symbol)}")["data"] + _SIZES[key] = _f(d[0].get("contract_size")) or 1.0 + elif exchange == "Gate": + d = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/contracts/{_q(symbol)}") + _SIZES[key] = _f(d.get("quanto_multiplier")) or 1.0 + else: + _SIZES[key] = 1.0 + return _SIZES[key] + + +def book(exchange: str, market: str, symbol: str) -> tuple[list, list]: + """(bids, asks) of the order book, best first, as [(price per symbol unit, quantity in symbol units)]; + market "spot" or "fut".""" + fut = market == "fut" + if exchange == "Bybit": + r = _http("GET", f"https://api.bybit.com/v5/market/orderbook?category={'linear' if fut else 'spot'}" + f"&symbol={_q(symbol)}&limit=50")["result"] + bids, asks = r["b"], r["a"] + elif exchange == "Binance": + host = "https://fapi.binance.com/fapi/v1" if fut else "https://api.binance.com/api/v3" + r = _http("GET", f"{host}/depth?symbol={_q(symbol)}&limit=20") + bids, asks = r["bids"], r["asks"] + elif exchange == "MEXC": + if fut: + r = _http("GET", f"https://contract.mexc.com/api/v1/contract/depth/{_q(symbol)}?limit=20")["data"] + size = _contract_size(exchange, symbol) + bids = [(b[0], _f(b[1]) * size) for b in r["bids"]] + asks = [(a[0], _f(a[1]) * size) for a in r["asks"]] + else: + r = _http("GET", f"https://api.mexc.com/api/v3/depth?symbol={_q(symbol)}&limit=20") + bids, asks = r["bids"], r["asks"] + elif exchange == "HTX": + if fut: + r = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/depth?contract_code={_q(symbol)}&type=step0")["tick"] + size = _contract_size(exchange, symbol) + bids = [(b[0], _f(b[1]) * size) for b in r["bids"]] + asks = [(a[0], _f(a[1]) * size) for a in r["asks"]] + else: + r = _http("GET", f"https://api.huobi.pro/market/depth?symbol={_q(symbol.lower())}&depth=20&type=step0")["tick"] + bids, asks = r["bids"], r["asks"] + elif exchange == "Gate": + if fut: + r = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/order_book?contract={_q(symbol)}&limit=20") + size = _contract_size(exchange, symbol) + bids = [(b["p"], abs(_f(b["s"])) * size) for b in r["bids"]] + asks = [(a["p"], abs(_f(a["s"])) * size) for a in r["asks"]] + else: + r = _http("GET", f"https://api.gateio.ws/api/v4/spot/order_book?currency_pair={_q(symbol)}&limit=20") + bids, asks = r["bids"], r["asks"] + else: + raise LiveError(f"нет стакана для {exchange}") + return [(_f(p), _f(q)) for p, q in bids[:50]], [(_f(p), _f(q)) for p, q in asks[:50]] + + +def fill_price(levels: list, usd: float) -> float | None: + """Average price of an order for `usd` $ walking the book from the best level; None when the book (as read) + holds less than that.""" + left, cost, qty = usd, 0.0, 0.0 + for price, q in levels: + if price <= 0 or q <= 0: + continue + take = min(left, price * q) + cost += take + qty += take / price + left -= take + if left <= 1e-9: + return cost / qty + return None + + +def execution(exchange: str, market: str, symbol: str, usd: float) -> dict: + """What an order of `usd` $ gets now: {"bid": average sale price, "ask": average purchase price (None: not + enough in the book), "best_bid", "best_ask", "spread_pct"} — prices per symbol unit.""" + bids, asks = book(exchange, market, symbol) + if not bids or not asks: + raise LiveError(f"{exchange}: пустой стакан {symbol}") + bb, ba = bids[0][0], asks[0][0] + return {"bid": fill_price(bids, usd), "ask": fill_price(asks, usd), "best_bid": bb, "best_ask": ba, + "spread_pct": (ba / bb - 1) * 100 if bb > 0 else 100.0} diff --git a/LinuxServer/historical_backtest.py b/LinuxServer/historical_backtest.py new file mode 100644 index 0000000..024483d --- /dev/null +++ b/LinuxServer/historical_backtest.py @@ -0,0 +1,1545 @@ +from __future__ import annotations + +import bisect +import csv +import heapq +import itertools +import json +import math +import sqlite3 +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Callable + +import strategy + +TAKER_FEE_PCT = 0.055 +API_URL = "https://api.bybit.com/v5/market/kline" +PAGE_TIMEOUT_SECONDS = 20 +PAGE_RETRY_DELAYS_SECONDS = (1, 2, 4, 8) +CANDLE_CACHE_DB = Path(__file__).with_name("historical_candles.sqlite3") +_CACHE_INIT_LOCK = threading.Lock() +TOP_N_DEFAULT = 100 + + +class RetryableBybitError(RuntimeError): + """A temporary Bybit API response that can succeed on a later attempt.""" + + +def _open_candle_cache(path: Path) -> sqlite3.Connection: + path.parent.mkdir(parents=True, exist_ok=True) + with _CACHE_INIT_LOCK: + connection = sqlite3.connect(str(path), timeout=30) + connection.execute("PRAGMA busy_timeout = 30000") + connection.execute( + "CREATE TABLE IF NOT EXISTS candles (" + "symbol TEXT NOT NULL, interval INTEGER NOT NULL, start_ms INTEGER NOT NULL, " + "open REAL NOT NULL, high REAL NOT NULL, low REAL NOT NULL, close REAL NOT NULL, " + "PRIMARY KEY(symbol, interval, start_ms))" + ) + connection.execute( + "CREATE TABLE IF NOT EXISTS coverage (" + "symbol TEXT NOT NULL, interval INTEGER NOT NULL, start_ms INTEGER NOT NULL, " + "end_ms INTEGER NOT NULL, PRIMARY KEY(symbol, interval, start_ms))" + ) + columns = {row[1] for row in connection.execute("PRAGMA table_info(candles)").fetchall()} + if "turnover" not in columns: + # Older caches stored OHLC only; turnover is needed for the liquidity ranking. + connection.execute("ALTER TABLE candles ADD COLUMN turnover REAL") + connection.execute( + "CREATE TABLE IF NOT EXISTS funding (" + "symbol TEXT NOT NULL, stamp_ms INTEGER NOT NULL, rate REAL NOT NULL, " + "PRIMARY KEY(symbol, stamp_ms))" + ) + connection.commit() + return connection + + +def _missing_ranges(start_ms: int, end_ms: int, coverage: list[tuple[int, int]], step_ms: int + ) -> list[tuple[int, int]]: + missing: list[tuple[int, int]] = [] + cursor = start_ms + for covered_start, covered_end in coverage: + if covered_end < cursor: + continue + if covered_start > cursor: + gap_end = min(end_ms, covered_start - step_ms) + if cursor <= gap_end: + missing.append((cursor, gap_end)) + cursor = max(cursor, covered_end + step_ms) + if cursor > end_ms: + break + if cursor <= end_ms: + missing.append((cursor, end_ms)) + return missing + + +def _cache_page(connection: sqlite3.Connection, symbol: str, interval: int, + page_start: int, page_end: int, rows: list[list[float]], step_ms: int) -> None: + connection.execute("BEGIN IMMEDIATE") + try: + connection.executemany( + "INSERT INTO candles(symbol, interval, start_ms, open, high, low, close, turnover) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT(symbol, interval, start_ms) DO UPDATE SET " + "open=excluded.open, high=excluded.high, low=excluded.low, close=excluded.close, " + "turnover=COALESCE(excluded.turnover, candles.turnover)", + [(symbol, interval, int(row[0]), *map(float, row[1:5]), + float(row[5]) if len(row) > 5 and row[5] is not None else None) for row in rows], + ) + coverage_rows = connection.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? " + "AND end_ms >= ? AND start_ms <= ?", + (symbol, interval, page_start - step_ms, page_end + step_ms), + ).fetchall() + merged_start, merged_end = page_start, page_end + for old_start, old_end in coverage_rows: + merged_start = min(merged_start, int(old_start)) + merged_end = max(merged_end, int(old_end)) + connection.executemany( + "DELETE FROM coverage WHERE symbol=? AND interval=? AND start_ms=?", + [(symbol, interval, int(old_start)) for old_start, _ in coverage_rows], + ) + connection.execute( + "INSERT OR REPLACE INTO coverage(symbol, interval, start_ms, end_ms) VALUES (?, ?, ?, ?)", + (symbol, interval, merged_start, merged_end), + ) + connection.commit() + except Exception: + connection.rollback() + raise + + +@dataclass +class SimPosition: + symbol: str + entry_price: float + qty: float + margin: float + entry_fees: float + opened_at: int + last_add_price: float + add_count: int = 0 + averaging_frozen: bool = False + funding: float = 0.0 # received (+) or paid (−) funding, USDT + + +FUNDING_URL = "https://api.bybit.com/v5/market/funding/history" +FUNDING_PAGE_LIMIT = 200 +# Coverage rows of the funding history use this pseudo-interval in the shared coverage table. +FUNDING_COVERAGE_INTERVAL = -1 + + +def _request_funding_page(symbol: str, start_ms: int, end_ms: int) -> list[tuple[int, float]]: + params = urllib.parse.urlencode({ + "category": "linear", "symbol": symbol, "startTime": str(start_ms), + "endTime": str(end_ms), "limit": str(FUNDING_PAGE_LIMIT), + }) + request = urllib.request.Request(f"{FUNDING_URL}?{params}", headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response: + payload = json.loads(response.read().decode("utf-8")) + ret_code = payload.get("retCode") + if ret_code != 0: + message = f"Bybit funding {symbol}: {ret_code} {payload.get('retMsg', '')}" + if str(ret_code) in {"10006", "10016"}: + raise RetryableBybitError(message) + raise RuntimeError(message) + rows = [] + for row in payload.get("result", {}).get("list", []): + try: + rows.append((int(row["fundingRateTimestamp"]), float(row["fundingRate"]))) + except (KeyError, TypeError, ValueError): + continue + return rows + + +def _cache_funding_page(connection: sqlite3.Connection, symbol: str, page_start: int, page_end: int, + rows: list[tuple[int, float]]) -> None: + connection.execute("BEGIN IMMEDIATE") + try: + connection.executemany( + "INSERT OR REPLACE INTO funding(symbol, stamp_ms, rate) VALUES (?, ?, ?)", + [(symbol, stamp, rate) for stamp, rate in rows], + ) + coverage_rows = connection.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? " + "AND end_ms >= ? AND start_ms <= ?", + (symbol, FUNDING_COVERAGE_INTERVAL, page_start - 1, page_end + 1), + ).fetchall() + merged_start, merged_end = page_start, page_end + for old_start, old_end in coverage_rows: + merged_start = min(merged_start, int(old_start)) + merged_end = max(merged_end, int(old_end)) + connection.executemany( + "DELETE FROM coverage WHERE symbol=? AND interval=? AND start_ms=?", + [(symbol, FUNDING_COVERAGE_INTERVAL, int(old_start)) for old_start, _ in coverage_rows], + ) + connection.execute( + "INSERT OR REPLACE INTO coverage(symbol, interval, start_ms, end_ms) VALUES (?, ?, ?, ?)", + (symbol, FUNDING_COVERAGE_INTERVAL, merged_start, merged_end), + ) + connection.commit() + except Exception: + connection.rollback() + raise + + +def fetch_funding_history(symbol: str, start_ms: int, end_ms: int, + cancel: Callable[[], bool] = lambda: False, + cache_path: Path | None = None) -> dict[int, float]: + """Settled funding rates {settlement_ms: rate as a fraction}; cached like the candles. + + A positive rate means LONG positions pay and SHORT positions receive + ``position value × rate`` at the settlement time. + """ + cache = _open_candle_cache(cache_path or CANDLE_CACHE_DB) + try: + coverage = [(int(row[0]), int(row[1])) for row in cache.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? ORDER BY start_ms", + (symbol, FUNDING_COVERAGE_INTERVAL), + ).fetchall()] + for gap_start, gap_end in _missing_ranges(start_ms, end_ms, coverage, 1): + cursor = gap_end + while cursor >= gap_start: + if cancel(): + raise InterruptedError("Исторический прогон отменён") + page = None + last_error: Exception | None = None + for attempt in range(len(PAGE_RETRY_DELAYS_SECONDS) + 1): + if cancel(): + raise InterruptedError("Исторический прогон отменён") + try: + page = _request_funding_page(symbol, gap_start, cursor) + break + except (RetryableBybitError, TimeoutError, urllib.error.URLError, + ConnectionError, OSError) as exc: + last_error = exc + if attempt >= len(PAGE_RETRY_DELAYS_SECONDS): + break + time.sleep(PAGE_RETRY_DELAYS_SECONDS[attempt]) + if page is None: + raise RuntimeError(f"Не удалось загрузить funding {symbol}: {last_error}") from last_error + page = [(stamp, rate) for stamp, rate in page if gap_start <= stamp <= cursor] + full_page = len(page) >= FUNDING_PAGE_LIMIT + page_start = min(stamp for stamp, _ in page) if full_page else gap_start + _cache_funding_page(cache, symbol, page_start, cursor, page) + if not full_page: + break + cursor = page_start - 1 + time.sleep(0.1) + return {int(row[0]): float(row[1]) for row in cache.execute( + "SELECT stamp_ms, rate FROM funding WHERE symbol=? AND stamp_ms BETWEEN ? AND ? ORDER BY stamp_ms", + (symbol, start_ms, end_ms), + ).fetchall()} + finally: + cache.close() + + +def _request_page(symbol: str, interval: int, start_ms: int, end_ms: int) -> list[list[float]]: + params = urllib.parse.urlencode({ + "category": "linear", "symbol": symbol, "interval": str(interval), + "start": str(start_ms), "end": str(end_ms), "limit": "1000", + }) + request = urllib.request.Request(f"{API_URL}?{params}", headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response: + payload = json.loads(response.read().decode("utf-8")) + ret_code = payload.get("retCode") + if ret_code != 0: + message = f"Bybit {symbol}: {ret_code} {payload.get('retMsg', '')}" + if str(ret_code) in {"10006", "10016"}: + raise RetryableBybitError(message) + raise RuntimeError(message) + output = [] + for row in payload.get("result", {}).get("list", []): + stamp = int(row[0]) + turnover = float(row[6]) if len(row) > 6 and row[6] not in (None, "") else None + output.append([stamp, float(row[1]), float(row[2]), float(row[3]), float(row[4]), turnover]) + return output + + +def fetch_klines(symbol: str, interval: int, start_ms: int, end_ms: int, + cancel: Callable[[], bool] = lambda: False, + progress: Callable[..., None] = lambda *_: None, + cache_path: Path | None = None, with_turnover: bool = False) -> list[list[float]]: + """Return cached candles and fetch only uncovered ranges, persisting every API page. + + Rows are [start_ms, open, high, low, close] or, with ``with_turnover``, + [start_ms, open, high, low, close, turnover]. + """ + step_ms = interval * 60_000 + first_open = ((start_ms + step_ms - 1) // step_ms) * step_ms + last_open = (end_ms // step_ms) * step_ms + if last_open < first_open: + raise RuntimeError(f"Пустой диапазон свечей для {symbol}") + estimated_total = (last_open - first_open) // step_ms + 1 + cache = _open_candle_cache(cache_path or CANDLE_CACHE_DB) + page_number = 0 + try: + coverage = [(int(row[0]), int(row[1])) for row in cache.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? ORDER BY start_ms", + (symbol, interval), + ).fetchall()] + gaps = _missing_ranges(first_open, last_open, coverage, step_ms) + cached_count = int(cache.execute( + "SELECT COUNT(*) FROM candles WHERE symbol=? AND interval=? AND start_ms BETWEEN ? AND ?", + (symbol, interval, first_open, last_open), + ).fetchone()[0]) + pages_total = sum(math.ceil(((gap_end - gap_start) // step_ms + 1) / 1000) + for gap_start, gap_end in gaps) + progress(symbol, cached_count, estimated_total, + f"локальный кэш: {cached_count:,} свечей; докачать страниц: {pages_total}") + + for gap_start, gap_end in gaps: + cursor = gap_end + while cursor >= gap_start: + if cancel(): + raise InterruptedError("Исторический прогон отменён") + page_number += 1 + # Query a bounded, non-overlapping block of up to 1,000 candle opens. + page_start = max(gap_start, cursor - 999 * step_ms) + progress(symbol, cached_count, estimated_total, + f"страница {page_number}/{pages_total}: запрос Bybit") + page = None + last_error: Exception | None = None + for attempt in range(len(PAGE_RETRY_DELAYS_SECONDS) + 1): + if cancel(): + raise InterruptedError("Исторический прогон отменён") + try: + page = _request_page(symbol, interval, page_start, cursor) + break + except (RetryableBybitError, TimeoutError, urllib.error.URLError, + ConnectionError, OSError) as exc: + last_error = exc + if attempt >= len(PAGE_RETRY_DELAYS_SECONDS): + break + progress(symbol, cached_count, estimated_total, + f"страница {page_number}/{pages_total}: повтор {attempt + 2}/5 ({exc})") + time.sleep(PAGE_RETRY_DELAYS_SECONDS[attempt]) + if page is None: + raise RuntimeError( + f"Не удалось загрузить страницу свечей {symbol} после " + f"{len(PAGE_RETRY_DELAYS_SECONDS) + 1} попыток: {last_error}" + ) from last_error + page_rows = [row for row in page if page_start <= int(row[0]) <= cursor] + _cache_page(cache, symbol, interval, page_start, cursor, page_rows, step_ms) + cached_count += len(page_rows) + progress(symbol, min(cached_count, estimated_total), estimated_total, + f"страница {page_number}/{pages_total} сохранена в кэш") + cursor = page_start - step_ms + if cursor >= gap_start: + time.sleep(0.25) + + result = [[int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4])] + + ([float(row[5] or 0.0)] if with_turnover else []) + for row in cache.execute( + "SELECT start_ms, open, high, low, close, turnover FROM candles " + "WHERE symbol=? AND interval=? AND start_ms BETWEEN ? AND ? ORDER BY start_ms", + (symbol, interval, first_open, last_open), + ).fetchall()] + finally: + cache.close() + if len(result) < 2: + raise RuntimeError(f"Bybit вернул только {len(result)} закрытых свечей для {symbol}") + return result + + +INSTRUMENTS_URL = "https://api.bybit.com/v5/market/instruments-info" +UNIVERSE_SCAN_INTERVAL_MINUTES = 60 + + +def _fee_cover_pct(fee_pct: float) -> float: + return strategy.fee_cover_pct(fee_pct) + + +def fetch_linear_usdt_symbols(end_ms: int | None = None) -> list[str]: + """Return USDT perpetual tickers, including delisted ones when Bybit still lists them. + + Including ``Closed`` contracts reduces survivorship bias: coins that pumped and were + later delisted stay in the historical universe whenever Bybit still serves their candles. + """ + symbols: set[str] = set() + errors: list[str] = [] + for status in ("Trading", "Closed"): + cursor = "" + for _ in range(20): + params = {"category": "linear", "limit": "1000", "status": status} + if cursor: + params["cursor"] = cursor + request = urllib.request.Request( + f"{INSTRUMENTS_URL}?{urllib.parse.urlencode(params)}", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}, + ) + try: + with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception as exc: # the Closed list is optional + errors.append(f"{status}: {exc}") + break + if payload.get("retCode") != 0: + errors.append(f"{status}: {payload.get('retCode')} {payload.get('retMsg', '')}") + break + result = payload.get("result", {}) + for row in result.get("list", []): + symbol = str(row.get("symbol") or "").upper() + if (row.get("quoteCoin") != "USDT" or row.get("contractType") != "LinearPerpetual" + or not symbol.endswith("USDT")): + continue + launch = int(row.get("launchTime") or 0) + if end_ms is not None and launch and launch > end_ms: + continue + symbols.add(symbol) + cursor = result.get("nextPageCursor") or "" + if not cursor: + break + if not symbols: + raise RuntimeError("Bybit не вернул список USDT-контрактов. " + " · ".join(errors)) + return sorted(symbols) + + +def build_universe_windows(hourly_by_symbol: dict[str, list[list[float]]], start_ms: int, end_ms: int, + min_growth_24h_pct: float, top_n: int = 100 + ) -> dict[str, list[tuple[int, int]]]: + """Point-in-time replica of the live auto-selection on hourly data. + + After each hourly candle closes, every symbol is ranked by its trailing 24-hour turnover; + of the ``top_n`` most liquid ones, those whose 24-hour change is strictly above + ``min_growth_24h_pct`` may open new entries during the following hour. + Returns merged ``[from_ms, to_ms)`` entry windows per symbol. + """ + hour_ms = 60 * 60 * 1000 + series: dict[str, dict[int, tuple[float, float]]] = { + symbol: {int(row[0]): (float(row[4]), float(row[5]) if len(row) > 5 else 0.0) for row in rows} + for symbol, rows in hourly_by_symbol.items() + } + first_hour = (start_ms // hour_ms) * hour_ms - hour_ms + windows: dict[str, list[tuple[int, int]]] = {} + rolling: dict[str, float] = {symbol: 0.0 for symbol in series} + # Prime trailing turnover sums with the 23 hours before the first decision. + for symbol, rows in series.items(): + rolling[symbol] = sum(rows.get(first_hour - k * hour_ms, (0.0, 0.0))[1] for k in range(1, 24)) + hour = first_hour + while hour <= end_ms: + decision_from = hour + hour_ms # the candle [hour, hour+1h) has closed + decision_to = decision_from + hour_ms + ranked: list[tuple[float, str, float]] = [] + for symbol, rows in series.items(): + current = rows.get(hour) + rolling[symbol] += current[1] if current else 0.0 + if current: + prior = rows.get(hour - 24 * hour_ms) + if prior and prior[0] > 0 and rolling[symbol] > 0: + ranked.append((rolling[symbol], symbol, (current[0] / prior[0] - 1) * 100)) + dropped = rows.get(hour - 23 * hour_ms) + rolling[symbol] -= dropped[1] if dropped else 0.0 + ranked.sort(reverse=True) + for _turnover, symbol, change in ranked[:top_n]: + if change > min_growth_24h_pct and decision_to > start_ms and decision_from <= end_ms: + spans = windows.setdefault(symbol, []) + lo = max(decision_from, start_ms) + if spans and spans[-1][1] >= lo: + spans[-1] = (spans[-1][0], decision_to) + else: + spans.append((lo, decision_to)) + hour += hour_ms + return windows + + +def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_n: int = TOP_N_DEFAULT, + cancel: Callable[[], bool] = lambda: False, + progress: Callable[..., None] = lambda *_: None, + cache_path: Path | None = None, workers: int = 4 + ) -> tuple[dict[str, list[tuple[int, int]]], list[str]]: + """Download hourly candles with turnover for every USDT perpetual and build entry windows. + + Returns (windows per symbol, symbols that could not be loaded). Hourly data is cached in the + same SQLite file, so later runs only download new hours. + """ + hour_ms = UNIVERSE_SCAN_INTERVAL_MINUTES * 60_000 + hourly_start = (start_ms // hour_ms) * hour_ms - 2 * 24 * hour_ms + hourly_end = (end_ms // hour_ms) * hour_ms - 1 + symbols = fetch_linear_usdt_symbols(end_ms) + hourly: dict[str, list[list[float]]] = {} + failed: list[str] = [] + done = 0 + + def load(symbol: str) -> list[list[float]]: + return fetch_klines(symbol, UNIVERSE_SCAN_INTERVAL_MINUTES, hourly_start, hourly_end, cancel, + cache_path=cache_path, with_turnover=True) + + with ThreadPoolExecutor(max_workers=max(1, workers)) as pool: + futures = {pool.submit(load, symbol): symbol for symbol in symbols} + for future in as_completed(futures): + symbol = futures[future] + if cancel(): + for pending in futures: + pending.cancel() + raise InterruptedError("Исторический прогон отменён") + try: + hourly[symbol] = future.result() + except InterruptedError: + raise + except Exception: + # Contracts listed after the period or with no candles are simply skipped. + failed.append(symbol) + done += 1 + progress("Отбор валют", done, len(symbols), + f"часовые свечи и оборот: {done}/{len(symbols)} контрактов") + windows = build_universe_windows(hourly, start_ms, end_ms, min_growth_24h_pct, top_n) + 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, + cancel: Callable[[], bool] = lambda: False, + trading_start_ms: int | None = None, + pause_below_24h_pct: float = 30.0, + resume_above_24h_pct: float = 31.0, + min_equity_pct: float = 10.0, + max_open_positions: int | None = None, + universe_windows: dict[str, list[tuple[int, int]]] | None = None, + funding_by_symbol: dict[str, dict[int, float]] | None = None) -> dict: + """Replay minute OHLC bars; the assumed path is O-L-H-C for green and O-H-L-C for red. + + ``max_open_positions`` mirrors the live/simulation limit on simultaneous positions. + ``universe_windows`` replaces the per-symbol 24-hour filter with the point-in-time + auto-selection: entries are allowed only inside a symbol's windows and averaging is + paused outside them, exactly like a pair waiting for retirement in live mode. + ``funding_by_symbol`` holds settled funding rates; an open LONG pays + ``qty × open price × rate`` at each settlement minute (receives it when the rate is negative). + """ + symbols = sorted(set(candles_by_symbol) & set(strategies)) + if not symbols: + raise ValueError("Нет свечей для прогона") + universe_mode = universe_windows is not None + # Stream candles in (time, ticker) order instead of building a full timeline in memory: + # the live-like selection can involve dozens of pairs with months of minute data. + first_stamp = min(int(candles_by_symbol[symbol][0][0]) for symbol in symbols) + def tagged(symbol: str): + for candle in candles_by_symbol[symbol]: + yield int(candle[0]), symbol, candle + + stream = heapq.merge(*(tagged(symbol) for symbol in symbols), key=lambda item: (item[0], item[1])) + grouped = ((stamp, [(symbol, candle) for _stamp, symbol, candle in items]) + for stamp, items in itertools.groupby(stream, key=lambda item: item[0])) + # The per-symbol 24-hour lookup is only needed by the classic growth filter. + lookup = ({} if universe_mode else + {symbol: {int(row[0]): row for row in candles_by_symbol[symbol]} for symbol in symbols}) + positions: dict[str, SimPosition] = {} + previous_close: dict[str, float] = {} + entry_allowed = {symbol: False for symbol in symbols} + filter_triggered = {symbol: False for symbol in symbols} + window_cursor = {symbol: 0 for symbol in symbols} + marks: dict[str, float] = {} + cash = float(initial_capital) + closed: list[dict] = [] + next_id = 1 + equity_floor = initial_capital * min_equity_pct / 100 if min_equity_pct > 0 else 0.0 + equity_stop: dict[str, object] = {"triggered": False, "timestamp": None, "equity": None} + processed_candles = {symbol: 0 for symbol in symbols} + risk = {"peak": float(initial_capital), "max_dd_usdt": 0.0, "max_dd_pct": 0.0, + "min_equity": float(initial_capital), "max_margin": 0.0, "max_positions": 0, + "skipped_limit": 0, "skipped_margin": 0} + funding_total = {"sum": 0.0, "events": 0} + last_stamp = first_stamp + + def equity_at(symbol: str | None = None, price: float | None = None) -> float: + equity = cash + for position_symbol, position in positions.items(): + mark = (price if position_symbol == symbol and price is not None + else marks.get(position_symbol, position.entry_price)) + unrealized = (mark - position.entry_price) * position.qty + estimated_exit_fee = mark * position.qty * fee_pct / 100 + equity += unrealized - estimated_exit_fee + return 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(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 + return False + + def used_margin() -> float: + return sum(p.margin for p in positions.values()) + + def free_margin() -> float: + # Same definition as simulation/live: equity (cash + unrealized P&L after the + # estimated closing fee) minus margin locked in open positions. + return equity_at() - used_margin() + + def note_exposure() -> None: + risk["max_margin"] = max(risk["max_margin"], used_margin()) + risk["max_positions"] = max(risk["max_positions"], len(positions)) + + def open_position(symbol: str, price: float, stamp: int) -> bool: + nonlocal cash, next_id + cfg = strategies[symbol] + stake, leverage = cfg["stake"], cfg["leverage"] + if max_open_positions is not None and len(positions) >= max_open_positions: + risk["skipped_limit"] += 1 + return False + if stake > max(0.0, free_margin()): + risk["skipped_margin"] += 1 + return False + notional = stake * leverage + qty = notional / price + entry_fee = notional * fee_pct / 100 + cash -= entry_fee + positions[symbol] = SimPosition(symbol, price, qty, stake, entry_fee, stamp, price) + positions[symbol]._trade_id = next_id + next_id += 1 + note_exposure() + return True + + def add_to_position(symbol: str, pos: SimPosition, level: float) -> bool: + nonlocal cash + cfg = strategies[symbol] + cfg_stake = cfg["stake"] + if cfg_stake > max(0.0, free_margin()): + # Skipped for lack of margin; a later, deeper level may still be filled. + risk["skipped_margin"] += 1 + return False + notional = cfg_stake * cfg["leverage"] + added_qty = notional / level + fee = notional * fee_pct / 100 + total_qty = pos.qty + added_qty + pos.entry_price = (pos.entry_price * pos.qty + level * added_qty) / total_qty + pos.qty = total_qty + pos.margin += cfg_stake + pos.entry_fees += fee + pos.last_add_price = level + pos.add_count += 1 + cash -= fee + note_exposure() + return True + + def close_position(symbol: str, price: float, stamp: int, reason: str, + liquidation: bool = False) -> None: + nonlocal cash + pos = positions.pop(symbol) + if liquidation: + # Isolated-margin liquidation forfeits the whole margin of the position. + gross = -pos.margin + exit_fee = 0.0 + else: + gross = (price - pos.entry_price) * pos.qty + exit_fee = price * pos.qty * fee_pct / 100 + fees = pos.entry_fees + exit_fee + # Funding already moved the cash while the position was open. + net = gross - fees + pos.funding + cash += gross - exit_fee + closed.append({ + "id": pos._trade_id, "symbol": symbol, "side": "LONG", + "opened_at": datetime.fromtimestamp(pos.opened_at / 1000, timezone.utc).isoformat(), + "closed_at": datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat(), + "entry": pos.entry_price, "exit": price, "entries": pos.add_count + 1, + "margin": pos.margin, "gross_usdt": gross, "fees_usdt": fees, "funding_usdt": pos.funding, + "net_usdt": net, "roi_pct": net / pos.margin * 100 if pos.margin else 0, + "hold_hours": (stamp - pos.opened_at) / 3_600_000, + "reason": reason, "status": "CLOSED", + }) + + def exit_levels(symbol: str, pos: SimPosition) -> tuple[float | None, float | None, float | None]: + cfg = strategies[symbol] + return (strategy.take_profit_price(pos.entry_price, cfg["take_profit"], fee_pct), + strategy.stop_loss_price(pos.entry_price, cfg["stop_loss"]), + strategy.liquidation_price(pos.entry_price, cfg["leverage"])) + + def handle_gap(symbol: str, price: float, stamp: int) -> None: + """Apply TP/stop/liquidation/adds when a candle opens beyond a level (price gap).""" + cfg = strategies[symbol] + for _ in range(int(cfg["max_adds"]) + 2): + pos = positions.get(symbol) + if pos is None: + return + tp, stop, liq = exit_levels(symbol, pos) + if liq is not None and price <= liq: + close_position(symbol, price, stamp, "Ликвидация (разрыв цены)", liquidation=True) + return + if stop is not None and price <= stop: + loss_pct = (pos.entry_price - price) / pos.entry_price * 100 + close_position(symbol, price, stamp, f"Стоп −{loss_pct:.3f}% (разрыв цены)") + return + if tp is not None and price >= tp: + gain_pct = (price / pos.entry_price - 1) * 100 + close_position(symbol, price, stamp, f"TP +{gain_pct:.3f}% (разрыв цены)") + return + level = strategy.add_level(pos.last_add_price, cfg["add_step"]) + if (level is None or not strategy.can_add(pos.add_count, cfg["max_adds"], cfg["add_step"], + pos.averaging_frozen) or price > level): + return + if not add_to_position(symbol, pos, price): + return + + def walk_segment(symbol: str, start: float, end: float, stamp: int, + baseline: float, armed: list[bool], allow_entry: bool) -> None: + cfg = strategies[symbol] + entry_level = strategy.entry_level(baseline, cfg["trigger"]) + current = start + rising = end > start + for _ in range(16 + 2 * int(cfg["max_adds"])): + if mark_and_check_stop(symbol, current, stamp): + return + if abs(end - current) <= max(abs(end), 1.0) * 1e-14: + mark_and_check_stop(symbol, end, stamp) + return + pos = positions.get(symbol) + if rising: + if pos is None: + if armed[0] and current < entry_level <= end: + if allow_entry and open_position(symbol, entry_level, stamp): + armed[0] = False + current = entry_level + if mark_and_check_stop(symbol, current, stamp): + return + continue + # Mark the trigger as crossed even when the filter blocks it; + # a new entry then needs a fresh cross or candle. + armed[0] = False + mark_and_check_stop(symbol, end, stamp) + return + tp_level, _stop, _liq = exit_levels(symbol, pos) + if tp_level is not None and current < tp_level <= end: + marks[symbol] = tp_level + tp_pct = strategy.effective_take_profit_pct(cfg["take_profit"], fee_pct) + close_position(symbol, tp_level, stamp, f"TP +{tp_pct:.3f}%") + armed[0] = False + current = tp_level + if mark_and_check_stop(symbol, current, stamp): + return + continue + mark_and_check_stop(symbol, end, stamp) + return + # Falling segment: once price is below the entry threshold, a later rebound may enter. + if pos is None: + if end < entry_level: + armed[0] = True + mark_and_check_stop(symbol, end, stamp) + return + candidates: list[tuple[float, str]] = [] + # Equity moves linearly with this symbol's price between strategy events. + # 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: + 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: + candidates.append((stop_level, "STOP")) + if liq_level is not None and end <= liq_level < current: + candidates.append((liq_level, "LIQ")) + if strategy.can_add(pos.add_count, cfg["max_adds"], cfg["add_step"], pos.averaging_frozen): + add_level = strategy.add_level(pos.last_add_price, cfg["add_step"]) + if add_level is not None and end <= add_level < current: + candidates.append((add_level, "ADD")) + if not candidates: + mark_and_check_stop(symbol, end, stamp) + return + level, event = max(candidates, key=lambda item: item[0]) + marks[symbol] = level + if event == "EQUITY_STOP": + mark_and_check_stop(symbol, level, stamp) + return + if event in ("STOP", "LIQ"): + if event == "LIQ": + close_position(symbol, level, stamp, f"Ликвидация (плечо {cfg['leverage']:g}x)", + liquidation=True) + else: + loss_pct = (pos.entry_price - level) / pos.entry_price * 100 + close_position(symbol, level, stamp, f"Стоп −{loss_pct:.3f}%") + armed[0] = False + current = level + if mark_and_check_stop(symbol, current, stamp): + return + continue + if not add_to_position(symbol, pos, level): + # Not enough free margin: consume this level so the next one is measured from it. + pos.last_add_price = level + current = level + if mark_and_check_stop(symbol, current, stamp): + return + + def update_entry_filter(symbol: str, stamp: int, close: float) -> None: + if universe_mode: + return + prior_day = lookup[symbol].get(stamp - 24 * 60 * 60 * 1000) + if not prior_day or prior_day[4] <= 0: + return + change_24h = (close / float(prior_day[4]) - 1) * 100 + if change_24h < pause_below_24h_pct: + entry_allowed[symbol] = False + filter_triggered[symbol] = True + # Once the market weakens below the pause threshold, do not increase + # exposure on the existing position while it waits for TP or stop. + position = positions.get(symbol) + if position is not None: + position.averaging_frozen = True + elif change_24h > resume_above_24h_pct: + entry_allowed[symbol] = True + + def update_universe(symbol: str, stamp: int) -> None: + spans = universe_windows.get(symbol, []) if universe_windows else [] + index = window_cursor[symbol] + while index < len(spans) and spans[index][1] <= stamp: + index += 1 + window_cursor[symbol] = index + inside = index < len(spans) and spans[index][0] <= stamp < spans[index][1] + if not inside and entry_allowed[symbol]: + filter_triggered[symbol] = True + entry_allowed[symbol] = inside + position = positions.get(symbol) + if position is not None: + # Outside the selection the pair only manages its position (no averaging), + # and averaging resumes if the pair qualifies again — as in live rotation. + position.averaging_frozen = not inside + + for stamp, minute_candles in grouped: + if equity_stop["triggered"]: + break + if cancel(): + raise InterruptedError("Исторический прогон отменён") + last_stamp = stamp + for symbol, candle in minute_candles: + if equity_stop["triggered"]: + break + if trading_start_ms is None or stamp >= trading_start_ms: + processed_candles[symbol] += 1 + if universe_mode: + update_universe(symbol, stamp) + funded = positions.get(symbol) + if funded is not None and funding_by_symbol: + rate = funding_by_symbol.get(symbol, {}).get(stamp) + if rate: + payment = funded.qty * float(candle[1]) * rate + cash -= payment + funded.funding -= payment + funding_total["sum"] -= payment + funding_total["events"] += 1 + previous = previous_close.get(symbol) + if previous is None: + previous_close[symbol] = float(candle[4]) + update_entry_filter(symbol, stamp, float(candle[4])) + continue + _, open_price, high, low, close = candle[:5] + open_price, high, low, close = float(open_price), float(high), float(low), float(close) + if symbol not in positions: + allow_entry = entry_allowed[symbol] and (trading_start_ms is None or stamp >= trading_start_ms) + limit_full = max_open_positions is not None and len(positions) >= max_open_positions + if not allow_entry or limit_full: + # Fast path: without a position and with entries impossible this candle + # cannot change cash, equity or any position, so only the baseline moves. + if allow_entry and high >= strategy.entry_level(previous, strategies[symbol]["trigger"]): + risk["skipped_limit"] += 1 + previous_close[symbol] = close + update_entry_filter(symbol, stamp, close) + continue + marks[symbol] = open_price + handle_gap(symbol, open_price, stamp) + if mark_and_check_stop(symbol, open_price, stamp): + break + cfg = strategies[symbol] + entry_level = strategy.entry_level(previous, cfg["trigger"]) + armed = [True] + allow_entry = entry_allowed[symbol] and (trading_start_ms is None or stamp >= trading_start_ms) + if symbol not in positions and open_price >= entry_level: + if allow_entry: + open_position(symbol, open_price, stamp) + armed[0] = False + if mark_and_check_stop(symbol, open_price, stamp): + break + # Heuristic intrabar ordering from candle direction; OHLC cannot reveal the true path. + path = [open_price, low, high, close] if close >= open_price else [open_price, high, low, close] + for a, b in zip(path, path[1:]): + walk_segment(symbol, a, b, stamp, previous, armed, allow_entry) + if equity_stop["triggered"]: + break + previous_close[symbol] = close + if equity_stop["triggered"]: + break + update_entry_filter(symbol, stamp, close) + + end_stamp = int(equity_stop["timestamp"] if equity_stop["triggered"] else last_stamp) + open_rows = [] + open_net = 0.0 + for symbol, pos in positions.items(): + last_candle = candles_by_symbol[symbol][-1] + mark = marks.get(symbol, float(last_candle[4])) + gross = (mark - pos.entry_price) * pos.qty + estimated_exit_fee = mark * pos.qty * fee_pct / 100 + net = gross - pos.entry_fees - estimated_exit_fee + pos.funding + open_net += net + open_rows.append({ + "id": pos._trade_id, "symbol": symbol, "side": "LONG", + "opened_at": datetime.fromtimestamp(pos.opened_at / 1000, timezone.utc).isoformat(), + "closed_at": "", "entry": pos.entry_price, "exit": mark, + "entries": pos.add_count + 1, "margin": pos.margin, "funding_usdt": pos.funding, + "gross_usdt": gross, "fees_usdt": pos.entry_fees + estimated_exit_fee, + "net_usdt": net, "roi_pct": net / pos.margin * 100 if pos.margin else 0, + "hold_hours": (end_stamp - pos.opened_at) / 3_600_000, + "reason": ("Открытая позиция на момент остановки по порогу капитала; выходная комиссия оценена" + if equity_stop["triggered"] else + "Открытая позиция на конце периода; выходная комиссия оценена"), + "status": "OPEN", + }) + + realized = sum(row["net_usdt"] for row in closed) + equity_net = realized + open_net + wins = sum(row["net_usdt"] > 0 for row in closed) + all_rows = closed + open_rows + stops = sum(row["reason"].startswith("Стоп") for row in closed) + liquidations = sum(row["reason"].startswith("Ликвидация") for row in closed) + open_losing = sum(row["net_usdt"] < 0 for row in open_rows) + if universe_mode: + filter_text = ( + "Отбор валют как в реальном режиме: после каждого закрытого часа валюты ранжируются по " + f"обороту за 24 ч, из топ-{TOP_N_DEFAULT} входы разрешены тем, чей рост за 24 ч выше порога. " + "Вне отбора позиция только сопровождается до TP/стопа, доливки приостанавливаются." + ) + else: + filter_text = ( + f"При росте за 24 ч ниже {pause_below_24h_pct:g}% новые входы блокируются, а усреднение " + "открытых позиций замораживается до их закрытия по TP/стопу. Новые входы разрешаются снова " + f"только выше {resume_above_24h_pct:g}%." + ) + summary = { + "symbols": symbols, + "period_start_utc": datetime.fromtimestamp((trading_start_ms if trading_start_ms is not None else first_stamp) / 1000, timezone.utc).isoformat(), + "period_end_utc": datetime.fromtimestamp(end_stamp / 1000, timezone.utc).isoformat(), + "candles": processed_candles, + "warmup_candles": {symbol: sum(1 for row in candles_by_symbol[symbol] + if trading_start_ms is not None and int(row[0]) < trading_start_ms) + for symbol in symbols}, + "initial_capital": initial_capital, + "closed_trades": len(closed), + "wins": wins, + "losses": len(closed) - wins, + "win_rate_pct": wins / len(closed) * 100 if closed else 0.0, + "stops": stops, + "liquidations": liquidations, + "realized_net_usdt": realized, + "open_positions": len(open_rows), + "open_losing_positions": open_losing, + "open_net_estimate_usdt": open_net, + "total_net_including_open_usdt": equity_net, + "ending_equity_estimate": initial_capital + equity_net, + "max_drawdown_pct": risk["max_dd_pct"], + "max_drawdown_usdt": risk["max_dd_usdt"], + "min_equity_usdt": risk["min_equity"], + "peak_equity_usdt": risk["peak"], + "max_margin_used_usdt": risk["max_margin"], + "max_simultaneous_positions": risk["max_positions"], + "max_open_positions_limit": max_open_positions, + "skipped_entries_position_limit": risk["skipped_limit"], + "skipped_orders_margin": risk["skipped_margin"], + "longest_hold_hours": max((row["hold_hours"] for row in all_rows), default=0.0), + "universe_mode": universe_mode, + "equity_stop_pct": min_equity_pct, + "equity_stop_triggered": bool(equity_stop["triggered"]), + "equity_stop_value_usdt": equity_floor if min_equity_pct > 0 else None, + "equity_at_stop_usdt": equity_stop["equity"], + "return_pct": equity_net / initial_capital * 100 if initial_capital else 0.0, + "fees_usdt": sum(row["fees_usdt"] for row in closed) + sum(row["fees_usdt"] for row in open_rows), + "fee_pct_per_side": fee_pct, + "strategy_mode": strategy.STRATEGY_CLASSIC, + "strategy_title": strategy.STRATEGY_TITLES[strategy.STRATEGY_CLASSIC], + "funding_included": funding_by_symbol is not None, + "funding_usdt": funding_total["sum"], + "funding_events": funding_total["events"], + "entry_filter": filter_text, + "filter_was_triggered": filter_triggered, + "entry_allowed_at_end": {symbol: entry_allowed[symbol] for symbol in symbols}, + "assumptions": ( + ("Отбор валют повторяет автоподбор по часовым свечам (в реальном режиме скан каждые 10 мин). " + if universe_mode else + "Рост за 24 ч считается по минутным закрытиям относительно закрытия ровно 1440 минут назад; " + "порог фильтра обновляется после закрытия свечи и действует со следующей. ") + + "Прогон останавливается при падении капитала (баланс с учётом нереализованного P&L открытых " + "позиций и оценочной комиссии закрытия) до установленного порога; открытые позиции остаются в " + "отчёте по цене остановки. Минутные OHLC; внутри свечи путь O-L-H-C для зелёной и O-H-L-C для " + "красной свечи; разрывы цены на открытии свечи исполняются по цене открытия. Комиссия taker по " + "заданной ставке. При плече выше 1 моделируется ликвидация с потерей всей маржи позиции " + f"(ставка поддерживающей маржи {strategy.MAINTENANCE_MARGIN_RATE_PCT:g}%). " + + _funding_assumption(funding_by_symbol is not None) + + "Проскальзывание и очередь исполнения не моделируются. Общий капитал распределяется между " + "сигналами в пределах одной минуты в алфавитном порядке тикеров. Высокий процент прибыльных " + "сделок без стоп-лосса не означает отсутствия убытков: смотрите открытые позиции и максимальную просадку." + ), + } + return {"summary": summary, "trades": all_rows} + + +def _funding_assumption(included: bool) -> str: + if not included: + return "Funding не учитывается (выключен в настройках прогона). " + return ("Funding учитывается по истории ставок Bybit: в минуту расчёта открытая позиция платит " + "(LONG при положительной ставке) или получает (SHORT при положительной ставке) " + "объём × цена открытия минуты × ставка; сумма входит в Net сделки. ") + + +@dataclass +class ModePosition: + symbol: str + side: str + entry_price: float + qty: float + margin: float + entry_fees: float + opened_at: int + stop: float + atr: float + extreme: float + partial_target: float | None + final_target: float | None + leverage: float + trade_id: int + initial_margin: float = 0.0 + initial_stop: float = 0.0 + partial_done: bool = False + realized_gross: float = 0.0 + realized_fees: float = 0.0 + funding: float = 0.0 + + +def _hourly_btc_regime(btc_hourly: list[list[float]] | None, ema_period: int + ) -> tuple[list[int], list[bool | None]]: + """BTC regime per closed hour: (hour end times, close above EMA).""" + if not btc_hourly: + return [], [] + ends: list[int] = [] + regime: list[bool | None] = [] + alpha = 2 / (ema_period + 1) + seed: list[float] = [] + value: float | None = None + for row in btc_hourly: + close = float(row[4]) + if value is None: + seed.append(close) + if len(seed) == ema_period: + value = sum(seed) / ema_period + else: + value = alpha * close + (1 - alpha) * value + ends.append(int(row[0]) + 3_600_000) + regime.append(None if value is None else close > value) + return ends, regime + + +def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str, + params: dict[str, float], initial_capital: float, + fee_pct: float = TAKER_FEE_PCT, + cancel: Callable[[], bool] = lambda: False, + trading_start_ms: int | None = None, + min_growth_24h_pct: float | None = None, + min_equity_pct: float = 10.0, + max_open_positions: int | None = None, + universe_windows: dict[str, list[tuple[int, int]]] | None = None, + funding_by_symbol: dict[str, dict[int, float]] | None = None, + btc_hourly: list[list[float]] | None = None) -> dict: + """Replay minute bars for strategy mode A (breakout) or B (fade). + + Minute rows [start, o, h, l, c, turnover] are grouped into signal candles of + ``params["timeframe_min"]``. A signal is evaluated when its candle closes and stays valid + until the next candle closes; the entry fills at the open of a later minute (no look-ahead). + Exits share the simulation rules: stop, partial take-profit on R with breakeven, + ATR trailing stop, optional final target and maximum holding time. + Without ``universe_windows`` entries need the 24h growth above ``min_growth_24h_pct`` + (when given), measured on closed signal candles. + """ + if mode not in (strategy.STRATEGY_BREAKOUT, strategy.STRATEGY_FADE): + raise ValueError(f"Неизвестный режим стратегии: {mode}") + symbols = sorted(symbol for symbol, rows in candles_by_symbol.items() if rows) + if not symbols: + raise ValueError("Нет свечей для прогона") + universe_mode = universe_windows is not None + tf_ms = int(params["timeframe_min"]) * 60_000 + stake = initial_capital * params["stake_pct"] / 100 + leverage = params["leverage"] + bars_24h = strategy.bars_for_hours(24, params["timeframe_min"]) + history_len = max(strategy.required_bars(mode, params), bars_24h + 1) + 2 + btc_ends, btc_regime = _hourly_btc_regime(btc_hourly, int(params.get("btc_ema", 200))) + funding_stamps = {symbol: sorted((funding_by_symbol or {}).get(symbol, {})) + for symbol in symbols} + + def tagged(symbol: str): + for candle in candles_by_symbol[symbol]: + yield int(candle[0]), symbol, candle + + first_stamp = min(int(candles_by_symbol[symbol][0][0]) for symbol in symbols) + stream = heapq.merge(*(tagged(symbol) for symbol in symbols), key=lambda item: (item[0], item[1])) + grouped = ((stamp, [(symbol, candle) for _stamp, symbol, candle in items]) + for stamp, items in itertools.groupby(stream, key=lambda item: item[0])) + + positions: dict[str, ModePosition] = {} + marks: dict[str, float] = {} + history: dict[str, list[list[float]]] = {symbol: [] for symbol in symbols} + bucket: dict[str, list[float] | None] = {symbol: None for symbol in symbols} + pending: dict[str, tuple[dict, int, bool]] = {} # signal, valid-until ms, already counted as skipped + entry_allowed = {symbol: not universe_mode and min_growth_24h_pct is None for symbol in symbols} + filter_triggered = {symbol: False for symbol in symbols} + window_cursor = {symbol: 0 for symbol in symbols} + processed_candles = {symbol: 0 for symbol in symbols} + signals_total = {"count": 0, "rejected_at_fill": 0} + cash = float(initial_capital) + closed: list[dict] = [] + next_id = 1 + equity_floor = initial_capital * min_equity_pct / 100 if min_equity_pct > 0 else 0.0 + equity_stop: dict[str, object] = {"triggered": False, "timestamp": None, "equity": None} + risk = {"peak": float(initial_capital), "max_dd_usdt": 0.0, "max_dd_pct": 0.0, + "min_equity": float(initial_capital), "max_margin": 0.0, "max_positions": 0, + "skipped_limit": 0, "skipped_margin": 0} + funding_total = {"sum": 0.0, "events": 0} + last_stamp = first_stamp + + def iso(stamp: int) -> str: + return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat() + + def equity_at(symbol: str | None = None, price: float | None = None) -> float: + equity = cash + for position_symbol, pos in positions.items(): + 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 + + 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(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 + return False + + def free_margin() -> float: + return equity_at() - sum(pos.margin for pos in positions.values()) + + def funding_rate_pct_at(symbol: str, stamp: int) -> float | None: + stamps = funding_stamps.get(symbol) or [] + index = bisect.bisect_right(stamps, stamp) - 1 + if index < 0: + return None + return funding_by_symbol[symbol][stamps[index]] * 100 + + def btc_ok_at(stamp: int) -> bool | None: + index = bisect.bisect_right(btc_ends, stamp) - 1 + return btc_regime[index] if index >= 0 else None + + def open_position(symbol: str, signal: dict, price: float, stamp: int) -> str: + nonlocal cash, next_id + if max_open_positions is not None and len(positions) >= max_open_positions: + return "limit" + if stake > max(0.0, free_margin()): + return "margin" + plan = strategy.entry_plan(signal, price, params) + if plan is None: + return "invalid" + notional = stake * leverage + qty = notional / price + entry_fee = notional * fee_pct / 100 + cash -= entry_fee + positions[symbol] = ModePosition( + symbol, plan["side"], price, qty, stake, entry_fee, stamp, plan["stop"], plan["atr"], price, + plan["partial_target"], plan["final_target"], leverage, next_id, + initial_margin=stake, initial_stop=plan["stop"], + ) + next_id += 1 + risk["max_margin"] = max(risk["max_margin"], sum(p.margin for p in positions.values())) + risk["max_positions"] = max(risk["max_positions"], len(positions)) + return "opened" + + def row_for(pos: ModePosition, exit_price: float, stamp: int, gross: float, fees: float, + reason: str, status: str) -> dict: + net = gross - fees + pos.funding + return { + "id": pos.trade_id, "symbol": pos.symbol, "side": pos.side.upper(), "status": status, + "opened_at": iso(pos.opened_at), "closed_at": iso(stamp) if status == "CLOSED" else "", + "entry": pos.entry_price, "exit": exit_price, "entries": 1, + "margin": pos.initial_margin, "gross_usdt": gross, "fees_usdt": fees, + "funding_usdt": pos.funding, "net_usdt": net, + "roi_pct": net / pos.initial_margin * 100 if pos.initial_margin else 0.0, + "hold_hours": (stamp - pos.opened_at) / 3_600_000, "stop_initial": pos.initial_stop, + "reason": reason, + } + + def close_position(symbol: str, price: float, stamp: int, reason: str, liquidation: bool = False) -> None: + nonlocal cash + pos = positions.pop(symbol) + if liquidation: + gross_final, exit_fee = -pos.margin, 0.0 + else: + gross_final = strategy.unrealized_pnl(pos.side, pos.entry_price, price, pos.qty) + exit_fee = price * pos.qty * fee_pct / 100 + cash += gross_final - exit_fee + closed.append(row_for(pos, price, stamp, pos.realized_gross + gross_final, + pos.entry_fees + pos.realized_fees + exit_fee, reason, "CLOSED")) + pending.pop(symbol, None) + + def partial_close(pos: ModePosition, price: float) -> None: + nonlocal cash + fraction = min(1.0, params["partial_pct"] / 100) + qty = pos.qty * fraction + gross = strategy.unrealized_pnl(pos.side, pos.entry_price, price, qty) + fee = price * qty * fee_pct / 100 + cash += gross - fee + pos.realized_gross += gross + pos.realized_fees += fee + pos.qty -= qty + pos.margin *= 1 - fraction + pos.partial_done = True + if params["breakeven"] >= 1: + pos.stop = strategy.tighten_stop(pos.side, pos.stop, + strategy.breakeven_price(pos.side, pos.entry_price, fee_pct)) + + def stop_reason(pos: ModePosition) -> str: + if pos.stop != pos.initial_stop: + return "Стоп (трейлинг/безубыток)" + return "Стоп" + + def take_target(symbol: str, pos: ModePosition, level: float, stamp: int, gap: bool) -> bool: + """Apply the nearest profit target at ``level``; True when the position closed.""" + suffix = " (разрыв цены)" if gap else "" + if (not pos.partial_done and pos.partial_target is not None + and strategy.target_hit(pos.side, level, pos.partial_target)): + fill = level if gap else pos.partial_target + if params["partial_pct"] >= 100: + close_position(symbol, fill, stamp, f"Частичный TP 100% на {params['partial_r']:g}R{suffix}") + return True + partial_close(pos, fill) + return False + if strategy.target_hit(pos.side, level, pos.final_target): + fill = level if gap else pos.final_target + close_position(symbol, fill, stamp, f"TP на {params['take_profit_r']:g}R{suffix}") + return True + return False + + def handle_open(symbol: str, price: float, stamp: int) -> None: + pos = positions.get(symbol) + if pos is None: + return + liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side) + if liq is not None and strategy.stop_hit(pos.side, price, liq): + close_position(symbol, price, stamp, "Ликвидация (разрыв цены)", liquidation=True) + return + if strategy.stop_hit(pos.side, price, pos.stop): + close_position(symbol, price, stamp, stop_reason(pos) + " (разрыв цены)") + return + for _ in range(2): + pos = positions.get(symbol) + if pos is None or not (strategy.target_hit(pos.side, price, pos.partial_target if not pos.partial_done else None) + or strategy.target_hit(pos.side, price, pos.final_target)): + break + if take_target(symbol, pos, price, stamp, gap=True): + return + pos = positions.get(symbol) + if pos is not None and params["max_hold_hours"] > 0 \ + and stamp - pos.opened_at >= params["max_hold_hours"] * 3_600_000: + close_position(symbol, price, stamp, f"Время удержания {params['max_hold_hours']:g} ч") + + def walk(symbol: str, start: float, end: float, stamp: int) -> None: + pos = positions.get(symbol) + if pos is None or start == end: + mark_and_check_stop(symbol, end, stamp) + return + favourable = (end > start) == (pos.side == "long") + if favourable: + for _ in range(3): + pos = positions.get(symbol) + if pos is None: + break + targets = [t for t in ((pos.partial_target if not pos.partial_done else None), pos.final_target) + if t is not None and (start < t <= end if pos.side == "long" else end <= t < start)] + if not targets: + break + level = min(targets) if pos.side == "long" else max(targets) + marks[symbol] = level + if take_target(symbol, pos, level, stamp, gap=False): + break + pos = positions.get(symbol) + if pos is not None: + pos.extreme = max(pos.extreme, end) if pos.side == "long" else min(pos.extreme, end) + if strategy.trailing_active(pos.partial_done, params): + pos.stop = strategy.trailing_stop(pos.side, pos.stop, pos.extreme, pos.atr, params["trail_atr"]) + mark_and_check_stop(symbol, end, stamp) + 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")) + if liq is not None and lo <= liq <= hi: + candidates.append((liq, "LIQ")) + if not candidates: + mark_and_check_stop(symbol, end, stamp) + return + # 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: + close_position(symbol, level, stamp, stop_reason(pos)) + mark_and_check_stop(symbol, end, stamp) + + def update_universe(symbol: str, stamp: int) -> None: + spans = universe_windows.get(symbol, []) if universe_windows else [] + index = window_cursor[symbol] + while index < len(spans) and spans[index][1] <= stamp: + index += 1 + window_cursor[symbol] = index + inside = index < len(spans) and spans[index][0] <= stamp < spans[index][1] + if not inside and entry_allowed[symbol]: + filter_triggered[symbol] = True + entry_allowed[symbol] = inside + + def close_bucket(symbol: str) -> None: + candle = bucket[symbol] + if candle is None: + return + rows = history[symbol] + rows.append(candle) + if len(rows) > history_len: + del rows[:len(rows) - history_len] + decided_at = int(candle[0]) + tf_ms + if not universe_mode and min_growth_24h_pct is not None and len(rows) > bars_24h: + day_ago = float(rows[-bars_24h - 1][4]) + if day_ago > 0: + allowed = (float(candle[4]) / day_ago - 1) * 100 > min_growth_24h_pct + if entry_allowed[symbol] and not allowed: + filter_triggered[symbol] = True + entry_allowed[symbol] = allowed + if symbol in positions: + return + signal = strategy.evaluate_signal(mode, rows, params, funding_rate_pct_at(symbol, decided_at), + btc_ok_at(decided_at)) + if signal is not None: + signals_total["count"] += 1 + pending[symbol] = (signal, decided_at + tf_ms, False) + + for stamp, minute_candles in grouped: + if equity_stop["triggered"]: + break + if cancel(): + raise InterruptedError("Исторический прогон отменён") + last_stamp = stamp + for symbol, candle in minute_candles: + if equity_stop["triggered"]: + break + trading = trading_start_ms is None or stamp >= trading_start_ms + if trading: + processed_candles[symbol] += 1 + if universe_mode: + update_universe(symbol, stamp) + open_price, high, low, close = (float(value) for value in candle[1:5]) + turnover = float(candle[5]) if len(candle) > 5 and candle[5] is not None else 0.0 + start = (stamp // tf_ms) * tf_ms + current = bucket[symbol] + if current is not None and int(current[0]) != start: + close_bucket(symbol) + current = None + if current is None: + bucket[symbol] = [start, open_price, high, low, close, turnover] + else: + current[2] = max(current[2], high) + current[3] = min(current[3], low) + current[4] = close + current[5] += turnover + pos = positions.get(symbol) + if pos is not None and funding_by_symbol: + rate = funding_by_symbol.get(symbol, {}).get(stamp) + if rate: + payment = -strategy.side_sign(pos.side) * pos.qty * open_price * rate + cash += payment + pos.funding += payment + funding_total["sum"] += payment + funding_total["events"] += 1 + if pos is None: + waiting = pending.get(symbol) + if waiting is not None and stamp >= waiting[1]: + pending.pop(symbol, None) + waiting = None + if waiting is None or not trading or not entry_allowed[symbol]: + marks[symbol] = close + continue + signal, valid_until, counted = waiting + outcome = open_position(symbol, signal, open_price, stamp) + if outcome in ("limit", "margin"): + if not counted: + risk["skipped_limit" if outcome == "limit" else "skipped_margin"] += 1 + pending[symbol] = (signal, valid_until, True) + marks[symbol] = close + continue + pending.pop(symbol, None) + if outcome == "invalid": + signals_total["rejected_at_fill"] += 1 + marks[symbol] = close + continue + else: + marks[symbol] = open_price + handle_open(symbol, open_price, stamp) + if mark_and_check_stop(symbol, open_price, stamp): + break + path = [open_price, low, high, close] if close >= open_price else [open_price, high, low, close] + for a, b in zip(path, path[1:]): + walk(symbol, a, b, stamp) + if equity_stop["triggered"]: + break + if equity_stop["triggered"]: + break + pos = positions.get(symbol) + if pos is not None and params["max_hold_hours"] > 0 \ + and stamp + 60_000 - pos.opened_at >= params["max_hold_hours"] * 3_600_000: + close_position(symbol, close, stamp + 60_000, f"Время удержания {params['max_hold_hours']:g} ч") + + end_stamp = int(equity_stop["timestamp"] if equity_stop["triggered"] else last_stamp) + open_rows = [] + for symbol, pos in positions.items(): + mark = marks.get(symbol, float(candles_by_symbol[symbol][-1][4])) + gross = pos.realized_gross + strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) + fees = pos.entry_fees + pos.realized_fees + mark * pos.qty * fee_pct / 100 + open_rows.append(row_for(pos, mark, end_stamp, gross, fees, + "Открытая позиция на момент остановки по порогу капитала; выходная комиссия оценена" + if equity_stop["triggered"] else + "Открытая позиция на конце периода; выходная комиссия оценена", "OPEN")) + realized = sum(row["net_usdt"] for row in closed) + open_net = sum(row["net_usdt"] for row in open_rows) + equity_net = realized + open_net + wins = sum(row["net_usdt"] > 0 for row in closed) + all_rows = closed + open_rows + gains = [row["net_usdt"] for row in closed if row["net_usdt"] > 0] + losses = [row["net_usdt"] for row in closed if row["net_usdt"] <= 0] + if universe_mode: + filter_text = ( + "Отбор валют как в реальном режиме: после каждого закрытого часа валюты ранжируются по " + f"обороту за 24 ч, из топ-{TOP_N_DEFAULT} сигналы режима разрешены тем, чей рост за 24 ч выше порога." + ) + elif min_growth_24h_pct is not None: + filter_text = f"Сигналы режима разрешены при росте за 24 ч выше {min_growth_24h_pct:g}%." + else: + filter_text = "Сигналы режима без дополнительного фильтра роста за 24 ч." + summary = { + "symbols": symbols, + "strategy_mode": mode, + "strategy_title": strategy.STRATEGY_TITLES[mode], + "strategy_params": dict(params), + "period_start_utc": iso(trading_start_ms if trading_start_ms is not None else first_stamp), + "period_end_utc": iso(end_stamp), + "candles": processed_candles, + "initial_capital": initial_capital, + "closed_trades": len(closed), + "wins": wins, + "losses": len(closed) - wins, + "win_rate_pct": wins / len(closed) * 100 if closed else 0.0, + "avg_win_usdt": sum(gains) / len(gains) if gains else 0.0, + "avg_loss_usdt": sum(losses) / len(losses) if losses else 0.0, + "profit_factor": (sum(gains) / -sum(losses)) if losses and sum(losses) < 0 else None, + "signals": signals_total["count"], + "signals_rejected_at_fill": signals_total["rejected_at_fill"], + "stops": sum(row["reason"].startswith("Стоп") for row in closed), + "liquidations": sum(row["reason"].startswith("Ликвидация") for row in closed), + "realized_net_usdt": realized, + "open_positions": len(open_rows), + "open_losing_positions": sum(row["net_usdt"] < 0 for row in open_rows), + "open_net_estimate_usdt": open_net, + "total_net_including_open_usdt": equity_net, + "ending_equity_estimate": initial_capital + equity_net, + "max_drawdown_pct": risk["max_dd_pct"], + "max_drawdown_usdt": risk["max_dd_usdt"], + "min_equity_usdt": risk["min_equity"], + "peak_equity_usdt": risk["peak"], + "max_margin_used_usdt": risk["max_margin"], + "max_simultaneous_positions": risk["max_positions"], + "max_open_positions_limit": max_open_positions, + "skipped_entries_position_limit": risk["skipped_limit"], + "skipped_orders_margin": risk["skipped_margin"], + "longest_hold_hours": max((row["hold_hours"] for row in all_rows), default=0.0), + "universe_mode": universe_mode, + "equity_stop_pct": min_equity_pct, + "equity_stop_triggered": bool(equity_stop["triggered"]), + "equity_stop_value_usdt": equity_floor if min_equity_pct > 0 else None, + "equity_at_stop_usdt": equity_stop["equity"], + "return_pct": equity_net / initial_capital * 100 if initial_capital else 0.0, + "fees_usdt": sum(row["fees_usdt"] for row in all_rows), + "fee_pct_per_side": fee_pct, + "funding_included": funding_by_symbol is not None, + "funding_usdt": funding_total["sum"], + "funding_events": funding_total["events"], + "entry_filter": filter_text, + "filter_was_triggered": filter_triggered, + "entry_allowed_at_end": dict(entry_allowed), + "assumptions": ( + f"Режим {strategy.STRATEGY_TITLES[mode]}. Сигнальные свечи {int(params['timeframe_min'])} мин " + "собираются из минутных; сигнал считается после закрытия свечи и действует до закрытия следующей, " + "вход — по цене открытия минуты (без заглядывания вперёд). Внутри минуты путь O-L-H-C для зелёной и " + "O-H-L-C для красной свечи; разрывы на открытии исполняются по цене открытия; частичный TP и " + "финальный TP — по своему уровню, стоп — по уровню стопа. " + + ("Фильтр BTC: закрытие часа BTCUSDT выше EMA. " if mode == strategy.STRATEGY_BREAKOUT + and params.get("btc_filter", 0) >= 1 else "") + + "Funding-фильтр сигнала использует последнюю расчётную ставку на момент закрытия свечи. " + + _funding_assumption(funding_by_symbol is not None) + + f"Комиссия taker {fee_pct:g}% за сторону. Ликвидация при плече выше 1 (у SHORT и при 1x) " + f"с потерей маржи позиции, поддерживающая маржа {strategy.MAINTENANCE_MARGIN_RATE_PCT:g}%. " + "Проскальзывание не моделируется. Капитал распределяется между сигналами одной минуты в " + "алфавитном порядке тикеров." + ), + } + return {"summary": summary, "trades": all_rows} + + +def save_report(result: dict, output_dir: Path) -> tuple[Path, Path]: + output_dir.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + csv_path = output_dir / f"backtest_{stamp}.csv" + json_path = output_dir / f"backtest_{stamp}.json" + columns = ["id", "symbol", "side", "status", "opened_at", "closed_at", "entry", "exit", "entries", + "margin", "gross_usdt", "fees_usdt", "funding_usdt", "net_usdt", "roi_pct", "hold_hours", + "reason"] + with csv_path.open("w", encoding="utf-8-sig", newline="") as file: + writer = csv.DictWriter(file, fieldnames=columns, extrasaction="ignore") + writer.writeheader() + writer.writerows(result["trades"]) + json_path.write_text(json.dumps(result["summary"], ensure_ascii=False, indent=2), encoding="utf-8") + return csv_path, json_path diff --git a/LinuxServer/keystore.py b/LinuxServer/keystore.py new file mode 100644 index 0000000..6fb060f --- /dev/null +++ b/LinuxServer/keystore.py @@ -0,0 +1,139 @@ +"""Exchange API keys for real trading, one pair (key + secret) per exchange. + +Stored in web_sim_data/api_keys.bin encrypted with Windows DPAPI (CryptProtectData, current user): the file can be +read back only by this Windows user on this computer. The page never receives a secret — only a masked key. +""" + +from __future__ import annotations + +import ctypes +import json +import os +import secrets +import threading +from ctypes import wintypes +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +KEYS_FILE = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT / "web_sim_data")) / "api_keys.bin" +EXCHANGES = {"bybit": "Bybit", "mexc": "MEXC", "htx": "HTX", "gate": "Gate"} +_lock = threading.Lock() + + +class _Blob(ctypes.Structure): + _fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))] + + +def _blob(data: bytes) -> _Blob: + buf = ctypes.create_string_buffer(data, len(data)) + return _Blob(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char))) + + +def _take(blob: _Blob) -> bytes: + try: + return ctypes.string_at(blob.pbData, blob.cbData) + finally: + ctypes.windll.kernel32.LocalFree(blob.pbData) + + +def protect(data: bytes) -> bytes: + if os.name != "nt": + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + nonce = secrets.token_bytes(12) + return b"CSK1" + nonce + AESGCM(_linux_master_key()).encrypt(nonce, data, b"crypto-scam-api-keys-v1") + out = _Blob() + if not ctypes.windll.crypt32.CryptProtectData(ctypes.byref(_blob(data)), "simulator api keys", None, None, None, + 0, ctypes.byref(out)): + raise OSError("не удалось зашифровать ключи (DPAPI)") + return _take(out) + + +def unprotect(data: bytes) -> bytes: + if os.name != "nt": + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + if not data.startswith(b"CSK1") or len(data) < 32: + raise OSError("неподдерживаемый формат или повреждённый файл ключей") + nonce = data[4:16] + try: + return AESGCM(_linux_master_key()).decrypt(nonce, data[16:], b"crypto-scam-api-keys-v1") + except Exception as exc: + raise OSError("не удалось расшифровать API-ключи Linux") from exc + out = _Blob() + if not ctypes.windll.crypt32.CryptUnprotectData(ctypes.byref(_blob(data)), None, None, None, None, 0, + ctypes.byref(out)): + raise OSError("не удалось расшифровать ключи (другой пользователь Windows или другой компьютер?)") + return _take(out) + + +def _linux_master_key() -> bytes: + path = Path(os.environ.get("CRYPTO_SCAM_MASTER_KEY_FILE", "/etc/crypto-scam/master.key")) + try: + key = path.read_bytes() + except OSError as exc: + raise OSError(f"нет серверного ключа шифрования: {path}") from exc + if len(key) != 32: + raise OSError("серверный ключ шифрования должен быть ровно 32 байта") + return key + + +def load(path: Path | None = None) -> dict[str, dict]: + path = path or KEYS_FILE + try: + raw = path.read_bytes() + except OSError: + return {} + try: + data = json.loads(unprotect(raw).decode("utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def _save(data: dict, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + tmp = path.with_suffix(".tmp") + tmp.write_bytes(protect(json.dumps(data).encode("utf-8"))) + try: + os.chmod(tmp, 0o600) + os.chmod(path.parent, 0o700) + except OSError: + pass + tmp.replace(path) + + +def set_keys(exchange: str, api_key: str, api_secret: str, path: Path | None = None) -> str: + if exchange not in EXCHANGES: + return "неизвестная биржа" + api_key, api_secret = (api_key or "").strip(), (api_secret or "").strip() + if not api_key or not api_secret: + return "нужны и API key, и secret" + if len(api_key) > 200 or len(api_secret) > 400 or any(c.isspace() for c in api_key + api_secret): + return "ключ выглядит неверно (пробелы или слишком длинный)" + with _lock: + data = load(path) + data[exchange] = {"key": api_key, "secret": api_secret} + _save(data, path or KEYS_FILE) + return "" + + +def delete_keys(exchange: str, path: Path | None = None) -> None: + with _lock: + data = load(path) + if data.pop(exchange, None) is not None: + _save(data, path or KEYS_FILE) + + +def get(exchange: str, path: Path | None = None) -> tuple[str, str] | None: + d = load(path).get(exchange) + return (d["key"], d["secret"]) if d and d.get("key") and d.get("secret") else None + + +def mask(key: str) -> str: + return key[:4] + "…" + key[-4:] if len(key) > 10 else "…" + key[-2:] + + +def summary(path: Path | None = None) -> dict[str, dict]: + """What the page may see: whether keys are set and a masked key — never the secret.""" + data = load(path) + return {ex: {"name": name, "set": ex in data, "key": mask(data[ex]["key"]) if ex in data else ""} + for ex, name in EXCHANGES.items()} diff --git a/LinuxServer/lead_window.py b/LinuxServer/lead_window.py new file mode 100644 index 0000000..3f0cacf --- /dev/null +++ b/LinuxServer/lead_window.py @@ -0,0 +1,692 @@ +"""Paper trading window: a leader exchange (KuCoin futures) predicts the follower (Bybit perpetual). + +Both feeds are read directly (KuCoin futures and Bybit public WebSockets); MetaScalp is not needed for the data. +When KuCoin's mid price moves more than Bybit's over a short window, a virtual market order is opened on Bybit in +KuCoin's direction; take-profit, stop-loss and a holding-time limit close it. Nothing is ever sent to an exchange. + +Run: py -3 scalp_hint.py (this window) + py -3 scalp_hint.py --legacy (the previous window with all the old strategies) +""" + +from __future__ import annotations + +import json +import queue +import statistics +import time +from collections import deque + +import scalp_hint as sh +import scalp_paper as sp + +MODES = {"lead": "Ведущая биржа: биржа для ставок отстала → догонит", + "vector": "Вектор: куда идёт ведущая, туда ставка", + "basis": "Разрыв цен: ставка на схождение к ведущей"} +COMMON_FIELDS = (("budget", "Бюджет, $"), ("stake", "Ставка, $"), ("leverage", "Плечо"), + ("min_target_pct", "Тейк-профит, %"), ("stop_loss_pct", "Стоп-лосс, %"), + ("max_hold_seconds", "Макс. удержание, с"), ("cooldown_ms", "Пауза после сделки, мс"), + ("max_positions", "Позиций одновременно"), ("entry_gap_seconds", "Между входами, с"), + ("min_confidence", "Мин. уверенность (0–1)")) +INT_FIELDS = {"max_positions"} +MODE_FIELDS = {"lead": (("lead_threshold_pct", "Отставание для входа, %"), ("lead_window_ms", "Окно сравнения, мс")), + "vector": (("vector_window_seconds", "Вектор ведущей за, с"), + ("vector_min_move_pct", "Мин. движение ведущей, %")), + "basis": (("basis_entry_z", "Вход: отклонение, σ"), ("basis_min_gap_pct", "Мин. разрыв, %"))} +AUTO_FIELDS = (("auto_tp_share_pct", "Доля догоняния, %"), ("auto_tp_horizon_seconds", "Горизонт прогноза, с")) +FIELDS = COMMON_FIELDS + MODE_FIELDS["lead"] + MODE_FIELDS["vector"] + MODE_FIELDS["basis"] + AUTO_FIELDS +TEXT_FIELDS = (("lead_ticker", "KuCoin (ведущая), тикер"), ("lead_pool", "Пул DEX Solana (адрес)"), + ("follow_ticker", "Ставки: тикер фьючерса")) +# Its own account and journal, so the old strategies' history stays untouched. +STATE_FILE = sp.DATA_DIR / "lead_paper_state.json" +TRADES_FILE = sp.DATA_DIR / "lead_paper_trades.csv" + + +def inherit_settings(paper: sp.PaperTrader) -> None: + """First run: budget, stake and leverage as they were in the previous window.""" + try: + old = json.loads(sp.STATE_FILE.read_text(encoding="utf-8")).get("settings", {}) + except (OSError, ValueError): + return + for key in ("budget", "stake", "leverage"): + if key in old: + setattr(paper.settings, key, float(old[key])) + paper.ledger.balance = paper.settings.budget + paper.ledger.save() + + +LEAD_MARKETS = {"futures": "KuCoin фьючерсы", "spot": "KuCoin спот", + "raydium": "DEX пул Solana (Raydium / PumpSwap / Meteora / Orca / PancakeSwap)"} +FOLLOW_EXCHANGES = {"bybit": "Bybit фьючерс", "mexc": "MEXC фьючерс"} + + +CONNECTIONS_FILE = sp.DATA_DIR / "lead_connections.json" +CONNECTION_KEYS = ("lead_market", "lead_ticker", "lead_pool", "follow_exchange", "follow_ticker") +# Connections already used; every new one is added so it can be picked again later (removed only by the user). +DEFAULT_CONNECTIONS = [ + {"lead_market": "raydium", "lead_ticker": "SIUSDTM", "lead_pool": "8uwFMFCUDi61rgT1e6bUuDEfaUcN6roSoL7qHkp2NtHk", + "follow_exchange": "mexc", "follow_ticker": "SI_USDT"}, + {"lead_market": "raydium", "lead_ticker": "CLAUDIAUSDTM", "lead_pool": "Fe7bpDYCs74GqiCUF14HwgUMToPKV1d9mDYVX5BTohFr", + "follow_exchange": "mexc", "follow_ticker": "CLAUDIA_USDT"}, + {"lead_market": "futures", "lead_ticker": "MARSCOINUSDTM", "lead_pool": "", + "follow_exchange": "bybit", "follow_ticker": "MARSCOINUSDT"}, + {"lead_market": "spot", "lead_ticker": "MARSCOIN-USDT", "lead_pool": "", + "follow_exchange": "bybit", "follow_ticker": "MARSCOINUSDT"}, +] + + +def connection_name(c: dict) -> str: + coin = c["follow_ticker"].replace("_USDT", "").removesuffix("USDT") + if c["lead_market"] == "raydium": + lead = f"DEX пул {c['lead_pool'][:6]}…" + else: + lead = f"KuCoin {'спот' if c['lead_market'] == 'spot' else 'фьючерс'} {c['lead_ticker']}" + follow = {"bybit": "Bybit", "mexc": "MEXC"}.get(c["follow_exchange"], c["follow_exchange"]) + return f"{coin}: {lead} → {follow} {c['follow_ticker']}" + + +def same_connection(a: dict, b: dict) -> bool: + keys = ["lead_market", "follow_exchange", "follow_ticker"] + keys.append("lead_pool" if a["lead_market"] == "raydium" else "lead_ticker") + return all(a.get(k) == b.get(k) for k in keys) + + +REMOVED_FILE = sp.DATA_DIR / "lead_connections_removed.json" # deleted by the user (× on a web tile) + + +def _read_list(path) -> list[dict]: + try: + saved = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + return [dict(c) for c in saved if isinstance(c, dict) and all(k in c for k in CONNECTION_KEYS)] \ + if isinstance(saved, list) else [] + + +def _write_list(path, items: list[dict]) -> None: + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps(items, ensure_ascii=False, indent=2), encoding="utf-8") + tmp.replace(path) + + +def is_removed(conn: dict, removed_path=None) -> bool: + return any(same_connection(conn, r) for r in _read_list(removed_path or REMOVED_FILE)) + + +def load_connections(path=None, removed_path=None) -> list[dict]: + removed = _read_list(removed_path or REMOVED_FILE) + out = [c for c in _read_list(path or CONNECTIONS_FILE) if c.get("follow_exchange") in FOLLOW_EXCHANGES + and not any(same_connection(c, r) for r in removed)] + for c in DEFAULT_CONNECTIONS: + if not any(same_connection(c, s) for s in out) and not any(same_connection(c, r) for r in removed): + out.append(dict(c)) + return out + + +def remove_connection(conn: dict, path=None, removed_path=None) -> None: + """Delete a connection on the user's request: out of the list, and remembered as removed so neither the + built-in defaults nor the autonomous search bring it back (adding it again by hand undoes this).""" + path, removed_path = path or CONNECTIONS_FILE, removed_path or REMOVED_FILE + _write_list(path, [c for c in _read_list(path) if not same_connection(c, conn)]) + removed = _read_list(removed_path) + if not any(same_connection(conn, r) for r in removed): + removed.append({k: conn[k] for k in CONNECTION_KEYS}) + _write_list(removed_path, removed) + + +def unremove_connection(conn: dict, removed_path=None) -> None: + removed_path = removed_path or REMOVED_FILE + removed = _read_list(removed_path) + keep = [r for r in removed if not same_connection(conn, r)] + if len(keep) != len(removed): + _write_list(removed_path, keep) + + +def remember_connection(connections: list[dict], current: dict, path=None) -> list[dict]: + """Add the current connection to the list (if new) and save; nothing is ever removed. The file is re-read + first, so connections added meanwhile by the autonomous search (meme_matcher/autoscan.py) are kept.""" + current = {k: current[k] for k in CONNECTION_KEYS} + if path is None: + unremove_connection(current) # picked again by hand: no longer deleted + for c in load_connections(path): + if not any(same_connection(c, x) for x in connections): + connections.append(c) + if not any(same_connection(current, c) for c in connections): + connections.append(current) + try: + (path or CONNECTIONS_FILE).write_text(json.dumps(connections, ensure_ascii=False, indent=2), encoding="utf-8") + except OSError: + pass + return connections + + +def futures_ticker(ticker: str, exchange: str) -> str: + """SI_USDT on MEXC, SIUSDT on Bybit / Binance.""" + t = ticker.strip().upper().replace("-", "") + base = t.removesuffix("_USDT").removesuffix("USDT") + return f"{base}_USDT" if exchange == "mexc" else f"{base}USDT" + + +def kucoin_ticker(ticker: str, market: str) -> str: + """MARSCOINUSDTM (futures) ↔ MARSCOIN-USDT (spot).""" + t = ticker.strip().upper() + base = t.removesuffix("-USDT") if t.endswith("-USDT") else t.removesuffix("USDTM").removesuffix("USDT") + return f"{base}-USDT" if market == "spot" else f"{base}USDTM" + + +def validate(values: dict[str, float]) -> str: + if values["stake"] <= 0 or values["budget"] <= 0 or not 1 <= values["leverage"] <= 100: + return "ставка и бюджет больше 0, плечо от 1 до 100" + if values["min_target_pct"] <= 0 or values["stop_loss_pct"] <= 0: + return "тейк-профит и стоп-лосс больше 0" + if values["max_hold_seconds"] <= 0 or values["cooldown_ms"] < 0: + return "удержание больше 0, пауза не меньше 0" + if values["lead_threshold_pct"] <= 0 or values["lead_window_ms"] < 50: + return "порог больше 0, окно не меньше 50 мс" + if values["vector_window_seconds"] <= 0 or values["vector_min_move_pct"] < 0: + return "окно вектора больше 0, мин. движение не меньше 0" + if values["max_positions"] < 1 or values["max_positions"] != int(values["max_positions"]) \ + or values["entry_gap_seconds"] < 0: + return "позиций одновременно — целое число от 1, интервал между входами не меньше 0" + if not 0 <= values["min_confidence"] <= 1: + return "мин. уверенность от 0 до 1 (0 — не проверять)" + if not 0 < values["auto_tp_share_pct"] <= 300 or values["auto_tp_horizon_seconds"] <= 0: + return "доля догоняния от 0 до 300%, горизонт прогноза больше 0" + if values.get("basis_entry_z", 2) <= 0 or values.get("basis_min_gap_pct", 0.15) < 0 \ + or values.get("basis_window_seconds", 60) < 5 or values.get("basis_exit_z", 0.5) < 0 \ + or values.get("basis_exit_z", 0.5) >= values.get("basis_entry_z", 2): + return "разрыв: вход больше 0σ и больше выхода, мин. разрыв ≥ 0, окно не меньше 5 с" + return "" + + +def run() -> None: + import tkinter as tk + from tkinter import ttk + + settings = sp.PaperSettings(mode="lead") + first_run = not STATE_FILE.exists() + paper = sp.PaperTrader(settings, sh.HintSettings(), STATE_FILE, TRADES_FILE) + if first_run: + inherit_settings(paper) + try: + saved = json.loads(STATE_FILE.read_text(encoding="utf-8")).get("settings", {}) + except (OSError, ValueError): + saved = {} + if "cooldown_ms" not in saved: + settings.cooldown_ms = settings.cooldown_seconds * 1000 # the pause used to be in seconds + paper.set_mode(settings.mode if settings.mode in MODES else "lead") + paper.policy = paper._make_policy() + ps = paper.settings + events: queue.Queue = queue.Queue() + book = sh.OrderBook() + state = {"leader_feed": None, "follower_feed": None, "recorder": None, "tick": 0.0, "leader": None, + "leader_status": "KuCoin: подключаюсь…", "follower_status": "Bybit: подключаюсь…", + "last_leader": 0.0, "last_follower": 0.0} + lat_follow: deque[float] = deque(maxlen=200) + lat_lead: deque[float] = deque(maxlen=200) + + root = tk.Tk() + root.title("Ведущая биржа → тестовые ставки на фьючерсе") + root.geometry("1080x860") + body = ttk.Frame(root, padding=10) + body.pack(fill="both", expand=True) + header = tk.StringVar() + ttk.Label(body, textvariable=header, font=("Segoe UI", 10, "bold"), wraplength=940).pack(anchor="w") + + panel = ttk.LabelFrame(body, text="Цены сейчас", padding=6) + panel.pack(fill="x", pady=(6, 4)) + lead_var, follow_var, signal_var = tk.StringVar(), tk.StringVar(), tk.StringVar() + for var in (lead_var, follow_var): + ttk.Label(panel, textvariable=var, font=("Consolas", 11)).pack(anchor="w") + signal_label = tk.Label(panel, textvariable=signal_var, font=("Segoe UI", 13, "bold"), anchor="w") + signal_label.pack(fill="x", pady=(4, 0)) + bar = tk.Canvas(panel, height=16, width=600, highlightthickness=0, background="#e8e8e8") + bar.pack(anchor="w", pady=(2, 0)) + + box = ttk.LabelFrame(body, text="Тестовые сделки на Bybit (виртуальный счёт, ордера на биржу не уходят)", + padding=6) + box.pack(fill="both", expand=True, pady=(4, 0)) + connections = load_connections() + conn_row = ttk.Frame(box) + conn_row.pack(fill="x", pady=(0, 4)) + ttk.Label(conn_row, text="Подключение:").pack(side="left") + conn_var = tk.StringVar() + conn_combo = ttk.Combobox(conn_row, textvariable=conn_var, state="readonly", width=90) + conn_combo.pack(side="left", padx=6) + ttk.Label(conn_row, text="(новые добавляются сами при «Применить», старые не удаляются)", + foreground="#777").pack(side="left") + + def show_connections() -> None: + conn_combo.configure(values=[connection_name(c) for c in connections]) + current = {k: getattr(ps, k) for k in CONNECTION_KEYS} + match = next((c for c in connections if same_connection(c, current)), None) + conn_var.set(connection_name(match) if match else "") + + def on_connection(_event=None) -> None: + c = next((c for c in connections if connection_name(c) == conn_var.get()), None) + if c is None: + return + market_var.set(LEAD_MARKETS[c["lead_market"]]) + follow_ex_var.set(FOLLOW_EXCHANGES[c["follow_exchange"]]) + for key in ("lead_ticker", "lead_pool", "follow_ticker"): + vars_[key].set(c[key]) + apply() + + conn_combo.bind("<>", on_connection) + mode_row = ttk.Frame(box) + mode_row.pack(fill="x", pady=(0, 4)) + ttk.Label(mode_row, text="Режим:").pack(side="left") + mode_var = tk.StringVar(value=MODES[ps.mode]) + mode_combo = ttk.Combobox(mode_row, textvariable=mode_var, values=list(MODES.values()), state="readonly", + width=58) + mode_combo.pack(side="left", padx=6) + ttk.Label(mode_row, text=" Ведущая:").pack(side="left") + market_var = tk.StringVar(value=LEAD_MARKETS.get(ps.lead_market, LEAD_MARKETS["futures"])) + market_combo = ttk.Combobox(mode_row, textvariable=market_var, values=list(LEAD_MARKETS.values()), + state="readonly", width=16) + market_combo.pack(side="left", padx=6) + + ttk.Label(mode_row, text=" Ставки на:").pack(side="left") + follow_ex_var = tk.StringVar(value=FOLLOW_EXCHANGES.get(ps.follow_exchange, FOLLOW_EXCHANGES["bybit"])) + follow_combo = ttk.Combobox(mode_row, textvariable=follow_ex_var, values=list(FOLLOW_EXCHANGES.values()), + state="readonly", width=16) + follow_combo.pack(side="left", padx=6) + + def on_market(_event=None) -> None: + market = next(k for k, v in LEAD_MARKETS.items() if v == market_var.get()) + if market in ("futures", "spot"): + vars_["lead_ticker"].set(kucoin_ticker(vars_["lead_ticker"].get(), market)) + apply() + + market_combo.bind("<>", on_market) + follow_combo.bind("<>", lambda _e: apply()) + form = ttk.Frame(box) + form.pack(fill="x") + vars_: dict[str, tk.StringVar] = {} + mode_cells: dict[str, list] = {m: [] for m in MODES} + + def add_field(key: str, label: str, row: int, column: int): + cell = ttk.Frame(form) + cell.grid(row=row, column=column, sticky="w", padx=(0, 8), pady=(0, 4)) + ttk.Label(cell, text=label).pack(anchor="w") + value = getattr(ps, key) + var = tk.StringVar(value=value if isinstance(value, str) else f"{value:g}") + ttk.Entry(cell, textvariable=var, width=16 if isinstance(value, str) else 12).pack(anchor="w") + vars_[key] = var + return cell + + for i, (key, label) in enumerate(COMMON_FIELDS): + add_field(key, label, i // 6, i % 6) + mode_row_index = (len(COMMON_FIELDS) + 5) // 6 + for mode, items in MODE_FIELDS.items(): + for i, (key, label) in enumerate(items): + mode_cells[mode].append(add_field(key, label, mode_row_index, i)) + for i, (key, label) in enumerate(TEXT_FIELDS): + add_field(key, label, mode_row_index, 2 + i) + auto_var = tk.BooleanVar(value=ps.auto_tp) + learn_var = tk.BooleanVar(value=ps.auto_tp_learn) + auto_cell = ttk.Frame(form) + auto_cell.grid(row=mode_row_index + 1, column=0, columnspan=2, sticky="w", pady=(0, 4)) + ttk.Checkbutton(auto_cell, text="Авто тейк-профит по прогнозу:\nтейк = доля × отставание фьючерса от ведущей", + variable=auto_var, command=lambda: apply()).pack(anchor="w") + for i, (key, label) in enumerate(AUTO_FIELDS): + add_field(key, label, mode_row_index + 1, 2 + i) + learn_cell = ttk.Frame(form) + learn_cell.grid(row=mode_row_index + 1, column=4, columnspan=2, sticky="w", pady=(0, 4)) + ttk.Checkbutton(learn_cell, text="Учить долю на истории сигналов\n(после 10 сигналов — вместо ручной)", + variable=learn_var, command=lambda: apply()).pack(anchor="w") + + def current_mode() -> str: + return next(k for k, v in MODES.items() if v == mode_var.get()) + + def show_mode_fields() -> None: + for mode, cells in mode_cells.items(): + for cell in cells: + cell.grid() if mode == current_mode() else cell.grid_remove() + + def on_mode(_event=None) -> None: + show_mode_fields() + apply() + + mode_combo.bind("<>", on_mode) + show_mode_fields() + actions = ttk.Frame(box) + actions.pack(fill="x", pady=(2, 2)) + enabled_var = tk.BooleanVar(value=ps.enabled) + start_btn = tk.Button(actions, text="▶ Старт", width=9, command=lambda: set_trading(True)) + start_btn.pack(side="left") + stop_btn = tk.Button(actions, text="■ Стоп", width=9, command=lambda: set_trading(False)) + stop_btn.pack(side="left", padx=(4, 0)) + trading_label = tk.Label(actions, text="", font=("Segoe UI", 9, "bold")) + trading_label.pack(side="left", padx=8) + + def show_trading() -> None: + on = ps.enabled + start_btn.configure(state="disabled" if on else "normal", bg="#d8f0dc" if on else "SystemButtonFace") + stop_btn.configure(state="normal" if on else "disabled", bg="SystemButtonFace" if on else "#f6d6d6") + trading_label.configure(text="Сделки открываются" if on else + "Новые сделки остановлены · цены, сравнение и прогноз продолжают работать", + fg="#1f8a4c" if on else "#c23b3b") + + def set_trading(on: bool) -> None: + """Start/stop opening new paper positions only; the feeds, the comparison, the forecast learning and the + exits of positions already open keep running.""" + enabled_var.set(on) + ps.enabled = on + paper.ledger.save() + show_trading() + message.set("Старт: новые сделки открываются" if on else + "Стоп: новые сделки не открываются; открытые позиции закроются по тейку, стопу или времени") + + ttk.Button(actions, text="Применить", command=lambda: apply()).pack(side="left", padx=6) + ttk.Button(actions, text="Закрыть позицию", command=lambda: paper.close_now(book, time.time(), "вручную")).pack( + side="left") + ttk.Button(actions, text="Сбросить счёт", command=lambda: reset()).pack(side="left", padx=6) + cut_row = ttk.Frame(box) + cut_row.pack(fill="x", pady=(0, 2)) + cut_var = tk.BooleanVar(value=ps.cut_loss) + ttk.Checkbutton(cut_row, text="Сразу закрывать, если ушло в минус на", variable=cut_var, + command=lambda: apply()).pack(side="left") + cut_ticks_var = tk.StringVar(value=str(ps.cut_loss_ticks)) + ttk.Entry(cut_row, textvariable=cut_ticks_var, width=4).pack(side="left", padx=4) + ttk.Label(cut_row, text="шаг(а) цены (середина Bybit против цены при входе) — и сразу брать следующий сигнал " + "без паузы").pack(side="left") + tick_row = ttk.Frame(box) + tick_row.pack(fill="x", pady=(0, 2)) + one_tick_var = tk.BooleanVar(value=ps.one_per_tick) + ttk.Checkbutton(tick_row, text="Не больше одной позиции на один шаг цены Bybit (в каждую сторону); всего " + "параллельно — до «Позиций одновременно»", variable=one_tick_var, + command=lambda: apply()).pack(side="left") + record_var = tk.BooleanVar(value=True) + ttk.Checkbutton(actions, text=f"Записывать поток в {sp.RECORD_DIR.name}\\", variable=record_var).pack( + side="left", padx=10) + summary, status, position, message = (tk.StringVar() for _ in range(4)) + ttk.Label(box, textvariable=summary, font=("Segoe UI", 10, "bold")).pack(anchor="w") + ttk.Label(box, textvariable=status, foreground="#1d4f91", wraplength=940).pack(anchor="w") + ttk.Label(box, textvariable=position, wraplength=940).pack(anchor="w") + ttk.Label(box, textvariable=message, foreground="#555", wraplength=940).pack(anchor="w") + columns = ("time", "ticker", "side", "qty", "usd", "entry", "exit", "pct", "net", "fee", "reason", "hold", "why") + heads = {"time": "Закрыта (UTC)", "ticker": "Тикер", "side": "Напр.", "qty": "Объём", "usd": "Объём в $", + "entry": "Цена откр.", "exit": "Цена закр.", "pct": "Процент", "net": "Чистая, $", "fee": "Комиссия, $", + "reason": "Причина", "hold": "Сек.", "why": "Почему вошли"} + widths = {"time": 115, "ticker": 95, "side": 45, "qty": 65, "usd": 60, "entry": 75, "exit": 75, "pct": 60, + "net": 70, "fee": 65, "reason": 60, "hold": 40, "why": 200} + table = ttk.Frame(box) + table.pack(fill="both", expand=True, pady=(4, 0)) + tree = ttk.Treeview(table, columns=columns, show="headings", height=10) + for col in columns: + tree.heading(col, text=heads[col]) + tree.column(col, width=widths[col], anchor="center") + tree.tag_configure("win", foreground="#13843b") + tree.tag_configure("loss", foreground="#c62828") + scroll = ttk.Scrollbar(table, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scroll.set) + tree.pack(side="left", fill="both", expand=True) + scroll.pack(side="right", fill="y") + shown = {"count": -1} + + def start_feeds() -> None: + for key in ("leader_feed", "follower_feed"): + if state[key]: + state[key].stop() + if state["recorder"]: + state["recorder"].close() + state["recorder"] = None + book.clear() + lat_follow.clear() + lat_lead.clear() + state["leader"] = None + paper.policy = paper._make_policy() + if ps.follow_exchange == "mexc": + state["tick"], size = sh.mexc_contract(ps.follow_ticker) + state["follower_feed"] = sh.MexcFeed(ps.follow_ticker, events, size) + else: + state["tick"] = sh.bybit_tick(ps.follow_ticker) + state["follower_feed"] = sh.BybitFeed(ps.follow_ticker, events) + if state["tick"] <= 0: + message.set(f"{FOLLOW_EXCHANGES[ps.follow_exchange]}: нет тикера {ps.follow_ticker} — проверьте настройку") + state["follower_status"] = f"{FOLLOW_EXCHANGES[ps.follow_exchange]}: подключаюсь…" + if ps.lead_market == "raydium": + if not ps.lead_pool: + message.set("Укажите адрес пула Raydium (например, из Meme Matcher)") + state["leader_feed"] = None + else: + state["leader_feed"] = sh.RaydiumFeed(ps.lead_pool, events) + else: + state["leader_feed"] = sh.KucoinFeed(ps.lead_ticker, events, spot=ps.lead_market == "spot") + state["leader_status"] = f"{LEAD_MARKETS[ps.lead_market]}: подключаюсь…" + state["follower_feed"].start() + if state["leader_feed"]: + state["leader_feed"].start() + + def apply() -> None: + try: + values = {key: float(vars_[key].get().replace(",", ".")) for key, _ in FIELDS} + except ValueError: + message.set("Проверьте настройки: нужны числа") + return + problem = validate(values) + try: + cut_ticks = int(cut_ticks_var.get()) + if cut_ticks < 1: + raise ValueError + except ValueError: + problem = problem or "минус для закрытия — целое число шагов, не меньше 1" + if problem: + message.set(f"Проверьте настройки: {problem}") + return + ps.cut_loss = bool(cut_var.get()) + ps.one_per_tick = bool(one_tick_var.get()) + ps.auto_tp = bool(auto_var.get()) + ps.auto_tp_learn = bool(learn_var.get()) + ps.cut_loss_ticks = cut_ticks + # tickers upper case; a Solana pool address is case-sensitive + tickers = {key: vars_[key].get().strip() if key == "lead_pool" else vars_[key].get().strip().upper() + for key, _ in TEXT_FIELDS} + budget_changed = values["budget"] != ps.budget + for key, value in values.items(): + setattr(ps, key, int(value) if key in INT_FIELDS else value) + ps.enabled = bool(enabled_var.get()) + market = next(k for k, v in LEAD_MARKETS.items() if v == market_var.get()) + follow = next(k for k, v in FOLLOW_EXCHANGES.items() if v == follow_ex_var.get()) + tickers["follow_ticker"] = futures_ticker(tickers["follow_ticker"], follow) + vars_["follow_ticker"].set(tickers["follow_ticker"]) + if market in ("futures", "spot"): + tickers["lead_ticker"] = kucoin_ticker(tickers["lead_ticker"], market) + vars_["lead_ticker"].set(tickers["lead_ticker"]) + restart = (tickers["lead_ticker"] != ps.lead_ticker or tickers["follow_ticker"] != ps.follow_ticker + or tickers["lead_pool"] != ps.lead_pool or market != ps.lead_market + or follow != ps.follow_exchange) + if restart: + paper.close_now(book, time.time(), "смена тикера") + ps.lead_ticker, ps.follow_ticker = tickers["lead_ticker"], tickers["follow_ticker"] + ps.lead_pool, ps.lead_market, ps.follow_exchange = tickers["lead_pool"], market, follow + if budget_changed and not paper.trades and paper.position is None: + paper.ledger.balance = ps.budget + mode = current_mode() + if mode != ps.mode: + paper.close_now(book, time.time(), "смена режима") + paper.set_mode(mode) # the new policy gathers its own window of prices first + paper.ledger.save() + remember_connection(connections, {k: getattr(ps, k) for k in CONNECTION_KEYS}) + show_connections() + if restart: + start_feeds() + message.set("Настройки применены" + (" · новый бюджет начнёт действовать после «Сбросить счёт»" + if budget_changed and (paper.trades or paper.position) else "")) + + def reset() -> None: + apply() + paper.reset() + shown["count"] = -1 + message.set(f"Счёт сброшен: {ps.budget:g}$") + + def pump() -> None: + if record_var.get() and state["recorder"] is None and state["tick"] > 0: + try: + state["recorder"] = sp.Recorder(ps.follow_ticker, 111 if ps.follow_exchange == "bybit" else 0, + state["tick"]) + except OSError: + pass + recorder = state["recorder"] if record_var.get() else None + for _ in range(5000): + try: + kind, data = events.get_nowait() + except queue.Empty: + break + now = time.time() + if kind == "book_snapshot": + book.apply_snapshot(data) + state["last_follower"] = now + if recorder: + recorder.write("S", {"asks": data.get("asks", []), "bids": data.get("bids", [])}, now) + paper.on_book(now, book, state["tick"]) + elif kind == "book_update": + book.apply_updates(data) + state["last_follower"] = now + if recorder: + recorder.write("U", data, now) + paper.on_book(now, book, state["tick"]) + elif kind == "trades": + if recorder: + recorder.write("T", data, now) + for raw in data: + try: + trade = sh.Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) + except (KeyError, TypeError, ValueError): + continue + paper.on_trade(trade) + elif kind == "leader": + bid, ask = data + state["leader"] = (bid, ask) + state["last_leader"] = now + if recorder: + recorder.write("L", [bid, ask], now) + paper.on_leader(now, bid, ask) + elif kind == "latency": + lat_follow.append(float(data)) + elif kind == "leader_latency": + lat_lead.append(float(data)) + elif kind == "status": + state["follower_status"] = data + elif kind == "leader_status": + state["leader_status"] = data + root.after(50, pump) + + def threshold() -> float: + return ps.vector_min_move_pct if ps.mode == "vector" else ps.lead_threshold_pct + + def draw_signal(value: float) -> None: + bar.delete("all") + width, mid = 600, 300 + thr = threshold() + scale = mid / max(thr * 3, 0.01) + x = mid + max(-mid, min(mid, value * scale)) + bar.create_rectangle(min(mid, x), 3, max(mid, x), 13, fill="#2e9d57" if value >= 0 else "#d04a4a", + outline="") + for t in (thr, -thr): + tx = mid + t * scale + bar.create_line(tx, 0, tx, 16, fill="#333", dash=(2, 2)) + bar.create_line(mid, 0, mid, 16, fill="#999") + + def refresh() -> None: + now = time.time() + lf = f" · задержка ~{statistics.median(lat_follow):.0f} мс" if len(lat_follow) >= 5 else "" + ll = f" · задержка ~{statistics.median(lat_lead):.0f} мс" if len(lat_lead) >= 5 else "" + header.set(f"{state['leader_status']}{ll} | {state['follower_status']}{lf}") + pol = paper.policy + if state["leader"]: + bid, ask = state["leader"] + age = (now - state["last_leader"]) * 1000 + if ps.lead_market == "raydium": + lead_var.set(f"{pol.L:8s} пул {ps.lead_pool[:10]}… цена {bid:<12.10g} (по последнему обмену) · " + f"{age:.0f} мс назад") + else: + lead_var.set(f"{pol.L:8s} {ps.lead_ticker:16s} bid {bid:<12.10g} ask {ask:<12.10g} mid " + f"{(bid + ask) / 2:<12.10g} спред {(ask - bid) / ((bid + ask) / 2) * 100:.3f}% · " + f"{age:.0f} мс назад") + best_bid, best_ask = book.best() + if best_bid and best_ask: + age = (now - state["last_follower"]) * 1000 + follow_var.set(f"{pol.F:8s} {ps.follow_ticker:16s} bid {best_bid:<12.10g} ask {best_ask:<12.10g} mid " + f"{(best_bid + best_ask) / 2:<12.10g} спред {(best_ask - best_bid) / ((best_ask + best_bid) / 2) * 100:.3f}%" + f" · {age:.0f} мс назад") + sig = getattr(pol, "signal", 0.0) + thr = threshold() + if ps.mode == "vector": + active = f"{'LONG' if sig > 0 else 'SHORT'}: {pol.L} {'растёт' if sig > 0 else 'падает'} " \ + f"{sig:+.3f}% за {ps.vector_window_seconds:g} с" + idle = f"Ждём направление: {pol.L} {sig:+.3f}% за {ps.vector_window_seconds:g} с (порог ±{thr:g}%)" + else: + active = f"{'LONG' if sig > 0 else 'SHORT'}: {pol.F} отстаёт от {pol.L} на {sig:+.3f}%" + idle = f"Ждём: отставание {sig:+.3f}% (порог ±{thr:g}%)" + conf = getattr(pol, "conf", 0.0) + conf_text = f" · уверенность {conf:.2f} (порог {ps.min_confidence:g})" + active += conf_text + idle += conf_text + if abs(sig) >= thr and thr > 0 and conf >= ps.min_confidence: + signal_var.set(active) + signal_label.configure(fg="#1f8a4c" if sig > 0 else "#c23b3b") + else: + signal_var.set(idle) + signal_label.configure(fg="#666") + draw_signal(sig) + status.set(pol.status) + positions = paper.ledger.positions + if positions: + best_bid, best_ask = book.best() + lines = [f"Открыто позиций: {len(positions)} из {ps.max_positions} · вместе сейчас " + f"{paper.unrealized(book):+.4f}$"] + for pos in positions[:8]: + price = best_bid if pos.side == "LONG" else best_ask + pnl = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty if price else 0.0 + lines.append(f" {pos.side} {pos.qty:.6g} по {pos.entry:.10g} · тейк {pos.target:.10g} · стоп " + f"{pos.stop:.10g} · {now - pos.opened:.0f} из {ps.max_hold_seconds:g} с · {pnl:+.4f}$") + if len(positions) > 8: + lines.append(f" … и ещё {len(positions) - 8}") + position.set("\n".join(lines)) + else: + position.set("Позиции нет" + ("" if ps.enabled else " · новые сделки остановлены (кнопка «Старт»)")) + summary.set(paper.summary()) + if paper.message: + message.set(paper.message) + if shown["count"] != len(paper.trades): + shown["count"] = len(paper.trades) + tree.delete(*tree.get_children()) + for t in reversed(paper.trades[-300:]): + tree.insert("", "end", values=( + t.closed_utc[:19].replace("T", " "), t.ticker, t.side, f"{t.qty:.6g}", f"{t.notional_usd:.2f}", + f"{t.entry:.10g}", f"{t.exit:.10g}", f"{t.pct:+.3f}%", f"{t.net_usd:+.4f}", f"{t.fee_usd:.4f}", + t.reason, f"{t.hold_seconds:.0f}", t.regime), tags=("win" if t.net_usd > 0 else "loss",)) + if now - state.get("conn_check", 0.0) > 30: + # pick up connections added by the autonomous search without a restart + state["conn_check"] = now + before = len(connections) + for c in load_connections(): + if not any(same_connection(c, x) for x in connections): + connections.append(c) + if len(connections) != before: + show_connections() + message.set(f"Автопоиск добавил подключений: {len(connections) - before} — смотрите список «Подключение»") + root.after(300, refresh) + + def on_close() -> None: + if state["recorder"]: + state["recorder"].close() + for key in ("leader_feed", "follower_feed"): + if state[key]: + state[key].stop() + paper.ledger.save() + root.destroy() + + root.protocol("WM_DELETE_WINDOW", on_close) + start_feeds() + show_trading() + remember_connection(connections, {k: getattr(ps, k) for k in CONNECTION_KEYS}) + show_connections() + pump() + refresh() + root.mainloop() + + +if __name__ == "__main__": + run() diff --git a/LinuxServer/live.py b/LinuxServer/live.py new file mode 100644 index 0000000..3eec55e --- /dev/null +++ b/LinuxServer/live.py @@ -0,0 +1,1453 @@ +"""Real orders on the exchanges (signed REST): balances, market orders on spot and on USDT perpetuals. + +Every client speaks in coins and per-coin prices, whatever the exchange's own units are (1000PEPE units on Bybit / +Binance, contracts on MEXC / HTX / Gate); quantities are rounded down to the exchange's lot step. + + spot_buy(base, usdt) market buy for a USDT amount + spot_sell(base, coins) market sell + spot_free(base) coins available on the spot / unified account + fut_order(symbol, side, coins, reduce_only) market order on the perpetual ("buy" / "sell") + fut_round(symbol, coins) the coins an order can actually have (lot step) + balances() USDT on spot and futures, for the «Проверить» button + +Errors from the exchange are raised as LiveError with the exchange's own message. +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import http.client +import json +import math +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from datetime import datetime, timezone + +from arb import split_base + +TIMEOUT = 15 + + +class LiveError(Exception): + """sent=True: the order may have reached the exchange (no answer, or its fill could not be confirmed) — + the caller must treat the position as possibly open and close it later; sent=False: certainly not placed.""" + + def __init__(self, message: str, sent: bool = False, order_id: str = "") -> None: + super().__init__(message) + self.sent, self.order_id = sent, order_id + + +class CircuitBreaker(LiveError): + """The exchange cancelled a market order unfilled to protect it from a wide spread (HTX 410): nothing was + traded — the same order can go as a limit at the book's price.""" + + +def _unsent(fn): + """Run the preparation of an order (rules, rounding): any failure there means nothing was sent.""" + try: + return fn() + except LiveError as exc: + raise LiveError(str(exc), sent=False) from None + + +def _placed(order_id: str, fn): + """Confirm the fill of an order the exchange has accepted: a failure here leaves the order possibly filled.""" + try: + return fn() + except LiveError as exc: + raise LiveError(f"ордер {order_id} принят биржей, но исполнение не подтверждено: {exc}", sent=True, + order_id=order_id) from None + + +@dataclass +class Fill: + coins: float # filled, in coins + price: float # average per coin + fee_usd: float # fee in $ as charged by the exchange (estimated from the taker rate only if exact=False) + order_id: str + raw: dict = field(default_factory=dict, repr=False) + exact: bool = True # price and fee are the exchange's own figures + tpsl: str = "" # opening order: "на бирже" — TP/SL set on the exchange; otherwise why not + + +def _floor(value: float, step: float) -> float: + if step <= 0: + return value + n = math.floor(value / step + 1e-9) + decimals = max(0, -int(math.floor(math.log10(step)))) if step < 1 else 0 + return round(n * step, decimals + 2) + + +def _tick(price: float, tick: float) -> float: + """Price rounded to the exchange's price step.""" + if tick <= 0: + return price + decimals = max(0, -int(math.floor(math.log10(tick)))) if tick < 1 else 0 + return round(round(price / tick) * tick, decimals + 2) + + +def _liq(rows: list, key: str, units: float, size) -> float | None: + """Liquidation price per coin from the exchange's position rows (the first row with a size); None when there + is no position or the exchange reports none (0 / empty: e.g. too much margin to ever be liquidated).""" + for r in rows or []: + if not isinstance(r, dict) or size(r) <= 0: + continue + try: + v = float(r.get(key) or 0) + except (TypeError, ValueError): + return None + return v / units if v > 0 else None + return None + + +def _num(text: float) -> str: + """A number for an order: its shortest exact decimal form, never an exponent. (12 fixed decimals printed the + float's noise on large amounts: 27481.05 → «27481.049999999999», refused by MEXC as a wrong quantity scale.)""" + from decimal import Decimal + s = format(Decimal(repr(round(float(text), 12))), "f") # 0.1 + 0.2 → «0.3», not «0.30000000000000004» + return s.rstrip("0").rstrip(".") if "." in s else s + + +# --- persistent connections ---------------------------------------------------------------------------------- +# A new HTTPS connection costs a TCP + TLS handshake (~70 ms more per order through the VPN, measured to MEXC); +# connections are kept open per host and reused, and warm_up() keeps one per exchange alive between orders. +IDLE_S = 15.0 # a connection idle longer than this is not reused (servers drop idle keep-alive ones) +_pool: dict[tuple[str, str], list[tuple[http.client.HTTPConnection, float]]] = {} +_pool_lock = threading.Lock() + + +def _take(scheme: str, host: str) -> tuple[http.client.HTTPConnection, bool]: + """(connection, reused) — an idle open connection to the host, or a new one.""" + now = time.monotonic() + with _pool_lock: + idle = _pool.get((scheme, host), []) + while idle: + conn, last = idle.pop() + if now - last < IDLE_S: + return conn, True + conn.close() + cls = http.client.HTTPSConnection if scheme == "https" else http.client.HTTPConnection + return cls(host, timeout=TIMEOUT), False + + +def _give_back(scheme: str, host: str, conn: http.client.HTTPConnection) -> None: + with _pool_lock: + idle = _pool.setdefault((scheme, host), []) + if len(idle) < 4: + idle.append((conn, time.monotonic())) + return + conn.close() + + +def _http(method: str, url: str, headers: dict | None = None, body: bytes | None = None) -> dict | list: + parts = urllib.parse.urlsplit(url) + target = parts.path + (f"?{parts.query}" if parts.query else "") + hdrs = {"User-Agent": "Mozilla/5.0", "Connection": "keep-alive", **(headers or {})} + for attempt in (1, 2): + conn, reused = _take(parts.scheme, parts.netloc) + try: + conn.request(method, target, body=body, headers=hdrs) + resp = conn.getresponse() + data = resp.read() + except (http.client.HTTPException, OSError) as exc: + conn.close() + # a reused connection the server had already closed: a read is simply repeated on a new one + if reused and method == "GET" and attempt == 1: + continue + # no answer: a POST may still have been executed by the exchange + raise LiveError(f"нет связи: {exc}", sent=method in ("POST", "DELETE")) from None + if resp.getheader("Connection", "").lower() == "close" or resp.will_close: + conn.close() + else: + _give_back(parts.scheme, parts.netloc, conn) + if resp.status >= 400: + 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("нет связи") + + +WARM_URLS = {"bybit": ["https://api.bybit.com/v5/market/time"], + "binance": ["https://fapi.binance.com/fapi/v1/ping", "https://api.binance.com/api/v3/ping"], + "mexc": ["https://contract.mexc.com/api/v1/contract/ping", "https://api.mexc.com/api/v3/ping"], + "htx": ["https://api.hbdm.com/api/v1/timestamp", "https://api.huobi.pro/v1/common/timestamp"], + "gate": ["https://api.gateio.ws/api/v4/spot/time"]} + + +def warm_up(exchanges) -> dict[str, float]: + """One cheap public request per API host of these exchanges, so an open connection is waiting for the next + order; returns the round trip per host in ms (shown on the page).""" + out = {} + for ex in exchanges: + for url in WARM_URLS.get(ex, []): + t = time.perf_counter() + try: + _http("GET", url) + out[urllib.parse.urlsplit(url).netloc] = (time.perf_counter() - t) * 1000 + except LiveError: + pass + return out + + +def _units(symbol_base: str) -> float: + """Coins in one unit of the symbol: 1000PEPE → 1000.""" + return split_base(symbol_base)[1] + + +# -------------------------------------------------------------------------------------------------------------- +class Bybit: + name, host = "Bybit", "https://api.bybit.com" + spot_fee, fut_fee = 0.1, 0.055 + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + + def _call(self, method: str, path: str, params: dict | None = None) -> dict: + ts, recv = str(int(time.time() * 1000)), "10000" + if method == "GET": + query = urllib.parse.urlencode(params or {}) + payload, url, body = ts + self.key + recv + query, f"{self.host}{path}?{query}", None + else: + text = json.dumps(params or {}) + payload, url, body = ts + self.key + recv + text, self.host + path, text.encode() + sign = hmac.new(self.secret.encode(), payload.encode(), hashlib.sha256).hexdigest() + d = _http(method, url, {"X-BAPI-API-KEY": self.key, "X-BAPI-TIMESTAMP": ts, "X-BAPI-RECV-WINDOW": recv, + "X-BAPI-SIGN": sign, "Content-Type": "application/json"}, body) + if d.get("retCode") != 0: + raise LiveError(f"Bybit {d.get('retCode')}: {d.get('retMsg')}") + return d["result"] + + def _rule(self, category: str, symbol: str) -> dict: + k = f"{category}:{symbol}" + if k not in self.rules: + items = _http("GET", f"{self.host}/v5/market/instruments-info?category={category}&symbol={symbol}") + items = items.get("result", {}).get("list") or [] + if not items: + raise LiveError(f"Bybit: нет инструмента {symbol}") + lot = items[0]["lotSizeFilter"] + self.rules[k] = {"step": float(lot.get("qtyStep") or lot.get("basePrecision") or 0), + "min": float(lot.get("minOrderQty") or 0), + "tick": float((items[0].get("priceFilter") or {}).get("tickSize") or 0)} + return self.rules[k] + + def _fill(self, category: str, order_id: str) -> dict: + for attempt in range(10): + for path in ("/v5/order/realtime", "/v5/order/history"): + items = self._call("GET", path, {"category": category, "orderId": order_id}).get("list") or [] + if items and items[0].get("orderStatus") in ("Filled", "PartiallyFilledCanceled", "Cancelled", + "Rejected", "Deactivated"): + return items[0] + time.sleep(0.3) + raise LiveError(f"Bybit: ордер {order_id} не исполнился за 3 с") + + # The perp account's position mode: one-way (positionIdx 0) or hedge (1 = the long side, 2 = the short side). + # Learned from the exchange: an order with the wrong index is refused (10001 «position idx not match position + # mode») — nothing was placed, so it is sent once more with the other mode's index. + hedge = False + + def _idx(self, side: str, reduce_only: bool) -> int: + if not self.hedge: + return 0 + short = (side == "Sell") != bool(reduce_only) # a sale opens a short, a reduce-only buy closes one + return 2 if short else 1 + + def _create(self, params: dict) -> dict: + if params.get("category") == "linear": + params["positionIdx"] = self._idx(params["side"], params.get("reduceOnly", False)) + try: + return self._call("POST", "/v5/order/create", params) + except LiveError as exc: + if params.get("category") != "linear" or "10001" not in str(exc) or "position idx" not in str(exc).lower(): + raise + self.hedge = not self.hedge + params["positionIdx"] = self._idx(params["side"], params.get("reduceOnly", False)) + return self._call("POST", "/v5/order/create", params) + + def _order(self, category: str, params: dict, fee_rate: float, mult: float = 1.0) -> Fill: + oid = self._create({"category": category, "orderType": "Market", **params})["orderId"] + o = _placed(oid, lambda: self._fill(category, oid)) + units, value = float(o.get("cumExecQty") or 0), float(o.get("cumExecValue") or 0) + if units <= 0: + raise LiveError(f"Bybit: ордер не исполнен ({o.get('orderStatus')})") + coins = units * mult + fee = float(o.get("cumExecFee") or 0) + fee_usd = fee * value / units if category == "spot" and params["side"] == "Buy" else fee # buy fee is in coins + return Fill(coins, value / coins, fee_usd or value * fee_rate / 100, oid, o) + + def spot_buy(self, base: str, usdt: float) -> Fill: + return self._order("spot", {"symbol": f"{base}USDT", "side": "Buy", "qty": _num(round(usdt, 2)), + "marketUnit": "quoteCoin"}, self.spot_fee) + + def spot_sell(self, base: str, coins: float) -> Fill: + qty = _unsent(lambda: _floor(coins, self._rule("spot", f"{base}USDT")["step"])) + return self._order("spot", {"symbol": f"{base}USDT", "side": "Sell", "qty": _num(qty), + "marketUnit": "baseCoin"}, self.spot_fee) + + def spot_coins(self) -> dict[str, float]: + """Free coins on the spot account, all at once (the stock spot–spot trades sell from).""" + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})["list"] + return {c["coin"]: float(c.get("walletBalance") or 0) - float(c.get("locked") or 0) + for c in ((acc[0].get("coin") or []) if acc else []) if c.get("coin") != "USDT"} + + def spot_free(self, base: str) -> float: + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": base})["list"] + coins = acc[0].get("coin") or [] if acc else [] + return float(coins[0].get("walletBalance") or 0) - float(coins[0].get("locked") or 0) if coins else 0.0 + + def fut_round(self, symbol: str, coins: float) -> float: + mult = _units(symbol[:-4]) + r = self._rule("linear", symbol) + units = _floor(coins / mult, r["step"]) + return units * mult if units >= r["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + """The smallest perp order, in coins.""" + r = self._rule("linear", symbol) + return max(r["min"], r["step"]) * _units(symbol[:-4]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + """tp / sl (per coin): take-profit and stop-loss of the whole position, kept by the exchange itself and + executed at market when the last price reaches them (removed by Bybit when the position closes).""" + mult = _units(symbol[:-4]) + rule = _unsent(lambda: self._rule("linear", symbol)) + units = _floor(coins / mult, rule["step"]) + if units <= 0: + raise LiveError("Bybit: количество меньше шага лота") + params = {"symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "qty": _num(units), + "reduceOnly": reduce_only} + if not reduce_only and (tp or sl): + params["tpslMode"] = "Full" + if tp: + params.update(takeProfit=_num(_tick(tp * mult, rule["tick"])), tpTriggerBy="LastPrice") + if sl: + params.update(stopLoss=_num(_tick(sl * mult, rule["tick"])), slTriggerBy="LastPrice") + fill = self._order("linear", params, self.fut_fee, mult) + if not reduce_only and (tp or sl): + fill.tpsl = "на бирже" + return fill + + def fut_position(self, symbol: str) -> float: + """Coins of the open perp position on the exchange: + long, − short, 0 none.""" + items = self._call("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}).get("list") or [] + mult = _units(symbol[:-4]) + return sum(float(i.get("size") or 0) * mult * (1 if i.get("side") == "Buy" else -1) for i in items) + + def fut_liq_price(self, symbol: str) -> float | None: + """The exchange's liquidation price of the open position, per coin (None: no position / not reported).""" + items = self._call("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}).get("list") or [] + return _liq(items, "liqPrice", _units(symbol[:-4]), lambda i: float(i.get("size") or 0)) + + def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]: + """Fills on `side` ("buy" / "sell") of the symbol since `since` (unix s): how the exchange closed it.""" + items = self._call("GET", "/v5/execution/list", {"category": "linear", "symbol": symbol, "limit": 100, + "startTime": int(since * 1000)}).get("list") or [] + mult, want = _units(symbol[:-4]), "Buy" if side == "buy" else "Sell" + return [Fill(float(e["execQty"]) * mult, float(e["execPrice"]) / mult, float(e.get("execFee") or 0), + e.get("orderId", "")) for e in items if e.get("side") == want and e.get("execType", "Trade") == "Trade"] + + def fut_cancel_all(self, symbol: str) -> None: + self._call("POST", "/v5/order/cancel-all", {"category": "linear", "symbol": symbol}) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + """Reduce-only LIMIT order closing the position at `price` (per coin) or better; `side` closes it.""" + mult = _units(symbol[:-4]) + rule = self._rule("linear", symbol) + return self._create({ + "category": "linear", "symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "orderType": "Limit", + "qty": _num(_floor(coins / mult, rule["step"])), "price": _num(_tick(price * mult, rule["tick"])), + "timeInForce": "GTC", "reduceOnly": True})["orderId"] + + # --- resting limit orders on the perp: placed, watched, cancelled --------------------------------------- + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + mult = _units(symbol[:-4]) + rule = _unsent(lambda: self._rule("linear", symbol)) + units = _floor(coins / mult, rule["step"]) + if units <= 0: + raise LiveError("Bybit: количество меньше шага лота") + return self._create({ + "category": "linear", "symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "orderType": "Limit", + "qty": _num(units), "price": _num(_tick(price * mult, rule["tick"])), "timeInForce": "GTC", + "reduceOnly": reduce_only})["orderId"] + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + """{"coins": filled, "price": average per coin, "fee": $, "final": no longer working}.""" + mult = _units(symbol[:-4]) + for path in ("/v5/order/realtime", "/v5/order/history"): + items = self._call("GET", path, {"category": "linear", "symbol": symbol, "orderId": order_id}).get("list") or [] + if items: + o = items[0] + units, value = float(o.get("cumExecQty") or 0), float(o.get("cumExecValue") or 0) + return {"coins": units * mult, "price": value / (units * mult) if units else 0.0, + "fee": float(o.get("cumExecFee") or 0), + "final": o.get("orderStatus") not in ("New", "PartiallyFilled", "Untriggered")} + raise LiveError(f"Bybit: ордер {order_id} не найден") + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._call("POST", "/v5/order/cancel", {"category": "linear", "symbol": symbol, "orderId": order_id}) + + def fut_fills(self, symbol: str, since: float) -> list[dict]: + """Every fill of the symbol since `since` as the exchange recorded it (for trades and statistics).""" + mult, out, cursor = _units(symbol[:-4]), [], "" + for _ in range(10): + params = {"category": "linear", "symbol": symbol, "limit": 100, "startTime": int(since * 1000)} + if cursor: + params["cursor"] = cursor + res = self._call("GET", "/v5/execution/list", params) + for e in res.get("list") or []: + if e.get("execType", "Trade") != "Trade": + continue + out.append({"time": int(e["execTime"]) / 1000, "side": "buy" if e["side"] == "Buy" else "sell", + "coins": float(e["execQty"]) * mult, "price": float(e["execPrice"]) / mult, + "fee": float(e.get("execFee") or 0), "pnl": None, "order": e.get("orderId", ""), + "close": float(e.get("closedSize") or 0) > 0}) + cursor = res.get("nextPageCursor") or "" + if not cursor: + break + return sorted(out, key=lambda f: f["time"]) + + def balances(self) -> dict: + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"})["list"] + coin = (acc[0].get("coin") or [{}])[0] if acc else {} + usdt = float(coin.get("equity") or coin.get("walletBalance") or 0) # incl. unrealized result + return {"Единый счёт USDT": usdt} + + unified = True # one account for spot and perps: nothing to move between them + + def usdt_free(self) -> dict: + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"})["list"] + coin = (acc[0].get("coin") or [{}])[0] if acc else {} + free = float(coin.get("walletBalance") or 0) - float(coin.get("locked") or 0) - float(coin.get("totalPositionIM") or 0) + return {"spot": free, "futures": free} + + def transfer_usdt(self, to: str, amount: float) -> None: + raise LiveError("Bybit: единый счёт — перевод не нужен") + + +# -------------------------------------------------------------------------------------------------------------- +class _BinanceLike: + """Binance spot / USDⓈ-M futures and MEXC spot share the signing scheme: HMAC-SHA256 of the query string.""" + name = "" + key_header = "X-MBX-APIKEY" + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + + def _signed(self, method: str, url: str, params: dict | None = None) -> dict | list: + q = dict(params or {}) + q["timestamp"] = int(time.time() * 1000) + q["recvWindow"] = 10000 + query = urllib.parse.urlencode(q) + query += "&signature=" + hmac.new(self.secret.encode(), query.encode(), hashlib.sha256).hexdigest() + return _http(method, f"{url}?{query}", {self.key_header: self.key}) + + +class Binance(_BinanceLike): + name = "Binance" + spot_fee, fut_fee = 0.1, 0.05 + SPOT, FUT = "https://api.binance.com", "https://fapi.binance.com" + + def _rule(self, market: str, symbol: str) -> dict: + k = f"{market}:{symbol}" + if k not in self.rules: + url = f"{self.SPOT}/api/v3/exchangeInfo?symbol={symbol}" if market == "spot" else f"{self.FUT}/fapi/v1/exchangeInfo" + info = next((s for s in _http("GET", url)["symbols"] if s["symbol"] == symbol), None) + if info is None: + raise LiveError(f"Binance: нет инструмента {symbol}") + f = {x["filterType"]: x for x in info["filters"]} + lot = f.get("MARKET_LOT_SIZE") if float((f.get("MARKET_LOT_SIZE") or {}).get("stepSize") or 0) > 0 else f["LOT_SIZE"] + self.rules[k] = {"step": float(lot["stepSize"]), "min": float(lot["minQty"]), + "tick": float((f.get("PRICE_FILTER") or {}).get("tickSize") or 0)} + return self.rules[k] + + def spot_buy(self, base: str, usdt: float) -> Fill: + o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"symbol": f"{base}USDT", "side": "BUY", "type": "MARKET", + "quoteOrderQty": _num(round(usdt, 2)), + "newOrderRespType": "FULL"}) + return self._spot_fill(o, base) + + def spot_sell(self, base: str, coins: float) -> Fill: + qty = _unsent(lambda: _floor(coins, self._rule("spot", f"{base}USDT")["step"])) + o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"symbol": f"{base}USDT", "side": "SELL", "type": "MARKET", + "quantity": _num(qty), "newOrderRespType": "FULL"}) + return self._spot_fill(o, base) + + def _spot_fill(self, o: dict, base: str) -> Fill: + qty, quote = float(o.get("executedQty") or 0), float(o.get("cummulativeQuoteQty") or 0) + if qty <= 0: + raise LiveError(f"Binance: ордер не исполнен ({o.get('status')})") + price = quote / qty + fee = 0.0 + for f in o.get("fills") or []: + c, asset = float(f.get("commission") or 0), f.get("commissionAsset") + fee += c if asset == "USDT" else c * price if asset == base else quote * self.spot_fee / 100 / max(1, len(o["fills"])) + return Fill(qty, price, fee, str(o.get("orderId")), o) + + def spot_coins(self) -> dict[str, float]: + return {b["asset"]: float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account", + {"omitZeroBalances": "true"})["balances"] + if b["asset"] != "USDT" and float(b["free"]) > 0} + + def spot_free(self, base: str) -> float: + for b in self._signed("GET", f"{self.SPOT}/api/v3/account", {"omitZeroBalances": "true"})["balances"]: + if b["asset"] == base: + return float(b["free"]) + return 0.0 + + def fut_round(self, symbol: str, coins: float) -> float: + mult = _units(symbol[:-4]) + r = self._rule("fut", symbol) + units = _floor(coins / mult, r["step"]) + return units * mult if units >= r["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + r = self._rule("fut", symbol) + return max(r["min"], r["step"]) * _units(symbol[:-4]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + fill = self._fut_market(symbol, side, coins, reduce_only) + if not reduce_only and (tp or sl): + # Binance has no TP/SL on a market order: two conditional orders that close the whole position + mult, tick = _units(symbol[:-4]), self._rule("fut", symbol)["tick"] + close_side = "SELL" if side == "buy" else "BUY" + problems = [] + for kind, price in (("TAKE_PROFIT_MARKET", tp), ("STOP_MARKET", sl)): + if not price: + continue + try: + self._signed("POST", f"{self.FUT}/fapi/v1/order", { + "symbol": symbol, "side": close_side, "type": kind, "stopPrice": _num(_tick(price * mult, tick)), + "closePosition": "true", "workingType": "CONTRACT_PRICE"}) + except LiveError as exc: + problems.append(f"{'TP' if kind.startswith('TAKE') else 'SL'}: {exc}") + fill.tpsl = "; ".join(problems) if problems else "на бирже" + return fill + + def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]: + rows = self._signed("GET", f"{self.FUT}/fapi/v1/userTrades", {"symbol": symbol, "startTime": int(since * 1000)}) + mult = _units(symbol[:-4]) + return [Fill(float(t["qty"]) * mult, float(t["price"]) / mult, float(t.get("commission") or 0), + str(t.get("orderId", ""))) for t in rows if t.get("side") == side.upper()] + + def fut_cancel_all(self, symbol: str) -> None: + self._signed("DELETE", f"{self.FUT}/fapi/v1/allOpenOrders", {"symbol": symbol}) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + mult = _units(symbol[:-4]) + rule = self._rule("fut", symbol) + o = self._signed("POST", f"{self.FUT}/fapi/v1/order", { + "symbol": symbol, "side": side.upper(), "type": "LIMIT", "timeInForce": "GTC", "reduceOnly": "true", + "quantity": _num(_floor(coins / mult, rule["step"])), "price": _num(_tick(price * mult, rule["tick"]))}) + return str(o.get("orderId")) + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + mult = _units(symbol[:-4]) + rule = _unsent(lambda: self._rule("fut", symbol)) + units = _floor(coins / mult, rule["step"]) + if units <= 0: + raise LiveError("Binance: количество меньше шага лота") + params = {"symbol": symbol, "side": side.upper(), "type": "LIMIT", "timeInForce": "GTC", + "quantity": _num(units), "price": _num(_tick(price * mult, rule["tick"]))} + if reduce_only: + params["reduceOnly"] = "true" + return str(self._signed("POST", f"{self.FUT}/fapi/v1/order", params).get("orderId")) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + o = self._signed("GET", f"{self.FUT}/fapi/v1/order", {"symbol": symbol, "orderId": order_id}) + mult = _units(symbol[:-4]) + units, quote = float(o.get("executedQty") or 0), float(o.get("cumQuote") or 0) + return {"coins": units * mult, "price": quote / (units * mult) if units else 0.0, + "fee": quote * self.fut_fee / 100, "final": o.get("status") not in ("NEW", "PARTIALLY_FILLED")} + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._signed("DELETE", f"{self.FUT}/fapi/v1/order", {"symbol": symbol, "orderId": order_id}) + + def fut_fills(self, symbol: str, since: float) -> list[dict]: + rows = self._signed("GET", f"{self.FUT}/fapi/v1/userTrades", + {"symbol": symbol, "startTime": int(since * 1000), "limit": 1000}) + mult = _units(symbol[:-4]) + return sorted(({"time": t["time"] / 1000, "side": t["side"].lower(), "coins": float(t["qty"]) * mult, + "price": float(t["price"]) / mult, "fee": float(t.get("commission") or 0), + "pnl": float(t.get("realizedPnl") or 0), "order": str(t.get("orderId", "")), + "close": float(t.get("realizedPnl") or 0) != 0} + for t in rows), key=lambda f: f["time"]) + + def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill: + mult = _units(symbol[:-4]) + units = _unsent(lambda: _floor(coins / mult, self._rule("fut", symbol)["step"])) + if units <= 0: + raise LiveError("Binance: количество меньше шага лота") + params = {"symbol": symbol, "side": side.upper(), "type": "MARKET", "quantity": _num(units), + "newOrderRespType": "RESULT"} + if reduce_only: + params["reduceOnly"] = "true" + o = self._signed("POST", f"{self.FUT}/fapi/v1/order", params) + units_done, quote = float(o.get("executedQty") or 0), float(o.get("cumQuote") or 0) + if units_done <= 0: + raise LiveError(f"Binance: ордер не исполнен ({o.get('status')})") + coins_done = units_done * mult + # no extra request for the fee: the estimate is replaced by the charged one at the next history sync + return Fill(coins_done, quote / coins_done, quote * self.fut_fee / 100, str(o.get("orderId")), o, False) + + def fut_position(self, symbol: str) -> float: + rows = self._signed("GET", f"{self.FUT}/fapi/v2/positionRisk", {"symbol": symbol}) + return sum(float(r.get("positionAmt") or 0) for r in rows) * _units(symbol[:-4]) + + def fut_liq_price(self, symbol: str) -> float | None: + rows = self._signed("GET", f"{self.FUT}/fapi/v2/positionRisk", {"symbol": symbol}) + return _liq(rows, "liquidationPrice", _units(symbol[:-4]), lambda r: abs(float(r.get("positionAmt") or 0))) + + def balances(self) -> dict: + spot = next((float(b["free"]) + float(b.get("locked") or 0) # incl. USDT held by open orders + for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] if b["asset"] == "USDT"), 0.0) + fut = next((float(b.get("balance") or 0) + float(b.get("crossUnPnl") or 0) + for b in self._signed("GET", f"{self.FUT}/fapi/v2/balance") + if b["asset"] == "USDT"), 0.0) + return {"Спот USDT": spot, "Фьючерсы USDT": fut} + + unified = False + + def usdt_free(self) -> dict: + spot = next((float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] + if b["asset"] == "USDT"), 0.0) + fut = next((float(b.get("availableBalance") or 0) for b in self._signed("GET", f"{self.FUT}/fapi/v2/balance") + if b["asset"] == "USDT"), 0.0) + return {"spot": spot, "futures": fut} + + def transfer_usdt(self, to: str, amount: float) -> None: + """Between the spot (MAIN) and USDⓈ-M futures accounts; the key needs «Permits Universal Transfer».""" + self._signed("POST", f"{self.SPOT}/sapi/v1/asset/transfer", { + "type": "MAIN_UMFUTURE" if to == "futures" else "UMFUTURE_MAIN", "asset": "USDT", "amount": _num(amount)}) + + +# -------------------------------------------------------------------------------------------------------------- +def mexc_order_id(data) -> str: + """MEXC futures answer a submit with the id itself or with {"orderId": "...", "ts": ...} (the newer form).""" + if isinstance(data, dict): + data = data.get("orderId") or data.get("order_id") + if not data: + raise LiveError("MEXC: биржа не вернула номер ордера", sent=True) + return str(data) + + +class Mexc(_BinanceLike): + name = "MEXC" + key_header = "X-MEXC-APIKEY" + spot_fee, fut_fee = 0.05, 0.02 + SPOT, FUT = "https://api.mexc.com", "https://contract.mexc.com" + + def _spot_rule(self, symbol: str) -> dict: + if symbol not in self.rules: + info = (_http("GET", f"{self.SPOT}/api/v3/exchangeInfo?symbol={symbol}").get("symbols") or [None])[0] + if info is None: + raise LiveError(f"MEXC: нет пары {symbol}") + self.rules[symbol] = {"step": 10 ** -int(info.get("baseAssetPrecision") or 2)} + return self.rules[symbol] + + def _spot_order(self, params: dict, base: str) -> Fill: + o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"type": "MARKET", **params}) + oid = str(o.get("orderId")) + + def poll(): + for _ in range(10): + d = self._signed("GET", f"{self.SPOT}/api/v3/order", {"symbol": params["symbol"], "orderId": oid}) + if d.get("status") in ("FILLED", "CANCELED", "PARTIALLY_CANCELED", "REJECTED"): + return d + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + d = _placed(oid, poll) + qty, quote = float(d.get("executedQty") or 0), float(d.get("cummulativeQuoteQty") or 0) + if qty <= 0: + raise LiveError(f"MEXC: ордер не исполнен ({d.get('status')})") + price = quote / qty + fee, exact = quote * self.spot_fee / 100, False + try: # commission actually charged, from the order's trades + trades = self._signed("GET", f"{self.SPOT}/api/v3/myTrades", {"symbol": params["symbol"], "orderId": oid}) + if isinstance(trades, list) and trades: + fee, exact = 0.0, True + for t in trades: + c, asset = float(t.get("commission") or 0), t.get("commissionAsset") + fee += c if asset == "USDT" else c * price if asset == base else 0.0 + except LiveError: + pass + return Fill(qty, price, fee, oid, d, exact) + + def spot_buy(self, base: str, usdt: float) -> Fill: + return self._spot_order({"symbol": f"{base}USDT", "side": "BUY", "quoteOrderQty": _num(round(usdt, 2))}, base) + + def spot_sell(self, base: str, coins: float) -> Fill: + symbol = f"{base}USDT" + rule = _unsent(lambda: self._spot_rule(symbol)) + while True: + qty = _floor(coins, rule["step"]) + try: + return self._spot_order({"symbol": symbol, "side": "SELL", "quantity": _num(qty)}, base) + except LiveError as exc: + # MEXC's exchangeInfo does not always tell the real quantity step (SUE: 2 decimals listed, refused + # with 400 «quantity scale is invalid»): the order was not taken — one decimal fewer, remembered + if "scale is invalid" not in str(exc) or getattr(exc, "sent", False) or rule["step"] >= 1: + raise + rule["step"] = min(1.0, rule["step"] * 10) + + def spot_coins(self) -> dict[str, float]: + return {b["asset"]: float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] + if b["asset"] != "USDT" and float(b["free"]) > 0} + + def spot_free(self, base: str) -> float: + for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"]: + if b["asset"] == base: + return float(b["free"]) + return 0.0 + + # futures: contract.mexc.com, signature = HMAC-SHA256(key + time + params); order placing through the API is + # closed for most accounts by MEXC itself — the exchange's refusal is shown as is + def _fut(self, method: str, path: str, params: dict | None = None) -> dict: + # MEXC answers reads now and then with 513 «try again later»: a read is simply repeated (never an order) + for attempt in range(3): + try: + return self._fut_once(method, path, params) + except LiveError as exc: + if method != "GET" or "513" not in str(exc) or attempt == 2: + raise + time.sleep(0.4 * (attempt + 1)) + + def _fut_once(self, method: str, path: str, params: dict | None = None) -> dict: + ts = str(int(time.time() * 1000)) + if method == "GET": + query = urllib.parse.urlencode(sorted((params or {}).items())) + text, url, body = query, f"{self.FUT}{path}" + (f"?{query}" if query else ""), None + else: + text = json.dumps(params or {}) + url, body = self.FUT + path, text.encode() + sign = hmac.new(self.secret.encode(), (self.key + ts + text).encode(), hashlib.sha256).hexdigest() + d = _http(method, url, {"ApiKey": self.key, "Request-Time": ts, "Signature": sign, + "Content-Type": "application/json"}, body) + if not d.get("success"): + raise LiveError(f"MEXC фьючерсы {d.get('code')}: {d.get('message')}") + return d.get("data") + + def _contract(self, symbol: str) -> dict: + k = f"fut:{symbol}" + if k not in self.rules: + d = _http("GET", f"{self.FUT}/api/v1/contract/detail?symbol={symbol}").get("data") or {} + if not d: + raise LiveError(f"MEXC: нет контракта {symbol}") + self.rules[k] = {"size": float(d["contractSize"]) * _units(symbol[:-5]), "min": float(d.get("minVol") or 1), + "tick": float(d.get("priceUnit") or 0)} + return self.rules[k] + + def fut_round(self, symbol: str, coins: float) -> float: + c = self._contract(symbol) + vol = math.floor(coins / c["size"] + 1e-9) + return vol * c["size"] if vol >= c["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + c = self._contract(symbol) + return c["size"] * max(1.0, c["min"]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + c = _unsent(lambda: self._contract(symbol)) + vol = math.floor(coins / c["size"] + 1e-9) + if vol <= 0: + raise LiveError("MEXC: количество меньше одного контракта") + # side: 1 open long, 2 close short, 3 open short, 4 close long; type 5 = market; openType 2 = cross + code = (2 if side == "buy" else 4) if reduce_only else (1 if side == "buy" else 3) + params = {"symbol": symbol, "vol": vol, "side": code, "type": 5, "openType": 2} + units = _units(symbol[:-5]) + if not reduce_only: # TP / SL attached to the opening order, kept by MEXC + if tp: + params["takeProfitPrice"] = _tick(tp * units, c["tick"]) + if sl: + params["stopLossPrice"] = _tick(sl * units, c["tick"]) + oid = mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", params)) + + def check(): + # ONE look at the order (a market order is filled by now): MEXC limits private requests, a series of + # polls ran into «510 too frequent»; if it is not confirmed, the caller checks the position instead + time.sleep(0.15) + o = self._fut("GET", f"/api/v1/private/order/get/{oid}") + if float(o.get("dealVol") or 0) > 0 and o.get("state") in (3, 4): + return o + raise LiveError(f"исполнение ещё не видно (state {o.get('state')})") + o = _placed(oid, check) + coins_done = float(o.get("dealVol") or 0) * c["size"] + if coins_done <= 0: + raise LiveError("MEXC: фьючерсный ордер не исполнен") + price = float(o.get("dealAvgPrice") or 0) / _units(symbol[:-5]) + charged = [o.get(k) for k in ("takerFee", "makerFee") if o.get(k) not in (None, "")] + tpsl = "на бирже" if not reduce_only and ("takeProfitPrice" in params or "stopLossPrice" in params) else "" + if charged: + return Fill(coins_done, price, sum(abs(float(x)) for x in charged), oid, o, tpsl=tpsl) + return Fill(coins_done, price, coins_done * price * self.fut_fee / 100, oid, o, False, tpsl) + + def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]: + """Closing orders (side 4 closes a long by selling, 2 closes a short by buying) since `since`.""" + size, units = self._contract(symbol)["size"], _units(symbol[:-5]) + want = 2 if side == "buy" else 4 + d = self._fut("GET", "/api/v1/private/order/list/history_orders", + {"symbol": symbol, "start_time": int(since * 1000), "page_num": 1, "page_size": 50}) or [] + rows = d if isinstance(d, list) else d.get("resultList") or [] + out = [] + for o in rows: + if o.get("side") == want and float(o.get("dealVol") or 0) > 0: + fee = sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")) + out.append(Fill(float(o["dealVol"]) * size, float(o.get("dealAvgPrice") or 0) / units, fee, + str(o.get("orderId", "")))) + return out + + def fut_cancel_all(self, symbol: str) -> None: + """Every open order of the symbol: limit orders (the TP) and the TP/SL plans.""" + problems = [] + for path in ("/api/v1/private/order/cancel_all", "/api/v1/private/stoporder/cancel_all"): + try: + self._fut("POST", path, {"symbol": symbol}) + except LiveError as exc: + problems.append(str(exc)) + if len(problems) == 2: + raise LiveError("; ".join(problems)) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + """Reduce-only limit close: side 2 closes a short (buy), 4 closes a long (sell); type 1 = limit.""" + c = self._contract(symbol) + vol = math.floor(coins / c["size"] + 1e-9) + return mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", { + "symbol": symbol, "vol": vol, "side": 2 if side == "buy" else 4, "type": 1, "openType": 2, + "price": _tick(price * _units(symbol[:-5]), c["tick"])})) + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + """Resting limit order (type 1): opens (1 long / 3 short) or, reduce-only, closes (2 short / 4 long).""" + c = _unsent(lambda: self._contract(symbol)) + vol = math.floor(coins / c["size"] + 1e-9) + if vol <= 0: + raise LiveError("MEXC: количество меньше одного контракта") + code = (2 if side == "buy" else 4) if reduce_only else (1 if side == "buy" else 3) + return mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", { + "symbol": symbol, "vol": vol, "side": code, "type": 1, "openType": 2, + "price": _tick(price * _units(symbol[:-5]), c["tick"])})) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + c = self._contract(symbol) + o = self._fut("GET", f"/api/v1/private/order/get/{order_id}") + coins = float(o.get("dealVol") or 0) * c["size"] + return {"coins": coins, "price": float(o.get("dealAvgPrice") or 0) / _units(symbol[:-5]), + "fee": sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")), + "final": o.get("state") in (3, 4, 5)} # 1/2 waiting · 3 filled · 4 cancelled · 5 invalid + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._fut("POST", "/api/v1/private/order/cancel", [order_id]) + + def fut_fills(self, symbol: str, since: float) -> list[dict]: + """Filled orders of the symbol since `since` (MEXC: per order — side 1/2 buy, 3/4 sell; `profit` is the + realized result of a closing order before fees, as in the exchange's trade history).""" + size, units = self._contract(symbol)["size"], _units(symbol[:-5]) + out = [] + for page in range(1, 11): + d = self._fut("GET", "/api/v1/private/order/list/history_orders", + {"symbol": symbol, "start_time": int(since * 1000), "page_num": page, "page_size": 100}) or [] + rows = d if isinstance(d, list) else d.get("resultList") or [] + for o in rows: + vol = float(o.get("dealVol") or 0) + if vol <= 0: + continue + code = o.get("side") + out.append({"time": (o.get("updateTime") or o.get("createTime") or 0) / 1000, + "side": "buy" if code in (1, 2) else "sell", "coins": vol * size, + "price": float(o.get("dealAvgPrice") or 0) / units, + "fee": sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")), + "pnl": float(o["profit"]) if code in (2, 4) and o.get("profit") not in (None, "") else None, + "close": code in (2, 4), + "order": str(o.get("orderId", ""))}) + if len(rows) < 100: + break + return sorted(out, key=lambda f: f["time"]) + + def fut_position(self, symbol: str) -> float: + size = self._contract(symbol)["size"] + rows = self._fut("GET", "/api/v1/private/position/open_positions", {"symbol": symbol}) or [] + return sum(float(r.get("holdVol") or 0) * size * (1 if r.get("positionType") == 1 else -1) for r in rows) + + def fut_liq_price(self, symbol: str) -> float | None: + rows = self._fut("GET", "/api/v1/private/position/open_positions", {"symbol": symbol}) or [] + return _liq(rows, "liquidatePrice", _units(symbol[:-5]), lambda r: float(r.get("holdVol") or 0)) + + def balances(self) -> dict: + spot = next((float(b["free"]) + float(b.get("locked") or 0) # incl. USDT held by open orders + for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] if b["asset"] == "USDT"), 0.0) + out = {"Спот USDT": spot} + try: + acc = next((a for a in self._fut("GET", "/api/v1/private/account/assets") if a.get("currency") == "USDT"), {}) + # equity: what the account is worth now (free + margin in positions + their unrealized result) + out["Фьючерсы USDT"] = float(acc.get("equity") or acc.get("availableBalance") or 0) + except LiveError as exc: + out["Фьючерсы"] = str(exc) + return out + + unified = False + + def usdt_free(self) -> dict: + spot = next((float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] + if b["asset"] == "USDT"), 0.0) + acc = next((a for a in self._fut("GET", "/api/v1/private/account/assets") if a.get("currency") == "USDT"), {}) + return {"spot": spot, "futures": float(acc.get("availableBalance") or 0)} + + def transfer_usdt(self, to: str, amount: float) -> None: + """Between the spot and futures accounts (spot API capital/transfer; the key needs the transfer right).""" + self._signed("POST", f"{self.SPOT}/api/v3/capital/transfer", { + "fromAccountType": "SPOT" if to == "futures" else "FUTURES", + "toAccountType": "FUTURES" if to == "futures" else "SPOT", "asset": "USDT", "amount": _num(amount)}) + + +# -------------------------------------------------------------------------------------------------------------- +class Htx: + name = "HTX" + spot_fee, fut_fee = 0.2, 0.05 + SPOT, FUT = "api.huobi.pro", "api.hbdm.com" + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + self.account_id: str | None = None + + def _call(self, method: str, host: str, path: str, params: dict | None = None, body: dict | None = None): + q = {"AccessKeyId": self.key, "SignatureMethod": "HmacSHA256", "SignatureVersion": "2", + "Timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S"), **(params or {})} + query = urllib.parse.urlencode(sorted(q.items()), quote_via=urllib.parse.quote) + payload = f"{method}\n{host}\n{path}\n{query}" + sign = base64.b64encode(hmac.new(self.secret.encode(), payload.encode(), hashlib.sha256).digest()).decode() + url = f"https://{host}{path}?{query}&Signature={urllib.parse.quote(sign, safe='')}" + data = None if body is None else json.dumps(body).encode() + d = _http(method, url, {"Content-Type": "application/json"}, data) + if d.get("status") not in ("ok", None) or (d.get("code") not in (None, 200) and "data" not in d): + raise LiveError(f"HTX {d.get('err-code') or d.get('err_code') or d.get('code')}: " + f"{d.get('err-msg') or d.get('err_msg') or d.get('message')}") + return d.get("data") + + def _account(self) -> str: + if self.account_id is None: + acc = next((a for a in self._call("GET", self.SPOT, "/v1/account/accounts") if a.get("type") == "spot"), None) + if acc is None: + raise LiveError("HTX: спотовый счёт не найден") + self.account_id = str(acc["id"]) + return self.account_id + + def _spot_order(self, base: str, kind: str, amount: str, fee_rate: float, price: str | None = None) -> Fill: + body = {"account-id": self._account(), "symbol": f"{base.lower()}usdt", "type": kind, "amount": amount, + "source": "spot-api"} + if price is not None: + body["price"] = price + oid = self._call("POST", self.SPOT, "/v1/order/orders/place", body=body) + + def poll(): + for _ in range(10): + o = self._call("GET", self.SPOT, f"/v1/order/orders/{oid}") + if o.get("state") in ("filled", "partial-canceled", "canceled"): + return o + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + o = _placed(str(oid), poll) + qty, quote = float(o.get("field-amount") or o.get("filled-amount") or 0), float( + o.get("field-cash-amount") or o.get("filled-cash-amount") or 0) + if qty <= 0: + # a market order cancelled with nothing filled: HTX's circuit breaker on a wide spread (410 — the order + # detail does not report the source, only the history does); nothing traded, a limit can go instead + if kind.endswith("-market") and o.get("state") == "canceled": + raise CircuitBreaker("HTX: рыночный ордер отменён защитой биржи (широкий спред)") + raise LiveError(f"HTX: ордер не исполнен ({o.get('state')})") + fee = float(o.get("field-fees") or o.get("filled-fees") or 0) + fee_usd = fee * quote / qty if kind.startswith("buy") else fee # a buy pays its fee in coins + return Fill(qty, quote / qty, fee_usd or quote * fee_rate / 100, str(oid), o) + + def _spot_rule(self, base: str) -> dict: + k = f"spot:{base}" + if k not in self.rules: + sym = next((s for s in _http("GET", f"https://{self.SPOT}/v1/common/symbols")["data"] + if s["symbol"] == f"{base.lower()}usdt"), None) + if sym is None: + raise LiveError(f"HTX: нет пары {base}/USDT") + self.rules[k] = {"step": 10 ** -int(sym.get("amount-precision", 4)), + "tick": 10 ** -int(sym.get("price-precision", 8))} + return self.rules[k] + + def _spot_step(self, base: str) -> float: + return self._spot_rule(base)["step"] + + def _book_price(self, base: str, side: str, size: float, in_quote: bool) -> float: + """The price an IOC limit order needs to fill `size` (coins, or USDT for a buy) from the book now: the last + level it reaches. For when HTX refuses a market order (its circuit breaker on a wide spread).""" + import fastquote + bids, asks = fastquote.book("HTX", "spot", f"{base.lower()}usdt") + levels, got = (asks if side == "buy" else bids), 0.0 + for p, q in levels: + got += p * q if in_quote else q + if got >= size: + return p + raise LiveError(f"HTX: в стакане {base} меньше нужного объёма") + + def spot_buy(self, base: str, usdt: float) -> Fill: + try: + return self._spot_order(base, "buy-market", _num(round(usdt, 2)), self.spot_fee) + except CircuitBreaker: + r = _unsent(lambda: self._spot_rule(base)) + price = _unsent(lambda: self._book_price(base, "buy", usdt, True)) + price = math.ceil(price / r["tick"] - 1e-9) * r["tick"] + coins = _floor(usdt / price, r["step"]) + return self._spot_order(base, "buy-ioc", _num(coins), self.spot_fee, _num(price)) + + def spot_sell(self, base: str, coins: float) -> Fill: + step = _unsent(lambda: self._spot_step(base)) + amount = _num(_floor(coins, step)) + try: + return self._spot_order(base, "sell-market", amount, self.spot_fee) + except CircuitBreaker: + # nothing was sold: the same coins as an IOC limit at the book price that takes them all + r = _unsent(lambda: self._spot_rule(base)) + price = _unsent(lambda: self._book_price(base, "sell", float(amount), False)) + price = math.floor(price / r["tick"] + 1e-9) * r["tick"] + return self._spot_order(base, "sell-ioc", amount, self.spot_fee, _num(price)) + + def spot_coins(self) -> dict[str, float]: + out: dict[str, float] = {} + for i in self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"]: + if i["type"] == "trade" and i["currency"] != "usdt" and float(i["balance"]) > 0: + out[i["currency"].upper()] = out.get(i["currency"].upper(), 0.0) + float(i["balance"]) + return out + + def spot_free(self, base: str) -> float: + items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"] + return sum(float(i["balance"]) for i in items if i["currency"] == base.lower() and i["type"] == "trade") + + def _contract(self, code: str) -> dict: + k = f"fut:{code}" + if k not in self.rules: + d = _http("GET", f"https://{self.FUT}/linear-swap-api/v1/swap_contract_info?contract_code={code}")["data"] + if not d: + raise LiveError(f"HTX: нет контракта {code}") + self.rules[k] = {"size": float(d[0]["contract_size"]) * _units(code[:-5])} + return self.rules[k] + + def fut_round(self, symbol: str, coins: float) -> float: + size = self._contract(symbol)["size"] + return math.floor(coins / size + 1e-9) * size + + def fut_min_coins(self, symbol: str) -> float: + return self._contract(symbol)["size"] + + # A futures account in the Multi-Assets Collateral mode (asset_mode 2) answers the v1 interface with 6023 + # «The current API version has expired»: it is traded through the V5 interface (same signature, host api.hbdm.com). + _v5_mode: bool | None = None + + def _v5(self) -> bool: + if self._v5_mode is None: + try: + self._v5_mode = int((self._call("GET", self.FUT, "/v5/account/asset_mode") or {}).get("asset_mode") + or 0) == 2 + except LiveError: + return False # not known yet: v1, asked again next time + return self._v5_mode + + V5_FINAL = ("filled", "partially_canceled", "canceled") + + def _v5_order(self, symbol: str, oid: str) -> dict: + o = self._call("GET", self.FUT, "/v5/trade/order", {"contract_code": symbol, "order_id": oid}) or {} + return o[0] if isinstance(o, list) and o else o if isinstance(o, dict) else {} + + def _v5_place(self, symbol: str, side: str, vol: int, reduce_only: bool, price: float | None) -> str: + body = {"contract_code": symbol, "margin_mode": "cross", "side": side, "volume": vol, + "type": "limit" if price else "market"} + if price: + body["price"] = price * _units(symbol[:-5]) + body["time_in_force"] = "gtc" + if reduce_only: + body["reduce_only"] = 1 + d = self._call("POST", self.FUT, "/v5/trade/order", body=body) or {} + oid = str(d.get("order_id") or d.get("order_id_str") or "") + if not oid: + raise LiveError(f"HTX: биржа не вернула номер ордера ({d})", sent=True) + return oid + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + fill = self._fut_market(symbol, side, coins, reduce_only) + if not reduce_only and (tp or sl): + fill.tpsl = "HTX: TP/SL на бирже не поддерживается программой — закрывает программа" + return fill + + def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill: + size = _unsent(lambda: self._contract(symbol))["size"] + vol = math.floor(coins / size + 1e-9) + if vol <= 0: + raise LiveError("HTX: количество меньше одного контракта") + if _unsent(self._v5): + oid = self._v5_place(symbol, side, vol, reduce_only, None) + + def poll_v5(): + for _ in range(10): + o = self._v5_order(symbol, oid) + if o.get("state") in self.V5_FINAL: + return o + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + o = _placed(oid, poll_v5) + done = float(o.get("trade_volume") or 0) * size + if done <= 0: + raise LiveError(f"HTX: фьючерсный ордер не исполнен ({o.get('state')})") + price = float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]) + fee = abs(float(o.get("fee") or 0)) + return Fill(done, price, fee or done * price * self.fut_fee / 100, oid, o, bool(fee)) + d = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order", body={ + "contract_code": symbol, "volume": vol, "direction": side, "offset": "close" if reduce_only else "open", + "lever_rate": 1, "order_price_type": "optimal_20"}) + oid = d["order_id_str"] + + def poll(): + for _ in range(10): + info = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order_info", + body={"order_id": oid, "contract_code": symbol}) + o = info[0] if info else {} + if o.get("status") in (6, 5, 7): # filled / partially filled then cancelled / cancelled + return o + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + o = _placed(oid, poll) + done = float(o.get("trade_volume") or 0) * size + if done <= 0: + raise LiveError("HTX: фьючерсный ордер не исполнен") + price = float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]) + fee = abs(float(o.get("fee") or 0)) + return Fill(done, price, fee or done * price * self.fut_fee / 100, oid, o, bool(fee)) + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + size = _unsent(lambda: self._contract(symbol))["size"] + vol = math.floor(coins / size + 1e-9) + if vol <= 0: + raise LiveError("HTX: количество меньше одного контракта") + if _unsent(self._v5): + return self._v5_place(symbol, side, vol, reduce_only, price) + d = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order", body={ + "contract_code": symbol, "volume": vol, "direction": side, "offset": "close" if reduce_only else "open", + "lever_rate": 1, "order_price_type": "limit", "price": price * _units(symbol[:-5])}) + return str(d["order_id_str"]) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + return self.fut_limit(symbol, side, coins, price, reduce_only=True) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + size = self._contract(symbol)["size"] + if self._v5(): + o = self._v5_order(symbol, order_id) + return {"coins": float(o.get("trade_volume") or 0) * size, + "price": float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]), + "fee": abs(float(o.get("fee") or 0)), "final": o.get("state") in self.V5_FINAL} + info = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order_info", + body={"order_id": order_id, "contract_code": symbol}) + o = info[0] if info else {} + return {"coins": float(o.get("trade_volume") or 0) * size, + "price": float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]), + "fee": abs(float(o.get("fee") or 0)), "final": o.get("status") in (5, 6, 7)} + + def fut_cancel(self, symbol: str, order_id: str) -> None: + if self._v5(): + self._call("POST", self.FUT, "/v5/trade/cancel_order", body={"order_id": order_id, "contract_code": symbol}) + return + self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_cancel", + body={"order_id": order_id, "contract_code": symbol}) + + def fut_cancel_all(self, symbol: str) -> None: + if self._v5(): + self._call("POST", self.FUT, "/v5/trade/cancel_all_orders", body={"contract_code": symbol}) + return + self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_cancelall", body={"contract_code": symbol}) + + def fut_position(self, symbol: str) -> float: + size = self._contract(symbol)["size"] + if self._v5(): + rows = self._call("GET", self.FUT, "/v5/trade/position/opens", {"contract_code": symbol}) or [] + + def sign(r: dict) -> int: # one-way mode: position_side "both", the side is direction + side = r.get("position_side") + return 1 if side == "long" or (side not in ("long", "short") and r.get("direction") == "buy") else -1 + return sum(float(r.get("volume") or 0) * size * sign(r) for r in rows + if r.get("contract_code", symbol) == symbol) + rows = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_position_info", + body={"contract_code": symbol}) or [] + return sum(float(r.get("volume") or 0) * size * (1 if r.get("direction") == "buy" else -1) for r in rows) + + def fut_liq_price(self, symbol: str) -> float | None: + if self._v5(): + rows = self._call("GET", self.FUT, "/v5/trade/position/opens", {"contract_code": symbol}) or [] + else: + rows = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_position_info", + body={"contract_code": symbol}) or [] + return _liq([r for r in rows if r.get("contract_code", symbol) == symbol], "liquidation_price", + _units(symbol[:-5]), lambda r: float(r.get("volume") or 0)) + + def _fut_account(self) -> tuple[float, float]: + """(equity, free margin) of the USDT futures account, $.""" + if self._v5(): + acc = self._call("GET", self.FUT, "/v5/account/balance") or {} + return float(acc.get("equity") or 0), float(acc.get("available_margin") or 0) + acc = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_account_info", body={"margin_account": "USDT"}) + a = acc[0] if acc else {} + return float(a.get("margin_balance") or 0), float(a.get("withdraw_available") or a.get("margin_available") or 0) + + def balances(self) -> dict: + items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"] + spot = sum(float(i["balance"]) for i in items if i["currency"] == "usdt" and i["type"] in ("trade", "frozen")) + out = {"Спот USDT": spot} + try: + out["Фьючерсы USDT"] = self._fut_account()[0] + except LiveError as exc: + out["Фьючерсы"] = str(exc) + return out + + unified = False + + def usdt_free(self) -> dict: + items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"] + spot = sum(float(i["balance"]) for i in items if i["currency"] == "usdt" and i["type"] == "trade") + return {"spot": spot, "futures": self._fut_account()[1]} + + def transfer_usdt(self, to: str, amount: float) -> None: + self._call("POST", self.SPOT, "/v2/account/transfer", body={ + "from": "spot" if to == "futures" else "linear-swap", "to": "linear-swap" if to == "futures" else "spot", + "currency": "usdt", "amount": float(_num(amount)), "margin-account": "USDT"}) + + +# -------------------------------------------------------------------------------------------------------------- +class Gate: + name = "Gate" + spot_fee, fut_fee = 0.1, 0.05 + HOST, PREFIX = "https://api.gateio.ws", "/api/v4" + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + + def _call(self, method: str, path: str, params: dict | None = None, body: dict | None = None): + query = urllib.parse.urlencode(params or {}) + text = "" if body is None else json.dumps(body) + ts = str(int(time.time())) + payload = "\n".join([method, self.PREFIX + path, query, hashlib.sha512(text.encode()).hexdigest(), ts]) + sign = hmac.new(self.secret.encode(), payload.encode(), hashlib.sha512).hexdigest() + url = self.HOST + self.PREFIX + path + (f"?{query}" if query else "") + d = _http(method, url, {"KEY": self.key, "Timestamp": ts, "SIGN": sign, "Content-Type": "application/json", + "Accept": "application/json"}, text.encode() if body is not None else None) + if isinstance(d, dict) and d.get("label"): + raise LiveError(f"Gate {d.get('label')}: {d.get('message')}") + return d + + def _spot_step(self, base: str) -> float: + k = f"spot:{base}" + if k not in self.rules: + d = _http("GET", f"{self.HOST}{self.PREFIX}/spot/currency_pairs/{base}_USDT") + self.rules[k] = {"step": 10 ** -int(d.get("amount_precision", 4))} + return self.rules[k]["step"] + + def _spot_order(self, base: str, side: str, amount: str, fee_rate: float) -> Fill: + o = self._call("POST", "/spot/orders", body={"currency_pair": f"{base}_USDT", "type": "market", "side": side, + "amount": amount, "time_in_force": "ioc"}) + quote = float(o.get("filled_total") or 0) + price = float(o.get("avg_deal_price") or 0) + qty = float(o.get("filled_amount") or 0) or (quote / price if price else 0) + if qty <= 0: + raise LiveError(f"Gate: ордер не исполнен ({o.get('status')})") + fee, cur = float(o.get("fee") or 0), (o.get("fee_currency") or "").upper() + fee_usd = fee if cur == "USDT" else fee * quote / qty if cur == base else quote * fee_rate / 100 + return Fill(qty, quote / qty, fee_usd, str(o.get("id")), o) + + def spot_buy(self, base: str, usdt: float) -> Fill: + return self._spot_order(base, "buy", _num(round(usdt, 2)), self.spot_fee) + + def spot_sell(self, base: str, coins: float) -> Fill: + step = _unsent(lambda: self._spot_step(base)) + return self._spot_order(base, "sell", _num(_floor(coins, step)), self.spot_fee) + + def spot_coins(self) -> dict[str, float]: + return {a["currency"]: float(a.get("available") or 0) for a in self._call("GET", "/spot/accounts") or [] + if a.get("currency") != "USDT" and float(a.get("available") or 0) > 0} + + def spot_free(self, base: str) -> float: + items = self._call("GET", "/spot/accounts", {"currency": base}) + return float(items[0]["available"]) if items else 0.0 + + def _contract(self, symbol: str) -> dict: + k = f"fut:{symbol}" + if k not in self.rules: + d = _http("GET", f"{self.HOST}{self.PREFIX}/futures/usdt/contracts/{symbol}") + self.rules[k] = {"size": float(d.get("quanto_multiplier") or 1) * _units(symbol[:-5]), + "min": float(d.get("order_size_min") or 1)} + return self.rules[k] + + def fut_round(self, symbol: str, coins: float) -> float: + c = self._contract(symbol) + n = math.floor(coins / c["size"] + 1e-9) + return n * c["size"] if n >= c["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + c = self._contract(symbol) + return c["size"] * max(1.0, c["min"]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + fill = self._fut_market(symbol, side, coins, reduce_only) + if not reduce_only and (tp or sl): + fill.tpsl = "Gate: TP/SL на бирже не поддерживается программой — закрывает программа" + return fill + + def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill: + c = _unsent(lambda: self._contract(symbol)) + n = math.floor(coins / c["size"] + 1e-9) + if n <= 0: + raise LiveError("Gate: количество меньше одного контракта") + o = self._call("POST", "/futures/usdt/orders", body={"contract": symbol, "size": n if side == "buy" else -n, + "price": "0", "tif": "ioc", "reduce_only": reduce_only}) + done = (abs(int(o.get("size") or 0)) - abs(int(o.get("left") or 0))) * c["size"] + if done <= 0: + raise LiveError(f"Gate: фьючерсный ордер не исполнен ({o.get('finish_as')})") + price = float(o.get("fill_price") or 0) / _units(symbol[:-5]) + fee, exact = self._order_fee(symbol, str(o.get("id"))) + return Fill(done, price, fee if exact else done * price * self.fut_fee / 100, str(o.get("id")), o, exact) + + def _order_fee(self, symbol: str, order_id: str) -> tuple[float, bool]: + """The fee Gate charged for the order, from its fills (the order answer has none); (0, False) if unread.""" + try: + fills = self._call("GET", "/futures/usdt/my_trades", {"contract": symbol, "order": order_id, "limit": 100}) + except LiveError: + return 0.0, False + fills = [f for f in fills or [] if str(f.get("order_id")) == order_id] + if not fills: + return 0.0, False + return sum(abs(float(f.get("fee") or 0)) for f in fills), True + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + c = _unsent(lambda: self._contract(symbol)) + n = math.floor(coins / c["size"] + 1e-9) + if n <= 0: + raise LiveError("Gate: количество меньше одного контракта") + o = self._call("POST", "/futures/usdt/orders", body={ + "contract": symbol, "size": n if side == "buy" else -n, "price": _num(price * _units(symbol[:-5])), + "tif": "gtc", "reduce_only": reduce_only}) + return str(o.get("id")) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + return self.fut_limit(symbol, side, coins, price, reduce_only=True) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + c = self._contract(symbol) + o = self._call("GET", f"/futures/usdt/orders/{order_id}") + done = (abs(int(o.get("size") or 0)) - abs(int(o.get("left") or 0))) * c["size"] + price = float(o.get("fill_price") or 0) / _units(symbol[:-5]) + fee, exact = self._order_fee(symbol, str(order_id)) if done > 0 else (0.0, False) + return {"coins": done, "price": price, "fee": fee if exact else done * price * self.fut_fee / 100, + "final": o.get("status") == "finished"} + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._call("DELETE", f"/futures/usdt/orders/{order_id}") + + def fut_cancel_all(self, symbol: str) -> None: + self._call("DELETE", "/futures/usdt/orders", {"contract": symbol}) + + def _position_rows(self, symbol: str) -> list[dict]: + """The symbol's position rows: one in the single mode; two (dual_long + dual_short) when the account is in + the hedge (dual) mode — then Gate answers with a LIST, which must not read as «no position».""" + try: + d = self._call("GET", f"/futures/usdt/positions/{symbol}") + except LiveError as exc: + if "POSITION_NOT_FOUND" in str(exc): # never traded on this account: no position + return [] + raise + if isinstance(d, list): + return [r for r in d if isinstance(r, dict)] + return [d] if isinstance(d, dict) else [] + + def fut_position(self, symbol: str) -> float: + """Coins of the open position: + long, − short (both sides summed in the hedge mode).""" + size = self._contract(symbol)["size"] + return sum(float(r.get("size") or 0) for r in self._position_rows(symbol)) * size + + def fut_liq_price(self, symbol: str) -> float | None: + return _liq(self._position_rows(symbol), "liq_price", _units(symbol[:-5]), + lambda r: abs(float(r.get("size") or 0))) + + def balances(self) -> dict: + spot = self._call("GET", "/spot/accounts", {"currency": "USDT"}) + out = {"Спот USDT": float(spot[0]["available"]) + float(spot[0].get("locked") or 0) if spot else 0.0} + try: + # equity: the balance plus the open positions' unrealized result (not only the free part) + acc = self._fut_account() + out["Фьючерсы USDT"] = float(acc.get("total") or 0) + float(acc.get("unrealised_pnl") or 0) + except LiveError as exc: + out["Фьючерсы"] = str(exc) + return out + + unified = False + + def usdt_free(self) -> dict: + spot = self._call("GET", "/spot/accounts", {"currency": "USDT"}) + return {"spot": float(spot[0]["available"]) if spot else 0.0, + "futures": float(self._fut_account().get("available") or 0)} + + def _fut_account(self) -> dict: + """The USDT futures account; {} while it does not exist (Gate creates it with the first transfer: + USER_NOT_FOUND «please transfer funds first») — an empty account, not an error.""" + try: + return self._call("GET", "/futures/usdt/accounts") or {} + except LiveError as exc: + if "USER_NOT_FOUND" in str(exc): + return {} + raise + + def transfer_usdt(self, to: str, amount: float) -> None: + self._call("POST", "/wallet/transfers", body={ + "currency": "USDT", "from": "spot" if to == "futures" else "futures", + "to": "futures" if to == "futures" else "spot", "amount": _num(amount), "settle": "usdt"}) + + +def ensure_usdt(c, spot_need: float, futures_need: float) -> str: + """Make `spot_need` USDT free on the spot account and `futures_need` on the futures one by moving the shortfall + from the other account. Returns what was done ("" = nothing needed); LiveError when the total is not enough.""" + if getattr(c, "unified", False): + return "" + free = c.usdt_free() + spot_gap = max(0.0, spot_need - free["spot"]) + fut_gap = max(0.0, futures_need - free["futures"]) + if spot_gap <= 0 and fut_gap <= 0: + return "" + if spot_gap > 0 and fut_gap > 0 or free["spot"] + free["futures"] < spot_need + futures_need: + raise LiveError(f"не хватает USDT в сумме: нужно {spot_need:.2f} на споте и {futures_need:.2f} на фьючерсах, " + f"есть {free['spot']:.2f} и {free['futures']:.2f}") + to, gap = ("futures", fut_gap) if fut_gap > 0 else ("spot", spot_gap) + amount = math.ceil(gap * 100) / 100 + 0.01 # a cent of margin for rounding + c.transfer_usdt(to, amount) + return f"переведено {amount:.2f} USDT {'со спота на фьючерсы' if to == 'futures' else 'с фьючерсов на спот'}" + + +CLIENTS = {"bybit": Bybit, "mexc": Mexc, "htx": Htx, "gate": Gate} +_cache: dict[str, tuple[tuple[str, str], object]] = {} + + +def client(exchange: str): + """Client with the exchange's saved keys (rebuilt when the keys change); LiveError when no keys.""" + import keystore + keys = keystore.get(exchange) + if keys is None: + raise LiveError(f"{keystore.EXCHANGES.get(exchange, exchange)}: API-ключи не заданы") + cached = _cache.get(exchange) + if cached is None or cached[0] != keys: + cached = (keys, CLIENTS[exchange](*keys)) + _cache[exchange] = cached + return cached[1] diff --git a/LinuxServer/main.py b/LinuxServer/main.py new file mode 100644 index 0000000..5fad405 --- /dev/null +++ b/LinuxServer/main.py @@ -0,0 +1,4558 @@ +from __future__ import annotations + +import json +import hashlib +import math +import os +import queue +import re +import threading +import time +import urllib.parse +import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed +from collections import deque +from datetime import datetime +from pathlib import Path +import tkinter as tk +from tkinter import messagebox, ttk +from bybit_live import BybitAPIError, BybitLiveClient +from credential_store import CredentialStoreError, delete_credentials, load_credentials, save_credentials +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 +except ImportError: + websocket = None + + +WS_URL = "wss://stream.bybit.com/v5/public/linear" +WINDOW_MS = 60_000 +CHART_SECONDS = 30 * 60 +CANDLE_INTERVAL_MINUTES = 1 +TAKER_FEE_PCT = 0.055 +AUTO_CURRENCY_SCAN_SECONDS = 10 * 60 +TOP_LIQUID_SYMBOLS = 100 +PUBLIC_MARKET_API_HOSTS = ("https://api.bybit.com", "https://api.bytick.com") +STRATEGY_DEFAULTS_VERSION = 2 +DEFAULT_CURRENCY_STRATEGY = { + "stake_pct": "5", + "max_adds": "2", + "leverage": "1", + "trigger_pct": "0.2", + "add_step_pct": "1.5", + "stop_loss_pct": "0", + "take_profit_pct": "10", +} +SETTINGS_FILE = Path(__file__).with_name("settings.json") +STATE_FILE = Path(__file__).with_name("account_state.json") +BACKTEST_REPORTS_DIR = Path(__file__).with_name("historical_reports") +HISTORICAL_MODE = "Исторический прогон" +UI_REDRAW_INTERVAL_MS = 250 +TILE_WIDTH = 184 +TILE_HEIGHT = 186 +TILE_GAP = 8 +MAX_EVENTS_PER_POLL = 2000 +MANUAL_CLOSE_CONFIRM_SECONDS = 15 + + +class PaperSimulator(ChartView): + def __init__(self, root: tk.Tk) -> None: + self.root = root + self.root.title("Bybit — симулятор сделок в реальном времени") + self.root.geometry("1200x850") + self.root.minsize(900, 650) + self.events: queue.Queue[tuple] = queue.Queue() + self.ws_app = None + self.ws_thread: threading.Thread | None = None + self.running = False + self.historical_running = False + self._backtest_cancel = threading.Event() + self.symbol = "BTCUSDT" + self.symbol_states: dict[str, CurrencyState] = {} + self.currencies: list[str] = [] + self.enabled_symbols: set[str] = set() + self.currency_settings: dict[str, dict[str, str]] = {} + self.strategy_by_symbol: dict[str, dict[str, float]] = {} + self._has_saved_enabled_symbols = False + self.tile_widgets: dict[str, dict] = {} + self.detail_windows: dict[str, tk.Toplevel] = {} + self.ticker_24h: dict[str, float] = {} + self.ticker_turnover_24h: dict[str, float] = {} + self.ticker_prices: dict[str, float] = {} + self._ticker_poll_busy = False + self.ws_symbols: list[str] = [] + self.session_started_at = time.time() + self.prices: deque[tuple[float, float]] = deque() + # Candle fields: minute timestamp, open, high, low, close. + self.candles: deque[list[float]] = deque() + self.entry_markers: deque[tuple[float, float, int]] = deque() + self.last_price: float | None = None + self.balance = 5000.0 + self.initial_balance = 5000.0 + self.total_fees = 0.0 + self.position: Position | None = None + self.trades: list[ClosedTrade] = [] + self.next_id = 1 + self.last_signal_pct: float | None = None + self.last_signal_ready = False + self._previous_entry_signal_pct: float | None = None + self.applied_settings: dict[str, float] | None = None + self.baseline_close: float | None = None + self.interval_minutes = CANDLE_INTERVAL_MINUTES + self._last_signal_refresh_at = 0.0 + self._live_minute_prices: deque[tuple[float, float]] = deque() + self.last_ws_message = 0.0 + self.chart_visible_seconds = CHART_SECONDS + self.chart_view_end: float | None = None + self.chart_price_center: float | None = None + self.chart_price_span: float | None = None + self._drag_anchor: tuple[int, int, float, float, float, float] | None = None + self._settings_save_job: str | None = None + self.mode_var = tk.StringVar(value="Симуляция") + self.auto_currency_growth_var = tk.StringVar(value="20") + self.auto_currency_status_var = tk.StringVar(value="Загружаю список Bybit…") + self.ticker_data_source = "" + self.max_active_sim_positions_var = tk.StringVar(value="5") + self.rotation_pending_disable: set[str] = set() + self.auto_enabling_symbols: set[str] = set() + self.auto_symbol_retry_after: dict[str, float] = {} + self.next_auto_currency_scan_at = 0.0 + self.startup_currency_filter_busy = False + self.startup_currency_filter_approved_for: str | None = None + self.historical_days_var = tk.StringVar(value="30") + self.historical_initial_capital_var = tk.StringVar(value="5000") + self.historical_growth_var = tk.StringVar(value="30") + self.historical_min_equity_var = tk.StringVar(value="10") + self.api_key_var = tk.StringVar(value="") + self.api_secret_var = tk.StringVar(value="") + self.credentials_status_var = tk.StringVar(value="Ключи ещё не сохранены на этом компьютере.") + self.testnet_var = tk.BooleanVar(value=True) + self.live_account_var = tk.StringVar(value="") + self.live_position: Position | None = None + self.live_position_info: dict | None = None + self.live_trades: list[ClosedTrade] = [] + self.next_live_id = 1 + self.live_wallet: dict[str, float] | None = None + self.live_positions: list[dict] = [] + self.live_orders: list[dict] = [] + self.live_closed_pnl: list[dict] = [] + self.live_initial_deposits: dict[str, float] = {} + self.api_connecting = False + self.live_client: BybitLiveClient | None = None + self.live_spec: dict[str, str] | None = None + self.live_fee_pct = TAKER_FEE_PCT + self.live_commands: queue.Queue[tuple] = queue.Queue() + self.live_commands_by_symbol: dict[str, queue.Queue] = {} + self.live_workers: dict[str, threading.Thread] = {} + self.live_preparing_symbols: set[str] = set() + self.live_order_lock = threading.Lock() + # Trade ids are allocated from worker threads and the UI thread. + self._live_id_lock = threading.Lock() + self._redraw_job: str | None = None + self._dirty_symbols: set[str] = set() + self._dirty_main = False + self.ws_subscribed: set[str] = set() + self._ws_lock = threading.Lock() + self.historical_universe_var = tk.BooleanVar(value=False) + self.historical_funding_var = tk.BooleanVar(value=True) + # Strategy mode (classic / A / B) for simulation and the historical run. + self.strategy_mode = strategy.STRATEGY_CLASSIC + self.strategy_mode_var = tk.StringVar(value=strategy.STRATEGY_TITLES[self.strategy_mode]) + self.mode_settings: dict[str, dict[str, str]] = { + mode: {key: f"{value:g}" for key, value in defaults.items()} + for mode, defaults in strategy.MODE_DEFAULTS.items() + } + self.strategy_window: tk.Toplevel | None = None + self.ticker_funding_pct: dict[str, float] = {} + self._btc_regime_cache: tuple[float, int, bool | None] = (0.0, 0, None) + self._btc_regime_lock = threading.Lock() + self._signal_pool = ThreadPoolExecutor(max_workers=4) + self.live_control_thread: threading.Thread | None = None + self.live_order_busy = False + self.live_preflight = False + self.live_halted = False + self.live_transition_pending = False + self._build_ui() + self.default_currency_settings = { + "stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + } + self._load_saved_settings() + self._load_saved_credentials() + self._load_saved_state() + self._load_currency_settings(self.symbol) + if not self.currencies: + self._ensure_symbol(self.symbol) + if not self.enabled_symbols and not self._has_saved_enabled_symbols: + self.enabled_symbols.add(self.symbol) + self._ensure_symbol(self.symbol) + if self.position: + self._ensure_symbol(self.position.symbol).position = self.position + self.enabled_symbols.add(self.position.symbol) + if self.live_position: + self._ensure_symbol(self.live_position.symbol).live_position = self.live_position + self.enabled_symbols.add(self.live_position.symbol) + self._render_currency_tiles() + if self.live_position is not None: + self.mode_var.set("Реальная торговля") + self._refresh_settings_summary() + self.root.after(100, self._poll_events) + self.root.after(5000, self._refresh_rolling_change) + self.root.after(5000, self._poll_mode_signals) + self.root.protocol("WM_DELETE_WINDOW", self._on_close) + self._refresh_ui() + self._poll_ticker_24h() + + def _build_ui(self) -> None: + outer = ttk.Frame(self.root, padding=10) + outer.pack(fill="both", expand=True) + + header = ttk.Frame(outer) + header.pack(fill="x") + historical_controls = ttk.Frame(outer) + self.historical_controls_frame = historical_controls + self.auto_currency_controls_frame = ttk.Frame(outer) + self.simulation_controls_frame = ttk.Frame(outer) + self.start_btn = ttk.Button(header, text="Старт", command=self.start) + self.start_btn.pack(side="left") + self.stop_btn = ttk.Button(header, text="Стоп", command=self.stop, state="disabled") + self.stop_btn.pack(side="left", padx=6) + ttk.Label(header, text="Режим:").pack(side="left", padx=(12, 3)) + self.mode_combo = ttk.Combobox(header, textvariable=self.mode_var, + values=("Симуляция", HISTORICAL_MODE, "Реальная торговля"), + state="readonly", width=22) + self.mode_combo.pack(side="left") + self.mode_combo.bind("<>", self._on_mode_change) + strategy_row = ttk.Frame(outer) + strategy_row.pack(fill="x", pady=(4, 0)) + ttk.Label(strategy_row, text="Режим стратегии (симуляция и исторический прогон):").pack(side="left", padx=(0, 4)) + self.strategy_combo = ttk.Combobox( + strategy_row, textvariable=self.strategy_mode_var, state="readonly", width=42, + values=[strategy.STRATEGY_TITLES[mode] for mode in strategy.STRATEGY_MODES], + ) + self.strategy_combo.pack(side="left") + self.strategy_combo.bind("<>", self._on_strategy_mode_selected) + self.strategy_settings_btn = ttk.Button(strategy_row, text="Настройки режима…", + command=self.open_strategy_settings) + self.strategy_settings_btn.pack(side="left", padx=6) + self.strategy_hint_var = tk.StringVar(value="") + ttk.Label(strategy_row, textvariable=self.strategy_hint_var, foreground="#55606b").pack(side="left", padx=6) + self.historical_days_spin = ttk.Spinbox( + historical_controls, from_=1, to=365, textvariable=self.historical_days_var, width=5, + command=self._schedule_settings_save, + ) + self.historical_days_var.trace_add("write", self._schedule_settings_save) + self.historical_days_label = ttk.Label(historical_controls, text="Дней:") + self.historical_capital_label = ttk.Label(historical_controls, text="Депозит, USDT:") + self.historical_capital_entry = ttk.Entry( + historical_controls, textvariable=self.historical_initial_capital_var, width=9, + ) + self.historical_initial_capital_var.trace_add("write", self._schedule_settings_save) + self.historical_growth_label = ttk.Label(historical_controls, text="Рост 24 ч, мин. %:") + self.historical_growth_spin = ttk.Spinbox( + historical_controls, from_=0, to=1000, increment=0.1, + textvariable=self.historical_growth_var, width=7, + command=self._schedule_settings_save, + ) + self.historical_growth_var.trace_add("write", self._schedule_settings_save) + self.historical_equity_label = ttk.Label(historical_controls, text="Стоп капитала, %:") + self.historical_equity_spin = ttk.Spinbox( + historical_controls, from_=1, to=100, increment=1, + textvariable=self.historical_min_equity_var, width=5, + command=self._schedule_settings_save, + ) + self.historical_min_equity_var.trace_add("write", self._schedule_settings_save) + self.historical_days_label.pack(side="left", padx=(0, 2)) + self.historical_days_spin.pack(side="left") + self.historical_capital_label.pack(side="left", padx=(8, 2)) + self.historical_capital_entry.pack(side="left") + self.historical_growth_label.pack(side="left", padx=(8, 2)) + self.historical_growth_spin.pack(side="left") + self.historical_equity_label.pack(side="left", padx=(8, 2)) + self.historical_equity_spin.pack(side="left") + self.historical_universe_check = ttk.Checkbutton( + historical_controls, + text="Отбор валют как в реальном режиме (топ-100 по обороту, порог автоподбора, лимит позиций)", + variable=self.historical_universe_var, command=self._schedule_settings_save, + ) + self.historical_universe_check.pack(side="left", padx=(12, 0)) + ttk.Checkbutton( + historical_controls, text="Учитывать funding", + variable=self.historical_funding_var, command=self._schedule_settings_save, + ).pack(side="left", padx=(12, 0)) + ttk.Label( + self.auto_currency_controls_frame, + text="Автоподбор: топ-100 USDT perpetual по обороту · скан каждые 10 мин · рост за 24 ч выше:", + ).pack(side="left") + self.auto_currency_growth_spin = ttk.Spinbox( + self.auto_currency_controls_frame, from_=0, to=1000, increment=0.1, + textvariable=self.auto_currency_growth_var, width=7, + command=self._schedule_settings_save, + ) + self.auto_currency_growth_spin.pack(side="left", padx=(5, 2)) + ttk.Label(self.auto_currency_controls_frame, text="%").pack(side="left") + ttk.Label( + self.auto_currency_controls_frame, + textvariable=self.auto_currency_status_var, + ).pack(side="left", padx=(10, 0)) + self.auto_currency_growth_var.trace_add("write", self._schedule_settings_save) + self.live_settings_btn = ttk.Button(header, text="API Bybit…", command=self.open_live_settings) + self.live_settings_btn.pack(side="left", padx=5) + self.connect_btn = ttk.Button(header, text="Подключиться", command=self.connect_bybit) + self.connect_btn.pack(side="left", padx=5) + self.status_var = tk.StringVar(value="Остановлен") + ttk.Label(header, textvariable=self.status_var).pack(side="left", padx=8) + + self._build_settings_window() + self._build_live_settings_window() + + ttk.Label(self.simulation_controls_frame, text="Депозит симуляции, USDT:").pack(side="left") + self.simulation_deposit_entry = ttk.Entry( + self.simulation_controls_frame, textvariable=self.initial_var, width=9, + ) + self.simulation_deposit_entry.pack(side="left", padx=(4, 10)) + # The simultaneous-position limit is shared by simulation, live trading and the + # backtest, so it lives in the auto-selection row shown in both trading modes. + ttk.Label(self.auto_currency_controls_frame, text=" Макс. одновременных позиций:").pack(side="left") + self.max_active_sim_positions_spin = ttk.Spinbox( + self.auto_currency_controls_frame, from_=1, to=100, increment=1, + textvariable=self.max_active_sim_positions_var, width=5, + command=self._schedule_settings_save, + ) + self.max_active_sim_positions_spin.pack(side="left", padx=(4, 8)) + self.max_active_sim_positions_var.trace_add("write", self._schedule_settings_save) + ttk.Button( + self.simulation_controls_frame, text="Применить", + command=self.apply_simulation_controls, + ).pack(side="left") + + self.strategy_summary_var = tk.StringVar(value="") + self.strategy_summary_label = ttk.Label( + outer, + textvariable=self.strategy_summary_var, + padding=(8, 5), + relief="groove", + justify="left", + ) + # Legacy account/chart/history views stay instantiated for the existing + # refresh and persistence code, but are no longer part of the home screen. + + self.currencies_frame = ttk.LabelFrame(outer, text="Валюты · независимые параллельные стратегии", padding=6) + self.currencies_frame.pack(fill="both", expand=True, pady=(6, 0)) + self.main_metrics_frame = ttk.Frame(outer) + self.main_metrics_frame.pack(fill="x", pady=(6, 0), before=self.currencies_frame) + self.main_metric_vars: dict[str, tk.StringVar] = {} + self.main_metric_titles: dict[str, ttk.LabelFrame] = {} + for key, title in (("balance", "Баланс"), ("pnl", "P&L"), ("equity", "Общий баланс с P&L"), + ("free", "Свободно для новых сделок")): + box = ttk.LabelFrame(self.main_metrics_frame, text=title, padding=(8, 5)) + box.pack(side="left", fill="x", expand=True, padx=(0, 6)) + value_var = tk.StringVar(value="—") + ttk.Label(box, textvariable=value_var, font=("Segoe UI", 12, "bold")).pack(anchor="w") + self.main_metric_vars[key] = value_var + self.main_metric_titles[key] = box + # Tiles are laid out as a grid that wraps to the window width and scrolls vertically. + self.tiles_canvas = tk.Canvas(self.currencies_frame, highlightthickness=0, background="#eef2f5") + tiles_scroll = ttk.Scrollbar(self.currencies_frame, orient="vertical", command=self.tiles_canvas.yview) + self.tiles_canvas.configure(yscrollcommand=tiles_scroll.set) + tiles_scroll.pack(side="right", fill="y") + self.tiles_canvas.pack(side="left", fill="both", expand=True) + self.tiles_inner = ttk.Frame(self.tiles_canvas) + self.tiles_canvas_window = self.tiles_canvas.create_window((0, 0), window=self.tiles_inner, anchor="nw") + self.tiles_inner.bind("", lambda _event: self.tiles_canvas.configure(scrollregion=self.tiles_canvas.bbox("all"))) + self.tiles_canvas.bind("", lambda _event: self._layout_currency_tiles()) + for sequence in ("", "", ""): + self.tiles_canvas.bind_all(sequence, self._on_tiles_wheel, add="+") + self.tile_frames: dict[str, ttk.Frame] = {} + self.tile_add_button: ttk.Button | None = None + self._tile_layout_key: tuple | None = None + self._render_currency_tiles() + + self._legacy_views = ttk.Frame(outer) + metrics = ttk.Frame(self._legacy_views) + metrics.pack(fill="x", pady=5) + self.metric_vars: dict[str, tk.StringVar] = {} + self.metric_title_vars: dict[str, tk.StringVar] = {} + self.metric_boxes: dict[str, ttk.LabelFrame] = {} + for title, key in (("Баланс", "balance"), ("Бюджет всего", "equity"), ("Без стартового", "pnl"), ("Свободно", "free"), ("Комиссии", "fees")): + box = ttk.LabelFrame(metrics, text=title, padding=(8, 5)) + box.pack(side="left", fill="x", expand=True, padx=(0, 6)) + var = tk.StringVar(value="—") + self.metric_vars[key] = var + title_var = tk.StringVar(value=title) + self.metric_title_vars[key] = title_var + self.metric_boxes[key] = box + box.configure(text=title) + ttk.Label(box, textvariable=var, font=("Segoe UI", 12, "bold")).pack(anchor="w") + + chart_frame = ttk.LabelFrame(self._legacy_views, text="Рыночная цена · публичные сделки Bybit", padding=4) + chart_frame.pack(fill="both", expand=True, pady=(5, 8)) + chart_toolbar = ttk.Frame(chart_frame) + chart_toolbar.pack(fill="x", pady=(0, 3)) + self.market_price_var = tk.StringVar(value="Ожидание цены…") + ttk.Label(chart_toolbar, textvariable=self.market_price_var, font=("Segoe UI", 12, "bold")).pack(side="left", padx=4) + self.live_button = ttk.Button(chart_toolbar, text="К текущему времени", command=self._go_to_live) + self.live_button.pack(side="right", padx=4) + self.canvas = tk.Canvas(chart_frame, background="#101820", highlightthickness=0, height=340) + self.canvas.pack(fill="both", expand=True) + self.canvas.bind("", lambda _event: self._draw_chart()) + self.canvas.bind("", self._on_chart_wheel) + self.canvas.bind("", lambda event: self._on_chart_wheel_linux(event, 1)) + self.canvas.bind("", lambda event: self._on_chart_wheel_linux(event, -1)) + self.canvas.bind("", self._on_chart_press) + self.canvas.bind("", self._on_chart_drag) + self.canvas.bind("", self._on_chart_release) + self.canvas.bind("", self._reset_chart_view) + self.chart_hint_var = tk.StringVar(value="Колесо: масштаб · перетаскивание: перемещение · двойной щелчок: сброс масштаба") + ttk.Label(chart_frame, textvariable=self.chart_hint_var).pack(anchor="w") + + pos_frame = ttk.LabelFrame(self._legacy_views, text="Открытая сделка", padding=5) + pos_frame.pack(fill="x", pady=(0, 6)) + self.position_var = tk.StringVar(value="Нет открытой сделки") + ttk.Label(pos_frame, textvariable=self.position_var).pack(side="left", anchor="w", fill="x", expand=True) + self.close_trade_btn = ttk.Button(pos_frame, text="Закрыть сделку", command=self._manual_close_position, state="disabled") + self.close_trade_btn.pack(side="right", padx=(8, 0)) + + history_frame = ttk.LabelFrame(self._legacy_views, text="История и данные Bybit", padding=5) + history_frame.pack(fill="both", expand=False) + self.history_tabs = ttk.Notebook(history_frame) + self.history_tabs.pack(fill="both", expand=True) + trades_tab = ttk.Frame(self.history_tabs, padding=3) + orders_tab = ttk.Frame(self.history_tabs, padding=3) + positions_tab = ttk.Frame(self.history_tabs, padding=3) + self.history_tabs.add(trades_tab, text="Сделки / P&L") + self.history_tabs.add(orders_tab, text="Ордера Bybit") + self.history_tabs.add(positions_tab, text="Открытые позиции") + cols = ("id", "symbol", "entry", "exit", "roi", "gross", "fees", "net", "reason") + self.table = ttk.Treeview(trades_tab, columns=cols, show="headings", height=5) + self.table.tag_configure("profit", foreground="#13843b") + self.table.tag_configure("loss", foreground="#c62828") + headings = {"id": "#", "symbol": "Тикер", "entry": "Вход", "exit": "Выход", "roi": "ROI %", "gross": "Gross USDT", "fees": "Комиссии", "net": "Net USDT", "reason": "Причина"} + widths = {"id": 45, "symbol": 100, "entry": 115, "exit": 115, "roi": 80, "gross": 105, "fees": 100, "net": 100, "reason": 115} + for col in cols: + self.table.heading(col, text=headings[col]) + self.table.column(col, width=widths[col], anchor="center") + scrollbar = ttk.Scrollbar(trades_tab, orient="vertical", command=self.table.yview) + self.table.configure(yscrollcommand=scrollbar.set) + self.table.pack(side="left", fill="both", expand=True) + scrollbar.pack(side="right", fill="y") + + order_cols = ("time", "symbol", "side", "type", "qty", "price", "fill", "status", "id") + self.bybit_orders_table = ttk.Treeview(orders_tab, columns=order_cols, show="headings", height=5) + order_heads = {"time": "Время", "symbol": "Тикер", "side": "Сторона", "type": "Тип", "qty": "Количество", "price": "Цена", "fill": "Средняя исполнения", "status": "Статус", "id": "Order ID"} + order_widths = {"time": 135, "symbol": 90, "side": 70, "type": 95, "qty": 95, "price": 95, "fill": 130, "status": 110, "id": 210} + for col in order_cols: + self.bybit_orders_table.heading(col, text=order_heads[col]) + self.bybit_orders_table.column(col, width=order_widths[col], anchor="center") + order_scroll = ttk.Scrollbar(orders_tab, orient="vertical", command=self.bybit_orders_table.yview) + self.bybit_orders_table.configure(yscrollcommand=order_scroll.set) + self.bybit_orders_table.pack(side="left", fill="both", expand=True) + order_scroll.pack(side="right", fill="y") + + position_cols = ("symbol", "side", "size", "entry", "mark", "upl", "leverage", "tp", "sl") + self.bybit_positions_table = ttk.Treeview(positions_tab, columns=position_cols, show="headings", height=5) + position_heads = {"symbol": "Тикер", "side": "Сторона", "size": "Объём", "entry": "Средняя цена", "mark": "Mark price", "upl": "Unrealized P&L", "leverage": "Плечо", "tp": "TP", "sl": "SL"} + for col in position_cols: + self.bybit_positions_table.heading(col, text=position_heads[col]) + self.bybit_positions_table.column(col, width=110, anchor="center") + position_scroll = ttk.Scrollbar(positions_tab, orient="vertical", command=self.bybit_positions_table.yview) + self.bybit_positions_table.configure(yscrollcommand=position_scroll.set) + self.bybit_positions_table.pack(side="left", fill="both", expand=True) + position_scroll.pack(side="right", fill="y") + + def _ensure_symbol(self, symbol: str) -> CurrencyState: + symbol = symbol.strip().upper() + if symbol not in self.symbol_states: + self.symbol_states[symbol] = CurrencyState() + if symbol not in self.currencies: + self.currencies.append(symbol) + return self.symbol_states[symbol] + + def _capture_active_symbol(self) -> None: + if not hasattr(self, "symbol_states"): + return + state = self._ensure_symbol(self.symbol) + state.prices = self.prices + state.candles = self.candles + state.entry_markers = self.entry_markers + state.last_price = self.last_price + state.baseline_close = self.baseline_close + state.last_signal_pct = self.last_signal_pct + state.last_signal_ready = self.last_signal_ready + state.previous_entry_signal_pct = self._previous_entry_signal_pct + state.live_minute_prices = self._live_minute_prices + state.last_ws_message = self.last_ws_message + state.position = self.position + state.live_position = self.live_position + state.live_position_info = self.live_position_info + state.live_order_busy = self.live_order_busy + state.live_transition_pending = self.live_transition_pending + state.live_halted = self.live_halted + + def _activate_symbol_state(self, symbol: str) -> None: + state = self._ensure_symbol(symbol) + self.symbol = symbol + self.prices = state.prices + self.candles = state.candles + self.entry_markers = state.entry_markers + self.last_price = state.last_price + self.baseline_close = state.baseline_close + self.last_signal_pct = state.last_signal_pct + self.last_signal_ready = state.last_signal_ready + self._previous_entry_signal_pct = state.previous_entry_signal_pct + self._live_minute_prices = state.live_minute_prices + self.last_ws_message = state.last_ws_message + self.position = state.position + self.live_position = state.live_position + self.live_position_info = state.live_position_info + self.live_order_busy = state.live_order_busy + self.live_transition_pending = state.live_transition_pending + self.live_halted = state.live_halted + + def _render_currency_tiles(self) -> None: + if not hasattr(self, "tiles_inner"): + return + for child in self.tiles_inner.winfo_children(): + child.destroy() + self.tile_widgets.clear() + self.tile_frames.clear() + self._tile_layout_key = None + for symbol in list(self.currencies): + self._ensure_symbol(symbol) + tile = ttk.Frame(self.tiles_inner, width=TILE_WIDTH, height=TILE_HEIGHT, padding=7, relief="ridge") + # Fixed tile size so the grid stays even regardless of the text inside. + tile.grid_propagate(False) + tile.pack_propagate(False) + self.tile_frames[symbol] = tile + enabled = tk.BooleanVar(value=symbol in self.enabled_symbols) + toggle = ttk.Checkbutton(tile, text="В торгах", variable=enabled, + command=lambda s=symbol, v=enabled: self._toggle_symbol(s, v.get())) + toggle.pack(anchor="w") + title = ttk.Label(tile, text=symbol, font=("Segoe UI", 11, "bold"), cursor="hand2") + title.pack(anchor="w", pady=(3, 2)) + price = ttk.Label(tile, text="Цена: ждём данные", cursor="hand2") + price.pack(anchor="w") + change = ttk.Label(tile, text="24 ч: —", cursor="hand2") + change.pack(anchor="w") + session = ttk.Label(tile, text="Запуск: +0.00 USDT", cursor="hand2") + session.pack(anchor="w", pady=(4, 0)) + account = ttk.Label(tile, text="Аккаунт: +0.00 USDT", cursor="hand2") + account.pack(anchor="w") + status = ttk.Label(tile, text="Ожидание", foreground="#576574", cursor="hand2", + wraplength=TILE_WIDTH - 20) + status.pack(anchor="w", pady=(3, 0)) + for widget in (tile, title, price, change, session, account, status): + widget.bind("", lambda _e, s=symbol: self._open_currency_details(s)) + widget.bind("", lambda _e, s=symbol: self._open_currency_details(s)) + self.tile_widgets[symbol] = {"enabled": enabled, "price": price, "change": change, + "session": session, "account": account, "status": status} + self.tile_add_button = ttk.Button(self.tiles_inner, text="+\nДобавить\nвалюту", + command=self._add_currency_dialog, width=19) + self._refresh_currency_tiles() + self._layout_currency_tiles() + + def _tile_order(self) -> list[str]: + """Enabled pairs first, then the rest; each group by 24 h change, highest first.""" + def change(symbol: str) -> float: + value = self.ticker_24h.get(symbol) + return value if value is not None and math.isfinite(value) else float("-inf") + enabled = sorted((s for s in self.tile_frames if s in self.enabled_symbols), + key=lambda s: (-change(s), s)) + disabled = sorted((s for s in self.tile_frames if s not in self.enabled_symbols), + key=lambda s: (-change(s), s)) + return enabled + disabled + + def _layout_currency_tiles(self) -> None: + if not hasattr(self, "tiles_canvas") or not hasattr(self, "tile_frames"): + return + width = max(int(self.tiles_canvas.winfo_width()), TILE_WIDTH + TILE_GAP) + columns = max(1, width // (TILE_WIDTH + TILE_GAP)) + order = self._tile_order() + key = (columns, tuple(order)) + if key == self._tile_layout_key: + return # nothing moved: avoid re-gridding (and flicker) on every refresh + self._tile_layout_key = key + for index, symbol in enumerate(order): + self.tile_frames[symbol].grid(row=index // columns, column=index % columns, + padx=TILE_GAP // 2, pady=TILE_GAP // 2) + if self.tile_add_button is not None: + index = len(order) + self.tile_add_button.grid(row=index // columns, column=index % columns, + padx=TILE_GAP // 2, pady=TILE_GAP // 2, sticky="nsew") + self.tiles_inner.update_idletasks() + self.tiles_canvas.configure(scrollregion=self.tiles_canvas.bbox("all")) + + def _on_tiles_wheel(self, event: tk.Event) -> None: + # Scroll the tile grid only when the pointer is over it (charts use their own wheel zoom). + widget = event.widget + while widget is not None: + if widget is self.tiles_canvas: + break + widget = getattr(widget, "master", None) + else: + return + if getattr(event, "num", None) == 4 or getattr(event, "delta", 0) > 0: + self.tiles_canvas.yview_scroll(-1, "units") + else: + self.tiles_canvas.yview_scroll(1, "units") + + def _add_currency_dialog(self) -> None: + dialog = tk.Toplevel(self.root) + dialog.title("Добавить валюту") + dialog.transient(self.root) + dialog.resizable(False, False) + body = ttk.Frame(dialog, padding=14) + body.pack(fill="both", expand=True) + ttk.Label(body, text="Тикер USDT perpetual, например ETHUSDT").pack(anchor="w") + value = tk.StringVar() + entry = ttk.Entry(body, textvariable=value, width=24) + entry.pack(fill="x", pady=8) + entry.focus_set() + def add() -> None: + symbol = value.get().strip().upper() + if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol): + messagebox.showerror("Неверный тикер", "Введите тикер контракта, например ETHUSDT.", parent=dialog) + return + self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + self._select_symbol(symbol) + self._save_settings() + self._render_currency_tiles() + if self.running: + self._subscribe_running_symbols() + self._fetch_baseline_async(symbol, self.interval_minutes) + dialog.destroy() + ttk.Button(body, text="Добавить и включить", command=add).pack(anchor="e") + entry.bind("", lambda _event: add()) + + def _toggle_symbol(self, symbol: str, enabled: bool) -> None: + self._ensure_symbol(symbol) + if enabled: + self.enabled_symbols.add(symbol) + self.rotation_pending_disable.discard(symbol) + else: + self.enabled_symbols.discard(symbol) + self.rotation_pending_disable.discard(symbol) + self._save_settings() + if self.running: + if enabled and self.mode_var.get() == "Реальная торговля" and symbol not in self.live_commands_by_symbol and symbol not in self.live_preparing_symbols: + self._begin_live_additional_symbol(symbol) + if enabled and self.symbol_states[symbol].baseline_close is None: + self._fetch_baseline_async(symbol, self.interval_minutes) + self._subscribe_running_symbols() + self._refresh_currency_tiles() + self._refresh_ui() + + def _begin_live_additional_symbol(self, symbol: str) -> None: + client = self.live_client + if client is None: + self.status_var.set("Сначала подключите Bybit API") + return + base = self.applied_settings or self._safe_read_settings() + defaults = self._read_default_strategy(base) + settings = self._strategy_for_symbol(symbol, defaults) + self.live_preparing_symbols.add(symbol) + thread = threading.Thread(target=self._live_additional_symbol_worker, + args=(client, symbol, settings), daemon=True) + thread.start() + + def _live_additional_symbol_worker(self, client: BybitLiveClient, symbol: str, + settings: dict[str, float]) -> None: + try: + spec = client.get_instrument(symbol) + fee_pct = client.get_taker_fee_pct(symbol) + rows = client.get_positions(symbol) + if any(int(row.get("positionIdx", 0)) != 0 for row in rows): + raise BybitAPIError(f"{symbol}: для бота нужен режим позиции One-Way") + position_row = next((row for row in rows if float(row.get("size") or 0) > 0), None) + state = self.symbol_states.get(symbol) + shadow = state.live_position if state else None + if position_row: + if position_row.get("side") != "Buy": + raise BybitAPIError(f"{symbol}: бот сопровождает только LONG-позиции") + avg, qty = float(position_row.get("avgPrice") or 0), float(position_row.get("size") or 0) + leverage = float(position_row.get("leverage") or settings["leverage"]) + settings["leverage"] = leverage + shadow = Position(**vars(shadow)) if shadow else Position( + self._allocate_live_id(), symbol, avg, qty, avg * qty / leverage, + avg * qty * fee_pct / 100, time.time(), avg, settings["max_adds"]) + shadow.entry_price, shadow.qty, shadow.stake = avg, qty, avg * qty / leverage + tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + client.update_position_stops(symbol, + avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0, + avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0, + spec["tick_size"]) + else: + wallet = client.get_wallet() + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + if wallet["available"] < required: + raise BybitAPIError(f"{symbol}: недостаточно свободной маржи для первого входа") + client.set_leverage(symbol, settings["leverage"]) + settings["fee"] = fee_pct + self.events.put(("live_symbol_ready", symbol, settings, spec, fee_pct, position_row, shadow)) + except Exception as exc: + self.events.put(("live_symbol_failed", symbol, str(exc))) + + def _activate_live_symbol(self, symbol: str, settings: dict[str, float], spec: dict[str, str], + fee_pct: float, position_row: dict | None, shadow: Position | None) -> None: + self.auto_enabling_symbols.discard(symbol) + state = self._ensure_symbol(symbol) + state.live_position = shadow + state.live_position_info = position_row + state.live_halted = False + state.live_order_busy = False + state.live_transition_pending = False + if shadow: + self._reserve_live_id(shadow.trade_id) + self.strategy_by_symbol[symbol] = settings.copy() + commands = self.live_commands_by_symbol[symbol] = queue.Queue() + worker = threading.Thread(target=self._live_worker, + args=(self.live_client, symbol, settings.copy(), spec, fee_pct, shadow, commands), daemon=True) + self.live_workers[symbol] = worker + worker.start() + if position_row: + self._replace_cached_position(position_row) + self._fetch_baseline_async(symbol, self.interval_minutes) + self._subscribe_running_symbols() + self._save_account_state() + self._refresh_currency_tiles() + self.status_var.set(f"Параллельное управление включено · {symbol}") + + def _select_symbol(self, symbol: str) -> None: + changed = symbol != self.symbol + if changed: + self._capture_active_symbol() + self._activate_symbol_state(symbol) + self.symbol_var.set(symbol) + self._load_currency_settings(symbol) + if symbol in self.strategy_by_symbol: + self.applied_settings = self.strategy_by_symbol[symbol].copy() + elif self.currency_settings.get(symbol): + self.applied_settings = self._strategy_for_symbol(symbol, self._safe_read_settings()) + if changed: + self.chart_view_end = None + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self._refresh_price_label() + self._refresh_ui() + self._draw_chart() + + def _load_currency_settings(self, symbol: str) -> None: + values = self.currency_settings.get(symbol) or self.default_currency_settings + variable_map = {"stake_pct": self.stake_var, "max_adds": self.max_adds_var, + "leverage": self.leverage_var, "trigger_pct": self.trigger_var, + "add_step_pct": self.add_step_var, "stop_loss_pct": self.stop_loss_var, + "take_profit_pct": self.take_profit_var} + for key, variable in variable_map.items(): + if key in values: + variable.set(str(values[key])) + + def _strategy_for_symbol(self, symbol: str, fallback: dict[str, float]) -> dict[str, float]: + if not self.currency_settings.get(symbol): + return fallback.copy() + variables = (self.stake_var, self.max_adds_var, self.leverage_var, self.trigger_var, + self.add_step_var, self.stop_loss_var, self.take_profit_var) + snapshot = [(variable, variable.get()) for variable in variables] + try: + self._load_currency_settings(symbol) + parsed = self._read_settings() + parsed["initial"] = fallback["initial"] + parsed["deposit_basis"] = fallback.get("deposit_basis", fallback["initial"]) + parsed["stake"] = parsed["deposit_basis"] * parsed["stake_pct"] / 100 + return parsed + except ValueError: + return fallback.copy() + finally: + for variable, value in snapshot: + variable.set(value) + + def _read_default_strategy(self, fallback: dict[str, float]) -> dict[str, float]: + variables = {"stake_pct": self.stake_var, "max_adds": self.max_adds_var, + "leverage": self.leverage_var, "trigger_pct": self.trigger_var, + "add_step_pct": self.add_step_var, "stop_loss_pct": self.stop_loss_var, + "take_profit_pct": self.take_profit_var} + snapshot = [(variable, variable.get()) for variable in variables.values()] + try: + for key, variable in variables.items(): + variable.set(str(self.default_currency_settings.get(key, variable.get()))) + parsed = self._read_settings() + parsed["initial"] = fallback["initial"] + parsed["deposit_basis"] = fallback.get("deposit_basis", fallback["initial"]) + parsed["stake"] = parsed["deposit_basis"] * parsed["stake_pct"] / 100 + return parsed + except ValueError: + return fallback.copy() + finally: + for variable, value in snapshot: + variable.set(value) + + def _open_currency_details(self, symbol: str) -> None: + self._select_symbol(symbol) + window = self.detail_windows.get(symbol) + if window and window.winfo_exists(): + self._load_detail_strategy_fields(symbol, window) + window.deiconify() + window.lift() + return + window = tk.Toplevel(self.root) + window.title(f"{symbol} · стратегия и график") + window.geometry("1100x800") + window.minsize(820, 600) + self.detail_windows[symbol] = window + if len(self.symbol_states[symbol].candles) < 10: + self._fetch_chart_candles_async(symbol, self.interval_minutes) + toolbar = ttk.Frame(window, padding=8) + toolbar.pack(fill="x") + ttk.Label(toolbar, text=symbol, font=("Segoe UI", 13, "bold")).pack(side="left") + metrics = ttk.Label(toolbar, text="") + metrics.pack(side="left", padx=16) + close_button = ttk.Button(toolbar, text="Закрыть сделку", + command=lambda s=symbol: self._close_from_detail(s), state="disabled") + close_button.pack(side="right", padx=(6, 0)) + window._close_button = close_button + strategy_frame = ttk.LabelFrame(window, text=f"Стратегия · {symbol}", padding=8) + strategy_frame.pack(fill="x", padx=8, pady=(0, 6)) + fields = ( + ("stake_pct", "Ставка, % депозита"), ("max_adds", "Количество доливок"), + ("leverage", "Плечо"), ("trigger_pct", "Рост для входа, %"), + ("add_step_pct", "Шаг доливки при снижении, %"), + ("stop_loss_pct", "Стоп от средней цены, %"), + ("take_profit_pct", "TP от средней цены, %"), + ) + window._strategy_vars = {} + for index, (key, label) in enumerate(fields): + row, column = divmod(index, 4) + cell = ttk.Frame(strategy_frame) + cell.grid(row=row, column=column, sticky="w", padx=(0, 12), pady=3) + ttk.Label(cell, text=label).pack(anchor="w") + variable = tk.StringVar() + window._strategy_vars[key] = variable + ttk.Entry(cell, textvariable=variable, width=15).pack(anchor="w") + ttk.Button(strategy_frame, text="Применить для этой валюты", + command=lambda s=symbol, w=window: self._apply_detail_strategy(s, w)).grid( + row=1, column=3, sticky="e", padx=4, pady=4) + ttk.Button(strategy_frame, text="Сделать дефолтными и применить ко всем", + command=lambda s=symbol, w=window: self._apply_detail_strategy(s, w, all_symbols=True)).grid( + row=2, column=3, sticky="e", padx=4, pady=4) + window._strategy_status = tk.StringVar(value="Настройки сохраняются отдельно для этой валюты.") + ttk.Label(strategy_frame, textvariable=window._strategy_status).grid( + row=3, column=0, columnspan=4, sticky="w", pady=(4, 0)) + for index in range(4): + strategy_frame.columnconfigure(index, weight=1) + self._load_detail_strategy_fields(symbol, window) + chart = tk.Canvas(window, background="#101820", highlightthickness=0) + chart.pack(fill="both", expand=True, padx=8, pady=(0, 8)) + window._symbol_chart = chart + window._symbol_metrics = metrics + chart.bind("", lambda _event, s=symbol: self._draw_detail_chart(s)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel_linux, event, 1)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel_linux, event, -1)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_press, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_drag, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_release, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._reset_chart_view, event)) + window.protocol("WM_DELETE_WINDOW", lambda s=symbol: self._close_detail(s)) + self._draw_detail_chart(symbol) + + def _load_detail_strategy_fields(self, symbol: str, window: tk.Toplevel) -> None: + if not hasattr(window, "_strategy_vars"): + return + values = self.currency_settings.get(symbol) or self.default_currency_settings + for key, variable in window._strategy_vars.items(): + variable.set(str(values.get(key, ""))) + if hasattr(window, "_strategy_status"): + window._strategy_status.set( + f"Индивидуальные настройки классического режима: {symbol}" + if self.strategy_mode == strategy.STRATEGY_CLASSIC else + f"Сейчас выбран режим «{strategy.STRATEGY_TITLES[self.strategy_mode]}»: его параметры общие для всех " + "валют («Настройки режима…»). Поля ниже относятся только к классическому режиму." + ) + + def _apply_detail_strategy(self, symbol: str, window: tk.Toplevel, *, all_symbols: bool = False) -> None: + if not window.winfo_exists(): + return + self._ensure_symbol(symbol) + values = {key: variable.get().strip().replace(",", ".") + for key, variable in window._strategy_vars.items()} + try: + stake_pct = float(values["stake_pct"]) + max_adds = float(values["max_adds"]) + leverage = float(values["leverage"]) + trigger = float(values["trigger_pct"]) + add_step = float(values["add_step_pct"]) + stop_loss = float(values["stop_loss_pct"]) + take_profit = float(values["take_profit_pct"]) + numeric = (stake_pct, max_adds, leverage, trigger, add_step, stop_loss, take_profit) + if any(not math.isfinite(value) for value in numeric): + raise ValueError("Все поля должны содержать конечные числа.") + if stake_pct <= 0 or stake_pct > 100: + raise ValueError("Ставка должна быть больше 0% и не больше 100%.") + if max_adds < 0 or not max_adds.is_integer() or max_adds > 100: + raise ValueError("Количество доливок должно быть целым числом от 0 до 100.") + if leverage < 1 or leverage > 100: + raise ValueError("Плечо должно быть от 1 до 100 (Bybit не принимает плечо меньше 1).") + if trigger <= 0 or add_step < 0 or stop_loss < 0 or take_profit < 0: + raise ValueError("Рост для входа должен быть больше 0; остальные проценты не могут быть отрицательными.") + if stop_loss == 0 and take_profit == 0: + raise ValueError("Укажите TP, стоп-лосс или оба уровня.") + except (KeyError, ValueError) as exc: + messagebox.showerror("Проверьте настройки", str(exc), parent=window) + return + + self._capture_active_symbol() + targets = list(self.currencies) if all_symbols else [symbol] + if symbol not in targets: + targets.append(symbol) + account_settings = self.applied_settings or self._safe_read_settings() + deposit_basis = (self._current_live_deposit_basis() or account_settings.get("deposit_basis", 0) + if self.mode_var.get() == "Реальная торговля" + else account_settings.get("initial", self.initial_balance)) + target_stake = deposit_basis * stake_pct / 100 + if self.mode_var.get() == "Реальная торговля": + incompatible = [target for target in targets + if self._ensure_symbol(target).live_position + and self.strategy_by_symbol.get(target, {}).get("leverage") != leverage] + if incompatible: + messagebox.showerror( + "Открыта реальная позиция", + "Нельзя изменить плечо для валют с открытыми позициями: " + ", ".join(incompatible), + parent=window, + ) + return + elif self.running and target_stake > self.balance: + messagebox.showerror("Проверьте ставку", "Ставка на каждый вход не может превышать свободный баланс.", parent=window) + return + + for target in targets: + self._ensure_symbol(target) + settings = { + **account_settings, + "initial": account_settings.get("initial", self.initial_balance), + "deposit_basis": deposit_basis, + "stake_pct": stake_pct, + "stake": target_stake, + "max_adds": int(max_adds), + "leverage": leverage, + "trigger": trigger, + "add_step": add_step, + "stop_loss": stop_loss, + "take_profit": take_profit, + "fee": self.live_fee_pct if self.mode_var.get() == "Реальная торговля" else TAKER_FEE_PCT, + "interval": float(CANDLE_INTERVAL_MINUTES), + } + self.currency_settings[target] = values.copy() + self.strategy_by_symbol[target] = settings.copy() + if self.symbol == target: + self._load_currency_settings(target) + self.applied_settings = settings.copy() + commands = self.live_commands_by_symbol.get(target) + state = self._ensure_symbol(target) + if commands and not state.live_order_busy: + state.live_order_busy = True + commands.put(("settings", time.time(), state.last_price or 0.0, settings.copy())) + if all_symbols: + self.default_currency_settings = values.copy() + self._save_settings() + self._save_account_state() + self._refresh_currency_tiles(set(targets)) + self._refresh_settings_summary() + if all_symbols: + window._strategy_status.set( + f"Настройки применены к {len(targets)} валютам и сохранены как значения по умолчанию." + ) + self.status_var.set(f"Дефолтная стратегия обновлена и применена к {len(targets)} валютам") + else: + window._strategy_status.set(f"Настройки применены только для {symbol}.") + self.status_var.set(f"Индивидуальная стратегия {symbol} сохранена") + + def _close_detail(self, symbol: str) -> None: + window = self.detail_windows.pop(symbol, None) + if window and window.winfo_exists(): + window.destroy() + + def _close_from_detail(self, symbol: str) -> None: + self._select_symbol(symbol) + self._manual_close_position() + + def _draw_detail_chart(self, symbol: str) -> None: + window = self.detail_windows.get(symbol) + if not window or not window.winfo_exists(): + return + self._capture_active_symbol() + active_symbol = self.symbol + active_canvas = self.canvas + self._activate_symbol_state(symbol) + self.canvas = window._symbol_chart + try: + self._draw_chart() + state = self._ensure_symbol(symbol) + pct = self.ticker_24h.get(symbol) + position = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position + exchange_position = next((row for row in self.live_positions if row.get("symbol") == symbol + and float(row.get("size") or 0) > 0), None) + window._symbol_metrics.configure(text=( + f"Цена {self._fmt_price(state.last_price or self.ticker_prices.get(symbol)) if (state.last_price or self.ticker_prices.get(symbol)) else '—'} · " + f"24 ч {pct:+.2f}%" if pct is not None else "24 ч —" + ) + (f" · позиция {position.entry_price:g}" if position else + f" · Bybit {exchange_position.get('side')} · P&L {float(exchange_position.get('unrealisedPnl') or 0):+.2f}" + if exchange_position else " · без позиции")) + window._close_button.configure(state="normal" if self.running and position else "disabled") + finally: + self.canvas = active_canvas + self._activate_symbol_state(active_symbol) + + def _detail_chart_action(self, symbol: str, callback, *args): + window = self.detail_windows.get(symbol) + if not window or not window.winfo_exists(): + return + active_symbol = self.symbol + active_canvas = self.canvas + self._capture_active_symbol() + self._activate_symbol_state(symbol) + self.canvas = window._symbol_chart + try: + callback(*args) + finally: + self._capture_active_symbol() + self.canvas = active_canvas + self._activate_symbol_state(active_symbol) + self._refresh_currency_tiles() + return "break" + + def _refresh_currency_tiles(self, only_symbols: set[str] | None = None) -> None: + if not hasattr(self, "tile_widgets"): + return + for symbol, widgets in list(self.tile_widgets.items()): + if only_symbols is not None and symbol not in only_symbols: + continue + state = self._ensure_symbol(symbol) + if not widgets["price"].winfo_exists(): + continue + widgets["enabled"].set(symbol in self.enabled_symbols) + current_price = state.last_price or self.ticker_prices.get(symbol) + widgets["price"].configure(text=f"Цена: {self._fmt_price(current_price) if current_price else '—'}") + pct = self.ticker_24h.get(symbol) + widgets["change"].configure(text=f"24 ч: {pct:+.2f}%" if pct is not None else "24 ч: —", + foreground="#13843b" if pct and pct > 0 else "#c62828" if pct and pct < 0 else "") + session_pnl = sum(t.net_pnl for t in self.trades if t.symbol == symbol and t.opened_at >= getattr(self, "session_started_at", 0)) + session_pnl += sum(t.net_pnl for t in self.live_trades if t.symbol == symbol and t.opened_at >= getattr(self, "session_started_at", 0)) + account_pnl = sum(t.net_pnl for t in self.trades if t.symbol == symbol) + local_live_total = sum(t.net_pnl for t in self.live_trades if t.symbol == symbol) + exchange_live_total = sum(float(row.get("closedPnl") or 0) for row in self.live_closed_pnl + if row.get("symbol") == symbol) + account_pnl += max(local_live_total, exchange_live_total) + state_position = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position + exchange_position = next((row for row in self.live_positions if row.get("symbol") == symbol + and float(row.get("size") or 0) > 0), None) + if state_position and state.last_price: + current_unrealized = strategy.unrealized_pnl(state_position.side, state_position.entry_price, + state.last_price, state_position.qty) + if state.live_position: + current_unrealized = float((state.live_position_info or {}).get("unrealisedPnl") or current_unrealized) + session_pnl += current_unrealized + account_pnl += current_unrealized + elif exchange_position: + exchange_unrealized = float(exchange_position.get("unrealisedPnl") or 0) + account_pnl += exchange_unrealized + widgets["session"].configure(text=f"Запуск: {session_pnl:+.2f} USDT") + widgets["account"].configure(text=f"Аккаунт: {account_pnl:+.2f} USDT") + pos = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position + if pos: + status_text = ("Сделка · выключится после закрытия" + if symbol in self.rotation_pending_disable else + f"{pos.side.upper()} · стоп {self._fmt_price(pos.stop_price)}" + if pos.mode != strategy.STRATEGY_CLASSIC else + f"В позиции · {pos.add_count + 1} входов") + elif state.mode_signal and self.running and self.mode_var.get() == "Симуляция": + status_text = f"Сигнал {state.mode_signal['side'].upper()} · ждёт входа" + elif exchange_position: + status_text = ("Сделка · выключится после закрытия" + if symbol in self.rotation_pending_disable else + f"Bybit {exchange_position.get('side')} · P&L {float(exchange_position.get('unrealisedPnl') or 0):+.2f}") + else: + status_text = ("Выключена" if symbol in self.rotation_pending_disable else + "В торгах" if symbol in self.enabled_symbols else "Выключена") + widgets["status"].configure(text=status_text) + if only_symbols is None: + self._layout_currency_tiles() + + def _poll_ticker_24h(self) -> None: + if not self._ticker_poll_busy: + self._ticker_poll_busy = True + def worker() -> None: + try: + snapshot, source, funding = self._fetch_ticker_snapshot() + self.events.put(("ticker_24h", snapshot, source, funding)) + except Exception as exc: + # Keep market-data failures visible: otherwise the scanner appears + # connected via WebSocket while its separate REST feed is empty. + self.events.put(("ticker_24h_error", str(exc))) + finally: + self._ticker_poll_busy = False + threading.Thread(target=worker, daemon=True).start() + if self.root.winfo_exists(): + self.root.after(15000, self._poll_ticker_24h) + + @staticmethod + def _fetch_ticker_snapshot() -> tuple[dict[str, tuple[float, float, float]], str, dict[str, float]]: + """(symbol → (price, 24h change %, 24h turnover), host, symbol → current funding rate %).""" + errors = [] + for host in PUBLIC_MARKET_API_HOSTS: + try: + request = urllib.request.Request( + f"{host}/v5/market/tickers?category=linear", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}, + ) + with urllib.request.urlopen(request, timeout=10) as response: + payload = json.loads(response.read().decode("utf-8")) + if payload.get("retCode") != 0: + raise RuntimeError(f"Bybit retCode {payload.get('retCode')}: {payload.get('retMsg', 'ошибка запроса')}") + snapshot = {} + funding: dict[str, float] = {} + for row in payload.get("result", {}).get("list", []): + symbol = str(row.get("symbol") or "").upper() + if not symbol.endswith("USDT"): + continue + try: + snapshot[symbol] = ( + float(row.get("lastPrice") or 0), + float(row.get("price24hPcnt") or 0) * 100, + float(row.get("turnover24h") or 0), + ) + if row.get("fundingRate") not in (None, ""): + funding[symbol] = float(row["fundingRate"]) * 100 + except (TypeError, ValueError): + continue + if not snapshot: + raise RuntimeError("Bybit вернул пустой список USDT-контрактов") + return snapshot, host, funding + except Exception as exc: + errors.append(f"{host}: {exc}") + raise RuntimeError("Не удалось загрузить тикеры. " + " · ".join(errors)) + + def _symbol_has_open_position(self, symbol: str) -> bool: + state = self.symbol_states.get(symbol) + if state and (state.position is not None or state.live_position is not None): + return True + return any(row.get("symbol") == symbol and float(row.get("size") or 0) > 0 + for row in self.live_positions) + + def _finish_auto_retirement(self, symbol: str) -> bool: + if symbol not in self.rotation_pending_disable or self._symbol_has_open_position(symbol): + return False + self.rotation_pending_disable.discard(symbol) + self.enabled_symbols.discard(symbol) + if self.running: + self._subscribe_running_symbols() + self._save_settings() + self._render_currency_tiles() + return True + + def _auto_enable_symbol(self, symbol: str) -> bool: + if symbol in self.enabled_symbols: + self.rotation_pending_disable.discard(symbol) + return False + if time.monotonic() < self.auto_symbol_retry_after.get(symbol, 0.0): + return False + self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + self.rotation_pending_disable.discard(symbol) + base = self.applied_settings or self._safe_read_settings() + defaults = self._read_default_strategy(base) + settings = self._strategy_for_symbol(symbol, defaults) + self.strategy_by_symbol[symbol] = settings.copy() + if self.running: + if self.mode_var.get() == "Реальная торговля": + if symbol not in self.live_commands_by_symbol and symbol not in self.live_preparing_symbols: + self.auto_enabling_symbols.add(symbol) + self._begin_live_additional_symbol(symbol) + else: + self._fetch_baseline_async(symbol, self.interval_minutes) + return True + + def _maybe_auto_rotate_currencies(self) -> None: + if not self.running or self.mode_var.get() not in ("Симуляция", "Реальная торговля"): + return + now = time.monotonic() + if now < self.next_auto_currency_scan_at: + return + try: + threshold = float(self.auto_currency_growth_var.get().strip().replace(",", ".")) + except (ValueError, tk.TclError): + self.auto_currency_status_var.set("Ошибка: проверьте порог роста за 24 ч") + self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS + return + if not math.isfinite(threshold) or not 0 <= threshold <= 1000: + self.auto_currency_status_var.set("Ошибка: порог должен быть от 0 до 1000%") + self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS + return + if not self.ticker_turnover_24h: + self.auto_currency_status_var.set("Ожидаю котировки Bybit REST…") + self.next_auto_currency_scan_at = now + 30 + return + self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS + ranked = sorted( + ((symbol, turnover) for symbol, turnover in self.ticker_turnover_24h.items() + if re.fullmatch(r"[A-Z0-9]+USDT", symbol) and turnover > 0), + key=lambda item: item[1], reverse=True, + )[:TOP_LIQUID_SYMBOLS] + top_symbols = {symbol for symbol, _turnover in ranked} + eligible = {symbol for symbol in top_symbols + if self.ticker_24h.get(symbol, float("-inf")) > threshold} + for symbol in list(self.auto_symbol_retry_after): + if symbol not in eligible: + self.auto_symbol_retry_after.pop(symbol, None) + observed = set(self.ticker_turnover_24h) + removed = 0 + deferred = 0 + changed = False + for symbol in list(self.enabled_symbols): + # Missing ticker data is treated as a temporary API omission, not as a reason to retire a pair. + if symbol not in observed or symbol in eligible: + if symbol in eligible: + self.rotation_pending_disable.discard(symbol) + continue + if self._symbol_has_open_position(symbol): + self.rotation_pending_disable.add(symbol) + deferred += 1 + else: + self.rotation_pending_disable.discard(symbol) + self.enabled_symbols.discard(symbol) + removed += 1 + changed = True + added = 0 + for symbol in sorted(eligible): + if symbol not in self.enabled_symbols: + if self._auto_enable_symbol(symbol): + added += 1 + changed = True + if changed: + if self.mode_var.get() == "Симуляция": + self._subscribe_running_symbols() + self._save_settings() + self._refresh_currency_tiles() + self.auto_currency_status_var.set( + f"Подходят: {len(eligible)} · новых: {added} · отключено: {removed} · ждут закрытия: {deferred}" + ) + + def _begin_startup_currency_filter(self, mode: str, threshold: float) -> None: + """Fetch fresh Bybit tickers before enabling any strategy entries.""" + if self.startup_currency_filter_busy: + return + self.startup_currency_filter_busy = True + self.start_btn.configure(state="disabled") + self.mode_combo.configure(state="disabled") + self.status_var.set(f"Проверяю рост за 24 ч перед запуском · порог {threshold:g}%…") + + def worker() -> None: + try: + snapshot, source, funding = self._fetch_ticker_snapshot() + self.ticker_funding_pct.update(funding) + self.events.put(("startup_currency_filter_ready", mode, threshold, snapshot, source)) + except Exception as exc: + self.events.put(("startup_currency_filter_failed", mode, str(exc))) + + threading.Thread(target=worker, daemon=True).start() + + def _apply_startup_currency_filter( + self, mode: str, threshold: float, + snapshot: dict[str, tuple[float, float, float]], source: str, + ) -> None: + for symbol, (price, change, turnover) in snapshot.items(): + self.ticker_prices[symbol] = price + self.ticker_24h[symbol] = change + self.ticker_turnover_24h[symbol] = turnover + self.ticker_data_source = source + + ranked = sorted( + ((symbol, row[2]) for symbol, row in snapshot.items() + if re.fullmatch(r"[A-Z0-9]+USDT", symbol) and row[2] > 0), + key=lambda item: item[1], reverse=True, + )[:TOP_LIQUID_SYMBOLS] + top_symbols = {symbol for symbol, _turnover in ranked} + eligible = {symbol for symbol in top_symbols if snapshot[symbol][1] > threshold} + known_symbols = set(self.currencies) | set(self.symbol_states) + known_symbols.update(str(row.get("symbol") or "").upper() for row in self.live_positions) + open_symbols = {symbol for symbol in known_symbols if self._symbol_has_open_position(symbol)} + + # Existing positions remain managed even when their currency misses the entry filter. + selected = eligible | open_symbols + self.rotation_pending_disable = open_symbols - eligible + self.enabled_symbols = set(selected) + for symbol in sorted(eligible): + self._ensure_symbol(symbol) + self._save_settings() + self._render_currency_tiles() + self._refresh_currency_tiles() + self.auto_currency_status_var.set( + f"Предстартовый отбор · топ-{len(top_symbols)} по обороту · порог > {threshold:g}% · подходит {len(eligible)}" + ) + self.startup_currency_filter_approved_for = mode + if not selected: + self.startup_currency_filter_approved_for = None + self.start_btn.configure(state="normal") + self.status_var.set(f"Запуск отменён: в топ-{TOP_LIQUID_SYMBOLS} нет валют с ростом выше {threshold:g}% за 24 ч") + messagebox.showwarning( + "Нет валют для запуска", + f"В топ-{TOP_LIQUID_SYMBOLS} по обороту сейчас нет валют с ростом выше {threshold:g}% за 24 часа.", + ) + return + self.start_btn.configure(state="normal") + self.status_var.set(f"Отбор завершён · подходит {len(eligible)} валют · продолжаю запуск") + self.start() + + @staticmethod + def _ws_send_topics(ws, op: str, symbols: list[str]) -> None: + # Bybit accepts a limited number of args per request; send in chunks of 10. + for index in range(0, len(symbols), 10): + chunk = symbols[index:index + 10] + ws.send(json.dumps({"op": op, "args": [f"publicTrade.{symbol}" for symbol in chunk]})) + + def _subscribe_running_symbols(self) -> None: + symbols = sorted(self.enabled_symbols | {s for s, state in self.symbol_states.items() + if state.position or state.live_position}) + self.ws_symbols = symbols + app = self.ws_app + sock = getattr(app, "sock", None) if app else None + if sock is not None and getattr(sock, "connected", False): + # Change topics on the live socket so trades of other pairs are not lost + # during a reconnect (open positions keep receiving prices). + try: + with self._ws_lock: + wanted = set(symbols) + added = sorted(wanted - self.ws_subscribed) + removed = sorted(self.ws_subscribed - wanted) + if removed: + self._ws_send_topics(app, "unsubscribe", removed) + if added: + self._ws_send_topics(app, "subscribe", added) + self.ws_subscribed = wanted + except Exception: + try: + app.close() # fall back to a reconnect, which resubscribes everything + except Exception: + pass + if self.running and symbols and not (self.ws_thread and self.ws_thread.is_alive()): + self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbols,), daemon=True) + self.ws_thread.start() + + def _build_settings_window(self) -> None: + self.settings_window = tk.Toplevel(self.root) + self.settings_window.title("Настройки стратегии и симуляции") + self.settings_window.geometry("1200x700") + self.settings_window.minsize(1000, 600) + self.settings_window.withdraw() + self.settings_window.protocol("WM_DELETE_WINDOW", self.settings_window.withdraw) + + body = ttk.Frame(self.settings_window, padding=12) + body.pack(fill="both", expand=True) + controls = ttk.LabelFrame(body, text="Параметры", padding=10) + controls.pack(fill="x", pady=(0, 10)) + + self.symbol_var = tk.StringVar(value="BTCUSDT") + symbol_cell = ttk.Frame(controls) + symbol_cell.grid(row=0, column=0, sticky="w", padx=(0, 10), pady=2) + ttk.Label(symbol_cell, text="Тикер Bybit").pack(anchor="w") + ttk.Entry(symbol_cell, textvariable=self.symbol_var, width=14).pack(anchor="w") + self.symbol_var.trace_add("write", self._schedule_settings_save) + + self.initial_var = self._setting(controls, "Начальный капитал, USDT", "5000", 0, 2) + self.stake_var = self._setting(controls, "Ставка на каждый вход, % стартового депозита", "5", 0, 4) + self.max_adds_var = self._setting(controls, "Максимум доливок, шт. (0 = выкл.)", "2", 0, 6) + self.leverage_var = self._setting(controls, "Плечо", "1", 1, 0) + self.trigger_var = self._setting(controls, "Рост от прошлой 1-мин свечи для входа, %", "0.2", 1, 2) + self.add_step_var = self._setting(controls, "Шаг доливки при снижении, %", "1.5", 1, 4) + self.stop_loss_var = self._setting(controls, "Стоп от средней цены, %", "0", 2, 0) + self.take_profit_var = self._setting(controls, "TP от средней цены, %", "10", 2, 2) + self.apply_btn = ttk.Button(controls, text="Применить", command=self.apply_settings) + self.apply_btn.grid(row=2, column=4, sticky="w", padx=(8, 0), pady=2) + ttk.Label(controls, text="Первый вход — по росту от закрытия прошлой минутной свечи. Доливки срабатывают при снижении от последней покупки на заданный шаг, пока не достигнут их лимит. Максимум 0 или шаг 0 отключает доливки. TP и стоп применяются ко всему объёму от средневзвешенной цены. В симуляции ставка считается от начального капитала, в реальной торговле — от первого загруженного USDT-депозита аккаунта.").grid( + row=3, column=0, columnspan=8, sticky="w", pady=(6, 0) + ) + + preview = ttk.LabelFrame(body, text="Как настройки влияют на входы и выходы", padding=6) + preview.pack(fill="both", expand=True) + self.preview_canvas = tk.Canvas(preview, background="#101820", highlightthickness=0, height=390) + self.preview_canvas.pack(fill="both", expand=True) + self.preview_canvas.bind("", lambda _event: self._refresh_strategy_preview()) + for variable in (self.trigger_var, self.add_step_var, self.max_adds_var, self.stop_loss_var, self.take_profit_var, self.stake_var, self.leverage_var): + variable.trace_add("write", lambda *_args: self._refresh_strategy_preview()) + self._refresh_strategy_preview() + + def open_settings(self) -> None: + self.settings_window.deiconify() + self.settings_window.lift() + self.settings_window.focus_force() + self._refresh_strategy_preview() + + def _build_live_settings_window(self) -> None: + self.live_settings_window = tk.Toplevel(self.root) + self.live_settings_window.title("Настройки подключения Bybit") + self.live_settings_window.geometry("700x340") + self.live_settings_window.resizable(False, False) + self.live_settings_window.withdraw() + self.live_settings_window.protocol("WM_DELETE_WINDOW", self.live_settings_window.withdraw) + body = ttk.Frame(self.live_settings_window, padding=14) + body.pack(fill="both", expand=True) + ttk.Label(body, text="API key").grid(row=0, column=0, sticky="w", pady=5) + self.api_key_entry = ttk.Entry(body, textvariable=self.api_key_var, width=58) + self.api_key_entry.grid(row=0, column=1, sticky="ew", pady=5) + ttk.Button(body, text="Вставить", command=lambda: self._paste_into(self.api_key_entry)).grid(row=0, column=2, padx=(6, 0)) + ttk.Label(body, text="API secret").grid(row=1, column=0, sticky="w", pady=5) + self.api_secret_entry = ttk.Entry(body, textvariable=self.api_secret_var, width=58, show="•") + self.api_secret_entry.grid(row=1, column=1, sticky="ew", pady=5) + ttk.Button(body, text="Вставить", command=lambda: self._paste_into(self.api_secret_entry)).grid(row=1, column=2, padx=(6, 0)) + ttk.Checkbutton(body, text="Testnet (тестовая среда, без реальных средств)", variable=self.testnet_var, + command=self._schedule_settings_save).grid(row=2, column=1, sticky="w", pady=(8, 3)) + ttk.Label(body, text="Режим Mainnet отправляет реальные рыночные ордера.", foreground="#a52626").grid( + row=3, column=1, sticky="w", pady=2 + ) + ttk.Label(body, text="Создайте ключ с чтением аккаунта и торговлей контрактами, без права вывода средств.", + wraplength=560).grid(row=4, column=1, sticky="w", pady=2) + ttk.Label(body, text="Сохранённые ключи шифруются Windows DPAPI и доступны только этому пользователю Windows.", + wraplength=560).grid(row=5, column=1, sticky="w", pady=2) + ttk.Label(body, textvariable=self.credentials_status_var, wraplength=560).grid( + row=6, column=1, sticky="w", pady=(8, 2) + ) + actions = ttk.Frame(body) + actions.grid(row=7, column=1, columnspan=2, sticky="e", pady=(8, 0)) + ttk.Button(actions, text="Сохранить ключи", command=self._save_api_credentials).pack(side="left", padx=(0, 6)) + ttk.Button(actions, text="Удалить сохранённые", command=self._delete_api_credentials).pack(side="left", padx=(0, 6)) + ttk.Button(actions, text="Готово", command=self.live_settings_window.withdraw).pack(side="left") + body.columnconfigure(1, weight=1) + + def _load_saved_credentials(self) -> None: + try: + credentials = load_credentials() + except CredentialStoreError as exc: + self.credentials_status_var.set(str(exc)) + return + if credentials: + self.api_key_var.set(credentials["api_key"]) + self.api_secret_var.set(credentials["api_secret"]) + self.credentials_status_var.set("Зашифрованные ключи загружены из хранилища Windows.") + + def _save_api_credentials(self) -> None: + try: + save_credentials(self.api_key_var.get(), self.api_secret_var.get()) + except CredentialStoreError as exc: + self.credentials_status_var.set(str(exc)) + messagebox.showerror("Не удалось сохранить ключи", str(exc), parent=self.live_settings_window) + return + self.credentials_status_var.set("Ключи сохранены в зашифрованном виде для текущего пользователя Windows.") + + def _delete_api_credentials(self) -> None: + try: + delete_credentials() + except CredentialStoreError as exc: + self.credentials_status_var.set(str(exc)) + messagebox.showerror("Не удалось удалить ключи", str(exc), parent=self.live_settings_window) + return + self.api_key_var.set("") + self.api_secret_var.set("") + self.credentials_status_var.set("Сохранённые ключи удалены.") + + @staticmethod + def _paste_into(entry: ttk.Entry) -> None: + entry.focus_set() + entry.event_generate("<>") + + def open_live_settings(self) -> None: + self.live_settings_window.deiconify() + self.live_settings_window.lift() + self.live_settings_window.focus_force() + + # ----- strategy modes (classic / A / B) ------------------------------------------------- + + def _mode_from_title(self, title: str) -> str: + return next((mode for mode, text in strategy.STRATEGY_TITLES.items() if text == title), + strategy.STRATEGY_CLASSIC) + + def _on_strategy_mode_selected(self, _event: tk.Event | None = None) -> None: + selected = self._mode_from_title(self.strategy_mode_var.get()) + if selected == self.strategy_mode: + return + if self.running or self.historical_running or self.live_preflight: + self.strategy_mode_var.set(strategy.STRATEGY_TITLES[self.strategy_mode]) + messagebox.showinfo("Режим стратегии", "Остановите торговлю или прогон, затем смените режим стратегии.") + return + self.strategy_mode = selected + for state in self.symbol_states.values(): + state.mode_signal = None + state.mode_signal_bucket = 0 + self._save_settings() + self._update_strategy_hint() + self._refresh_settings_summary() + if self.strategy_window is not None and self.strategy_window.winfo_exists(): + self._build_strategy_settings_content() + self.status_var.set(f"Режим стратегии: {strategy.STRATEGY_TITLES[selected]}") + + def _update_strategy_hint(self) -> None: + if not hasattr(self, "strategy_hint_var"): + return + if self.strategy_mode == strategy.STRATEGY_CLASSIC: + text = "настройки — в плитке каждой валюты" + else: + try: + params = self._strategy_mode_params(self.strategy_mode) + text = (f"ставка {params['stake_pct']:g}% × плечо {params['leverage']:g} · " + f"свечи {int(params['timeframe_min'])} мин · общие для всех валют") + except ValueError as exc: + text = f"ошибка настроек: {exc}" + if self.mode_var.get() == "Реальная торговля": + text += " · в реальной торговле доступна только классика" + self.strategy_hint_var.set(text) + + def _strategy_mode_params(self, mode: str | None = None) -> dict[str, float]: + mode = mode or self.strategy_mode + return strategy.parse_mode_params(mode, self.mode_settings.get(mode, {})) + + def open_strategy_settings(self) -> None: + window = self.strategy_window + if window is None or not window.winfo_exists(): + window = tk.Toplevel(self.root) + window.title("Настройки режима стратегии") + window.geometry("980x600") + window.minsize(760, 480) + self.strategy_window = window + top = ttk.Frame(window, padding=(12, 10, 12, 4)) + top.pack(fill="x") + ttk.Label(top, text="Режим:").pack(side="left") + combo = ttk.Combobox(top, textvariable=self.strategy_mode_var, state="readonly", width=44, + values=[strategy.STRATEGY_TITLES[mode] for mode in strategy.STRATEGY_MODES]) + combo.pack(side="left", padx=6) + combo.bind("<>", self._on_strategy_mode_selected) + window._content = ttk.Frame(window, padding=(12, 4, 12, 12)) + window._content.pack(fill="both", expand=True) + self._build_strategy_settings_content() + window.deiconify() + window.lift() + window.focus_force() + + def _build_strategy_settings_content(self) -> None: + window = self.strategy_window + if window is None or not window.winfo_exists(): + return + content = window._content + for child in content.winfo_children(): + child.destroy() + mode = self.strategy_mode + ttk.Label(content, text=strategy.STRATEGY_TITLES[mode], font=("Segoe UI", 12, "bold")).pack(anchor="w") + ttk.Label(content, text=strategy.STRATEGY_DESCRIPTIONS[mode], wraplength=930, justify="left").pack( + anchor="w", pady=(4, 10)) + grid = ttk.LabelFrame(content, text="Параметры режима", padding=8) + grid.pack(fill="x") + window._strategy_vars = {} + if mode == strategy.STRATEGY_CLASSIC: + fields = [("stake_pct", "Ставка, % депозита"), ("max_adds", "Количество доливок"), + ("leverage", "Плечо"), ("trigger_pct", "Рост для входа, %"), + ("add_step_pct", "Шаг доливки при снижении, %"), + ("stop_loss_pct", "Стоп от средней цены, %"), ("take_profit_pct", "TP от средней цены, %")] + values = self.default_currency_settings + else: + fields = [(key, label) for key, label, *_rest in strategy.MODE_FIELDS[mode]] + values = self.mode_settings.get(mode, {}) + for index, (key, label) in enumerate(fields): + row, column = divmod(index, 3) + cell = ttk.Frame(grid) + cell.grid(row=row, column=column, sticky="w", padx=(0, 18), pady=3) + ttk.Label(cell, text=label).pack(anchor="w") + variable = tk.StringVar(value=str(values.get(key, ""))) + window._strategy_vars[key] = variable + ttk.Entry(cell, textvariable=variable, width=18).pack(anchor="w") + for column in range(3): + grid.columnconfigure(column, weight=1) + actions = ttk.Frame(content) + actions.pack(fill="x", pady=(10, 0)) + if mode == strategy.STRATEGY_CLASSIC: + ttk.Button(actions, text="Применить ко всем валютам", + command=lambda: self._apply_detail_strategy(self.symbol, window, all_symbols=True)).pack(side="left") + else: + ttk.Button(actions, text="Применить", command=self._apply_strategy_mode_settings).pack(side="left") + ttk.Button(actions, text="Рекомендуемые значения", command=self._reset_strategy_mode_fields).pack(side="left", padx=6) + ttk.Button(actions, text="Закрыть", command=window.withdraw).pack(side="right") + window._strategy_status = tk.StringVar(value=( + "Шаблон классики: применяется ко всем валютам, индивидуальные настройки задаются в плитке валюты." + if mode == strategy.STRATEGY_CLASSIC else + "Параметры общие для всех валют. Стоп и цели открытых позиций рассчитываются при входе; " + "доля частичной фиксации, безубыток, трейлинг и время удержания берутся из текущих настроек." + )) + ttk.Label(content, textvariable=window._strategy_status, wraplength=930, justify="left").pack( + anchor="w", pady=(8, 0)) + if mode != strategy.STRATEGY_CLASSIC: + ttk.Label(content, wraplength=930, justify="left", foreground="#55606b", text=( + "R — расстояние от входа до начального стопа. Funding указывается в процентах за расчётный период " + "(0.01 = 0.01%). Режимы A и B работают в симуляции и историческом прогоне; реальная торговля " + "использует только классический режим. Лимит одновременных позиций и автоподбор валют — общие." + )).pack(anchor="w", pady=(6, 0)) + + def _reset_strategy_mode_fields(self) -> None: + window = self.strategy_window + if window is None or not window.winfo_exists(): + return + defaults = (DEFAULT_CURRENCY_STRATEGY if self.strategy_mode == strategy.STRATEGY_CLASSIC + else {key: f"{value:g}" for key, value in strategy.MODE_DEFAULTS[self.strategy_mode].items()}) + for key, variable in window._strategy_vars.items(): + if key in defaults: + variable.set(str(defaults[key])) + window._strategy_status.set("Подставлены рекомендуемые значения. Нажмите «Применить», чтобы сохранить.") + + def _apply_strategy_mode_settings(self) -> None: + window = self.strategy_window + mode = self.strategy_mode + if window is None or not window.winfo_exists() or mode == strategy.STRATEGY_CLASSIC: + return + raw = {key: variable.get().strip().replace(",", ".") for key, variable in window._strategy_vars.items()} + try: + strategy.parse_mode_params(mode, raw) + except ValueError as exc: + messagebox.showerror("Проверьте настройки режима", str(exc), parent=window) + return + self.mode_settings[mode] = raw + self._save_settings() + self._update_strategy_hint() + self._refresh_settings_summary() + window._strategy_status.set(f"Настройки режима сохранены: {strategy.STRATEGY_TITLES[mode]}.") + self.status_var.set("Настройки режима стратегии применены") + + def _on_mode_change(self, _event: tk.Event | None = None) -> None: + selected = self.mode_var.get() + if self.running or self.historical_running or self.live_preflight: + self.mode_var.set("Реальная торговля" if self.live_client else "Симуляция") + return + if selected == "Реальная торговля" and any(state.position for state in self.symbol_states.values()): + messagebox.showerror("Открыта симуляционная сделка", "Сначала закройте позицию в режиме симуляции.") + self.mode_var.set("Симуляция") + elif selected == "Симуляция" and any(state.live_position for state in self.symbol_states.values()): + messagebox.showerror("Открыта реальная позиция", "Сначала закройте позицию на Bybit в реальном режиме.") + self.mode_var.set("Реальная торговля") + else: + self.start_btn.configure(text="Запустить прогон" if selected == HISTORICAL_MODE else "Старт") + self.applied_settings = self._safe_read_settings() + self._refresh_settings_summary() + self._update_historical_controls() + self._update_auto_currency_controls() + self._update_simulation_controls() + self._update_strategy_hint() + self._refresh_ui() + + def _update_historical_controls(self) -> None: + if self.mode_var.get() == HISTORICAL_MODE: + if not self.historical_controls_frame.winfo_manager(): + self.historical_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame) + else: + self.historical_controls_frame.pack_forget() + + def _update_auto_currency_controls(self) -> None: + if self.mode_var.get() in ("Симуляция", "Реальная торговля"): + if not self.auto_currency_controls_frame.winfo_manager(): + self.auto_currency_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame) + else: + self.auto_currency_controls_frame.pack_forget() + + def _update_simulation_controls(self) -> None: + if self.mode_var.get() == "Симуляция": + if not self.simulation_controls_frame.winfo_manager(): + self.simulation_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame) + else: + self.simulation_controls_frame.pack_forget() + + def _simulation_position_limit(self) -> int: + raw = self.max_active_sim_positions_var.get().strip().replace(",", ".") + try: + value = float(raw) + except (ValueError, tk.TclError) as exc: + raise ValueError("Количество одновременных сделок должно быть целым числом от 1 до 100.") from exc + if not math.isfinite(value) or not value.is_integer() or not 1 <= value <= 100: + raise ValueError("Количество одновременных сделок должно быть целым числом от 1 до 100.") + return int(value) + + def apply_simulation_controls(self) -> None: + try: + deposit = float(self.initial_var.get().strip().replace(",", ".")) + if not math.isfinite(deposit) or deposit <= 0: + raise ValueError + self._simulation_position_limit() + except (ValueError, tk.TclError): + messagebox.showerror( + "Проверьте настройки симуляции", + "Укажите депозит больше нуля и целый лимит сделок от 1 до 100.", + ) + return + + deposit_changed = abs(deposit - self.initial_balance) > 1e-9 + has_open_positions = any(state.position is not None for state in self.symbol_states.values()) + if deposit_changed and (self.running or has_open_positions): + messagebox.showerror( + "Нельзя изменить депозит", + "Остановите симуляцию и закройте открытые сделки, затем примените новый депозит.", + ) + return + if deposit_changed: + # Preserve already-earned simulation P&L when changing the starting capital. + self.balance += deposit - self.initial_balance + self.initial_balance = deposit + self._save_account_state() + self._save_settings() + self._refresh_ui() + self.status_var.set("Настройки симуляции применены") + + def _refresh_strategy_preview(self) -> None: + canvas = getattr(self, "preview_canvas", None) + if canvas is None or not canvas.winfo_exists(): + return + canvas.delete("all") + width = max(canvas.winfo_width(), 900) + height = max(canvas.winfo_height(), 360) + + def value(var: tk.StringVar, fallback: float) -> float: + try: + return max(0.0, float(var.get().strip().replace(",", "."))) + except (ValueError, tk.TclError): + return fallback + + trigger = value(self.trigger_var, .3) + add_step = value(self.add_step_var, .5) + max_adds = int(value(self.max_adds_var, 2)) + stop_loss = value(self.stop_loss_var, .45) + take_profit = value(self.take_profit_var, .5) + stake_pct = value(self.stake_var, 2) + try: + simulation_capital = max(0.0, float(self.initial_var.get().strip().replace(",", "."))) + except (ValueError, tk.TclError): + simulation_capital = 5000.0 + deposit_basis = (self._current_live_deposit_basis() + if self.mode_var.get() == "Реальная торговля" else None) or simulation_capital + stake = deposit_basis * stake_pct / 100 + leverage = value(self.leverage_var, 10) + reference = 100.0 + entry_prices = [reference * (1 + trigger / 100)] + for _ in range(max_adds if add_step > 0 else 0): + entry_prices.append(entry_prices[-1] * (1 - add_step / 100)) + notional_per_entry = stake * leverage + quantities = [notional_per_entry / price for price in entry_prices] + total_qty = sum(quantities) + total_notional = notional_per_entry * len(entry_prices) + average = total_notional / total_qty if total_qty else entry_prices[-1] + effective_tp = max(take_profit, self._fee_cover_pct(TAKER_FEE_PCT)) + tp_price = average * (1 + effective_tp / 100) if take_profit > 0 else None + sl_price = average * (1 - stop_loss / 100) if stop_loss > 0 else None + next_add_price = entry_prices[-1] * (1 - add_step / 100) if add_step > 0 and len(entry_prices) <= max_adds else None + gross = ((tp_price - average) * total_qty) if tp_price is not None else 0.0 + exit_notional = (tp_price * total_qty) if tp_price is not None else 0.0 + fees = (total_notional + exit_notional) * TAKER_FEE_PCT / 100 + net = gross - fees + total_margin = stake * len(entry_prices) + roi = net / total_margin * 100 if total_margin else 0.0 + + canvas.create_text(16, 12, anchor="nw", fill="#e5edf5", font=("Segoe UI", 11, "bold"), text=f"Пример усреднения · условная прошлая цена = 100.00 USDT · максимум доливок: {max_adds} · 1-мин свечи") + left, right = 78, width - 30 + top, bottom = 52, height - 95 + preview_levels = [reference, *entry_prices, sl_price if sl_price else average] + if next_add_price is not None: + preview_levels.append(next_add_price) + if tp_price is not None: + preview_levels.append(tp_price) + low = min(preview_levels) * .998 + high = max(preview_levels) * 1.002 + if high <= low: + high = low + 1 + + def y_for(price: float) -> float: + return bottom - (price - low) / (high - low) * (bottom - top) + + def fmt(price: float) -> str: + return f"{price:.6f}".rstrip("0").rstrip(".") + + def level(price: float, label: str, color: str, dash: tuple[int, ...] = (4, 3)) -> None: + y = y_for(price) + canvas.create_line(left, y, right, y, fill=color, dash=dash, width=1) + canvas.create_text(left + 5, y - 13, anchor="sw", fill=color, font=("Segoe UI", 8), text=f"{label}: {fmt(price)}") + + level(reference, "Закрытие прошлой свечи", "#9fb2c4") + for index, price in enumerate(entry_prices): + title = f"Вход #{index + 1}" if index == 0 else f"Доливка #{index} (−{add_step:g}%)" + level(price, title, "#63a8ff" if index == 0 else "#b49cff") + level(average, "Средняя цена позиции", "#f2c14e", (2, 3)) + if tp_price is not None: + level(tp_price, f"TP +{effective_tp:g}%", "#40d6b0") + if sl_price is not None: + level(sl_price, f"Стоп −{stop_loss:g}%", "#ff6969") + if next_add_price is not None: + level(next_add_price, f"Следующая доливка −{add_step:g}%", "#d28cff") + + # Draw only the entry levels enabled by the add-step setting. + entry_x = [left + (right-left) * (.24 + index * .18) for index in range(len(entry_prices))] + path = [(left + 10, reference), *zip(entry_x, entry_prices), (right - 10, tp_price if tp_price is not None else average)] + coords = [(x, y_for(price)) for x, price in path] + candle_width = min(34, max(16, (right - left) / (len(path) * 2.8))) + for index, ((x1, open_price), (x2, close_price)) in enumerate(zip(path, path[1:])): + wick = max(abs(close_price - open_price) * .2, max(open_price, close_price) * .0005) + center_x = (x1 + x2) / 2 + canvas.create_line(center_x, y_for(max(open_price, close_price) + wick), center_x, y_for(min(open_price, close_price) - wick), fill="#ef5965" if close_price < open_price else "#38d996", width=2) + color = "#38d996" if close_price >= open_price else "#ef5965" + body_top, body_bottom = sorted((y_for(open_price), y_for(close_price))) + if body_bottom - body_top < 3: + body_bottom = body_top + 3 + canvas.create_rectangle(center_x-candle_width/2, body_top, center_x+candle_width/2, body_bottom, fill=color, outline=color) + for index in range(len(entry_prices)): + x, y = coords[index + 1] + label = "ВХОД" if index == 0 else f"ДОЛИВКА {index}" + canvas.create_oval(x-4, y-4, x+4, y+4, fill="#63a8ff" if index == 0 else "#b49cff", outline="white") + canvas.create_text(x, y-8, anchor="s", fill="#c6b4ff" if index else "#8fc2ff", font=("Segoe UI", 8, "bold"), text=label) + if tp_price is not None: + x, y = coords[-1] + canvas.create_oval(x-4, y-4, x+4, y+4, fill="#40d6b0", outline="white") + canvas.create_text(x, y-8, anchor="s", fill="#63e6c2", font=("Segoe UI", 8, "bold"), text="ЗАКРЫТИЕ TP") + + pnl_text = f"При TP после {len(entry_prices)} вход(а/ов): Gross {gross:+.4f} · комиссии {fees:.4f} · Net {net:+.4f} USDT ({roi:+.2f}% на суммарную ставку {total_margin:g})" + entries_text = " → ".join((f"вход {fmt(entry_prices[0])}", *(f"доливка {fmt(price)}" for price in entry_prices[1:]))) + canvas.create_text(16, height-58, anchor="nw", fill="#dce7f0", font=("Segoe UI", 9), text=f"Пример: 100.00 → {entries_text} → средняя {fmt(average)} → TP {fmt(tp_price) if tp_price else 'выкл.'} / стоп {fmt(sl_price) if sl_price else 'выкл.'}") + canvas.create_text(16, height-38, anchor="nw", fill="#dce7f0", font=("Segoe UI", 9), text=pnl_text) + canvas.create_text(16, height-18, anchor="nw", fill="#9fb2c4", font=("Segoe UI", 8), text=f"Ставка {stake_pct:g}% от базы {deposit_basis:g} USDT = {stake:g} USDT × плечо {leverage:g} на каждый вход · taker-комиссия {TAKER_FEE_PCT:g}% за сторону · расчёт примерный, без проскальзывания и funding.") + + def _setting(self, parent: ttk.Widget, label: str, default: str, row: int, col: int) -> tk.StringVar: + cell = ttk.Frame(parent) + cell.grid(row=row, column=col, sticky="w", padx=(0, 10), pady=2) + ttk.Label(cell, text=label).pack(anchor="w") + var = tk.StringVar(value=default) + ttk.Entry(cell, textvariable=var, width=13).pack(anchor="w") + var.trace_add("write", self._schedule_settings_save) + return var + + def _settings_payload(self) -> dict[str, object]: + return { + "symbol": self.symbol_var.get().strip().upper(), + "currencies": self.currencies, + "enabled_symbols": sorted(self.enabled_symbols), + "currency_settings": self.currency_settings, + "default_currency_settings": self.default_currency_settings, + "strategy_defaults_version": STRATEGY_DEFAULTS_VERSION, + "initial_capital": self.initial_var.get(), + "stake_pct": self.stake_var.get(), + "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), + "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), + "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + "historical_days": self.historical_days_var.get(), + "historical_initial_capital": self.historical_initial_capital_var.get(), + "historical_growth_threshold_pct": self.historical_growth_var.get(), + "historical_min_equity_pct": self.historical_min_equity_var.get(), + "historical_universe_mode": bool(self.historical_universe_var.get()), + "historical_include_funding": bool(self.historical_funding_var.get()), + "strategy_mode": self.strategy_mode, + "strategy_mode_settings": self.mode_settings, + "auto_currency_min_growth_24h_pct": self.auto_currency_growth_var.get(), + "max_active_sim_positions": self.max_active_sim_positions_var.get(), + "live_testnet": bool(self.testnet_var.get()), + } + + def _load_saved_settings(self) -> None: + try: + saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError, TypeError): + return + variables = { + "symbol": self.symbol_var, + "initial_capital": self.initial_var, + "max_adds": self.max_adds_var, + "leverage": self.leverage_var, + "trigger_pct": self.trigger_var, + "add_step_pct": self.add_step_var, + "stop_loss_pct": self.stop_loss_var, + "take_profit_pct": self.take_profit_var, + } + if "historical_days" in saved: + self.historical_days_var.set(str(saved["historical_days"])) + if "historical_initial_capital" in saved: + self.historical_initial_capital_var.set(str(saved["historical_initial_capital"])) + elif "initial_capital" in saved: + self.historical_initial_capital_var.set(str(saved["initial_capital"])) + if "historical_growth_threshold_pct" in saved: + self.historical_growth_var.set(str(saved["historical_growth_threshold_pct"])) + if "historical_min_equity_pct" in saved: + self.historical_min_equity_var.set(str(saved["historical_min_equity_pct"])) + if "historical_universe_mode" in saved: + self.historical_universe_var.set(bool(saved["historical_universe_mode"])) + if "historical_include_funding" in saved: + self.historical_funding_var.set(bool(saved["historical_include_funding"])) + saved_modes = saved.get("strategy_mode_settings") + if isinstance(saved_modes, dict): + for mode, values in saved_modes.items(): + if mode in self.mode_settings and isinstance(values, dict): + self.mode_settings[mode].update({str(key): str(value) for key, value in values.items() + if key in strategy.MODE_DEFAULTS[mode]}) + if saved.get("strategy_mode") in strategy.STRATEGY_MODES: + self.strategy_mode = saved["strategy_mode"] + self.strategy_mode_var.set(strategy.STRATEGY_TITLES[self.strategy_mode]) + self._update_strategy_hint() + if "auto_currency_min_growth_24h_pct" in saved: + self.auto_currency_growth_var.set(str(saved["auto_currency_min_growth_24h_pct"])) + if "max_active_sim_positions" in saved: + self.max_active_sim_positions_var.set(str(saved["max_active_sim_positions"])) + for key, variable in variables.items(): + if key in saved: + variable.set(str(saved[key])) + if "stake_pct" in saved: + self.stake_var.set(str(saved["stake_pct"])) + elif "stake" in saved: + # Migrate earlier settings where stake was saved as a fixed USDT amount. + try: + old_capital = float(str(saved.get("initial_capital", self.initial_var.get())).replace(",", ".")) + old_stake = float(str(saved["stake"]).replace(",", ".")) + if old_capital > 0 and old_stake > 0: + self.stake_var.set(f"{old_stake / old_capital * 100:.8g}") + except (ValueError, TypeError): + pass + if "live_testnet" in saved: + self.testnet_var.set(bool(saved["live_testnet"])) + if "add_step_pct" not in saved: + self.add_step_var.set("0.5") + if "max_adds" not in saved: + self.max_adds_var.set("2") + configured = saved.get("currencies", []) + if isinstance(configured, list): + for value in configured: + symbol = str(value).strip().upper() + if re.fullmatch(r"[A-Z0-9]{2,30}", symbol): + self._ensure_symbol(symbol) + active = saved.get("enabled_symbols") + if isinstance(active, list): + self._has_saved_enabled_symbols = True + self.enabled_symbols = {str(value).strip().upper() for value in active + if re.fullmatch(r"[A-Z0-9]{2,30}", str(value).strip().upper())} + else: + self.enabled_symbols = {self.symbol_var.get().strip().upper()} + saved_overrides = saved.get("currency_settings", {}) + if isinstance(saved_overrides, dict): + self.currency_settings = {str(symbol).strip().upper(): dict(values) + for symbol, values in saved_overrides.items() + if isinstance(values, dict)} + if not self.currencies: + self.currencies = [self.symbol_var.get().strip().upper()] + self.default_currency_settings = { + "stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + } + saved_defaults = saved.get("default_currency_settings", {}) + try: + saved_defaults_version = int(saved.get("strategy_defaults_version", 0)) + except (TypeError, ValueError): + saved_defaults_version = 0 + if saved_defaults_version >= STRATEGY_DEFAULTS_VERSION and isinstance(saved_defaults, dict): + self.default_currency_settings.update({str(key): str(value) for key, value in saved_defaults.items() + if key in self.default_currency_settings}) + else: + # Upgrade the old shared template to the requested defaults while + # preserving individual overrides already saved for specific symbols. + self.default_currency_settings = DEFAULT_CURRENCY_STRATEGY.copy() + self._load_currency_settings(self.symbol_var.get().strip().upper()) + self._render_currency_tiles() + self._update_historical_controls() + self._update_auto_currency_controls() + self._update_simulation_controls() + + def _load_saved_state(self) -> None: + """Restore the virtual account and closed-trade history from the prior run.""" + if not STATE_FILE.exists(): + try: + configured_capital = float(self.initial_var.get().strip().replace(",", ".")) + if configured_capital > 0: + self.initial_balance = self.balance = configured_capital + except (ValueError, tk.TclError): + pass + return + try: + state = json.loads(STATE_FILE.read_text(encoding="utf-8")) + initial = float(state["initial_balance"]) + balance = float(state["balance"]) + fees = float(state.get("total_fees", 0.0)) + next_id = int(state.get("next_id", 1)) + if initial <= 0 or balance < 0 or fees < 0 or next_id < 1: + raise ValueError("Некорректные значения счёта") + loaded_trades = [ClosedTrade(**row) for row in state.get("trades", [])] + position_data = state.get("position") + loaded_position = Position(**position_data) if position_data else None + loaded_positions = {str(symbol): Position(**row) for symbol, row in state.get("positions", {}).items()} + loaded_live_trades = [ClosedTrade(**row) for row in state.get("live_trades", [])] + loaded_deposit_bases = {str(key): float(value) for key, value in state.get("live_initial_deposits", {}).items() + if float(value) > 0} + live_position_data = state.get("live_position") + loaded_live_position = Position(**live_position_data) if live_position_data else None + loaded_live_positions = {str(symbol): Position(**row) for symbol, row in state.get("live_positions_managed", {}).items()} + if loaded_position and (loaded_position.qty <= 0 or loaded_position.entry_price <= 0): + raise ValueError("Некорректные данные открытой позиции") + if loaded_live_position and (loaded_live_position.qty <= 0 or loaded_live_position.entry_price <= 0): + raise ValueError("Некорректные данные реальной позиции") + except (OSError, json.JSONDecodeError, TypeError, KeyError, ValueError) as exc: + self.status_var.set(f"Не удалось загрузить счёт из {STATE_FILE.name}: {exc}") + return + + self.initial_balance = initial + self.balance = balance + self.total_fees = fees + self.trades = loaded_trades + self.position = loaded_position + self.live_trades = loaded_live_trades + self.live_initial_deposits = loaded_deposit_bases + self.live_position = loaded_live_position + for symbol, position in loaded_positions.items(): + self._ensure_symbol(symbol).position = position + self.enabled_symbols.add(symbol) + for symbol, position in loaded_live_positions.items(): + self._ensure_symbol(symbol).live_position = position + self.enabled_symbols.add(symbol) + if loaded_position: + self._ensure_symbol(loaded_position.symbol).position = loaded_position + if loaded_live_position: + self._ensure_symbol(loaded_live_position.symbol).live_position = loaded_live_position + max_trade_id = max((trade.trade_id for trade in loaded_trades), default=0) + max_open_id = max((position.trade_id for position in loaded_positions.values()), default=0) + self.next_id = max(next_id, max_trade_id + 1, max_open_id + 1, + loaded_position.trade_id + 1 if loaded_position else 1) + self.next_live_id = max(int(state.get("next_live_id", 1)), max((trade.trade_id for trade in loaded_live_trades), default=0) + 1, + max((position.trade_id for position in loaded_live_positions.values()), default=0) + 1, + loaded_live_position.trade_id + 1 if loaded_live_position else 1) + self.initial_var.set(str(initial)) + if loaded_position or loaded_live_position: + restored_symbol = loaded_position.symbol if loaded_position else loaded_live_position.symbol + self.symbol = restored_symbol + self.symbol_var.set(restored_symbol) + for trade in reversed(loaded_trades): + tag = "profit" if trade.net_pnl > 0 else "loss" if trade.net_pnl < 0 else "" + self.table.insert( + "", "end", + values=(trade.trade_id, trade.symbol, self._fmt_price(trade.entry_price), self._fmt_price(trade.exit_price), + f"{trade.roi_pct:+.2f}", f"{trade.gross_pnl:+.4f}", f"{trade.fees:.4f}", + f"{trade.net_pnl:+.4f}", trade.reason), + tags=(tag,), + ) + for trade in reversed(loaded_live_trades): + tag = "profit" if trade.net_pnl > 0 else "loss" if trade.net_pnl < 0 else "" + self.table.insert( + "", "end", + values=(f"R{trade.trade_id}", trade.symbol, self._fmt_price(trade.entry_price), self._fmt_price(trade.exit_price), + f"{trade.roi_pct:+.2f}", f"{trade.gross_pnl:+.4f}", f"{trade.fees:.4f}", + f"{trade.net_pnl:+.4f}", f"LIVE · {trade.reason}"), + tags=(tag,), + ) + self.status_var.set(f"Загружено сделок: {len(loaded_trades)} · баланс {self.balance:,.2f} USDT") + + def _save_account_state(self) -> None: + self._capture_active_symbol() + state = { + "version": 1, + "initial_balance": self.initial_balance, + "balance": self.balance, + "total_fees": self.total_fees, + "next_id": self.next_id, + "trades": [vars(trade) for trade in self.trades], + "position": vars(self.position) if self.position else None, + "positions": {symbol: vars(state.position) for symbol, state in self.symbol_states.items() if state.position}, + "next_live_id": self.next_live_id, + "live_trades": [vars(trade) for trade in self.live_trades], + "live_position": vars(self.live_position) if self.live_position else None, + "live_positions_managed": {symbol: vars(state.live_position) for symbol, state in self.symbol_states.items() if state.live_position}, + "live_initial_deposits": self.live_initial_deposits, + } + try: + atomic_write_json(STATE_FILE, state) + except (OSError, ValueError) as exc: + if hasattr(self, "status_var"): + self.status_var.set(f"Не удалось сохранить историю счёта: {exc}") + + def _schedule_settings_save(self, *_args) -> None: + if not hasattr(self, "root") or not self.root.winfo_exists(): + return + if self._settings_save_job is not None: + try: + self.root.after_cancel(self._settings_save_job) + except tk.TclError: + pass + self._settings_save_job = self.root.after(350, self._save_settings) + + def _save_settings(self) -> None: + self._settings_save_job = None + try: + atomic_write_json(SETTINGS_FILE, self._settings_payload()) + except (OSError, ValueError) as exc: + self.status_var.set(f"Не удалось сохранить настройки: {exc}") + + @staticmethod + def _num(var: tk.StringVar, label: str, *, minimum: float = 0, allow_zero: bool = False) -> float: + try: + value = float(var.get().strip().replace(",", ".")) + except ValueError as exc: + raise ValueError(f"Проверьте значение «{label}».") from exc + if not math.isfinite(value) or value < minimum or (not allow_zero and value == 0): + raise ValueError(f"«{label}» должно быть {('не меньше' if allow_zero else 'больше')} {minimum}.") + return value + + def _read_settings(self) -> dict[str, float]: + take_profit = self._num(self.take_profit_var, "TP", allow_zero=True) + stop_loss = self._num(self.stop_loss_var, "стоп-лосс", allow_zero=True) + max_adds_value = self._num(self.max_adds_var, "максимум доливок", allow_zero=True) + if not max_adds_value.is_integer() or max_adds_value > 100: + raise ValueError("Максимум доливок должен быть целым числом от 0 до 100.") + if take_profit == 0 and stop_loss == 0: + raise ValueError("Укажите TP, стоп-лосс или оба уровня — нельзя запускать позицию без условий выхода.") + initial = self._num(self.initial_var, "начальный капитал") + stake_pct = self._num(self.stake_var, "ставка от депозита") + if stake_pct > 100: + raise ValueError("Ставка на каждый вход должна быть не больше 100% депозита.") + deposit_basis = self._current_live_deposit_basis() if self.mode_var.get() == "Реальная торговля" else None + stake = (deposit_basis if deposit_basis is not None else initial) * stake_pct / 100 + return { + "initial": initial, + "stake_pct": stake_pct, + "deposit_basis": deposit_basis or initial, + "stake": stake, + "leverage": self._num(self.leverage_var, "плечо", minimum=1, allow_zero=True), + "trigger": self._num(self.trigger_var, "порог роста"), + "add_step": self._num(self.add_step_var, "шаг доливки", allow_zero=True), + "max_adds": int(max_adds_value), + "stop_loss": stop_loss, + "take_profit": take_profit, + "fee": TAKER_FEE_PCT, + "interval": float(CANDLE_INTERVAL_MINUTES), + } + + def _deposit_baseline_key(self, api_key: str | None = None, testnet: bool | None = None) -> str | None: + key = (api_key if api_key is not None else self.api_key_var.get()).strip() + if not key: + return None + network = self.testnet_var.get() if testnet is None else testnet + fingerprint = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16] + return f"{'testnet' if network else 'mainnet'}:{fingerprint}" + + def _current_live_deposit_basis(self) -> float | None: + key = self._deposit_baseline_key() + value = self.live_initial_deposits.get(key) if key else None + return float(value) if value and value > 0 else None + + def _remember_live_deposit(self, api_key: str, testnet: bool, wallet: dict[str, float], baseline: float | None = None) -> float: + key = self._deposit_baseline_key(api_key, testnet) + if not key: + return float(baseline or wallet.get("wallet") or 0) + saved = self.live_initial_deposits.get(key) + if saved and saved > 0: + return float(saved) + value = float(baseline or wallet.get("wallet") or 0) + if value > 0: + self.live_initial_deposits[key] = value + self._save_account_state() + return value + + def connect_bybit(self) -> None: + """Read the account snapshot without starting the trading loop or placing orders.""" + if self.running or self.live_preflight: + self.status_var.set("Остановите торговый цикл перед новым подключением аккаунта") + return + if self.api_connecting: + return + api_key = self.api_key_var.get().strip() + api_secret = self.api_secret_var.get().strip() + if not api_key or not api_secret: + self.open_live_settings() + self.status_var.set("Вставьте API key и secret, затем нажмите «Подключиться»") + return + self.api_connecting = True + self.connect_btn.configure(state="disabled") + self.status_var.set(f"Подключаюсь к Bybit ({'Testnet' if self.testnet_var.get() else 'Mainnet'}) · только чтение…") + threading.Thread(target=self._api_connect_worker, + args=(api_key, api_secret, self.testnet_var.get()), daemon=True).start() + + def _api_connect_worker(self, api_key: str, api_secret: str, testnet: bool) -> None: + try: + client = BybitLiveClient(api_key, api_secret, testnet) + wallet = client.get_wallet() + optional_results = [] + warnings = [] + for label, method in ( + ("позиции", client.get_open_positions), + ("ордера", lambda: client.get_order_history(50)), + ("историю P&L", lambda: client.get_closed_pnl_history(50)), + ): + try: + optional_results.append(method()) + except Exception as exc: + optional_results.append([]) + warnings.append(f"{label}: {exc}") + positions, orders, closed_pnl = optional_results + self.events.put(("api_connected", client, wallet, positions, orders, closed_pnl, + self._deposit_baseline_key(api_key, testnet), warnings)) + except Exception as exc: + self.events.put(("api_connect_failed", str(exc))) + + def _show_api_snapshot(self, client: BybitLiveClient, wallet: dict[str, float], positions: list[dict], + orders: list[dict], closed_pnl: list[dict], baseline_key: str | None, + warnings: list[str] | None = None) -> None: + self.live_client = client + self.live_wallet = wallet + self.live_positions = positions + for row in positions: + symbol = str(row.get("symbol") or "").upper() + if symbol: + self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + self._render_currency_tiles() + self.live_orders = orders + self.live_closed_pnl = closed_pnl + self.testnet_var.set(client.testnet) + if baseline_key: + baseline = self.live_initial_deposits.get(baseline_key) + if not baseline or baseline <= 0: + baseline = float(wallet.get("wallet") or 0) + if baseline > 0: + self.live_initial_deposits[baseline_key] = baseline + else: + baseline = float(wallet.get("wallet") or 0) + if wallet.get("unrealized_pnl") is None: + wallet["unrealized_pnl"] = sum(float(row.get("unrealisedPnl") or 0) for row in positions) + self._render_bybit_orders() + self._render_bybit_positions() + self.mode_var.set("Реальная торговля") + self._update_historical_controls() + self._update_auto_currency_controls() + self._update_simulation_controls() + self.applied_settings = self._safe_read_settings() + if positions: + self.history_tabs.select(2) + else: + self.history_tabs.select(1) + recent_realized = sum(float(row.get("closedPnl") or 0) for row in closed_pnl) + network = "Testnet" if client.testnet else "MAINNET" + self.live_account_var.set( + f"{network} подключён · стартовый депозит {baseline:,.2f} · кошелёк {wallet['wallet']:,.2f} · " + f"equity {wallet['equity']:,.2f} · P&L нереализованный {wallet.get('unrealized_pnl', 0):+,.2f} · " + f"реализованный за загруженную историю {recent_realized:+,.2f} USDT · " + f"ордеров {len(orders)} · открытых позиций {len(positions)}" + ) + if self.live_position is None: + selected = next((row for row in positions if row.get("symbol") == self.symbol_var.get().strip().upper()), None) + if selected: + self.position_var.set( + f"Bybit · {selected.get('symbol')} {selected.get('side')} · объём {selected.get('size')} · " + f"средняя {selected.get('avgPrice')} · P&L {float(selected.get('unrealisedPnl') or 0):+.4f} USDT · " + f"TP {selected.get('takeProfit') or '—'} · SL {selected.get('stopLoss') or '—'} · " + "подключено для просмотра; нажмите «Старт» для сопровождения ботом" + ) + elif positions: + self.position_var.set(f"На аккаунте открыто позиций: {len(positions)} · подробности во вкладке «Открытые позиции»") + else: + self.position_var.set("Bybit · открытых позиций нет") + self._save_account_state() + self._save_settings() + self._refresh_settings_summary() + self._refresh_ui() + status = f"Bybit подключён · торговля не запущена · ордеров: {len(orders)} · позиций: {len(positions)}" + if warnings: + status += " · часть данных не загружена: " + "; ".join(warnings) + self.status_var.set(status) + + def _render_bybit_orders(self) -> None: + if not hasattr(self, "bybit_orders_table"): + return + for item in self.bybit_orders_table.get_children(): + self.bybit_orders_table.delete(item) + for row in self.live_orders: + stamp = int(row.get("updatedTime") or row.get("createdTime") or 0) / 1000 + try: + time_text = datetime.fromtimestamp(stamp).strftime("%Y-%m-%d %H:%M:%S") + except (OverflowError, OSError, ValueError): + time_text = "—" + self.bybit_orders_table.insert("", "end", values=( + time_text, row.get("symbol", ""), row.get("side", ""), row.get("orderType", ""), + row.get("qty", ""), row.get("price", ""), row.get("avgPrice", ""), + row.get("orderStatus", ""), row.get("orderId", ""), + )) + + def _render_bybit_positions(self) -> None: + if not hasattr(self, "bybit_positions_table"): + return + for item in self.bybit_positions_table.get_children(): + self.bybit_positions_table.delete(item) + for row in self.live_positions: + self.bybit_positions_table.insert("", "end", values=( + row.get("symbol", ""), row.get("side", ""), row.get("size", ""), row.get("avgPrice", ""), + row.get("markPrice", ""), row.get("unrealisedPnl", ""), row.get("leverage", ""), + row.get("takeProfit", "") or "—", row.get("stopLoss", "") or "—", + )) + + def apply_settings(self) -> None: + requested_symbol = self.symbol_var.get().strip().upper() + if not re.fullmatch(r"[A-Z0-9]{2,30}", requested_symbol): + messagebox.showerror("Неверный тикер", "Введите тикер USDT-перпетуального контракта, например BTCUSDT.") + return + self._ensure_symbol(requested_symbol) + self.enabled_symbols.add(requested_symbol) + self._capture_active_symbol() + self._activate_symbol_state(requested_symbol) + try: + settings = self._read_settings() + except ValueError as exc: + messagebox.showerror("Проверьте настройки", str(exc)) + return + if self.mode_var.get() == "Реальная торговля" and any(s.live_position for s in self.symbol_states.values()) and self.applied_settings: + if settings["leverage"] != self.applied_settings["leverage"]: + messagebox.showerror("Открыта реальная позиция", "Нельзя менять плечо, пока позиция открыта. Закройте её и примените новое плечо.") + self.leverage_var.set(str(self.applied_settings["leverage"])) + return + if self.mode_var.get() == "Симуляция" and settings["stake"] > self.balance: + messagebox.showerror("Проверьте ставку", "Ставка не может быть больше текущего баланса.") + return + if not self.running and self.mode_var.get() == "Симуляция" and settings["stake"] > settings["initial"]: + messagebox.showerror("Проверьте ставку", "Ставка не может быть больше начального капитала.") + return + if not self.running and self.mode_var.get() == "Симуляция": + self.balance += settings["initial"] - self.initial_balance + self.initial_balance = settings["initial"] + if self.mode_var.get() == "Реальная торговля": + settings["fee"] = self.live_fee_pct + self.currency_settings[requested_symbol] = { + "stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + } + self.strategy_by_symbol[requested_symbol] = settings.copy() + old_interval = self.interval_minutes + self.applied_settings = settings + self.interval_minutes = int(settings["interval"]) + if self.running: + for state in self.symbol_states.values(): + state.baseline_close = None + state.last_signal_ready = False + state.last_signal_pct = None + if old_interval != self.interval_minutes: + state.candles.clear() + if old_interval != self.interval_minutes: + self.chart_view_end = None + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self.chart_price_center = None + self.chart_price_span = None + for symbol in sorted(self.enabled_symbols): + self._fetch_baseline_async(symbol, self.interval_minutes) + if self.mode_var.get() == "Симуляция": + self._subscribe_running_symbols() + self._refresh_price_label() + if self.mode_var.get() == "Реальная торговля": + for symbol, commands in self.live_commands_by_symbol.items(): + state = self._ensure_symbol(symbol) + if not state.live_order_busy: + state.live_order_busy = True + symbol_settings = self.strategy_by_symbol.get(symbol, settings).copy() + commands.put(("settings", time.time(), state.last_price or 0.0, symbol_settings)) + self._save_settings() + self._render_currency_tiles() + self._save_account_state() + self._refresh_settings_summary() + self._refresh_ui() + self.status_var.set("Настройки применены") + + def start(self) -> None: + if self.running: + return + mode = self.mode_var.get() + if mode == HISTORICAL_MODE: + self._start_historical_backtest() + return + if mode == "Реальная торговля" and self.strategy_mode != strategy.STRATEGY_CLASSIC: + messagebox.showerror( + "Режим стратегии", + "Режимы A и B пока работают только в симуляции и историческом прогоне. " + "Для реальной торговли выберите классический режим стратегии.", + ) + return + if self.strategy_mode != strategy.STRATEGY_CLASSIC: + try: + self._strategy_mode_params() + except ValueError as exc: + messagebox.showerror("Проверьте настройки режима", str(exc)) + return + if websocket is None: + messagebox.showerror("Нет зависимости", "Не найден websocket-client. Запустите приложение через run.bat.") + return + if self.startup_currency_filter_busy: + return + if self.startup_currency_filter_approved_for != mode: + try: + threshold = float(self.auto_currency_growth_var.get().strip().replace(",", ".")) + except (ValueError, tk.TclError): + messagebox.showerror("Проверьте порог", "Введите корректный порог роста за 24 часа.") + return + if not math.isfinite(threshold) or not 0 <= threshold <= 1000: + messagebox.showerror("Проверьте порог", "Порог роста за 24 часа должен быть от 0 до 1000%.") + return + self._begin_startup_currency_filter(mode, threshold) + return + self.startup_currency_filter_approved_for = None + self.startup_currency_filter_busy = False + self.mode_combo.configure(state="readonly") + symbols = sorted(self.enabled_symbols) + if not symbols: + messagebox.showerror("Нет активных валют", "Включите переключатель «В торгах» хотя бы у одной валюты.") + return + invalid = next((symbol for symbol in symbols if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol)), None) + if invalid: + messagebox.showerror("Неверный тикер", f"Проверьте тикер {invalid}.") + return + classic = self.strategy_mode == strategy.STRATEGY_CLASSIC + try: + # Modes A/B do not use the classic per-currency settings, so those cannot block a start. + visible_settings = self._read_settings() if classic else self._safe_read_settings() + if self.mode_var.get() == "Симуляция": + self._simulation_position_limit() + except ValueError as exc: + messagebox.showerror("Проверьте настройки", str(exc)) + return + default_settings = self._read_default_strategy(visible_settings) + selected_symbol = self.symbol_var.get().strip().upper() + if selected_symbol not in symbols: + selected_symbol = symbols[0] + per_symbol_settings = {symbol: self._strategy_for_symbol(symbol, default_settings) for symbol in symbols} + settings = per_symbol_settings[selected_symbol] + if classic and self.mode_var.get() == "Симуляция" and any( + item["stake"] > item["initial"] for item in per_symbol_settings.values() + ): + messagebox.showerror("Проверьте ставку", "Ставка не может быть больше начального капитала.") + return + if self.mode_var.get() == "Реальная торговля": + self._begin_live_preflight(symbols[0], settings, per_symbol_settings) + return + self.strategy_by_symbol = per_symbol_settings + self.applied_settings = settings.copy() + self.interval_minutes = int(settings["interval"]) + self._refresh_settings_summary() + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self._save_settings() + for symbol in symbols: + state = self._ensure_symbol(symbol) + state.mode_signal = None + state.mode_signal_bucket = 0 + state.mode_eval_busy = False + if state.position: + # Keep its restored position and indicators; only refresh market data. + state.baseline_close = None + else: + state.prices.clear() + state.candles.clear() + state.entry_markers.clear() + state.last_price = None + state.baseline_close = None + state.previous_entry_signal_pct = None + state.last_signal_pct = None + state.last_signal_ready = False + state.live_minute_prices.clear() + self._last_signal_refresh_at = 0.0 + selected = selected_symbol + if selected not in symbols: + selected = symbols[0] + self.symbol_var.set(selected) + self._activate_symbol_state(selected) + self.market_price_var.set(f"{selected}: ожидаю данные Bybit…") + self.running = True + self.next_auto_currency_scan_at = 0.0 + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + self.session_started_at = time.time() + self.status_var.set(f"Подключение к Bybit: {', '.join(symbols)} · параллельно") + for symbol in symbols: + self._fetch_baseline_async(symbol, self.interval_minutes) + self._save_account_state() + self.ws_symbols = symbols + self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbols,), daemon=True) + self.ws_thread.start() + + def _start_historical_backtest(self) -> None: + if self.running or self.live_preflight or self.historical_running: + self.status_var.set("Сначала завершите текущий торговый цикл или прогон") + return + universe_mode = bool(self.historical_universe_var.get()) + symbols = sorted(self.enabled_symbols) + if universe_mode: + # Symbols come from the point-in-time selection; strategies are prepared for + # every pair with saved overrides, the rest use the default strategy. + symbols = sorted(set(self.currency_settings) | set(self.enabled_symbols)) + if not symbols and not universe_mode: + messagebox.showerror("Нет активных валют", "Включите валюты, которые нужно проверить исторически.") + return + invalid = next((symbol for symbol in symbols if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol)), None) + if invalid: + messagebox.showerror("Неверный тикер", f"Проверьте тикер {invalid}.") + return + try: + # Modes A/B do not use the classic per-currency settings, so those cannot block a run. + visible = (self._read_settings() if self.strategy_mode == strategy.STRATEGY_CLASSIC + else self._safe_read_settings()) + days = int(self.historical_days_var.get().strip()) + if not 1 <= days <= 365: + raise ValueError("Количество дней для прогона должно быть от 1 до 365.") + historical_capital = float( + self.historical_initial_capital_var.get().strip().replace(",", ".") + ) + if not math.isfinite(historical_capital) or historical_capital <= 0: + raise ValueError("Начальный депозит для прогона должен быть больше 0 USDT.") + growth_threshold = float(self.historical_growth_var.get().strip().replace(",", ".")) + if not math.isfinite(growth_threshold) or not 0 <= growth_threshold <= 1000: + raise ValueError("Порог роста за 24 часа должен быть от 0 до 1000%.") + min_equity_pct = float(self.historical_min_equity_var.get().strip().replace(",", ".")) + if not math.isfinite(min_equity_pct) or not 1 <= min_equity_pct <= 100: + raise ValueError("Порог остановки капитала должен быть от 1 до 100%.") + max_positions = self._simulation_position_limit() + if universe_mode: + growth_threshold = float(self.auto_currency_growth_var.get().strip().replace(",", ".")) + if not math.isfinite(growth_threshold) or not 0 <= growth_threshold <= 1000: + raise ValueError("Порог автоподбора (рост за 24 ч) должен быть от 0 до 1000%.") + # Historical stake percentages must use the historical deposit, not the + # separate paper-account capital currently configured in the main UI. + visible["initial"] = historical_capital + visible["deposit_basis"] = historical_capital + visible["stake"] = historical_capital * visible["stake_pct"] / 100 + defaults = self._read_default_strategy(visible) + settings_by_symbol = { + symbol: self._strategy_for_symbol(symbol, defaults) for symbol in symbols + } + mode_params = (self._strategy_mode_params() if self.strategy_mode != strategy.STRATEGY_CLASSIC + else None) + except ValueError as exc: + messagebox.showerror("Проверьте настройки", str(exc)) + return + self._save_settings() + def compact(settings: dict[str, float]) -> dict[str, float]: + return { + "stake": settings["stake"], "leverage": settings["leverage"], + "trigger": settings["trigger"], "add_step": settings["add_step"], + "max_adds": settings["max_adds"], "stop_loss": settings["stop_loss"], + "take_profit": settings["take_profit"], + } + + strategies = {symbol: compact(settings) for symbol, settings in settings_by_symbol.items()} + default_strategy = compact(defaults) + self._backtest_cancel.clear() + self.historical_running = True + self.mode_combo.configure(state="disabled") + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + self.status_var.set( + f"{strategy.STRATEGY_TITLES[self.strategy_mode]} · " + f"загружаю свечи за {days} дн. · депозит {historical_capital:g} USDT · " + f"{'автоподбор' if universe_mode else 'фильтр роста 24 ч'}: {growth_threshold:g}% · " + f"лимит позиций {max_positions} · стоп капитала: {min_equity_pct:g}%" + + ("" if universe_mode else f": {', '.join(symbols)}") + "…" + ) + thread = threading.Thread( + target=self._historical_backtest_worker, + args=(symbols, strategies, historical_capital, int(visible["interval"]), + days, growth_threshold, min_equity_pct), + kwargs={"max_open_positions": max_positions, "universe_mode": universe_mode, + "default_strategy": default_strategy, + "include_funding": bool(self.historical_funding_var.get()), + "strategy_mode": self.strategy_mode, "mode_params": mode_params}, + daemon=True, + ) + thread.start() + + def _historical_backtest_worker(self, symbols: list[str], strategies: dict[str, dict[str, float]], + initial_capital: float, interval: int, days: int = 30, + growth_threshold: float = 30.0, + min_equity_pct: float = 10.0, + max_open_positions: int | None = None, + universe_mode: bool = False, + default_strategy: dict[str, float] | None = None, + include_funding: bool = True, + strategy_mode: str = strategy.STRATEGY_CLASSIC, + mode_params: dict[str, float] | None = None) -> None: + step_ms = interval * 60_000 + end_ms = (int(time.time() * 1000) // step_ms) * step_ms - 1 + period_ms = days * 24 * 60 * 60 * 1000 + trading_start_ms = ((end_ms - period_ms) // step_ms) * step_ms + start_ms = trading_start_ms - 24 * 60 * 60 * 1000 - step_ms + mode_run = strategy_mode != strategy.STRATEGY_CLASSIC and mode_params is not None + # Modes A/B need closed signal candles before the first decision (24h covers B's growth). + warmup_ms = (max(strategy.required_bars(strategy_mode, mode_params) + 2, + strategy.bars_for_hours(24, mode_params["timeframe_min"]) + 2) + * int(mode_params["timeframe_min"]) * 60_000 if mode_run else 2 * step_ms) + if mode_run: + start_ms = min(start_ms, trading_start_ms - warmup_ms) + + def progress(symbol: str, count: int, total: int, stage: str = "") -> None: + self.events.put(("historical_progress", symbol, count, total, stage)) + + candles_by_symbol: dict[str, list[list[float]]] = {} + try: + windows = None + ranges = {symbol: start_ms for symbol in symbols} + skipped: list[str] = [] + if universe_mode: + windows, skipped = prepare_universe(trading_start_ms, end_ms, growth_threshold, + cancel=self._backtest_cancel.is_set, progress=progress) + if not windows: + raise RuntimeError( + f"За период ни одна валюта из топ-100 по обороту не выросла за 24 ч больше {growth_threshold:g}%" + ) + symbols = sorted(windows) + fallback = default_strategy or next(iter(strategies.values())) + strategies = {symbol: strategies.get(symbol, fallback) for symbol in symbols} + # Minute data is needed from just before a pair first qualifies. + ranges = {symbol: max(start_ms, windows[symbol][0][0] - warmup_ms) for symbol in symbols} + with ThreadPoolExecutor(max_workers=max(1, min(2, len(symbols)))) as pool: + futures = { + pool.submit(fetch_klines, symbol, interval, ranges[symbol], end_ms, + self._backtest_cancel.is_set, progress, with_turnover=mode_run): symbol + for symbol in symbols + } + for future in as_completed(futures): + symbol = futures[future] + try: + candles_by_symbol[symbol] = future.result() + except InterruptedError: + raise + except Exception: + if not universe_mode: + raise + skipped.append(symbol) + if self._backtest_cancel.is_set(): + raise InterruptedError("Исторический прогон отменён") + funding_by_symbol: dict[str, dict[int, float]] | None = None + funding_failed: list[str] = [] + if include_funding: + funding_by_symbol = {} + loaded = sorted(candles_by_symbol) + with ThreadPoolExecutor(max_workers=4) as pool: + futures = {pool.submit(fetch_funding_history, symbol, int(candles_by_symbol[symbol][0][0]), + end_ms, self._backtest_cancel.is_set): symbol for symbol in loaded} + for done, future in enumerate(as_completed(futures), start=1): + symbol = futures[future] + try: + funding_by_symbol[symbol] = future.result() + except InterruptedError: + raise + except Exception: + funding_failed.append(symbol) + progress("Funding", done, len(loaded), f"история funding: {done}/{len(loaded)}") + if mode_run: + btc_hourly = None + if strategy_mode == strategy.STRATEGY_BREAKOUT and mode_params["btc_filter"] >= 1: + hour_ms = 3_600_000 + btc_start = trading_start_ms - (int(mode_params["btc_ema"]) * 3 + 48) * hour_ms + btc_hourly = fetch_klines("BTCUSDT", 60, btc_start, end_ms, self._backtest_cancel.is_set, progress) + result = run_mode_backtest( + candles_by_symbol, strategy_mode, mode_params, initial_capital, TAKER_FEE_PCT, + self._backtest_cancel.is_set, trading_start_ms=trading_start_ms, + min_growth_24h_pct=None if universe_mode else growth_threshold, + min_equity_pct=min_equity_pct, max_open_positions=max_open_positions, + universe_windows=windows, funding_by_symbol=funding_by_symbol, btc_hourly=btc_hourly, + ) + else: + result = run_backtest(candles_by_symbol, strategies, initial_capital, + TAKER_FEE_PCT, self._backtest_cancel.is_set, + trading_start_ms=trading_start_ms, + pause_below_24h_pct=growth_threshold, + resume_above_24h_pct=growth_threshold + 1.0, + min_equity_pct=min_equity_pct, + max_open_positions=max_open_positions, + universe_windows=windows, + funding_by_symbol=funding_by_symbol) + result["summary"]["unavailable_symbols"] = sorted(skipped) + result["summary"]["funding_unavailable_symbols"] = sorted(funding_failed) + csv_path, json_path = save_report(result, BACKTEST_REPORTS_DIR) + self.events.put(("historical_completed", result, str(csv_path), str(json_path))) + except InterruptedError: + self.events.put(("historical_cancelled",)) + except Exception as exc: + self.events.put(("historical_failed", str(exc))) + + def _show_historical_report(self, result: dict, csv_path: str, json_path: str) -> None: + summary = result["summary"] + window = tk.Toplevel(self.root) + window.title("Результат исторического прогона · Bybit") + window.geometry("1100x680") + window.minsize(820, 480) + body = ttk.Frame(window, padding=10) + body.pack(fill="both", expand=True) + net = summary["total_net_including_open_usdt"] + candle_items = list(summary["candles"].items()) + ttk.Label(body, text=( + f"{summary['period_start_utc'][:16]} — {summary['period_end_utc'][:16]} UTC · " + f"валют: {len(summary['symbols'])} · свечей: " + ", ".join( + f"{symbol} {count:,}" for symbol, count in candle_items[:30]) + + (f" … ещё {len(candle_items) - 30}" if len(candle_items) > 30 else "") + ), wraplength=1050).pack(anchor="w", pady=(0, 6)) + funding_text = ( + f" · funding {summary.get('funding_usdt', 0.0):+.4f} USDT ({summary.get('funding_events', 0)} начислений)" + if summary.get("funding_included") else " · funding не учтён" + ) + ttk.Label(body, text=( + f"{summary.get('strategy_title', strategy.STRATEGY_TITLES[strategy.STRATEGY_CLASSIC])} · " + f"Капитал {summary['initial_capital']:.2f} → оценка {summary['ending_equity_estimate']:.2f} USDT · " + f"Net {net:+.2f} USDT ({summary['return_pct']:+.2f}%) · " + f"закрыто {summary['closed_trades']} · прибыльных {summary['wins']} · " + f"процент прибыльных {summary['win_rate_pct']:.1f}% · " + f"комиссии {summary['fees_usdt']:.4f} USDT{funding_text} · открытых позиций {summary['open_positions']}" + ), font=("Segoe UI", 10, "bold"), wraplength=1050).pack(anchor="w", pady=(0, 8)) + if "avg_win_usdt" in summary: + profit_factor = summary.get("profit_factor") + ttk.Label(body, text=( + f"Средняя прибыльная {summary['avg_win_usdt']:+.4f} · средняя убыточная " + f"{summary['avg_loss_usdt']:+.4f} USDT · profit factor " + f"{profit_factor:.2f}" if profit_factor is not None else + f"Средняя прибыльная {summary['avg_win_usdt']:+.4f} · средняя убыточная " + f"{summary['avg_loss_usdt']:+.4f} USDT · profit factor —" + ) + f" · сигналов {summary.get('signals', 0)} · отменено при входе " + f"{summary.get('signals_rejected_at_fill', 0)}", wraplength=1050).pack(anchor="w", pady=(0, 6)) + if summary.get("funding_unavailable_symbols"): + ttk.Label(body, text="Нет истории funding (без funding): " + + ", ".join(summary["funding_unavailable_symbols"][:40]), wraplength=1050).pack(anchor="w") + if "max_drawdown_pct" in summary: + hold_days = summary.get("longest_hold_hours", 0.0) / 24 + risk_text = ( + f"Риск: макс. просадка {summary['max_drawdown_pct']:.2f}% " + f"({summary['max_drawdown_usdt']:.2f} USDT) · минимум капитала {summary['min_equity_usdt']:.2f} USDT · " + f"стопов {summary.get('stops', 0)} · ликвидаций {summary.get('liquidations', 0)} · " + f"открытых в минусе {summary.get('open_losing_positions', 0)} · " + f"самое долгое удержание {hold_days:.1f} дн. · макс. маржа в позициях " + f"{summary.get('max_margin_used_usdt', 0.0):.2f} USDT · одновременно позиций до " + f"{summary.get('max_simultaneous_positions', 0)}" + + (f" (лимит {summary['max_open_positions_limit']}, пропущено сигналов " + f"{summary.get('skipped_entries_position_limit', 0)})" + if summary.get("max_open_positions_limit") else "") + ) + ttk.Label(body, text=risk_text, foreground="#b45309", wraplength=1050).pack(anchor="w", pady=(0, 8)) + if summary.get("unavailable_symbols"): + ttk.Label(body, text="Нет данных Bybit (пропущены): " + ", ".join(summary["unavailable_symbols"][:40]) + + (" …" if len(summary["unavailable_symbols"]) > 40 else ""), + wraplength=1050).pack(anchor="w", pady=(0, 6)) + if summary.get("equity_stop_triggered"): + stop_message = ( + f"Прогон остановлен: капитал достиг {summary['equity_stop_pct']:g}% " + f"от начального ({summary['equity_stop_value_usdt']:.2f} USDT). " + f"Оценка капитала в момент остановки: {summary['equity_at_stop_usdt']:.2f} USDT; " + "открытые позиции показаны по цене срабатывания." + ) + ttk.Label(body, text=stop_message, foreground="#b42318", wraplength=1050).pack( + anchor="w", pady=(0, 8) + ) + else: + ttk.Label(body, text=( + f"Защитный порог капитала: {summary['equity_stop_pct']:g}% от начального " + "(с учётом открытого P&L и оценочной комиссии закрытия); не достигнут." + ), wraplength=1050).pack(anchor="w", pady=(0, 8)) + gate_items = list(summary["entry_allowed_at_end"].items()) + gate_state = " · ".join( + f"{symbol}: входы {'разрешены' if allowed else 'заблокированы'}" + for symbol, allowed in gate_items[:30] + ) + (f" · … ещё {len(gate_items) - 30}" if len(gate_items) > 30 else "") + ttk.Label(body, text=f"{summary['entry_filter']} {gate_state}", wraplength=1050).pack(anchor="w", pady=(0, 6)) + table_frame = ttk.Frame(body) + table_frame.pack(fill="both", expand=True) + columns = ("symbol", "side", "status", "opened", "closed", "entry", "exit", "entries", "gross", "fees", + "funding", "net", "roi", "reason") + tree = ttk.Treeview(table_frame, columns=columns, show="headings") + heads = {"symbol": "Тикер", "side": "Сторона", "status": "Статус", "opened": "Вход UTC", "closed": "Выход UTC", + "entry": "Средняя входа", "exit": "Выход / цена", "entries": "Входов", + "gross": "Gross USDT", "fees": "Комиссии", "funding": "Funding", "net": "Net USDT", + "roi": "ROI %", "reason": "Причина"} + widths = {"symbol": 90, "side": 60, "status": 66, "opened": 135, "closed": 135, "entry": 100, "exit": 100, + "entries": 55, "gross": 88, "fees": 80, "funding": 80, "net": 88, "roi": 70, "reason": 210} + for column in columns: + tree.heading(column, text=heads[column]) + tree.column(column, width=widths[column], anchor="center") + tree.tag_configure("profit", foreground="#13843b") + tree.tag_configure("loss", foreground="#c62828") + tree.pack(side="left", fill="both", expand=True) + scrollbar = ttk.Scrollbar(table_frame, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scrollbar.set) + scrollbar.pack(side="right", fill="y") + for trade in result["trades"]: + tree.insert("", "end", values=( + trade["symbol"], trade.get("side", "LONG"), trade["status"], trade["opened_at"][:19].replace("T", " "), + trade["closed_at"][:19].replace("T", " ") if trade["closed_at"] else "—", + f"{trade['entry']:.10g}", f"{trade['exit']:.10g}", trade["entries"], + f"{trade['gross_usdt']:+.4f}", f"{trade['fees_usdt']:.4f}", f"{trade.get('funding_usdt', 0.0):+.4f}", + f"{trade['net_usdt']:+.4f}", f"{trade['roi_pct']:+.2f}", trade["reason"], + ), tags=("profit" if trade["net_usdt"] > 0 else "loss" if trade["net_usdt"] < 0 else "",)) + ttk.Label(body, text=summary["assumptions"], wraplength=1050, justify="left").pack(anchor="w", pady=8) + ttk.Label(body, text=f"CSV: {csv_path} · Сводка: {json_path}", wraplength=1050).pack(anchor="w") + + def _begin_live_preflight(self, symbol: str, settings: dict[str, float], + per_symbol_settings: dict[str, dict[str, float]] | None = None) -> None: + api_key = self.api_key_var.get().strip() + api_secret = self.api_secret_var.get().strip() + if not api_key or not api_secret: + messagebox.showerror("Нет API-данных", "Откройте «API Bybit…» и вставьте API key и API secret.") + self.open_live_settings() + return + all_settings = list((per_symbol_settings or {}).values()) or [settings] + no_stop = [item for item in all_settings if item.get("stop_loss", 0) <= 0] + if no_stop and not self.testnet_var.get(): + worst_leverage = max(item.get("leverage", 1) for item in no_stop) + if not messagebox.askyesno( + "Стоп-лосс выключен", + "У части валют стоп-лосс равен 0: убыток позиции ничем не ограничен, а доливки " + "увеличивают объём при падении цены" + + (f". При плече {worst_leverage:g}x позицию может ликвидировать биржа" if worst_leverage > 1 else "") + + ".\n\nВсё равно запустить на Mainnet?", + icon="warning", + ): + return + if not self.testnet_var.get() and not messagebox.askyesno( + "Подтвердите реальные ордера", + f"Будут отправляться реальные рыночные ордера по {', '.join(sorted(self.enabled_symbols))} " + f"с плечом {settings['leverage']:g}. " + "Биржевые TP/SL останутся активны, пока позиция открыта. Продолжить на Mainnet?", + icon="warning", + ): + return + self.live_preflight = True + self.mode_combo.configure(state="disabled") + self.start_btn.configure(state="disabled") + network_name = "Testnet" if self.testnet_var.get() else "Mainnet" + self.status_var.set(f"Проверяю API Bybit ({network_name})…") + thread = threading.Thread( + target=self._live_preflight_multi_worker, + args=(api_key, api_secret, self.testnet_var.get(), sorted(self.enabled_symbols), + settings.copy(), per_symbol_settings or {}), + daemon=True, + ) + thread.start() + + def _live_preflight_multi_worker(self, api_key: str, api_secret: str, testnet: bool, + symbols: list[str], base_settings: dict[str, float], + per_symbol_settings: dict[str, dict[str, float]]) -> None: + """Validate and reconcile every enabled symbol before starting parallel live loops.""" + try: + client = BybitLiveClient(api_key, api_secret, testnet) + wallet = client.get_wallet() + baseline_key = self._deposit_baseline_key(api_key, testnet) + baseline = float(self.live_initial_deposits.get(baseline_key, 0) or wallet.get("wallet") or 0) + if baseline <= 0: + raise BybitAPIError("Не удалось определить стартовый депозит аккаунта для расчёта ставки") + prepared = [] + projected_available = float(wallet.get("available") or 0) + for symbol in symbols: + settings = per_symbol_settings.get(symbol, base_settings).copy() + settings["deposit_basis"] = baseline + settings["stake"] = baseline * settings["stake_pct"] / 100 + spec = client.get_instrument(symbol) + fee_pct = client.get_taker_fee_pct(symbol) + rows = client.get_positions(symbol) + if any(int(row.get("positionIdx", 0)) != 0 for row in rows): + raise BybitAPIError(f"{symbol}: для бота нужен режим позиции One-Way (positionIdx=0), а не Hedge") + exchange_position = next((row for row in rows if float(row.get("size") or 0) > 0), None) + saved_position = self.symbol_states.get(symbol, CurrencyState()).live_position + if saved_position is None and self.live_position and self.live_position.symbol == symbol: + saved_position = self.live_position + resume_position = None + if exchange_position: + if exchange_position.get("side") != "Buy": + raise BybitAPIError(f"{symbol}: найдена SHORT-позиция; бот сопровождает только LONG") + actual_leverage = float(exchange_position.get("leverage") or settings["leverage"]) + settings["leverage"] = actual_leverage + avg = float(exchange_position.get("avgPrice") or (saved_position.entry_price if saved_position else 0)) + qty = float(exchange_position.get("size") or 0) + if avg <= 0 or qty <= 0: + raise BybitAPIError(f"{symbol}: у Bybit-позиции нет цены или размера") + if saved_position: + resume_position = Position(**vars(saved_position)) + changed = abs(qty - saved_position.qty) > float(spec["qty_step"]) * 2 + resume_position.entry_price = avg + resume_position.qty = qty + resume_position.stake = avg * qty / actual_leverage + if changed: + resume_position.add_count = settings["max_adds"] + else: + resume_position = Position(self._allocate_live_id(), symbol, avg, qty, + avg * qty / actual_leverage, avg * qty * fee_pct / 100, + time.time(), avg, settings["max_adds"]) + tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + client.update_position_stops(symbol, + avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0, + avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0, + spec["tick_size"]) + else: + if saved_position: + # The saved position was closed on Bybit while the app was off: + # record its realized result instead of silently dropping it. + closed = client.get_latest_closed_pnl(symbol, int(saved_position.opened_at * 1000)) + self.events.put(("live_restored_closed", closed, saved_position)) + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + if projected_available < required: + raise BybitAPIError( + f"{symbol}: для всех включённых валют не хватает свободной маржи; " + f"после предыдущих резервов осталось {projected_available:.2f} USDT, нужно около {required:.2f} USDT" + ) + projected_available -= required + client.set_leverage(symbol, settings["leverage"]) + settings["fee"] = fee_pct + prepared.append((symbol, settings, spec, fee_pct, exchange_position, resume_position)) + self.events.put(("live_ready_multi", client, wallet, prepared, baseline_key, baseline)) + except Exception as exc: + self.events.put(("live_preflight_failed", str(exc))) + + def _activate_live_multi(self, client: BybitLiveClient, wallet: dict[str, float], prepared: list, + baseline_key: str | None, baseline: float) -> None: + self._capture_active_symbol() + self.live_preflight = False + self.mode_combo.configure(state="readonly") + self.live_client = client + self.live_wallet = wallet + if baseline_key: + self.live_initial_deposits[baseline_key] = float(baseline) + self.live_order_lock = threading.Lock() + self.running = True + self.next_auto_currency_scan_at = 0.0 + self.session_started_at = time.time() + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + for symbol, settings, spec, fee_pct, exchange_position, resume_position in prepared: + state = self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + state.live_position = resume_position + state.live_position_info = exchange_position + state.live_order_busy = False + state.live_transition_pending = False + state.live_halted = False + self.live_commands_by_symbol[symbol] = queue.Queue() + if resume_position: + self._reserve_live_id(resume_position.trade_id) + if exchange_position: + self._replace_cached_position(exchange_position) + else: + self._replace_cached_position(None, symbol) + self._fetch_baseline_async(symbol, self.interval_minutes) + worker = threading.Thread(target=self._live_worker, + args=(client, symbol, settings.copy(), spec, fee_pct, resume_position, + self.live_commands_by_symbol[symbol]), daemon=True) + self.live_workers[symbol] = worker + worker.start() + selected = self.symbol_var.get().strip().upper() + if selected not in self.enabled_symbols: + selected = prepared[0][0] + self.symbol_var.set(selected) + selected_config = next((item for item in prepared if item[0] == selected), prepared[0]) + self.applied_settings = selected_config[1].copy() + self.live_spec = selected_config[2] + self.live_fee_pct = selected_config[3] + self._activate_symbol_state(selected) + self.ws_symbols = sorted(self.enabled_symbols | {s for s, state in self.symbol_states.items() if state.live_position}) + self.ws_thread = threading.Thread(target=self._ws_worker, args=(self.ws_symbols,), daemon=True) + self.ws_thread.start() + self.status_var.set(f"Реальный бот запущен параллельно · {len(prepared)} валют · {'Testnet' if client.testnet else 'MAINNET'}") + self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · equity {wallet['equity']:.2f} · доступно {wallet['available']:.2f} USDT") + self._refresh_settings_summary() + self._refresh_ui() + self._refresh_currency_tiles() + self._save_account_state() + + def _live_preflight_worker(self, api_key: str, api_secret: str, testnet: bool, symbol: str, + settings: dict[str, float], saved_position: Position | None) -> None: + try: + client = BybitLiveClient(api_key, api_secret, testnet) + wallet = client.get_wallet() + baseline_key = self._deposit_baseline_key(api_key, testnet) + baseline = float(self.live_initial_deposits.get(baseline_key, 0) or wallet.get("wallet") or 0) + if baseline <= 0: + raise BybitAPIError("Не удалось определить стартовый депозит аккаунта для расчёта ставки") + settings["deposit_basis"] = baseline + settings["stake"] = baseline * settings["stake_pct"] / 100 + spec = client.get_instrument(symbol) + fee_pct = client.get_taker_fee_pct(symbol) + rows = client.get_positions(symbol) + if any(int(row.get("positionIdx", 0)) != 0 for row in rows): + raise BybitAPIError("Для этого бота нужен режим позиции One-Way (positionIdx=0), а не Hedge") + exchange_position = next((row for row in rows if float(row.get("size") or 0) > 0), None) + resume_position = None + if exchange_position: + if exchange_position.get("side") != "Buy": + raise BybitAPIError("По тикеру уже открыта SHORT-позиция; бот управляет только LONG") + if saved_position and saved_position.symbol != symbol: + raise BybitAPIError( + f"В истории программы есть позиция {saved_position.symbol}, а на бирже обнаружена {symbol}. " + "Укажите тикер открытой позиции, чтобы продолжить её сопровождение." + ) + actual_leverage = float(exchange_position.get("leverage") or settings["leverage"]) + settings["leverage"] = actual_leverage + avg = float(exchange_position.get("avgPrice") or (saved_position.entry_price if saved_position else 0)) + qty = float(exchange_position.get("size") or 0) + if avg <= 0 or qty <= 0: + raise BybitAPIError("Bybit вернул открытую позицию без цены или размера; сопровождение не запущено") + if saved_position: + # Reconcile local shadow against the authoritative position. + # This also recovers fills that happened just before a shutdown. + resume_position = Position(**vars(saved_position)) + quantity_changed = abs(qty - saved_position.qty) > float(spec["qty_step"]) * 2 + resume_position.entry_price = avg + resume_position.qty = qty + resume_position.stake = avg * qty / actual_leverage + resume_position.last_add_price = resume_position.last_add_price or avg + if quantity_changed: + # The precise number of fills may be unknown after a + # crash; avoid exceeding the configured add limit. + resume_position.add_count = settings["max_adds"] + else: + # Adopt an existing LONG even when the app has no local + # shadow (e.g. the process restarted after a fill). + now = time.time() + resume_position = Position( + self._allocate_live_id(), symbol, avg, qty, avg * qty / actual_leverage, + avg * qty * fee_pct / 100, now, avg, settings["max_adds"], + ) + tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + tp = avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0 + sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + client.update_position_stops(symbol, tp, sl, spec["tick_size"]) + else: + if saved_position: + closed = client.get_latest_closed_pnl(symbol, int(saved_position.opened_at * 1000)) + self.events.put(("live_restored_closed", closed, saved_position)) + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + if wallet["available"] < required: + raise BybitAPIError(f"Доступно {wallet['available']:.2f} USDT, требуется около {required:.2f} USDT на маржу и комиссию") + client.set_leverage(symbol, settings["leverage"]) + self.events.put(("live_ready", client, wallet, spec, fee_pct, settings, symbol, + exchange_position, resume_position, baseline_key, baseline)) + except Exception as exc: + self.events.put(("live_preflight_failed", str(exc))) + + def _activate_live(self, client: BybitLiveClient, wallet: dict[str, float], spec: dict[str, str], + fee_pct: float, settings: dict[str, float], symbol: str, exchange_position: dict | None, + resume_position: Position | None, baseline_key: str | None = None, + baseline: float | None = None) -> None: + self.live_preflight = False + self.mode_combo.configure(state="readonly") + self.live_client = client + self.live_wallet = wallet + if baseline_key: + self.live_initial_deposits[baseline_key] = float(baseline or settings.get("deposit_basis") or wallet.get("wallet") or 0) + self._save_account_state() + self.live_spec = spec + self.live_fee_pct = fee_pct + settings["fee"] = fee_pct + self.applied_settings = settings.copy() + self.symbol = symbol + self.interval_minutes = CANDLE_INTERVAL_MINUTES + self.live_halted = False + self.live_order_busy = False + self.live_transition_pending = False + if exchange_position: + if resume_position is None: + raise RuntimeError("Не удалось восстановить данные открытой позиции Bybit") + self.live_position = resume_position + self._reserve_live_id(resume_position.trade_id) + self.leverage_var.set(str(settings["leverage"])) + self.live_position_info = exchange_position + self._replace_cached_position(exchange_position) + self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · Equity {wallet['equity']:.2f} · доступно {wallet['available']:.2f} USDT") + self._save_account_state() + self.status_var.set( + f"Открытая позиция Bybit восстановлена · {symbol} · средняя {resume_position.entry_price:g} · " + f"объём {resume_position.qty:g}; управление возобновлено" + ) + else: + self.live_position_info = None + self.live_positions = [row for row in self.live_positions if row.get("symbol") != symbol] + self._render_bybit_positions() + self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · стартовый депозит {settings.get('deposit_basis', wallet['wallet']):.2f} · кошелёк {wallet['wallet']:.2f} · доступно {wallet['available']:.2f} USDT") + self.running = True + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + restored = " · сопровождение открытой позиции восстановлено" if exchange_position else "" + self.status_var.set(f"Реальный бот запущен · {symbol} · {'Testnet' if client.testnet else 'MAINNET'}{restored}") + self._refresh_settings_summary() + self._refresh_ui() + self._fetch_baseline_async(symbol, self.interval_minutes) + self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbol,), daemon=True) + self.ws_thread.start() + self.live_control_thread = threading.Thread(target=self._live_worker, args=(client, symbol, settings.copy(), spec, fee_pct, self.live_position), daemon=True) + self.live_control_thread.start() + self._save_account_state() + + def _allocate_live_id(self) -> int: + """Return a unique live trade id; safe to call from worker threads.""" + with self._live_id_lock: + trade_id = self.next_live_id + self.next_live_id += 1 + return trade_id + + def _reserve_live_id(self, trade_id: int) -> None: + """Make sure future ids are above an id restored from disk or the exchange.""" + with self._live_id_lock: + self.next_live_id = max(self.next_live_id, trade_id + 1) + + def _replace_cached_position(self, row: dict | None, symbol: str | None = None) -> None: + target = symbol or (row.get("symbol") if row else None) + if target: + self.live_positions = [item for item in self.live_positions if item.get("symbol") != target] + if row and float(row.get("size") or 0) > 0: + self.live_positions.append(row) + self._render_bybit_positions() + + def _live_worker(self, client: BybitLiveClient, symbol: str, settings: dict[str, float], + spec: dict[str, str], fee_pct: float, shadow: Position | None, + command_queue: queue.Queue | None = None) -> None: + command_queue = command_queue or self.live_commands + try: + self._live_worker_loop(client, symbol, settings, spec, fee_pct, shadow, command_queue) + finally: + # Let the UI thread unregister this worker's queue so the symbol can get a + # fresh worker when it is enabled again (manually or by auto-rotation). + self.events.put(("live_worker_exited", symbol, command_queue)) + + def _live_worker_loop(self, client: BybitLiveClient, symbol: str, settings: dict[str, float], + spec: dict[str, str], fee_pct: float, shadow: Position | None, + command_queue: queue.Queue) -> None: + last_wallet_at = 0.0 + last_position_at = 0.0 + while self.running: + if symbol not in self.enabled_symbols and shadow is None: + return + try: + command = command_queue.get(timeout=0.4) + except queue.Empty: + command = None + try: + if command: + action, timestamp, price, *extra = command + if action == "settings": + updated_settings = extra[0] + updated_settings["fee"] = fee_pct + if updated_settings["leverage"] != settings["leverage"]: + client.set_leverage(symbol, updated_settings["leverage"]) + settings = updated_settings + if shadow: + action = "stops" + else: + self.events.put(("live_settings_updated", symbol)) + action = "settings_done" + if action in ("open", "add"): + skip_reason = None + with self.live_order_lock: + wallet_now = client.get_wallet() + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + order_qty = "" + notional = 0.0 + if wallet_now["available"] < required: + skip_reason = (f"недостаточно доступной маржи: {wallet_now['available']:.2f} USDT; " + f"требуется около {required:.2f} USDT с учётом комиссии") + else: + try: + order_qty = client.floor_qty(settings["stake"] * settings["leverage"] / price, spec) + except BybitAPIError as exc: + skip_reason = str(exc) + else: + notional = float(order_qty) * price + minimum = float(spec.get("min_notional") or 0) + if notional < minimum: + skip_reason = (f"размер заявки {notional:.4f} USDT меньше минимума " + f"контракта {minimum:g} USDT") + if skip_reason: + # A skipped signal is not an exchange failure: keep managing the + # symbol. For an add, consume this level (same rule as simulation + # and backtest) so the next add is measured from this price. + if action == "add" and shadow is not None: + shadow.last_add_price = price + self.events.put(("live_order_skipped", symbol, action, skip_reason, price)) + continue + added_qty = float(order_qty) + expected_avg = price if shadow is None else (shadow.entry_price * shadow.qty + price * added_qty) / (shadow.qty + added_qty) + target_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + tp = expected_avg * (1 + target_pct / 100) if settings["take_profit"] > 0 else 0.0 + sl = expected_avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + submitted_at_ms = int(time.time() * 1000) + order_id = client.place_market_buy(symbol, order_qty, tp, sl, spec["tick_size"]) + row = None + order_info = None + closed_row = None + no_fill_status = None + for attempt in range(20): + time.sleep(.5) + row = client.get_open_position(symbol) + if row and row.get("side") == "Buy": + break + if attempt % 4 == 3 and order_id: + order_info = client.get_order(symbol, order_id) + if order_info: + order_status = str(order_info.get("orderStatus") or "") + executed_qty = float(order_info.get("cumExecQty") or 0) + if order_status in {"Cancelled", "Rejected", "Deactivated"} and executed_qty <= 0: + no_fill_status = order_status + break + if order_status == "Filled": + closed_row = client.get_latest_closed_pnl(symbol, submitted_at_ms - 2000) + if (closed_row and int(closed_row.get("updatedTime") or 0) >= submitted_at_ms - 2000 + and float(closed_row.get("closedSize") or 0) > 0): + break + if no_fill_status: + self.events.put(("live_order_no_fill", symbol, action, no_fill_status)) + continue + if not row and not closed_row: + # Keep the execution worker alive and block further + # entries until the exchange can confirm the order. + # Never resend an order whose result is ambiguous. + self.events.put(("live_order_pending", symbol, order_id)) + while self.running and not row and not no_fill_status and not closed_row: + time.sleep(2.0) + try: + row = client.get_open_position(symbol) + if row: + break + order_info = client.get_order(symbol, order_id) if order_id else None + if order_info: + order_status = str(order_info.get("orderStatus") or "") + executed_qty = float(order_info.get("cumExecQty") or 0) + if order_status in {"Cancelled", "Rejected", "Deactivated"} and executed_qty <= 0: + no_fill_status = order_status + break + if order_status == "Filled" or executed_qty > 0: + closed_row = client.get_latest_closed_pnl(symbol, submitted_at_ms - 2000) + if (closed_row and int(closed_row.get("updatedTime") or 0) >= submitted_at_ms - 2000 + and float(closed_row.get("closedSize") or 0) > 0): + break + except Exception: + # Transient API failures do not justify + # duplicating an order with unknown status. + continue + if not self.running: + return + if no_fill_status: + self.events.put(("live_order_no_fill", symbol, action, no_fill_status)) + continue + if not row and closed_row: + # A fast TP/SL can close the position before the + # position endpoint ever observes it. Record the + # exchange's realized result and continue the loop. + closed_avg = float(closed_row.get("avgEntryPrice") or expected_avg) + closed_qty = float(closed_row.get("closedSize") or closed_row.get("qty") or added_qty) + if shadow is None: + recovered_id = self._allocate_live_id() + shadow = Position( + recovered_id, symbol, closed_avg, closed_qty, + closed_avg * closed_qty / settings["leverage"], + float(closed_row.get("openFee") or 0), timestamp, closed_avg, 0, + ) + else: + shadow.entry_price = closed_avg + shadow.qty = closed_qty + shadow.stake = closed_avg * closed_qty / settings["leverage"] + wallet = client.get_wallet() + self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True + self.events.put(("live_closed", shadow, closed_row, wallet, + "TP/стоп Bybit сработал сразу после входа")) + shadow = None + last_position_at = time.time() + last_wallet_at = last_position_at + continue + if not row or row.get("side") != "Buy": + raise BybitAPIError("Bybit подтвердил позицию в неизвестном направлении; автоматическое управление остановлено") + avg = float(row["avgPrice"]) + qty = float(row["size"]) + stake_total = avg * qty / settings["leverage"] + if shadow is None: + shadow = Position(self._allocate_live_id(), symbol, avg, qty, stake_total, + notional * fee_pct / 100, timestamp, price, 0) + else: + shadow.entry_price = avg + shadow.qty = qty + shadow.stake = stake_total + shadow.entry_fee += notional * fee_pct / 100 + shadow.last_add_price = price + shadow.add_count += 1 + # Persist the confirmed fill before any follow-up API call can fail. + self.events.put(("live_order_result", symbol, action, shadow, row, None)) + actual_tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + actual_tp = avg * (1 + actual_tp_pct / 100) if settings["take_profit"] > 0 else 0.0 + actual_sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + client.update_position_stops(symbol, actual_tp, actual_sl, spec["tick_size"]) + wallet = client.get_wallet() + self.events.put(("live_sync", symbol, shadow, row, wallet)) + last_position_at = time.time() + last_wallet_at = last_position_at + elif action == "close" and not shadow: + self.events.put(("live_order_skipped", symbol, action, "нет открытой позиции", price)) + elif action == "close" and shadow: + qty = client.floor_qty(shadow.qty, spec) + client.close_long_market(symbol, qty) + # Poll for the exchange to confirm instead of failing after one short check. + deadline = time.time() + MANUAL_CLOSE_CONFIRM_SECONDS + row = None + while self.running: + time.sleep(0.5) + try: + row = client.get_open_position(symbol) + except BybitAPIError: + row = shadow # unknown state: keep waiting until the deadline + if not row or time.time() >= deadline: + break + if row: + # Still open (or unknown): keep managing the position; the user can retry. + self.events.put(("live_order_skipped", symbol, action, + "Bybit не подтвердил закрытие за " + f"{MANUAL_CLOSE_CONFIRM_SECONDS} с; позиция остаётся под управлением, " + "проверьте её на бирже", price)) + last_position_at = 0.0 + continue + closed_row = client.get_latest_closed_pnl(symbol, int(shadow.opened_at * 1000)) + wallet = client.get_wallet() + self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True + self.events.put(("live_closed", shadow, closed_row, wallet, "Ручное закрытие")) + shadow = None + last_wallet_at = time.time() + elif action == "stops" and shadow: + avg = shadow.entry_price + target_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + tp = avg * (1 + target_pct / 100) if settings["take_profit"] > 0 else 0.0 + sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + client.update_position_stops(symbol, tp, sl, spec["tick_size"]) + self.events.put(("live_stops_updated", symbol)) + now = time.time() + if now - last_position_at >= 2.0: + row = client.get_open_position(symbol) + if row is None and shadow is not None: + closed_row = client.get_latest_closed_pnl(symbol, int(shadow.opened_at * 1000)) + wallet = client.get_wallet() + self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True + self.events.put(("live_closed", shadow, closed_row, wallet, "TP/стоп на Bybit")) + shadow = None + last_wallet_at = now + elif row is not None and shadow is None: + raise BybitAPIError("На аккаунте появилась позиция без записи бота. Автоматическая торговля остановлена") + elif row is not None: + shadow.entry_price = float(row.get("avgPrice") or shadow.entry_price) + shadow.qty = float(row.get("size") or shadow.qty) + shadow.stake = shadow.entry_price * shadow.qty / settings["leverage"] + wallet = client.get_wallet() if now - last_wallet_at >= 8.0 else None + self.events.put(("live_sync", symbol, shadow, row, wallet)) + if wallet: + last_wallet_at = now + last_position_at = now + except Exception as exc: + self.events.put(("live_worker_failed", symbol, str(exc))) + break + + def _position_limit_or_none(self) -> int | None: + try: + return self._simulation_position_limit() + except ValueError: + return None + + def _live_slots_in_use(self) -> int: + """Open live positions plus entries already sent and not yet reconciled.""" + self._capture_active_symbol() + return sum(1 for state in self.symbol_states.values() + if state.live_position is not None + or (state.live_order_busy and state.live_position is None)) + + def _on_live_tick(self, timestamp: float, price: float, crossed_entry_threshold: bool) -> None: + if self.live_order_busy or self.live_halted or self.live_transition_pending or not self.live_client: + return + settings = self.strategy_by_symbol.get(self.symbol) or self.applied_settings or self._safe_read_settings() + if self.live_position is None: + if (crossed_entry_threshold and self.symbol in self.enabled_symbols + and self.symbol not in self.rotation_pending_disable): + limit = self._position_limit_or_none() + if limit is not None and self._live_slots_in_use() >= limit: + self.status_var.set(f"Вход {self.symbol} пропущен: лимит одновременных позиций {limit} занят") + return + self.live_order_busy = True + commands = self.live_commands_by_symbol.get(self.symbol, self.live_commands) + commands.put(("open", timestamp, price)) + self.status_var.set(f"Сигнал входа · отправляю рыночный ордер {self.symbol}") + elif (self.symbol in self.enabled_symbols and self.symbol not in self.rotation_pending_disable + and strategy.can_add(self.live_position.add_count, settings["max_adds"], settings["add_step"]) + and price <= strategy.add_level(self.live_position.last_add_price, settings["add_step"])): + # Pairs waiting for retirement only manage their position (same rule as the backtest). + self.live_order_busy = True + commands = self.live_commands_by_symbol.get(self.symbol, self.live_commands) + commands.put(("add", timestamp, price)) + self.status_var.set(f"Уровень доливки · отправляю ордер {self.symbol}") + + def _ws_worker(self, symbols: list[str] | str) -> None: + if isinstance(symbols, str): + symbols = [symbols] + while self.running: + try: + symbols = list(self.ws_symbols) + if not symbols: + time.sleep(1) + continue + def on_open(ws) -> None: + # Subscribe to whatever is current at connect time; later changes are + # applied with subscribe/unsubscribe on this socket (no reconnect). + with self._ws_lock: + selected = sorted(set(self.ws_symbols)) + self._ws_send_topics(ws, "subscribe", selected) + self.ws_subscribed = set(selected) + + app = websocket.WebSocketApp( + WS_URL, + on_open=on_open, + on_message=self._on_message, + on_error=lambda _ws, err: self.events.put(("status", f"Ошибка потока: {err}")), + on_close=lambda _ws, code, _msg: self.events.put(("status", f"Соединение закрыто ({code}); переподключение…")), + ) + self.ws_app = app + app.run_forever(ping_interval=20, ping_timeout=10) + except Exception as exc: + self.events.put(("status", f"Ошибка подключения: {exc}")) + if self.running: + time.sleep(2) + + def _on_message(self, _ws, message: str) -> None: + try: + packet = json.loads(message) + if packet.get("op") == "subscribe": + self.events.put(("status", "Поток Bybit подключён" if packet.get("success") else f"Подписка: {packet}")) + topic = str(packet.get("topic") or "") + symbol = topic.removeprefix("publicTrade.").upper() + if symbol not in self.ws_symbols: + return + for trade in packet.get("data", []): + price = float(trade["p"]) + timestamp = int(trade["T"]) / 1000.0 + self.events.put(("trade", symbol, timestamp, price)) + except (ValueError, KeyError, TypeError, json.JSONDecodeError) as exc: + self.events.put(("status", f"Не удалось разобрать сообщение Bybit: {exc}")) + + def stop(self) -> None: + if self.historical_running: + self._backtest_cancel.set() + self.status_var.set("Останавливаю исторический прогон…") + self.stop_btn.configure(state="disabled") + return + if not self.running: + return + self.running = False + self._save_account_state() + for commands in [self.live_commands, *self.live_commands_by_symbol.values()]: + while True: + try: + commands.get_nowait() + except queue.Empty: + break + if self.ws_app: + try: + self.ws_app.close() + except Exception: + pass + if self.mode_var.get() == "Реальная торговля" and any(s.live_position for s in self.symbol_states.values()): + self.status_var.set("Мониторинг остановлен · биржевые TP/SL продолжают действовать на Bybit") + else: + self.status_var.set("Остановлен") + self.start_btn.configure(state="normal") + self.stop_btn.configure(state="disabled") + self._refresh_ui() + self._draw_chart() + + def _poll_events(self) -> None: + handled = 0 + while handled < MAX_EVENTS_PER_POLL: + try: + event = self.events.get_nowait() + except queue.Empty: + break + handled += 1 + if event[0] == "historical_progress": + _, symbol, count, total, *stage = event + if self.historical_running: + detail = f" · {stage[0]}" if stage and stage[0] else "" + if symbol == "Отбор валют": + self.status_var.set(f"Отбор валют по истории: {count:,} из {total:,} контрактов{detail}") + elif symbol == "Funding": + self.status_var.set(f"Загружаю историю funding: {count:,} из {total:,} валют") + else: + self.status_var.set(f"Загружаю {symbol}: {count:,} из ~{total:,} свечей{detail}") + elif event[0] == "historical_completed": + _, result, csv_path, json_path = event + self.historical_running = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal", text="Запустить прогон") + self.stop_btn.configure(state="disabled") + summary = result["summary"] + self.status_var.set( + (f"Прогон остановлен по лимиту капитала {summary['equity_stop_pct']:g}% · " + if summary.get("equity_stop_triggered") else "Прогон завершён · ") + + f"Net {summary['total_net_including_open_usdt']:+.2f} USDT · отчёт {csv_path}" + ) + self._show_historical_report(result, csv_path, json_path) + elif event[0] == "historical_cancelled": + self.historical_running = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal", text="Запустить прогон") + self.stop_btn.configure(state="disabled") + self.status_var.set("Исторический прогон отменён") + elif event[0] == "historical_failed": + self.historical_running = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal", text="Запустить прогон") + self.stop_btn.configure(state="disabled") + self.status_var.set(f"Исторический прогон не выполнен: {event[1]}") + messagebox.showerror("Исторический прогон не выполнен", event[1]) + elif event[0] == "startup_currency_filter_ready": + _, mode, threshold, snapshot, source = event + self.startup_currency_filter_busy = False + self.mode_combo.configure(state="readonly") + if mode != self.mode_var.get(): + self.start_btn.configure(state="normal") + self.status_var.set("Режим изменён во время проверки. Нажмите «Старт» ещё раз.") + continue + self._apply_startup_currency_filter(mode, threshold, snapshot, source) + elif event[0] == "startup_currency_filter_failed": + _, mode, error = event + self.startup_currency_filter_busy = False + self.startup_currency_filter_approved_for = None + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal") + self.status_var.set(f"Предстартовая проверка не выполнена: {error}") + messagebox.showerror( + "Проверка валют не выполнена", + "Не удалось получить актуальные данные Bybit за 24 часа. Сделки не запущены.\n\n" + error, + ) + elif event[0] == "status": + if self.running: + self.status_var.set(event[1]) + elif event[0] == "api_connected": + self.api_connecting = False + self.connect_btn.configure(state="normal") + self._show_api_snapshot(*event[1:]) + elif event[0] == "api_connect_failed": + self.api_connecting = False + self.connect_btn.configure(state="normal") + self.status_var.set(f"Не удалось подключиться к Bybit: {event[1]}") + messagebox.showerror("Подключение Bybit не выполнено", event[1]) + elif event[0] == "baseline": + if self.running and int(event[2]) == self.interval_minutes: + self._capture_active_symbol() + state = self._ensure_symbol(event[1]) + state.baseline_close = float(event[3]) + state.previous_entry_signal_pct = None + if event[1] == self.symbol: + self._activate_symbol_state(event[1]) + self.status_var.set(f"База сигнала {event[1]} загружена: закрытие {self.interval_minutes}-мин свечи") + self._refresh_rolling_change(reschedule=False) + elif event[0] == "trade" and self.running: + if len(event) >= 4: + self._on_trade(event[1], event[2], event[3]) + else: + self._on_trade(self.symbol, event[1], event[2]) + elif event[0] == "ticker_24h": + for symbol, (price, change, turnover) in event[1].items(): + self.ticker_prices[symbol] = price + self.ticker_24h[symbol] = change + self.ticker_turnover_24h[symbol] = turnover + self.ticker_data_source = event[2] if len(event) > 2 else "Bybit" + if len(event) > 3: + self.ticker_funding_pct.update(event[3]) + if self.auto_currency_status_var.get().startswith("Ошибка"): + self.auto_currency_status_var.set(f"Данные восстановлены · пар: {len(event[1])}") + self._refresh_currency_tiles() + for symbol in list(self.detail_windows): + self._draw_detail_chart(symbol) + self._maybe_auto_rotate_currencies() + elif event[0] == "mode_signal": + _, symbol, mode, bucket, tf_ms, signal, error = event + state = self._ensure_symbol(symbol) + state.mode_eval_busy = False + if mode != self.strategy_mode or not self.running: + continue + if error: + # Retry on the next poll unless the candle is long gone (e.g. a delisted pair). + if time.time() * 1000 - (bucket + tf_ms) > 60_000: + state.mode_signal_bucket = bucket + self.status_var.set(f"Сигнал {symbol}: {error}") + continue + state.mode_signal_bucket = bucket + self._capture_active_symbol() + if signal is not None and state.position is None: + signal["valid_until"] = (bucket + 2 * tf_ms) / 1000 + signal["mode"] = mode + state.mode_signal = signal + side = "SHORT" if signal["side"] == "short" else "LONG" + self.status_var.set( + f"Сигнал {side} {symbol} · закрытие {self._fmt_price(signal['close'])} · " + f"ATR {self._fmt_price(signal['atr'])} · вход на следующей сделке" + ) + self._request_redraw(symbol) + else: + state.mode_signal = None + elif event[0] == "ticker_24h_error": + self.auto_currency_status_var.set(f"Ошибка котировок: {event[1][:150]}") + elif event[0] == "chart_candles": + _, symbol, interval, candles, baseline = event + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + if interval == self.interval_minutes: + merged = {int(row[0]): row for row in candles} + merged.update({int(row[0]): row for row in state.candles}) + state.candles = deque([merged[key] for key in sorted(merged)[-300:]]) + state.baseline_close = baseline + if symbol == self.symbol: + self._activate_symbol_state(symbol) + self._draw_chart() + self._draw_detail_chart(symbol) + elif event[0] == "live_ready": + self._activate_live(*event[1:]) + elif event[0] == "live_ready_multi": + self._activate_live_multi(*event[1:]) + elif event[0] == "live_symbol_ready": + _, symbol, settings, spec, fee_pct, row, shadow = event + self.live_preparing_symbols.discard(symbol) + self._activate_live_symbol(symbol, settings, spec, fee_pct, row, shadow) + elif event[0] == "live_symbol_failed": + _, symbol, error = event + self.live_preparing_symbols.discard(symbol) + was_auto_added = symbol in self.auto_enabling_symbols + self.auto_enabling_symbols.discard(symbol) + if was_auto_added: + self.auto_symbol_retry_after[symbol] = time.monotonic() + AUTO_CURRENCY_SCAN_SECONDS + self.enabled_symbols.discard(symbol) + self._save_settings() + self._render_currency_tiles() + self.status_var.set(f"Не удалось включить {symbol}: {error}") + if not was_auto_added: + messagebox.showerror("Не удалось включить валюту", f"{symbol}: {error}") + elif event[0] == "live_preflight_failed": + self.live_preflight = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal") + self.status_var.set(f"Реальный режим не запущен: {event[1]}") + messagebox.showerror("Проверка Bybit не пройдена", event[1]) + elif event[0] == "live_restored_closed": + self._record_live_close(event[2], event[1], None, "Закрыта на Bybit во время перерыва") + elif event[0] == "live_order_result": + if len(event) == 6: + _kind, symbol, action, position, row, wallet = event + else: + _kind, action, position, row, wallet = event + symbol = position.symbol + selected = self.symbol + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_position = position + state.live_position_info = row + state.live_order_busy = False + state.entry_markers.append((time.time(), position.last_add_price, position.trade_id)) + if wallet: + self.live_wallet = wallet + self._replace_cached_position(row) + self._activate_symbol_state(selected) + self._save_account_state() + self.status_var.set(("Открыта реальная позиция" if action == "open" else "Доливка реальной позиции") + + f" #{position.trade_id} · {position.qty:.8g} {position.symbol}") + self._refresh_ui() + self._draw_chart() + elif event[0] == "live_order_no_fill": + _kind, symbol, action, order_status = event + self._capture_active_symbol() + self._ensure_symbol(symbol).live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set( + f"Bybit не исполнил ордер ({order_status or 'без исполнения'}); бот продолжает работу" + ) + self._refresh_ui() + elif event[0] == "live_order_pending": + _kind, symbol, order_id = event + self.status_var.set( + f"Жду подтверждения ордера Bybit {symbol} {order_id or ''}; повторный ордер заблокирован до сверки" + ) + elif event[0] == "live_sync": + if len(event) == 5: + _kind, symbol, position, row, wallet = event + else: + _kind, position, row, wallet = event + symbol = position.symbol if position else str((row or {}).get("symbol") or self.symbol) + selected = self.symbol + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_position = position + state.live_position_info = row + self._replace_cached_position(row, position.symbol if position else None) + if wallet: + self.live_wallet = wallet + self._activate_symbol_state(selected) + self._save_account_state() + self._refresh_ui() + self._draw_chart() + elif event[0] == "live_closed": + _kind, position, row, wallet, reason = event + self._record_live_close(position, row, wallet, reason) + elif event[0] == "live_worker_failed": + symbol, error = event[1], event[2] + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_halted = True + state.live_transition_pending = False + state.live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set(f"Реальная торговля {symbol} приостановлена: {error}") + messagebox.showerror("Реальная торговля приостановлена", f"{symbol}: {error}\nПроверьте позицию и TP/SL на Bybit.") + self._refresh_ui() + elif event[0] == "live_stops_updated": + self._capture_active_symbol() + self._ensure_symbol(event[1]).live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set(f"Биржевые TP/SL обновлены · {event[1]}") + self._refresh_ui() + elif event[0] == "live_settings_updated": + self._capture_active_symbol() + self._ensure_symbol(event[1]).live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set("Настройки реальной стратегии применены") + self._refresh_ui() + elif event[0] == "live_order_skipped": + _kind, symbol, action, reason, price = event + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_order_busy = False + if action == "add" and state.live_position is not None: + state.live_position.last_add_price = min(state.live_position.last_add_price, price) + self._activate_symbol_state(self.symbol) + labels = {"open": "Вход", "add": "Доливка", "close": "Закрытие"} + self.status_var.set(f"{labels.get(action, action)} {symbol} пропущен(а): {reason}") + self._request_redraw(symbol, main=True) + elif event[0] == "live_worker_exited": + _kind, symbol, command_queue = event + if self.live_commands_by_symbol.get(symbol) is command_queue: + self.live_commands_by_symbol.pop(symbol, None) + self.live_workers.pop(symbol, None) + if self.running and symbol in self.enabled_symbols: + state = self._ensure_symbol(symbol) + if not state.live_halted and self.mode_var.get() == "Реальная торговля" \ + and symbol not in self.live_preparing_symbols: + # The worker ended although the pair is enabled (e.g. it was + # re-enabled right as the old worker retired): start a new one. + self._begin_live_additional_symbol(symbol) + # Drain bursts without starving Tk: continue immediately if events remain. + self.root.after(1 if handled >= MAX_EVENTS_PER_POLL else 100, self._poll_events) + + # ----- strategy modes A/B in the simulation ------------------------------------------ + + def _poll_mode_signals(self) -> None: + """Evaluate mode A/B signals once per closed signal candle for every enabled pair.""" + try: + if (self.running and self.mode_var.get() == "Симуляция" + and self.strategy_mode != strategy.STRATEGY_CLASSIC): + params = self._strategy_mode_params() + tf_ms = int(params["timeframe_min"]) * 60_000 + now_ms = int(time.time() * 1000) + last_closed = (now_ms // tf_ms) * tf_ms - tf_ms + # Give Bybit a few seconds to publish the closed candle. + if now_ms - (last_closed + tf_ms) >= 3000: + self._capture_active_symbol() + for symbol in sorted(self.enabled_symbols): + if symbol in self.rotation_pending_disable: + continue + state = self._ensure_symbol(symbol) + if state.mode_eval_busy or state.mode_signal_bucket == last_closed: + continue + if state.position is not None: + state.mode_signal = None + state.mode_signal_bucket = last_closed + continue + state.mode_eval_busy = True + self._signal_pool.submit(self._mode_signal_worker, symbol, self.strategy_mode, + dict(params), last_closed) + except ValueError as exc: + self.status_var.set(f"Настройки режима стратегии: {exc}") + finally: + if self.root.winfo_exists(): + self.root.after(5000, self._poll_mode_signals) + + @staticmethod + def _fetch_recent_klines(symbol: str, interval: int, limit: int) -> list[list[float]]: + """Closed candles [start_ms, o, h, l, c, turnover], oldest first.""" + query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, "interval": str(interval), + "limit": str(max(2, min(1000, limit)))}) + request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + with urllib.request.urlopen(request, timeout=10) as response: + payload = json.loads(response.read().decode("utf-8")) + if payload.get("retCode") != 0: + raise RuntimeError(f"Bybit {payload.get('retCode')}: {payload.get('retMsg', 'ошибка свечей')}") + now_ms = int(time.time() * 1000) + interval_ms = interval * 60_000 + rows = [[int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]), + float(row[6]) if len(row) > 6 and row[6] not in (None, "") else 0.0] + for row in payload.get("result", {}).get("list", []) + if int(row[0]) + interval_ms <= now_ms] + rows.sort(key=lambda row: row[0]) + return rows + + def _btc_regime(self, ema_period: int) -> bool | None: + """BTC closed-hour close above its EMA, refreshed once per hour.""" + hour = int(time.time() // 3600) + with self._btc_regime_lock: + cached_hour, cached_period, value = self._btc_regime_cache + if cached_hour == hour and cached_period == ema_period and value is not None: + return value + rows = self._fetch_recent_klines("BTCUSDT", 60, ema_period * 3 + 5) + value = strategy.btc_regime_ok([row[4] for row in rows], ema_period) + self._btc_regime_cache = (hour, ema_period, value) + return value + + def _mode_signal_worker(self, symbol: str, mode: str, params: dict[str, float], bucket: int) -> None: + tf = int(params["timeframe_min"]) + try: + rows = self._fetch_recent_klines(symbol, tf, strategy.required_bars(mode, params) + 5) + rows = [row for row in rows if row[0] <= bucket] + if not rows or rows[-1][0] != bucket: + raise RuntimeError("Bybit ещё не опубликовал закрытую свечу") + btc_ok: bool | None = True + if mode == strategy.STRATEGY_BREAKOUT and params["btc_filter"] >= 1: + btc_ok = self._btc_regime(int(params["btc_ema"])) + signal = strategy.evaluate_signal(mode, rows, params, self.ticker_funding_pct.get(symbol), btc_ok) + self.events.put(("mode_signal", symbol, mode, bucket, tf * 60_000, signal, None)) + except Exception as exc: + self.events.put(("mode_signal", symbol, mode, bucket, tf * 60_000, None, str(exc)[:160])) + + def _maybe_enter_mode_position(self, price: float, timestamp: float) -> None: + state = self.symbol_states.get(self.symbol) + signal = state.mode_signal if state else None + if not signal: + return + if timestamp > signal["valid_until"] or signal.get("mode") != self.strategy_mode: + state.mode_signal = None + return + if self.symbol not in self.enabled_symbols or self.symbol in self.rotation_pending_disable: + return + try: + params = self._strategy_mode_params(signal["mode"]) + position_limit = self._simulation_position_limit() + except ValueError as exc: + self.status_var.set(str(exc)) + return + active_positions = sum(item.position is not None for item in self.symbol_states.values()) + stake = self.initial_balance * params["stake_pct"] / 100 + if active_positions >= position_limit or stake > max(0.0, self._sim_free_margin()): + if not signal.get("skip_noted"): + signal["skip_noted"] = True + self.status_var.set( + f"Сигнал {self.symbol} ждёт: " + ("лимит одновременных сделок занят" + if active_positions >= position_limit + else "свободного баланса меньше ставки") + ) + return + plan = strategy.entry_plan(signal, price, params) + state.mode_signal = None + if plan is None: + self.status_var.set(f"Сигнал {self.symbol} отменён: цена ушла за уровень сигнала или стоп слишком далеко") + return + notional = stake * params["leverage"] + qty = notional / price + entry_fee = notional * TAKER_FEE_PCT / 100 + self.balance -= entry_fee + self.total_fees += entry_fee + self.position = Position( + self.next_id, self.symbol, price, qty, stake, entry_fee, timestamp, price, + side=plan["side"], mode=signal["mode"], leverage=params["leverage"], + stop_price=plan["stop"], initial_stop=plan["stop"], atr=plan["atr"], extreme=price, + partial_target=plan["partial_target"] or 0.0, final_target=plan["final_target"] or 0.0, + opened_stake=stake, + ) + state.position = self.position + self.entry_markers.append((timestamp, price, self.position.trade_id)) + self.next_id += 1 + self._save_account_state() + self.status_var.set( + f"Открыта {plan['side'].upper()} #{self.position.trade_id} · {self.symbol} · {price:g} · " + f"стоп {self._fmt_price(plan['stop'])}" + ) + + def _partial_close_position(self, price: float, params: dict[str, float]) -> None: + pos = self.position + if pos is None: + return + fraction = min(1.0, params["partial_pct"] / 100) + qty = pos.qty * fraction + gross = strategy.unrealized_pnl(pos.side, pos.entry_price, price, qty) + exit_fee = price * qty * TAKER_FEE_PCT / 100 + self.balance += gross - exit_fee + self.total_fees += exit_fee + pos.realized_gross += gross + pos.realized_fees += exit_fee + pos.qty -= qty + pos.stake *= 1 - fraction + pos.partial_done = True + if params["breakeven"] >= 1: + pos.stop_price = strategy.tighten_stop(pos.side, pos.stop_price, + strategy.breakeven_price(pos.side, pos.entry_price, TAKER_FEE_PCT)) + self._save_account_state() + self.status_var.set( + f"Частичная фиксация {params['partial_pct']:g}% #{pos.trade_id} · {pos.symbol} · {price:g} · " + f"gross {gross:+.4f} · стоп {self._fmt_price(pos.stop_price)}" + ) + + def _manage_mode_position(self, price: float, timestamp: float) -> None: + pos = self.position + if pos is None: + return + try: + params = self._strategy_mode_params(pos.mode) + except ValueError: + params = strategy.parse_mode_params(pos.mode, {}) + side = pos.side + liquidation = strategy.liquidation_price(pos.entry_price, pos.leverage, side=side) + if liquidation is not None and strategy.stop_hit(side, price, liquidation): + self._close_position(price, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True) + return + if strategy.stop_hit(side, price, pos.stop_price): + moved = abs(pos.stop_price - pos.initial_stop) > 1e-12 + self._close_position(price, "Стоп (трейлинг/безубыток)" if moved else "Стоп") + return + if params["max_hold_hours"] > 0 and timestamp - pos.opened_at >= params["max_hold_hours"] * 3600: + self._close_position(price, f"Время удержания {params['max_hold_hours']:g} ч") + return + if (not pos.partial_done and pos.partial_target > 0 + and strategy.target_hit(side, price, pos.partial_target)): + if params["partial_pct"] >= 100: + self._close_position(pos.partial_target, f"TP на {params['partial_r']:g}R") + return + self._partial_close_position(pos.partial_target, params) + if pos.final_target > 0 and strategy.target_hit(side, price, pos.final_target): + self._close_position(pos.final_target, f"TP на {params['take_profit_r']:g}R") + return + pos.extreme = max(pos.extreme, price) if side == "long" else min(pos.extreme, price) + if strategy.trailing_active(pos.partial_done, params): + pos.stop_price = strategy.trailing_stop(side, pos.stop_price, pos.extreme, pos.atr, params["trail_atr"]) + + def _on_trade(self, symbol: str, timestamp: float, price: float) -> None: + display_symbol = self.symbol + balance_before = self.balance + self._display_symbol_during_tick = display_symbol + self._capture_active_symbol() + self._activate_symbol_state(symbol) + try: + self._process_active_trade(timestamp, price) + finally: + self._capture_active_symbol() + self._activate_symbol_state(display_symbol) + self._display_symbol_during_tick = None + self._request_redraw(symbol, main=symbol == display_symbol or self.balance != balance_before) + + def _request_redraw(self, symbol: str | None = None, main: bool = False) -> None: + """Coalesce UI updates: at most one redraw every UI_REDRAW_INTERVAL_MS. + + Redrawing the whole chart on every public trade starves the Tk thread when many + pairs are subscribed, so prices would be processed late. + """ + if symbol: + self._dirty_symbols.add(symbol) + self._dirty_main = self._dirty_main or main + if self._redraw_job is None and self.root.winfo_exists(): + self._redraw_job = self.root.after(UI_REDRAW_INTERVAL_MS, self._flush_redraw) + + def _flush_redraw(self) -> None: + self._redraw_job = None + symbols, self._dirty_symbols = self._dirty_symbols, set() + main, self._dirty_main = self._dirty_main, False + if symbols: + self._refresh_currency_tiles(symbols) + if main or self.symbol in symbols: + self._refresh_price_label() + self._refresh_ui() + self._draw_chart() + for symbol in symbols: + if symbol in self.detail_windows: + self._draw_detail_chart(symbol) + + def _process_active_trade(self, timestamp: float, price: float) -> None: + self.last_ws_message = time.time() + self.last_price = price + self._live_minute_prices.append((timestamp, price)) + while self._live_minute_prices and self._live_minute_prices[0][0] < timestamp - 2 * WINDOW_MS / 1000: + self._live_minute_prices.popleft() + self.prices.append((timestamp, price)) + cutoff = timestamp - WINDOW_MS / 1000 + while self.prices and self.prices[0][0] < cutoff - 2: + self.prices.popleft() + candle_start = int(timestamp // (self.interval_minutes * 60)) * (self.interval_minutes * 60) + new_candle = not self.candles or self.candles[-1][0] != candle_start + if new_candle: + self._previous_entry_signal_pct = None + self._update_candle(timestamp, price) + keep_seconds = max(CHART_SECONDS, self.interval_minutes * 60 * 30) + while self.candles and self.candles[0][0] < timestamp - keep_seconds: + expired = self.candles.popleft() + while self.entry_markers and self.entry_markers[0][0] < expired[0]: + self.entry_markers.popleft() + + settings = self.strategy_by_symbol.get(self.symbol) or self.applied_settings or self._safe_read_settings() + + signal_pct =((price / self.baseline_close) - 1) * 100 if self.baseline_close and self.baseline_close > 0 else None + crossed_entry_threshold = ( + signal_pct is not None + and signal_pct >= settings["trigger"] + and (self._previous_entry_signal_pct is None or self._previous_entry_signal_pct < settings["trigger"]) + ) + if self.mode_var.get() == "Реальная торговля": + self._on_live_tick(timestamp, price, crossed_entry_threshold) + self._previous_entry_signal_pct = signal_pct + return + self._previous_entry_signal_pct = signal_pct + if self.position and self.position.mode != strategy.STRATEGY_CLASSIC: + self._manage_mode_position(price, timestamp) + return + if self.position is None and self.strategy_mode != strategy.STRATEGY_CLASSIC: + self._maybe_enter_mode_position(price, timestamp) + return + if self.position: + stop_price = strategy.stop_loss_price(self.position.entry_price, settings["stop_loss"]) + effective_tp_pct = strategy.effective_take_profit_pct(settings["take_profit"], settings["fee"]) + take_profit_price = strategy.take_profit_price(self.position.entry_price, settings["take_profit"], settings["fee"]) + liquidation_price = strategy.liquidation_price(self.position.entry_price, settings["leverage"]) + add_price = strategy.add_level(self.position.last_add_price, settings["add_step"]) + if liquidation_price is not None and price <= liquidation_price: + self._close_position(price, f"Ликвидация (плечо {settings['leverage']:g}x)", liquidation=True) + elif stop_price is not None and price <= stop_price: + stop_pct = (self.position.entry_price - price) / self.position.entry_price * 100 + self._close_position(price, f"Стоп от средней цены {stop_pct:.2f}%") + elif take_profit_price is not None and price >= take_profit_price: + # Exchange TP is a trigger at the level; do not credit the overshoot of a jump. + self._close_position(take_profit_price, f"TP от средней цены +{effective_tp_pct:.3f}%") + elif (self.symbol in self.enabled_symbols and self.symbol not in self.rotation_pending_disable + and strategy.can_add(self.position.add_count, settings["max_adds"], settings["add_step"]) + and add_price is not None and price <= add_price): + self._add_position(price, timestamp, settings) + elif (crossed_entry_threshold and self.symbol in self.enabled_symbols + and self.symbol not in self.rotation_pending_disable): + self._open_position(price, timestamp, settings) + + def _refresh_rolling_change(self, reschedule: bool = True, now: float | None = None) -> None: + if now is None: + now = time.time() + self._last_signal_refresh_at = now + current = self.last_price + self.last_signal_pct = ((current / self.baseline_close) - 1) * 100 if current and self.baseline_close and self.baseline_close > 0 else None + self.last_signal_ready = self.last_signal_pct is not None + if hasattr(self, "market_price_var"): + self._refresh_price_label() + if hasattr(self, "root") and self.root.winfo_exists(): + self._refresh_ui() + if reschedule: + self.root.after(5000, self._refresh_rolling_change) + + def _refresh_price_label(self) -> None: + current = self.last_price + if not current: + self.market_price_var.set(f"{self.symbol}: ожидаю цену Bybit…") + elif self.last_signal_ready and self.last_signal_pct is not None: + self.market_price_var.set( + f"{self.symbol}: {self._fmt_price(current)} USDT " + f"Изменение от закрытия прошлой {self.interval_minutes}-мин свечи: {self.last_signal_pct:+.2f}%" + ) + else: + self.market_price_var.set( + f"{self.symbol}: {self._fmt_price(current)} USDT " + f"Изменение от закрытия прошлой {self.interval_minutes}-мин свечи: ждём базу…" + ) + + def _sim_free_margin(self) -> float: + """Money available for new simulated entries/adds. + + Like Bybit's available balance: cash minus margin locked in open positions, plus + their current unrealized P&L after the estimated closing fee. Losing positions + therefore reduce what can still be invested; the same figure is shown on screen. + """ + self._capture_active_symbol() + free = self.balance + for state in self.symbol_states.values(): + pos = state.position + if pos is None: + continue + settings = self.strategy_by_symbol.get(pos.symbol) or self.applied_settings or {} + fee_pct = settings.get("fee", TAKER_FEE_PCT) if pos.mode == strategy.STRATEGY_CLASSIC else TAKER_FEE_PCT + mark = state.last_price or pos.entry_price + free += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) + - mark * pos.qty * fee_pct / 100 - pos.stake) + return free + + def _open_position(self, price: float, timestamp: float, settings: dict[str, float]) -> None: + try: + position_limit = self._simulation_position_limit() + except ValueError as exc: + self.status_var.set(str(exc)) + return + active_positions = sum(state.position is not None for state in self.symbol_states.values()) + if active_positions >= position_limit: + self.status_var.set( + f"Вход пропущен: лимит одновременных сделок {position_limit} уже занят" + ) + return + if settings["stake"] > max(0.0, self._sim_free_margin()): + self.status_var.set("Вход пропущен: свободного баланса меньше ставки") + return + notional = settings["stake"] * settings["leverage"] + qty = notional / price + entry_fee = notional * settings["fee"] / 100 + self.balance -= entry_fee + self.total_fees += entry_fee + self.position = Position(self.next_id, self.symbol, price, qty, settings["stake"], entry_fee, timestamp, price) + self.entry_markers.append((timestamp, price, self.position.trade_id)) + self.next_id += 1 + self._save_account_state() + self.status_var.set(f"Открыта LONG #{self.position.trade_id} · {self.symbol} · {price:g}") + + def _add_position(self, price: float, timestamp: float, settings: dict[str, float]) -> None: + pos = self.position + if pos is None: + return + free_margin = self._sim_free_margin() + if free_margin < settings["stake"]: + # Same rule as live and backtest: the level is consumed, the next add is measured from here. + pos.last_add_price = price + self.status_var.set("Доливка пропущена: недостаточно свободного капитала") + return + notional = settings["stake"] * settings["leverage"] + added_qty = notional / price + added_fee = notional * settings["fee"] / 100 + total_qty = pos.qty + added_qty + pos.entry_price = (pos.entry_price * pos.qty + price * added_qty) / total_qty + pos.qty = total_qty + pos.stake += settings["stake"] + pos.entry_fee += added_fee + pos.last_add_price = price + pos.add_count += 1 + self.balance -= added_fee + self.total_fees += added_fee + self.entry_markers.append((timestamp, price, pos.trade_id)) + self._save_account_state() + self.status_var.set(f"Доливка #{pos.add_count} в сделку #{pos.trade_id} · {price:g} · средняя {pos.entry_price:g}") + + def _mark_position(self, price: float, settings: dict[str, float]) -> tuple[float, float, float]: + assert self.position is not None + p = self.position + gross = strategy.unrealized_pnl(p.side, p.entry_price, price, p.qty) + exit_fee = price * p.qty * settings["fee"] / 100 + fees = p.entry_fee + exit_fee + return gross - fees, fees, gross + + def _close_position(self, price: float, reason: str, liquidation: bool = False) -> None: + if not self.position: + return + pos = self.position + if pos.mode != strategy.STRATEGY_CLASSIC: + settings = {"fee": TAKER_FEE_PCT} # modes A/B never read the classic currency settings + else: + settings = (self.strategy_by_symbol.get(pos.symbol) or self.applied_settings + or self._safe_read_settings()) + if liquidation: + # Isolated-margin liquidation forfeits the position margin (as in the backtest). + gross, exit_fee = -pos.stake, 0.0 + else: + _net, fees, gross = self._mark_position(price, settings) + exit_fee = max(0, fees - pos.entry_fee) + self.balance += gross - exit_fee + self.total_fees += exit_fee + # A partial take-profit (modes A/B) was already credited; report the whole trade. + gross += pos.realized_gross + fees = pos.entry_fee + pos.realized_fees + exit_fee + net = gross - fees + roi = net / (pos.opened_stake or pos.stake) * 100 + if pos.mode != strategy.STRATEGY_CLASSIC: + reason = f"{pos.side.upper()} · {reason}" + closed = ClosedTrade(pos.trade_id, pos.symbol, pos.entry_price, price, pos.qty, gross, fees, net, roi, pos.opened_at, time.time(), reason) + self.trades.append(closed) + self.table.insert("", 0, values=(closed.trade_id, closed.symbol, self._fmt_price(closed.entry_price), self._fmt_price(closed.exit_price), f"{closed.roi_pct:+.2f}", f"{closed.gross_pnl:+.4f}", f"{closed.fees:.4f}", f"{closed.net_pnl:+.4f}", closed.reason), tags=("profit" if closed.net_pnl > 0 else "loss" if closed.net_pnl < 0 else "",)) + self.position = None + state = self._ensure_symbol(pos.symbol) + state.position = None + self._save_account_state() + self.status_var.set(f"Закрыта сделка #{closed.trade_id}: {closed.reason} · net {closed.net_pnl:+.4f} USDT") + self._finish_auto_retirement(pos.symbol) + + def _manual_close_position(self) -> None: + if self.mode_var.get() == "Реальная торговля": + if not self.live_position: + self.status_var.set("Нет открытой реальной позиции") + return + if not self.running or self.live_order_busy or self.live_halted: + self.status_var.set("Для ручного закрытия запустите реальный бот; дождитесь завершения текущего ордера") + return + if not messagebox.askyesno("Закрыть позицию Bybit", f"Отправить рыночный ордер на закрытие LONG {self.live_position.symbol}?"): + return + self.live_order_busy = True + commands = self.live_commands_by_symbol.get(self.live_position.symbol, self.live_commands) + commands.put(("close", time.time(), self.last_price or self.live_position.entry_price)) + self.status_var.set("Отправляю reduce-only ордер на закрытие…") + self._refresh_ui() + return + if not self.position: + self.status_var.set("Нет открытой сделки для закрытия") + return + if not self.running or not self.last_price or self.last_price <= 0: + self.status_var.set("Для ручного закрытия запустите поток цен Bybit") + return + self._close_position(self.last_price, "Закрыта вручную") + self._refresh_ui() + self._draw_chart() + + def _record_live_close(self, position: Position, row: dict | None, + wallet: dict[str, float] | None, reason: str) -> None: + if row: + state = self._ensure_symbol(position.symbol) + exit_price = float(row.get("avgExitPrice") or row.get("avgEntryPrice") or state.last_price or position.entry_price) + entry_price = float(row.get("avgEntryPrice") or position.entry_price) + qty = float(row.get("closedSize") or row.get("qty") or position.qty) + # Bybit's closedPnl is the authoritative net result. Gross is derived from the + # fill prices so it never depends on how funding is reported in the record; + # any difference between gross − fees and net is funding/other charges. + net = float(row.get("closedPnl") or 0.0) + fees = float(row.get("openFee") or 0.0) + float(row.get("closeFee") or 0.0) + gross = (exit_price - entry_price) * qty + close_time = float(row.get("updatedTime") or int(time.time() * 1000)) / 1000 + else: + exit_price = self._ensure_symbol(position.symbol).last_price or position.entry_price + qty = position.qty + fees = position.entry_fee + exit_price * qty * self.live_fee_pct / 100 + gross = (exit_price - position.entry_price) * qty + net = gross - fees + close_time = time.time() + reason += " · PnL не подтверждён API" + roi = net / position.stake * 100 if position.stake else 0.0 + closed = ClosedTrade(position.trade_id, position.symbol, position.entry_price, exit_price, + qty, gross, fees, net, roi, position.opened_at, close_time, reason) + # Replayed close events can occur when an app closes while Bybit already closed the position. + if not any(existing.trade_id == closed.trade_id for existing in self.live_trades): + self.live_trades.append(closed) + tag = "profit" if net > 0 else "loss" if net < 0 else "" + self.table.insert("", 0, values=(f"R{closed.trade_id}", closed.symbol, + self._fmt_price(closed.entry_price), self._fmt_price(closed.exit_price), + f"{closed.roi_pct:+.2f}", f"{closed.gross_pnl:+.4f}", f"{closed.fees:.4f}", + f"{closed.net_pnl:+.4f}", f"LIVE · {closed.reason}"), tags=(tag,)) + state = self._ensure_symbol(position.symbol) + if state.live_position and state.live_position.trade_id == position.trade_id: + state.live_position = None + state.live_position_info = None + state.live_order_busy = False + state.live_transition_pending = False + if self.live_position and self.live_position.trade_id == position.trade_id: + self.live_position = None + self._replace_cached_position(None, position.symbol) + self._finish_auto_retirement(position.symbol) + if self.symbol == position.symbol: + self.live_order_busy = False + self.live_transition_pending = False + if wallet: + self.live_wallet = wallet + self._save_account_state() + self.status_var.set(f"Реальная сделка #{closed.trade_id} закрыта · net {closed.net_pnl:+.4f} USDT · {reason}") + self._refresh_ui() + self._draw_chart() + + @staticmethod + def _fmt_price(price: float) -> str: + return f"{price:.10g}" + + @staticmethod + def _fee_cover_pct(fee_pct: float) -> float: + """Minimum gross price rise that offsets taker fees on entry and exit fills.""" + return strategy.fee_cover_pct(fee_pct) + + def _safe_read_settings(self) -> dict[str, float]: + try: + return self._read_settings() + except ValueError: + return {"initial": self.initial_balance, "stake_pct": 2, "deposit_basis": self.initial_balance, + "stake": 0, "leverage": 1, "trigger": 5, "add_step": .5, "max_adds": 2, + "stop_loss": 1, "take_profit": 1, "fee": TAKER_FEE_PCT, + "interval": float(CANDLE_INTERVAL_MINUTES)} + + def _refresh_settings_summary(self) -> None: + """Show the active strategy thresholds in the main window.""" + settings = self.applied_settings or self._safe_read_settings() + stop_loss = "выключен" if settings["stop_loss"] == 0 else f"−{settings['stop_loss']:g}%" + take_profit = ( + "выключен" + if settings["take_profit"] == 0 + else f"+{settings['take_profit']:g}% (уровень с учётом комиссий не ниже {self._fee_cover_pct(settings['fee']):.3f}%)" + ) + add_text = (f"доливка через −{settings['add_step']:g}% от последнего входа, максимум {settings['max_adds']}" + if settings["add_step"] > 0 and settings["max_adds"] > 0 else "доливки выключены") + self.strategy_summary_var.set( + f"Параметры: 1-мин свеча · первый вход при росте +{settings['trigger']:g}% от предыдущего закрытия · " + f"{add_text} · ставка {settings.get('stake_pct', 0):g}% от стартового депозита " + f"({settings.get('deposit_basis', settings['initial']):g} USDT = {settings['stake']:g} USDT на вход) × плечо {settings['leverage']:g} · " + f"TP {take_profit} / стоп {stop_loss} от средней цены · " + f"комиссия taker {settings['fee']:g}% за сторону" + ) + + def _refresh_ui(self) -> None: + current = self.last_price or 0.0 + self._refresh_price_label() + settings = self.applied_settings or self._safe_read_settings() + if self.mode_var.get() == HISTORICAL_MODE: + self.main_metrics_frame.pack_forget() + elif not self.main_metrics_frame.winfo_manager(): + self.main_metrics_frame.pack(fill="x", pady=(6, 0), before=self.currencies_frame) + if self.mode_var.get() == "Реальная торговля": + wallet = self.live_wallet or {"wallet": 0.0, "equity": 0.0, "available": 0.0, "unrealized_pnl": 0.0} + if self.live_client: + network = "Testnet" if self.live_client.testnet else "MAINNET" + baseline = self._current_live_deposit_basis() or wallet["wallet"] + realized = sum(float(row.get("closedPnl") or 0) for row in self.live_closed_pnl) + self.live_account_var.set( + f"{network} · стартовый депозит {baseline:,.2f} · кошелёк {wallet['wallet']:,.2f} · " + f"equity {wallet['equity']:,.2f} · нереализованный P&L {wallet.get('unrealized_pnl', 0):+,.2f} · " + f"реализованный P&L (последние {len(self.live_closed_pnl)}) {realized:+,.2f} USDT · " + f"ордеров {len(self.live_orders)} · позиций {len(self.live_positions)}" + ) + position = self.live_position + unrealized = float((self.live_position_info or {}).get("unrealisedPnl") or 0.0) + if position: + mark_price = current or float((self.live_position_info or {}).get("markPrice") or position.entry_price) + unrealized = float((self.live_position_info or {}).get("unrealisedPnl") or ((mark_price - position.entry_price) * position.qty)) + margin = position.stake + pnl_pct = unrealized / margin * 100 if margin else 0.0 + self.position_var.set( + f"LIVE LONG #{position.trade_id} · {position.symbol} · средняя {self._fmt_price(position.entry_price)} · " + f"входов {position.add_count + 1} · текущая {self._fmt_price(mark_price)} · размер {position.qty:.8g} · " + f"unrealized PnL {unrealized:+.4f} USDT ({pnl_pct:+.2f}%)" + ) + else: + selected = next((row for row in self.live_positions if row.get("symbol") == self.symbol_var.get().strip().upper()), None) + if selected: + self.position_var.set( + f"Bybit · {selected.get('symbol')} {selected.get('side')} · объём {selected.get('size')} · " + f"средняя {selected.get('avgPrice')} · P&L {float(selected.get('unrealisedPnl') or 0):+.4f} USDT · " + f"TP {selected.get('takeProfit') or '—'} · SL {selected.get('stopLoss') or '—'} · " + "нажмите «Старт» для сопровождения ботом" + ) + elif self.live_positions: + self.position_var.set(f"На аккаунте открыто позиций: {len(self.live_positions)} · подробности во вкладке «Открытые позиции»") + else: + self.position_var.set("LIVE · открытых позиций нет; ждём сигнал") + self.close_trade_btn.configure(state="normal" if self.running and position and not self.live_order_busy else "disabled") + for key, title in (("balance", "Bybit кошелёк"), ("equity", "Equity"), + ("pnl", "Нереализованный PnL"), ("free", "Доступно"), + ("fees", "Комиссии сделки · оценка")): + self.metric_title_vars[key].set(title) + self.metric_boxes[key].configure(text=title) + values = { + "balance": f"{wallet['wallet']:,.2f} USDT", + "equity": f"{wallet['equity']:,.2f} USDT", + "free": f"{wallet['available']:,.2f} USDT", + "pnl": f"{float(wallet.get('unrealized_pnl', unrealized)):+,.2f} USDT", + "fees": (f"{position.entry_fee + position.entry_price * position.qty * self.live_fee_pct / 100:,.4f} USDT" + if position else "см. историю Bybit"), + } + for key, value in values.items(): + self.metric_vars[key].set(value) + live_open = sum(1 for state in self.symbol_states.values() if state.live_position is not None) + self._set_main_metrics( + wallet["wallet"], float(wallet.get("unrealized_pnl", unrealized)), wallet["equity"], + "Баланс Bybit", "Нереализованный P&L", "Общий баланс с P&L", + free=float(wallet.get("available") or 0.0), open_positions=live_open, + free_title="Свободно на Bybit для новых сделок", + ) + return + for key, title in (("balance", "Баланс"), ("equity", "Бюджет всего"), ("pnl", "Без стартового"), + ("free", "Свободно"), ("fees", "Комиссии")): + self.metric_title_vars[key].set(title) + self.metric_boxes[key].configure(text=title) + open_positions = [(symbol, state.position, state.last_price or state.position.entry_price) + for symbol, state in self.symbol_states.items() if state.position] + unrealized_gross = 0.0 + estimated_exit_fees = 0.0 + used_margin = 0.0 + position_lines = [] + for symbol, pos, mark in open_positions: + assert pos is not None + gross = strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) + exit_fee = mark * pos.qty * settings["fee"] / 100 + unrealized_gross += gross + estimated_exit_fees += exit_fee + used_margin += pos.stake + net = gross - exit_fee - pos.entry_fee + pos.realized_gross - pos.realized_fees + side = f"{pos.side.upper()} " if pos.mode != strategy.STRATEGY_CLASSIC else "" + position_lines.append( + f"{symbol}: {side}#{pos.trade_id} · {self._fmt_price(pos.entry_price)} → {self._fmt_price(mark)} · " + + (f"стоп {self._fmt_price(pos.stop_price)}" if pos.mode != strategy.STRATEGY_CLASSIC + else f"{pos.add_count + 1} вход(ов)") + + f" · net {net:+.3f} USDT" + ) + equity = self.balance + unrealized_gross - estimated_exit_fees + free = max(0.0, self._sim_free_margin()) + pnl = equity - self.initial_balance + if position_lines: + self.position_var.set("Открытые позиции · " + " | ".join(position_lines)) + selected_position = self.position is not None and self.last_price is not None + self.close_trade_btn.configure(state="normal" if self.running and selected_position else "disabled") + else: + self.position_var.set("Нет открытых сделок") + self.close_trade_btn.configure(state="disabled") + values = { + "balance": f"{self.balance:,.2f} USDT", + "equity": f"{equity:,.2f} USDT", + "free": f"{free:,.2f} USDT", + "pnl": f"{pnl:+,.2f} USDT", + "fees": f"{self.total_fees:,.4f} USDT", + } + for key, value in values.items(): + self.metric_vars[key].set(value) + self._set_main_metrics( + self.balance, pnl, equity, "Баланс симуляции", "P&L с запуска", "Общий баланс с P&L", + free=free, open_positions=len(open_positions), + free_title="Свободно для новых сделок", + ) + + def _set_main_metrics(self, balance: float, pnl: float, equity: float, + balance_title: str, pnl_title: str, equity_title: str, *, + free: float | None = None, open_positions: int = 0, + free_title: str = "Свободно для новых сделок") -> None: + titles = {"balance": balance_title, "pnl": pnl_title, "equity": equity_title, "free": free_title} + values = { + "balance": f"{balance:,.2f} USDT", + "pnl": f"{pnl:+,.2f} USDT", + "equity": f"{equity:,.2f} USDT", + "free": "—" if free is None else f"{free:,.2f} USDT" + self._entries_left_text(free, open_positions), + } + for key in ("balance", "pnl", "equity", "free"): + self.main_metric_titles[key].configure(text=titles[key]) + self.main_metric_vars[key].set(values[key]) + + def _entries_left_text(self, free: float, open_positions: int) -> str: + """How many more default-size entries fit into free money and the position limit.""" + settings = self._safe_read_settings() + if self.strategy_mode != strategy.STRATEGY_CLASSIC and self.mode_var.get() == "Симуляция": + # Modes A/B size entries from their own settings, not the classic currency template. + try: + params = self._strategy_mode_params() + settings = {"stake": self.initial_balance * params["stake_pct"] / 100, + "leverage": params["leverage"]} + except ValueError: + return "" + stake = float(settings.get("stake") or 0.0) if settings else 0.0 + if stake <= 0: + return "" + by_money = max(0, int(free // (stake * (1 + float(settings.get("leverage", 1)) * TAKER_FEE_PCT / 100)))) + limit = self._position_limit_or_none() + if limit is not None: + by_limit = max(0, limit - open_positions) + return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}" + return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}" + + def _update_candle(self, timestamp: float, price: float) -> None: + interval_seconds = self.interval_minutes * 60 + candle_start = int(timestamp // interval_seconds) * interval_seconds + if self.chart_view_end is None: + self.chart_view_end = candle_start + interval_seconds + elif self.chart_view_end >= candle_start - interval_seconds: + # Keep the live candle on screen when the view is following the market. + self.chart_view_end = candle_start + interval_seconds + if not self.candles or self.candles[-1][0] != candle_start: + if self.candles: + self.baseline_close = self.candles[-1][4] + self.candles.append([candle_start, price, price, price, price]) + else: + candle = self.candles[-1] + candle[2] = max(candle[2], price) + candle[3] = min(candle[3], price) + candle[4] = price + + def reset_statistics(self) -> None: + if self.mode_var.get() == "Реальная торговля": + messagebox.showinfo("Сброс статистики", "Реальная история загружается с Bybit и не может быть сброшена из симулятора. Сброс доступен только для виртуального счёта.") + return + if any(state.position for state in self.symbol_states.values()): + messagebox.showerror("Сброс статистики", "Сначала дождитесь закрытия открытой позиции по TP или стопу.") + return + if not messagebox.askyesno( + "Сброс статистики", + "Очистить историю, комиссии и результат симуляции?", + ): + return + self.trades.clear() + self.total_fees = 0.0 + self.balance = self.initial_balance + self.next_id = 1 + self.entry_markers.clear() + for state in self.symbol_states.values(): + state.entry_markers.clear() + for item in self.table.get_children(): + self.table.delete(item) + self._save_account_state() + self._refresh_ui() + self._draw_chart() + self.status_var.set("Статистика сброшена; симуляция продолжает работу" if self.running else "Статистика сброшена") + + def _fetch_baseline_async(self, symbol: str, interval: int) -> None: + threading.Thread(target=self._fetch_baseline, args=(symbol, interval), daemon=True).start() + + def _fetch_chart_candles_async(self, symbol: str, interval: int) -> None: + def worker() -> None: + query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, + "interval": str(interval), "limit": "50"}) + request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + try: + with urllib.request.urlopen(request, timeout=8) as response: + result = json.loads(response.read().decode("utf-8")) + if result.get("retCode") != 0: + return + interval_seconds = interval * 60 + now = time.time() + candles = [[int(row[0]) / 1000, float(row[1]), float(row[2]), float(row[3]), float(row[4])] + for row in result.get("result", {}).get("list", []) + if int(row[0]) / 1000 + interval_seconds <= now] + candles.sort(key=lambda row: row[0]) + if candles: + self.events.put(("chart_candles", symbol, interval, candles, candles[-1][4])) + except Exception: + return + threading.Thread(target=worker, daemon=True).start() + + def _fetch_baseline(self, symbol: str, interval: int) -> None: + query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, "interval": str(interval), "limit": "3"}) + request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}", headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + try: + with urllib.request.urlopen(request, timeout=8) as response: + result = json.loads(response.read().decode("utf-8")) + if result.get("retCode") != 0: + raise RuntimeError(result.get("retMsg", "Bybit kline request failed")) + interval_ms = interval * 60_000 + now_ms = int(time.time() * 1000) + closed = [row for row in result.get("result", {}).get("list", []) if int(row[0]) + interval_ms <= now_ms] + if not closed: + raise RuntimeError("Bybit не вернул закрытую свечу") + latest = max(closed, key=lambda row: int(row[0])) + self.events.put(("baseline", symbol, interval, float(latest[4]))) + except Exception as exc: + self.events.put(("status", f"Не удалось загрузить закрытие свечи: {exc}")) + + @staticmethod + def _draw_level(canvas: tk.Canvas, price: float, low: float, high: float, left: int, right: int, top: int, bottom: int, label: str, color: str) -> None: + if not low <= price <= high: + return + y = bottom - (price - low) / (high - low) * (bottom - top) + canvas.create_line(left, y, right, y, fill=color, dash=(5, 3)) + canvas.create_text(left + 4, y - 3, anchor="sw", fill=color, text=f"{label}: {PaperSimulator._fmt_price(price)}") + + def _on_close(self) -> None: + if self.running: + self.stop() + self._save_settings() + self._save_account_state() + self._signal_pool.shutdown(wait=False, cancel_futures=True) + self.root.destroy() + + +def main() -> None: + root = tk.Tk() + PaperSimulator(root) + root.mainloop() + + +if __name__ == "__main__": + main() diff --git a/LinuxServer/meme_matcher/README.md b/LinuxServer/meme_matcher/README.md new file mode 100644 index 0000000..e10f103 --- /dev/null +++ b/LinuxServer/meme_matcher/README.md @@ -0,0 +1,105 @@ +# Meme Matcher + +Finds the same memecoins on **CEX perpetual futures** and on **DEX spot**, and compares their prices. + +``` +py -3 meme_matcher.py # window +py -3 meme_matcher.py --once # console table + meme_matches.csv +``` + +Python 3.10+ standard library only; all APIs are public (no keys). + +## Sources + +| What | Where | +|---|---| +| USDT perpetuals: price, 24h volume, funding | Bybit, Binance, OKX, Gate, MEXC, Bitget, BingX | +| Which coins are memecoins, market cap, contract addresses | CoinGecko, category `meme-token` (top 1000 by default, 4 pages × 250) | +| DEX pools: price, liquidity, 24h volume | DexScreener (Solana, Ethereum, BSC, Base, Arbitrum, TON, …) | +| DEX spot order book | HyperLiquid spot (USDC pairs) | + +The CoinGecko contract list (~4 MB) is cached in `cache/` for 24 h. + +## How a coin is identified + +A ticker alone is not enough: CoinGecko lists 21 different "PEPE" tokens, and one exchange can list `CAT` and +`1000CAT` as two different coins. So: + +1. Contract size prefixes and suffixes are removed and the price is converted to one coin (`1000PEPE`, `1MBABYDOGE`, + `SHIB1000`). +2. Each CEX contract is tied to the CoinGecko meme token with the same symbol **whose price agrees** with it (within + ±50%); contracts that agree with no meme token are skipped (not a memecoin, or an unknown one). +3. For that token's contract addresses every DexScreener pool is fetched; the token must be the pool's base asset. + The chosen pool is the deepest one whose price is within ±25% of the CEX price; HyperLiquid spot is added by + token name with the same price check. +4. Status by the DEX − CEX price gap: **совпадает** ≤ 5%, **проверить** ≤ 25%, **разные монеты?** above that (only + pools at a very different price exist — usually a copycat token on another chain), **нет на DEX**. + +## Window + +Exchange checkboxes, minimum DEX liquidity and CEX volume, number of CoinGecko pages, "only on DEX" and +"only matching" filters. Columns sort on click; a double click opens the pool on DexScreener / HyperLiquid; +"Сохранить CSV" saves what is shown. `(+N)` after the DEX means the coin also trades on N more chains at the same +price. Funding is the largest absolute funding rate over the listed exchanges. + +## Lead-lag: does the DEX move before the futures? + +``` +py -3 leadlag.py --minutes 30 --coins 12 # scan, record, analyse +py -3 leadlag.py --analyze recordings\leadlag_….jsonl.gz +``` + +Also the «Опережение DEX…» button in the window. Coins: status «совпадает», a pool on **Solana, BSC or Base** +(blocks ≤ 2 s; a 12 s Ethereum block cannot show a 1 s lead) with at least 120 swaps an hour (the most active pool +is used), and a perpetual on Binance, Bybit, Gate or MEXC (in that order of preference). + +Recorded at the same time: +* futures trades over WebSockets with exchange timestamps in ms (Binance `fstream…/market/stream` aggTrade, Bybit + publicTrade, Gate futures.trades, MEXC push.deal); +* DEX swaps from GeckoTerminal (`/pools/{pool}/trades`, last 300 swaps, polled every 30 s, ≤ 26 requests a minute) + with **on-chain block timestamps** — so the lead is measured on chain time, not on when the API showed the swap. + +Recordings go to `recordings/`, verdicts to `leadlag_results.csv`. + +Analysis on a 1-second grid (DEX: volume-weighted price of the block second; futures: last trade of the second): +* correlation of 1-s returns at lags −10…+10 s (+ = futures after the DEX); +* events — seconds where the DEX moved ≥ 0.15%: the futures move in the same direction in that second, and **from + t+1 to t+3/5/10** — i.e. after the DEX second and the next one, so a sub-second reaction that merely lands in the + next second does not count as a lead. Block times are whole seconds, so a lead under ~1 s cannot be told apart + from "simultaneous". +* verdicts: **DEX опережает ≥1 с** (t+1→t+5 move the DEX way, t ≥ 2, hit rate ≥ 60%, ≥ 10 events), **фьючерс + опережает** (best correlation at a negative lag), **после DEX фьючерс откатывает**, **одновременно / нет + опережения**, **мало движений DEX / мало данных**. + +**Live use:** GeckoTerminal publishes swaps 1–2 minutes late (column «Задержка данных DEX»). The tool can find +which coins lead; acting on a lead needs a direct chain feed (Solana RPC WebSocket on the pool), not this API. + +## Autonomous search (autoscan) + +``` +py -3 autoscan.py --minutes 15 --coins 12 # or autoscan.bat, or «Автопоиск…» → «Запустить» in the window +``` + +Runs on its own in a loop: scan → up to 12 coins (earlier leaders are re-checked first, the rest rotate through all +candidates) → 15 min recording → lead analysis → next cycle (one cycle ≈ 20 min). Every result is appended to +`autoscan_history.csv`, the log to `autoscan.log`. A coin with «DEX опережает ≥1 с» whose pool is on Solana and of a +type the simulator reads live (Raydium AMM v4 / CPMM, PumpSwap, Meteora DLMM — checked through the pool account's +owner program) and whose futures are on Binance, Bybit or MEXC is added to the simulator's `../lead_connections.json` +(never removed; the simulator's active connection is not changed; the simulator picks the new entry up within 30 s). +Only one autoscan runs at a time (`autoscan.lock`); the manual «Опережение DEX…» recording shares GeckoTerminal's +rate limit with it. «Автопоиск…» in the window shows the history (leaders highlighted, what was added) and starts or +stops the background process, which keeps running when the windows are closed. + +## Limits + +* The meme universe is CoinGecko's `meme-token` category: memecoins that CoinGecko has not tagged, or that are + outside the scanned pages, are not found. +* The CoinGecko free API allows a few requests per minute; the scanner waits between pages and retries on HTTP 429. +* Prices come from different moments (each API is polled once); small gaps are timing, not arbitrage. DEX prices + do not include swap fees, slippage or gas. + +## Tests + +``` +py -3 -m unittest discover -s tests +``` diff --git a/LinuxServer/meme_matcher/autoscan.py b/LinuxServer/meme_matcher/autoscan.py new file mode 100644 index 0000000..a19a8bb --- /dev/null +++ b/LinuxServer/meme_matcher/autoscan.py @@ -0,0 +1,420 @@ +"""Autonomous DEX → futures lead search: scan, record, analyse, repeat — and hand the leaders to the simulator. + +Each cycle: +1. Meme Matcher scan (CEX perpetuals ↔ DEX pools, same coin, prices agree); +2. up to N coins: coins that led before are re-checked first, the rest rotate through every candidate (most active + pools first), so all of them get measured over a few cycles; +3. record M minutes (CEX trades + on-chain DEX swaps) and analyse the lead (leadlag.analyze); +4. every result goes to autoscan_history.csv; a coin where the DEX leads ≥ 1 s, on a Solana pool the simulator can + read live (Raydium AMM v4 / CPMM / CLMM, PumpSwap, Meteora DLMM, Orca Whirlpool, PancakeSwap CLMM) and a futures exchange it can trade (Binance, Bybit, + MEXC), is added to the simulator's connection list (../lead_connections.json) — never removed, the active + connection is not changed; +5. start again. + +Run: py -3 autoscan.py --minutes 15 --coins 12 (or autoscan.bat; stop with Ctrl+C or by closing the window) +""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import sys +import threading +import time +import urllib.request +from datetime import datetime +from pathlib import Path + +import leadlag as ll +import meme_matcher as mm + +ROOT = Path(__file__).resolve().parent +SIM_DIR = ROOT.parent +DATA_DIR = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", SIM_DIR / "web_sim_data")).resolve() +CONNECTIONS_FILE = DATA_DIR / "lead_connections.json" +HISTORY_CSV = DATA_DIR / "autoscan_history.csv" +LOG_FILE = DATA_DIR / "autoscan.log" +LOCK_FILE = DATA_DIR / "autoscan.lock" +LEAD_VERDICT = "DEX опережает ≥1 с" +SIM_EXCHANGES = ["Bybit", "MEXC"] # futures the simulator can paper-trade on +SUPPORTED_OWNERS = { + "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8": "Raydium AMM v4", + "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C": "Raydium CPMM", + "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA": "PumpSwap", + "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo": "Meteora DLMM", + "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc": "Orca Whirlpool", + "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK": "Raydium CLMM", + "HpNfyc2Saw7RKkQd8nEL4khUcuPhQ7WwY1B2qjx8jxFq": "PancakeSwap CLMM", +} +HISTORY_COLUMNS = ["time", "cycle", "symbol", "verdict", "futures", "futures_symbol", "dex_pool", "pool_address", + "dex_moves", "best_lag_s", "follow_t1_t5_pct", "hit_t5", "t_stat", "added_to_simulator"] + + +def log(text: str) -> None: + line = f"{datetime.now():%Y-%m-%d %H:%M:%S} {text}" + print(line, flush=True) + try: + with LOG_FILE.open("a", encoding="utf-8") as f: + f.write(line + "\n") + except OSError: + pass + + +def pool_owner(pool: str) -> str: + """Program that owns a Solana pool account (public RPC).""" + body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "getAccountInfo", + "params": [pool, {"encoding": "base64", "dataSlice": {"offset": 0, "length": 0}}]}).encode() + req = urllib.request.Request("https://api.mainnet-beta.solana.com", data=body, + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=20) as resp: + value = json.loads(resp.read())["result"]["value"] + return value["owner"] if value else "" + except (OSError, ValueError, KeyError, TypeError): + return "" + + +def simulator_connection(t: ll.Target) -> dict | None: + """The simulator's connection for a target, or None when the simulator cannot trade / read it live.""" + if t.chain != "solana" or t.cex not in SIM_EXCHANGES: + return None + exchange = t.cex.lower() + return {"lead_market": "raydium", "lead_ticker": f"{t.symbol}USDTM", "lead_pool": t.pool, + "follow_exchange": exchange, "follow_ticker": t.cex_symbol} + + +def same_connection(a: dict, b: dict) -> bool: + keys = ["lead_market", "follow_exchange", "follow_ticker"] + keys.append("lead_pool" if a.get("lead_market") == "raydium" else "lead_ticker") + return all(a.get(k) == b.get(k) for k in keys) + + +def lw_removed(conn: dict) -> bool: + """The user deleted this pair from the simulator (lead_connections_removed.json).""" + try: + removed = json.loads((DATA_DIR / "lead_connections_removed.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return False + return any(isinstance(r, dict) and same_connection(r, conn) for r in removed) + + +def add_connection(conn: dict, path: Path = CONNECTIONS_FILE) -> bool: + """Append a connection to the simulator's list (re-read first, so nothing written meanwhile is lost).""" + try: + existing = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(existing, list): + existing = [] + except (OSError, ValueError): + existing = [] + if any(isinstance(c, dict) and same_connection(c, conn) for c in existing): + return False + existing.append(conn) + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=2), encoding="utf-8") + os.replace(tmp, path) + return True + + +def choose_targets(candidates: list[ll.Target], leaders: list[str], offset: int, n: int) -> tuple[list, int]: + """Earlier leaders first (re-check), then the next coins of the rotation.""" + by_symbol = {t.symbol: t for t in candidates} + chosen = [by_symbol[s] for s in leaders if s in by_symbol][:n] + rest = [t for t in candidates if t.symbol not in {c.symbol for c in chosen}] + if rest: + start = offset % len(rest) + rotated = rest[start:] + rest[:start] + take = rotated[:max(0, n - len(chosen))] + chosen += take + offset = (start + len(take)) % len(rest) + return chosen, offset + + +def append_history(cycle: int, results: list[ll.LeadResult], targets: dict, added: dict, + path: Path = HISTORY_CSV) -> None: + new = not path.exists() + with path.open("a", newline="", encoding="utf-8-sig") as f: + w = csv.writer(f, delimiter=";") + if new: + w.writerow(HISTORY_COLUMNS) + now = datetime.now().strftime("%Y-%m-%d %H:%M") + for r in results: + t = targets.get(r.symbol) + w.writerow([now, cycle, r.symbol, r.verdict, r.cex, t.cex_symbol if t else "", r.pool, t.pool if t else "", + r.events, r.best_lag, f"{r.follow.get(5, 0):+.3f}", f"{r.hit.get(5, 0):.2f}", + f"{r.t_stat:+.2f}", added.get(r.symbol, "")]) + + +def read_leaders(path: Path = HISTORY_CSV, last_cycles: int = 3) -> list[str]: + """Coins that led in any of the last few cycles (to re-check first).""" + try: + rows = list(csv.DictReader(path.open(encoding="utf-8-sig"), delimiter=";")) + except OSError: + return [] + if not rows: + return [] + top = max(int(r["cycle"]) for r in rows) + return list(dict.fromkeys(r["symbol"] for r in rows + if r["verdict"] == LEAD_VERDICT and int(r["cycle"]) > top - last_cycles)) + + +def last_cycle(path: Path = HISTORY_CSV) -> int: + try: + rows = list(csv.DictReader(path.open(encoding="utf-8-sig"), delimiter=";")) + return max(int(r["cycle"]) for r in rows) if rows else 0 + except (OSError, ValueError): + return 0 + + +def take_lock() -> bool: + """Allow one autoscan per application account.""" + try: + pid = int(LOCK_FILE.read_text()) + if pid != os.getpid() and _alive(pid): + return False + except (OSError, ValueError): + pass + LOCK_FILE.write_text(str(os.getpid())) + return True + + +def _alive(pid: int) -> bool: + if os.name != "nt": + try: + os.kill(pid, 0) + return True + except OSError: + return False + try: + import ctypes + handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION + if not handle: + return False + code = ctypes.c_ulong() + ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(code)) + ctypes.windll.kernel32.CloseHandle(handle) + return code.value == 259 # STILL_ACTIVE + except Exception: + return False + + +CONFIG_FILE = DATA_DIR / "autoscan_config.json" + + +def load_config() -> dict: + """auto_add: add DEX leaders to the simulator by themselves (off: the web page's «Добавить» button does it).""" + try: + cfg = json.loads(CONFIG_FILE.read_text(encoding="utf-8")) + except (OSError, ValueError): + cfg = {} + return {"auto_add": bool(cfg.get("auto_add", False))} + + +def save_config(cfg: dict) -> None: + CONFIG_FILE.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8") + + +def run(minutes: float, coins: int, min_txns: int, threshold: float, stop: threading.Event | None = None) -> None: + import traceback + stop = stop or threading.Event() + ll.CEX_PRIORITY = SIM_EXCHANGES + [e for e in ll.CEX_PRIORITY if e not in SIM_EXCHANGES] + state = {"cycle": last_cycle(), "offset": 0} + while not stop.is_set(): + try: + _cycle(state, minutes, coins, min_txns, threshold, stop) + except Exception: + log("ошибка цикла, продолжаю через минуту:\n" + traceback.format_exc()) + stop.wait(60) + + +def _cycle(st: dict, minutes: float, coins: int, min_txns: int, threshold: float, stop: threading.Event) -> None: + st["cycle"] += 1 + cycle = st["cycle"] + log(f"=== цикл {cycle}: сканирую биржи и DEX") + try: + matches = mm.scan(log=lambda s: None) + except Exception as exc: + log(f"скан не удался: {exc}; повтор через минуту") + stop.wait(60) + return + candidates = ll.pick_targets(matches, max_coins=1000, min_txns_h1=min_txns) + leaders = read_leaders() + targets, st["offset"] = choose_targets(candidates, leaders, st["offset"], coins) + if not targets: + log("подходящих монет нет; повтор через 5 минут") + stop.wait(300) + return + log(f"кандидатов {len(candidates)}, в этом цикле: " + ", ".join( + f"{t.symbol}{'*' if t.symbol in leaders else ''} ({t.cex}, {t.chain}/{t.dex})" for t in targets) + + " (* — перепроверка лидера)") + # record() sets its stop event when it is done (to stop its threads), so it gets its own one: sharing the + # loop's event used to end the whole autoscan after the first cycle + rec = ll.record(targets, minutes, log=lambda s: None, stop=threading.Event()) + if stop.is_set(): + return + path = rec.save() + results = ll.analyze(targets, rec.cex, rec.dex, rec.gaps, threshold) + by_symbol = {t.symbol: t for t in targets} + auto_add = load_config()["auto_add"] + added = {} + for r in results: + if r.verdict != LEAD_VERDICT: + continue + t = by_symbol[r.symbol] + conn = simulator_connection(t) + if conn is None: + added[r.symbol] = f"нет: {t.chain}/{t.cex} не поддерживается симулятором" + continue + owner = pool_owner(t.pool) + if owner not in SUPPORTED_OWNERS: + added[r.symbol] = "нет: тип пула не читается симулятором вживую" + continue + if auto_add and lw_removed(conn): + added[r.symbol] = f"можно добавить ({SUPPORTED_OWNERS[owner]}; удалена вручную — сама не добавляется)" + elif auto_add: + added[r.symbol] = ("да" if add_connection(conn) else "уже был") + f" ({SUPPORTED_OWNERS[owner]})" + else: + added[r.symbol] = f"можно добавить ({SUPPORTED_OWNERS[owner]})" + append_history(cycle, results, by_symbol, added) + ll.save_results(results) + found = [f"{r.symbol} ({added.get(r.symbol, '')})" for r in results if r.verdict == LEAD_VERDICT] + log(f"цикл {cycle} готов, запись {path.name}; DEX опережает: {', '.join(found) if found else 'не найдено'}") + + +def running_pid() -> int | None: + try: + pid = int(LOCK_FILE.read_text()) + except (OSError, ValueError): + return None + return pid if _alive(pid) else None + + +def start_background(minutes: float = 15, coins: int = 12) -> None: + """Start autoscan as its own hidden process, so it keeps running when the windows are closed.""" + import subprocess + flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0) + subprocess.Popen([sys.executable, str(ROOT / "autoscan.py"), "--minutes", str(minutes), "--coins", str(coins)], + cwd=ROOT, creationflags=flags, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=os.name != "nt") + + +def stop_background() -> None: + pid = running_pid() + if pid: + import subprocess + if os.name == "nt": + subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True) + else: + try: + os.kill(pid, 15) + except OSError: + pass + try: + LOCK_FILE.unlink() + except OSError: + pass + log("остановлено из окна") + + +def open_window(parent) -> None: + """History of the autonomous search + start/stop, refreshed every 15 s.""" + import tkinter as tk + from tkinter import ttk + + win = tk.Toplevel(parent) + win.title("Автопоиск: DEX опережает фьючерсы") + win.geometry("1250x620") + top = ttk.Frame(win, padding=6) + top.pack(fill="x") + minutes, coins = tk.StringVar(value="15"), tk.StringVar(value="12") + ttk.Label(top, text="Минут на цикл").pack(side="left") + ttk.Entry(top, textvariable=minutes, width=5).pack(side="left", padx=(4, 10)) + ttk.Label(top, text="Монет за цикл (до 13)").pack(side="left") + ttk.Entry(top, textvariable=coins, width=5).pack(side="left", padx=(4, 10)) + start_btn = ttk.Button(top, text="▶ Запустить автопоиск") + start_btn.pack(side="left", padx=4) + stop_btn = ttk.Button(top, text="■ Остановить") + stop_btn.pack(side="left") + state_var = tk.StringVar() + ttk.Label(top, textvariable=state_var, padding=(10, 0)).pack(side="left") + only_leaders = tk.BooleanVar(value=False) + ttk.Checkbutton(top, text="Только «DEX опережает»", variable=only_leaders, command=lambda: fill()).pack(side="left") + cols = {"time": ("Время", 110), "cycle": ("Цикл", 45), "symbol": ("Монета", 80), "verdict": ("Вывод", 200), + "futures": ("Фьючерс", 70), "dex_pool": ("Пул DEX", 130), "dex_moves": ("Движений", 70), + "best_lag_s": ("Лаг, с", 50), "follow_t1_t5_pct": ("t+1→t+5", 70), "hit_t5": ("Попад.", 55), + "t_stat": ("t", 50), "added_to_simulator": ("В симулятор", 230)} + tree = ttk.Treeview(win, columns=list(cols), show="headings", height=18) + for key, (title, width) in cols.items(): + tree.heading(key, text=title) + tree.column(key, width=width, anchor="w") + tree.tag_configure("lead", background="#e8f7e8") + tree.pack(fill="both", expand=True, padx=6) + log_var = tk.StringVar() + ttk.Label(win, textvariable=log_var, padding=6, wraplength=1200, justify="left", foreground="#444").pack(fill="x") + + def fill() -> None: + tree.delete(*tree.get_children()) + try: + rows = list(csv.DictReader(HISTORY_CSV.open(encoding="utf-8-sig"), delimiter=";")) + except OSError: + rows = [] + for r in reversed(rows[-500:]): + if only_leaders.get() and r["verdict"] != LEAD_VERDICT: + continue + tree.insert("", "end", values=[r.get(k, "") for k in cols], + tags=("lead",) if r["verdict"] == LEAD_VERDICT else ()) + + def refresh() -> None: + pid = running_pid() + state_var.set(f"автопоиск работает (процесс {pid})" if pid else "автопоиск остановлен") + start_btn.configure(state="disabled" if pid else "normal") + stop_btn.configure(state="normal" if pid else "disabled") + fill() + try: + lines = LOG_FILE.read_text(encoding="utf-8").splitlines()[-4:] + except OSError: + lines = [] + log_var.set("\n".join(lines)) + if win.winfo_exists(): + win.after(15000, refresh) + + def start() -> None: + try: + m, n = float(minutes.get()), max(1, min(13, int(coins.get()))) + except ValueError: + state_var.set("проверьте числа") + return + start_background(m, n) + win.after(1500, refresh) + + start_btn.configure(command=start) + stop_btn.configure(command=lambda: (stop_background(), win.after(500, refresh))) + refresh() + + +def main() -> None: + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + parser = argparse.ArgumentParser(description="autonomous DEX → futures lead search") + parser.add_argument("--minutes", type=float, default=15, help="recording per cycle") + parser.add_argument("--coins", type=int, default=12, help="coins per cycle (GeckoTerminal allows ~13)") + parser.add_argument("--min-txns", type=int, default=120, help="min swaps per hour in the DEX pool") + parser.add_argument("--threshold", type=float, default=0.15, help="DEX move in one second, %%") + args = parser.parse_args() + if not take_lock(): + print("Автопоиск уже запущен (autoscan.lock) — второй экземпляр не нужен") + return + try: + run(args.minutes, min(13, args.coins), args.min_txns, args.threshold) + except KeyboardInterrupt: + log("остановлено") + finally: + try: + LOCK_FILE.unlink() + except OSError: + pass + + +if __name__ == "__main__": + main() diff --git a/LinuxServer/meme_matcher/leadlag.py b/LinuxServer/meme_matcher/leadlag.py new file mode 100644 index 0000000..c7938be --- /dev/null +++ b/LinuxServer/meme_matcher/leadlag.py @@ -0,0 +1,591 @@ +"""Lead-lag: does the DEX spot price move BEFORE the CEX perpetual (by at least a second)? + +For memecoins found by meme_matcher (same coin, price agrees, a pool on a fast chain) it records at the same time +* CEX perpetual trades from a WebSocket (Binance, Bybit, Gate or MEXC) with exchange timestamps in milliseconds; +* DEX swaps of the most active pool from GeckoTerminal with ON-CHAIN block timestamps (1 s resolution). + +Then, on a 1-second grid, it checks whether a DEX move in second t is followed by the futures moving the same way +AFTER second t+1 - i.e. later than any same-second reaction could explain. That is the part one could trade. + +Note: GeckoTerminal publishes swaps ~40-60 s after the block (it caches for 30 s), so this tool MEASURES the lead +on chain time; using a lead live needs a direct chain feed (e.g. a Solana RPC WebSocket). The DEX data delay is +reported per coin. + +Run: py -3 leadlag.py --minutes 20 --coins 10 (scan, record, analyse) + py -3 leadlag.py --analyze recordings\\leadlag_....jsonl.gz +""" + +from __future__ import annotations + +import argparse +import csv +import gzip +import json +import math +import threading +import time +from collections import deque +from dataclasses import asdict, dataclass, field +from datetime import datetime +from pathlib import Path + +import numpy as np + +import meme_matcher as mm + +ROOT = Path(__file__).resolve().parent +REC_DIR = ROOT / "recordings" +RESULTS_CSV = ROOT / "leadlag_results.csv" + +# DexScreener chain -> GeckoTerminal network. Only chains with blocks of ~2 s or faster: a 12 s Ethereum block +# cannot show a 1 s lead. +FAST_CHAINS = {"solana": "solana", "bsc": "bsc", "base": "base"} +CEX_PRIORITY = ["Binance", "Bybit", "Gate", "MEXC"] +GECKO_CALLS_PER_MIN = 26 # free tier: 30 a minute +MIN_POLL_S = 30 # GeckoTerminal caches responses for 30 s +TAIL_S = 180 # extra DEX polling after the CEX recording ends (swaps are published late) + + +@dataclass +class Target: + symbol: str + cg_id: str + cex: str + cex_symbol: str + multiplier: float + chain: str + network: str + pool: str + token: str + dex: str + txns_h1: int + + +def pick_targets(matches: list[mm.Match], max_coins: int = 10, min_txns_h1: int = 120) -> list[Target]: + out = [] + for m in matches: + if m.status != "совпадает": + continue + pools = [p for p in m.pools if p.source == "DexScreener" and p.chain in FAST_CHAINS and p.pair_address] + if not pools: + continue + pool = max(pools, key=lambda p: p.txns_h1) + if pool.txns_h1 < min_txns_h1: + continue + by_exchange = {l.exchange: l for l in m.cex} + listing = next((by_exchange[e] for e in CEX_PRIORITY if e in by_exchange), None) + if listing is None: + continue + out.append(Target(m.symbol, m.cg_id, listing.exchange, listing.symbol, listing.multiplier, pool.chain, + FAST_CHAINS[pool.chain], pool.pair_address, pool.contract, pool.dex, pool.txns_h1)) + out.sort(key=lambda t: -t.txns_h1) + return out[:max_coins] + + +# -------------------------------------------------------------------------------------------- +# Recording +# -------------------------------------------------------------------------------------------- + +class Recorder: + def __init__(self, targets: list[Target]) -> None: + self.targets = targets + self.lock = threading.Lock() + self.cex: dict[str, list[tuple[float, float]]] = {t.symbol: [] for t in targets} + self.dex: dict[str, list[tuple[float, float, float, str, float]]] = {t.symbol: [] for t in targets} + self.seen: set[str] = set() + self.gaps: dict[str, int] = {t.symbol: 0 for t in targets} + self.errors: deque[str] = deque(maxlen=20) + self.started = time.time() + + def add_cex(self, symbol: str, ts: float, price: float) -> None: + with self.lock: + self.cex[symbol].append((ts, price)) + + def add_dex(self, symbol: str, trade_id: str, ts: float, price: float, volume: float, kind: str) -> bool: + with self.lock: + if trade_id in self.seen: + return False + self.seen.add(trade_id) + self.dex[symbol].append((ts, price, volume, kind, time.time())) + return True + + def counts(self) -> dict[str, tuple[int, int]]: + with self.lock: + return {s: (len(self.cex[s]), len(self.dex[s])) for s in self.cex} + + def save(self, path: Path | None = None) -> Path: + REC_DIR.mkdir(exist_ok=True) + path = path or REC_DIR / f"leadlag_{datetime.now():%Y%m%d_%H%M%S}.jsonl.gz" + with self.lock, gzip.open(path, "wt", encoding="utf-8") as f: + f.write(json.dumps({"meta": {"started": self.started, "saved": time.time(), "gaps": self.gaps, + "targets": [asdict(t) for t in self.targets]}}) + "\n") + for s, rows in self.cex.items(): + for ts, price in rows: + f.write(json.dumps(["C", s, ts, price]) + "\n") + for s, rows in self.dex.items(): + for row in rows: + f.write(json.dumps(["D", s, *row]) + "\n") + return path + + +def load(path: Path) -> tuple[list[Target], dict, dict, dict]: + cex: dict[str, list] = {} + dex: dict[str, list] = {} + meta = {} + with gzip.open(path, "rt", encoding="utf-8") as f: + for line in f: + row = json.loads(line) + if isinstance(row, dict): + meta = row["meta"] + elif row[0] == "C": + cex.setdefault(row[1], []).append((row[2], row[3])) + else: + dex.setdefault(row[1], []).append(tuple(row[2:])) + targets = [Target(**t) for t in meta.get("targets", [])] + return targets, cex, dex, meta + + +class CexFeed(threading.Thread): + """Trades of one exchange's perpetuals over a WebSocket; reconnects on errors.""" + + def __init__(self, exchange: str, targets: list[Target], rec: Recorder, stop: threading.Event) -> None: + super().__init__(daemon=True) + self.exchange, self.rec, self.stop_event = exchange, rec, stop + self.by_symbol = {t.cex_symbol: t for t in targets} + + def _url(self) -> str: + if self.exchange == "Binance": + streams = "/".join(f"{s.lower()}@aggTrade" for s in self.by_symbol) + return f"wss://fstream.binance.com/market/stream?streams={streams}" + return {"Bybit": "wss://stream.bybit.com/v5/public/linear", "Gate": "wss://fx-ws.gateio.ws/v4/ws/usdt", + "MEXC": "wss://contract.mexc.com/edge"}[self.exchange] + + def _subscribe(self, ws) -> None: + symbols = list(self.by_symbol) + if self.exchange == "Bybit": + for i in range(0, len(symbols), 10): + ws.send(json.dumps({"op": "subscribe", "args": [f"publicTrade.{s}" for s in symbols[i:i + 10]]})) + elif self.exchange == "Gate": + ws.send(json.dumps({"time": int(time.time()), "channel": "futures.trades", "event": "subscribe", + "payload": symbols})) + elif self.exchange == "MEXC": + for s in symbols: + ws.send(json.dumps({"method": "sub.deal", "param": {"symbol": s}})) + + def _ping(self, ws) -> None: + if self.exchange == "Bybit": + ws.send(json.dumps({"op": "ping"})) + elif self.exchange == "Gate": + ws.send(json.dumps({"time": int(time.time()), "channel": "futures.ping"})) + elif self.exchange == "MEXC": + ws.send(json.dumps({"method": "ping"})) + + def _emit(self, symbol: str, ts_ms, price) -> None: + target = self.by_symbol.get(symbol) + if target is not None: + self.rec.add_cex(target.symbol, float(ts_ms) / 1000, float(price) / target.multiplier) + + def handle(self, msg: dict) -> None: + if self.exchange == "Binance": + d = msg.get("data") or {} + if d.get("e") == "aggTrade": + self._emit(d["s"], d["T"], d["p"]) + elif self.exchange == "Bybit": + if str(msg.get("topic", "")).startswith("publicTrade."): + for d in msg.get("data", []): + self._emit(d["s"], d["T"], d["p"]) + elif self.exchange == "Gate": + if msg.get("channel") == "futures.trades" and msg.get("event") == "update": + for d in msg.get("result", []): + self._emit(d["contract"], d["create_time_ms"], d["price"]) + elif self.exchange == "MEXC": + if msg.get("channel") == "push.deal": + data = msg.get("data") + for d in data if isinstance(data, list) else [data]: + self._emit(msg.get("symbol", ""), d["t"], d["p"]) + + def run(self) -> None: + import websocket + + while not self.stop_event.is_set(): + try: + ws = websocket.create_connection(self._url(), timeout=5) + self._subscribe(ws) + last_ping = time.time() + while not self.stop_event.is_set(): + if time.time() - last_ping > 15: + self._ping(ws) + last_ping = time.time() + try: + raw = ws.recv() + except websocket.WebSocketTimeoutException: + continue + if raw: + self.handle(json.loads(raw)) + ws.close() + except Exception as exc: + self.rec.errors.append(f"{self.exchange}: {exc}") + self.stop_event.wait(3) + + +def parse_gecko_trades(data: dict, token: str) -> list[tuple[str, float, float, float, str]]: + """GeckoTerminal /trades -> (id, block time, price of OUR token in USD, volume USD, buy/sell).""" + token = token.lower() + out = [] + for item in data.get("data") or []: + a = item.get("attributes") or {} + try: + ts = datetime.fromisoformat(a["block_timestamp"].replace("Z", "+00:00")).timestamp() + except (KeyError, ValueError): + continue + if str(a.get("from_token_address", "")).lower() == token: + price = mm._f(a.get("price_from_in_usd")) + elif str(a.get("to_token_address", "")).lower() == token: + price = mm._f(a.get("price_to_in_usd")) + else: + continue + if price > 0: + out.append((item.get("id") or a.get("tx_hash", ""), ts, price, mm._f(a.get("volume_in_usd")), + a.get("kind", ""))) + return out + + +class DexPoller(threading.Thread): + def __init__(self, targets: list[Target], rec: Recorder, stop: threading.Event) -> None: + super().__init__(daemon=True) + self.targets, self.rec, self.stop_event = targets, rec, stop + + def run(self) -> None: + gap = 60.0 / GECKO_CALLS_PER_MIN + first = {t.symbol: True for t in self.targets} + while not self.stop_event.is_set(): + cycle_start = time.time() + for t in self.targets: + if self.stop_event.is_set(): + return + try: + data = mm.http_json(f"https://api.geckoterminal.com/api/v2/networks/{t.network}/pools/{t.pool}" + "/trades", retries=2) + trades = parse_gecko_trades(data or {}, t.token) + new = sum(self.rec.add_dex(t.symbol, *tr) for tr in trades) + if not first[t.symbol] and trades and new == len(trades) and len(trades) >= 300: + self.rec.gaps[t.symbol] += 1 # all 300 were new: some swaps were missed + first[t.symbol] = False + except Exception as exc: + self.rec.errors.append(f"GeckoTerminal {t.symbol}: {exc}") + self.stop_event.wait(gap) + rest = MIN_POLL_S - (time.time() - cycle_start) + if rest > 0: + self.stop_event.wait(rest) + + +def record(targets: list[Target], minutes: float, log=print, stop: threading.Event | None = None) -> Recorder: + rec = Recorder(targets) + stop = stop or threading.Event() + threads = [DexPoller(targets, rec, stop)] + for exchange in CEX_PRIORITY: + mine = [t for t in targets if t.cex == exchange] + if mine: + threads.append(CexFeed(exchange, mine, rec, stop)) + for th in threads: + th.start() + end = time.time() + minutes * 60 + while time.time() < end and not stop.is_set(): + stop.wait(10) + counts = rec.counts() + left = max(0, end - time.time()) / 60 + log(f"Запись: осталось {left:.1f} мин · " + ", ".join(f"{s} {c}/{d}" for s, (c, d) in counts.items()) + + " (сделок фьючерс/DEX)") + # GeckoTerminal shows swaps 1-2 min late: keep polling the DEX so the last minutes of CEX data are covered + if not stop.is_set(): + log(f"Дозаписываю последние сделки DEX (они появляются с задержкой 1–2 мин), {TAIL_S // 60} мин…") + stop.wait(TAIL_S) + stop.set() + for th in threads: + th.join(timeout=10) + return rec + + +# -------------------------------------------------------------------------------------------- +# Analysis +# -------------------------------------------------------------------------------------------- + +@dataclass +class LeadResult: + symbol: str + cex: str + pool: str + seconds: int + cex_trades: int + dex_trades: int + events: int # seconds with a DEX move of at least the threshold + corr: dict[int, float] # lag (s, + = futures after DEX) -> correlation of 1-s returns + best_lag: int + same_second: float # mean futures move in the DEX move's direction, same second, % + follow: dict[int, float] # mean futures move from t+1 to t+k in the DEX direction, % + hit: dict[int, float] # share of events where that move went the DEX way (of those that moved) + t_stat: float # of the follow move t+1 -> t+5 + dex_delay_s: float # how late GeckoTerminal published the swaps (median) + gaps: int + verdict: str + notes: list[str] = field(default_factory=list) + + +def second_series(trades: list[tuple], t0: int, t1: int, vwap: bool) -> np.ndarray: + """Price per second on [t0, t1], forward-filled. DEX: volume-weighted within the block second.""" + n = t1 - t0 + 1 + px = np.full(n, np.nan) + if vwap: + num, den = np.zeros(n), np.zeros(n) + for ts, price, vol, *_ in trades: + i = int(ts) - t0 + if 0 <= i < n: + w = max(vol, 1e-9) + num[i] += price * w + den[i] += w + mask = den > 0 + px[mask] = num[mask] / den[mask] + else: + for ts, price in sorted(trades): + i = int(math.floor(ts)) - t0 + if 0 <= i < n: + px[i] = price # last trade of the second + # forward fill + last = np.nan + for i in range(n): + if np.isnan(px[i]): + px[i] = last + else: + last = px[i] + return px + + +def analyze_coin(target: Target, cex: list, dex: list, gaps: int = 0, threshold_pct: float = 0.15, + max_lag: int = 10) -> LeadResult: + notes = [] + empty = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", 0, len(cex), len(dex), 0, {}, 0, + 0.0, {}, {}, 0.0, 0.0, gaps, "мало данных", notes) + if len(cex) < 20 or len(dex) < 20: + return empty + t0 = int(max(min(t for t, _ in cex), min(r[0] for r in dex))) + t1 = int(min(max(t for t, _ in cex), max(r[0] for r in dex))) + if t1 - t0 < 120: + return empty + c = second_series(cex, t0, t1, vwap=False) + d = second_series(dex, t0, t1, vwap=True) + ok = ~(np.isnan(c) | np.isnan(d)) + start = int(np.argmax(ok)) + c, d = np.log(c[start:]), np.log(d[start:]) + rc, rd = np.diff(c), np.diff(d) + n = len(rc) + corr = {} + for k in range(-max_lag, max_lag + 1): + a = rd[max(0, -k): n - max(0, k)] + b = rc[max(0, k): n - max(0, -k)] + corr[k] = float(np.corrcoef(a, b)[0, 1]) if len(a) > 30 and a.std() > 0 and b.std() > 0 else 0.0 + best_lag = max(corr, key=lambda k: corr[k]) + # events: DEX moved at least the threshold within one second (rd[i] = second i+1 vs i) + thr = threshold_pct / 100 + horizons = (2, 3, 5, 10) + same, follow, hit = [], {k: [] for k in horizons}, {k: [] for k in horizons} + for i in np.nonzero(np.abs(rd) >= thr)[0]: + t = i + 1 # index of the second where the DEX move landed + if t + max(horizons) >= len(c) or t < 1: + continue + sign = 1.0 if rd[i] > 0 else -1.0 + same.append(sign * (c[t] - c[t - 1])) + for k in horizons: + move = sign * (c[t + k] - c[t + 1]) # strictly after the DEX second and the next one + follow[k].append(move) + if abs(move) > 1e-12: + hit[k].append(move > 0) + events = len(same) + f5 = np.array(follow[5]) if follow[5] else np.array([0.0]) + t_stat = float(f5.mean() / (f5.std(ddof=1) / math.sqrt(len(f5)))) if len(f5) > 2 and f5.std() > 0 else 0.0 + # publication delay only for swaps made during the recording (the first poll returns old history) + first_cex = min(t for t, _ in cex) + delays = [r[4] - r[0] for r in dex if len(r) > 4 and r[0] >= first_cex] + res = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", n, len(cex), len(dex), events, corr, + best_lag, float(np.mean(same) * 100) if same else 0.0, + {k: float(np.mean(v) * 100) if v else 0.0 for k, v in follow.items()}, + {k: float(np.mean(v)) if v else 0.0 for k, v in hit.items()}, t_stat, + float(np.median(delays)) if delays else 0.0, gaps, "", notes) + if gaps: + notes.append(f"пропуски DEX: {gaps} раз пришло 300 новых сделок подряд") + if events < 10: + res.verdict = "мало движений DEX" + elif t_stat >= 2 and res.hit[5] >= 0.6 and res.follow[5] > 0: + res.verdict = "DEX опережает ≥1 с" + elif best_lag < 0 and corr[best_lag] > corr.get(0, 0) and corr[best_lag] > 3 / math.sqrt(n): + res.verdict = "фьючерс опережает" + elif t_stat <= -2: + res.verdict = "после DEX фьючерс откатывает" + else: + res.verdict = "одновременно / нет опережения" + return res + + +def analyze(targets: list[Target], cex: dict, dex: dict, gaps: dict | None = None, + threshold_pct: float = 0.15) -> list[LeadResult]: + out = [analyze_coin(t, cex.get(t.symbol, []), dex.get(t.symbol, []), (gaps or {}).get(t.symbol, 0), + threshold_pct) for t in targets] + order = {"DEX опережает ≥1 с": 0, "одновременно / нет опережения": 1, "фьючерс опережает": 2, + "после DEX фьючерс откатывает": 3, "мало движений DEX": 4, "мало данных": 5} + out.sort(key=lambda r: (order.get(r.verdict, 9), -r.t_stat)) + return out + + +RESULT_COLUMNS = ["symbol", "verdict", "cex", "dex_pool", "minutes", "cex_trades", "dex_trades", "dex_moves", + "best_lag_s", "corr_lag0", "corr_lag1", "corr_lag2", "corr_lag-1", "same_second_pct", + "follow_t1_t3_pct", "follow_t1_t5_pct", "follow_t1_t10_pct", "hit_t5", "t_stat", + "dex_publish_delay_s", "notes"] + + +def result_row(r: LeadResult) -> list: + return [r.symbol, r.verdict, r.cex, r.pool, f"{r.seconds / 60:.1f}", r.cex_trades, r.dex_trades, r.events, + r.best_lag, f"{r.corr.get(0, 0):.3f}", f"{r.corr.get(1, 0):.3f}", f"{r.corr.get(2, 0):.3f}", + f"{r.corr.get(-1, 0):.3f}", f"{r.same_second:+.3f}", f"{r.follow.get(3, 0):+.3f}", + f"{r.follow.get(5, 0):+.3f}", f"{r.follow.get(10, 0):+.3f}", f"{r.hit.get(5, 0):.2f}", + f"{r.t_stat:+.2f}", f"{r.dex_delay_s:.0f}", "; ".join(r.notes)] + + +def save_results(results: list[LeadResult], path: Path = RESULTS_CSV) -> None: + with path.open("w", newline="", encoding="utf-8-sig") as f: + w = csv.writer(f, delimiter=";") + w.writerow(RESULT_COLUMNS) + w.writerows(result_row(r) for r in results) + + +def print_results(results: list[LeadResult]) -> None: + print(f"\n{'Монета':10s} {'Вывод':30s} {'Фьючерс':8s} {'DEX':18s} {'Движ.':>5s} {'Лаг':>4s} " + f"{'Та же с':>8s} {'t+1→t+5':>8s} {'Попад.':>6s} {'t':>6s} {'Задержка':>8s}") + for r in results: + print(f"{r.symbol:10s} {r.verdict:30s} {r.cex:8s} {r.pool[:18]:18s} {r.events:5d} {r.best_lag:+4d} " + f"{r.same_second:+7.3f}% {r.follow.get(5, 0):+7.3f}% {r.hit.get(5, 0) * 100:5.0f}% {r.t_stat:+6.2f} " + f"{r.dex_delay_s:7.0f}с") + + +def open_window(parent, get_matches) -> None: + """'Опережение DEX' dialog for the Meme Matcher window: pick coins, record N minutes, show the verdicts.""" + import tkinter as tk + from tkinter import ttk + + win = tk.Toplevel(parent) + win.title("Опережение DEX → фьючерсы") + win.geometry("1200x560") + form = ttk.Frame(win, padding=6) + form.pack(fill="x") + minutes, coins, min_txns, thr = (tk.StringVar(value=v) for v in ("20", "10", "120", "0.15")) + for label, var in (("Минут записи", minutes), ("Монет (до 13)", coins), ("Мин. сделок в пуле за час", min_txns), + ("Движение DEX за 1 с, %", thr)): + ttk.Label(form, text=label).pack(side="left", padx=(0, 4)) + ttk.Entry(form, textvariable=var, width=7).pack(side="left", padx=(0, 10)) + start_btn = ttk.Button(form, text="Записать и проверить") + start_btn.pack(side="left", padx=4) + stop_btn = ttk.Button(form, text="Остановить", state="disabled") + stop_btn.pack(side="left") + columns = {"symbol": ("Монета", 80), "verdict": ("Вывод", 210), "cex": ("Фьючерс", 70), "pool": ("Пул DEX", 140), + "events": ("Движений DEX", 90), "lag": ("Лучший лаг, с", 85), "same": ("Та же секунда", 90), + "follow": ("После t+1 → t+5", 105), "hit": ("Попадание", 75), "t": ("t-стат.", 60), + "delay": ("Задержка данных DEX", 125)} + tree = ttk.Treeview(win, columns=list(columns), show="headings", height=14) + for key, (title, width) in columns.items(): + tree.heading(key, text=title) + tree.column(key, width=width, anchor="w") + tree.tag_configure("lead", background="#e8f7e8") + tree.pack(fill="both", expand=True, padx=6) + status = tk.StringVar(value="Берутся монеты со статусом «совпадает», пулом на Solana/BSC/Base и фьючерсом на " + "Binance/Bybit/Gate/MEXC. «После t+1 → t+5» — движение фьючерса в сторону DEX, " + "начиная со следующей секунды после движения на DEX.") + ttk.Label(win, textvariable=status, padding=6, wraplength=1150).pack(fill="x") + stop_event = threading.Event() + + def show(results): + tree.delete(*tree.get_children()) + for r in results: + tree.insert("", "end", tags=("lead",) if r.verdict.startswith("DEX опережает") else (), values=( + r.symbol, r.verdict, r.cex, r.pool, r.events, f"{r.best_lag:+d}", f"{r.same_second:+.3f}%", + f"{r.follow.get(5, 0):+.3f}%", f"{r.hit.get(5, 0) * 100:.0f}%", f"{r.t_stat:+.2f}", + f"{r.dex_delay_s:.0f} с")) + + def log(text): + win.after(0, status.set, text) + + def start(): + matches = get_matches() + if not matches: + status.set("Сначала дождитесь сканирования в главном окне") + return + try: + n_min, n_coins = float(minutes.get()), max(1, min(13, int(coins.get()))) + n_txns, threshold = int(min_txns.get()), float(thr.get()) + except ValueError: + status.set("Проверьте числа в полях") + return + targets = pick_targets(matches, n_coins, n_txns) + if not targets: + status.set("Нет подходящих монет — уменьшите «Мин. сделок в пуле за час»") + return + stop_event.clear() + start_btn.configure(state="disabled") + stop_btn.configure(state="normal") + + def work(): + rec = record(targets, n_min, log, stop_event) + path = rec.save() + results = analyze(targets, rec.cex, rec.dex, rec.gaps, threshold) + save_results(results) + win.after(0, finish, results, path) + + threading.Thread(target=work, daemon=True).start() + + def finish(results, path): + start_btn.configure(state="normal") + stop_btn.configure(state="disabled") + show(results) + leaders = [r.symbol for r in results if r.verdict.startswith("DEX опережает")] + status.set(f"Запись: {path.name} · результаты: {RESULTS_CSV.name} · DEX опережает: " + f"{', '.join(leaders) if leaders else 'не найдено'}") + + start_btn.configure(command=start) + stop_btn.configure(command=lambda: (stop_event.set(), status.set("Останавливаю и считаю…"))) + + +def main() -> None: + import sys + + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + parser = argparse.ArgumentParser(description="DEX → CEX futures lead-lag for memecoins") + parser.add_argument("--minutes", type=float, default=20) + parser.add_argument("--coins", type=int, default=10) + parser.add_argument("--min-txns", type=int, default=120, help="min swaps per hour in the DEX pool") + parser.add_argument("--threshold", type=float, default=0.15, help="DEX move in one second, %%") + parser.add_argument("--analyze", type=Path, help="analyse an existing recording instead of recording") + args = parser.parse_args() + if args.analyze: + targets, cex, dex, meta = load(args.analyze) + results = analyze(targets, cex, dex, meta.get("gaps"), args.threshold) + else: + matches = mm.scan() + targets = pick_targets(matches, args.coins, args.min_txns) + if not targets: + print("Нет подходящих монет (совпадение цены, пул на Solana/BSC/Base, достаточно сделок в час)") + return + print("Монеты для записи:") + for t in targets: + print(f" {t.symbol:10s} {t.cex:8s} {t.cex_symbol:16s} {t.chain}/{t.dex} пул {t.pool[:10]}… " + f"сделок в час {t.txns_h1}") + rec = record(targets, args.minutes) + path = rec.save() + print(f"Запись: {path}") + for e in rec.errors: + print(" ошибка:", e) + results = analyze(targets, rec.cex, rec.dex, rec.gaps, args.threshold) + save_results(results) + print_results(results) + print(f"\nCSV: {RESULTS_CSV}") + + +if __name__ == "__main__": + main() diff --git a/LinuxServer/meme_matcher/meme_matcher.py b/LinuxServer/meme_matcher/meme_matcher.py new file mode 100644 index 0000000..83ebe15 --- /dev/null +++ b/LinuxServer/meme_matcher/meme_matcher.py @@ -0,0 +1,714 @@ +"""Meme Matcher: the same memecoins on CEX perpetual futures and on DEX spot. + +Sources (public APIs, no keys): +* CEX USDT perpetuals: Bybit, Binance, OKX, Gate, MEXC, Bitget, BingX - symbol, price, 24h volume, funding. +* CoinGecko category "meme-token" - which coins are memecoins, their market cap and contract addresses. +* DexScreener - the most liquid DEX pair of each contract (Solana, Ethereum, BSC, Base, Arbitrum, ...). +* HyperLiquid spot - matched by token name and price. + +A ticker alone does not identify a coin (CoinGecko has 21 different "PEPE" tokens), so a CEX symbol is tied to +the meme token with the same symbol whose price agrees with the CEX price, and the DEX pair is looked up by that +token's contract address. The DEX price is compared with the CEX price again: a large gap means a different coin. + +Run: py -3 meme_matcher.py (window) + py -3 meme_matcher.py --once (console table + meme_matches.csv) +""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +import re +import statistics +import threading +import time +import urllib.error +import urllib.request +import webbrowser +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +CACHE_DIR = ROOT / "cache" +OUT_CSV = ROOT / "meme_matches.csv" +USER_AGENT = "Mozilla/5.0 (meme-matcher)" + +MATCH_PCT = 5.0 # DEX vs CEX price within this -> "совпадает" +CHECK_PCT = 25.0 # up to this -> "проверить"; beyond -> probably a different coin +SYMBOL_PRICE_TOL = 0.5 # CoinGecko vs CEX price: |log ratio| below ln(1.5) still counts as the same coin + +# CoinGecko platform id -> DexScreener chain id +CHAINS = { + "solana": "solana", "ethereum": "ethereum", "binance-smart-chain": "bsc", "base": "base", + "arbitrum-one": "arbitrum", "polygon-pos": "polygon", "avalanche": "avalanche", "optimistic-ethereum": "optimism", + "the-open-network": "ton", "sui": "sui", "tron": "tron", "hyperevm": "hyperevm", "blast": "blast", + "fantom": "fantom", "sonic": "sonic", "mantle": "mantle", "cronos": "cronos", "linea": "linea", + "zksync": "zksync", "abstract": "abstract", "berachain": "berachain", "aptos": "aptos", "near-protocol": "near", + "pulsechain": "pulsechain", "unichain": "unichain", "monad": "monad", "plasma": "plasma", +} +EVM_CHAINS = {"ethereum", "bsc", "base", "arbitrum", "polygon", "avalanche", "optimism", "hyperevm", "blast", + "fantom", "sonic", "mantle", "cronos", "linea", "zksync", "abstract", "berachain", "pulsechain", + "unichain", "monad", "plasma"} + + +# -------------------------------------------------------------------------------------------- +# HTTP +# -------------------------------------------------------------------------------------------- + +def http_json(url: str, body: dict | None = None, retries: int = 3, timeout: float = 30): + data = json.dumps(body).encode() if body is not None else None + for attempt in range(retries): + req = urllib.request.Request(url, data=data, headers={"User-Agent": USER_AGENT, + "Content-Type": "application/json", + "Accept": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read()) + except urllib.error.HTTPError as exc: + if exc.code == 429 and attempt < retries - 1: # rate limit (CoinGecko free tier) + time.sleep(20 * (attempt + 1)) + continue + raise + except (urllib.error.URLError, TimeoutError): + if attempt < retries - 1: + time.sleep(2) + continue + raise + return None + + +# -------------------------------------------------------------------------------------------- +# CEX perpetual futures +# -------------------------------------------------------------------------------------------- + +@dataclass +class Listing: + exchange: str + symbol: str # as the exchange names it + base: str # coin ticker without the size prefix, upper case + multiplier: float # 1000PEPE -> 1000 (one contract unit = 1000 coins) + price: float # price of ONE coin + volume_usd: float + funding: float | None = None + + +_PREFIX = re.compile(r"^(1000000|100000|10000|1000|100|1M)(?=[A-Z])") +_SUFFIX = re.compile(r"^([A-Z][A-Z0-9]*?)(1000000|10000|1000)$") + + +def split_base(raw: str) -> tuple[str, float]: + """'1000PEPE' -> ('PEPE', 1000); '1MBABYDOGE' -> ('BABYDOGE', 1e6); 'SHIB1000' -> ('SHIB', 1000); '1INCH' stays.""" + raw = raw.upper() + m = _PREFIX.match(raw) + if m: + mult = 1_000_000.0 if m.group(1) == "1M" else float(m.group(1)) + return raw[m.end():], mult + m = _SUFFIX.match(raw) + if m and len(m.group(1)) >= 2: + return m.group(1), float(m.group(2)) + return raw, 1.0 + + +def _f(value, default=0.0) -> float: + try: + return float(value) + except (TypeError, ValueError): + return default + + +def _listing(exchange: str, symbol: str, raw_base: str, price, volume_usd, funding=None) -> Listing | None: + base, mult = split_base(raw_base) + price = _f(price) + if not base or price <= 0: + return None + return Listing(exchange, symbol, base, mult, price / mult, _f(volume_usd), + None if funding in (None, "") else _f(funding)) + + +def parse_bybit(data) -> list[Listing]: + out = [] + for t in data["result"]["list"]: + s = t["symbol"] + if s.endswith("USDT"): + out.append(_listing("Bybit", s, s[:-4], t.get("lastPrice"), t.get("turnover24h"), t.get("fundingRate"))) + return [x for x in out if x] + + +def parse_binance(data) -> list[Listing]: + out = [] + for t in data: + s = t["symbol"] + if s.endswith("USDT") and "_" not in s: + out.append(_listing("Binance", s, s[:-4], t.get("lastPrice"), t.get("quoteVolume"))) + return [x for x in out if x] + + +def parse_okx(data) -> list[Listing]: + out = [] + for t in data["data"]: + s = t["instId"] + if s.endswith("-USDT-SWAP"): + last = _f(t.get("last")) + out.append(_listing("OKX", s, s[:-10], last, _f(t.get("volCcy24h")) * last)) + return [x for x in out if x] + + +def parse_gate(data) -> list[Listing]: + out = [] + for t in data: + s = t["contract"] + if s.endswith("_USDT"): + out.append(_listing("Gate", s, s[:-5], t.get("last"), t.get("volume_24h_quote"), t.get("funding_rate"))) + return [x for x in out if x] + + +def parse_mexc(data) -> list[Listing]: + out = [] + for t in data["data"]: + s = t["symbol"] + if s.endswith("_USDT"): + out.append(_listing("MEXC", s, s[:-5], t.get("lastPrice"), t.get("amount24"), t.get("fundingRate"))) + return [x for x in out if x] + + +def parse_bitget(data) -> list[Listing]: + out = [] + for t in data["data"]: + s = t["symbol"] + if s.endswith("USDT"): + out.append(_listing("Bitget", s, s[:-4], t.get("lastPr"), t.get("usdtVolume"), t.get("fundingRate"))) + return [x for x in out if x] + + +def parse_bingx(data) -> list[Listing]: + out = [] + for t in data["data"]: + s = t["symbol"] + if s.endswith("-USDT"): + out.append(_listing("BingX", s, s[:-5], t.get("lastPrice"), t.get("quoteVolume"))) + return [x for x in out if x] + + +CEX_SOURCES = { + "Bybit": ("https://api.bybit.com/v5/market/tickers?category=linear", parse_bybit), + "Gate": ("https://api.gateio.ws/api/v4/futures/usdt/tickers", parse_gate), + "MEXC": ("https://contract.mexc.com/api/v1/contract/ticker", parse_mexc), +} + + +def fetch_cex(exchanges: list[str], log=print) -> list[Listing]: + def one(name): + url, parser = CEX_SOURCES[name] + try: + items = parser(http_json(url)) + log(f"{name}: {len(items)} фьючерсов") + return items + except Exception as exc: # one exchange down must not stop the rest + log(f"{name}: ошибка {exc}") + return [] + + with ThreadPoolExecutor(max_workers=len(exchanges) or 1) as pool: + return [x for chunk in pool.map(one, exchanges) for x in chunk] + + +# -------------------------------------------------------------------------------------------- +# CoinGecko: which coins are memes, and their contracts +# -------------------------------------------------------------------------------------------- + +@dataclass +class MemeCoin: + cg_id: str + symbol: str # upper case + name: str + price: float + market_cap: float + platforms: dict[str, str] = field(default_factory=dict) # CoinGecko platform -> contract + + +def fetch_memes(pages: int, log=print) -> list[dict]: + rows = [] + for page in range(1, pages + 1): + chunk = http_json("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=meme-token" + f"&order=market_cap_desc&per_page=250&page={page}") or [] + rows += chunk + log(f"CoinGecko: мемкойнов {len(rows)}") + if len(chunk) < 250: + break + time.sleep(2.5) # free tier: a few requests per minute + return rows + + +def fetch_platforms(max_age_hours: float = 24, log=print) -> dict[str, dict[str, str]]: + """CoinGecko id -> {platform: contract}; the 4 MB list is cached for a day.""" + CACHE_DIR.mkdir(exist_ok=True) + path = CACHE_DIR / "coingecko_platforms.json" + if path.exists() and time.time() - path.stat().st_mtime < max_age_hours * 3600: + return json.loads(path.read_text(encoding="utf-8")) + data = http_json("https://api.coingecko.com/api/v3/coins/list?include_platform=true") or [] + platforms = {c["id"]: {k: v for k, v in (c.get("platforms") or {}).items() if k and v} for c in data} + path.write_text(json.dumps(platforms), encoding="utf-8") + log(f"CoinGecko: адреса контрактов {len(platforms)} монет") + return platforms + + +def build_memes(markets: list[dict], platforms: dict[str, dict[str, str]]) -> list[MemeCoin]: + out = [] + for m in markets: + price = _f(m.get("current_price")) + if not m.get("symbol") or price <= 0: + continue + out.append(MemeCoin(m["id"], m["symbol"].upper(), m.get("name") or m["id"], price, _f(m.get("market_cap")), + platforms.get(m["id"], {}))) + return out + + +def pick_coin(base: str, cex_price: float, memes_by_symbol: dict[str, list[MemeCoin]]) -> MemeCoin | None: + """The meme token behind a CEX ticker: same symbol, price closest to the CEX price (and not wildly off).""" + best, best_gap = None, None + for coin in memes_by_symbol.get(base.upper(), []): + gap = abs(math.log(coin.price / cex_price)) + if best_gap is None or gap < best_gap: + best, best_gap = coin, gap + if best is None or best_gap > math.log(1 + SYMBOL_PRICE_TOL) + 1e-12: + return None + return best + + +# -------------------------------------------------------------------------------------------- +# DEX +# -------------------------------------------------------------------------------------------- + +@dataclass +class DexPair: + source: str # DexScreener / HyperLiquid + chain: str + dex: str + pair: str # e.g. PEPE/WETH + price: float + liquidity_usd: float + volume_usd: float + contract: str + url: str + pair_address: str = "" + txns_h1: int = 0 # swaps in the last hour (DexScreener) + + +def best_pairs(pairs: list[dict]) -> dict[tuple[str, str], DexPair]: + """(chain, lower-case token address) -> its most liquid pair where the token is the BASE asset.""" + out: dict[tuple[str, str], DexPair] = {} + for p in pairs: + base = p.get("baseToken") or {} + price = _f(p.get("priceUsd")) + if not base.get("address") or price <= 0: + continue + key = (p.get("chainId", ""), base["address"].lower()) + liq = _f((p.get("liquidity") or {}).get("usd")) + if key in out and out[key].liquidity_usd >= liq: + continue + h1 = (p.get("txns") or {}).get("h1") or {} + out[key] = DexPair("DexScreener", p.get("chainId", ""), p.get("dexId", ""), + f"{base.get('symbol', '')}/{(p.get('quoteToken') or {}).get('symbol', '')}", price, liq, + _f((p.get("volume") or {}).get("h24")), base["address"], p.get("url", ""), + p.get("pairAddress", ""), int(_f(h1.get("buys")) + _f(h1.get("sells")))) + return out + + +def fetch_dexscreener(contracts: dict[str, set[str]], log=print) -> dict[tuple[str, str], list[DexPair]]: + """contracts: DexScreener chain -> addresses. One request per contract returns all its pools (DexScreener + allows ~300 requests a minute); the batch endpoint returns only one pool per token, often not the deepest.""" + jobs = [(chain, address) for chain, addresses in contracts.items() for address in sorted(addresses)] + + def one(job): + chain, address = job + try: + return http_json(f"https://api.dexscreener.com/token-pairs/v1/{chain}/{address}") or [] + except Exception as exc: + log(f"DexScreener {chain} {address[:10]}…: ошибка {exc}") + return [] + + with ThreadPoolExecutor(max_workers=4) as pool: + pairs = [p for chunk in pool.map(one, jobs) for p in chunk] + log(f"DexScreener: {len(pairs)} пар по {len(jobs)} контрактам") + return all_pairs(pairs) + + +def all_pairs(pairs: list[dict]) -> dict[tuple[str, str], list[DexPair]]: + """(chain, lower-case token address) -> every pool where the token is the BASE asset, deepest first.""" + out: dict[tuple[str, str], list[DexPair]] = {} + seen = set() + for p in pairs: + if p.get("pairAddress") in seen: + continue + seen.add(p.get("pairAddress")) + best = best_pairs([p]) + for key, pair in best.items(): + out.setdefault(key, []).append(pair) + for items in out.values(): + items.sort(key=lambda d: (-d.liquidity_usd, -d.volume_usd)) + return out + + +def parse_hyperliquid_spot(data) -> dict[str, DexPair]: + """Upper-case token name -> its USDC spot pair on HyperLiquid.""" + meta, ctxs = data + tokens = {t["index"]: t for t in meta["tokens"]} + out = {} + for market in meta["universe"]: + base_i, quote_i = market["tokens"] + if tokens.get(quote_i, {}).get("name") != "USDC" or market["index"] >= len(ctxs): + continue + ctx = ctxs[market["index"]] + price = _f(ctx.get("midPx")) or _f(ctx.get("markPx")) + name = tokens.get(base_i, {}).get("name", "").upper() + if not name or price <= 0: + continue + pair = DexPair("HyperLiquid", "hyperliquid", "hyperliquid", f"{name}/USDC", price, 0.0, + _f(ctx.get("dayNtlVlm")), tokens[base_i].get("tokenId", ""), + f"https://app.hyperliquid.xyz/trade/{market['name']}") + if name not in out or pair.volume_usd > out[name].volume_usd: + out[name] = pair + return out + + +def fetch_hyperliquid(log=print) -> dict[str, DexPair]: + try: + out = parse_hyperliquid_spot(http_json("https://api.hyperliquid.xyz/info", {"type": "spotMetaAndAssetCtxs"})) + log(f"HyperLiquid: спот-пар {len(out)}") + return out + except Exception as exc: + log(f"HyperLiquid: ошибка {exc}") + return {} + + +# -------------------------------------------------------------------------------------------- +# Matching +# -------------------------------------------------------------------------------------------- + +@dataclass +class Match: + symbol: str + name: str + cg_id: str + market_cap: float + cex: list[Listing] + cex_price: float # median price of one coin over the CEX listings + cex_volume_usd: float + dex: DexPair | None + dex_count: int # how many chains the token has a DEX pair on + diff_pct: float | None # (DEX - CEX) / CEX + status: str + pools: list[DexPair] = field(default_factory=list) # every DEX pool whose price agrees with the CEX + + @property + def exchanges(self) -> str: + return ", ".join(sorted(f"{l.exchange}" + (f"×{l.multiplier:g}" if l.multiplier != 1 else "") + for l in self.cex)) + + @property + def funding(self) -> float | None: + values = [l.funding for l in self.cex if l.funding is not None] + return max(values, key=abs) if values else None + + +def status_of(diff_pct: float | None) -> str: + if diff_pct is None: + return "нет на DEX" + if abs(diff_pct) <= MATCH_PCT: + return "совпадает" + if abs(diff_pct) <= CHECK_PCT: + return "проверить" + return "разные монеты?" + + +def contracts_for(coins: list[MemeCoin]) -> dict[str, set[str]]: + out: dict[str, set[str]] = {} + for coin in coins: + for platform, address in coin.platforms.items(): + chain = CHAINS.get(platform) + if chain: + out.setdefault(chain, set()).add(address.lower() if chain in EVM_CHAINS else address) + return out + + +def _agrees(price: float, ref: float, pct: float = CHECK_PCT) -> bool: + return price > 0 and ref > 0 and abs(math.log(price / ref)) <= math.log(1 + pct / 100) + + +def match(listings: list[Listing], memes: list[MemeCoin], dex_pairs: dict[tuple[str, str], list[DexPair]], + hl_pairs: dict[str, DexPair]) -> list[Match]: + by_symbol: dict[str, list[MemeCoin]] = {} + for coin in memes: + by_symbol.setdefault(coin.symbol, []).append(coin) + # Each CEX contract is tied to a coin by its own price: CAT and 1000CAT on one exchange can be two coins. + groups: dict[str, tuple[MemeCoin, list[Listing]]] = {} + for l in listings: + coin = pick_coin(l.base, l.price, by_symbol) + if coin is not None: + groups.setdefault(coin.cg_id, (coin, []))[1].append(l) + out = [] + for coin, items in groups.values(): + cex_price = statistics.median(l.price for l in items) + pools = [] + for platform, address in coin.platforms.items(): + chain = CHAINS.get(platform) + if chain: + pools += dex_pairs.get((chain, address.lower()), []) + hl = hl_pairs.get(coin.symbol) + if hl and _agrees(hl.price, cex_price): + pools.append(hl) + # The deepest pool whose price agrees with the CEX; a lone disagreeing pool is still shown, flagged. + agreeing = [p for p in pools if _agrees(p.price, cex_price)] + candidates = agreeing or pools + dex = max(candidates, key=lambda p: (p.liquidity_usd, p.volume_usd)) if candidates else None + diff = (dex.price / cex_price - 1) * 100 if dex else None + chains = len({p.chain for p in agreeing}) + out.append(Match(coin.symbol, coin.name, coin.cg_id, coin.market_cap, items, cex_price, + sum(l.volume_usd for l in items), dex, chains, diff, status_of(diff), agreeing)) + out.sort(key=lambda m: -m.cex_volume_usd) + return out + + +def scan(exchanges: list[str] | None = None, meme_pages: int = 4, log=print) -> list[Match]: + exchanges = exchanges or list(CEX_SOURCES) + listings = fetch_cex(exchanges, log) + memes = build_memes(fetch_memes(meme_pages, log), fetch_platforms(log=log)) + bases = {l.base for l in listings} + wanted = [c for c in memes if c.symbol in bases] + log(f"Мемкойнов с фьючерсами на CEX (по тикеру): {len(wanted)}") + dex_pairs = fetch_dexscreener(contracts_for(wanted), log) + hl_pairs = fetch_hyperliquid(log) + result = match(listings, wanted, dex_pairs, hl_pairs) + log(f"Готово: совпадений {len(result)}, из них на DEX {sum(m.dex is not None for m in result)}") + return result + + +# -------------------------------------------------------------------------------------------- +# Output +# -------------------------------------------------------------------------------------------- + +CSV_COLUMNS = ["symbol", "name", "coingecko_id", "market_cap_usd", "cex_exchanges", "cex_price", "cex_volume_24h_usd", + "max_funding", "dex_source", "dex_chain", "dex", "dex_pair", "dex_price", "dex_liquidity_usd", + "dex_volume_24h_usd", "dex_chains", "diff_pct", "status", "contract", "url"] + + +def to_row(m: Match) -> list: + d = m.dex + return [m.symbol, m.name, m.cg_id, f"{m.market_cap:.0f}", m.exchanges, f"{m.cex_price:.10g}", + f"{m.cex_volume_usd:.0f}", "" if m.funding is None else f"{m.funding:.6f}", + d.source if d else "", d.chain if d else "", d.dex if d else "", d.pair if d else "", + f"{d.price:.10g}" if d else "", f"{d.liquidity_usd:.0f}" if d else "", f"{d.volume_usd:.0f}" if d else "", + m.dex_count, "" if m.diff_pct is None else f"{m.diff_pct:+.2f}", m.status, d.contract if d else "", + d.url if d else ""] + + +def save_csv(matches: list[Match], path: Path = OUT_CSV) -> None: + with path.open("w", newline="", encoding="utf-8-sig") as f: + writer = csv.writer(f, delimiter=";") + writer.writerow(CSV_COLUMNS) + writer.writerows(to_row(m) for m in matches) + + +def human(value: float) -> str: + for unit, size in (("B", 1e9), ("M", 1e6), ("K", 1e3)): + if abs(value) >= size: + return f"{value / size:.1f}{unit}" + return f"{value:.0f}" + + +def print_table(matches: list[Match]) -> None: + print(f"{'Монета':12s} {'CEX фьючерсы':38s} {'Объём CEX':>9s} {'DEX':24s} {'Ликв.':>7s} {'Разница':>8s} Статус") + for m in matches: + d = m.dex + dex = f"{d.chain}/{d.dex}" if d else "—" + print(f"{m.symbol:12s} {m.exchanges[:38]:38s} {human(m.cex_volume_usd):>9s} {dex[:24]:24s} " + f"{human(d.liquidity_usd) if d else '':>7s} {'' if m.diff_pct is None else f'{m.diff_pct:+.2f}%':>8s} " + f"{m.status}") + + +# -------------------------------------------------------------------------------------------- +# Window +# -------------------------------------------------------------------------------------------- + +def run_window() -> None: + import tkinter as tk + from tkinter import messagebox, ttk + + root = tk.Tk() + root.title("Meme Matcher — мемкойны: фьючерсы CEX ↔ спот DEX") + root.geometry("1280x720") + state: dict = {"matches": [], "sort": ("cex_volume", True)} + + top = ttk.Frame(root, padding=6) + top.pack(fill="x") + ex_vars = {name: tk.BooleanVar(value=True) for name in CEX_SOURCES} + ttk.Label(top, text="Биржи:").pack(side="left") + for name, var in ex_vars.items(): + ttk.Checkbutton(top, text=name, variable=var).pack(side="left") + filters = ttk.Frame(root, padding=(6, 0)) + filters.pack(fill="x") + min_liq = tk.StringVar(value="10000") + min_vol = tk.StringVar(value="0") + pages = tk.StringVar(value="4") + only_dex = tk.BooleanVar(value=True) + only_match = tk.BooleanVar(value=False) + for label, var, width in (("Мин. ликвидность DEX, $", min_liq, 10), ("Мин. объём CEX за 24 ч, $", min_vol, 12), + ("Страниц мемов CoinGecko (×250)", pages, 4)): + ttk.Label(filters, text=label).pack(side="left", padx=(0, 4)) + ttk.Entry(filters, textvariable=var, width=width).pack(side="left", padx=(0, 12)) + ttk.Checkbutton(filters, text="Только есть на DEX", variable=only_dex, command=lambda: fill()).pack(side="left") + ttk.Checkbutton(filters, text="Только «совпадает»", variable=only_match, command=lambda: fill()).pack(side="left") + scan_btn = ttk.Button(filters, text="Обновить", command=lambda: start()) + scan_btn.pack(side="left", padx=8) + ttk.Button(filters, text="Сохранить CSV", command=lambda: export()).pack(side="left") + ttk.Button(filters, text="Опережение DEX…", command=lambda: open_leadlag()).pack(side="left", padx=8) + ttk.Button(filters, text="Автопоиск…", command=lambda: __import__("autoscan").open_window(root)).pack(side="left") + + def open_leadlag(): + import leadlag + leadlag.open_window(root, lambda: state["matches"]) + + columns = {"symbol": ("Монета", 90), "name": ("Название", 140), "cex": ("Фьючерсы CEX", 250), + "cex_volume": ("Объём CEX 24 ч", 100), "funding": ("Funding", 70), "dex": ("DEX", 150), + "pair": ("Пара", 110), "liquidity": ("Ликвидность", 90), "dex_volume": ("Объём DEX", 90), + "diff": ("Разница", 70), "status": ("Статус", 110), "mcap": ("Капитализация", 100)} + frame = ttk.Frame(root, padding=6) + frame.pack(fill="both", expand=True) + tree = ttk.Treeview(frame, columns=list(columns), show="headings") + for key, (title, width) in columns.items(): + tree.heading(key, text=title, command=lambda k=key: sort_by(k)) + tree.column(key, width=width, anchor="w") + tree.tag_configure("совпадает", background="#e8f7e8") + tree.tag_configure("проверить", background="#fff6d8") + tree.tag_configure("разные монеты?", background="#fde3e3") + scroll = ttk.Scrollbar(frame, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scroll.set) + tree.pack(side="left", fill="both", expand=True) + scroll.pack(side="right", fill="y") + status = tk.StringVar(value="Нажмите «Обновить». Двойной щелчок по строке открывает пару на DEX.") + ttk.Label(root, textvariable=status, padding=6).pack(fill="x") + + def keyf(m: Match, key: str): + d = m.dex + return {"symbol": m.symbol, "name": m.name, "cex": m.exchanges, "cex_volume": m.cex_volume_usd, + "funding": abs(m.funding or 0), "dex": f"{d.chain}/{d.dex}" if d else "", "pair": d.pair if d else "", + "liquidity": d.liquidity_usd if d else -1, "dex_volume": d.volume_usd if d else -1, + "diff": abs(m.diff_pct) if m.diff_pct is not None else 1e9, "status": m.status, + "mcap": m.market_cap}[key] + + def sort_by(key): + prev, desc = state["sort"] + state["sort"] = (key, not desc if prev == key else key in ("cex_volume", "liquidity", "dex_volume", "mcap")) + fill() + + def visible() -> list[Match]: + try: + liq, vol = float(min_liq.get() or 0), float(min_vol.get() or 0) + except ValueError: + liq = vol = 0.0 + out = [] + for m in state["matches"]: + if only_dex.get() and m.dex is None: + continue + if only_match.get() and m.status != "совпадает": + continue + if m.dex is not None and m.dex.source == "DexScreener" and m.dex.liquidity_usd < liq: + continue + if m.cex_volume_usd < vol: + continue + out.append(m) + key, desc = state["sort"] + return sorted(out, key=lambda m: keyf(m, key), reverse=desc) + + def fill(): + tree.delete(*tree.get_children()) + rows = visible() + for i, m in enumerate(rows): + d = m.dex + tree.insert("", "end", iid=str(i), tags=(m.status,), values=( + m.symbol, m.name, m.exchanges, human(m.cex_volume_usd), + "" if m.funding is None else f"{m.funding * 100:+.3f}%", + f"{d.chain}/{d.dex}" + (f" (+{m.dex_count - 1})" if m.dex_count > 1 else "") if d else "—", + d.pair if d else "", human(d.liquidity_usd) if d and d.liquidity_usd else ("" if not d else "—"), + human(d.volume_usd) if d else "", "" if m.diff_pct is None else f"{m.diff_pct:+.2f}%", m.status, + human(m.market_cap))) + state["rows"] = rows + total = len(state["matches"]) + on_dex = sum(m.dex is not None for m in state["matches"]) + same = sum(m.status == "совпадает" for m in state["matches"]) + if total: + status.set(f"Мемкойнов с фьючерсами: {total} · есть на DEX: {on_dex} · цена совпадает: {same} · " + f"показано: {len(rows)}") + + def open_row(_event=None): + sel = tree.selection() + if sel: + m = state["rows"][int(sel[0])] + if m.dex and m.dex.url: + webbrowser.open(m.dex.url) + + tree.bind("", open_row) + + def log(text): + root.after(0, status.set, text) + + def start(): + chosen = [n for n, v in ex_vars.items() if v.get()] + if not chosen: + messagebox.showwarning("Meme Matcher", "Выберите хотя бы одну биржу", parent=root) + return + try: + n_pages = max(1, min(20, int(pages.get()))) + except ValueError: + n_pages = 4 + scan_btn.configure(state="disabled") + + def work(): + try: + result = scan(chosen, n_pages, log) + save_csv(result) + root.after(0, done, result, "") + except Exception as exc: + root.after(0, done, None, str(exc)) + + threading.Thread(target=work, daemon=True).start() + + def done(result, error): + scan_btn.configure(state="normal") + if error: + status.set(f"Ошибка: {error}") + return + state["matches"] = result + fill() + + def export(): + save_csv(visible()) + status.set(f"Сохранено: {OUT_CSV}") + + root.after(200, start) + root.mainloop() + + +def main() -> None: + import sys + + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--once", action="store_true", help="print the table and save meme_matches.csv") + parser.add_argument("--pages", type=int, default=4, help="CoinGecko meme pages of 250 coins") + parser.add_argument("--exchanges", default=",".join(CEX_SOURCES), help="comma-separated CEX list") + args = parser.parse_args() + if args.once: + matches = scan([e for e in args.exchanges.split(",") if e in CEX_SOURCES], args.pages) + save_csv(matches) + print_table([m for m in matches if m.dex is not None]) + print(f"\nCSV: {OUT_CSV}") + else: + run_window() + + +if __name__ == "__main__": + main() diff --git a/LinuxServer/minorder.py b/LinuxServer/minorder.py new file mode 100644 index 0000000..cf7ce3a --- /dev/null +++ b/LinuxServer/minorder.py @@ -0,0 +1,224 @@ +"""The smallest orders the five exchanges accept, spot and USDT perpetual, and from them the smallest trade amount a +spot–futures trade can be entered with: the spot buy must reach the spot minimum (USDT and coins) and the coins +bought must make at least the perp's minimum lot (and its minimum notional) — both legs, or the trade is not made. + +The rules come from the exchanges' public instrument lists (no keys), loaded in the background and renewed hourly. +Paper and real trading check the same figure, so the paper trades are only those a real account could make. +""" + +from __future__ import annotations + +import math +import threading +import time + +import arb + +REFRESH_S = 3600.0 +RETRY_S = 300.0 +MARGIN = 1.02 # prices move between the check and the order, and the lot is rounded down +AUTOLOAD = False # the program turns it on; tests fill the rules themselves (no network) + + +def _f(v, default: float = 0.0) -> float: + try: + return float(v) + except (TypeError, ValueError): + return default + + +def _units(symbol_base: str) -> float: + return arb.split_base(symbol_base)[1] + + +# --- loaders: {key: rule}; spot keyed by base coin, perp by the symbol the price lists use -------------------------- +# spot rule: {"usd": smallest order in USDT, "coins": smallest quantity}; perp rule: {"coins": smallest order in +# coins (lot × contract size), "usd": smallest notional} +def _bybit(category: str) -> dict: + out, cursor = {}, "" + while True: + res = arb._get(f"https://api.bybit.com/v5/market/instruments-info?category={category}&limit=1000" + + (f"&cursor={cursor}" if cursor else ""))["result"] + for x in res["list"]: + if x.get("quoteCoin") != "USDT" or x.get("status") != "Trading": + continue + lot = x.get("lotSizeFilter") or {} + if category == "spot": + out[x["baseCoin"]] = {"usd": _f(lot.get("minOrderAmt")), "coins": _f(lot.get("minOrderQty"))} + else: + out[x["symbol"]] = {"coins": max(_f(lot.get("minOrderQty")), _f(lot.get("qtyStep"))) + * _units(x["symbol"][:-4]), "usd": _f(lot.get("minNotionalValue"))} + cursor = res.get("nextPageCursor") or "" + if not cursor or not res["list"]: + return out + + +def _binance_spot() -> dict: + out = {} + for s in arb._get("https://api.binance.com/api/v3/exchangeInfo?symbolStatus=TRADING")["symbols"]: + if s.get("quoteAsset") != "USDT": + continue + f = {x["filterType"]: x for x in s.get("filters", [])} + notional = f.get("NOTIONAL") or f.get("MIN_NOTIONAL") or {} + out[s["baseAsset"]] = {"usd": _f(notional.get("minNotional")), "coins": _f((f.get("LOT_SIZE") or {}).get("minQty"))} + return out + + +def _binance_fut() -> dict: + out = {} + for s in arb._get("https://fapi.binance.com/fapi/v1/exchangeInfo")["symbols"]: + if s.get("quoteAsset") != "USDT" or s.get("status") != "TRADING": + continue + f = {x["filterType"]: x for x in s.get("filters", [])} + lot = f.get("MARKET_LOT_SIZE") if _f((f.get("MARKET_LOT_SIZE") or {}).get("stepSize")) > 0 else f.get("LOT_SIZE", {}) + out[s["symbol"]] = {"coins": max(_f(lot.get("minQty")), _f(lot.get("stepSize"))) * _units(s["symbol"][:-4]), + "usd": _f((f.get("MIN_NOTIONAL") or {}).get("notional"))} + return out + + +def _mexc_spot() -> dict: + out = {} + for s in arb._get("https://api.mexc.com/api/v3/exchangeInfo")["symbols"]: + if s.get("quoteAsset") != "USDT": + continue + out[s["baseAsset"]] = {"usd": _f(s.get("quoteAmountPrecisionMarket") or s.get("quoteAmountPrecision")), + "coins": _f(s.get("baseSizePrecision"))} + return out + + +def _mexc_fut() -> dict: + out = {} + for c in arb._get("https://contract.mexc.com/api/v1/contract/detail")["data"]: + if c.get("quoteCoin") != "USDT": + continue + out[c["symbol"]] = {"coins": _f(c.get("contractSize"), 1) * _units(c["symbol"][:-5]) * max(1.0, _f(c.get("minVol"), 1)), + "usd": 0.0} + return out + + +def _htx_spot() -> dict: + out = {} + for s in arb._get("https://api.huobi.pro/v1/settings/common/market-symbols")["data"]: + if s.get("qc") != "usdt" or s.get("state") != "online": + continue + # market buy: «minov» USDT; the market sale later: «smminoa» coins + out[s["bc"].upper()] = {"usd": _f(s.get("minov")), "coins": _f(s.get("smminoa") or s.get("minoa"))} + return out + + +def _htx_fut() -> dict: + out = {} + for c in arb._get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]: + if not c["contract_code"].endswith("-USDT"): + continue + out[c["contract_code"]] = {"coins": _f(c.get("contract_size"), 1) * _units(c["contract_code"][:-5]), "usd": 0.0} + return out + + +def _gate_spot() -> dict: + out = {} + for s in arb._get("https://api.gateio.ws/api/v4/spot/currency_pairs"): + if s.get("quote") != "USDT" or s.get("trade_status") not in (None, "tradable"): + continue + out[s["base"]] = {"usd": _f(s.get("min_quote_amount")), "coins": _f(s.get("min_base_amount"))} + return out + + +def _gate_fut() -> dict: + out = {} + for c in arb._get("https://api.gateio.ws/api/v4/futures/usdt/contracts"): + out[c["name"]] = {"coins": _f(c.get("quanto_multiplier"), 1) * _units(c["name"][:-5]) + * max(1.0, _f(c.get("order_size_min"), 1)), "usd": 0.0} + return out + + +LOADERS = {("Bybit", "spot"): lambda: _bybit("spot"), ("Bybit", "fut"): lambda: _bybit("linear"), + ("Binance", "spot"): _binance_spot, ("Binance", "fut"): _binance_fut, + ("MEXC", "spot"): _mexc_spot, ("MEXC", "fut"): _mexc_fut, + ("HTX", "spot"): _htx_spot, ("HTX", "fut"): _htx_fut, + ("Gate", "spot"): _gate_spot, ("Gate", "fut"): _gate_fut} + + +class Rules: + def __init__(self) -> None: + self.data: dict[tuple[str, str], dict] = {} + self.loaded: dict[tuple[str, str], float] = {} # when loaded (or when the last try failed) + self.loading: set = set() + self.lock = threading.Lock() + + def set(self, exchange: str, market: str, rules: dict) -> None: + with self.lock: + self.data[(exchange, market)] = rules + self.loaded[(exchange, market)] = time.time() + + def _get(self, exchange: str, market: str) -> dict: + key = (exchange, market) + if AUTOLOAD and key in LOADERS: + with self.lock: + stale = time.time() - self.loaded.get(key, 0.0) > (REFRESH_S if key in self.data else RETRY_S) + start = stale and key not in self.loading + if start: + self.loading.add(key) + if start: + threading.Thread(target=self._load, args=(key,), daemon=True).start() + return self.data.get(key) or {} + + def _load(self, key) -> None: + try: + rules = LOADERS[key]() + if rules: + self.set(*key, rules) + except Exception: + with self.lock: + self.loaded[key] = time.time() # tried: again in RETRY_S + finally: + with self.lock: + self.loading.discard(key) + + def spot(self, exchange: str, base: str) -> dict | None: + return self._get(exchange, "spot").get(base) + + def fut(self, exchange: str, symbol: str) -> dict | None: + return self._get(exchange, "fut").get(symbol) + + def min_entry(self, spot_ex: str, base: str, spot_ask: float, fut_ex: str, fut_symbol: str, fut_bid: float, + spot_fee_pct: float) -> dict | None: + """The smallest trade amount, $, both legs accept: {"usd": total, "spot": $ the spot leg needs (None: + unknown), "fut": $ the perp leg needs}; None when neither exchange's rules are known yet.""" + sr, fr = self.spot(spot_ex, base), self.fut(fut_ex, fut_symbol) + if sr is None and fr is None or spot_ask <= 0 or fut_bid <= 0: + return None + keep = 1 - spot_fee_pct / 100 # the buy fee is taken in coins + spot_usd = None if sr is None else max(sr["usd"], sr["coins"] * spot_ask / keep) + fut_usd = None + if fr is not None: # the coins bought must make the perp's smallest order + coins = max(fr["coins"], fr["usd"] / fut_bid if fr["usd"] else 0.0) + fut_usd = coins * spot_ask / keep + need = max(v for v in (spot_usd, fut_usd) if v is not None) * MARGIN + return {"usd": math.ceil(need * 100) / 100, "spot": spot_usd, "fut": fut_usd} + + + def min_entry_ss(self, spot_ex: str, base: str, spot_ask: float, sell_ex: str, sell_bid: float, + spot_fee_pct: float) -> dict | None: + """Spot–spot: the buy on A's spot and the sale of the same coins on B's spot must both pass their spot + minimums ("fut" = what B's sale needs).""" + ra, rb = self.spot(spot_ex, base), self.spot(sell_ex, base) + if ra is None and rb is None or spot_ask <= 0 or sell_bid <= 0: + return None + keep = 1 - spot_fee_pct / 100 + buy_usd = None if ra is None else max(ra["usd"], ra["coins"] * spot_ask / keep) + sell_usd = None if rb is None else max(rb["coins"], rb["usd"] / sell_bid if rb["usd"] else 0.0) * spot_ask / keep + need = max(v for v in (buy_usd, sell_usd) if v is not None) * MARGIN + return {"usd": math.ceil(need * 100) / 100, "spot": buy_usd, "fut": sell_usd} + + +RULES = Rules() + + +def too_small(amount: float, m: dict | None, spot_ex: str, fut_ex: str, b_leg: str = "фьюч") -> str: + """Why `amount` cannot enter the trade ("" when it can, or when the rules are not known).""" + if m is None or amount >= m["usd"]: + return "" + parts = ([f"спот {spot_ex} ≥ {m['spot']:.2f} $"] if m["spot"] is not None else []) + \ + ([f"{b_leg} {fut_ex} ≥ {m['fut']:.2f} $"] if m["fut"] is not None else []) + return f"сумма {amount:g} $ меньше мин. входа {m['usd']:.2f} $ ({', '.join(parts)})" diff --git a/LinuxServer/paper_execution.py b/LinuxServer/paper_execution.py new file mode 100644 index 0000000..c5505d6 --- /dev/null +++ b/LinuxServer/paper_execution.py @@ -0,0 +1,72 @@ +"""Delayed paper execution for the web leader simulator; never uses private APIs.""" +import inspect +import threading +import time + + +def install(engine): + trader = engine.paper + if getattr(trader, '_execution_installed', False): + return + trader._execution_installed = True + pending = set() + original_open, original_close = trader.ledger.open, trader.close + + def schedule(function, opening, args, kwargs): + values = inspect.signature(function).bind(*args, **kwargs) + values.apply_defaults() + data = values.arguments + pos = None if opening else (data['pos'] or trader.ledger.position) + if not opening and pos is None: + return + key = 'entry' if opening else pos.uid + if key in pending: + return + pending.add(key) + delay = trader.settings.simulation_entry_delay_ms if opening else trader.settings.simulation_exit_delay_ms + + def execute(): + with engine.lock: + pending.discard(key) + if engine.paper is not trader or engine.stopped.is_set(): + return + now = time.time() + bid, ask = engine.book.best() + if not bid or not ask or now - engine.last_follower > trader.settings.max_data_age_ms / 1000: + trader.message = 'Исполнение отложено: нет свежего стакана' + return + if opening: + if not trader.settings.enabled or engine.removing or trader.ledger.positions: + trader.message = 'Вход отменён: остановка или незавершённая позиция' + return + limit = float(engine.mirror.settings().get('max_ping_ms', 400) or 0) + ping = engine.mirror.ping() + if limit > 0 and ping is not None and ping > limit: + trader.message = 'Вход отменён: превышен допустимый пинг' + return + old = data['price'] + price = ask if data['side'] == 'LONG' else bid + import minorder + ps = trader.settings + exchange = {'bybit': 'Bybit', 'binance': 'Binance', 'mexc': 'MEXC'}.get(ps.follow_exchange, ps.follow_exchange) + rule = minorder.RULES.fut(exchange, ps.follow_ticker) + notional = data['notional_usd'] or ps.stake * ps.leverage + if rule is None or notional < max(rule.get('usd', 0), rule.get('coins', 0) * price): + trader.message = 'Вход отменён: неизвестен или не достигнут минимальный лот' + return + data['price'], data['now'], data['entry_mid'] = price, now, (bid + ask) / 2 + data['target'] *= price / old + if data['stop'] is not None: + data['stop'] *= price / old + function(**data) + elif pos in trader.ledger.positions: + data.update(price=bid if pos.side == 'LONG' else ask, now=now, pos=pos, utc=None, + fee_pct=trader.policy.taker) + function(**data) + + timer = threading.Timer(max(0, delay) / 1000, execute) + timer.daemon = True + timer.start() + + trader.ledger.open = lambda *a, **kw: schedule(original_open, True, a, kw) + trader.close = lambda *a, **kw: schedule(original_close, False, a, kw) diff --git a/LinuxServer/pending_removals.py b/LinuxServer/pending_removals.py new file mode 100644 index 0000000..81eb452 --- /dev/null +++ b/LinuxServer/pending_removals.py @@ -0,0 +1,45 @@ +"""Durable removal intents: retain a connection until its real exposure is closed.""" +from __future__ import annotations + +import copy +import json +import threading +from pathlib import Path + +from persistence import atomic_write_json + + +class PendingRemovals: + def __init__(self, path: Path): + self.path = Path(path) + self.lock = threading.RLock() + self.items = {} + self.error = "" + try: + value = json.loads(self.path.read_text(encoding="utf-8")) + if not isinstance(value, dict) or not all(isinstance(v, dict) for v in value.values()): + raise ValueError("неверный формат") + self.items = value + except FileNotFoundError: + pass + except (OSError, ValueError) as exc: + self.error = f"Не прочитаны ожидающие удаления: {exc}" + + def connections(self): + with self.lock: + return copy.deepcopy(self.items) + + def schedule(self, key: str, connection: dict): + with self.lock: + if self.error: + raise ValueError(self.error) + updated = {**self.items, key: dict(connection)} + atomic_write_json(self.path, updated) + self.items = updated + + def complete(self, key: str): + with self.lock: + updated = dict(self.items) + updated.pop(key, None) + atomic_write_json(self.path, updated) + self.items = updated diff --git a/LinuxServer/persistence.py b/LinuxServer/persistence.py new file mode 100644 index 0000000..0dbc4b3 --- /dev/null +++ b/LinuxServer/persistence.py @@ -0,0 +1,27 @@ +"""Atomic local JSON snapshots; callers must handle write failures explicitly.""" + +from __future__ import annotations + +import json +import os +import tempfile +from pathlib import Path + + +def atomic_write_json(path: Path, payload) -> None: + """Flush a new snapshot before replacing the old file, or leave the old file intact.""" + path = Path(path) + encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8") + path.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(fd, "wb") as stream: + stream.write(encoded) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + try: + os.unlink(temporary) + except FileNotFoundError: + pass diff --git a/LinuxServer/real_mirror.py b/LinuxServer/real_mirror.py new file mode 100644 index 0000000..e15cee9 --- /dev/null +++ b/LinuxServer/real_mirror.py @@ -0,0 +1,664 @@ +"""Real trading for the «Симулятор» tab: a paper position the simulator opens on a coin's futures exchange is repeated +with a real market order of the same size and closed with a real reduce-only order when the paper one closes. + +Strictly one real trade per coin at a time: while real mode is on, the simulator opens nothing new on the coin until +the previous real trade is closed AND the exchange shows no position left on the symbol (`gate`). A paper position +whose real order did not go through is closed at once, so paper and real trades stay one to one. + +Results (prices, fees) are the exchange's own fills; `exact` is False where the exchange did not report a figure. +- the tab-wide switch is in web_sim_data/real_simulator.json; it gates new trades only — an open real trade is + always closed with its paper twin; +- real positions are saved (web_sim_data/real_positions_.json); a saved real position is conservatively + closed right after a restart («осиротевшая»), independently of the restored paper account; +- every order and every error goes to web_sim_data/real_orders.jsonl (journal on the page). +""" + +from __future__ import annotations + +import json +import os +from persistence import atomic_write_json +import queue +import threading +import time +from pathlib import Path + +import live + +ROOT = Path(__file__).resolve().parent +DATA_DIR = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT / "web_sim_data")).resolve() +SETTINGS_FILE = DATA_DIR / "real_simulator.json" +JOURNAL = DATA_DIR / "real_orders.jsonl" +_journal_lock = threading.Lock() +RECENT: list[dict] = [] # last events of both tabs, newest last + + +def journal(tab: str, exchange: str, coin: str, action: str, ok: bool, text: str, **extra) -> dict: + event = {"time": time.time(), "tab": tab, "exchange": exchange, "coin": coin, "action": action, "ok": ok, + "text": text, **extra} + with _journal_lock: + RECENT.append(event) + del RECENT[:-300] + try: + DATA_DIR.mkdir(exist_ok=True) + with JOURNAL.open("a", encoding="utf-8") as f: + f.write(json.dumps(event, ensure_ascii=False) + "\n") + except OSError: + pass + return event + + +def load_recent(limit: int = 300) -> None: + try: + lines = JOURNAL.read_text(encoding="utf-8").splitlines()[-limit:] + except OSError: + return + with _journal_lock: + RECENT[:] = [json.loads(x) for x in lines if x.strip()] + + +DEFAULT_SL_PCT = 1.5 # stop-loss of a real position on the exchange, % from the entry +DEFAULT_MAX_PING_MS = 400.0 # no new entry while the round trip to the exchange is above this (0 = no check) +FEES: dict[str, float] = {} # exchange → real taker rate %, measured from the exchange's own fills +FEE_LISTENERS: list = [] # fn(exchange, pct): called when a new real rate is measured + + +def load_settings() -> dict: + """{"coins": {coin_key: {"on": bool, "since": t}}, "exchange_tpsl": bool} — real mode is per coin; + `since` = from when the coin's real statistics are taken from the exchange (first switch-on or a reset).""" + s = {"coins": {}, "exchange_tpsl": True, "auto_transfer": True, "sl_pct": DEFAULT_SL_PCT, + "max_ping_ms": DEFAULT_MAX_PING_MS, "fees": {}} + try: + s.update(json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))) + except (OSError, ValueError): + pass + s.pop("enabled", None) # the old tab-wide switch: real mode is per coin now + return s + + +def save_settings(values: dict) -> str: + s = load_settings() + for key in ("exchange_tpsl", "auto_transfer"): + if key in values: + s[key] = values[key] in (True, "true", 1, "1") + if "sl_pct" in values: + try: + v = float(values["sl_pct"]) + except (TypeError, ValueError): + return "неверный стоп-лосс" + if not 0 <= v <= 50: + return "стоп-лосс должен быть от 0 до 50 %" + s["sl_pct"] = v + if "max_ping_ms" in values: + try: + v = float(values["max_ping_ms"]) + except (TypeError, ValueError): + return "неверный порог пинга" + if not 0 <= v <= 10000: + return "порог пинга должен быть от 0 до 10000 мс" + s["max_ping_ms"] = v + for ex, pct in (values.get("fee") or {}).items(): + s.setdefault("fees", {})[ex] = round(float(pct), 5) + coin = values.get("coin") + if coin: + c = s["coins"].setdefault(str(coin), {"on": False, "since": 0.0}) + if "enabled" in values: + c["on"] = values["enabled"] in (True, "true", 1, "1") + if c["on"] and not c.get("since"): + c["since"] = time.time() + if values.get("reset_stats"): + c["since"] = time.time() + DATA_DIR.mkdir(exist_ok=True) + atomic_write_json(SETTINGS_FILE, s) + return "" + + +def symbol_units(symbol: str) -> float: + """Coins in one unit of a futures symbol: 1000PEPEUSDT → 1000, SI_USDT → 1.""" + base = symbol.upper().replace("_USDT", "").replace("-USDT", "").removesuffix("USDT") + return live._units(base) + + +def trades_from_fills(fills: list[dict]) -> list[dict]: + """Round trips (flat → position → flat) rebuilt from the exchange's own fills, in time order. + + Prices, fees and — where the exchange reports it (MEXC `profit`, Binance `realizedPnl`) — the realized result of + each closing fill are the exchange's figures; otherwise the result is (exit − entry) × coins of the closed part.""" + trades, pos, cost, fees_open, opened = [], 0.0, 0.0, 0.0, 0.0 + gross = fees = closed_coins = closed_value = in_coins = in_value = 0.0 + # fills of the same second: openings before closings (the exchange's time has 1 s resolution on MEXC) + for f in sorted(fills, key=lambda x: (x["time"], 1 if x.get("close") else 0, str(x.get("order", "")))): + signed = f["coins"] if f["side"] == "buy" else -f["coins"] + if abs(pos) < 1e-12 or (pos > 0) == (signed > 0): + if abs(pos) < 1e-12: + opened, cost, fees_open, gross, fees, closed_coins, closed_value = f["time"], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 + in_coins = in_value = 0.0 + pos += signed + cost += f["coins"] * f["price"] + fees_open += f["fee"] + in_coins += f["coins"] + in_value += f["coins"] * f["price"] + continue + # closing (part of) the position + closing = min(abs(signed), abs(pos)) + entry = cost / abs(pos) + side = 1 if pos > 0 else -1 + share = closing / f["coins"] + gross += f["pnl"] * share if f.get("pnl") is not None else side * (f["price"] - entry) * closing + fees += fees_open * closing / abs(pos) + f["fee"] * share + fees_open -= fees_open * closing / abs(pos) + cost -= entry * closing + pos -= side * closing + closed_coins += closing + closed_value += f["price"] * closing + if abs(pos) < 1e-9: + exit_price = closed_value / closed_coins + entry_avg = in_value / in_coins if in_coins else entry + trades.append({"side": "LONG" if side > 0 else "SHORT", "coins": closed_coins, "entry": entry_avg, + "exit": exit_price, "opened": opened, "closed": f["time"], "gross": gross, "fees": fees, + "net": gross - fees, "pct": side * (exit_price / entry_avg - 1) * 100 if entry_avg else 0.0, + "reason": "по данным биржи", "exact": True}) + pos, cost, fees_open = 0.0, 0.0, 0.0 + rest = abs(signed) - closing # a fill that flips the position opens the new one + if rest > 1e-12: + pos, cost, fees_open, opened = (rest if signed > 0 else -rest), rest * f["price"], f["fee"] * (1 - share), f["time"] + gross = fees = closed_coins = closed_value = 0.0 + in_coins, in_value = rest, rest * f["price"] + return trades + + +def trade_stats(trades: list[dict]) -> dict: + """Totals of real trades, all from the exchange's fills.""" + n = len(trades) + wins = sum(t["net"] > 0 for t in trades) + notional = sum(t["entry"] * t["coins"] for t in trades) + net = sum(t["net"] for t in trades) + return {"trades": n, "wins": wins, "winrate": wins / n * 100 if n else None, "net": net, + "fees": sum(t["fees"] for t in trades), "gross": sum(t["gross"] for t in trades), + "net_pct": net / notional * 100 if notional else None, + "exact": all(t.get("exact", True) for t in trades)} + + +class FuturesMirror: + RETRY_S = 0.7 # a refused close is tried again after this, then ×1.5 each time (up to RETRY_MAX_S) + RETRY_MAX_S = 5.0 + VERIFY_TOLERANCE = 1e-9 + + def __init__(self, coin_key: str, coin: str, exchange: str, symbol: str, data_dir: Path = DATA_DIR, + client_for=live.client, settings=load_settings) -> None: + self.coin_key, self.coin, self.exchange, self.symbol = coin_key, coin, exchange, symbol + self.file = data_dir / f"real_positions_{coin_key}.json" + self.client_for, self.settings = client_for, settings + self.lock = threading.Lock() + 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) + self.synced, self.sync_error, self.last_sync = 0.0, "", 0.0 + self.last_error, self.paused_until = "", 0.0 # the exchange's last refusal of an entry, and the pause + self.ping = lambda: None # → current round trip to the exchange's futures API, ms (or None) + self.jobs: queue.Queue = queue.Queue() + for ex, pct in (self.settings().get("fees") or {}).items(): + FEES.setdefault(ex, pct) + self._load() + threading.Thread(target=self._worker, daemon=True).start() + + # --- persistence ------------------------------------------------------------------------------------------- + def _load(self) -> None: + try: + d = json.loads(self.file.read_text(encoding="utf-8")) + 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: + pos["uid"] = None + 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: + 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: + return (self.settings().get("coins") or {}).get(self.coin_key) or {} + + def enabled(self) -> bool: + return bool(self.coin_settings().get("on")) + + def gate(self) -> str: + """Why the simulator may not open a new position on this coin now ("" = it may).""" + 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 + return f"пауза после отказа биржи ещё {left:.0f} с: {self.last_error}" + if self.state == "": + # a slow connection now = the order arrives late and fills far from the signal price: skip + limit = float(self.settings().get("max_ping_ms", DEFAULT_MAX_PING_MS) or 0) + ping = self.ping() + if limit > 0 and ping is not None and ping > limit: + return f"пинг до биржи {ping:.0f} мс выше порога {limit:.0f} мс — вход пропущен" + return "" + what = {"opening": "открывается реальный ордер", "open": "открыта реальная позиция", + "closing": "реальная позиция закрывается", "check": "жду подтверждения биржи, что позиция закрыта"} + return f"{what.get(self.state, self.state)} — новая сделка только после закрытия" + ( + f" ({self.problem})" if self.problem else "") + + def hook(self, event: str, pos) -> None: + """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 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) + self.position = {"uid": pos.uid, "side": pos.side, "coins": pos.qty * units, + "paper_entry": pos.entry / units, "opened": time.time(), + # 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(), "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", "закрыта в симуляторе")) + + def request_close(self, reason: str = "удаление подключения") -> None: + """Also close a recovered real position whose paper twin no longer exists.""" + with self.lock: + if self.position and self.state not in ("recover", "blocked"): + self.jobs.put(("close", reason)) + + def ready_to_remove(self) -> bool: + with self.lock: + return self.position is None and self.state == "" and not self.storage_error and self.jobs.empty() + + # --- worker ------------------------------------------------------------------------------------------------ + WATCH_S = 1.0 # while a real position is open: how often to ask the exchange whether TP/SL closed it + + def _worker(self) -> None: + while True: + try: + kind, arg = self.jobs.get(timeout=self.WATCH_S) + except queue.Empty: + kind, arg = "watch", None + try: + if kind == "open": + 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) + + SYNC_S = 10.0 # how often the coin's trades are rebuilt from the exchange's fill history + + def reset_stats(self) -> None: + """Real statistics of the coin start again from now (the exchange's history before is left out).""" + if self.settings is load_settings: # (tests pass their own settings and must not write the file) + save_settings({"coin": self.coin_key, "reset_stats": True}) + with self.lock: + self.trades, self.exchange_trades, self.last_sync = [], None, 0.0 + self._save() + + def sync(self) -> None: + """Trades and statistics of the coin from the exchange's own fills since real mode was switched on.""" + since = self.coin_settings().get("since") + if not since: + return + self.last_sync = time.time() + try: + fills = self.client_for(self.exchange).fut_fills(self.symbol, since) + except (live.LiveError, AttributeError) as exc: + with self.lock: + self.sync_error = str(exc) + return + trades = trades_from_fills(fills) + with self.lock: + self.exchange_trades, self.synced, self.sync_error = trades, time.time(), "" + # the fee rate the exchange really charges, from its own fills (orders no longer ask for it separately) + rates = sorted(f["fee"] / (f["coins"] * f["price"]) * 100 for f in fills[-50:] + if f.get("fee") and f.get("coins") and f.get("price")) + if rates: + rate = rates[len(rates) // 2] + if abs(rate - FEES.get(self.exchange, 0.0)) > 0.0005: + self._record_fee(rate) + + 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() + with self.lock: + if self.state != "open" or not (self.position or {}).get("tpsl_on"): + return + try: + held = self.client_for(self.exchange).fut_position(self.symbol) + except live.LiveError: + return + if abs(held) <= self.VERIFY_TOLERANCE: + self._close("закрыта биржей по TP/SL") + + def _retry_close(self, reason: str) -> None: + # fast first (a «510 too frequent» passes in under a second), slower if the exchange keeps refusing + with self.lock: + fails = (self.position or {}).get("close_fails", 0) + if self.position is not None: + self.position["close_fails"] = fails + 1 + delay = min(self.RETRY_MAX_S, self.RETRY_S * 1.5 ** fails) + timer = threading.Timer(delay, lambda: self.jobs.put(("close", reason))) + timer.daemon = True + timer.start() + + TP_MARGIN_PCT = 0.05 # the TP must be at least two fees + this beyond the real entry to leave a profit + + 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 + s = self.settings() + use_tpsl = s.get("exchange_tpsl", True) + sl_pct = float(s.get("sl_pct", DEFAULT_SL_PCT) or 0) + # stop-loss goes with the entry (Bybit / MEXC attach it to the order; Binance sets it right after the fill) + sl = pos["paper_entry"] * (1 - sign * sl_pct / 100) if use_tpsl and sl_pct > 0 else None + try: + c = self.client_for(self.exchange) + if sl: + fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False, sl=sl) + else: + fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False) + except live.LiveError as exc: + 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 = c.fut_position(self.symbol) + except live.LiveError: + 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: + self._record_fee(fee_pct) + notes = [] + sl_set = bool(sl) and getattr(fill, "tpsl", "") == "на бирже" + if sl: + notes.append(f"SL {sl:.10g} (−{sl_pct:g}%) на бирже" if sl_set else f"SL НЕ выставлен: {fill.tpsl or 'нет ответа'}") + tp_id = "" + if use_tpsl and pos.get("tp_pct") is not None: + # TP: a reduce-only LIMIT order at the paper distance from the REAL entry (never closer than two fees + # plus a margin) — it fills at the TP price or better, not through the spread like a triggered market order + need = 2 * (fee_pct or FEES.get(self.exchange) or 0.1) + self.TP_MARGIN_PCT + dist = max(abs(pos["tp_pct"]), need) + tp = fill.price * (1 + sign * dist / 100) + try: + tp_id = c.fut_take_profit(self.symbol, "sell" if side == "buy" else "buy", fill.coins, tp) + notes.append(f"TP лимит {tp:.10g} ({'+' if sign > 0 else '−'}{dist:.3f}% от реального входа" + + (f", бумажный {abs(pos['tp_pct']):.3f}% меньше двух комиссий — отодвинут" if dist > abs(pos['tp_pct']) else "") + + ")") + except (live.LiveError, AttributeError) as exc: + notes.append(f"TP НЕ выставлен: {exc}") + with self.lock: + pos.update(coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd, exact=fill.exact, order_in=fill.order_id, + tp_order=tp_id, tpsl_on=sl_set or bool(tp_id)) + closing_requested = self.state == "closing" + self.state, self.problem = ("closing" if closing_requested else "open"), "" + self._save() + journal("simulator", self.exchange, self.coin, "open", True, + f"{'лонг' if side == 'buy' else 'шорт'} {fill.coins:g} по {fill.price:.10g} (сигнал " + f"{pos['paper_entry']:.10g}, {(fill.price / pos['paper_entry'] - 1) * 100 * sign:+.3f}% проскальзывание" + + (f", пинг {pos['ping']:.0f} мс" if pos.get("ping") is not None else "") + "), " + f"комиссия {fill.fee_usd:.4f} $" + (f"; {'; '.join(notes)}" if notes else ""), side=pos["side"], + coins=fill.coins, price=fill.price, order=fill.order_id, ping=pos.get("ping"), + slip=(fill.price / pos["paper_entry"] - 1) * 100 * sign) + + def _top_up_futures(self, c, error: str, notional: float) -> None: + """The exchange refused for lack of money: move USDT from the spot account so the NEXT signal can trade + (this one is gone: no extra requests before an entry, they would delay every order).""" + if c is None or not self.settings().get("auto_transfer", True): + return + if not any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно")): + return + try: + moved = live.ensure_usdt(c, 0.0, notional * 1.03) + if moved: + journal("simulator", self.exchange, self.coin, "transfer", True, moved + " — для следующей сделки") + except (live.LiveError, AttributeError) as exc: + journal("simulator", self.exchange, self.coin, "transfer", False, f"перевод не удался: {exc}") + + def _record_fee(self, pct: float) -> None: + """Remember the exchange's real taker rate; listeners (the paper model) use it from now on.""" + FEES[self.exchange] = pct + if self.settings is load_settings: # (tests pass their own settings and must not write the file) + save_settings({"fee": {self.exchange: pct}}) + for fn in FEE_LISTENERS: + fn(self.exchange, pct) + + def _blocked(self, problem: str, text: str, pos: dict) -> None: + """The close is not confirmed yet: keep the coin blocked; journal only when the reason changes.""" + with self.lock: + changed = problem != self.problem + self.state, self.problem = "closing", problem + self._save() + if changed: + journal("simulator", self.exchange, self.coin, "close", False, text, side=pos["side"]) + + PAUSE_S = 30.0 # after the exchange refused an entry: no new trade on the coin for this long + BLOCKED_PAUSE_S = 900.0 # …and this long when the account itself is restricted (MEXC 6002) or rate-limited + + def _failed_open(self, why: str) -> None: + account = any(k in why for k in ("6002", "restricted", "510", "too frequent", "10006", "Too many")) + pause = self.BLOCKED_PAUSE_S if account else self.PAUSE_S + with self.lock: + uid = self.position["uid"] if self.position else None + side = self.position["side"] if self.position else "" + self.position, self.state, self.problem = None, "", "" + self.last_error, self.paused_until = why, time.time() + pause + self._save() + hint = (" — биржа ограничила аккаунт или частоту запросов: проверьте почту и уведомления биржи" if account else "") + journal("simulator", self.exchange, self.coin, "open", False, + f"{why}{hint}; бумажная позиция тоже закрыта, новые входы по монете на паузе {pause / 60:.0f} мин" + if pause >= 60 else f"{why}; бумажная позиция тоже закрыта, пауза {pause:.0f} с", side=side) + if uid is not None and self.on_failed_open: + 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 == "": + return + self.state = "closing" + c = self.client_for(self.exchange) + side = "sell" if pos["side"] == "LONG" else "buy" + fills = pos.setdefault("exit_fills", []) + try: + if pos.get("tp_order") and not pos.get("tp_cancelled"): + try: # the TP limit must not fill on top of our close + c.fut_cancel_all(self.symbol) + pos["tp_cancelled"] = True + except (live.LiveError, AttributeError): + pass # reduce-only orders cannot overshoot anyway + held = c.fut_position(self.symbol) # what is really open: TP/SL may have closed it already + if abs(held) > self.VERIFY_TOLERANCE: + try: + fill = c.fut_order(self.symbol, side, abs(held), reduce_only=True) + fills.append({"coins": fill.coins, "price": fill.price, "fee": fill.fee_usd, "exact": fill.exact, + "order": fill.order_id}) + except live.LiveError as exc: + if not getattr(exc, "sent", False): + raise + # accepted, not confirmed: the position check below decides + with self.lock: + self.state = "check" + self._save() + held = c.fut_position(self.symbol) + except live.LiveError as exc: + self._blocked(str(exc), f"не закрыта: {exc} — повторяю через {self.RETRY_S:g} с и дальше", pos) + self._retry_close(reason) + return + left = abs(held) + if left > self.VERIFY_TOLERANCE: + with self.lock: + pos["left"] = left + self._blocked(f"на бирже ещё {held:+g} {self.coin}", f"на бирже осталась позиция {held:+g} — докрываю", pos) + self._retry_close(reason) + return + # confirmed: no position on the symbol any more + done_ours = sum(f["coins"] for f in fills) + if done_ours < pos["coins"] * 0.999: + # (part of) it was closed by the exchange (TP / SL): its own closing fills give the result + try: + theirs = c.fut_closes(self.symbol, side, pos["opened"] - 2) + ours = {f.get("order") for f in fills} + for f in theirs: + if f.order_id not in ours and done_ours < pos["coins"] * 0.999: + fills.append({"coins": f.coins, "price": f.price, "fee": f.fee_usd, "exact": f.exact, + "order": f.order_id}) + done_ours += f.coins + if theirs and "биржей" not in reason: + reason = f"закрыта биржей по TP/SL ({reason})" + except (live.LiveError, AttributeError): + pass + if pos.get("tpsl_on") and not pos.get("tp_cancelled"): + try: # (already done before our own close: not twice) + c.fut_cancel_all(self.symbol) # TP / SL orders left after the exchange's close + except (live.LiveError, AttributeError): + pass + done = sum(f["coins"] for f in fills) + exit_price = sum(f["coins"] * f["price"] for f in fills) / done if done else pos.get("entry", 0.0) + sign = 1 if pos["side"] == "LONG" else -1 + coins = min(done, pos["coins"]) if done else pos["coins"] + gross = sign * (exit_price - pos.get("entry", exit_price)) * coins + fees = pos.get("fee_in", 0.0) + sum(f["fee"] for f in fills) + trade = {"side": pos["side"], "coins": coins, "entry": pos.get("entry", 0.0), "exit": exit_price, + "opened": pos["opened"], "closed": time.time(), "gross": gross, "fees": fees, "net": gross - fees, + "pct": sign * (exit_price / pos["entry"] - 1) * 100 if pos.get("entry") else 0.0, + "reason": reason, "exact": pos.get("exact", True) and all(f["exact"] for f in fills) and bool(fills)} + with self.lock: + self.trades.append(trade) + self.position, self.state, self.problem = None, "", "" + self._save() + self.last_sync = 0.0 # pull the exchange's own figures for this trade soon + journal("simulator", self.exchange, self.coin, "close", True, + f"закрыта по {exit_price:.10g}, биржа подтвердила: позиции нет; итог {trade['net']:+.4f} $ " + f"(комиссии {fees:.4f} $, {reason})", side=pos["side"], coins=coins, price=exit_price, net=trade["net"]) + + # --- view ------------------------------------------------------------------------------------------------------ + def view(self) -> dict: + with self.lock: + # the exchange's history when synced; until then the program's own record of its orders + trades = self.exchange_trades if self.exchange_trades is not None else [ + 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.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"), + "last_error": self.last_error, "paused_s": max(0.0, self.paused_until - time.time()), + "trade_list": list(reversed(trades[-200:]))} diff --git a/LinuxServer/request_security.py b/LinuxServer/request_security.py new file mode 100644 index 0000000..a8d47f7 --- /dev/null +++ b/LinuxServer/request_security.py @@ -0,0 +1,52 @@ +"""Validate the original browser request before proxying or executing local commands.""" +from __future__ import annotations + +import ipaddress +import os +from urllib.parse import urlsplit + +LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"} +PUBLIC_HOST = os.environ.get("CRYPTO_SCAM_PUBLIC_HOST", "").strip().lower().rstrip(".") + + +def _authority(value: str): + try: + url = urlsplit("http://" + value) + hostname = (url.hostname or "").lower().rstrip(".") + allowed = hostname in LOCAL_HOSTS or (PUBLIC_HOST and hostname == PUBLIC_HOST) + if (not allowed 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 + is_public = bool(PUBLIC_HOST and host[0] == PUBLIC_HOST) + if is_public and (handler.headers.get("X-Forwarded-Proto", "").lower() != "https" + or host[1] not in (80, 443)): + return False + origins = handler.headers.get_all("Origin", []) + if len(origins) > 1: + return False + if origins: + try: + origin = urlsplit(origins[0]) + expected_scheme = "https" if is_public else "http" + if (origin.scheme != expected_scheme or origin.path or origin.query or origin.fragment + or _authority(origin.netloc) != host): + return False + except ValueError: + return False + if handler.headers.get("Sec-Fetch-Site") == "cross-site": + return False + return not command or handler.headers.get("X-Sim") == "1" diff --git a/LinuxServer/requirements.txt b/LinuxServer/requirements.txt new file mode 100644 index 0000000..0ee383c --- /dev/null +++ b/LinuxServer/requirements.txt @@ -0,0 +1,3 @@ +# Python 3.11+ +websocket-client==1.8.0 +numpy==2.3.5 diff --git a/LinuxServer/runtime_lock.py b/LinuxServer/runtime_lock.py new file mode 100644 index 0000000..18a02a5 --- /dev/null +++ b/LinuxServer/runtime_lock.py @@ -0,0 +1,45 @@ +"""One trading engine per data directory, even with different HTTP ports.""" +from __future__ import annotations + +import os +from pathlib import Path + + +class RuntimeLock: + def __init__(self, path: Path): + self.path = Path(path) + self.stream = None + + def __enter__(self): + self.path.parent.mkdir(parents=True, exist_ok=True) + stream = self.path.open("a+b") + if stream.seek(0, os.SEEK_END) == 0: + stream.write(b"\0") + stream.flush() + stream.seek(0) + try: + if os.name == "nt": + import msvcrt + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + stream.close() + raise RuntimeError("Движок уже запущен для этой папки. Откройте существующее окно программы.") from None + self.stream = stream + return self + + def __exit__(self, *args): + if self.stream is not None: + try: + self.stream.seek(0) + if os.name == "nt": + import msvcrt + msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + fcntl.flock(self.stream.fileno(), fcntl.LOCK_UN) + finally: + self.stream.close() + self.stream = None diff --git a/LinuxServer/scalp_hint.py b/LinuxServer/scalp_hint.py new file mode 100644 index 0000000..a082534 --- /dev/null +++ b/LinuxServer/scalp_hint.py @@ -0,0 +1,1711 @@ +"""Scalping hint from the MetaScalp order book and tape: which side, where to enter, stop and target. + +Read-only: connects to the local MetaScalp API (127.0.0.1:17845-17855), follows the order book that +is open in the terminal and never sends orders. The rules mirror a manual read of the book: + +* book imbalance - resting size near the price on the bid side versus the ask side; +* tape delta and momentum - who hits the market and where the price moved recently; +* absorption - heavy market selling that does not push the price down (or the mirror case); +* plan - enter next to the density on the chosen side, keep the stop BEHIND that density, + aim just before the opposite density and skip moves that do not cover the trading costs. + +Every hint that becomes actionable is also checked against the following trades (would the limit +fill, then stop or target first) and appended to a CSV journal, so the hints build their own statistics. +""" + +from __future__ import annotations + +import csv +import json +import math +import os +import queue +import statistics +import threading +import time +import urllib.request +from collections import deque +from dataclasses import dataclass, field, fields +from datetime import datetime, timezone +from pathlib import Path + +API_HOST = "127.0.0.1" +API_PORTS = range(17845, 17856) +JOURNAL_FILE = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", Path(__file__).resolve().parent)) / "scalp_hint_journal.csv" +MAKER_FEE_PCT = 0.02 +TAKER_FEE_PCT = 0.055 +# Weights of the score components; the adaptive paper policy re-weights them from its own results. +DEFAULT_WEIGHTS = {"book_imb": 0.35, "near_imb": 0.15, "tape_delta": 0.3, "momentum": 0.2, "absorption": 0.15} + + +@dataclass +class HintSettings: + weights: dict = field(default_factory=lambda: dict(DEFAULT_WEIGHTS)) + window_pct: float = 0.3 # depth window around the mid price for imbalance and densities + near_levels: int = 5 # levels per side for the "near the price" imbalance + density_mult: float = 4.0 # a density is a level >= mult x median level size in the window + tape_seconds: float = 60.0 # tape window for delta, momentum and absorption + entry_offset_ticks: int = 1 # enter this many ticks in front of the density + stop_buffer_ticks: int = 2 # stop this many ticks behind the density / recent extreme + min_target_pct: float = 0.15 # the move must at least cover fees and slippage + min_rr: float = 1.5 # minimum reward / risk + max_entry_distance_pct: float = 0.3 + score_threshold: float = 0.25 # below this |score| the hint is "wait" + min_trades: int = 5 # fewer tape trades than this: the tape is ignored + min_risk_pct: float = 0.1 # stop at least this far, and at least half the recent tape range + smooth_seconds: float = 8.0 # time constant of the score smoothing (removes flicker) + fill_minutes: float = 2.0 # how long a hinted limit order may wait for a fill + hold_minutes: float = 5.0 # time stop once filled + + +class OrderBook: + """Absolute-size price levels; an update with size 0 removes the level.""" + + def __init__(self) -> None: + self.asks: dict[float, float] = {} + self.bids: dict[float, float] = {} + + def clear(self) -> None: + self.asks.clear() + self.bids.clear() + + def apply_snapshot(self, data: dict) -> None: + self.clear() + for level in data.get("asks", []): + self._set(self.asks, level) + for level in data.get("bids", []): + self._set(self.bids, level) + marks = [level for level in (data.get("bestAsk"), data.get("bestBid")) if isinstance(level, dict)] + if marks: + self.apply_updates(marks) + + def apply_updates(self, updates: list[dict]) -> None: + best_ask_mark = best_bid_mark = None + for level in updates: + kind = str(level.get("type", "")) + if kind in ("Ask", "BestAsk"): + self._set(self.asks, level) + elif kind in ("Bid", "BestBid"): + self._set(self.bids, level) + try: + if kind == "BestAsk" and float(level["size"]) > 0: + best_ask_mark = float(level["price"]) + elif kind == "BestBid" and float(level["size"]) > 0: + best_bid_mark = float(level["price"]) + except (KeyError, TypeError, ValueError): + pass + # MetaScalp marks the current best prices; levels in front of them are stale (consumed or + # cancelled without an explicit removal), so they are dropped. + if best_ask_mark is not None: + for price in [p for p in self.asks if p < best_ask_mark]: + del self.asks[price] + if best_bid_mark is not None: + for price in [p for p in self.bids if p > best_bid_mark]: + del self.bids[price] + if self.asks and self.bids: + best_ask, best_bid = min(self.asks), max(self.bids) + if best_bid >= best_ask: + # Still crossed without best-price marks: drop the crossing bids until the next update. + for price in [p for p in self.bids if p >= best_ask]: + del self.bids[price] + + @staticmethod + def _set(side: dict[float, float], level: dict) -> None: + try: + price, size = float(level["price"]), float(level["size"]) + except (KeyError, TypeError, ValueError): + return + if size <= 0: + side.pop(price, None) + else: + side[price] = size + + def best(self) -> tuple[float | None, float | None]: + return (max(self.bids) if self.bids else None, min(self.asks) if self.asks else None) + + +@dataclass +class Trade: + ts: float + price: float + size: float + side: str # "Buy" or "Sell" (aggressor) + + +class Tape: + def __init__(self, keep_seconds: float = 900.0) -> None: + self.trades: deque[Trade] = deque() + self.keep = keep_seconds + + def add(self, trade: Trade) -> None: + self.trades.append(trade) + while self.trades and self.trades[0].ts < trade.ts - self.keep: + self.trades.popleft() + + def window(self, seconds: float, now: float) -> list[Trade]: + return [t for t in self.trades if t.ts >= now - seconds] + + def clear(self) -> None: + self.trades.clear() + + +@dataclass +class Hint: + side: str # "LONG", "SHORT" or "WAIT" + confidence: str + score: float + entry: float | None = None + stop: float | None = None + target: float | None = None + rr: float | None = None + reasons: list[str] = field(default_factory=list) + metrics: dict = field(default_factory=dict) + + +def _clip(value: float) -> float: + return max(-1.0, min(1.0, value)) + + +def _to_tick(price: float, tick: float, up: bool | None = None) -> float: + steps = price / tick + steps = math.ceil(steps - 1e-9) if up else math.floor(steps + 1e-9) if up is False else round(steps) + decimals = max(0, -int(math.floor(math.log10(tick)))) if tick < 1 else 0 + return round(steps * tick, decimals + 2) + + +def _imbalance(bid: float, ask: float) -> float: + total = bid + ask + return (bid - ask) / total if total > 0 else 0.0 + + +def significant_imbalance(book: OrderBook, depth_pct: float = 0.3, low_pct: float = 20.0, + high_pct: float = 90.0) -> dict | None: + """Imbalance of the 'significant' resting orders near the price. + + Levels within ±depth_pct of the mid are pooled (both sides); levels below the low percentile of their + sizes (noise) and above the high percentile (outsized walls, often pulled before the price arrives) + are dropped, and the remaining sizes are summed per side. Returns None without a usable book. + """ + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return None + mid = (best_bid + best_ask) / 2 + window = mid * depth_pct / 100 + levels = sorted([(s, "ask") for p, s in book.asks.items() if p <= mid + window] + + [(s, "bid") for p, s in book.bids.items() if p >= mid - window]) + if len(levels) < 4: + return None + # Cut by count, not by value: many identical sizes at a percentile would otherwise all be + # kept or all be dropped. The smallest low_pct% and the largest (100 - high_pct)% of levels go. + n = len(levels) + drop_low = int(n * low_pct / 100) + drop_high = int(n * (100 - high_pct) / 100) + kept = levels[drop_low:n - drop_high] or levels + bid_sum = sum(s for s, side in kept if side == "bid") + ask_sum = sum(s for s, side in kept if side == "ask") + return {"mid": mid, "bid_sum": bid_sum, "ask_sum": ask_sum, "imbalance": _imbalance(bid_sum, ask_sum), + "low": kept[0][0], "high": kept[-1][0], "used": len(kept), "levels": n} + + +class HintEngine: + """Smooths the score over time so the hint does not flip on every book update.""" + + def __init__(self, settings: HintSettings) -> None: + self.settings = settings + self.score: float | None = None + self.at = 0.0 + + def reset(self) -> None: + self.score = None + + def __call__(self, book: OrderBook, tape: Tape, tick: float, now: float) -> Hint: + raw = evaluate(book, tape, tick, self.settings, now) + if not raw.metrics: + return raw + if self.score is None: + self.score = raw.score + else: + alpha = 1 - math.exp(-max(0.0, now - self.at) / self.settings.smooth_seconds) + self.score += alpha * (raw.score - self.score) + self.at = now + return evaluate(book, tape, tick, self.settings, now, score_override=self.score) + + +def evaluate(book: OrderBook, tape: Tape, tick: float, settings: HintSettings, now: float, + score_override: float | None = None) -> Hint: + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None or tick <= 0: + return Hint("WAIT", "—", 0.0, reasons=["Нет стакана — жду данные MetaScalp"]) + mid = (best_bid + best_ask) / 2 + spread_pct = (best_ask - best_bid) / mid * 100 + window = mid * settings.window_pct / 100 + asks = sorted((p, s) for p, s in book.asks.items() if p <= mid + window) + bids = sorted(((p, s) for p, s in book.bids.items() if p >= mid - window), reverse=True) + if not asks or not bids: + return Hint("WAIT", "—", 0.0, reasons=["Стакан слишком тонкий в окне ±{:g}%".format(settings.window_pct)]) + + # Book imbalance, levels closer to the price weigh more. + def weighted(levels): + return sum(s * (1 - abs(p - mid) / window) for p, s in levels) + + book_imb = _imbalance(weighted(bids), weighted(asks)) + near_imb = _imbalance(sum(s for _, s in bids[:settings.near_levels]), + sum(s for _, s in asks[:settings.near_levels])) + + # Safety: the book must agree with the tape, otherwise it is out of sync and nothing is hinted. + if tape.trades: + last_price = tape.trades[-1].price + if abs(last_price - mid) / mid * 100 > 0.3: + return Hint("WAIT", "—", 0.0, reasons=[ + f"Стакан расходится с лентой ({mid:.10g} против последней сделки {last_price:.10g}) — " + "жду обновления данных"]) + + # Tape delta, momentum and absorption. + recent = tape.window(settings.tape_seconds, now) + buy = sum(t.size for t in recent if t.side == "Buy") + sell = sum(t.size for t in recent if t.side == "Sell") + enough = len(recent) >= settings.min_trades + tape_delta = _imbalance(buy, sell) if enough else 0.0 + if enough: + momentum = _clip((recent[-1].price - recent[0].price) / mid / (settings.window_pct / 100)) + tape_high = max(t.price for t in recent) + tape_low = min(t.price for t in recent) + else: + momentum, tape_high, tape_low = 0.0, best_ask, best_bid + absorption = 0.0 + if enough and buy + sell > 0: + if tape_delta < -0.3 and momentum >= 0: + absorption = 1.0 # sellers hit hard, price does not fall: buyers absorb + elif tape_delta > 0.3 and momentum <= 0: + absorption = -1.0 # buyers hit hard, price does not rise: sellers absorb + + w = settings.weights + raw_score = (w["book_imb"] * book_imb + w["near_imb"] * near_imb + w["tape_delta"] * tape_delta + + w["momentum"] * momentum + w["absorption"] * absorption) + score = raw_score if score_override is None else score_override + min_risk = max(mid * settings.min_risk_pct / 100, (tape_high - tape_low) / 2, 2 * tick) + sizes = [s for _, s in asks] + [s for _, s in bids] + median = statistics.median(sizes) if sizes else 0.0 + threshold = median * settings.density_mult + resistance = next(((p, s) for p, s in asks if s >= threshold and p > best_ask - tick / 2), None) + support = next(((p, s) for p, s in bids if s >= threshold and p < best_bid + tick / 2), None) + + metrics = {"mid": mid, "spread_pct": spread_pct, "book_imb": book_imb, "near_imb": near_imb, + "tape_delta": tape_delta, "momentum": momentum, "absorption": absorption, + "trades": len(recent), "resistance": resistance, "support": support, + "ask_volume": sum(s for _, s in asks), "bid_volume": sum(s for _, s in bids)} + reasons = [ + f"Стакан ±{settings.window_pct:g}%: покупатели {metrics['bid_volume']:,.0f} / продавцы " + f"{metrics['ask_volume']:,.0f} (перекос {book_imb:+.2f}, у цены {near_imb:+.2f})", + (f"Лента {settings.tape_seconds:.0f} с: покупки {buy:,.0f} / продажи {sell:,.0f} " + f"(перевес {tape_delta:+.2f}), импульс {momentum:+.2f}, сделок {len(recent)}") + if enough else f"Лента: мало сделок за {settings.tape_seconds:.0f} с ({len(recent)}) — не учитывается", + ] + if absorption > 0: + reasons.append("Поглощение: продают по рынку, но цена не падает — снизу держат") + elif absorption < 0: + reasons.append("Поглощение: покупают по рынку, но цена не растёт — сверху держат") + if resistance: + reasons.append(f"Плотность продавцов {resistance[1]:,.0f} на {resistance[0]:.10g}") + if support: + reasons.append(f"Плотность покупателей {support[1]:,.0f} на {support[0]:.10g}") + reasons.append(f"Спред {spread_pct:.3f}%") + thin = min(metrics["ask_volume"], metrics["bid_volume"]) / max(metrics["ask_volume"], metrics["bid_volume"]) + if thin < 0.08: + reasons.append("Внимание: одна сторона стакана почти пустая — так бывает при резком движении; " + "сверьтесь со стаканом в терминале") + + strength = abs(score) + if strength < settings.score_threshold: + reasons.insert(0, "Перевеса нет — боковик, вход не нужен") + return Hint("WAIT", "—", score, reasons=reasons, metrics=metrics) + confidence = "высокая" if strength >= 0.65 else "средняя" if strength >= 0.45 else "низкая" + side = "LONG" if score > 0 else "SHORT" + offset = settings.entry_offset_ticks * tick + buffer = settings.stop_buffer_ticks * tick + if side == "SHORT": + if resistance and resistance[0] - offset >= best_ask: + entry = resistance[0] - offset + stop = resistance[0] + buffer + else: + entry = best_ask + stop = max(entry, tape_high) + buffer + stop = max(stop, entry + min_risk) + risk = stop - entry + target = support[0] + offset if support and support[0] + offset < entry - risk else entry - 2 * risk + reward = entry - target + else: + if support and support[0] + offset <= best_bid: + entry = support[0] + offset + stop = support[0] - buffer + else: + entry = best_bid + stop = min(entry, tape_low) - buffer + stop = min(stop, entry - min_risk) + risk = entry - stop + target = resistance[0] - offset if resistance and resistance[0] - offset > entry + risk else entry + 2 * risk + reward = target - entry + # Orders sit on the price grid: the stop rounds away from the entry, the target towards it. + if side == "SHORT": + entry, stop, target = _to_tick(entry, tick), _to_tick(stop, tick, up=True), _to_tick(target, tick, up=True) + risk, reward = stop - entry, entry - target + else: + entry, stop, target = _to_tick(entry, tick), _to_tick(stop, tick, up=False), _to_tick(target, tick, up=False) + risk, reward = entry - stop, target - entry + rr = reward / risk if risk > 0 else 0.0 + reward_pct = reward / entry * 100 + entry_distance = abs(entry - mid) / mid * 100 + hint = Hint(side, confidence, score, entry, stop, target, rr, reasons, metrics) + problems = [] + if reward_pct < settings.min_target_pct: + problems.append(f"ход до цели {reward_pct:.2f}% меньше издержек ({settings.min_target_pct:g}%)") + if rr < settings.min_rr: + problems.append(f"риск/прибыль 1:{rr:.1f} хуже 1:{settings.min_rr:g}") + if entry_distance > settings.max_entry_distance_pct: + problems.append(f"вход далеко от цены ({entry_distance:.2f}%)") + if problems: + hint.reasons.insert(0, f"Перевес в {side}, но сделка невыгодна: " + "; ".join(problems)) + hint.side = "WAIT" + return hint + + +@dataclass +class Tracked: + ticker: str + side: str + entry: float + stop: float + target: float + created: float + confidence: str + score: float + filled_at: float | None = None + result: str = "" + pnl_pct: float = 0.0 + + +class Journal: + """Checks each actionable hint against later trades: fill, then stop or target first.""" + + def __init__(self, settings: HintSettings, path: Path = JOURNAL_FILE) -> None: + self.settings = settings + self.path = path + self.active: Tracked | None = None + self.done: list[Tracked] = [] + self._load() + + def _load(self) -> None: + try: + with self.path.open(encoding="utf-8-sig") as file: + for row in csv.DictReader(file): + self.done.append(Tracked(row["ticker"], row["side"], float(row["entry"]), float(row["stop"]), + float(row["target"]), 0.0, row["confidence"], float(row["score"]), + result=row["result"], pnl_pct=float(row["pnl_pct"] or 0))) + except (OSError, KeyError, ValueError): + pass + + def offer(self, ticker: str, hint: Hint, now: float) -> None: + if self.active is not None or hint.side == "WAIT" or hint.entry is None: + return + self.active = Tracked(ticker, hint.side, hint.entry, hint.stop, hint.target, now, hint.confidence, hint.score) + + def cancel(self, reason: str) -> None: + if self.active and self.active.filled_at is None: + self._finish(reason, 0.0) + elif self.active: + self._finish(reason, self.active.pnl_pct) + + def on_trade(self, trade: Trade) -> None: + tr = self.active + if tr is None: + return + long = tr.side == "LONG" + if tr.filled_at is None: + # A resting limit fills only when the market trades through it (queue is unknown). + through = trade.price < tr.entry if long else trade.price > tr.entry + if through: + tr.filled_at = trade.ts + elif trade.ts - tr.created > self.settings.fill_minutes * 60: + self._finish("не исполнился", 0.0) + return + stop_hit = trade.price <= tr.stop if long else trade.price >= tr.stop + target_hit = trade.price >= tr.target if long else trade.price <= tr.target + sign = 1 if long else -1 + if stop_hit: + self._finish("стоп", sign * (tr.stop - tr.entry) / tr.entry * 100 - MAKER_FEE_PCT - TAKER_FEE_PCT) + elif target_hit: + self._finish("цель", sign * (tr.target - tr.entry) / tr.entry * 100 - 2 * MAKER_FEE_PCT) + elif trade.ts - tr.filled_at > self.settings.hold_minutes * 60: + self._finish("время", sign * (trade.price - tr.entry) / tr.entry * 100 - MAKER_FEE_PCT - TAKER_FEE_PCT) + + def _finish(self, result: str, pnl: float) -> None: + tr = self.active + self.active = None + if tr is None: + return + tr.result, tr.pnl_pct = result, pnl + self.done.append(tr) + new_file = not self.path.exists() + try: + with self.path.open("a", encoding="utf-8-sig", newline="") as file: + writer = csv.writer(file) + if new_file: + writer.writerow(["time_utc", "ticker", "side", "confidence", "score", "entry", "stop", "target", + "result", "pnl_pct"]) + writer.writerow([datetime.now(timezone.utc).isoformat(timespec="seconds"), tr.ticker, tr.side, + tr.confidence, f"{tr.score:.3f}", f"{tr.entry:.10g}", f"{tr.stop:.10g}", + f"{tr.target:.10g}", result, f"{pnl:.4f}"]) + except OSError: + pass + + def stats(self) -> str: + filled = [t for t in self.done if t.result in ("стоп", "цель", "время")] + if not filled: + unfilled = sum(t.result == "не исполнился" for t in self.done) + return f"Проверено подсказок: 0 исполненных · не исполнилось {unfilled}" + wins = sum(t.pnl_pct > 0 for t in filled) + avg = sum(t.pnl_pct for t in filled) / len(filled) + return (f"Исполнено {len(filled)} · в плюс {wins} ({wins / len(filled) * 100:.0f}%) · " + f"средний итог {avg:+.3f}% после комиссий · не исполнилось " + f"{sum(t.result == 'не исполнился' for t in self.done)}") + + +# -------------------------------------------------------------------------------------------- +# MetaScalp connection +# -------------------------------------------------------------------------------------------- + +def discover_port() -> int | None: + for port in API_PORTS: + try: + with urllib.request.urlopen(f"http://{API_HOST}:{port}/ping", timeout=1) as response: + if json.loads(response.read().decode("utf-8")).get("app") == "MetaScalp": + return port + except Exception: + continue + return None + + +def active_order_book(port: int) -> dict | None: + """The order book document of the selected tab: connection id, ticker and price step.""" + with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/ui/state", timeout=3) as response: + state = json.loads(response.read().decode("utf-8")) + for window in state.get("windows", []): + tabs = window.get("tabs", []) + for tab in sorted(tabs, key=lambda t: not t.get("isSelected")): + for doc in tab.get("documents", []): + if doc.get("kind") == "orderBook" and doc.get("orderBook"): + return {"connectionId": doc["connectionId"], "ticker": doc["ticker"], + "tick": float(doc["orderBook"].get("priceIncrement") or 0)} + return None + + +def connection_name(port: int, connection_id: int) -> str: + try: + with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/connections/{connection_id}", timeout=3) as r: + data = json.loads(r.read().decode("utf-8")) + return str(data.get("Name") or data.get("name") or connection_id) + except Exception: + return str(connection_id) + + +def connection_info(port: int, connection_id: int) -> dict: + try: + with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/connections/{connection_id}", timeout=3) as r: + return json.loads(r.read().decode("utf-8")) + except Exception: + return {} + + +BYBIT_WS = "wss://stream.bybit.com/v5/public/linear" + + +class ClockSync: + """Exchange-minus-local clock offset, re-measured every `period` seconds (the PC clock drifts and Windows + steps it now and then, which would otherwise show up as a sudden jump in measured latency).""" + + def __init__(self, period: float = 60.0) -> None: + self.period = period + self.offset: float | None = None + self.measured = -1e9 + + def get(self) -> float | None: + if time.monotonic() - self.measured > self.period: + self.measured = time.monotonic() + value = bybit_clock_offset() + if value is not None: + self.offset = value + return self.offset + + +def bybit_clock_offset() -> float | None: + """Exchange clock minus local clock, seconds (round-trip corrected); None when Bybit is unreachable.""" + try: + t0 = time.time() + with urllib.request.urlopen("https://api.bybit.com/v5/market/time", timeout=5) as response: + payload = json.loads(response.read().decode("utf-8")) + t1 = time.time() + server = int(payload["result"]["timeNano"]) / 1e9 + return server - (t0 + t1) / 2 + except Exception: + return None + + +def parse_time(value: str) -> float: + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() + except (ValueError, AttributeError): + return time.time() + + +class Feed(threading.Thread): + """WebSocket reader: pushes ("book_snapshot"|"book_update"|"trades", data) into a queue.""" + + def __init__(self, port: int, connection_id: int, ticker: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.port, self.connection_id, self.ticker, self.out = port, connection_id, ticker, out + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + self.ws = websocket.create_connection(f"ws://{API_HOST}:{self.port}/", timeout=30) + base = {"connectionId": self.connection_id, "ticker": self.ticker} + self.ws.send(json.dumps({"Type": "orderbook_subscribe", + "Data": {**base, "zoomIndex": 0, "depthLevels": 100, "depthPercent": 1.0}})) + self.ws.send(json.dumps({"Type": "trade_subscribe", "Data": {**base, "zoomIndex": 1}})) + self.out.put(("status", f"Подключено: {self.ticker}")) + while not self.stopped.is_set(): + message = json.loads(self.ws.recv()) + kind = message.get("Type") + data = message.get("Data") or {} + if data.get("ticker") not in (None, self.ticker): + continue + if kind == "orderbook_snapshot": + self.out.put(("book_snapshot", data)) + elif kind == "orderbook_update": + self.out.put(("book_update", data.get("updates", []))) + elif kind == "trade_update": + trades = data.get("trades", []) + self.out.put(("trades", trades)) + offset = clock.get() + if offset is not None and trades: + exchange_time = parse_time(trades[-1].get("time")) + self.out.put(("latency", (time.time() + offset - exchange_time) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с MetaScalp: {exc}; переподключение…")) + time.sleep(2) + + +class BybitFeed(threading.Thread): + """Direct Bybit public WebSocket (orderbook.50 every ~20 ms + public trades), converted to the same events + as the MetaScalp feed. Sizes are converted from coins to USDT so both sources look alike.""" + + def __init__(self, ticker: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.ticker, self.out = ticker, out + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + @staticmethod + def _levels(rows, kind: str) -> list[dict]: + out = [] + for price, size in rows: + p, s = float(price), float(size) + out.append({"price": p, "size": s * p, "type": kind}) + return out + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + self.ws = websocket.create_connection(BYBIT_WS, timeout=10) + self.ws.send(json.dumps({"op": "subscribe", + "args": [f"orderbook.50.{self.ticker}", f"publicTrade.{self.ticker}"]})) + self.out.put(("status", f"Bybit напрямую: {self.ticker}")) + last_ping = time.time() + self.ws.settimeout(5) + while not self.stopped.is_set(): + if time.time() - last_ping > 20: + self.ws.send(json.dumps({"op": "ping"})) + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + topic = str(message.get("topic", "")) + data = message.get("data") + if topic.startswith("orderbook.") and isinstance(data, dict): + if message.get("type") == "snapshot": + self.out.put(("book_snapshot", {"asks": self._levels(data.get("a", []), "Ask"), + "bids": self._levels(data.get("b", []), "Bid")})) + else: + self.out.put(("book_update", self._levels(data.get("a", []), "Ask") + + self._levels(data.get("b", []), "Bid"))) + elif topic.startswith("publicTrade.") and isinstance(data, list): + trades = [] + for row in data: + try: + p = float(row["p"]) + trades.append({"price": p, "size": float(row["v"]) * p, "side": row.get("S"), + "time": datetime.fromtimestamp(int(row["T"]) / 1000, + timezone.utc).isoformat()}) + except (KeyError, TypeError, ValueError): + continue + if trades: + self.out.put(("trades", trades)) + offset = clock.get() + if offset is not None: + self.out.put(("latency", (time.time() + offset - int(data[-1]["T"]) / 1000) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с Bybit: {exc}; переподключение…")) + time.sleep(2) + + +KUCOIN_BULLET = "https://api-futures.kucoin.com/api/v1/bullet-public" +KUCOIN_SPOT_BULLET = "https://api.kucoin.com/api/v1/bullet-public" + + +class KucoinFeed(threading.Thread): + """KuCoin public WebSocket: best bid/ask of one futures contract (tickerV2, e.g. MARSCOINUSDTM) or one spot pair + (/market/ticker, e.g. MARSCOIN-USDT), pushed as ("leader", (bid, ask)) plus ("leader_latency", ms) measured + against Bybit's clock.""" + + def __init__(self, ticker: str, out: queue.Queue, spot: bool = False) -> None: + super().__init__(daemon=True) + self.ticker, self.out, self.spot = ticker, out, spot + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def parse(self, message: dict) -> tuple[float, float, float] | None: + """(bid, ask, exchange time in s) from a futures tickerV2 or a spot /market/ticker message.""" + data = message.get("data") or {} + try: + if self.spot and message.get("subject") == "trade.ticker": + return float(data["bestBid"]), float(data["bestAsk"]), float(data.get("time") or 0) / 1e3 + if not self.spot and message.get("subject") == "tickerV2": + return float(data["bestBidPrice"]), float(data["bestAskPrice"]), float(data.get("ts") or 0) / 1e9 + except (KeyError, TypeError, ValueError): + return None + return None + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + req = urllib.request.Request(KUCOIN_SPOT_BULLET if self.spot else KUCOIN_BULLET, data=b"", + method="POST", headers={"User-Agent": "Mozilla/5.0"}) + with urllib.request.urlopen(req, timeout=10) as resp: + bullet = json.loads(resp.read())["data"] + server = bullet["instanceServers"][0] + self.ws = websocket.create_connection(f"{server['endpoint']}?token={bullet['token']}", timeout=5) + topic = f"/market/ticker:{self.ticker}" if self.spot else f"/contractMarket/tickerV2:{self.ticker}" + self.ws.send(json.dumps({"id": "1", "type": "subscribe", "response": True, "topic": topic})) + self.out.put(("leader_status", f"KuCoin {'спот' if self.spot else 'фьючерс'}: {self.ticker}")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 15: + self.ws.send(json.dumps({"id": "ping", "type": "ping"})) + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + bid_ask = self.parse(message) + if bid_ask is None: + continue + bid, ask, exchange_time = bid_ask + self.out.put(("leader", (bid, ask))) + offset = clock.get() + if offset is not None and exchange_time: + self.out.put(("leader_latency", (time.time() + offset - exchange_time) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("leader_status", f"Нет связи с KuCoin: {exc}; переподключение…")) + time.sleep(2) + + +BINANCE_PUBLIC_WS = "wss://fstream.binance.com/public/stream?streams=" # bookTicker +BINANCE_MARKET_WS = "wss://fstream.binance.com/market/stream?streams=" # aggTrade + + +class BinanceFeed(threading.Thread): + """Binance USDⓈ-M futures: best bid/ask (bookTicker, every change) as a one-level book plus aggregated trades, + as the same events as the Bybit feed (sizes in USDT).""" + + def __init__(self, ticker: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.ticker, self.out = ticker, out + self.stopped = threading.Event() + self.sockets: list = [] + + def stop(self) -> None: + self.stopped.set() + for ws in self.sockets: + try: + ws.close() + except Exception: + pass + + def book_event(self, data: dict) -> tuple | None: + try: + bid, ask = float(data["b"]), float(data["a"]) + return ("book_snapshot", {"bids": [{"price": bid, "size": float(data["B"]) * bid, "type": "Bid"}], + "asks": [{"price": ask, "size": float(data["A"]) * ask, "type": "Ask"}]}) + except (KeyError, TypeError, ValueError): + return None + + @staticmethod + def trade_event(data: dict) -> tuple | None: + try: + p = float(data["p"]) + return ("trades", [{"price": p, "size": float(data["q"]) * p, "side": "Sell" if data.get("m") else "Buy", + "time": datetime.fromtimestamp(int(data["T"]) / 1000, timezone.utc).isoformat()}]) + except (KeyError, TypeError, ValueError): + return None + + def _loop(self, url: str, kind: str) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + ws = websocket.create_connection(url, timeout=5) + self.sockets.append(ws) + self.out.put(("status", f"Binance фьючерс напрямую: {self.ticker}")) + while not self.stopped.is_set(): + try: + message = json.loads(ws.recv()) + except websocket.WebSocketTimeoutException: + continue + data = message.get("data") or {} + event = self.book_event(data) if kind == "book" else self.trade_event(data) + if event: + self.out.put(event) + offset = clock.get() + if kind == "trades" and offset is not None and data.get("T"): + self.out.put(("latency", (time.time() + offset - int(data["T"]) / 1000) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с Binance: {exc}; переподключение…")) + time.sleep(2) + + def run(self) -> None: + s = self.ticker.lower() + threading.Thread(target=self._loop, args=(f"{BINANCE_MARKET_WS}{s}@aggTrade", "trades"), daemon=True).start() + self._loop(f"{BINANCE_PUBLIC_WS}{s}@bookTicker", "book") + + +MEXC_WS = "wss://contract.mexc.com/edge" + + +def mexc_contract(ticker: str) -> tuple[float, float]: + """(price step, coins per contract) of a MEXC USDT perpetual such as SI_USDT.""" + try: + with urllib.request.urlopen(f"https://contract.mexc.com/api/v1/contract/detail?symbol={ticker}", + timeout=15) as resp: + data = json.loads(resp.read())["data"] + return float(data["priceUnit"]), float(data["contractSize"]) + except (OSError, ValueError, KeyError, TypeError): + return 0.0, 1.0 + + +class MexcFeed(threading.Thread): + """MEXC USDT perpetual (e.g. SI_USDT): the top 5 levels of the book (push.depth.full) and trades (push.deal), + as the same events as the Bybit feed (sizes in USDT, from contracts × contract size).""" + + def __init__(self, ticker: str, out: queue.Queue, contract_size: float = 1.0) -> None: + super().__init__(daemon=True) + self.ticker, self.out, self.contract_size = ticker, out, contract_size + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def parse(self, message: dict) -> list[tuple]: + channel, data = message.get("channel"), message.get("data") + events = [] + try: + if channel == "push.depth.full" and isinstance(data, dict): + def levels(rows, kind): + return [{"price": float(p), "size": float(v) * self.contract_size * float(p), "type": kind} + for p, v, *_ in rows] + events.append(("book_snapshot", {"asks": levels(data.get("asks", []), "Ask"), + "bids": levels(data.get("bids", []), "Bid")})) + elif channel == "push.deal": + rows = data if isinstance(data, list) else [data] + trades = [{"price": float(d["p"]), "size": float(d["v"]) * self.contract_size * float(d["p"]), + "side": "Buy" if int(d.get("T", 1)) == 1 else "Sell", + "time": datetime.fromtimestamp(int(d["t"]) / 1000, timezone.utc).isoformat()} + for d in rows] + if trades: + events.append(("trades", trades)) + except (KeyError, TypeError, ValueError): + return [] + return events + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + self.ws = websocket.create_connection(MEXC_WS, timeout=5) + self.ws.send(json.dumps({"method": "sub.depth.full", "param": {"symbol": self.ticker, "limit": 5}})) + self.ws.send(json.dumps({"method": "sub.deal", "param": {"symbol": self.ticker}})) + self.out.put(("status", f"MEXC фьючерс напрямую: {self.ticker}")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 15: + self.ws.send(json.dumps({"method": "ping"})) + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + for event in self.parse(message): + self.out.put(event) + offset = clock.get() + if event[0] == "trades" and offset is not None and message.get("ts"): + self.out.put(("latency", (time.time() + offset - int(message["ts"]) / 1000) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с MEXC: {exc}; переподключение…")) + time.sleep(2) + + +def binance_tick(ticker: str) -> float: + """Price step of a Binance USDⓈ-M perpetual (public REST).""" + try: + with urllib.request.urlopen("https://fapi.binance.com/fapi/v1/exchangeInfo", timeout=15) as resp: + symbols = json.loads(resp.read())["symbols"] + for s in symbols: + if s["symbol"] == ticker.upper(): + return float(next(f["tickSize"] for f in s["filters"] if f["filterType"] == "PRICE_FILTER")) + except (OSError, ValueError, KeyError, StopIteration): + pass + return 0.0 + + +SOLANA_RPC = "https://api.mainnet-beta.solana.com" +SOLANA_WS = "wss://api.mainnet-beta.solana.com" +RAYDIUM_AMM_V4 = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" +RAYDIUM_CPMM = "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C" +PUMPSWAP = "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" +WSOL = "So11111111111111111111111111111111111111112" +STABLES = {"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"} +_B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + +def b58encode(raw: bytes) -> str: + n = int.from_bytes(raw, "big") + out = "" + while n: + n, r = divmod(n, 58) + out = _B58[r] + out + return "1" * (len(raw) - len(raw.lstrip(b"\0"))) + out + + +def solana_rpc(method: str, params: list): + body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode() + req = urllib.request.Request(SOLANA_RPC, data=body, headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=20) as resp: + return json.loads(resp.read())["result"] + + +def raydium_pool(owner: str, data: bytes) -> dict: + """Vaults and mints of a Raydium constant-product pool (AMM v4 or CPMM) from its account data.""" + import struct + if owner == RAYDIUM_AMM_V4: + return {"vault0": b58encode(data[336:368]), "vault1": b58encode(data[368:400]), + "mint0": b58encode(data[400:432]), "mint1": b58encode(data[432:464])} + if owner == RAYDIUM_CPMM: + return {"vault0": b58encode(data[72:104]), "vault1": b58encode(data[104:136]), + "mint0": b58encode(data[168:200]), "mint1": b58encode(data[200:232])} + if owner == PUMPSWAP: + # pool_bump u8, index u16, creator, base_mint, quote_mint, lp_mint, base vault, quote vault + return {"vault0": b58encode(data[139:171]), "vault1": b58encode(data[171:203]), + "mint0": b58encode(data[43:75]), "mint1": b58encode(data[75:107])} + raise ValueError("тип пула не поддерживается: нужен Raydium AMM v4 / CPMM / CLMM, PumpSwap, Meteora DLMM, " + "Orca Whirlpool или PancakeSwap CLMM") + + +METEORA_DLMM = "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" + + +def dlmm_state(data: bytes) -> tuple[int, int, str, str]: + """(active bin id, bin step in bps, token X mint, token Y mint) of a Meteora DLMM LbPair account.""" + import struct + active_id, bin_step = struct.unpack_from(" float: + """Price of X in Y of the active bin: (1 + bin_step/10000) ** active_id, scaled by the decimals.""" + return (1 + bin_step / 10000) ** active_id * 10 ** (decimals_x - decimals_y) + + +ORCA_WHIRLPOOL = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" +RAYDIUM_CLMM = "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK" +PANCAKE_CLMM = "HpNfyc2Saw7RKkQd8nEL4khUcuPhQ7WwY1B2qjx8jxFq" # a Raydium CLMM fork, same pool layout +CLMM_KINDS = {ORCA_WHIRLPOOL: "Orca Whirlpool", RAYDIUM_CLMM: "Raydium CLMM", PANCAKE_CLMM: "PancakeSwap CLMM"} + + +def clmm_state(owner: str, data: bytes) -> tuple[int, str, str]: + """(sqrt price Q64.64, mint of token 0/A, mint of token 1/B) of a concentrated-liquidity pool account.""" + if owner == ORCA_WHIRLPOOL: + # discriminator, config, bump, tick spacing, seed, fee, protocol fee, liquidity u128, sqrt_price u128 @65 + return int.from_bytes(data[65:81], "little"), b58encode(data[101:133]), b58encode(data[181:213]) + # Raydium CLMM PoolState: discriminator, bump, amm config, owner, mint0 @73, mint1 @105, …, sqrt_price_x64 @253 + return int.from_bytes(data[253:269], "little"), b58encode(data[73:105]), b58encode(data[105:137]) + + +def clmm_price(sqrt_price_x64: int, decimals_0: int, decimals_1: int) -> float: + """Price of token 0 in token 1: (sqrt_price / 2**64) ** 2, scaled by the decimals.""" + return (sqrt_price_x64 / 2 ** 64) ** 2 * 10 ** (decimals_0 - decimals_1) + + +def mint_decimals(mint: str) -> int: + return int(solana_rpc("getAccountInfo", [mint, {"encoding": "jsonParsed"}])["value"]["data"]["parsed"]["info"] + ["decimals"]) + + +def pool_price_usd(amounts: dict, token_vault: str, quote_vault: str, quote_usd: float) -> float | None: + token, quote = amounts.get(token_vault), amounts.get(quote_vault) + if not token or not quote or quote_usd <= 0: + return None + return quote / token * quote_usd + + +class RaydiumFeed(threading.Thread): + """A Raydium pool on Solana in real time: the two vault balances over the public Solana RPC WebSocket + (accountSubscribe, 'processed' commitment); price = quote vault / token vault, in USD through Binance's SOL price + when the pool is quoted in SOL. Pushed as ("leader", (price, price)) on every swap (never on SOL moves alone).""" + + def __init__(self, pool: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.pool, self.out = pool, out + self.stopped = threading.Event() + self.ws = None + self.sol_usd = 0.0 + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def _start_sol_price(self) -> None: + if not getattr(self, "_sol_thread", None): + self._sol_thread = threading.Thread(target=self._sol_price, daemon=True) + self._sol_thread.start() + + def _run_dlmm(self, owner: str = METEORA_DLMM) -> None: + """Pools whose price lives in the pool account itself — the pool account is watched, so every swap + refreshes the price. Meteora DLMM: the active bin's (1 + bin step) ** active id; Orca Whirlpool and + Raydium/PancakeSwap CLMM: (sqrt price) ** 2.""" + import base64 + import websocket + data = base64.b64decode(solana_rpc("getAccountInfo", [self.pool, {"encoding": "base64"}])["value"]["data"][0]) + if owner == METEORA_DLMM: + _, _, mint_x, mint_y = dlmm_state(data) + kind = "Meteora DLMM" + else: + _, mint_x, mint_y = clmm_state(owner, data) + kind = CLMM_KINDS[owner] + dec_x, dec_y = mint_decimals(mint_x), mint_decimals(mint_y) + token_is_x = mint_y in (WSOL, *STABLES) or mint_x not in (WSOL, *STABLES) + quote_mint = mint_y if token_is_x else mint_x + if quote_mint == WSOL: + self._start_sol_price() + self.ws = websocket.create_connection(SOLANA_WS, timeout=30) + self.ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "accountSubscribe", + "params": [self.pool, {"encoding": "base64", "commitment": "processed"}]})) + self.out.put(("leader_status", f"{kind} пул {self.pool[:6]}… (Solana, в реальном времени)")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 30: + self.ws.ping() + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + try: + raw = base64.b64decode(message["params"]["result"]["value"]["data"][0]) + except (KeyError, TypeError, IndexError): + continue + if owner == METEORA_DLMM: + active_id, bin_step, _, _ = dlmm_state(raw) + price_y_per_x = dlmm_price(active_id, bin_step, dec_x, dec_y) + else: + price_y_per_x = clmm_price(clmm_state(owner, raw)[0], dec_x, dec_y) + if price_y_per_x <= 0: + continue + in_quote = price_y_per_x if token_is_x else 1 / price_y_per_x + quote_usd = self.sol_usd if quote_mint == WSOL else 1.0 + if quote_usd > 0: + price = in_quote * quote_usd + self.out.put(("leader", (price, price))) + + def _sol_price(self) -> None: + import websocket + while not self.stopped.is_set(): + try: + ws = websocket.create_connection(f"{BINANCE_PUBLIC_WS}solusdt@bookTicker", timeout=5) + while not self.stopped.is_set(): + try: + d = json.loads(ws.recv()).get("data") or {} + except websocket.WebSocketTimeoutException: + continue + if d.get("b") and d.get("a"): + self.sol_usd = (float(d["b"]) + float(d["a"])) / 2 + except Exception: + time.sleep(2) + + def run(self) -> None: + import base64 + import websocket + while not self.stopped.is_set(): + try: + info = solana_rpc("getAccountInfo", [self.pool, {"encoding": "base64"}])["value"] + if info["owner"] == METEORA_DLMM or info["owner"] in CLMM_KINDS: + self._run_dlmm(info["owner"]) + continue + pool = raydium_pool(info["owner"], base64.b64decode(info["data"][0])) + if pool["mint0"] in (WSOL, *STABLES) and pool["mint1"] not in (WSOL, *STABLES): + token_vault, quote_vault, quote_mint = pool["vault1"], pool["vault0"], pool["mint0"] + else: + token_vault, quote_vault, quote_mint = pool["vault0"], pool["vault1"], pool["mint1"] + quote_is_sol = quote_mint == WSOL + if quote_is_sol: + self._start_sol_price() + accounts = solana_rpc("getMultipleAccounts", [[token_vault, quote_vault], + {"encoding": "jsonParsed", "commitment": "processed"}]) + amounts = {acc: v["data"]["parsed"]["info"]["tokenAmount"]["uiAmount"] + for acc, v in zip((token_vault, quote_vault), accounts["value"])} + self.ws = websocket.create_connection(SOLANA_WS, timeout=30) + ids = {} + for i, acc in enumerate((token_vault, quote_vault), start=1): + ids[i] = acc + self.ws.send(json.dumps({"jsonrpc": "2.0", "id": i, "method": "accountSubscribe", + "params": [acc, {"encoding": "jsonParsed", "commitment": "processed"}]})) + subs, slots = {}, {} + kind = "PumpSwap" if info["owner"] == PUMPSWAP else "Raydium" + self.out.put(("leader_status", f"{kind} пул {self.pool[:6]}… (Solana, в реальном времени)")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 30: + self.ws.ping() + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + if "id" in message and "result" in message: + subs[message["result"]] = ids.get(message["id"]) + continue + params = message.get("params") or {} + acc = subs.get(params.get("subscription")) + if acc is None: + continue + try: + amounts[acc] = params["result"]["value"]["data"]["parsed"]["info"]["tokenAmount"]["uiAmount"] + slots[acc] = params["result"]["context"]["slot"] + except (KeyError, TypeError): + continue + # a swap changes both vaults in one slot: price only when both are from the same slot + if slots.get(token_vault) != slots.get(quote_vault): + continue + price = pool_price_usd(amounts, token_vault, quote_vault, self.sol_usd if quote_is_sol else 1.0) + if price: + self.out.put(("leader", (price, price))) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("leader_status", f"Нет связи с Solana: {exc}; переподключение…")) + time.sleep(3) + + +def bybit_tick(ticker: str) -> float: + """Price step of a Bybit USDT perpetual (public REST).""" + try: + with urllib.request.urlopen(f"https://api.bybit.com/v5/market/instruments-info?category=linear&symbol={ticker}", + timeout=10) as resp: + items = json.loads(resp.read())["result"]["list"] + return float(items[0]["priceFilter"]["tickSize"]) if items else 0.0 + except (OSError, ValueError, KeyError, IndexError): + return 0.0 + + +# -------------------------------------------------------------------------------------------- +# Window +# -------------------------------------------------------------------------------------------- + +def run_legacy_window() -> None: + """The previous window with every strategy (simple, adaptive, pulse, sums, Algo Hunter): py -3 scalp_hint.py --legacy""" + import tkinter as tk + from tkinter import messagebox, ttk + + import scalp_paper as sp + + settings = HintSettings() + root = tk.Tk() + root.title("Подсказка скальпера · MetaScalp") + root.geometry("940x960") + root.attributes("-topmost", True) + events: queue.Queue = queue.Queue() + book, tape, journal = OrderBook(), Tape(), Journal(settings) + paper = sp.PaperTrader(sp.PaperSettings(), settings) + engine = HintEngine(settings) + state = {"port": None, "doc": None, "feed": None, "name": "", "last_side": "WAIT", "recorder": None} + + header = tk.StringVar(value="Ищу MetaScalp…") + side_var = tk.StringVar(value="—") + plan_var = tk.StringVar(value="") + reasons_var = tk.StringVar(value="") + stats_var = tk.StringVar(value=journal.stats()) + follow = tk.BooleanVar(value=True) + + body = ttk.Frame(root, padding=10) + body.pack(fill="both", expand=True) + ttk.Label(body, textvariable=header, font=("Segoe UI", 10, "bold"), wraplength=860).pack(anchor="w") + top_row = ttk.Frame(body) + top_row.pack(fill="x") + ttk.Checkbutton(top_row, text="Следовать за стаканом, открытым в MetaScalp", variable=follow).pack(side="left") + sources = {"metascalp": "MetaScalp (стакан ~раз в 220 мс)", "bybit": "Bybit напрямую (стакан ~раз в 20 мс)"} + ttk.Label(top_row, text=" Источник стакана:").pack(side="left") + source_var = tk.StringVar(value=sources.get(paper.settings.data_source, sources["metascalp"])) + source_combo = ttk.Combobox(top_row, textvariable=source_var, values=list(sources.values()), state="readonly", + width=36) + source_combo.pack(side="left", padx=4) + latency_var = tk.StringVar(value="") + ttk.Label(top_row, textvariable=latency_var, foreground="#555").pack(side="left", padx=8) + latencies: deque[float] = deque(maxlen=300) + + def on_source_change(_event=None) -> None: + paper.settings.data_source = next(k for k, v in sources.items() if v == source_var.get()) + paper.ledger.save() + if state["doc"] is not None: + switch(state["doc"]) # reconnect with the new source + + source_combo.bind("<>", on_source_change) + side_label = tk.Label(body, textvariable=side_var, font=("Segoe UI", 22, "bold"), anchor="w") + side_label.pack(fill="x", pady=(8, 2)) + tk.Label(body, textvariable=plan_var, font=("Consolas", 11), justify="left", anchor="w").pack(fill="x") + bars = {} + for key, title in (("book_imb", "Стакан"), ("tape_delta", "Лента"), ("momentum", "Импульс")): + row = ttk.Frame(body) + row.pack(fill="x", pady=1) + ttk.Label(row, text=f"{title:8s}", width=9).pack(side="left") + canvas = tk.Canvas(row, height=14, width=300, highlightthickness=0, background="#e8e8e8") + canvas.pack(side="left") + value = ttk.Label(row, width=7) + value.pack(side="left", padx=4) + bars[key] = (canvas, value) + ttk.Label(body, textvariable=reasons_var, wraplength=860, justify="left").pack(anchor="w", pady=(8, 4)) + ttk.Label(body, textvariable=stats_var, wraplength=860, foreground="#334").pack(anchor="w") + + # --- paper trading ------------------------------------------------------------------- + paper_box = ttk.LabelFrame(body, text="Тестовые сделки (виртуальный счёт, ордера на биржу не уходят)", padding=6) + paper_box.pack(fill="both", expand=True, pady=(8, 0)) + ps = paper.settings + mode_row = ttk.Frame(paper_box) + mode_row.pack(fill="x", pady=(0, 4)) + ttk.Label(mode_row, text="Схема решений:").pack(side="left") + mode_var = tk.StringVar(value=sp.MODES.get(ps.mode, sp.MODES["adaptive"])) + mode_combo = ttk.Combobox(mode_row, textvariable=mode_var, values=list(sp.MODES.values()), state="readonly", + width=42) + mode_combo.pack(side="left", padx=6) + mode_combo.bind("<>", lambda _e: (show_mode_fields(), apply_paper())) + record_var = tk.BooleanVar(value=True) + ttk.Checkbutton(mode_row, text=f"Записывать поток в {sp.RECORD_DIR.name}\\ (для сравнения схем)", + variable=record_var).pack(side="left", padx=10) + # Common settings in the first row; the second row shows only the fields of the selected scheme. + common_fields = (("budget", "Бюджет, $"), ("stake", "Ставка, $"), ("leverage", "Плечо"), + ("min_target_pct", "Цель не меньше, %"), ("max_hold_minutes", "Макс. удержание, мин")) + mode_fields = { + "simple": (("adverse_ticks", "Закрыть при откате, шагов цены"),), + "adaptive": (("noise_mult", "Стоп × шум"), ("min_rr", "Прибыль / риск после комиссий")), + "pulse": (("pulse_offset_pct", "Лимитка от цены, %"),), + "sums": (("sums_depth_pct", "Глубина стакана, ±%"), ("sums_low_pct", "Без мелких: ниже перцентиля"), + ("sums_high_pct", "Без крупных: выше перцентиля"), ("sums_threshold", "Перевес для входа (0–1)")), + # Algo Hunter keeps its own config (algo_hunter_config.json); the key prefix "ah." marks those fields. + "algo_hunter": (("ah.min_confidence", "Мин. уверенность (0–1)"), ("ah.tp_ticks", "TP, шагов цены"), + ("ah.sl_ticks", "SL, шагов цены"), ("ah.max_hold_ms", "Удержание, мс"), + ("ah.min_entry_spread_ticks", "Мин. спред для входа,\nшагов цены (0 = выкл)")), + } + import algo_hunter as ah + ah_cfg = paper.algo_config or ah.AlgoHunterConfig.load() + paper.algo_config = ah_cfg + if ps.mode == "algo_hunter" and getattr(paper.policy, "cfg", None) is not ah_cfg: + paper.policy = paper._make_policy() + paper_vars: dict[str, tk.StringVar] = {} + mode_cells: dict[str, list] = {} + form = ttk.Frame(paper_box) + form.pack(fill="x") + + def add_field(key: str, label: str, row: int, column: int): + cell = ttk.Frame(form) + cell.grid(row=row, column=column, sticky="w", padx=(0, 8), pady=(0, 2)) + ttk.Label(cell, text=label).pack(anchor="w") + source = ah_cfg if key.startswith("ah.") else ps + var = tk.StringVar(value=f"{getattr(source, key.removeprefix('ah.')):g}") + ttk.Entry(cell, textvariable=var, width=12).pack(anchor="w") + paper_vars[key] = var + return cell + + for index, (key, label) in enumerate(common_fields): + add_field(key, label, 0, index) + mode_title = ttk.Label(form, text="", foreground="#1d4f91") + mode_title.grid(row=1, column=0, sticky="sw", pady=(4, 0)) + for mode, items in mode_fields.items(): + mode_cells[mode] = [add_field(key, label, 1, index + 1) for index, (key, label) in enumerate(items)] + invert_var = tk.BooleanVar(value=ps.sums_invert) + invert_cell = ttk.Checkbutton(form, text="Торговать против перевеса\n(LONG ↔ SHORT)", variable=invert_var, + command=lambda: apply_paper()) + invert_cell.grid(row=1, column=len(mode_fields["sums"]) + 1, sticky="sw", padx=(4, 0)) + mode_cells["sums"].append(invert_cell) + dry_run_var = tk.BooleanVar(value=ah_cfg.dry_run) + dry_run_cell = ttk.Checkbutton(form, text="Только проверка (dry-run):\nдетект и лог, без сделок", + variable=dry_run_var, command=lambda: apply_paper()) + dry_run_cell.grid(row=1, column=len(mode_fields["algo_hunter"]) + 1, sticky="sw", padx=(4, 0)) + mode_cells["algo_hunter"].append(dry_run_cell) + quick_exit_var = tk.BooleanVar(value=ah_cfg.quick_exit) + requote_var = tk.BooleanVar(value=ah_cfg.requote) + quick_cell = ttk.Frame(form) + quick_cell.grid(row=1, column=len(mode_fields["algo_hunter"]) + 2, sticky="sw", padx=(4, 0)) + ttk.Checkbutton(quick_cell, text="Закрывать на следующем тике\n(без TP/SL/времени)", variable=quick_exit_var, + command=lambda: apply_paper()).pack(anchor="w") + ttk.Checkbutton(quick_cell, text="Переставлять заявку за стаканом", variable=requote_var, + command=lambda: apply_paper()).pack(anchor="w") + fallback_var = tk.BooleanVar(value=ah_cfg.fallback) + ttk.Checkbutton(quick_cell, text="Без алгоса: микроцена + сдвиги спреда\n(заявка всегда стоит)", + variable=fallback_var, command=lambda: apply_paper()).pack(anchor="w") + mode_cells["algo_hunter"].append(quick_cell) + + def show_mode_fields(*_args) -> None: + mode = next((k for k, v in sp.MODES.items() if v == mode_var.get()), "adaptive") + mode_title.configure(text="Настройки схемы:") + for name, cells in mode_cells.items(): + for cell in cells: + if name == mode: + cell.grid() + else: + cell.grid_remove() + + show_mode_fields() + enabled_var = tk.BooleanVar(value=ps.enabled) + actions = ttk.Frame(paper_box) + actions.pack(fill="x", pady=(4, 2)) + ttk.Checkbutton(actions, text="Открывать тестовые сделки по сигналам", variable=enabled_var, + command=lambda: apply_paper()).pack(side="left") + ttk.Button(actions, text="Применить", command=lambda: apply_paper()).pack(side="left", padx=6) + ttk.Button(actions, text="Закрыть позицию", command=lambda: paper.close_now(book, time.time(), "вручную")).pack( + side="left") + ttk.Button(actions, text="Сбросить счёт", command=lambda: reset_paper()).pack(side="left", padx=6) + paper_summary = tk.StringVar(value=paper.summary()) + paper_position = tk.StringVar(value="") + paper_message = tk.StringVar(value="") + paper_status = tk.StringVar(value="") + ttk.Label(paper_box, textvariable=paper_summary, font=("Segoe UI", 10, "bold")).pack(anchor="w") + ttk.Label(paper_box, textvariable=paper_status, foreground="#1d4f91", wraplength=880).pack(anchor="w") + ttk.Label(paper_box, textvariable=paper_position, wraplength=880).pack(anchor="w") + ttk.Label(paper_box, textvariable=paper_message, foreground="#555", wraplength=860).pack(anchor="w") + columns = ("time", "ticker", "side", "qty", "usd", "entry", "exit", "pct", "net", "fee", "reason", "hold") + heads = {"time": "Закрыта (UTC)", "ticker": "Тикер", "side": "Напр.", "qty": "Объём", "usd": "Объём в $", + "entry": "Цена откр.", "exit": "Цена закр.", "pct": "Процент", "net": "Чистая, $", + "fee": "Комиссия, $", "reason": "Причина", "hold": "Сек."} + widths = {"time": 120, "ticker": 90, "side": 50, "qty": 70, "usd": 70, "entry": 80, "exit": 80, "pct": 65, + "net": 75, "fee": 75, "reason": 150, "hold": 45} + table_frame = ttk.Frame(paper_box) + table_frame.pack(fill="both", expand=True, pady=(4, 0)) + tree = ttk.Treeview(table_frame, columns=columns, show="headings", height=8) + for col in columns: + tree.heading(col, text=heads[col]) + tree.column(col, width=widths[col], anchor="center") + tree.tag_configure("win", foreground="#13843b") + tree.tag_configure("loss", foreground="#c62828") + scroll = ttk.Scrollbar(table_frame, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scroll.set) + tree.pack(side="left", fill="both", expand=True) + scroll.pack(side="right", fill="y") + shown = {"count": -1} + + def apply_paper() -> None: + try: + values = {key: float(var.get().replace(",", ".")) for key, var in paper_vars.items()} + if values["stake"] <= 0 or values["budget"] <= 0 or not 1 <= values["leverage"] <= 100: + raise ValueError("ставка и бюджет больше 0, плечо от 1 до 100") + if values["min_target_pct"] < 0 or values["adverse_ticks"] < 1 or values["max_hold_minutes"] <= 0: + raise ValueError("цель ≥ 0, откат ≥ 1 шага, удержание > 0") + if values["noise_mult"] <= 0 or values["min_rr"] <= 0: + raise ValueError("множитель шума и прибыль/риск больше 0") + if values["pulse_offset_pct"] < 0: + raise ValueError("отступ лимитки не может быть отрицательным") + if not (values["sums_depth_pct"] > 0 and 0 <= values["sums_low_pct"] < values["sums_high_pct"] <= 100 + and 0 < values["sums_threshold"] < 1): + raise ValueError("глубина > 0, перцентили 0 ≤ мелкие < крупные ≤ 100, перевес от 0 до 1") + if not (0 < values["ah.min_confidence"] <= 1 and values["ah.tp_ticks"] >= 1 and values["ah.sl_ticks"] >= 1 + and values["ah.max_hold_ms"] > 0 and values["ah.min_entry_spread_ticks"] >= 0): + raise ValueError("Algo Hunter: уверенность от 0 до 1, TP и SL ≥ 1 шага (SL обязателен), удержание > 0, " + "мин. спред ≥ 0") + except ValueError as exc: + paper_message.set(f"Проверьте настройки: {exc}") + return + budget_changed = values["budget"] != ps.budget + # Settings that live only in algo_hunter_config.json may have been edited by hand: take them from the file. + on_disk = ah.AlgoHunterConfig.load() + for f in fields(ah.AlgoHunterConfig): + if f"ah.{f.name}" not in values and f.name not in ("dry_run", "quick_exit", "requote", "fallback"): + setattr(ah_cfg, f.name, getattr(on_disk, f.name)) + for key, value in values.items(): + if key.startswith("ah."): + name = key.removeprefix("ah.") + setattr(ah_cfg, name, type(getattr(ah_cfg, name))(value)) + else: + setattr(ps, key, int(value) if key == "adverse_ticks" else value) + ah_cfg.dry_run = bool(dry_run_var.get()) + ah_cfg.quick_exit = bool(quick_exit_var.get()) + ah_cfg.requote = bool(requote_var.get()) + ah_cfg.fallback = bool(fallback_var.get()) + ah_cfg.save() + if hasattr(paper.policy, "rearm"): + paper.policy.rearm() # «Применить» switches Algo Hunter back on after an adaptation shutdown + ps.enabled = bool(enabled_var.get()) + ps.sums_invert = bool(invert_var.get()) + mode = next((k for k, v in sp.MODES.items() if v == mode_var.get()), "adaptive") + if mode != ps.mode: + paper.close_now(book, time.time(), "смена схемы") + paper.set_mode(mode) + if budget_changed and not paper.trades and paper.position is None: + paper.ledger.balance = ps.budget + paper.ledger.save() + paper_message.set("Настройки тестовых сделок применены" + + (" · новый бюджет начнёт действовать после «Сбросить счёт»" + if budget_changed and (paper.trades or paper.position) else "")) + + def reset_paper() -> None: + apply_paper() + paper.reset() + shown["count"] = -1 + paper_message.set(f"Счёт сброшен: {ps.budget:g}$") + + ttk.Label(body, text="Это подсказка по текущему стакану, не гарантия. Ордера не отправляются. " + f"Журналы: {JOURNAL_FILE.name}, {sp.TRADES_FILE.name}; записи потока: " + f"{sp.RECORD_DIR.name}\\ (сравнение: py -3 scalp_paper.py compare)", wraplength=880, + foreground="#777").pack(anchor="w", side="bottom") + + def draw_bar(key: str, value: float) -> None: + canvas, label = bars[key] + canvas.delete("all") + width, mid = 300, 150 + x = mid + value * mid + canvas.create_line(mid, 0, mid, 14, fill="#999") + canvas.create_rectangle(min(mid, x), 2, max(mid, x), 12, fill="#2e9d57" if value >= 0 else "#d04a4a", + outline="") + label.configure(text=f"{value:+.2f}") + + def switch(doc: dict) -> None: + if state["feed"]: + state["feed"].stop() + journal.cancel("смена тикера") + paper.close_now(book, time.time(), "смена тикера") + book.clear() + tape.clear() + engine.reset() + state["last_side"] = "WAIT" + state["doc"] = doc + state["name"] = connection_name(state["port"], doc["connectionId"]) + if state["recorder"]: + state["recorder"].close() + state["recorder"] = None + if record_var.get(): + try: + state["recorder"] = sp.Recorder(doc["ticker"], doc["connectionId"], doc["tick"]) + except OSError as exc: + paper_message.set(f"Запись потока недоступна: {exc}") + latencies.clear() + paper.data_latency_ms = None + feed = None + if paper.settings.data_source == "bybit": + info = connection_info(state["port"], doc["connectionId"]) + if info.get("Exchange") == "Bybit" and "USDT" in str(info.get("Market", "")) \ + and "Perpetual" in str(info.get("Market", "")): + feed = BybitFeed(doc["ticker"], events) + else: + paper_message.set(f"Bybit напрямую доступен только для фьючерсов Bybit USDT; {doc['ticker']} " + f"({info.get('Name', '?')}) читается через MetaScalp") + if feed is None: + feed = Feed(state["port"], doc["connectionId"], doc["ticker"], events) + state["feed"] = feed + state["source_name"] = "Bybit напрямую" if isinstance(feed, BybitFeed) else "MetaScalp" + feed.start() + + def poll_ui() -> None: + try: + if state["port"] is None: + state["port"] = discover_port() + if state["port"] is None: + header.set("MetaScalp не найден на 127.0.0.1:17845–17855 — запустите терминал") + if state["port"] is not None and follow.get(): + doc = active_order_book(state["port"]) + if doc and (state["doc"] is None or (doc["connectionId"], doc["ticker"]) != + (state["doc"]["connectionId"], state["doc"]["ticker"])): + switch(doc) + elif doc is None and state["doc"] is None: + header.set("Откройте стакан в MetaScalp") + except Exception as exc: + header.set(f"Ошибка API MetaScalp: {exc}") + state["port"] = None + root.after(2000, poll_ui) + + def pump() -> None: + if record_var.get() and state["recorder"] is None and state["doc"] is not None: + try: + doc = state["doc"] + state["recorder"] = sp.Recorder(doc["ticker"], doc["connectionId"], doc["tick"]) + except OSError: + pass + recorder = state["recorder"] if record_var.get() else None + for _ in range(5000): + try: + kind, data = events.get_nowait() + except queue.Empty: + break + # Receive time is used everywhere (tape, paper trades, recording) so a replay of the + # recording sees exactly the same sequence as the window. + now = time.time() + if kind == "book_snapshot": + book.apply_snapshot(data) + if recorder: + recorder.write("S", {"asks": data.get("asks", []), "bids": data.get("bids", []), + "bestAsk": data.get("bestAsk"), "bestBid": data.get("bestBid")}, now) + if state["doc"]: + paper.on_book(now, book, state["doc"]["tick"]) + elif kind == "book_update": + book.apply_updates(data) + if recorder: + recorder.write("U", data, now) + if state["doc"]: + paper.on_book(now, book, state["doc"]["tick"]) + elif kind == "latency": + latencies.append(float(data)) + if len(latencies) >= 5: + paper.data_latency_ms = statistics.median(latencies) + elif kind == "trades": + if recorder: + recorder.write("T", data, now) + for raw in data: + try: + trade = Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) + except (KeyError, TypeError, ValueError): + continue + tape.add(trade) + journal.on_trade(trade) + paper.on_trade(trade) + elif kind == "status": + header.set(data) + root.after(100, pump) + + def refresh() -> None: + doc = state["doc"] + if doc: + hint = engine(book, tape, doc["tick"], time.time()) + m = hint.metrics + header.set(f"{doc['ticker']} · {state['name']} · данные: {state.get('source_name', '')}" + + (f" · цена {m['mid']:.10g} · спред {m['spread_pct']:.3f}%" if m else "")) + if paper.data_latency_ms is not None: + latency_var.set(f"задержка данных ~{paper.data_latency_ms:.0f} мс (по часам Bybit)") + if (paper.settings.mode == "algo_hunter" and not state.get("latency_warned") + and paper.data_latency_ms > ah_cfg.max_data_latency_ms): + state["latency_warned"] = True + messagebox.showwarning( + "Algo Hunter: задержка слишком большая", + f"Данные приходят с задержкой ~{paper.data_latency_ms:.0f} мс (порог " + f"{ah_cfg.max_data_latency_ms:g} мс). Реальную гонку за место в очереди перед алгосом " + "с такой задержкой не выиграть: режим полезен только как проверка (dry-run) и для " + "виртуальной статистики, а RiskGuard не пустит виртуальные входы при задержке выше " + f"{ah_cfg.max_order_latency_ms:g} мс.", parent=root) + colors = {"LONG": "#1f8a4c", "SHORT": "#c23b3b", "WAIT": "#666"} + side_label.configure(fg=colors[hint.side]) + if hint.side == "WAIT": + side_var.set("ЖДАТЬ") + plan_var.set("") + else: + mid = m["mid"] + side_var.set(f"{hint.side} · уверенность {hint.confidence}") + plan_var.set( + f"Вход лимиткой {hint.entry:.10g} ({(hint.entry / mid - 1) * 100:+.2f}%)\n" + f"Стоп {hint.stop:.10g} ({(hint.stop / mid - 1) * 100:+.2f}%)\n" + f"Цель {hint.target:.10g} ({(hint.target / mid - 1) * 100:+.2f}%)\n" + f"Риск/прибыль 1:{hint.rr:.1f} стоп по времени {settings.hold_minutes:g} мин") + if state["last_side"] != hint.side: + journal.offer(doc["ticker"], hint, time.time()) + state["last_side"] = hint.side + for key in bars: + draw_bar(key, m.get(key, 0.0) if m else 0.0) + reasons_var.set("\n".join("• " + r for r in hint.reasons)) + active = journal.active + stats_var.set("Проверка подсказок лимиткой: " + journal.stats() + ( + f"\nПроверяется: {active.side} от {active.entry:.10g} — " + + ("ждём исполнения" if active.filled_at is None else "в позиции") if active else "")) + if book.asks and book.bids: + paper.on_tick(time.time(), doc["ticker"], hint, book, doc["tick"]) + pos = paper.position + order = paper.pending_order() + if pos: + pnl = paper.unrealized(book) + if paper.settings.mode == "pulse": + plan = "закрытие по рынку на следующем тике" + elif paper.settings.mode == "sums": + plan = (f"цель {pos.target:.10g} · выход при развороте перевеса или через " + f"{paper.settings.max_hold_minutes:g} мин") + else: + plan = (f"цель {pos.target:.10g} · " + (f"стоп {pos.stop:.10g}" if pos.stop is not None else + f"закрытие при откате на {paper.settings.adverse_ticks} шаг(а)")) + paper_position.set( + f"Позиция: {pos.side} {pos.ticker} {pos.qty:.6g} по {pos.entry:.10g} ({pos.entry * pos.qty:.2f}$) · " + f"{plan}{' · ' + pos.regime if pos.regime else ''} · сейчас {pnl:+.4f}$") + elif order and paper.settings.mode == "algo_hunter": + ahead = f"{order.ahead:,.0f}$" if order.ahead is not None else "ещё не на бирже" + paper_position.set(f"Лимитка {order.side} {order.price:.10g} ({order.scenario}) · в очереди перед нами " + f"{ahead} · впереди алгоса: {'да' if order.front_run else 'пока нет'}") + elif order and paper.settings.mode == "sums": + paper_position.set(f"Лимитка {order.side} {order.price:.10g} по лучшей цене — держится, пока есть перевес · " + f"цель {order.target:.10g}") + elif order and paper.settings.mode == "pulse": + paper_position.set(f"Лимитка {order.side} {order.price:.10g} — снимется и переставится на следующем тике, " + "если не исполнится") + elif order: + paper_position.set(f"Ждёт исполнения: лимитка {order.side} {order.price:.10g} ({order.regime}) · стоп " + f"{order.stop:.10g} · цель {order.target:.10g} · {time.time() - order.created:.0f} с") + else: + paper_position.set("Позиции нет" + ("" if paper.settings.enabled else " · тестовые сделки выключены")) + status = paper.policy.status + if paper.settings.mode == "pulse": + status = "Импульс + стакан: " + status + elif paper.settings.mode == "sums": + status = "Суммы: " + status + elif paper.settings.mode == "algo_hunter": + status = "Algo Hunter: " + status + elif paper.settings.mode == "adaptive": + weights = ", ".join(f"{k} {v:.2f}" for k, v in settings.weights.items()) + status = f"Адаптивная: {status}\nВеса признаков: {weights}" + paper_status.set(status) + paper_summary.set(paper.summary()) + if paper.message: + paper_message.set(paper.message) + if shown["count"] != len(paper.trades): + shown["count"] = len(paper.trades) + tree.delete(*tree.get_children()) + for t in reversed(paper.trades[-300:]): + tree.insert("", "end", values=( + t.closed_utc[:19].replace("T", " "), t.ticker, t.side, f"{t.qty:.6g}", f"{t.notional_usd:.2f}", + f"{t.entry:.10g}", f"{t.exit:.10g}", f"{t.pct:+.3f}%", f"{t.net_usd:+.4f}", f"{t.fee_usd:.4f}", + t.reason, f"{t.hold_seconds:.0f}"), tags=("win" if t.net_usd > 0 else "loss",)) + root.after(500, refresh) + + def on_close() -> None: + if state["recorder"]: + state["recorder"].close() + if state["feed"]: + state["feed"].stop() + root.destroy() + + root.protocol("WM_DELETE_WINDOW", on_close) + poll_ui() + pump() + refresh() + root.mainloop() + + +def run_console(seconds: float) -> None: + """Headless check: print a hint every few seconds (used for testing the connection).""" + settings = HintSettings() + port = discover_port() + if port is None: + raise SystemExit("MetaScalp не найден") + doc = active_order_book(port) + if not doc: + raise SystemExit("В MetaScalp не открыт стакан") + events: queue.Queue = queue.Queue() + book, tape = OrderBook(), Tape() + engine = HintEngine(settings) + feed = Feed(port, doc["connectionId"], doc["ticker"], events) + feed.start() + end = time.time() + seconds + next_print = time.time() + 5 + while time.time() < end: + try: + kind, data = events.get(timeout=0.2) + if kind == "book_snapshot": + book.apply_snapshot(data) + elif kind == "book_update": + book.apply_updates(data) + elif kind == "trades": + for raw in data: + tape.add(Trade(parse_time(raw.get("time")), float(raw["price"]), float(raw["size"]), raw["side"])) + except queue.Empty: + pass + hint = engine(book, tape, doc["tick"], time.time()) if book.asks else None + if hint and time.time() >= next_print: + next_print = time.time() + 5 + plan = (f" вход {hint.entry:.10g} стоп {hint.stop:.10g} цель {hint.target:.10g} 1:{hint.rr:.1f}" + if hint.side != "WAIT" else "") + print(f"{doc['ticker']} {hint.side} ({hint.confidence}, score {hint.score:+.2f}){plan}") + for reason in hint.reasons: + print(" ", reason) + feed.stop() + + +if __name__ == "__main__": + import sys + if len(sys.argv) > 2 and sys.argv[1] == "--console": + run_console(float(sys.argv[2])) + elif len(sys.argv) > 1 and sys.argv[1] == "--legacy": + run_legacy_window() + else: + import lead_window + lead_window.run() diff --git a/LinuxServer/scalp_paper.py b/LinuxServer/scalp_paper.py new file mode 100644 index 0000000..1d90f49 --- /dev/null +++ b/LinuxServer/scalp_paper.py @@ -0,0 +1,1589 @@ +"""Paper trading for the scalping hint: a virtual ledger, two decision policies, a stream recorder +and an offline replay that runs any policy over a recorded MetaScalp stream. + +Policies +* simple - market entry whenever the hint is actionable and its target is at least min_target_pct away; + exit at the target (limit), as soon as the mid price moves `adverse_ticks` against the entry, + or on the time stop. +* adaptive - decides from the market state: + - noise: the typical 30-second price swing; the stop sits beyond it (never one tick); + - regime: trend when the last minutes moved efficiently in one direction, otherwise range; + trend -> join the move with a passive limit; range -> fade only at the edge of the range + (near a density), never in the middle; + - costs: the target after fees must be at least min_rr x the stop after fees and slippage; + - self-tuning: component weights move towards what worked, and a losing streak raises the + entry threshold and pauses trading for a while. +No order is ever sent to an exchange. +""" + +from __future__ import annotations + +import csv +import gzip +import json +import os +import math +import statistics +import sys +import time +from collections import deque +from dataclasses import asdict, dataclass, field +from datetime import datetime, timezone +from pathlib import Path + +import scalp_hint as sh +from persistence import atomic_write_json + +ROOT = Path(__file__).resolve().parent +DATA_DIR = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT)).resolve() +STATE_FILE = DATA_DIR / "scalp_paper_state.json" +TRADES_FILE = DATA_DIR / "scalp_paper_trades.csv" +RECORD_DIR = DATA_DIR / "scalp_recordings" +MAKER = sh.MAKER_FEE_PCT +TAKER = sh.TAKER_FEE_PCT +# (taker, maker) fees in % of the USDT perpetuals the lead/vector modes trade on (public base rates) +FOLLOW_FEES = {"bybit": (0.055, 0.02), "binance": (0.05, 0.02), "mexc": (0.02, 0.0)} +COLUMNS = ["closed_utc", "ticker", "mode", "side", "qty", "notional_usd", "entry", "exit", "pct", "net_usd", + "fee_usd", "reason", "hold_seconds", "regime"] +MODES = {"simple": "Простая (вход по рынку, выход при откате)", "adaptive": "Адаптивная", + "pulse": "Импульс + стакан (лимитка, выход на следующем тике)", + "sums": "Суммы значимых заявок (перевес стакана без мелких и крупных)", + "algo_hunter": "Algo Hunter (охота на маркет-мейкерские алгоритмы)", + "lead": "Ведущая биржа: KuCoin → ставки на Bybit", + "vector": "Вектор KuCoin → ставка на Bybit (+цель %)", + "basis": "Разрыв цен ведущей и фьючерса → ставка на схождение"} + + +@dataclass +class PaperSettings: + simulation_entry_delay_ms: float = 600.0 + simulation_exit_delay_ms: float = 600.0 + enabled: bool = True + mode: str = "adaptive" + data_source: str = "metascalp" # "metascalp" or "bybit" (direct public WebSocket, Bybit pairs only) + budget: float = 300.0 + stake: float = 5.0 + leverage: float = 1.0 + min_target_pct: float = 0.2 + max_hold_minutes: float = 5.0 + cooldown_seconds: float = 15.0 + cooldown_ms: float = 0.0 # lead / vector / basis modes: pause after a trade, milliseconds + # simple policy + adverse_ticks: int = 1 + # adaptive policy + noise_mult: float = 1.5 # stop beyond this many typical 30-second swings + min_rr: float = 1.5 # net reward / net risk after fees + limit_timeout_seconds: float = 60.0 + regime_minutes: float = 5.0 + trend_efficiency: float = 0.35 # net move / path length above which the market trends + edge_share: float = 0.25 # range edge = outer quarter of the recent range + reversal_threshold: float = 0.15 # book-based confirmation needed to fade a range edge + loss_streak: int = 3 # losses in a row that trigger a pause + pause_minutes: float = 3.0 + learning: bool = True + learn_rate: float = 0.1 + # pulse policy + pulse_offset_pct: float = 0.15 # limit order at least this far from the current price + # significant-orders policy + sums_depth_pct: float = 0.3 # book window around the mid price + sums_low_pct: float = 20.0 # drop levels smaller than this percentile of sizes (noise) + sums_high_pct: float = 90.0 # drop levels larger than this percentile (outsized walls) + sums_threshold: float = 0.2 # |imbalance| needed to enter; the opposite imbalance closes + sums_invert: bool = False # trade against the imbalance (SHORT on buyer dominance and vice versa) + # lead-exchange policy: a leader exchange's move predicts the follower (where the paper trades are made) + lead_market: str = "futures" # leader: KuCoin "futures", KuCoin "spot" or a "raydium" pool on Solana + lead_pool: str = "" # Raydium pool address (AMM v4 / CPMM) when lead_market == "raydium" + follow_exchange: str = "bybit" # where the paper trades are made: "bybit", "binance" or "mexc" perpetuals + lead_ticker: str = "MARSCOINUSDTM" # KuCoin futures contract (MARSCOINUSDTM) or spot pair (MARSCOIN-USDT) + follow_ticker: str = "MARSCOINUSDT" # Bybit USDT perpetual + lead_threshold_pct: float = 0.05 # leader moved this much more than the follower within the window + lead_window_ms: float = 500.0 + stop_loss_pct: float = 0.3 + max_hold_seconds: float = 30.0 + max_data_age_ms: float = 2000.0 # no entry when either feed has been silent longer than this + min_confidence: float = 0.0 # lead/vector: enter only when the signal's confidence (0-1) is this high + # automatic take-profit: forecast of the follower's move from how far it lags behind the leader + auto_tp: bool = False + auto_tp_share_pct: float = 100.0 # share of the lag the follower is expected to catch up (when not learnt) + auto_tp_learn: bool = True # learn that share from what actually happened after past signals + auto_tp_horizon_seconds: float = 10.0 # ...measured this long after each signal + max_positions: int = 1 # parallel positions (each one stake) in the lead/vector modes + entry_gap_seconds: float = 1.0 # at least this long between two entries + one_per_tick: bool = True # at most one open position per price step (and side) of Bybit's book + cut_loss: bool = False # close at once when Bybit's mid goes against the entry, then go on + cut_loss_ticks: int = 1 # ...by this many price steps (mid vs mid at entry, so the spread + # paid on entry alone does not trigger it); no pause after such a close + # live leader check (all lead modes): who actually moves first right now, from the last minutes of prices + require_leader: bool = True # no entries while the follower, not the leader, moves first + leader_min_edge: float = 0.1 # leader→follower correlation must beat follower→leader by this much + auto_stop_pct: float = 20.0 # web simulator: stop a pair when the futures lead the leader by this + # share, % of (follower→leader − leader→follower) / both; 0 = off + # basis policy: the price gap leader − follower vs its usual level; bet on the gap closing + basis_window_seconds: float = 60.0 # usual gap = exponential average over about this long + basis_entry_z: float = 2.0 # enter when the gap is this many standard deviations from usual + basis_exit_z: float = 0.5 # close when it is back within this many + basis_min_gap_pct: float = 0.15 # ...and only when the extra gap is at least this large (fees) + # vector policy: KuCoin's direction over a longer window, bet on Bybit moving the same way + vector_window_seconds: float = 5.0 + vector_min_move_pct: float = 0.1 + + +@dataclass +class Position: + ticker: str + side: str + qty: float + entry: float + target: float + stop: float | None + opened: float + fee_in: float + entry_mid: float + regime: str = "" + features: dict = field(default_factory=dict) + uid: int = 0 # unique per ledger, so one of several open positions can be closed by hand + margin: float = 0.0 # fixed at entry; changing leverage later must not release collateral + + +@dataclass +class Order: + ticker: str + side: str + price: float + target: float + stop: float + created: float + regime: str + features: dict + + +@dataclass +class PaperTrade: + closed_utc: str + ticker: str + mode: str + side: str + qty: float + notional_usd: float + entry: float + exit: float + pct: float + net_usd: float + fee_usd: float + reason: str + hold_seconds: float + regime: str = "" + + +class Ledger: + def __init__(self, settings: PaperSettings, state_path: Path | None = None, + trades_path: Path | None = None) -> None: + self.settings = settings + self.state_path = state_path + self.trades_path = trades_path + self.balance = settings.budget + self.positions: list[Position] = [] + self.trades: list[PaperTrade] = [] + self.policy_state: dict = {} + self.state_provider = None + self.storage_error = "" + self._recovery_error = "" + self._uid = 0 + self.account = None + self.signal_only = False # private real-signal bookkeeping, never a shared wallet setting + self.account_owner = "" + self.account_origin = self.balance + self._unrealized = 0.0 + self._position_marks: dict[int, float] = {} + self.hooks: list = [] # hook(event, pos): "open" / "close" — real trading mirrors the paper positions + self._load() + + def _load(self) -> None: + snapshot_trades = False + if self.state_path: + try: + state = json.loads(self.state_path.read_text(encoding="utf-8")) + balance = float(state.get("balance", self.settings.budget)) + positions = [Position(**row) for row in state.get("positions", [])] + next_uid = max(int(state.get("next_uid", 0)), + max((pos.uid for pos in positions), default=0)) + policy_state = state.get("policy_state", {}) + if not math.isfinite(balance) or not isinstance(policy_state, dict): + raise ValueError("повреждён снимок счёта") + restored_trades = None + if "trades" in state: + restored_trades = [PaperTrade(**row) for row in state["trades"]] + settings = PaperSettings(**vars(self.settings)) + for key, value in state.get("settings", {}).items(): + if hasattr(settings, key): + setattr(settings, key, type(getattr(settings, key))(value)) + for pos in positions: + if (pos.side not in ("LONG", "SHORT") or not math.isfinite(pos.qty) or pos.qty <= 0 + or not math.isfinite(pos.entry) or pos.entry <= 0): + raise ValueError("повреждена открытая позиция") + if pos.margin <= 0: + pos.margin = pos.qty * pos.entry / max(settings.leverage, 1.0) + self.balance, self.positions, self._uid = balance, positions, next_uid + self.policy_state = policy_state + self._position_marks = {int(uid): float(value) for uid, value in state.get("position_marks", {}).items()} + self._unrealized = float(state.get("unrealized", sum(self._position_marks.values()))) + vars(self.settings).update(vars(settings)) + if restored_trades is not None: + self.trades = restored_trades + snapshot_trades = True + except FileNotFoundError: + pass + except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: + self.storage_error = f"Не удалось восстановить бумажный счёт: {exc}" + self._recovery_error = self.storage_error + if self.trades_path and not snapshot_trades: + header: list[str] = [] + try: + with self.trades_path.open(encoding="utf-8-sig") as file: + reader = csv.DictReader(file) + header = list(reader.fieldnames or []) + for row in reader: + self.trades.append(PaperTrade( + row["closed_utc"], row["ticker"], row.get("mode") or "simple", row["side"], + float(row["qty"]), float(row["notional_usd"]), float(row["entry"]), float(row["exit"]), + float(row["pct"]), float(row["net_usd"]), float(row["fee_usd"]), row["reason"], + float(row["hold_seconds"]), row.get("regime") or "")) + except (OSError, KeyError, ValueError): + pass + if header and header != COLUMNS: + self._rewrite() # an older journal without the mode/regime columns + + def _rewrite(self) -> None: + try: + with self.trades_path.open("w", encoding="utf-8-sig", newline="") as file: + writer = csv.writer(file) + writer.writerow(COLUMNS) + for t in self.trades: + writer.writerow([t.closed_utc, t.ticker, t.mode, t.side, f"{t.qty:.8g}", f"{t.notional_usd:.4f}", + f"{t.entry:.10g}", f"{t.exit:.10g}", f"{t.pct:.4f}", f"{t.net_usd:.6f}", + f"{t.fee_usd:.6f}", t.reason, f"{t.hold_seconds:.1f}", t.regime]) + except OSError: + pass + + def snapshot(self) -> dict: + state = self.state_provider() if self.state_provider else self.policy_state + return {"version": 2, "balance": self.balance, "settings": vars(self.settings).copy(), + "positions": [asdict(pos) for pos in self.positions], "next_uid": self._uid, + "policy_state": state, "account_origin": self.account_origin, + "position_marks": dict(self._position_marks), "unrealized": self._unrealized, + "trades": [asdict(trade) for trade in self.trades]} + + @property + def available(self) -> float: + """Free common collateral when bound; retain standalone balance semantics otherwise.""" + if self.signal_only and self.account is None: + return math.inf + return self.account.view()["free"] if self.account is not None else self.balance + + def bind_account(self, account, owner: str) -> None: + """Attach this ledger to one shared virtual wallet; its snapshot is authoritative.""" + saved = account.restore(owner) + if saved is not None: + self.balance = float(saved["balance"]) + self.account_origin = float(saved["account_origin"]) + self.positions = [Position(**row) for row in saved.get("positions", [])] + self.trades = [PaperTrade(**row) for row in saved.get("trades", [])] + self._uid = int(saved.get("next_uid", 0)) + self.policy_state = saved.get("policy_state", {}) + self._position_marks = {int(uid): float(value) for uid, value in saved.get("position_marks", {}).items()} + self._unrealized = float(saved.get("unrealized", sum(self._position_marks.values()))) + for key, value in saved.get("settings", {}).items(): + if hasattr(self.settings, key): + setattr(self.settings, key, value) + self.storage_error = self._recovery_error = "" + else: + if self._recovery_error: + raise ValueError(self._recovery_error) + self.account_origin = self.balance + sum(pos.fee_in for pos in self.positions) + self.account, self.account_owner = account, owner + if saved is None: + account.commit(owner, self.snapshot(), cash_total=self.balance - self.account_origin, + reserved=sum(pos.margin for pos in self.positions), allow_existing=True, + event="import paper ledger") + + def save(self) -> bool: + if self._recovery_error: + self.storage_error = self._recovery_error + return False + try: + payload = self.snapshot() + if self.account is not None: + self.account.commit(self.account_owner, payload, + cash_total=self.balance - self.account_origin, + reserved=sum(pos.margin for pos in self.positions), unrealized=self._unrealized, + event="paper ledger") + elif self.state_path: + atomic_write_json(self.state_path, payload) + self.storage_error = "" + return True + except Exception as exc: + self.storage_error = f"Не удалось сохранить бумажный счёт: {exc}" + return False + + def reset(self) -> bool: + if self.account is not None and self.positions: + self.storage_error = "Сначала закройте открытые позиции общего виртуального счёта" + return False + previous_balance, previous_positions, previous_trades = self.balance, self.positions, self.trades + previous_marks, previous_unrealized = self._position_marks, self._unrealized + if self.account is None: + self.balance = self.settings.budget + self.position = None + self.trades = [] + self._position_marks, self._unrealized = {}, 0.0 + if not self.save(): + self.balance, self.positions, self.trades = previous_balance, previous_positions, previous_trades + self._position_marks, self._unrealized = previous_marks, previous_unrealized + return False + for pos in previous_positions: # positions dropped by an explicit standalone reset close for real too + for hook in self.hooks: + hook("close", pos) + if self.trades_path: + try: + self.trades_path.unlink() + except OSError: + pass + return True + + def open(self, ticker: str, side: str, price: float, now: float, fee_pct: float, target: float, + stop: float | None, entry_mid: float, regime: str = "", features: dict | None = None, + notional_usd: float | None = None) -> Position | None: + notional = self.settings.stake * self.settings.leverage if notional_usd is None else notional_usd + if not math.isfinite(notional) or notional <= 0 or not math.isfinite(price) or price <= 0: + raise ValueError("Размер и цена бумажной позиции должны быть положительными") + qty = notional / price + fee = notional * fee_pct / 100 + old_balance, old_uid = self.balance, self._uid + self.balance -= fee + self._uid = getattr(self, "_uid", 0) + 1 + pos = Position(ticker, side, qty, price, target, stop, now, fee, entry_mid, regime, features or {}, self._uid, + notional / max(self.settings.leverage, 1.0)) + self.positions.append(pos) + if not self.save(): + self.positions.remove(pos) + self.balance, self._uid = old_balance, old_uid + return None + for hook in self.hooks: + hook("open", pos) + return pos + + @property + def position(self) -> Position | None: + """The first open position (the single position of every mode except parallel lead/vector trading).""" + return self.positions[0] if self.positions else None + + @position.setter + def position(self, value: Position | None) -> None: + self.positions = [] if value is None else [value] + + def close(self, price: float, now: float, reason: str, fee_pct: float, utc: str | None = None, + pos: Position | None = None) -> PaperTrade | None: + pos = pos or self.position + assert pos is not None + old_balance, old_unrealized = self.balance, self._unrealized + index = self.positions.index(pos) + self.positions.remove(pos) + # The next quote will remark any remaining positions; do not retain a closed position's P&L. + previous_mark = self._position_marks.pop(pos.uid, 0.0) + self._unrealized -= previous_mark + sign = 1 if pos.side == "LONG" else -1 + gross = sign * (price - pos.entry) * pos.qty + fee_out = price * pos.qty * fee_pct / 100 + self.balance += gross - fee_out + trade = PaperTrade(utc or datetime.now(timezone.utc).isoformat(timespec="seconds"), pos.ticker, + self.settings.mode, pos.side, pos.qty, pos.entry * pos.qty, pos.entry, price, + sign * (price / pos.entry - 1) * 100, gross - pos.fee_in - fee_out, pos.fee_in + fee_out, + reason, max(0.0, now - pos.opened), pos.regime) + self.trades.append(trade) + if not self.save(): + self.trades.pop() + self.positions.insert(index, pos) + self.balance, self._unrealized = old_balance, old_unrealized + self._position_marks[pos.uid] = previous_mark + return None + for hook in self.hooks: + hook("close", pos) + if self.trades_path: + new_file = not self.trades_path.exists() + try: + with self.trades_path.open("a", encoding="utf-8-sig", newline="") as file: + writer = csv.writer(file) + if new_file: + writer.writerow(COLUMNS) + writer.writerow([trade.closed_utc, trade.ticker, trade.mode, trade.side, f"{trade.qty:.8g}", + f"{trade.notional_usd:.4f}", f"{trade.entry:.10g}", f"{trade.exit:.10g}", + f"{trade.pct:.4f}", f"{trade.net_usd:.6f}", f"{trade.fee_usd:.6f}", + trade.reason, f"{trade.hold_seconds:.1f}", trade.regime]) + except OSError: + pass + return trade + + +def _round(price: float, tick: float, up: bool | None) -> float: + return sh._to_tick(price, tick, up) + + +class SimplePolicy: + name = "simple" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.status = "" + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + led = trader.ledger + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return + mid = (best_bid + best_ask) / 2 + pos = led.position + if pos is not None: + long = pos.side == "LONG" + exit_price = best_bid if long else best_ask + against = (pos.entry_mid - mid) if long else (mid - pos.entry_mid) + if against >= self.s.adverse_ticks * tick - tick * 1e-6: + trader.close(exit_price, now, "курс против — закрыто", TAKER) + elif now - pos.opened >= self.s.max_hold_minutes * 60: + trader.close(exit_price, now, "время", TAKER) + return + if not self.s.enabled or hint.side == "WAIT" or hint.target is None: + return + if now - trader.last_close < self.s.cooldown_seconds: + return + long = hint.side == "LONG" + entry = best_ask if long else best_bid + target_pct = (hint.target - entry) / entry * 100 * (1 if long else -1) + if target_pct < self.s.min_target_pct: + trader.message = (f"Сигнал {hint.side}, но до цели {target_pct:.2f}% < {self.s.min_target_pct:g}% — " + "сделка не открыта") + return + if led.available < self.s.stake: + trader.message = "Баланс меньше ставки — сделки остановлены" + return + led.open(ticker, hint.side, entry, now, TAKER, hint.target, None, mid) + trader.message = f"Открыта {hint.side} {ticker} по {entry:.10g}, цель {hint.target:.10g} (+{target_pct:.2f}%)" + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + pos = trader.ledger.position + if pos is not None: + hit = trade.price > pos.target if pos.side == "LONG" else trade.price < pos.target + if hit: + trader.close(pos.target, trade.ts, "цель", MAKER) + + +class AdaptivePolicy: + name = "adaptive" + + def __init__(self, settings: PaperSettings, hint_settings: sh.HintSettings) -> None: + self.s = settings + self.hs = hint_settings + self.samples: deque[tuple[float, float]] = deque() + self.order: Order | None = None + self.losses = 0 + self.bump = 0.0 + self.pause_until = 0.0 + self.status = "Накапливаю статистику рынка…" + self.base_weights = dict(sh.DEFAULT_WEIGHTS) + + # --- market state ------------------------------------------------------------------ + def market(self, now: float) -> dict | None: + horizon = self.s.regime_minutes * 60 + recent = [(t, m) for t, m in self.samples if t >= now - horizon] + if len(recent) < 20 or recent[-1][0] - recent[0][0] < 0.6 * horizon: + return None + buckets: dict[int, list[float]] = {} + for t, m in self.samples: + if t >= now - 600: + lo_hi = buckets.setdefault(int(t // 30), [m, m]) + lo_hi[0], lo_hi[1] = min(lo_hi[0], m), max(lo_hi[1], m) + noise = statistics.median(hi - lo for lo, hi in buckets.values()) if buckets else 0.0 + points: dict[int, float] = {} + for t, m in recent: + points[int(t // 5)] = m + series = [points[k] for k in sorted(points)] + path = sum(abs(b - a) for a, b in zip(series, series[1:])) + move = series[-1] - series[0] + mids = [m for _, m in recent] + return {"noise": noise, "efficiency": abs(move) / path if path > 0 else 0.0, "move": move, + "high": max(mids), "low": min(mids)} + + # --- main loop --------------------------------------------------------------------- + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return + mid = (best_bid + best_ask) / 2 + self.samples.append((now, mid)) + while self.samples and self.samples[0][0] < now - 900: + self.samples.popleft() + led = trader.ledger + pos = led.position + if pos is not None: + if now - pos.opened >= self.s.max_hold_minutes * 60: + trader.close(best_bid if pos.side == "LONG" else best_ask, now, "время", TAKER) + return + state = self.market(now) + if state is None: + self.status = f"Накапливаю статистику рынка ({self.s.regime_minutes:g} мин)…" + return + trend = state["efficiency"] >= self.s.trend_efficiency and abs(state["move"]) >= 2 * state["noise"] + regime_text = (f"{'тренд ' + ('вверх' if state['move'] > 0 else 'вниз') if trend else 'боковик'} " + f"{state['low']:.10g}–{state['high']:.10g} · шум 30 с {state['noise'] / mid * 100:.3f}% · " + f"направленность {state['efficiency']:.2f}") + threshold = self.hs.score_threshold + self.bump + self.status = regime_text + f" · порог {threshold:.2f}" + ( + f" · пауза ещё {self.pause_until - now:.0f} с" if now < self.pause_until else "") + if self.order is not None: + order = self.order + direction = 1 if order.side == "LONG" else -1 + if now - order.created > self.s.limit_timeout_seconds: + self.order = None + trader.message = f"Лимитка {order.side} {order.price:.10g} снята: не исполнилась за " \ + f"{self.s.limit_timeout_seconds:.0f} с" + elif hint.score * direction < -threshold: + self.order = None + trader.message = f"Лимитка {order.side} снята: перевес сменился" + return + if (not self.s.enabled or now < self.pause_until or now - trader.last_close < self.s.cooldown_seconds + or not hint.metrics or led.available < self.s.stake): + return + spread = best_ask - best_bid + min_risk = max(self.s.noise_mult * state["noise"], 2 * spread, mid * 0.001, 2 * tick) + score = hint.score + metrics = hint.metrics + if trend: + direction = 1 if state["move"] > 0 else -1 + if score * direction < 0.6 * threshold: + return + side = "LONG" if direction > 0 else "SHORT" + entry = best_bid if direction > 0 else best_ask + stop = entry - direction * min_risk + target = entry + direction * max(mid * self.s.min_target_pct / 100, 2 * min_risk) + regime = "тренд" + else: + width = state["high"] - state["low"] + if width < 2 * state["noise"] or width <= 0: + self.status += " · узкий боковик (меньше двух шумов) — не торгую" + return + where = (mid - state["low"]) / width + # At a range edge the tape and momentum point INTO the edge by construction (price just got + # there), so a reversal is confirmed by the book: imbalance near the price and absorption. + reversal = (0.5 * metrics.get("book_imb", 0.0) + 0.25 * metrics.get("near_imb", 0.0) + + 0.25 * metrics.get("absorption", 0.0)) + edge_threshold = self.s.reversal_threshold + self.bump + self.status += f" · разворот {reversal:+.2f} (нужно ±{edge_threshold:.2f})" + if where <= self.s.edge_share and reversal >= edge_threshold: + direction = 1 + anchor = state["low"] + if metrics.get("support"): + anchor = min(anchor, metrics["support"][0]) + entry = best_bid + stop = min(anchor - max(0.5 * state["noise"], 2 * tick), entry - min_risk) + target = state["high"] - tick + regime = "боковик: нижний край" + elif where >= 1 - self.s.edge_share and reversal <= -edge_threshold: + direction = -1 + anchor = state["high"] + if metrics.get("resistance"): + anchor = max(anchor, metrics["resistance"][0]) + entry = best_ask + stop = max(anchor + max(0.5 * state["noise"], 2 * tick), entry + min_risk) + target = state["low"] + tick + regime = "боковик: верхний край" + else: + self.status += (" · середина диапазона — жду края" if self.s.edge_share < where < 1 - self.s.edge_share + else " · у края, но перевеса стакана/ленты нет") + return + side = "LONG" if direction > 0 else "SHORT" + long = direction > 0 + entry = _round(entry, tick, None) + stop = _round(stop, tick, up=not long) + target = _round(target, tick, up=not long) + risk_pct = abs(entry - stop) / entry * 100 + reward_pct = (target - entry) / entry * 100 * direction + if reward_pct < self.s.min_target_pct: + trader.message = f"{side} ({regime}): до цели {reward_pct:.2f}% < {self.s.min_target_pct:g}% — пропуск" + return + net_reward = reward_pct - 2 * MAKER + net_risk = risk_pct + MAKER + TAKER + tick / entry * 100 + if net_reward < self.s.min_rr * net_risk: + trader.message = (f"{side} ({regime}): прибыль {net_reward:.2f}% против риска {net_risk:.2f}% " + f"после комиссий — хуже 1:{self.s.min_rr:g}, пропуск") + return + features = {k: float(metrics.get(k, 0.0)) for k in sh.DEFAULT_WEIGHTS} + self.order = Order(ticker, side, entry, target, stop, now, regime, features) + trader.message = (f"Лимитка {side} {entry:.10g} ({regime}) · стоп {stop:.10g} (−{risk_pct:.2f}%) · " + f"цель {target:.10g} (+{reward_pct:.2f}%)") + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + led = trader.ledger + if self.order is not None: + order = self.order + through = trade.price < order.price if order.side == "LONG" else trade.price > order.price + if through: + self.order = None + led.open(order.ticker, order.side, order.price, trade.ts, MAKER, order.target, order.stop, + order.price, order.regime, order.features) + trader.message = f"Лимитка {order.side} исполнена по {order.price:.10g} ({order.regime})" + pos = led.position + if pos is None: + return + long = pos.side == "LONG" + if pos.stop is not None and (trade.price <= pos.stop if long else trade.price >= pos.stop): + # A stop-market fills at the stop or worse: one tick of slippage beyond the stop. + slip = abs(pos.entry) * 0.0002 + trader.close(pos.stop - slip if long else pos.stop + slip, trade.ts, "стоп", TAKER) + elif trade.price > pos.target if long else trade.price < pos.target: + trader.close(pos.target, trade.ts, "цель", MAKER) + + def on_close(self, trade: PaperTrade, features: dict, now: float) -> None: + if trade.net_usd < 0: + self.losses += 1 + if self.losses >= self.s.loss_streak: + self.pause_until = now + self.s.pause_minutes * 60 + self.bump = min(0.2, self.bump + 0.1) + self.losses = 0 + else: + self.losses = 0 + self.bump = max(0.0, self.bump - 0.05) + if self.s.learning and features: + outcome = 1.0 if trade.net_usd > 0 else -1.0 + direction = 1.0 if trade.side == "LONG" else -1.0 + weights = self.hs.weights + for key, base in self.base_weights.items(): + factor = math.exp(self.s.learn_rate * outcome * direction * features.get(key, 0.0)) + weights[key] = min(2 * base, max(0.5 * base, weights[key] * factor)) + scale = sum(self.base_weights.values()) / sum(weights.values()) + for key in weights: + weights[key] *= scale + + +class PulsePolicy: + """Impulse + book: a limit order `pulse_offset_pct` away from the price in the direction where the price + impulse and the book imbalance agree. A tick is the next trade at a different price: an unfilled order is + then cancelled and re-placed from the new price, and a filled position is closed at market. No time limits.""" + + name = "pulse" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.order: Order | None = None + self.hint: sh.Hint | None = None + self.book: sh.OrderBook | None = None + self.tick = 0.0 + self.ticker = "" + self.last_price: float | None = None + self.status = "Жду импульс и перекос стакана в одну сторону…" + + def direction(self) -> int: + """+1 / -1 when impulse and book agree, 0 otherwise.""" + m = self.hint.metrics if self.hint else {} + momentum, book_imb = m.get("momentum", 0.0), m.get("book_imb", 0.0) + if momentum > 0 and book_imb > 0: + return 1 + if momentum < 0 and book_imb < 0: + return -1 + return 0 + + def place(self, trader: "PaperTrader", now: float) -> None: + self.order = None + if not self.s.enabled or self.book is None or self.hint is None or trader.ledger.position is not None: + return + if trader.ledger.available < self.s.stake: + self.status = "Баланс меньше ставки — сделки остановлены" + return + best_bid, best_ask = self.book.best() + if best_bid is None or best_ask is None or self.tick <= 0: + return + m = self.hint.metrics + direction = self.direction() + if direction == 0: + self.status = (f"Импульс {m.get('momentum', 0.0):+.2f} и стакан {m.get('book_imb', 0.0):+.2f} " + "смотрят в разные стороны — заявки нет") + return + mid = (best_bid + best_ask) / 2 + offset = self.s.pulse_offset_pct / 100 + long = direction > 0 + price = _round(mid * (1 - offset), self.tick, up=False) if long else _round(mid * (1 + offset), self.tick, up=True) + side = "LONG" if long else "SHORT" + self.order = Order(self.ticker, side, price, price, price, now, "импульс + стакан", {}) + self.status = (f"Импульс {m.get('momentum', 0.0):+.2f}, стакан {m.get('book_imb', 0.0):+.2f} → {side}: " + f"лимитка {price:.10g} ({'−' if long else '+'}{self.s.pulse_offset_pct:g}% от {mid:.10g})") + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + self.hint, self.book, self.tick, self.ticker = hint, book, tick, ticker + if self.order is None and trader.ledger.position is None: + self.place(trader, now) + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + new_tick = self.last_price is not None and trade.price != self.last_price + led = trader.ledger + pos = led.position + if pos is not None and new_tick: + best_bid, best_ask = self.book.best() if self.book else (None, None) + exit_price = (best_bid if pos.side == "LONG" else best_ask) or trade.price + trader.close(exit_price, trade.ts, "следующий тик", TAKER) + self.place(trader, trade.ts) + elif self.order is not None: + order = self.order + through = trade.price < order.price if order.side == "LONG" else trade.price > order.price + if through: + self.order = None + led.open(order.ticker, order.side, order.price, trade.ts, MAKER, order.price, None, order.price, + order.regime) + trader.message = f"Лимитка {order.side} исполнена по {order.price:.10g}" + elif new_tick: + self.place(trader, trade.ts) # not filled by the next tick: cancel and re-place from the new price + self.last_price = trade.price + + +class SumsPolicy: + """Direction from the imbalance of significant resting orders (small and outsized levels dropped). + + Entry: a passive limit at the best bid (LONG) / best ask (SHORT) while |imbalance| >= threshold; it is + cancelled when the imbalance weakens or flips. Exit: take-profit limit at min_target_pct, at market when + the imbalance flips beyond the threshold, or on the time stop.""" + + name = "sums" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.order: Order | None = None + self.last: dict | None = None + self.status = "Жду стакан…" + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + s = self.s + info = sh.significant_imbalance(book, s.sums_depth_pct, s.sums_low_pct, s.sums_high_pct) + if info is None: + return + self.last = info + imb = info["imbalance"] + signal = 1 if imb >= s.sums_threshold else -1 if imb <= -s.sums_threshold else 0 + if s.sums_invert: + signal = -signal + self.status = (f"значимые заявки {info['low']:,.0f}–{info['high']:,.0f}$ ({info['used']} из {info['levels']} " + f"уровней ±{s.sums_depth_pct:g}%): покупатели {info['bid_sum']:,.0f}$ / продавцы " + f"{info['ask_sum']:,.0f}$ · перевес {imb:+.2f} → " + + ({1: "LONG", -1: "SHORT", 0: f"нет (нужно ±{s.sums_threshold:g})"}[signal]) + + (" (против перевеса)" if s.sums_invert and signal else "")) + best_bid, best_ask = book.best() + led = trader.ledger + pos = led.position + if pos is not None: + direction = 1 if pos.side == "LONG" else -1 + exit_price = best_bid if direction > 0 else best_ask + if signal == -direction: + trader.close(exit_price, now, "перевес развернулся", TAKER) + elif now - pos.opened >= s.max_hold_minutes * 60: + trader.close(exit_price, now, "время", TAKER) + return + if self.order is not None: + direction = 1 if self.order.side == "LONG" else -1 + touch = best_bid if direction > 0 else best_ask + if signal != direction: + self.order = None + trader.message = "Лимитка снята: перевес ослаб или развернулся" + elif touch != self.order.price: + self.order = Order(ticker, self.order.side, touch, self._target(touch, direction, tick), 0.0, now, + "суммы", {}) # follow the best price + return + if not s.enabled or signal == 0 or led.available < s.stake or now - trader.last_close < s.cooldown_seconds: + return + price = best_bid if signal > 0 else best_ask + self.order = Order(ticker, "LONG" if signal > 0 else "SHORT", price, self._target(price, signal, tick), 0.0, + now, "суммы", {}) + trader.message = f"Лимитка {self.order.side} {price:.10g} по перевесу {imb:+.2f}" + + def _target(self, price: float, direction: int, tick: float) -> float: + return _round(price * (1 + direction * self.s.min_target_pct / 100), tick, up=direction > 0) + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + led = trader.ledger + if self.order is not None: + order = self.order + if trade.price < order.price if order.side == "LONG" else trade.price > order.price: + self.order = None + led.open(order.ticker, order.side, order.price, trade.ts, MAKER, order.target, None, order.price, + "суммы") + trader.message = f"Лимитка {order.side} исполнена по {order.price:.10g}, цель {order.target:.10g}" + pos = led.position + if pos is not None and (trade.price > pos.target if pos.side == "LONG" else trade.price < pos.target): + trader.close(pos.target, trade.ts, "цель", MAKER) + + +class LeadPolicy: + """Leader exchange → paper trades on the follower. + + The leader (KuCoin futures) and the follower (Bybit perpetual) are watched at the same time. When the leader's + mid price moved over the last `lead_window_ms` by at least `lead_threshold_pct` MORE than the follower's mid, + the follower is expected to catch up: a market order is opened on the follower in the leader's direction. + Exits: take-profit `min_target_pct` (limit, filled when the follower trades through it), stop-loss + `stop_loss_pct` (market, on the follower's best price), time `max_hold_seconds` (market).""" + + name = "lead" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.leader: deque[tuple[float, float]] = deque() # (local time, mid) + self.follower: deque[tuple[float, float]] = deque() + self.leader_quote: tuple[float, float] | None = None + self.book: sh.OrderBook | None = None + self.tick = 0.0 + self.ticker = settings.follow_ticker + self.signal = 0.0 # leader move − follower move over the window, % + self.moves = (0.0, 0.0) # (leader, follower) moves over the window, % + self.skip_pause = False # set after a cut-loss close: the next signal does not wait for the pause + self.last_entry = 0.0 + self.last_entry_price: dict[str, float] = {} # side -> price of the last entry (one per price step) + # 0.5 s price grid of both exchanges for the live leader check (and the basis mode) + self.grid: deque[tuple[float, float, float]] = deque(maxlen=2400) # (time, leader mid, follower mid) + self.next_grid = 0.0 + self.next_check = 0.0 + self.leadership: dict = {"lead": 0.0, "follow": 0.0, "edge": None, "pct": None, "minutes": 0.0, + "since": None, "at": None} + self.suitable_since: float | None = None + self.samples: deque[tuple[float, int, float, float]] = deque() # (time, direction, lag %, follower mid) + self.ratios: deque[float] = deque(maxlen=200) # follower's later move / lag at the signal + self.last_sample = 0.0 + self.forecast = 0.0 # forecast follower move for the current signal, % + self.conf = 0.0 # confidence of the current signal, 0-1 + self.status = f"Жду данные {self.L} и {self.F}…" + + @property + def L(self) -> str: + """Name of the leader for the texts.""" + return {"futures": "KuCoin", "spot": "KuCoin спот", "raydium": "DEX"}.get(self.s.lead_market, "KuCoin") + + @property + def F(self) -> str: + """Name of the follower (where the paper trades are made).""" + return {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC"}.get(self.s.follow_exchange, "Bybit") + + @property + def taker(self) -> float: + """Market-order fee of the follower exchange, %.""" + return FOLLOW_FEES.get(self.s.follow_exchange, (TAKER, MAKER))[0] + + @property + def maker(self) -> float: + """Limit-order fee of the follower exchange, %.""" + return FOLLOW_FEES.get(self.s.follow_exchange, (TAKER, MAKER))[1] + + # --- data ------------------------------------------------------------------------------ + def _trim(self, series: deque, now: float) -> None: + keep = max(self.s.lead_window_ms / 1000 * 3, 5.0) + while len(series) > 2 and series[1][0] < now - keep: + series.popleft() + + @staticmethod + def _move(series: deque, now: float, window: float) -> float | None: + """% change of the mid over the last `window` seconds (from the last value at or before now − window).""" + if not series: + return None + start = None + for t, mid in series: + if t <= now - window: + start = mid + else: + break + if start is None: + return None + return (series[-1][1] / start - 1) * 100 + + @staticmethod + def _efficiency(series: deque, now: float, window: float) -> float: + """Net move / path length of the mid over the window: 1 = a clean one-way move, ~0 = back-and-forth.""" + points = [mid for t, mid in series if t >= now - window] + before = [mid for t, mid in series if t < now - window] + if before: + points.insert(0, before[-1]) + if len(points) < 2: + return 0.0 + path = sum(abs(b - a) for a, b in zip(points, points[1:])) + return abs(points[-1] - points[0]) / path if path > 0 else 0.0 + + def confidence(self, move: float, threshold: float, window: float, follow_move: float | None) -> float: + """0-1: average of the KuCoin move's strength (1 at twice the threshold), how one-way it was, and (when + `follow_move` is given) how much Bybit already confirms the direction (1 when it moved as much).""" + parts = [min(1.0, abs(move) / (2 * threshold)) if threshold > 0 else 1.0, + self._efficiency(self.leader, self.leader[-1][0], window)] + if follow_move is not None and move: + parts.append(max(0.0, min(1.0, follow_move / move))) + return sum(parts) / len(parts) + + # --- live leader check ------------------------------------------------------------------ + GRID_STEP = 0.5 + LAGS = 10 # ± 5 s on the 0.5 s grid + + def _sample(self, now: float) -> None: + if now < self.next_grid or not self.leader or not self.follower: + return + self.next_grid = now + self.GRID_STEP + self.grid.append((now, self.leader[-1][1], self.follower[-1][1])) + self._on_grid(now) + if now >= self.next_check and len(self.grid) >= 240: # at least 2 minutes of prices + self.next_check = now + 10 + self.leadership = self.measure_leadership() + # since when the leader has been really leading (suitable for trades), for the indicator + if self.leadership["edge"] >= self.s.leader_min_edge: + self.leadership["since"] = self.suitable_since = self.suitable_since or now + else: + self.suitable_since = None + self.leadership["since"] = None + + def _on_grid(self, now: float) -> None: + """Hook for policies that work on the 0.5 s grid.""" + + def measure_leadership(self) -> dict: + """Sum of positive correlations of grid returns with the follower AFTER the leader (lead) and BEFORE + it (follow), lags up to 5 s; edge = lead − follow (> 0: the leader really moves first).""" + pts = list(self.grid) + rl = [math.log(b[1] / a[1]) for a, b in zip(pts, pts[1:])] + rf = [math.log(b[2] / a[2]) for a, b in zip(pts, pts[1:])] + + def corr(a: list, b: list) -> float: + n = len(a) + if n < 30: + return 0.0 + ma, mb = sum(a) / n, sum(b) / n + va = sum((x - ma) ** 2 for x in a) + vb = sum((y - mb) ** 2 for y in b) + if va <= 0 or vb <= 0: + return 0.0 + return sum((x - ma) * (y - mb) for x, y in zip(a, b)) / math.sqrt(va * vb) + + n = len(rl) + lead = sum(max(0.0, corr(rl[:n - k], rf[k:])) for k in range(1, self.LAGS + 1)) + follow = sum(max(0.0, corr(rl[k:], rf[:n - k])) for k in range(1, self.LAGS + 1)) + # the same as a percentage: +100 = only the leader moves first, −100 = only the follower does + pct = (lead - follow) / (lead + follow) * 100 if lead + follow > 0 else 0.0 + return {"lead": lead, "follow": follow, "edge": lead - follow, "pct": pct, + "minutes": (pts[-1][0] - pts[0][0]) / 60, "at": pts[-1][0]} + + def leader_block(self) -> str: + """Why the live leader check blocks entries now ('' = it does not).""" + if not self.s.require_leader: + return "" + edge = self.leadership.get("edge") + if edge is None: + return f"проверяю, кто ведёт: копится {len(self.grid) * self.GRID_STEP / 60:.1f} из 2 мин цен" + if edge < self.s.leader_min_edge: + who = self.F if edge < 0 else "никто явно" + return (f"сейчас ведёт {who}, а не {self.L} ({self.L}→{self.F} {self.leadership['lead']:.2f} / " + f"{self.F}→{self.L} {self.leadership['follow']:.2f})") + return "" + + def on_leader(self, trader: "PaperTrader", now: float, bid: float, ask: float) -> None: + if bid <= 0 or ask <= 0 or bid > ask: # bid == ask: a DEX pool price (no book) + return + self.leader_quote = (bid, ask) + self.leader.append((now, (bid + ask) / 2)) + self._trim(self.leader, now) + self._sample(now) + self._evaluate(trader, now) + + def on_book(self, trader: "PaperTrader", now: float, book: sh.OrderBook, tick: float) -> None: + self.book = book + if tick > 0: + self.tick = tick + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return + self.follower.append((now, (best_bid + best_ask) / 2)) + self._trim(self.follower, now) + self._sample(now) + mid = (best_bid + best_ask) / 2 + for pos in list(trader.ledger.positions): + long = pos.side == "LONG" + exit_price = best_bid if long else best_ask + against = (pos.entry_mid - mid if long else mid - pos.entry_mid) / self.tick if self.tick > 0 else 0.0 + if pos.stop is not None and (exit_price <= pos.stop if long else exit_price >= pos.stop): + trader.close(exit_price, now, "стоп", self.taker, pos=pos) + elif now - pos.opened >= self.s.max_hold_seconds: + trader.close(exit_price, now, "время", self.taker, pos=pos) + elif self.s.cut_loss and against >= self.s.cut_loss_ticks - 1e-9: + trader.close(exit_price, now, "минус — закрыта сразу", self.taker, pos=pos) + self.skip_pause = True # the next signal is taken at once + self._extra_exits(trader, now, best_bid, best_ask) + self._resolve_samples(now, mid) + self._evaluate(trader, now) + + def _extra_exits(self, trader: "PaperTrader", now: float, best_bid: float, best_ask: float) -> None: + """Hook for policy-specific exits (the basis mode closes when the gap is gone).""" + + # --- forecast for the automatic take-profit ---------------------------------------------- + def _resolve_samples(self, now: float, mid: float) -> None: + """How much of the lag did the follower actually catch up `auto_tp_horizon_seconds` after each signal.""" + while self.samples and self.samples[0][0] <= now - self.s.auto_tp_horizon_seconds: + _, d, lag, mid0 = self.samples.popleft() + if lag > 0 and mid0 > 0: + self.ratios.append(d * (mid / mid0 - 1) * 100 / lag) + + def share(self) -> tuple[float, str]: + """(share of the lag expected to be caught up, where it comes from).""" + if self.s.auto_tp_learn and len(self.ratios) >= 10: + return max(0.0, min(3.0, statistics.median(self.ratios))), f"выучено по {len(self.ratios)} сигналам" + note = f"копится история {len(self.ratios)}/10" if self.s.auto_tp_learn else "задано вручную" + return self.s.auto_tp_share_pct / 100, note + + def _record_sample(self, now: float, direction: int) -> None: + if direction == 0 or now - self.last_sample < 1.0 or not self.follower: + return + lead_move, follow_move = self.moves + lag = direction * (lead_move - follow_move) + if lag > 0: + self.samples.append((now, direction, lag, self.follower[-1][1])) + self.last_sample = now + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + for pos in list(trader.ledger.positions): + long = pos.side == "LONG" + if (trade.price > pos.target) if long else (trade.price < pos.target): + trader.close(pos.target, trade.ts, "цель", self.maker, pos=pos) + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint, book: sh.OrderBook, tick: float) -> None: + self.ticker = ticker or self.s.follow_ticker + self.book = book + if tick > 0: + self.tick = tick + + # --- decision -------------------------------------------------------------------------- + def _signal(self, now: float) -> tuple[int, str, str, str] | None: + """(direction +1/−1/0, status text, why not entering, why entered) or None while data is gathering.""" + window = self.s.lead_window_ms / 1000 + lead_move = self._move(self.leader, now, window) + follow_move = self._move(self.follower, now, window) + if lead_move is None or follow_move is None: + return None + self.moves = (lead_move, follow_move) + self.signal = lead_move - follow_move + # Bybit lagging is the signal here, so its own move does not add confidence + self.conf = self.confidence(lead_move, self.s.lead_threshold_pct, window, None) + base = (f"{self.L} {lead_move:+.3f}% · {self.F} {follow_move:+.3f}% за {self.s.lead_window_ms:g} мс · " + f"отставание {self.F} {self.signal:+.3f}% (порог ±{self.s.lead_threshold_pct:g}%) · " + f"уверенность {self.conf:.2f}") + # only KuCoin's own move is a signal; Bybit moving first is not traded + if (abs(lead_move) < self.s.lead_threshold_pct or abs(self.signal) < self.s.lead_threshold_pct + or lead_move * self.signal <= 0): + return 0, base, f"ждём, когда {self.L} уйдёт вперёд", "" + return ((1 if self.signal > 0 else -1), base, "", + f"{self.L} {lead_move:+.3f}% / {self.F} {follow_move:+.3f}% · уверенность {self.conf:.2f}") + + def _evaluate(self, trader: "PaperTrader", now: float) -> None: + sig = self._signal(now) + if sig is None: + self.status = "Копятся данные обеих бирж…" + return + direction, base, wait, why = sig + self._record_sample(now, direction) + if self.s.auto_tp and direction: + share, note = self.share() + lead_move, follow_move = self.moves + self.forecast = max(0.0, share * direction * (lead_move - follow_move)) + base += f" · прогноз {self.F} {direction * self.forecast:+.3f}% (доля {share * 100:.0f}%, {note})" + stale = max(now - self.leader[-1][0], now - self.follower[-1][0]) * 1000 + open_n = len(trader.ledger.positions) + if open_n: + base += f" · открыто позиций {open_n} из {max(1, int(self.s.max_positions))}" + reason = "" + if open_n >= max(1, int(self.s.max_positions)): + reason = "открыто максимум позиций" + elif open_n and now - self.last_entry < self.s.entry_gap_seconds: + reason = f"следующая позиция не раньше чем через {self.s.entry_gap_seconds - (now - self.last_entry):.1f} с" + elif not self.s.enabled: + reason = "тестовые сделки выключены" + elif trader.gate is not None and trader.gate(): + reason = trader.gate() # real trading: the previous real trade is not closed yet + elif stale > self.s.max_data_age_ms: + reason = f"данные устарели ({stale:.0f} мс)" + elif (now - trader.last_close) * 1000 < self.s.cooldown_ms and not self.skip_pause: + reason = f"пауза после сделки ещё {self.s.cooldown_ms - (now - trader.last_close) * 1000:.0f} мс" + elif trader.ledger.available < self.s.stake * (1 if trader.ledger.account is not None else open_n + 1): + reason = "баланса не хватает ещё на одну ставку" + elif direction == 0: + reason = wait + elif self.leader_block(): + reason = self.leader_block() + elif self.conf < self.s.min_confidence: + reason = f"уверенность {self.conf:.2f} ниже порога {self.s.min_confidence:g}" + self.status = base + (f" · {reason}" if reason else "") + if reason or self.book is None: + return + best_bid, best_ask = self.book.best() + if best_bid is None or best_ask is None: + return + long = direction > 0 + price = best_ask if long else best_bid # market order on the follower + side = "LONG" if long else "SHORT" + half = (self.tick or price * 1e-9) / 2 + # forget the last entry price once Bybit's price for that side has moved to another step + for s_, p_ in list(self.last_entry_price.items()): + current = best_ask if s_ == "LONG" else best_bid + if abs(current - p_) >= half: + del self.last_entry_price[s_] + if self.s.one_per_tick: + if any(p.side == side and abs(p.entry - price) < half for p in trader.ledger.positions): + self.status = base + f" · на цене {price:.10g} уже есть позиция {side} (одна на шаг цены)" + return + if side in self.last_entry_price: + # one entry per price step even if the previous one is already closed: the next one only after + # Bybit's price moves to another step + self.status = base + f" · на цене {price:.10g} уже был вход {side} — жду другой шаг цены" + return + spread_pct = (best_ask - best_bid) / ((best_ask + best_bid) / 2) * 100 + if spread_pct >= self.s.stop_loss_pct: + self.status = (base + f" · спред {self.F} {spread_pct:.3f}% не меньше стоп-лосса {self.s.stop_loss_pct:g}% — " + "сделка закрылась бы по стопу сразу") + return + sign = 1 if long else -1 + if self.s.auto_tp: + # take-profit where the forecast puts Bybit's mid; skip when that does not pay spread and fees + target = (best_bid + best_ask) / 2 * (1 + sign * self.forecast / 100) + expected = sign * (target / price - 1) * 100 - (self.taker + self.maker) + if expected <= 0: + self.status = (base + f" · прогноз {sign * self.forecast:+.3f}% не покрывает спред и комиссию " + f"({self.taker + self.maker:.3f}%)") + return + why += f" · прогноз {sign * self.forecast:+.3f}%" + else: + target = price * (1 + sign * self.s.min_target_pct / 100) + stop = price * (1 - sign * self.s.stop_loss_pct / 100) + if self.tick > 0: + target = _round(target, self.tick, up=long) + stop = _round(stop, self.tick, up=not long) + self.skip_pause = False + self.last_entry = now + self.last_entry_price[side] = price + trader.ledger.open(self.ticker, side, price, now, self.taker, target, stop, (best_bid + best_ask) / 2, why) + trader.message = f"Открыта {side} {self.ticker} по {price:.10g} · {why} · цель {target:.10g}" + + +class VectorPolicy(LeadPolicy): + """Direction (vector) of KuCoin over the last `vector_window_seconds` → the same direction on Bybit. + + Rising on KuCoin → LONG on Bybit, falling → SHORT, once the KuCoin move over the window is at least + `vector_min_move_pct`. Unlike the lead mode, Bybit having moved too does not matter. Same exits: take-profit + `min_target_pct` (e.g. +0.2%), stop-loss, holding time.""" + + name = "vector" + + def _trim(self, series: deque, now: float) -> None: + keep = max(self.s.vector_window_seconds * 2, 5.0) + while len(series) > 2 and series[1][0] < now - keep: + series.popleft() + + def _signal(self, now: float) -> tuple[int, str, str, str] | None: + move = self._move(self.leader, now, self.s.vector_window_seconds) + follow_move = self._move(self.follower, now, self.s.vector_window_seconds) + if move is None or follow_move is None: + return None + self.moves = (move, follow_move) + self.signal = move + self.conf = self.confidence(move, self.s.vector_min_move_pct, self.s.vector_window_seconds, follow_move) + base = (f"Вектор {self.L} за {self.s.vector_window_seconds:g} с: {move:+.3f}% ({self.F} {follow_move:+.3f}%) · " + f"порог ±{self.s.vector_min_move_pct:g}% · уверенность {self.conf:.2f}") + if abs(move) < self.s.vector_min_move_pct: + return 0, base, "направления нет", "" + word = "растёт" if move > 0 else "падает" + return ((1 if move > 0 else -1), base, "", + f"{self.L} {word} {move:+.3f}% за {self.s.vector_window_seconds:g} с · уверенность {self.conf:.2f}") + + +class BasisPolicy(LeadPolicy): + """The price gap between the leader and the follower (ln leader − ln follower, %) against its usual level. + + The usual gap and its spread are exponential averages over `basis_window_seconds` on the 0.5 s grid. When the + gap is `basis_entry_z` standard deviations (and at least `basis_min_gap_pct`) away from usual — typically a DEX + jump the futures have not followed yet — the follower is bought (gap above usual) or sold (below) for the gap to + close. The position is closed when the gap is back within `basis_exit_z` deviations («разрыв закрылся»), or by + take-profit / stop-loss / holding time. With the automatic take-profit the forecast is share × extra gap.""" + + name = "basis" + + def __init__(self, settings: PaperSettings) -> None: + super().__init__(settings) + self.b_mean: float | None = None + self.b_var = 0.0 + self.b_count = 0 + self.dev = 0.0 + self.z = 0.0 + + def _basis(self) -> float | None: + if not self.leader or not self.follower: + return None + return (math.log(self.leader[-1][1]) - math.log(self.follower[-1][1])) * 100 + + def _on_grid(self, now: float) -> None: + b = self._basis() + if b is None: + return + alpha = min(1.0, self.GRID_STEP / max(self.s.basis_window_seconds, self.GRID_STEP)) + if self.b_mean is None: + self.b_mean, self.b_var = b, 0.0 + else: + diff = b - self.b_mean + self.b_mean += alpha * diff + self.b_var = (1 - alpha) * (self.b_var + alpha * diff * diff) + self.b_count += 1 + + def _sd(self) -> float: + return max(math.sqrt(self.b_var), 0.01) # at least 0.01 %: a flat gap is not "many sigmas" off + + def _signal(self, now: float) -> tuple[int, str, str, str] | None: + b = self._basis() + warm = int(self.s.basis_window_seconds / self.GRID_STEP / 2) + if b is None or self.b_mean is None or self.b_count < warm: + return None + self.dev = b - self.b_mean + self.z = self.dev / self._sd() + self.moves = (self.dev, 0.0) # the extra gap is what the follower should catch up + self.signal = self.dev + self.conf = min(1.0, abs(self.z) / (2 * self.s.basis_entry_z)) + base = (f"разрыв {self.L}−{self.F} {b:+.3f}% · обычный {self.b_mean:+.3f}% ±{self._sd():.3f}% · " + f"отклонение {self.dev:+.3f}% ({self.z:+.1f}σ, вход от {self.s.basis_entry_z:g}σ и " + f"{self.s.basis_min_gap_pct:g}%)") + if abs(self.z) < self.s.basis_entry_z or abs(self.dev) < self.s.basis_min_gap_pct: + return 0, base, "разрыв в обычных пределах", "" + side = "выше" if self.dev > 0 else "ниже" + return ((1 if self.dev > 0 else -1), base, "", + f"{self.L} {side} {self.F} на {abs(self.dev):.3f}% сверх обычного ({self.z:+.1f}σ)") + + def _extra_exits(self, trader: "PaperTrader", now: float, best_bid: float, best_ask: float) -> None: + b = self._basis() + if b is None or self.b_mean is None: + return + dev = b - self.b_mean + for pos in list(trader.ledger.positions): + sign = 1 if pos.side == "LONG" else -1 + if sign * dev <= self.s.basis_exit_z * self._sd(): + trader.close(best_bid if sign > 0 else best_ask, now, "разрыв закрылся", self.taker, pos=pos) + + +class PaperTrader: + """Ledger + the selected policy; used by the window and by the replay.""" + + def __init__(self, settings: PaperSettings, hint_settings: sh.HintSettings, + state_path: Path | None = STATE_FILE, trades_path: Path | None = TRADES_FILE) -> None: + self.settings = settings + self.hint_settings = hint_settings + self.ledger = Ledger(settings, state_path, trades_path) + self.message = "" + self.last_close = 0.0 + self.gate = None # callable → "" or why no new position may open (real trading: previous not closed) + self.data_latency_ms: float | None = None # measured delay of market data, set by the window + self.algo_config = None # AlgoHunterConfig, loaded lazily for the algo_hunter mode + if settings.mode == "algo_hunter": + import algo_hunter + self.algo_config = algo_hunter.AlgoHunterConfig.load() if state_path else algo_hunter.AlgoHunterConfig() + self.policy = self._make_policy() + self._restore_policy() + self.ledger.state_provider = self._policy_snapshot + self._last_checkpoint = 0.0 + + def _policy_snapshot(self) -> dict: + # Quotes and pending orders are deliberately not restored: the feeds must warm up again. + names = ("losses", "bump", "pause_until", "last_entry", "last_entry_price", "skip_pause", + "b_mean", "b_var", "b_count", "tick", "ticker") + policy = {name: getattr(self.policy, name) for name in names if hasattr(self.policy, name)} + export = getattr(self.policy, "export_state", None) + if export: + policy.update(export()) + return {"mode": self.settings.mode, "last_close": self.last_close, + "weights": dict(self.hint_settings.weights), "policy": policy} + + def _restore_policy(self) -> None: + state = self.ledger.policy_state + if state.get("mode") != self.settings.mode: + return + self.last_close = float(state.get("last_close", 0.0)) + self.hint_settings.weights.update(state.get("weights", {})) + policy = state.get("policy", {}) + for name in ("losses", "bump", "pause_until", "last_entry", "last_entry_price", "skip_pause", + "b_mean", "b_var", "b_count", "tick", "ticker"): + if name in policy and hasattr(self.policy, name): + setattr(self.policy, name, policy[name]) + restore = getattr(self.policy, "restore_state", None) + if restore: + restore(policy, self.ledger.position) + + def bind_account(self, account, owner: str) -> None: + self.ledger.bind_account(account, owner) + self.policy = self._make_policy() + self._restore_policy() + + def _checkpoint(self, now: float, force: bool = False) -> None: + if force or (self.ledger.positions and now - self._last_checkpoint >= 5): + self.ledger.save() + self._last_checkpoint = now + + def _make_policy(self): + if self.settings.mode == "adaptive": + return AdaptivePolicy(self.settings, self.hint_settings) + if self.settings.mode == "pulse": + return PulsePolicy(self.settings) + if self.settings.mode == "sums": + return SumsPolicy(self.settings) + if self.settings.mode == "lead": + return LeadPolicy(self.settings) + if self.settings.mode == "vector": + return VectorPolicy(self.settings) + if self.settings.mode == "basis": + return BasisPolicy(self.settings) + if self.settings.mode == "algo_hunter": + import algo_hunter # isolated module, loaded only when the mode is selected + return algo_hunter.AlgoHunterPolicy(self.settings, self.algo_config, + algo_hunter.TRADES_FILE if self.ledger.trades_path else None) + return SimplePolicy(self.settings) + + def set_mode(self, mode: str) -> None: + if mode != self.settings.mode: + self.settings.mode = mode + if mode == "algo_hunter" and self.algo_config is None: + import algo_hunter + self.algo_config = algo_hunter.AlgoHunterConfig.load() + self.policy = self._make_policy() + self.ledger.save() + + def on_book(self, now: float, book: sh.OrderBook, tick: float) -> None: + """Every order-book update (only policies that watch the book itself use it).""" + handler = getattr(self.policy, "on_book", None) + if handler is not None: + handler(self, now, book, tick) + self.mark_account(book) + self._checkpoint(now) + + def on_leader(self, now: float, bid: float, ask: float) -> None: + """Best quotes of the leader exchange (lead mode only).""" + handler = getattr(self.policy, "on_leader", None) + if handler is not None: + handler(self, now, bid, ask) + + @property + def position(self) -> Position | None: + return self.ledger.position + + @property + def trades(self) -> list[PaperTrade]: + return self.ledger.trades + + @property + def balance(self) -> float: + return self.ledger.balance + + def pending_order(self) -> Order | None: + return getattr(self.policy, "order", None) + + def on_tick(self, now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, tick: float) -> None: + self.policy.on_tick(self, now, ticker, hint, book, tick) + self._checkpoint(now) + + def on_trade(self, trade: sh.Trade) -> None: + before = [(p.uid, p.qty, p.stop, p.target) for p in self.ledger.positions] + self.policy.on_trade(self, trade) + after = [(p.uid, p.qty, p.stop, p.target) for p in self.ledger.positions] + if before != after: + self._checkpoint(trade.ts, force=True) + + def close(self, price: float, now: float, reason: str, fee_pct: float, utc: str | None = None, + pos: Position | None = None) -> None: + target = pos or self.ledger.position + features = target.features if target else {} + trade = self.ledger.close(price, now, reason, fee_pct, utc, pos) + if trade is None: + self.message = self.ledger.storage_error + return + self.last_close = now + self.message = f"Закрыта {trade.side} {trade.ticker}: {reason}, итог {trade.net_usd:+.4f}$" + if isinstance(self.policy, AdaptivePolicy): + self.policy.on_close(trade, features, now) + self.ledger.save() + + def close_now(self, book: sh.OrderBook, now: float, reason: str) -> None: + if hasattr(self.policy, "order"): + self.policy.order = None + best_bid, best_ask = book.best() + for pos in list(self.ledger.positions): + price = (best_bid if pos.side == "LONG" else best_ask) or pos.entry + self.close(price, now, reason, TAKER, pos=pos) + + def reset(self) -> None: + if not self.ledger.reset(): + self.message = self.ledger.storage_error + return + self.policy = self._make_policy() + self.hint_settings.weights = dict(sh.DEFAULT_WEIGHTS) + self.ledger.save() + + def unrealized(self, book: sh.OrderBook) -> float: + best_bid, best_ask = book.best() + total = 0.0 + for pos in self.ledger.positions: + price = best_bid if pos.side == "LONG" else best_ask + if price is not None: + gross = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty + total += gross + return total + + def mark_account(self, book: sh.OrderBook) -> None: + """Call only for a fresh follower-book update, never for a UI/timer refresh.""" + if self.ledger.account is None: + return + bid, ask = book.best() + if bid is None or ask is None: + return + marks = {} + for pos in self.ledger.positions: + price = bid if pos.side == "LONG" else ask + marks[pos.uid] = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty - price * pos.qty * TAKER / 100 + self.ledger._position_marks = marks + self.ledger._unrealized = sum(marks.values()) + self.ledger.account.mark(self.ledger.account_owner, self.ledger._unrealized) + + def summary(self) -> str: + trades = self.ledger.trades + n = len(trades) + wins = sum(t.net_usd > 0 for t in trades) + net = sum(t.net_usd for t in trades) + fees = sum(t.fee_usd for t in trades) + return (f"Баланс {self.ledger.balance:.2f}$ (старт {self.settings.budget:g}$) · сделок {n} · в плюс {wins}" + f"{f' ({wins / n * 100:.0f}%)' if n else ''} · чистая прибыль {net:+.4f}$ · комиссии {fees:.4f}$") + + +# -------------------------------------------------------------------------------------------- +# Recording and replay +# -------------------------------------------------------------------------------------------- + +class Recorder: + """Appends the raw MetaScalp stream to a gzip JSON-lines file: [receive_time, kind, data].""" + + def __init__(self, ticker: str, connection_id: int, tick: float, folder: Path = RECORD_DIR) -> None: + folder.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + self.path = folder / f"{ticker}_{connection_id}_{stamp}.jsonl.gz" + self.file = gzip.open(self.path, "at", encoding="utf-8") + self.lines = 0 + self.write("meta", {"ticker": ticker, "connectionId": connection_id, "tick": tick}) + + def write(self, kind: str, data, now: float | None = None) -> None: + if self.file is None: + return + self.file.write(json.dumps([round(now if now is not None else time.time(), 3), kind, data], + separators=(",", ":")) + "\n") + self.lines += 1 + if self.lines % 500 == 0: + self.file.flush() + + def close(self) -> None: + if self.file is not None: + self.file.close() + self.file = None + + +def read_recording(path: Path): + """Rows of a recording; a file still being written (or cut off) is read up to its last flushed line.""" + try: + with gzip.open(path, "rt", encoding="utf-8") as file: + for line in file: + try: + yield json.loads(line) + except json.JSONDecodeError: + return + except (EOFError, OSError): + return + + +def replay(paths: list[Path], settings: PaperSettings, step: float = 0.5, algo_config=None) -> PaperTrader: + """Run a policy over recordings exactly as the window would: book/tape updates, a decision every step.""" + hint_settings = sh.HintSettings() + trader = PaperTrader(settings, hint_settings, state_path=None, trades_path=None) + if algo_config is not None: + trader.algo_config = algo_config + trader.policy = trader._make_policy() + for path in paths: + book, tape = sh.OrderBook(), sh.Tape() + engine = sh.HintEngine(hint_settings) + meta = {"ticker": "?", "tick": 0.0} + next_tick = None + last_t = None + for t, kind, data in read_recording(path): + if kind == "meta": + meta = data + continue + while next_tick is not None and next_tick <= t: + if book.asks and book.bids: + hint = engine(book, tape, meta["tick"], next_tick) + trader.on_tick(next_tick, meta["ticker"], hint, book, meta["tick"]) + next_tick += step + if kind == "S": + book.apply_snapshot(data) + trader.on_book(t, book, meta["tick"]) + elif kind == "U": + book.apply_updates(data) + trader.on_book(t, book, meta["tick"]) + elif kind == "L": + trader.on_leader(t, float(data[0]), float(data[1])) + elif kind == "T": + for raw in data: + try: + trade = sh.Trade(t, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) + except (KeyError, TypeError, ValueError): + continue + tape.add(trade) + trader.on_trade(trade) + if next_tick is None: + next_tick = t + step + last_t = t + if trader.position is not None and last_t is not None: + trader.close_now(book, last_t, "конец записи") + if hasattr(trader.policy, "order"): + trader.policy.order = None + return trader + + +def compare(paths: list[Path]) -> None: + variants = [(f"простая, откат {n} шаг.", PaperSettings(mode="simple", adverse_ticks=n)) for n in (1, 3, 5, 10)] + variants += [("адаптивная", PaperSettings(mode="adaptive")), + ("адаптивная без самонастройки", PaperSettings(mode="adaptive", learning=False))] + variants += [(f"импульс + стакан, лимитка {p:g}%", PaperSettings(mode="pulse", pulse_offset_pct=p)) + for p in (0.05, 0.1, 0.15, 0.25)] + variants += [(f"суммы ±{d:g}%, перевес {th:g}, цель {tp:g}%", + PaperSettings(mode="sums", sums_depth_pct=d, sums_threshold=th, min_target_pct=tp)) + for d, th, tp in ((0.3, 0.2, 0.2), (0.3, 0.4, 0.2), (0.6, 0.2, 0.2), (0.6, 0.4, 0.3))] + minutes = 0.0 + for path in paths: + times = [row[0] for row in read_recording(path) if row[1] != "meta"] + if times: + minutes += (times[-1] - times[0]) / 60 + print(f"Записей: {len(paths)}, всего {minutes:.0f} мин потока\n") + print(f"{'вариант':34s} {'сделок':>6s} {'в плюс':>7s} {'итог $':>9s} {'на сделку':>10s} {'комиссии':>9s} причины") + for name, settings in variants: + trader = replay(paths, settings) + trades = trader.trades + n = len(trades) + net = sum(t.net_usd for t in trades) + wins = sum(t.net_usd > 0 for t in trades) + reasons: dict[str, int] = {} + for t in trades: + reasons[t.reason] = reasons.get(t.reason, 0) + 1 + print(f"{name:34s} {n:6d} {(wins / n * 100 if n else 0):6.0f}% {net:+9.4f} " + f"{(net / n if n else 0):+10.5f} {sum(t.fee_usd for t in trades):9.4f} {reasons}") + + +if __name__ == "__main__": + if len(sys.argv) >= 2 and sys.argv[1] == "compare": + files = [Path(p) for p in sys.argv[2:]] or sorted(RECORD_DIR.glob("*.jsonl.gz")) + if not files: + raise SystemExit(f"Нет записей в {RECORD_DIR}") + compare(files) + else: + print("usage: py -3 scalp_paper.py compare [files...]") diff --git a/LinuxServer/strategy.py b/LinuxServer/strategy.py new file mode 100644 index 0000000..c0cef37 --- /dev/null +++ b/LinuxServer/strategy.py @@ -0,0 +1,396 @@ +"""Shared strategy formulas used by simulation, live trading and the historical backtest. + +Keeping these rules in one place prevents the three modes from drifting apart. +""" + +from __future__ import annotations + +import math + +# Approximate maintenance-margin rate for Bybit USDT perpetuals at the lowest risk tier. +MAINTENANCE_MARGIN_RATE_PCT = 0.5 + + +def fee_cover_pct(fee_pct: float) -> float: + """Minimum gross price rise that offsets taker fees on entry and exit fills.""" + fee = max(0.0, fee_pct) / 100 + return ((1 + fee) / (1 - fee) - 1) * 100 if fee < 1 else math.inf + + +def effective_take_profit_pct(take_profit_pct: float, fee_pct: float) -> float: + """TP percentage raised to cover round-trip fees; 0 keeps TP disabled.""" + if take_profit_pct <= 0: + return 0.0 + return max(take_profit_pct, fee_cover_pct(fee_pct)) + + +def take_profit_price(avg_entry: float, take_profit_pct: float, fee_pct: float) -> float | None: + pct = effective_take_profit_pct(take_profit_pct, fee_pct) + return avg_entry * (1 + pct / 100) if pct > 0 else None + + +def stop_loss_price(avg_entry: float, stop_loss_pct: float) -> float | None: + return avg_entry * (1 - stop_loss_pct / 100) if stop_loss_pct > 0 else None + + +def entry_level(baseline_close: float, trigger_pct: float) -> float: + return baseline_close * (1 + trigger_pct / 100) + + +def add_level(last_add_price: float, add_step_pct: float) -> float | None: + return last_add_price * (1 - add_step_pct / 100) if add_step_pct > 0 else None + + +def can_add(add_count: int, max_adds: int, add_step_pct: float, averaging_frozen: bool = False) -> bool: + return add_step_pct > 0 and add_count < max_adds and not averaging_frozen + + +def liquidation_price(avg_entry: float, leverage: float, + mmr_pct: float = MAINTENANCE_MARGIN_RATE_PCT, side: str = "long") -> float | None: + """Approximate isolated-margin liquidation price; None when leverage <= 1 for a LONG. + + With leverage 1 a LONG cannot lose more than its margin before price reaches 0, + so liquidation is not modelled. For higher leverage the LONG price is + entry * (1 - 1/leverage + MMR) and the SHORT price is entry * (1 + 1/leverage - MMR). + A 1x SHORT is liquidated near a doubling of the price. + """ + if side == "short": + return avg_entry * (1 + 1 / max(leverage, 1.0) - mmr_pct / 100) + if leverage <= 1: + return None + return max(0.0, avg_entry * (1 - 1 / leverage + mmr_pct / 100)) + + +# --------------------------------------------------------------------------- +# Strategy modes. +# +# "classic" — the original rule: entry on a rise above the previous 1-minute close, +# averaging down, TP/stop from the average price (settings per currency). +# "breakout" — mode A: LONG on a close above the N-hour high with a volume spike, +# ATR stop, partial take-profit, breakeven and ATR trailing stop. +# "fade" — mode B: SHORT after a pump stalls (24h growth, high funding, close back +# under the turnover-weighted average price and below the recent high). +# Modes A and B share one exit engine and one parameter set for all currencies. +# --------------------------------------------------------------------------- + +STRATEGY_CLASSIC = "classic" +STRATEGY_BREAKOUT = "breakout" +STRATEGY_FADE = "fade" +STRATEGY_MODES = (STRATEGY_CLASSIC, STRATEGY_BREAKOUT, STRATEGY_FADE) +STRATEGY_TITLES = { + STRATEGY_CLASSIC: "Классика: пробой 1-мин свечи + усреднение", + STRATEGY_BREAKOUT: "A: пробой N-часового максимума (ATR)", + STRATEGY_FADE: "B: шорт затухающего пампа", +} +STRATEGY_DESCRIPTIONS = { + STRATEGY_CLASSIC: ( + "LONG при росте от закрытия прошлой минутной свечи, доливки при снижении, TP и стоп от средней " + "цены. Настройки задаются для каждой валюты отдельно; здесь — шаблон, который применяется ко всем." + ), + STRATEGY_BREAKOUT: ( + "LONG, когда закрытие свечи таймфрейма выше максимума за N часов и оборот свечи в K раз выше " + "среднего. Стоп = вход − ATR × множитель, без усреднения. Часть позиции фиксируется на заданном R " + "(R — расстояние до стопа), стоп переносится в безубыток, остаток ведётся трейлинг-стопом по ATR. " + "Фильтры: BTC выше EMA на часовом графике и funding не выше порога." + ), + STRATEGY_FADE: ( + "SHORT монеты после пампа: рост за 24 ч выше порога, funding не ниже порога, максимум за " + "последние часы уже позади, закрытие ниже него на заданный процент и ниже средней цены по " + "обороту (VWAP). Стоп — над максимумом + ATR × буфер; сделка пропускается, если стоп дальше " + "заданного процента. Выход: частичная фиксация на R, безубыток, трейлинг по ATR. " + "Funding при положительной ставке получают шорты." + ), +} + +# (key, label, minimum, maximum, integer?) — minimum 0 usually means "0 = выключено". +_COMMON_RISK_FIELDS = ( + ("stake_pct", "Ставка, % депозита", 0.01, 100.0, False), + ("leverage", "Плечо", 1.0, 100.0, False), + ("timeframe_min", "Таймфрейм сигнала, мин (5/15/30/60)", 5.0, 60.0, True), + ("atr_period", "Период ATR, свечей", 2.0, 200.0, True), +) +_COMMON_EXIT_FIELDS = ( + ("partial_r", "Частичная фиксация на R (0 = выкл.)", 0.0, 50.0, False), + ("partial_pct", "Доля частичной фиксации, %", 0.0, 100.0, False), + ("breakeven", "Безубыток после частичной (1/0)", 0.0, 1.0, True), + ("trail_atr", "Трейлинг-стоп, ATR (0 = выкл.)", 0.0, 50.0, False), + ("take_profit_r", "Финальный TP на R (0 = выкл.)", 0.0, 100.0, False), + ("max_hold_hours", "Макс. удержание, ч (0 = выкл.)", 0.0, 10000.0, False), +) +MODE_FIELDS: dict[str, tuple[tuple[str, str, float, float, bool], ...]] = { + STRATEGY_BREAKOUT: _COMMON_RISK_FIELDS + ( + ("breakout_hours", "Пробой максимума за, ч", 0.25, 168.0, False), + ("volume_mult", "Оборот свечи × среднего (0 = выкл.)", 0.0, 100.0, False), + ("stop_atr", "Стоп, ATR от входа", 0.1, 50.0, False), + ("btc_filter", "Фильтр BTC выше EMA 1ч (1/0)", 0.0, 1.0, True), + ("btc_ema", "Период EMA BTC, часов", 2.0, 900.0, True), + ("max_funding_pct", "Не входить при funding выше, % (0 = выкл.)", 0.0, 10.0, False), + ) + _COMMON_EXIT_FIELDS, + STRATEGY_FADE: _COMMON_RISK_FIELDS + ( + ("min_growth_24h", "Рост за 24 ч, не меньше %", 0.0, 10000.0, False), + ("min_funding_pct", "Funding не ниже, % (0 = выкл.)", 0.0, 10.0, False), + ("high_lookback_hours", "Максимум пампа за последние, ч", 0.5, 72.0, False), + ("pullback_pct", "Закрытие ниже максимума на, %", 0.0, 90.0, False), + ("vwap_hours", "VWAP по обороту за, ч", 0.5, 72.0, False), + ("stop_buffer_atr", "Стоп над максимумом, ATR", 0.0, 20.0, False), + ("max_stop_pct", "Макс. расстояние до стопа, %", 0.1, 100.0, False), + ) + _COMMON_EXIT_FIELDS, +} +MODE_DEFAULTS: dict[str, dict[str, float]] = { + STRATEGY_BREAKOUT: { + "stake_pct": 5.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0, + "breakout_hours": 4.0, "volume_mult": 2.0, "stop_atr": 2.0, + "btc_filter": 1.0, "btc_ema": 200.0, "max_funding_pct": 0.05, + "partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0, + "take_profit_r": 0.0, "max_hold_hours": 48.0, + }, + STRATEGY_FADE: { + "stake_pct": 3.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0, + "min_growth_24h": 30.0, "min_funding_pct": 0.03, "high_lookback_hours": 6.0, + "pullback_pct": 3.0, "vwap_hours": 6.0, "stop_buffer_atr": 0.5, "max_stop_pct": 15.0, + "partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0, + "take_profit_r": 0.0, "max_hold_hours": 24.0, + }, +} +ALLOWED_TIMEFRAMES = (5, 15, 30, 60) + + +def parse_mode_params(mode: str, raw: dict[str, object]) -> dict[str, float]: + """Validate the text values of a mode's settings; raises ValueError with a readable message.""" + params: dict[str, float] = {} + for key, label, minimum, maximum, integer in MODE_FIELDS[mode]: + value = raw.get(key, MODE_DEFAULTS[mode][key]) + try: + number = float(str(value).strip().replace(",", ".")) + except ValueError as exc: + raise ValueError(f"Проверьте значение «{label}».") from exc + if not math.isfinite(number) or not minimum <= number <= maximum: + raise ValueError(f"«{label}» должно быть от {minimum:g} до {maximum:g}.") + if integer and not number.is_integer(): + raise ValueError(f"«{label}» должно быть целым числом.") + params[key] = number + if int(params["timeframe_min"]) not in ALLOWED_TIMEFRAMES: + raise ValueError("Таймфрейм сигнала: 5, 15, 30 или 60 минут.") + if params["partial_pct"] > 0 and params["partial_r"] <= 0: + raise ValueError("Для частичной фиксации укажите R больше 0 или долю 0%.") + if (params["trail_atr"] <= 0 and params["take_profit_r"] <= 0 + and not (params["partial_r"] > 0 and params["partial_pct"] >= 100) + and params["max_hold_hours"] <= 0): + raise ValueError("Задайте выход по прибыли: трейлинг, финальный TP, 100% частичную фиксацию " + "или максимальное удержание.") + return params + + +def side_sign(side: str) -> float: + return -1.0 if side == "short" else 1.0 + + +def unrealized_pnl(side: str, entry: float, mark: float, qty: float) -> float: + return side_sign(side) * (mark - entry) * qty + + +def bars_for_hours(hours: float, timeframe_min: float) -> int: + return max(1, int(round(hours * 60 / timeframe_min))) + + +def aggregate_candles(rows: list[list[float]], timeframe_min: int) -> list[list[float]]: + """Group minute rows [start_ms, o, h, l, c, (turnover)] into timeframe candles.""" + step = int(timeframe_min) * 60_000 + output: list[list[float]] = [] + for row in rows: + bucket = (int(row[0]) // step) * step + turnover = float(row[5]) if len(row) > 5 and row[5] is not None else 0.0 + if output and output[-1][0] == bucket: + candle = output[-1] + candle[2] = max(candle[2], float(row[2])) + candle[3] = min(candle[3], float(row[3])) + candle[4] = float(row[4]) + candle[5] += turnover + else: + output.append([bucket, float(row[1]), float(row[2]), float(row[3]), float(row[4]), turnover]) + return output + + +def average_true_range(candles: list[list[float]], period: int) -> float | None: + """Simple average of the true range over the last ``period`` candles.""" + period = int(period) + if period < 1 or len(candles) < period + 1: + return None + ranges = [] + for previous, current in zip(candles[-period - 1:-1], candles[-period:]): + high, low, prev_close = float(current[2]), float(current[3]), float(previous[4]) + ranges.append(max(high - low, abs(high - prev_close), abs(low - prev_close))) + value = sum(ranges) / len(ranges) + return value if value > 0 else None + + +def turnover_vwap(candles: list[list[float]]) -> float | None: + """Average typical price weighted by turnover (falls back to an equal-weight mean).""" + if not candles: + return None + typical = [(float(c[2]) + float(c[3]) + float(c[4])) / 3 for c in candles] + weights = [float(c[5]) if len(c) > 5 and c[5] else 0.0 for c in candles] + total = sum(weights) + if total > 0: + return sum(price * weight for price, weight in zip(typical, weights)) / total + return sum(typical) / len(typical) + + +def ema(values: list[float], period: int) -> float | None: + period = int(period) + if period < 1 or len(values) < period: + return None + alpha = 2 / (period + 1) + value = sum(values[:period]) / period + for item in values[period:]: + value = alpha * item + (1 - alpha) * value + return value + + +def btc_regime_ok(hourly_closes: list[float], ema_period: int) -> bool | None: + """True when the last closed BTC hour is above its EMA; None without enough data.""" + average = ema(hourly_closes, ema_period) + if average is None: + return None + return hourly_closes[-1] > average + + +def required_bars(mode: str, params: dict[str, float]) -> int: + """Closed timeframe candles the signal needs (oldest to the just-closed one).""" + tf = params["timeframe_min"] + atr_bars = int(params["atr_period"]) + 1 + if mode == STRATEGY_BREAKOUT: + return max(bars_for_hours(params["breakout_hours"], tf) + 1, atr_bars) + return max(bars_for_hours(24, tf) + 1, bars_for_hours(params["high_lookback_hours"], tf), + bars_for_hours(params["vwap_hours"], tf), atr_bars) + + +def evaluate_breakout(candles: list[list[float]], params: dict[str, float], + funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None: + """Mode A signal on closed candles [start, o, h, l, c, turnover]; the last one has just closed.""" + if len(candles) < required_bars(STRATEGY_BREAKOUT, params): + return None + lookback = bars_for_hours(params["breakout_hours"], params["timeframe_min"]) + last = candles[-1] + prior = candles[-lookback - 1:-1] + level = max(float(c[2]) for c in prior) + close = float(last[4]) + if close <= level: + return None + if params["volume_mult"] > 0: + average = sum(float(c[5]) if len(c) > 5 else 0.0 for c in prior) / len(prior) + turnover = float(last[5]) if len(last) > 5 else 0.0 + if average > 0 and turnover < params["volume_mult"] * average: + return None + if params["btc_filter"] >= 1 and btc_ok is not True: + return None + if (params["max_funding_pct"] > 0 and funding_rate_pct is not None + and funding_rate_pct > params["max_funding_pct"]): + return None + atr = average_true_range(candles, int(params["atr_period"])) + if atr is None: + return None + return {"side": "long", "atr": atr, "level": level, "close": close, "candle_start": int(last[0])} + + +def evaluate_fade(candles: list[list[float]], params: dict[str, float], + funding_rate_pct: float | None = None) -> dict | None: + """Mode B signal on closed candles; returns the planned SHORT stop above the pump high.""" + if len(candles) < required_bars(STRATEGY_FADE, params): + return None + tf = params["timeframe_min"] + last = candles[-1] + close = float(last[4]) + day_ago = float(candles[-bars_for_hours(24, tf) - 1][4]) + if day_ago <= 0: + return None + growth = (close / day_ago - 1) * 100 + if growth < params["min_growth_24h"]: + return None + if params["min_funding_pct"] > 0 and (funding_rate_pct is None + or funding_rate_pct < params["min_funding_pct"]): + return None + window = candles[-bars_for_hours(params["high_lookback_hours"], tf):] + high_index = max(range(len(window)), key=lambda index: float(window[index][2])) + high = float(window[high_index][2]) + if high_index == len(window) - 1: + return None # the pump is still printing new highs + if close > high * (1 - params["pullback_pct"] / 100): + return None + vwap = turnover_vwap(candles[-bars_for_hours(params["vwap_hours"], tf):]) + if vwap is None or close >= vwap: + return None + atr = average_true_range(candles, int(params["atr_period"])) + if atr is None: + return None + return {"side": "short", "atr": atr, "high": high, "stop": high + params["stop_buffer_atr"] * atr, + "vwap": vwap, "growth": growth, "close": close, "candle_start": int(last[0])} + + +def evaluate_signal(mode: str, candles: list[list[float]], params: dict[str, float], + funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None: + if mode == STRATEGY_BREAKOUT: + return evaluate_breakout(candles, params, funding_rate_pct, btc_ok) + if mode == STRATEGY_FADE: + return evaluate_fade(candles, params, funding_rate_pct) + return None + + +def entry_plan(signal: dict, entry_price: float, params: dict[str, float]) -> dict | None: + """Stop and targets for an entry at ``entry_price``; None when the signal is no longer valid.""" + side = signal["side"] + if entry_price <= 0: + return None + if side == "long": + if entry_price <= signal["level"]: + return None # price fell back under the breakout level before the fill + stop = entry_price - params["stop_atr"] * signal["atr"] + if stop <= 0: + return None + else: + stop = signal["stop"] + if entry_price >= stop or (stop / entry_price - 1) * 100 > params["max_stop_pct"]: + return None + risk = abs(entry_price - stop) + sign = side_sign(side) + partial = (entry_price + sign * params["partial_r"] * risk + if params["partial_r"] > 0 and params["partial_pct"] > 0 else None) + final = entry_price + sign * params["take_profit_r"] * risk if params["take_profit_r"] > 0 else None + if final is not None and final <= 0: + final = None + if partial is not None and partial <= 0: + partial = None + return {"side": side, "stop": stop, "risk": risk, "atr": signal["atr"], + "partial_target": partial, "final_target": final} + + +def breakeven_price(side: str, entry: float, fee_pct: float) -> float: + cover = fee_cover_pct(fee_pct) / 100 + return entry * (1 + cover) if side == "long" else entry * (1 - cover) + + +def tighten_stop(side: str, stop: float, candidate: float) -> float: + """Stops only move in the trade's favour.""" + return max(stop, candidate) if side == "long" else min(stop, candidate) + + +def trailing_stop(side: str, stop: float, extreme: float, atr: float, trail_atr: float) -> float: + if trail_atr <= 0 or atr <= 0: + return stop + candidate = extreme - trail_atr * atr if side == "long" else extreme + trail_atr * atr + return tighten_stop(side, stop, candidate) + + +def trailing_active(partial_done: bool, params: dict[str, float]) -> bool: + """Trail from the start without a partial exit, otherwise only after it.""" + return params["trail_atr"] > 0 and (partial_done or params["partial_r"] <= 0 or params["partial_pct"] <= 0) + + +def stop_hit(side: str, price: float, stop: float) -> bool: + return price <= stop if side == "long" else price >= stop + + +def target_hit(side: str, price: float, target: float | None) -> bool: + if target is None or target <= 0: + return False + return price >= target if side == "long" else price <= target diff --git a/LinuxServer/user_auth.py b/LinuxServer/user_auth.py new file mode 100644 index 0000000..8867602 --- /dev/null +++ b/LinuxServer/user_auth.py @@ -0,0 +1,136 @@ +"""Local multi-user authentication and isolated per-user data folders.""" + +from __future__ import annotations + +import hashlib +import hmac +import os +import re +import secrets +import sqlite3 +import time +import uuid +from pathlib import Path + + +class AuthError(ValueError): + pass + + +class UserStore: + ITERATIONS = 420_000 + SESSION_SECONDS = 12 * 60 * 60 + USER_RE = re.compile(r"^[a-zA-Z0-9_.-]{3,32}$") + + def __init__(self, root: Path): + self.root = Path(root) + self.db = self.root / "accounts.sqlite3" + self.users_dir = self.root / "users" + self.root.mkdir(parents=True, exist_ok=True) + self.users_dir.mkdir(parents=True, exist_ok=True) + with self.connect() as con: + con.executescript(""" + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + salt BLOB NOT NULL, + password_hash BLOB NOT NULL, + created REAL NOT NULL + ); + CREATE TABLE IF NOT EXISTS sessions ( + token_hash BLOB PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires REAL NOT NULL, + created REAL NOT NULL + ); + CREATE TABLE IF NOT EXISTS metadata ( + name TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires); + """) + + def connect(self): + con = sqlite3.connect(self.db, timeout=15) + con.execute("PRAGMA foreign_keys=ON") + con.execute("PRAGMA journal_mode=WAL") + return con + + @classmethod + def _password_hash(cls, password: str, salt: bytes) -> bytes: + return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, cls.ITERATIONS) + + def register(self, username: str, password: str) -> str: + username, password = (username or "").strip(), password or "" + if not self.USER_RE.fullmatch(username): + raise AuthError("Логин: 3–32 символа, латинские буквы, цифры, точка, дефис или подчёркивание") + if len(password) < 12 or len(password) > 256: + raise AuthError("Пароль должен содержать от 12 до 256 символов") + user_id, salt = uuid.uuid4().hex, secrets.token_bytes(16) + try: + with self.connect() as con: + con.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?)", + (user_id, username, salt, self._password_hash(password, salt), time.time())) + except sqlite3.IntegrityError: + raise AuthError("Такой логин уже зарегистрирован") from None + (self.users_dir / user_id).mkdir(parents=True, exist_ok=True) + return user_id + + def authenticate(self, username: str, password: str) -> str | None: + with self.connect() as con: + row = con.execute("SELECT id, salt, password_hash FROM users WHERE username=? COLLATE NOCASE", + ((username or "").strip(),)).fetchone() + if row is None: + # Keep the missing-user path close to the cost of a real password check. + self._password_hash(password or "", b"\0" * 16) + return None + return row[0] if hmac.compare_digest(self._password_hash(password or "", row[1]), row[2]) else None + + @staticmethod + def _token_hash(token: str) -> bytes: + return hashlib.sha256(token.encode("ascii")).digest() + + def create_session(self, user_id: str) -> str: + token = secrets.token_urlsafe(36) + now = time.time() + with self.connect() as con: + con.execute("DELETE FROM sessions WHERE expires < ?", (now,)) + con.execute("INSERT INTO sessions VALUES (?, ?, ?, ?)", + (self._token_hash(token), user_id, now + self.SESSION_SECONDS, now)) + return token + + def user_for_session(self, token: str | None) -> str | None: + if not token or len(token) > 128: + return None + with self.connect() as con: + row = con.execute("SELECT user_id FROM sessions WHERE token_hash=? AND expires>=?", + (self._token_hash(token), time.time())).fetchone() + return row[0] if row else None + + def delete_session(self, token: str | None) -> None: + if token: + with self.connect() as con: + con.execute("DELETE FROM sessions WHERE token_hash=?", (self._token_hash(token),)) + + def user_ids(self) -> list[str]: + with self.connect() as con: + return [row[0] for row in con.execute("SELECT id FROM users ORDER BY created")] + + def username(self, user_id: str) -> str: + with self.connect() as con: + row = con.execute("SELECT username FROM users WHERE id=?", (user_id,)).fetchone() + return row[0] if row else "" + + def mark_legacy_imported(self) -> bool: + """Atomically elect only the first registered account to receive the old single-user data.""" + with self.connect() as con: + cur = con.execute("INSERT OR IGNORE INTO metadata VALUES ('legacy_imported', '1')") + return cur.rowcount == 1 + + def data_dir(self, user_id: str) -> Path: + if not re.fullmatch(r"[0-9a-f]{32}", user_id): + raise AuthError("Некорректный идентификатор пользователя") + path = self.users_dir / user_id / "data" + path.mkdir(parents=True, exist_ok=True) + return path + diff --git a/LinuxServer/virtual_account.py b/LinuxServer/virtual_account.py new file mode 100644 index 0000000..6e4784b --- /dev/null +++ b/LinuxServer/virtual_account.py @@ -0,0 +1,245 @@ +"""One durable paper account shared by the web simulator and paper arbitrage. + +Each engine commits its complete recovery snapshot together with its cumulative +cash movement and reserved capital. A failed write changes neither the account +nor the authoritative engine snapshot. No exchange client is used here. +""" +from __future__ import annotations + +import copy +import math +import threading +import time +from pathlib import Path +import json + +from persistence import atomic_write_json + +_PATH_LOCKS: dict[str, threading.RLock] = {} +_PATH_LOCKS_LOCK = threading.Lock() + + +class AccountError(ValueError): + pass + + +def _number(value, name: str) -> float: + if isinstance(value, bool): + raise AccountError(f"{name}: введите число") + try: + result = float(value) + except (TypeError, ValueError, OverflowError): + raise AccountError(f"{name}: введите число") from None + if not math.isfinite(result) or abs(result) > 1e12: + raise AccountError(f"{name}: недопустимая сумма") + return result + + +class VirtualAccount: + MAX_MARK_AGE = 30.0 + + def __init__(self, path: Path, initial_balance: float = 300.0): + self.path = Path(path) + with _PATH_LOCKS_LOCK: + self.lock = _PATH_LOCKS.setdefault(str(self.path.resolve()).casefold(), threading.RLock()) + self.error = "" + self.marks: dict[str, tuple[float, float]] = {} + initial = _number(initial_balance, "Начальный баланс") + if initial < 0: + raise AccountError("Начальный баланс не может быть отрицательным") + self.data = {"schema": 1, "version": 0, "balance": initial, + "net_deposits": initial, "owners": {}, "adjustments": {}, "journal": [], + "updated_at": time.time()} + try: + loaded = json.loads(self.path.read_text(encoding="utf-8")) + self._validate(loaded) + self.data = loaded + except FileNotFoundError: + try: + atomic_write_json(self.path, self.data) + except (OSError, ValueError) as exc: + self.error = f"Не удалось создать виртуальный счёт: {exc}" + except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: + self.error = f"Виртуальный счёт не прочитан; операции заблокированы: {exc}" + + @staticmethod + def _validate(data): + if not isinstance(data, dict) or data.get("schema") != 1: + raise AccountError("неподдерживаемый формат счёта") + for key in ("balance", "net_deposits", "version", "updated_at"): + if isinstance(data[key], bool) or not isinstance(data[key], (int, float)): + raise AccountError(f"неверный тип поля {key}") + _number(data[key], key) + if not isinstance(data.get("owners"), dict) or not isinstance(data.get("adjustments"), dict): + raise AccountError("повреждён список операций") + if not isinstance(data.get("journal"), list): + raise AccountError("повреждён журнал") + for owner in data["owners"].values(): + if not isinstance(owner, dict) or not isinstance(owner.get("state"), dict): + raise AccountError("повреждено состояние симуляции") + for key in ("cash_total", "reserved", "unrealized"): + value = owner.get(key, 0.0) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise AccountError(f"неверный тип поля {key}") + _number(owner["cash_total"], "Движение средств") + if _number(owner["reserved"], "Резерв") < 0: + raise AccountError("отрицательный резерв") + _number(owner.get("unrealized", 0), "Открытый результат") + for key, value in data["adjustments"].items(): + if not isinstance(key, str) or isinstance(value, bool) or not isinstance(value, (int, float)): + raise AccountError("повреждены идентификаторы операций") + _number(value, "Пополнение / списание") + + def _refresh(self): + """Read the latest in-process writer under the lock shared by this path. + + The application-wide runtime lock prevents different server processes + from owning this account directory at the same time. + """ + self._ready() + try: + data = json.loads(self.path.read_text(encoding="utf-8")) + self._validate(data) + except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: + self.error = f"Виртуальный счёт не прочитан; операции заблокированы: {exc}" + raise AccountError(self.error) from None + if data["version"] != self.data["version"]: + for owner in list(self.marks): + if data["owners"].get(owner) != self.data["owners"].get(owner): + self.marks.pop(owner, None) + self.data = data + + def _ready(self): + if self.error: + raise AccountError(self.error) + + def restore(self, owner: str) -> dict | None: + with self.lock: + self._ready() + record = self.data["owners"].get(owner) + return copy.deepcopy(record["state"]) if record else None + + def _save(self, data): + data["version"] = self.data["version"] + 1 + data["updated_at"] = time.time() + try: + # Individual movements may be valid while their sum exceeds the readable storage range. + # Reject the entire transaction before replacing a valid snapshot with an unreadable one. + self._validate(data) + atomic_write_json(self.path, data) + except (OSError, ValueError, TypeError) as exc: + raise AccountError(f"Не удалось сохранить виртуальный счёт: {exc}") from None + self.data = data + + def _metrics(self, data=None, marks=None): + data = self.data if data is None else data + marks = self.marks if marks is None else marks + now = time.time() + reserved = unrealized = 0.0 + stale = [] + for name, owner in data["owners"].items(): + reserved += owner["reserved"] + value, at = marks.get(name, (owner.get("unrealized", 0.0), 0.0)) + unrealized += value + if owner["reserved"] > 1e-8 and now - at > self.MAX_MARK_AGE: + stale.append(name) + balance = data["balance"] + equity = balance + unrealized + return {"balance": balance, "equity": equity, "reserved": reserved, + "unrealized": unrealized, "free": max(0.0, min(balance, equity) - reserved), + "deficit": max(0.0, reserved - min(balance, equity)), "stale": stale} + + def view(self) -> dict: + with self.lock: + return {**self._metrics(), "net_deposits": self.data["net_deposits"], + "realized": self.data["balance"] - self.data["net_deposits"], + "version": self.data["version"], + "updated_at": max(self.data["updated_at"], + max((stamp for _, stamp in self.marks.values()), default=0.0)), + "error": self.error, + "journal": copy.deepcopy(self.data["journal"][-100:][::-1])} + + def mark(self, owner: str, unrealized: float) -> None: + value = _number(unrealized, "Открытый результат") + with self.lock: + if owner in self.data["owners"]: + self.marks[owner] = (value, time.time()) + + def commit(self, owner: str, state: dict, *, cash_total: float, reserved: float, + unrealized: float = 0.0, allow_existing: bool = False, event: str = "") -> dict: + """Atomically replace an owner's recovery state and apply only its new cash delta. + + allow_existing is only accepted for first-time migration. Existing exposure + is preserved even when the chosen initial deposit is smaller than its margin. + Decreasing exposure and settlement remain possible when the account is in deficit. + """ + cash = _number(cash_total, "Движение средств") + reserve = _number(reserved, "Резерв") + unrealized = _number(unrealized, "Открытый результат") + if reserve < 0 or not isinstance(state, dict) or not owner: + raise AccountError("Некорректное состояние симуляции") + with self.lock: + self._refresh() + old = self.data["owners"].get(owner, {"cash_total": 0.0, "reserved": 0.0}) + migration = allow_existing and owner not in self.data["owners"] + delta = cash - old["cash_total"] + before = self._metrics() + data = copy.deepcopy(self.data) + data["balance"] += delta + data["owners"][owner] = {"cash_total": cash, "reserved": reserve, + "unrealized": unrealized, "state": copy.deepcopy(state)} + marks = dict(self.marks) + # A settings/checkpoint write is not a new market quote. In particular, + # loading a saved position must not make its old valuation fresh. + if reserve <= 1e-8: + marks[owner] = (0.0, time.time()) + elif reserve > old["reserved"] + 1e-8: + marks[owner] = (unrealized, 0.0 if migration else time.time()) + elif owner in marks: + marks[owner] = (unrealized, marks[owner][1]) + after = self._metrics(data, marks) + if reserve > old["reserved"] + 1e-8 and not migration: + if before["stale"]: + raise AccountError("Нет свежей оценки открытых позиций; новый вход приостановлен") + if after["deficit"] > 1e-8: + needed = reserve - old["reserved"] + max(0.0, -delta) + raise AccountError(f"Недостаточно виртуальных средств: доступно {before['free']:.2f} USDT, " + f"требуется {needed:.2f} USDT") + if event and (abs(delta) > 1e-10 or reserve != old["reserved"]): + data["journal"].append({"time": time.time(), "type": "trade", "amount": delta, + "balance": data["balance"], "reason": event, "owner": owner, + "request_id": ""}) + data["journal"] = data["journal"][-1000:] + self._save(data) + self.marks = marks + return self.view() + + def adjust(self, amount, request_id: str) -> dict: + delta = round(_number(amount, "Сумма"), 8) + if delta == 0: + raise AccountError("Сумма должна быть больше нуля") + if not isinstance(request_id, str) or not 8 <= len(request_id) <= 120: + raise AccountError("Неверный идентификатор операции") + with self.lock: + self._refresh() + previous = self.data["adjustments"].get(request_id) + if previous is not None: + if previous != delta: + raise AccountError("Этот идентификатор уже использован для другой суммы") + return self.view() + metrics = self._metrics() + if delta < 0: + if metrics["stale"]: + raise AccountError("Списание приостановлено: нет свежей оценки открытых позиций") + if -delta > metrics["free"] + 1e-8: + raise AccountError(f"Можно списать не больше свободного остатка: {metrics['free']:.2f} USDT") + data = copy.deepcopy(self.data) + data["balance"] = round(data["balance"] + delta, 8) + data["net_deposits"] = round(data["net_deposits"] + delta, 8) + data["adjustments"][request_id] = delta + data["journal"].append({"time": time.time(), "type": "deposit" if delta > 0 else "withdrawal", + "amount": delta, "balance": data["balance"], + "reason": "Пополнение" if delta > 0 else "Списание", "request_id": request_id}) + data["journal"] = data["journal"][-1000:] + self._save(data) + return self.view() diff --git a/LinuxServer/web/app.css b/LinuxServer/web/app.css new file mode 100644 index 0000000..96aebac --- /dev/null +++ b/LinuxServer/web/app.css @@ -0,0 +1,179 @@ +: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; } +[hidden] { display: none !important; } +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; } } +.system-status { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 18px; padding: 10px 16px; border-bottom: 1px solid var(--line); background: var(--panel); } +.mode-status { color: #91baff; font-size: 12px; letter-spacing: .035em; } +.mode-status.mode-live { color: var(--red); } +.connection-status { font-size: 12px; } +.connection-status.connected { color: var(--muted); } +.connection-status.disconnected { color: var(--yellow); } +.command-notice { padding: 9px 16px; border-bottom: 1px solid var(--line); background: var(--panel2); overflow-wrap: anywhere; } +.paper-account { margin: 16px 18px 0; padding: 16px 18px; border: 1px solid #35517b; border-radius: 12px; background: linear-gradient(120deg, #172235, #151c28); } +.account-heading { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-bottom: 14px; } +.account-heading h2 { margin: 0; font-size: 17px; color: var(--text); letter-spacing: 0; text-transform: none; } +.paper-badge { font-size: 10px; font-weight: 700; color: #a9c8ff; border: 1px solid #35517b; padding: 3px 7px; border-radius: 5px; } +.account-metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; } +.account-metrics > div { display: flex; flex-direction: column; gap: 4px; } +.account-metrics span { color: #b1bdd0; font-size: 12px; } +.account-metrics strong { font-size: clamp(19px, 2vw, 26px); font-variant-numeric: tabular-nums; } +.account-metrics small { color: var(--muted); font-size: 11px; } +.paper-account .field input { width: 180px; } +.account-journal { margin-top: 14px; border-top: 1px solid var(--line); padding-top: 10px; } +.account-journal summary { cursor: pointer; color: #b1c9ed; } +.account-journal .tablewrap { margin-top: 8px; max-height: 220px; } +.account-journal td:nth-child(2) { white-space: normal; min-width: 160px; } +.help-btn { margin-left: auto; align-self: center; margin-bottom: 6px; font-weight: 600; } +.calcbtn { margin-left: 0; } +.help-dialog { width: min(900px, calc(100vw - 28px)); max-height: min(90vh, 980px); padding: 24px; background: var(--panel); color: var(--text); border: 1px solid #3c5273; border-radius: 14px; box-shadow: 0 20px 100px #000a; overflow: auto; } +.help-dialog::backdrop { background: #030812bd; backdrop-filter: blur(3px); } +.help-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; } +.help-heading h2 { margin: 0; font-size: 24px; } +.help-heading p { color: var(--muted); margin: 5px 0 20px; } +.help-close { font-size: 24px; padding: 0; width: 36px; height: 36px; flex: 0 0 auto; } +.help-search-label { display: block; font-size: 12px; color: var(--muted); margin-bottom: 6px; } +.help-search { width: 100%; padding: 11px 12px; color: var(--text); background: var(--panel2); border: 1px solid #3c5273; border-radius: 8px; font: inherit; } +.help-content h3 { margin: 22px 0 8px; color: #9fc4ff; font-size: 15px; } +.help-entry { padding: 12px 0; border-bottom: 1px solid var(--line); } +.help-entry h4 { margin: 0 0 5px; font-size: 13px; } +.help-entry p { margin: 0; color: #b8c2d2; line-height: 1.55; overflow-wrap: anywhere; } +.help-entry code { color: var(--muted); font-size: 11px; font-weight: 400; margin-left: 6px; overflow-wrap: anywhere; } +button:focus-visible, input:focus-visible, select:focus-visible, summary:focus-visible { outline: 2px solid #8db8ff; outline-offset: 3px; } +@media (max-width: 900px) { .tabs { flex-wrap: wrap; padding-bottom: 6px; } .tab { padding: 8px 10px; } .help-btn { margin-left: 0; } .title { flex-wrap: wrap; } } +@media (max-width: 620px) { + .account-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 10px; } + .paper-account { margin: 12px 10px 0; padding: 14px; } + .help-dialog { padding: 18px; } + .check { white-space: normal; } + .field label { white-space: normal; max-width: 260px; } + .keygrid { grid-template-columns: 1fr; } +} +@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; } } diff --git a/LinuxServer/web/app.js b/LinuxServer/web/app.js new file mode 100644 index 0000000..b4bcb6c --- /dev/null +++ b/LinuxServer/web/app.js @@ -0,0 +1,1499 @@ +const MAIN_FIELDS = [ + ["mode", "Режим", "select"], ["stake", "Ставка, $"], ["leverage", "Плечо"], ["min_target_pct", "Тейк-профит, %"], + ["stop_loss_pct", "Стоп-лосс, %"], ["max_hold_seconds", "Удержание, с"], ["max_positions", "Позиций одновременно"], + ["entry_gap_seconds", "Между входами, с"], ["min_confidence", "Мин. уверенность"], + ["auto_stop_pct", "Автостоп: CEX опережает на, %"], + ["auto_tp", "Авто тейк-профит по прогнозу", "check"], ["require_leader", "Входить, только если ведущая правда ведёт", "check"], +]; +const MORE_FIELDS = [ + ["simulation_entry_delay_ms", "Задержка открытия в симуляции, мс"], + ["simulation_exit_delay_ms", "Задержка закрытия в симуляции, мс"], + ["cooldown_ms", "Пауза после сделки, мс"], ["lead_threshold_pct", "Отставание для входа, %"], + ["lead_window_ms", "Окно сравнения, мс"], ["vector_window_seconds", "Вектор за, с"], ["vector_min_move_pct", "Мин. движение, %"], + ["auto_tp_share_pct", "Доля догоняния, %"], ["auto_tp_horizon_seconds", "Горизонт прогноза, с"], + ["cut_loss_ticks", "Минус для закрытия, шагов"], ["max_data_age_ms", "Данные не старше, мс"], + ["leader_min_edge", "Перевес ведущей (корр.)"], ["basis_window_seconds", "Разрыв: обычный за, с"], + ["basis_entry_z", "Разрыв: вход, σ"], ["basis_exit_z", "Разрыв: выход, σ"], ["basis_min_gap_pct", "Разрыв: мин., %"], + ["auto_tp_learn", "Учить долю на истории", "check"], ["one_per_tick", "Одна позиция на шаг цены", "check"], + ["cut_loss", "Сразу закрывать в минусе", "check"], +]; +let state = null, selected = localStorage.getItem("sim.coin") || null, detail = null; +let detailEpoch = 0, detailRequest = 0, detailApplied = 0; +let bxEpoch = 0, bxRequest = 0, bxApplied = 0, bxDataVenue = null; +let range = +(localStorage.getItem("sim.range") || 300), seenOpen = new Set(), seenClosed = 0, settingsDirty = false; +let stateRequest = 0, stateApplied = 0, realRequest = 0, realApplied = 0; +const readHealth = new Map(), pendingReads = new Map(), pendingCommands = new Set(), pendingPolls = new Map(), readGenerations = new Map(); +const FRESH_MS = 10000; +let accountData = null, accountBusy = false, pendingAccountAdjustment = null; +const accountIsStale = account => Array.isArray(account?.stale) ? account.stale.length > 0 : !!account?.stale; +const escapeHtml = value => String(value ?? "").replace(/[&<>"']/g, c => ({"&":"&", "<":"<", ">":">", '"':""", "'":"'"}[c])); + +// all times on the page are Moscow time, whatever the computer's time zone +const MSK = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", hour: "2-digit", minute: "2-digit", second: "2-digit"}); +const MSK_DAY = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", day: "2-digit", month: "2-digit"}); +const msk = seconds => MSK.format(new Date(seconds * 1000)); +const mskFull = seconds => { + const d = new Date(seconds * 1000), today = MSK_DAY.format(new Date()); + return (MSK_DAY.format(d) === today ? "" : MSK_DAY.format(d) + " ") + MSK.format(d); +}; +const fmt = (v, d = 4) => v == null || isNaN(v) ? "—" : (+v).toFixed(d); +const price = v => v == null ? "—" : (+v).toPrecision(6); +const money = v => (v >= 0 ? "+" : "") + (+v).toFixed(4) + " $"; +const cls = v => v > 0 ? "pos" : v < 0 ? "neg" : "mut"; +function commandNotice(message, bad = false) { + const el = document.getElementById("commandNotice"); + if (!el) return; + el.textContent = message; el.hidden = !message; el.className = bad ? "command-notice neg" : "command-notice pos"; +} +function freshRead(path) { + const h = readHealth.get(path); + return !!h && !h.error && Date.now() - h.time < FRESH_MS; +} +function invalidateRead(path) { + readGenerations.set(path, (readGenerations.get(path) || 0) + 1); + pendingReads.delete(path); readHealth.delete(path); +} +function commandRead(path) { + if (path.startsWith("/api/account/")) return "/api/account"; + if (/^\/api\/coin\/[^/]+\/remove$/.test(path)) return "/api/state"; + if (path.startsWith("/api/coin/")) return path.split("/").slice(0, 4).join("/"); + if (path.startsWith("/api/basis/")) return `/api/basis?ex=${path.split("/")[3]}`; + if (path.startsWith("/api/scanner/")) return "/api/scanner"; + if (path.startsWith("/api/real/")) return "/api/real"; + return "/api/state"; +} +function activeRead() { + if (tab === "basis") return `/api/basis?ex=${bxVenue}`; + if (tab === "real") return "/api/real"; + return selected === SCANNER ? "/api/scanner" : selected ? `/api/coin/${selected}` : "/api/state"; +} +function connectionLabel(path) { + const h = readHealth.get(path); + if (!h) return "Подключение к серверу…"; + const age = h.time ? Math.max(0, Math.floor((Date.now() - h.time) / 1000)) : null; + if (!freshRead(path)) return `Связь потеряна или данные устарели${age == null ? "" : ` · последние данные ${age} с назад`}. ${h.error || "Жду обновления"}. Команды заблокированы до восстановления связи.`; + return `Связь с сервером есть · получено ${age} с назад`; +} +function refreshConnection() { + const path = activeRead(), fresh = freshRead(path); + const el = document.getElementById("connectionStatus"); + if (el) { el.textContent = connectionLabel(path); el.className = fresh ? "connection-status connected" : "connection-status disconnected"; } + const mode = document.getElementById("modeStatus"); + if (mode) { + const selectedCoin = detail?.key === selected ? detail : state?.coins?.find(c => c.key === selected); + const live = tab === "basis" ? bxVenue === "cross_real" : tab === "sim" && !!selectedCoin?.real?.enabled; + mode.textContent = tab === "real" ? "API-ключи и журнал бирж" : tab === "sim" && selected && selected !== SCANNER && !selectedCoin ? "Режим выбранной монеты загружается…" : live ? "РЕАЛЬНАЯ ТОРГОВЛЯ · средства биржи" : "СИМУЛЯЦИЯ · общий виртуальный счёт"; + mode.className = live ? "mode-status mode-live" : "mode-status"; + } + document.querySelectorAll("button[onclick], input[onchange]").forEach(control => { + const handler = control.getAttribute("onclick") || control.getAttribute("onchange") || ""; + if (/\b(saveSettings|trade|resetCoin|removeCoin|closePos|scanner|addCoin|keySave|keyCheck|keyDelete|coinReal|simRealTransfer|simRealPing|simRealSl|simRealTpsl|basisReal|crossToggle|crossFeesSave|basisSave|basisRun|basisClose|basisAdopt|basisReset)\s*\(/.test(handler)) { + control.dataset.command = /\b(saveSettings|removeCoin)\b/.test(handler) ? "state" : /\b(keySave|keyCheck|keyDelete|simRealTransfer|simRealPing|simRealSl|simRealTpsl)\b/.test(handler) ? "real" : "active"; + } + }); + document.querySelectorAll("[data-command]").forEach(control => { + const source = control.dataset.command === "account" ? "/api/account" : control.dataset.command === "state" ? "/api/state" : control.dataset.command === "real" ? "/api/real" : path; + const blocked = !freshRead(source) || (source === "/api/account" && (accountBusy || accountData?.error || (accountIsStale(accountData) && control.dataset.accountDirection === "-1"))); + if (blocked && !control.dataset.connectionDisabled) { + control.dataset.wasDisabled = control.disabled ? "1" : "0"; control.dataset.connectionDisabled = "1"; control.disabled = true; + } else if (!blocked && control.dataset.connectionDisabled) { + control.disabled = control.dataset.wasDisabled === "1"; + delete control.dataset.connectionDisabled; delete control.dataset.wasDisabled; + } else if (blocked) control.disabled = true; + }); + updateAccountVisibility(); +} +function setControlDisabled(control, disabled) { + if (control.dataset?.connectionDisabled) control.dataset.wasDisabled = disabled ? "1" : "0"; + else control.disabled = disabled; +} +async function api(path, body) { + const reading = body === undefined; + if (reading && pendingReads.has(path)) return pendingReads.get(path); + const generation = readGenerations.get(path) || 0; + if (!reading && (!freshRead(commandRead(path)) || (path === "/api/real/simulator" && body.coin && !freshRead(`/api/coin/${body.coin}`)))) { + const error = new Error("Команда не отправлена: сначала дождитесь свежих данных сервера."); + commandNotice(error.message, true); throw error; + } + if (!reading && pendingCommands.has(path)) { + const error = new Error("Эта команда уже выполняется. Дождитесь ответа сервера."); + commandNotice(error.message, true); throw error; + } + const request = (async () => { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), reading ? 8000 : 20000); + if (!reading) pendingCommands.add(path); + try { + const response = await fetch(path, reading ? {signal: controller.signal, cache: "no-store"} : {method: "POST", signal: controller.signal, + headers: {"Content-Type": "application/json", "X-Sim": "1"}, body: JSON.stringify(body)}); + let data; + try { data = await response.json(); } catch (_) { throw new Error(`Сервер вернул некорректный ответ (HTTP ${response.status})`); } + if (!response.ok) throw new Error(data.error || `Ошибка сервера HTTP ${response.status}`); + if (reading && data.error && !(path === "/api/account" && data.balance != null)) throw new Error(data.error); + if (reading) { + if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: Date.now(), error: data.error || ""}); + } + else if (data.ok === false || data.error) commandNotice(data.error || data.message || "Команда отклонена сервером", true); + else commandNotice(data.message || "Команда подтверждена сервером"); + return data; + } catch (cause) { + const reason = cause.name === "AbortError" ? "Сервер не ответил вовремя" : cause.message || "Нет связи с сервером"; + if (reading) { + if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: readHealth.get(path)?.time || 0, error: reason}); + } + else { + cause.userMessage = `Результат команды не подтверждён: ${reason}. Проверьте состояние перед повтором. Автоматического повтора нет.`; + commandNotice(cause.userMessage, true); + } + cause.apiHandled = true; + throw cause; + } finally { + clearTimeout(timeout); + if (!reading) pendingCommands.delete(path); + refreshConnection(); + } + })(); + if (reading) { + pendingReads.set(path, request); + try { return await request; } finally { if (pendingReads.get(path) === request) pendingReads.delete(path); } + } + return request; +} +async function poll(task) { + if (pendingPolls.has(task)) return pendingPolls.get(task); + const work = (async () => { + try { await task(); } catch (error) { + if (!error.apiHandled) commandNotice(`Не удалось обновить интерфейс: ${error.message || "неожиданная ошибка"}`, true); + // api() records connectivity; the next scheduled read recovers. + } + })(); + pendingPolls.set(task, work); + try { await work; } finally { if (pendingPolls.get(task) === work) pendingPolls.delete(task); } +} +function updateAccountVisibility() { + const panel = document.getElementById("paperAccount"); + if (panel) panel.hidden = !(tab === "sim" || (tab === "basis" && bxVenue === "cross")); +} +function renderAccount(account) { + if (!account) return; + if (accountData && account.version != null && accountData.version != null && account.version < accountData.version) return; + if (accountData && account.version === accountData.version && account.updated_at != null && accountData.updated_at != null && account.updated_at < accountData.updated_at) return; + accountData = account; + const health = document.getElementById("accountHealth"); + if (health) { health.textContent = account.error || (accountIsStale(account) ? "Оценка открытых позиций устарела. Дождитесь свежих котировок." : "Один счёт для всех виртуальных сделок. Реальные деньги бирж учитываются отдельно."); health.className = account.error || accountIsStale(account) ? "statusline neg" : "statusline"; } + for (const key of ["balance", "equity", "reserved", "free"]) { + const el = document.getElementById(`account-${key}`); + if (el) el.textContent = account[key] == null ? "—" : `${Number(account[key]).toFixed(2)} $`; + } + const rows = document.getElementById("accountJournal"); + if (rows) rows.innerHTML = (account.journal || []).slice(0, 100).map(entry => `${entry.time ? mskFull(entry.time) : "—"}${escapeHtml(entry.reason || entry.type || entry.action || "Операция")}${entry.amount == null ? "—" : money(entry.amount)}${entry.balance == null ? "—" : Number(entry.balance).toFixed(2)}`).join("") || 'Операций пока нет'; +} +async function loadAccount() { renderAccount(await api("/api/account")); } +async function adjustAccount(direction) { + if (accountBusy) return; + const input = document.getElementById("accountDelta"), msg = document.getElementById("accountMsg"); + const value = input.value.trim().replace(",", "."); + if (!/^\d+(?:\.\d{1,8})?$/.test(value) || !Number.isFinite(Number(value)) || Number(value) <= 0) { + msg.textContent = "Введите сумму больше 0, до 8 знаков после запятой."; return; + } + const [whole, fraction = ""] = value.split("."), decimals = fraction.replace(/0+$/, ""); + const amount = `${direction < 0 ? "-" : ""}${whole.replace(/^0+(?=\d)/, "")}${decimals ? "." + decimals : ""}`; + if (accountData?.error || (direction < 0 && accountIsStale(accountData))) { msg.textContent = accountData.error || "Оценка открытых позиций устарела. Списание доступно после обновления котировок."; return; } + if (pendingAccountAdjustment && pendingAccountAdjustment.amount !== amount) { + msg.textContent = `Прошлая операция (${pendingAccountAdjustment.amount} $) не подтверждена. Повторите её с той же суммой: повторное списание или пополнение исключено по идентификатору.`; return; + } + const request = pendingAccountAdjustment || {amount, request_id: globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}`}; + accountBusy = true; refreshConnection(); msg.textContent = "Сохраняю операцию…"; + try { + // Keep the identifier only after freshness checks: a blocked command has not been sent. + if (!freshRead("/api/account")) { msg.textContent = "Нет свежих данных счёта. Дождитесь восстановления связи."; return; } + pendingAccountAdjustment = request; + const result = await api("/api/account/adjust", request); + pendingAccountAdjustment = null; + if (result.account) renderAccount(result.account); + msg.textContent = result.ok ? `${direction > 0 ? "Пополнено" : "Списано"}: ${Number(value).toFixed(2)} $. Виртуальные деньги.` : result.error || result.message || "Операция отклонена"; + if (result.ok) input.value = ""; + await poll(loadAccount); + } catch (_) { + msg.textContent = "Ответ не получен. Проверьте журнал. Повтор этой суммы использует тот же идентификатор и не проведёт операцию дважды."; + } finally { accountBusy = false; refreshConnection(); } +} + +function buildSettings() { + const s = state.settings; + const make = (box, list) => { + box.innerHTML = ""; + for (const [key, label, kind] of list) { + if (kind === "check") { + box.insertAdjacentHTML("beforeend", ``); + } else if (kind === "select") { + const opts = Object.entries(state.modes).map(([k, v]) => ``).join(""); + box.insertAdjacentHTML("beforeend", `
`); + } else { + box.insertAdjacentHTML("beforeend", `
`); + } + } + }; + make(document.getElementById("settingsMain"), MAIN_FIELDS); + make(document.getElementById("settingsMore"), MORE_FIELDS); + document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => { + settingsDirty = true; + document.getElementById("settingsMsg").textContent = "Есть несохранённые изменения — нажмите «Применить ко всем монетам»"; + })); + if (typeof applyHelpHints === "function") applyHelpHints(); + refreshConnection(); +} +function toggleMore() { + const m = document.getElementById("settingsMore"); + m.classList.toggle("open"); + document.getElementById("moreBtn").textContent = m.classList.contains("open") ? "Скрыть ▴" : "Ещё настройки ▾"; +} +async function saveSettings() { + const body = {}; + document.querySelectorAll("header [data-k]").forEach(el => body[el.dataset.k] = el.type === "checkbox" ? el.checked : el.value); + const r = await api("/api/settings", body); + const msg = document.getElementById("settingsMsg"); + msg.textContent = r.ok ? "Настройки применены ко всем монетам" : "Ошибка: " + r.error; + msg.style.color = r.ok ? "var(--green)" : "var(--red)"; + if (r.ok) { settingsDirty = false; await loadState(true); } +} + +function leaderBadge(c) { + const l = c.leadership || {}; + if (l.edge == null) return 'проверяется…'; + const edge = l.edge, who = edge >= 0 ? c.leader : c.follower; + const ok = !c.leader_block; + return `${who} ${ok ? "✓" : "✗"} (${Math.abs(l.pct ?? 0).toFixed(0)}%)`; +} +// Is the coin suitable for trades now: does the leader (DEX / KuCoin) really move before the futures? +function suitability(c) { + const l = c.leadership || {}, edge = l.edge, min = c.min_edge ?? 0.1; + const tip = l.edge == null ? "" : `${c.leader}→${c.follower} ${l.lead.toFixed(2)} / ${c.follower}→${c.leader} ${l.follow.toFixed(2)} · перевес ${edge >= 0 ? "+" : ""}${edge.toFixed(2)}, нужно ${min}`; + const pct = l.pct ?? 0; + let level, text; + if (edge == null) { + level = "check"; text = `◌ проверяю, кто ведёт (${(c.grid_minutes || 0).toFixed(1)} из 2 мин данных)`; + } else if (edge >= min) { + const mins = l.since ? (c.now - l.since) / 60 : 0; + const fresh = mins < 2; + level = fresh ? "new" : "ok"; + text = `● подходит: ${c.leader} опережает ${c.follower} на ${pct.toFixed(0)}%` + + (l.since ? ` · ${fresh ? "только что" : "уже " + mins.toFixed(0) + " мин"}, с ${msk(l.since).slice(0, 5)}` : ""); + } else if (edge > 0) { + level = "near"; text = `◐ почти: ${c.leader} впереди на ${pct.toFixed(0)}%, мало`; + } else { + level = "no"; text = `○ не подходит: ${c.follower} опережает ${c.leader} на ${(-pct).toFixed(0)}%`; + } + const stop = c.auto_stop ? `
⏸ ${c.auto_stop}
` : ""; + return {level, html: `
${text}
${stop}`}; +} +function renderTiles() { + const box = document.getElementById("tiles"); + box.innerHTML = state.coins.map(c => { + const realOn = !!(c.real && c.real.enabled); + if (realOn) c = {...c, trades: c.real.trades, wins: c.real.wins, net: c.real.net, unrealized: 0}; // exchange figures + const pnl = c.net + c.unrealized; + const fit = suitability(c); + return `
+ ${realOn ? 'РЕАЛ' : ""} + + +
${c.symbol} ${c.follower} + ${c.open ? `${c.open} откр.` : ""}
+
сигнал: ${c.leader} → фьючерс ${c.follower} ${c.follow_ticker}${c.live ? "" : " · нет данных"}
+ ${suitability(c).html} +
цена${price(c.price)}
+
сделок ${c.trades}${money(pnl)}
+
винрейт${c.trades + ? `${(c.wins / c.trades * 100).toFixed(0)}% · ${c.wins} из ${c.trades}` + : '—'}
+
`; + }).join("") + `
+
+
сканер новых монет
`; +} +async function loadState(rebuild) { + const request = ++stateRequest, result = await api("/api/state"); + if (request < stateApplied) return; + stateApplied = request; state = result; + renderAccount(state.account); + if (rebuild || !document.querySelector("header [data-k]")) buildSettings(); + if ((!selected || (selected !== SCANNER && !state.coins.some(c => c.key === selected))) && state.coins.length) { + detailEpoch++; detail = null; selected = state.coins[0].key; + } + renderTiles(); + refreshConnection(); +} +function selectCoin(key) { + detailEpoch++; + invalidateRead(key === SCANNER ? "/api/scanner" : `/api/coin/${key}`); + pendingPolls.delete(loadDetail); pendingPolls.delete(loadScanner); + selected = key; localStorage.setItem("sim.coin", key); + seenOpen = new Set(); seenClosed = 0; detail = null; + document.getElementById("center").textContent = "Загрузка выбранной монеты…"; + if (state) renderTiles(); refreshCenter(); refreshConnection(); +} +function refreshCenter() { return poll(selected === SCANNER ? loadScanner : loadDetail); } + +// --- scanner panel ------------------------------------------------------------------------------- +const SCANNER = "__scanner__"; +let scannerBuilt = false; +function scannerSkeleton() { + document.getElementById("center").innerHTML = ` +
Сканер новых монет
+
ищет монеты, где цена на DEX опережает фьючерсы (запись 15 мин на цикл, по кругу)
+
+
+
+
+ + + + +
+
+
+
+

Проверенные монеты — «Добавить» переносит монету в левую панель (остановленной); зелёные — где DEX опережал

+
+ + +
МонетаПроверокDEX опережалПоследний выводФьючерсПул DEXЛаг, сt+1→t+5Попад.tКогда
+
+

Журнал сканера

`; + scannerBuilt = true; +} +async function loadScanner() { + if (selected !== SCANNER || tab !== "sim") return; + const epoch = detailEpoch; + if (!document.getElementById("scRows")) scannerSkeleton(); + const s = await api("/api/scanner"); + if (selected !== SCANNER || epoch !== detailEpoch || tab !== "sim" || !document.getElementById("scRows")) return; + if (s.error) { document.getElementById("scMsg").textContent = s.error; return; } + setControlDisabled(document.getElementById("scStart"), s.running); + setControlDisabled(document.getElementById("scStop"), !s.running); + document.getElementById("scAuto").checked = s.auto_add; + document.getElementById("scState").innerHTML = s.running + ? `● сканер работает · циклов ${s.cycles}` : `■ сканер остановлен · циклов ${s.cycles}`; + document.getElementById("scLog").textContent = s.log.join("\n"); + document.getElementById("scRows").innerHTML = s.coins.map(c => { + let action; + if (c.in_list) action = 'в левой панели'; + else if (c.addable && c.leads) action = ``; + else if (c.addable) action = ``; + else action = `${c.unsupported || "нельзя добавить"}`; + return `${c.symbol}${c.checks} + ${c.leads}${c.verdict}${c.futures} ${c.futures_symbol} + ${c.dex_pool}${c.lag}${c.follow}%${c.hit} + ${c.t_stat}${c.last_lead || c.last_time}${action}`; + }).join("") || 'Пока нет результатов — запустите сканер; первый цикл ≈ 20 минут'; + refreshConnection(); +} +async function scanner(action) { + const body = action === "config" ? {auto_add: document.getElementById("scAuto").checked} + : {minutes: document.getElementById("scMin").value, coins: document.getElementById("scCoins").value}; + if (action === "start") { + body.minutes = Number(String(body.minutes).replace(",", ".")); body.coins = Number(body.coins); + if (!Number.isFinite(body.minutes) || body.minutes <= 0 || !Number.isInteger(body.coins) || body.coins < 1 || body.coins > 13) { + document.getElementById("scMsg").textContent = "Минут на цикл — число больше 0; монет за цикл — целое число от 1 до 13."; return; + } + } + const epoch = detailEpoch; + const result = await api(`/api/scanner/${action}`, body); + if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = result.error || result.message || "Команда подтверждена"; + setTimeout(() => { if (selected === SCANNER && epoch === detailEpoch) poll(loadScanner); }, 1200); +} +async function addCoin(symbol) { + const epoch = detailEpoch; + const r = await api("/api/scanner/add", {symbol}); + if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = r.message || r.error || ""; + await loadState(); if (selected === SCANNER && epoch === detailEpoch) await loadScanner(); +} + +function centerSkeleton() { + document.getElementById("center").innerHTML = ` +
+
+
+
+
+
+
${[60, 300, 600].map(s => ``).join(" ")}
+
+ +
изменение цены в % от начала окна · ▲▼ — входы, ● — выходы
+
+
+
+
+ + + + + + +
+
+
+
+

Сделки — открытые сверху (жёлтым), ✕ закрывает по текущей цене

+
+ + +
Время (МСК)Напр.Объём, $ВходВыход / сейчас%Итог, $КомиссияПричинаСек.Почему вошли
+
`; + document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === range)); +} +function setRange(s) { range = s; localStorage.setItem("sim.range", s); document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === s)); drawChart(); } +async function trade(action) { if (!coinReady()) return; const key = detail.key; await api(`/api/coin/${key}/${action}`, {}); loadDetail(); loadState(); } +async function resetCoin() { + if (!coinReady() || !confirm(`Сбросить статистику ${detail.symbol} (${detail.leader} → ${detail.follower})?\nИстория этой пары будет очищена. Общий виртуальный счёт не меняется. При открытых позициях сброс недоступен.`)) return; + const r = await api(`/api/coin/${selected}/reset`, {}); + if (document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || ""; + if (r.ok) { seenOpen = new Set(); seenClosed = 0; } + loadDetail(); loadState(); +} +async function removeCoin(key) { + const c = state.coins.find(x => x.key === key); + if (!c || !confirm(`Удалить ${c.name}?\n\nСбор цен и сравнение для этой пары остановятся` + + (c.open ? `, открытые позиции (${c.open}) закроются по текущей цене` : "") + + `.\nВернуть можно через «+» → сканер → «Добавить».`)) return; + const r = await api(`/api/coin/${key}/remove`, {}); + const wasSelected = selected === key; + if (wasSelected) selected = null; + await loadState(); + if (wasSelected) selectCoin(selected || SCANNER); + alert(r.message || r.error || ""); +} +function coinReady() { return !!detail && detail.key === selected; } +async function closePos(uid, key = detail?.key) { + if (!coinReady() || key !== selected) return; + const r = await api(`/api/coin/${key}/close${uid ? "/" + uid : ""}`, {}); + if (key === selected && document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || ""; + loadDetail(); +} + +async function loadDetail() { + if (tab !== "sim" || !selected || selected === SCANNER) return; + const key = selected, epoch = detailEpoch, request = ++detailRequest; + const d = await api(`/api/coin/${key}`); + if (key !== selected || epoch !== detailEpoch || request < detailApplied) return; + detailApplied = request; + if (d.error) { document.getElementById("center").innerHTML = `
${d.error}
`; return; } + if (!document.getElementById("chart") || !detail || detail.key !== d.key) centerSkeleton(); + detail = d; + document.getElementById("cName").innerHTML = `${d.symbol} фьючерс на ${d.follower} + сигнал: ${d.leader} → ставки: ${d.follower} ${d.follow_ticker}`; + const lat = v => v == null ? "" : ` · ~${v.toFixed(0)} мс`; + const linksBox = document.getElementById("cLinks"); + const linksHtml = (d.links || []).map(l => `${l.label} ↗`).join(""); + if (linksBox.innerHTML !== linksHtml) linksBox.innerHTML = linksHtml; + document.getElementById("cFeeds").textContent = `${d.lead_status}${lat(d.lead_latency)} | ${d.follow_status}${lat(d.follow_latency)}`; + document.getElementById("lgLead").textContent = `${d.leader}: ${price(d.lead_price)}`; + document.getElementById("lgFollow").textContent = `${d.follower} ${d.follow_ticker}: ${price(d.bid)} / ${price(d.ask)}`; + const winPct = d.trades ? (d.wins / d.trades * 100).toFixed(0) + "%" : "—"; + const realOn = !!(d.real && d.real.enabled); + const rb = document.getElementById("btnReal"); + rb.textContent = realOn ? "● РЕАЛЬНАЯ торговля — выключить" : "Включить реальную торговлю"; + rb.className = realOn ? "realon" : ""; + let stats; + if (realOn) { + // real mode: every figure is from the exchange (its fill history for this coin, the account's balance) + const r = d.real, bal = real && real.balances && real.balances[d.exchange]; + const age = bal && bal.time ? Math.round(Date.now() / 1000 - bal.time) : null; + const balText = !bal ? "нет ключей" : !bal.values ? `${bal.error}` + : Object.entries(bal.values).map(([k, v]) => `
${k}: ${typeof v === "number" ? v.toFixed(4) : v}
`).join("") + + `
${bal.error ? 'не обновился: ' + bal.error + " · " : ""}${age} с назад
`; + const stateText = {"": "нет", opening: "открывается…", open: "открыта", closing: "закрывается…", check: "проверка закрытия…"}[r.state] || r.state; + const src = r.source === "биржа" ? `история биржи, ${Math.round(Date.now() / 1000 - r.synced)} с назад` + + (r.sync_error ? ` · ${r.sync_error}` : "") : `жду историю биржи${r.sync_error ? ": " + r.sync_error : ""}`; + stats = [ + ["Баланс на бирже", balText, ""], ["Реальных сделок", r.trades, ""], + ["В плюс", r.trades ? `${r.winrate.toFixed(0)}% · ${r.wins} из ${r.trades}` : "—", ""], + ["PNL биржи (до комиссий)", money(r.gross), cls(r.gross)], ["Комиссии биржи", "−" + r.fees.toFixed(4) + " $", "neg"], + ["Итог после комиссий", money(r.net), cls(r.net)], ["Итог, % от объёма", r.net_pct == null ? "—" : r.net_pct.toFixed(3) + "%", cls(r.net_pct || 0)], + ["Реальная позиция", stateText + (r.problem ? `
${r.problem}
` : "") + + (r.paused_s > 0 ? `
пауза ${Math.ceil(r.paused_s / 60)} мин: ${r.last_error}
` : ""), + r.state || r.paused_s > 0 ? "neg" : ""], + ["Откуда цифры", `${src}`, ""], + ]; + } else { + stats = [ + ["Общий виртуальный баланс", accountData ? Number(accountData.balance).toFixed(2) + " $" : "—", ""], ["Сделок", d.trades, ""], ["В плюс", winPct, ""], + ["Итог", money(d.net), cls(d.net)], ["Комиссии", d.fees.toFixed(4) + " $", ""], + ["Открыто", `${d.open} · ${money(d.unrealized)}`, cls(d.unrealized)], + ]; + } + stats.push( + ["Сигнал", `${d.signal >= 0 ? "+" : ""}${d.signal.toFixed(3)}%`, cls(d.signal)], + ["Уверенность", d.confidence.toFixed(2), ""], + ["Кто ведёт", leaderBadge(d), ""], + ["Подходит для сделок", suitability(d).html, ""]); + if (state && state.settings.auto_tp) stats.push(["Прогноз", `${d.forecast.toFixed(3)}%`, ""]); + document.getElementById("stats").innerHTML = stats.map(([k, v, c]) => `
${k}
${v}
`).join(""); + setControlDisabled(document.getElementById("btnStart"), d.running); + setControlDisabled(document.getElementById("btnStop"), !d.running); + document.getElementById("cStatus").textContent = (d.running ? "● сделки открываются · " : "■ новые сделки остановлены (цены и прогноз работают) · ") + d.status; + if (d.message) document.getElementById("cMsg").textContent = d.message; + renderRows(d); + drawChart(); + refreshConnection(); +} + +function renderRows(d) { + const t = mskFull; + const open = d.positions.map(p => { + const fresh = !seenOpen.has(p.uid); seenOpen.add(p.uid); + return `${t(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.side}${p.usd.toFixed(2)} + ${price(p.entry)}${price(p.side === "LONG" ? d.bid : d.ask)}${p.pct.toFixed(3)}% + ${money(p.pnl)}тейк ${price(p.target)} · стоп ${price(p.stop)} + открыта${p.age.toFixed(0)}${p.why} + `; + }).join(""); + if (d.real && d.real.enabled) { + // real mode: closed trades are the real ones, rebuilt from the exchange's own fills + const rows = (d.real_trades || []).map(c => ` + ${mskFull(c.closed)} РЕАЛ${c.side}${(c.entry * c.coins).toFixed(2)} + ${price(c.entry)}${price(c.exit)}${c.pct.toFixed(3)}% + ${money(c.net)} + ${c.fees.toFixed(4)}${c.exact ? "" : ' ≈'} + PNL биржи ${money(c.gross)}${(c.closed - c.opened).toFixed(0)}${c.reason}`).join(""); + document.getElementById("rows").innerHTML = open + rows || 'Реальных сделок пока нет'; + return; + } + const freshClosed = d.closed.length - seenClosed; seenClosed = d.closed.length; + const closed = d.closed.map((c, i) => ` + ${mskFull(Date.parse(c.closed) / 1000)}${c.side}${c.usd.toFixed(2)}${price(c.entry)}${price(c.exit)} + ${c.pct.toFixed(3)}%${money(c.net)}${c.fee.toFixed(4)} + ${c.reason}${c.hold.toFixed(0)}${c.why}`).join(""); + document.getElementById("rows").innerHTML = open + closed || 'Сделок пока нет'; +} + +function drawChart() { + const cv = document.getElementById("chart"); if (!cv || !detail) return; + const dpr = window.devicePixelRatio || 1, w = cv.clientWidth, h = cv.clientHeight; + cv.width = w * dpr; cv.height = h * dpr; + const g = cv.getContext("2d"); g.scale(dpr, dpr); g.clearRect(0, 0, w, h); + const t1 = detail.now, t0 = t1 - range, pad = {l: 52, r: 10, t: 10, b: 22}; + const norm = s => { const pts = s.filter(p => p[0] >= t0); if (!pts.length) return []; const b = pts[0][1]; return pts.map(p => [p[0], (p[1] / b - 1) * 100]); }; + const L = norm(detail.lead_series), F = norm(detail.follow_series); + const all = L.concat(F).map(p => p[1]); + let lo = Math.min(-0.05, ...all), hi = Math.max(0.05, ...all); const span = hi - lo; lo -= span * 0.08; hi += span * 0.08; + const X = t => pad.l + (t - t0) / (t1 - t0) * (w - pad.l - pad.r), Y = v => pad.t + (hi - v) / (hi - lo) * (h - pad.t - pad.b); + g.strokeStyle = "#2a3240"; g.fillStyle = "#8b95a7"; g.font = "11px Segoe UI"; g.lineWidth = 1; + const raw = (hi - lo) / 5, mag = Math.pow(10, Math.floor(Math.log10(raw))); + const step = [1, 2, 5, 10].map(k => k * mag).find(s => s >= raw); + for (let v = Math.ceil(lo / step) * step; v <= hi; v += step) { + g.beginPath(); g.moveTo(pad.l, Y(v)); g.lineTo(w - pad.r, Y(v)); g.stroke(); + g.fillText(v.toFixed(step < 0.01 ? 3 : 2) + "%", 4, Y(v) + 4); + } + for (let k = 0; k <= 4; k++) { const t = t0 + k * range / 4; g.fillText(msk(t), X(t) - 22, h - 6); } + const line = (pts, color, stepped) => { + if (!pts.length) return; g.strokeStyle = color; g.lineWidth = 1.8; g.beginPath(); + pts.forEach((p, i) => { const x = X(p[0]), y = Y(p[1]); if (!i) g.moveTo(x, y); else { if (stepped) g.lineTo(x, Y(pts[i - 1][1])); g.lineTo(x, y); } }); + g.lineTo(X(t1), Y(pts[pts.length - 1][1])); g.stroke(); + }; + line(L, getComputedStyle(document.body).getPropertyValue("--lead"), true); + line(F, getComputedStyle(document.body).getPropertyValue("--follow"), false); + // trade markers on the futures line + const at = t => { let best = null; for (const p of F) { if (p[0] <= t) best = p; else break; } return best || F[0]; }; + const mark = (t, up, color, circle) => { + if (t < t0 || !F.length) return; const p = at(t); if (!p) return; const x = X(t), y = Y(p[1]); + g.fillStyle = color; g.beginPath(); + if (circle) g.arc(x, y, 3.5, 0, 7); else if (up) { g.moveTo(x, y - 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); } else { g.moveTo(x, y + 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); } + g.fill(); + }; + for (const c of detail.closed) { + const tc = Date.parse(c.closed) / 1000; if (tc < t0) continue; + mark(tc - c.hold, c.side === "LONG", "#8b95a7"); mark(tc, false, c.net > 0 ? "#2ecc71" : "#ff5c5c", true); + } + for (const p of detail.positions) mark(p.opened, p.side === "LONG", "#f5c542"); + if (!L.length && !F.length) { g.fillStyle = "#8b95a7"; g.fillText("копятся цены…", w / 2 - 40, h / 2); } +} + +// --- arbitrage tab ------------------------------------------------------------------------------- +let tab = localStorage.getItem("sim.tab") || "sim", arb = null, arbSort = localStorage.getItem("arb.sort") || "net_transfer"; +let arbMarket = localStorage.getItem("arb.market") || "spot"; +let arbOpen = new Set(), arbExBuilt = false, feesFor = null; +const isSpot = () => arbMarket === "spot"; +const val = (id, d) => { const v = parseFloat(document.getElementById(id).value); return isNaN(v) ? d : v; }; +// --- budget calculator (top of the page, every tab) ----------------------------------------------------------- +// One spot–futures trade of «stake» $: the coins bought on spot (stake + fees) and the short's futures money. With +// E $ behind a short of N $ the short is liquidated at a rise of x = (E/N − mmr)/(1 + mmr), so for a wanted x: +// E = N·((1 + mmr)·x + mmr) — the same formula the program checks before every short. +const CALC_IDS = ["cStake", "cCount", "cLiq", "cEx", "cMmr", "cFee"]; +function calcToggle() { + const p = document.getElementById("calcPanel"), open = p.style.display === "none"; + p.style.display = open ? "" : "none"; + document.getElementById("calcBtn").classList.toggle("on", open); + if (open) calcRun(); +} +function calcRun() { + const v = id => { const x = parseFloat(String(document.getElementById(id).value).replace(",", ".")); return isFinite(x) ? x : NaN; }; + const stake = v("cStake"), n = Math.floor(v("cCount")), liq = v("cLiq"), ex = Math.floor(v("cEx")), mmr = v("cMmr") / 100, + fee = v("cFee") / 100; + const out = document.getElementById("calcOut"); + try { localStorage.setItem("calc", JSON.stringify(Object.fromEntries(CALC_IDS.map(i => [i, document.getElementById(i).value])))); } catch (e) {} + if (![stake, n, liq, ex, mmr, fee].every(isFinite) || stake <= 0 || n < 1 || liq <= 0 || ex < 1 || mmr < 0 || fee < 0) { + out.innerHTML = '
Заполните поля положительными числами
'; return; + } + const spot = stake * (1 + fee); // the coins bought on spot, with the buy fee + const futFor = x => stake * ((1 + mmr) * x / 100 + mmr); // futures money for a liquidation x % above the entry + const fut = futFor(liq), money = x => x.toFixed(2) + " $"; + const back = stake * (liq / 100); // what the short loses at the liquidation price + // what the program itself requires before an entry (cross.py: SPOT_NEED 1.01, FUT_NEED 1.03 or more for the + // liquidation reserve): spot of A ≥ 101 % of the stake, futures of B ≥ max(103 %, the reserve's money) + const pSpot = stake * 1.01, pFut = Math.max(stake * 1.03, fut); + const progLiq = ((pFut / stake) - mmr) / (1 + mmr) * 100; + // money on the accounts for the wanted move to the liquidation: the futures account carries the shorts, the spot + // account buys the coins; between exchanges every trade has its spot on one exchange and its short on another + const trades = Math.max(1, Math.floor(n * ex / 2)); // n per exchange, each trade takes two exchanges + const steps = [...new Set([25, 50, 100, 150, 200, Math.round(liq)])].sort((a, b) => a - b); + out.innerHTML = ` +
Цена может вырасти на ${liq}% до ликвидации шорта — для этого на счетах каждой биржи: +
Фьючерсный счёт (${n} шорт.)${money(n * fut)}
+
Спотовый счёт (${n} покупок монет)${money(n * spot)}
+
С автопереводом между спотом и фьючерсами биржи${money(n * Math.max(spot, fut))}
+
Под шорты: ${n} × ${money(fut)}; ликвидация при росте монеты на ${liq}% (шорт теряет ≈ ${money(back)} на сделку). + Сделки одной биржи: шорты на её фьючерсах, покупки — на её споте.
+
Всего на ${ex} ${ex === 1 ? "бирже" : "биржах"}: ${money(n * Math.max(spot, fut) * ex)} +
чтобы каждая биржа могла быть и стороной спота, и стороной шорта в ${n} сделках. Минимум, если + все ${trades} сделок в одну сторону (спот на одних биржах, шорт на других): ${money(trades * (spot + fut))}
+
Одна сделка: спот / фьючерсы / обе ноги${money(spot)} / ${money(fut)} / ${money(spot + fut)}
+
Спот-фьюч на одной бирже (обе ноги там же), ${n} сделок${money(n * (spot + fut))}
+ + ${steps.map(x => ` + `).join("")}
До ликвидацииФьючерсы на 1 шортФьючерсы на ${n} шорт.
+${x}%${money(futFor(x))}${money(n * futFor(x))}
+
По текущей логике программы на каждой бирже: ${money(n * Math.max(pSpot, pFut))}, + всего на ${ex}: ${money(n * Math.max(pSpot, pFut) * ex)} +
Фьючерсный / спотовый счёт${money(n * pFut)} / ${money(n * pSpot)}
+ ${liq < progLiq - 0.5 ? `
Желаемые ${liq}% меньше, чем держит программа: + на фьючерсах будет ${money(n * pFut)} и ликвидация ≈ +${progLiq.toFixed(0)}% — дальше, чем вы просили.
` : ""} +
Перед входом программа требует на споте биржи A 101% ставки, а на фьючерсах биржи B — не меньше + 103% ставки (ликвидация ≈ +${progLiq.toFixed(0)}%) или больше, если «Мин. запас до ликвидации» выше. Меньше — биржа + краснеет и не участвует в поиске.
`; +} +async function calcFromSettings() { + const r = await api("/api/basis?ex=cross_real"); + if (!r || r.error) return; + const limits = ((r.balances || {}).rows || []).map(x => x.limit).filter(x => x != null); + document.getElementById("cStake").value = r.settings.amount; + document.getElementById("cLiq").value = r.settings.min_liq_pct; + if (limits.length) document.getElementById("cCount").value = Math.max(...limits); + const keyed = ((r.balances || {}).rows || []).filter(x => x.keys && x.on).length; + if (keyed) document.getElementById("cEx").value = keyed; + calcRun(); +} +(function calcInit() { + let saved = {}; + try { saved = JSON.parse(localStorage.getItem("calc") || "{}"); } catch (e) {} + for (const id of CALC_IDS) { + const el = document.getElementById(id); + if (saved[id] != null) el.value = saved[id]; + el.addEventListener("input", calcRun); + } +})(); +function showTab(name) { + if (name === "arb") name = "basis"; // the old «Арбитраж» is gone: the one mode lives in «basis» + tab = name; localStorage.setItem("sim.tab", name); + document.getElementById("simView").style.display = name === "sim" ? "" : "none"; + document.getElementById("basisView").style.display = name === "basis" ? "" : "none"; + document.getElementById("realView").style.display = name === "real" ? "" : "none"; + document.getElementById("tabSim").classList.toggle("on", name === "sim"); + document.getElementById("tabArb").classList.toggle("on", name === "basis"); + document.getElementById("tabReal").classList.toggle("on", name === "real"); + if (name === "basis") poll(loadBasis); + if (name === "real") { realBuilt = false; poll(loadReal); } + if (name === "sim") refreshCenter(); + refreshConnection(); +} + +// --- real trading: keys, switches, journal ------------------------------------------------------- +let real = null, realBuilt = false; +async function loadReal() { + const request = ++realRequest, result = await api("/api/real"); + if (request < realApplied) return; + realApplied = request; real = result; + const s = real.simulator; + const tpsl = document.getElementById("simRealTpsl"); + if (document.activeElement !== tpsl) tpsl.checked = s.exchange_tpsl !== false; + const trBox = document.getElementById("simRealTransfer"); + if (document.activeElement !== trBox) trBox.checked = s.auto_transfer !== false; + const slBox = document.getElementById("simRealSl"); + if (document.activeElement !== slBox) slBox.value = s.sl_pct ?? 1.5; + const pingBox = document.getElementById("simRealPing"); + if (document.activeElement !== pingBox) pingBox.value = s.max_ping_ms ?? 400; + const fees = Object.entries(s.fees || {}).map(([e, p]) => `${e} ${p.toFixed(3)}%`).join(", "); + const lat = Object.entries(real.latency || {}).map(([h, ms]) => `${h.split(".").slice(0, -1).join(".")} ${ms.toFixed(0)} мс`).join(", "); + document.getElementById("simRealFees").textContent = (fees ? `· комиссия с биржи: ${fees}` : "") + (lat ? ` · задержка до бирж: ${lat}` : ""); + const realCoins = state ? state.coins.filter(c => c.real && c.real.enabled).map(c => c.symbol) : []; + document.getElementById("simReal").classList.toggle("on", realCoins.length > 0); + document.getElementById("simRealHint").innerHTML = realCoins.length + ? `РЕАЛЬНАЯ ТОРГОВЛЯ: ${realCoins.join(", ")} · остальные монеты — виртуальные сделки` + : "виртуальные сделки, ордера на биржи не отправляются"; + if (tab !== "real") return; + if (!realBuilt) { + document.getElementById("keyCards").innerHTML = Object.entries(real.keys).map(([ex, k]) => `
+ ${k.name} + + +
+ +
+
`).join(""); + realBuilt = true; + } + for (const [ex, k] of Object.entries(real.keys)) { + document.getElementById(`kst-${ex}`).innerHTML = k.set ? `ключ сохранён: ${k.key}` : 'ключей нет'; + } + document.getElementById("realJournal").innerHTML = real.journal.map(j => ` + ${mskFull(j.time)}${j.tab === "basis" ? "Арбитраж" : "Симулятор"}${j.exchange}${j.coin} + ${{open: "открытие", close: "закрытие", orphan: "закрытие осиротевшей", transfer: "перевод USDT"}[j.action] || j.action} + ${j.text}`).join("") + || 'Реальных ордеров ещё не было'; +} +async function keySave(ex) { + const key = document.getElementById(`kk-${ex}`), secret = document.getElementById(`ks-${ex}`); + const r = await api(`/api/real/keys/${ex}`, {api_key: key.value, api_secret: secret.value}); + document.getElementById(`kmsg-${ex}`).innerHTML = r.ok ? 'сохранено' : `${r.error}`; + if (r.ok) { key.value = ""; secret.value = ""; } + loadReal(); +} +async function keyCheck(ex) { + const msg = document.getElementById(`kmsg-${ex}`); + msg.textContent = "проверяю…"; + const r = await api(`/api/real/keys/${ex}/check`, {}); + msg.innerHTML = r.ok ? 'ключи работают: ' + Object.entries(r.balances).map(([k, v]) => + `${k} ${typeof v === "number" ? v.toFixed(2) : v}`).join(" · ") + "" : `${r.error}`; +} +async function keyDelete(ex) { + if (!confirm("Удалить сохранённые ключи этой биржи?")) return; + const r = await api(`/api/real/keys/${ex}/delete`, {}); + document.getElementById(`kmsg-${ex}`).textContent = r.ok ? "удалены" : r.error || r.message || "Удаление не подтверждено"; + loadReal(); +} +async function coinReal() { + if (!coinReady()) return; + const want = !(detail.real && detail.real.enabled); + if (want) { + const keys = real && real.keys[detail.exchange]; + if (!keys || !keys.set) { alert(`Сначала сохраните API-ключи ${detail.follower} во вкладке «Реальная торговля · API-ключи».`); return; } + if (!confirm(`Включить РЕАЛЬНУЮ торговлю для ${detail.symbol} (${detail.follower} ${detail.follow_ticker})?\n\n` + + "Каждая новая позиция этой монеты будет открываться настоящим рыночным ордером на фьючерсе " + + `(ставка × плечо из настроек)${real.simulator.exchange_tpsl !== false ? ", с TP и SL на бирже" : ""}. ` + + "Одна сделка за раз: следующая — только после подтверждённого закрытия.")) return; + } + const r = await api("/api/real/simulator", {coin: detail.key, enabled: want}); + document.getElementById("cMsg").textContent = r.ok ? (want ? "реальная торговля включена" : "реальная торговля выключена") : r.error; + await loadState(); await loadReal(); loadDetail(); +} +async function simRealTransfer() { + const r = await api("/api/real/simulator", {auto_transfer: document.getElementById("simRealTransfer").checked}); + document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error; + loadReal(); +} +async function simRealPing() { + const r = await api("/api/real/simulator", {max_ping_ms: document.getElementById("simRealPing").value}); + document.getElementById("simRealMsg").textContent = r.ok ? "порог пинга сохранён" : r.error; + loadReal(); +} +async function simRealSl() { + const r = await api("/api/real/simulator", {sl_pct: document.getElementById("simRealSl").value}); + document.getElementById("simRealMsg").textContent = r.ok ? "стоп-лосс сохранён" : r.error; + loadReal(); +} +async function simRealTpsl() { + const r = await api("/api/real/simulator", {exchange_tpsl: document.getElementById("simRealTpsl").checked}); + document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error; + loadReal(); +} +async function basisReal() { + if (!basisReady()) return; + const want = !bx.settings.real; + if (want && bx.mode === "cross") { + const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange); + if (ready.length < 2) { alert("Нужны API-ключи хотя бы двух включённых бирж (вкладка «Реальная торговля · API-ключи»)."); return; } + if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Между биржами»?\n\nБиржи с ключами: ${ready.join(", ")}.\n\nПри входе: шорт на бирже B, ` + + `затем покупка тех же монет на споте биржи A на ${bx.settings.amount} $; при возврате разницы к обычной — выкуп шорта и продажа ` + + "спота. Нужны USDT на споте A и на фьючерсах B. Одна сделка за раз; изменение баланса считается с момента «Старт».")) return; + } else if (want) { + const keys = (real && real.keys[bxVenue]) || {}; + if (!keys.set) { alert(`Сначала сохраните API-ключи ${bx.venue} во вкладке «Реальная торговля · API-ключи».`); return; } + if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Спот-фьюч» на ${bx.venue}?\n\nПри входе: покупка монеты на споте на ` + + `${bx.settings.amount} $ и шорт того же количества на фьючерсе; при схождении — выкуп шорта и продажа спота.`)) return; + } + const r = await api(`/api/basis/${bxVenue}/settings`, {real: want}); + document.getElementById("bxMsg").textContent = r.ok ? "" : r.error; + loadBasis(); +} + +// --- spot–futures tab -------------------------------------------------------------------------- +// «Арбитраж»: the simulation and real trading — two engines, each with its own Start / Stop, settings and trades +const BX_VENUES = [["cross", "Симуляция"], ["cross_real", "● Реальная торговля"]]; +const BX_READY = new Set(["cross", "cross_real"]); +// «between exchanges»: spot on A, perp on B — its own settings and tables +const CX_FIELDS = [ + ["amount", "Сумма сделки, $"], ["min_net_pct", "Мин. чистая прибыль для входа, %"], + ["max_gap_pct", "Макс. разница, %"], ["history_min", "Наблюдать пару не меньше, мин"], + ["exit_over_usual_pct", "Закрыть при разнице ≤ обычной + , %"], + ["exit_hold_s", "Выход: условие держится не меньше, с (0 — сразу)"], + ["stop_widen_pct", "Стоп: разница шире входа на, % (0 — нет)"], + ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["cooldown_s", "Пауза по монете, с"], + ["min_turnover", "Мин. оборот каждой ноги 24ч, $"], ["limit_hold_s", "Лимитный вход: ждать, с"], + ["negative_funding_before_minutes", "При отрицательном funding не входить за, мин"], + ["min_funding_pct", "Не входить, если funding ниже, %"], + ["simulation_entry_delay_ms", "Задержка открытия в симуляции, мс"], + ["simulation_exit_delay_ms", "Задержка закрытия в симуляции, мс"], + ["max_spread_pct", "Макс. спред каждой ноги, % (0 — нет)"], + ["confirm_ms", "Подтверждение по стакану: пауза между 2 проверками, мс"], + ["min_liq_pct", "Мин. запас до ликвидации шорта при входе, %"], + ["liq_close_pct", "Закрыть, если до ликвидации меньше, % (0 — нет)"]]; +const CX_CHECKS = [["search_sf", "Искать: спот → фьючерс между биржами"], ["search_in", "Искать: спот → фьючерс внутри биржи"], + ["search_ss", "Искать: спот → спот между биржами (реально — из запаса монеты на бирже продажи)"], + ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами внутри биржи (реальный режим)"], + ["entry_ioc", "Вход первой ногой лимитным IOC по подтверждённой цене: не исполнился — сделки нет (реальный режим)"], + ["entry_limit", "Вход лимитным шортом с ожиданием «Лимитный вход: ждать, с» (если IOC выключен)"], + ["block_negative_funding", "Не открывать сделку при отрицательном funding"], + ["fees_auto", "Комиссии сами корректируются по завершённым реальным сделкам"]]; +const CX_EX = ["Bybit", "MEXC", "HTX", "Gate"]; +// the balances card: built once (the fee fields keep what is typed), its figures refreshed with every update +function cxBalBuild() { + document.getElementById("cxBal").innerHTML = CX_EX.map(e => ` + ${e}
+ + ————— + 0 / +
+
${e === "Bybit" + ? `
зона инноваций:
+
` : ""}`).join(""); + document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => el.addEventListener("input", () => { + el.dataset.dirty = "1"; document.getElementById("cxBalMsg").textContent = "есть изменения — нажмите «Сохранить комиссии и лимиты»"; })); +} +function cxBalRender() { + const b = bx.balances, s = bx.settings; + if (!b) return; + const money = v => v == null ? "—" : v.toFixed(2); + const chg = (p, usd) => p == null ? '—' + : `${pct(p, 2)}${usd != null ? ` (${dollars(usd)} $)` : ""}`; + for (const r of b.rows) { + const e = r.exchange, on = document.getElementById(`cxon-${e}`); + if (!on) continue; + on.checked = r.on; + // too little money for a trade of «Сумма»: red, out of the search until it is topped up (then back by itself) + const tr = document.getElementById(`cxrow-${e}`); + tr.style.background = r.low_funds ? "rgba(239, 68, 68, 0.16)" : ""; + tr.style.boxShadow = r.low_funds ? "inset 3px 0 0 #ef4444" : ""; + document.getElementById(`cxk-${e}`).innerHTML = (r.low_funds + ? `${r.low_funds} — не участвует в поиске, вернётся сама после пополнения
` : "") + + (!r.keys ? "нет API-ключей" + : r.error ? `ошибка чтения` + : r.age != null ? `${r.age.toFixed(0)} с назад` : ""); + document.getElementById(`cxs-${e}`).innerHTML = r.unified ? `${money(r.spot)} единый счёт` : money(r.spot); + document.getElementById(`cxf-${e}`).textContent = r.unified ? "—" : money(r.futures); + document.getElementById(`cxc-${e}`).textContent = r.coins ? money(r.coins) : r.keys ? "0.00" : "—"; + document.getElementById(`cxt-${e}`).innerHTML = `${money(r.total)}`; + document.getElementById(`cxd-${e}`).innerHTML = chg(r.change_pct, r.start != null && r.total != null ? r.total - r.start : null); + const oc = document.getElementById(`cxo-${e}`); + oc.textContent = r.open_count; oc.className = r.open_count >= r.limit ? "neg" : ""; + const li = document.querySelector(`#cxBal input[data-cxlimit="${e}"]`); + if (document.activeElement !== li && !li.dataset.dirty) li.value = r.limit; + for (const leg of ["spot", "fut", "fut_innovation"]) { + const el = document.querySelector(`#cxBal input[data-cxfee="${e}|${leg}"]`); + if (!el) continue; + if (document.activeElement !== el && !el.dataset.dirty) el.value = r[`fee_${leg}`]; + document.getElementById(`cxsrc-${e}-${leg}`).textContent = r[`fee_${leg}_src`] || "базовая"; + } + } + document.getElementById("cxBalTotal").innerHTML = `Всего на всех биржах с ключами` + + (b.start_time ? ` · отсчёт с запуска ${mskFull(b.start_time)} МСК${b.start_total != null ? ` (было ${money(b.start_total)} $)` : " — жду первые балансы после запуска"}` + : ' · изменение считается с момента запуска реальной торговли (кнопка «Старт»)') + + `${money(b.total)}${chg(b.change_pct, b.change_usd)}`; +} +async function crossToggle(ex, on) { + if (!basisReady()) return; + const r = await api(`/api/basis/${bxVenue}/settings`, {[`use_${ex.toLowerCase()}`]: on}); + document.getElementById("cxBalMsg").textContent = r.ok ? `${ex}: ${on ? "включена в поиск и торговлю" : "выключена из поиска и торговли"}` : r.error; + loadBasis(); +} +async function crossFeesSave() { + if (!basisReady()) return; + const venue = bxVenue, epoch = bxEpoch; + const fees = {}, limits = {}; + document.querySelectorAll("#cxBal input[data-cxfee]").forEach(el => { + const [e, leg] = el.dataset.cxfee.split("|"); (fees[e] = fees[e] || {})[leg] = el.value; }); + document.querySelectorAll("#cxBal input[data-cxlimit]").forEach(el => limits[el.dataset.cxlimit] = el.value); + const r = await api(`/api/basis/${venue}/settings`, {fees, limits}); + if (venue !== bxVenue || epoch !== bxEpoch) return; + document.getElementById("cxBalMsg").textContent = r.ok ? "комиссии и лимиты сделок сохранены" : r.error; + if (r.ok) { + document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => delete el.dataset.dirty); + rememberBasisDraft(); + } + loadBasis(); +} +const CX_ROWS_HEAD = `МонетаТипПокупка наПродажа / шорт на + Покупка (ask)Продажа (bid)Разница для входа + Обычная + Выше обычной + Чистая прибыль, % + Наблюдаем, минFunding (шорт)Объём по ценам, $ + Мин. вход, $ + Оборот 24ч`; +const CX_POS_HEAD = `Время (МСК)МонетаТип · биржиМонетКуплено (A)Продано / шорт (B) + Разница при входеОбычная (цель)Разница сейчас + До ликвидации, % + Funding $Комиссии $Если закрыть сейчас`; +let bxHeads = null; +let bxVenue = ["cross", "cross_real"].includes(localStorage.getItem("bx.venue")) ? localStorage.getItem("bx.venue") : "cross", bx = null, bxBuilt = false, bxDirty = false; +const basisDrafts = new Map(); +function rememberBasisDraft() { + if (!bxBuilt) return; + const fields = {}; + document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => { + if (!el.dataset.bx && !el.dataset.dirty) return; + if (el.dataset.bx && !bxDirty) return; + const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`; + fields[key] = el.type === "checkbox" ? el.checked : el.value; + }); + if (Object.keys(fields).length) basisDrafts.set(bxVenue, fields); else basisDrafts.delete(bxVenue); +} +function restoreBasisDraft() { + const draft = basisDrafts.get(bxVenue); + if (!draft) return; + document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => { + const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`; + if (!(key in draft)) return; + if (el.type === "checkbox") el.checked = draft[key]; else el.value = draft[key]; + if (el.dataset.bx) bxDirty = true; else el.dataset.dirty = "1"; + }); + document.getElementById("bxMsg").textContent = "Восстановлены несохранённые изменения этого режима"; +} +let bxSort = localStorage.getItem("bx.sort") || "entry_gap"; +const BX_FIELDS = [ + ["amount", "Сумма сделки, $"], ["min_gap_pct", "Мин. расхождение для входа, %"], ["max_gap_pct", "Макс. расхождение, %"], + ["exit_gap_pct", "Закрыть при разнице ≤, %"], ["stop_gap_pct", "Стоп: разница ≥, % (0 — нет)"], + ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["max_positions", "Макс. позиций"], ["cooldown_s", "Пауза по монете, с"], + ["min_turnover", "Мин. оборот 24ч, $"], ["min_depth", "Мин. объём по ценам, $"], ["new_days", "Новые: фьючерсу ≤ дней"], + ["limit_hold_s", "Лимитный вход: ждать, с"], ["max_real_positions", "Одновременно реальных позиций"], + ["spot_fee", "Комиссия спот, %"], ["fut_fee", "Комиссия фьюч, %"], + ["fut_fee_innovation", "Комиссия фьюч зоны инноваций, %", "bybit"]]; +const BX_CHECKS = [["use_new", "Новые монеты"], ["use_innovation", "Зона инноваций / метка «новая» биржи"], ["use_memes", "Мемкойны"], + ["all_coins", "Все монеты со спотом и фьючем"], + ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами (реальный режим)"], + ["entry_limit", "Вход лимитным шортом по цене сигнала, потом спот (реальный режим)"], + ["block_negative_funding", "Не открывать сделку при отрицательном funding"]]; +function bxTabs() { + document.getElementById("bxTabs").innerHTML = BX_VENUES.map(([k, n]) => BX_READY.has(k) + ? `` + : ``).join(" "); +} +function bxSelect(k) { + rememberBasisDraft(); + invalidateRead(`/api/basis?ex=${k}`); pendingPolls.delete(loadBasis); + bxEpoch++; bx = null; bxDataVenue = null; bxDirty = false; + setBasisReady(false); + document.getElementById("bxPos").innerHTML = ""; + document.getElementById("bxMsg").textContent = "Загрузка выбранного режима…"; + bxVenue = k; localStorage.setItem("bx.venue", k); bxBuilt = false; + bxSort = "net_pct"; // the net profit decides the entry — sorted by it + bxTabs(); poll(loadBasis); refreshConnection(); +} +function bxBuild(s) { + const cross = true; // «Арбитраж»: one mode, simulation or real + if (!bxHeads) bxHeads = {rows: document.getElementById("bxRowsHead").innerHTML, pos: document.getElementById("bxPosHead").innerHTML, + title: document.getElementById("bxTitle").textContent, help: document.getElementById("bxHelp").innerHTML}; + document.getElementById("bxRowsHead").innerHTML = cross ? CX_ROWS_HEAD : bxHeads.rows; + document.getElementById("bxPosHead").innerHTML = cross ? CX_POS_HEAD : bxHeads.pos; + document.getElementById("bxTitle").textContent = (bxVenue === "cross_real" ? "Арбитраж · РЕАЛЬНАЯ торговля" : "Арбитраж · симуляция") + + ": купить там, где дешевле, продать там, где дороже, закрыть при возврате разницы к обычной"; + document.getElementById("bxHelp").innerHTML = + "Связки трёх типов (включаются галочками ниже): спот → фьючерс между биржами (покупка на споте A, шорт на фьючерсе B), " + + "спот → фьючерс внутри биржи (обе ноги на одной бирже) и спот → спот (покупка на споте A, продажа тех же монет на " + + "споте B из запаса, который лежит на B; при закрытии — продажа на A и выкуп запаса на B). Для каждой связки программа следит за " + + "обычной разницей (~30 мин). Вход — по «Чистой прибыли, %»: сколько останется, если разница вернётся к обычной, за вычетом запаса " + + "выхода и 4 комиссий (из таблицы бирж). Биржи, их лимиты сделок и комиссии — в карточке «Биржи». Симуляция и реальная торговля — " + + "отдельные вкладки: у каждой свой «Старт», свои настройки и сделки. Деньги между биржами программа не переводит."; + document.getElementById("bxReal").style.display = "none"; // the tab decides paper or real + document.getElementById("bxAdoptBox").style.display = cross ? "none" : ""; + document.getElementById("cxBalCard").style.display = cross ? "" : "none"; + if (cross) cxBalBuild(); + const fieldsList = cross ? CX_FIELDS : BX_FIELDS, checks = cross ? CX_CHECKS : BX_CHECKS; + document.getElementById("bxSettings").innerHTML = + fieldsList.filter(([, , only]) => !only || only === bxVenue) // a field of one exchange only + .map(([k, l]) => `
`).join("") + + checks.map(([k, l]) => ``).join(""); + document.querySelectorAll("#bxSettings input").forEach(el => el.addEventListener("input", () => { + bxDirty = true; document.getElementById("bxMsg").textContent = "есть несохранённые изменения"; })); + document.querySelectorAll("#basisView th[data-b]").forEach(th => th.onclick = () => { + bxSort = th.dataset.b; localStorage.setItem("bx.sort", bxSort); renderBasis(); }); + bxBuilt = true; bxDirty = false; + restoreBasisDraft(); + if (typeof applyHelpHints === "function") applyHelpHints(); +} +async function basisSave() { + if (!basisReady()) return; + const body = {}; + document.querySelectorAll("#bxSettings input").forEach(el => body[el.dataset.bx] = el.type === "checkbox" ? el.checked : el.value); + const venue = bxVenue, epoch = bxEpoch; + const r = await api(`/api/basis/${venue}/settings`, body); + if (venue !== bxVenue || epoch !== bxEpoch) return; + document.getElementById("bxMsg").textContent = r.ok ? "сохранено" : r.error; + if (r.ok) { + bxDirty = false; + rememberBasisDraft(); // Fee/limit drafts belong to their separate Save button. + bxBuilt = false; await loadBasis(); + } +} +async function basisRun() { + if (!basisReady()) return; + if (bxVenue === "cross_real" && !bx.settings.running) { + const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange); + if (!ready.length) { alert("Нет включённых бирж с API-ключами (вкладка «Реальная торговля · API-ключи»)."); return; } + const s = bx.settings, kinds = [s.search_sf && "спот → фьючерс между биржами", s.search_in && "спот → фьючерс внутри биржи", + s.search_ss && "спот → спот (из запаса монет)"].filter(Boolean).join(", "); + if (!confirm(`Запустить РЕАЛЬНУЮ торговлю?\n\nБиржи: ${ready.join(", ")}.\nСвязки: ${kinds || "ни одной не включено"}.\n` + + `Сумма сделки: ${s.amount} $. Настоящие ордера с вашими API-ключами; одна сделка за раз, лимиты сделок по биржам.\n` + + "Изменение баланса считается с этого момента.")) return; + } + const r = await api(`/api/basis/${bxVenue}/settings`, {running: !bx.settings.running}); + document.getElementById("bxMsg").textContent = r.ok ? "" : r.error; + loadBasis(); +} +async function basisClose(uid, venue = bxDataVenue) { + if (!basisReady() || venue !== bxVenue) return; + const r = await api(`/api/basis/${venue}/close${uid ? "/" + uid : ""}`, {}); + if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || ""; + loadBasis(); +} +async function basisAdopt() { + if (!basisReady()) return; + const base = document.getElementById("bxAdopt").value.trim(); + if (!base) return; + const r = await api(`/api/basis/${bxVenue}/adopt`, {base, price: document.getElementById("bxAdoptPrice").value.trim()}); + document.getElementById("bxAdoptMsg").innerHTML = `${r.message || r.error}`; + loadBasis(); +} +async function basisReset() { + if (!basisReady()) return; + if (!confirm("Сбросить статистику этого режима? История закрытых сделок будет очищена. Общий виртуальный счёт не меняется; при открытых позициях сброс недоступен.")) return; + const venue = bxVenue, r = await api(`/api/basis/${venue}/reset`, {}); + if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || (r.ok ? "Статистика сброшена" : "Сброс отклонён"); + await loadBasis(); +} +function basisReady() { return !!bx && bxDataVenue === bxVenue; } +function setBasisReady(ready) { + document.querySelectorAll("#basisView button, #basisView input").forEach(el => { + if (!el.closest("#bxTabs")) setControlDisabled(el, !ready); + }); +} +async function loadBasis() { + if (tab !== "basis") return; + bxTabs(); + const venue = bxVenue, epoch = bxEpoch, request = ++bxRequest; + const r = await api(`/api/basis?ex=${venue}`); + if (venue !== bxVenue || epoch !== bxEpoch || request < bxApplied) return; + bxApplied = request; + if (r.error) { document.getElementById("bxStatus").textContent = r.error; return; } + bx = r; bxDataVenue = venue; + renderAccount(r.paper_account); + if (!bxBuilt) bxBuild(bx.settings); + renderBasis(); + setBasisReady(true); + refreshConnection(); +} +const dollars = v => v == null ? "—" : (v >= 0 ? "+" : "−") + Math.abs(v).toFixed(2); +const hold = s => s < 60 ? `${s.toFixed(0)} с` : s < 3600 ? `${(s / 60).toFixed(1)} мин` : `${(s / 3600).toFixed(1)} ч`; +const kusd = v => v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(0) + "K" : v.toFixed(0); +// how fresh the prices of an open position are (the fast watch looks several times a second) +const freshness = p => p.price_age == null ? '
жду быстрые цены…
' + : `
цены ${(p.price_age * 1000).toFixed(0)} мс назад · опрос ${p.fast_ms} мс
`; +// the smallest amount both legs accept; red when «Сумма сделки» is below it (then not traded, paper or real) +function minEntryCell(r, s) { + if (r.min_entry == null) return '?'; + const parts = [r.min_spot != null ? `спот ≥ ${r.min_spot.toFixed(2)} $` : "", r.min_fut != null ? `фьюч ≥ ${r.min_fut.toFixed(2)} $` : ""] + .filter(Boolean).join(", "); + return `${r.min_entry.toFixed(2)}`; +} +function renderCross() { + const s = bx.settings; + const bad = Object.entries(bx.ex_status || {}).map(([k, v]) => `${k}: ${v}`).join("; "); + document.getElementById("bxStatus").textContent = (bx.status === "ok" + ? `связок «спот на A → шорт на B»: ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (цикл ${(bx.cycle_ms / 1000).toFixed(1)} с)` + : bx.status) + ` · ${s.running ? `новые ${s.real ? "РЕАЛЬНЫЕ" : "бумажные"} сделки открываются` : "остановлено — новые сделки не открываются"}` + + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : "") + (bad ? ` · ${bad}` : ""); + cxBalRender(); + document.getElementById("bxPos").innerHTML = bx.positions.map(p => ` + ${mskFull(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.error ? `
${p.error}` : ""}${p.base} спот · фьюч + ${p.spot_ex} → ${p.fut_ex}
${p.kind_name}
${p.qty.toPrecision(5)} + ${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)}` : ""} + ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)}` : ""} + ${pct(p.entry_gap)}${p.exit_level != null && p.exit_level > p.usual + ? `${pct(p.exit_level)} (+${s.exit_over_usual_pct})
сместилась: при входе ${pct(p.usual)}
` + : `${pct(p.usual)} (+${s.exit_over_usual_pct})${p.usual_now != null ? `
сейчас обычная ${pct(p.usual_now)}
` : ""}`} + ${pct(p.gap_now)}${freshness(p)}${p.exit_held != null + ? `
у обычной ${p.exit_held.toFixed(1)} из ${s.exit_hold_s} с — закрытие, если удержится
` : ""} + ${p.liq_pct == null ? "—" + : `${p.liq_pct.toFixed(1)}%
${price(p.liq_price)} · ${p.liq_src}${ + p.liq_src === "биржа" && p.liq_calc ? ` (расчёт ${price(p.liq_calc)})` : ""}
`} + ${dollars(p.funding)}${(p.fees_total ?? p.fees).toFixed(3)} + ${dollars(p.net)} + `).join("") + || 'Нет открытых позиций'; + const key = bxSort, val = r => r[key]; + const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9)); + document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key)); + document.getElementById("bxCount").textContent = `Связки: лучшие для ${rows.length} монет (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`; + const open = new Set(bx.positions.map(p => p.base)); + document.getElementById("bxRows").innerHTML = rows.map(r => ` + ${r.base}${r.kind_name}${r.spot_ex} + ${r.fut_ex}${r.innovation ? ' иннов.' : ""} + ${price(r.spot_ask)} + ${price(r.fut_bid)} + ${pct(r.entry_gap)}${r.usual == null ? "—" : pct(r.usual)} + ${r.excess == null ? "—" : pct(r.excess)} + ${r.net_pct == null ? "—" : pct(r.net_pct)}${r.hot + ? `
⚡ ${r.price_age == null ? "" : (r.price_age < 1 ? (r.price_age * 1000).toFixed(0) + " мс" : r.price_age.toFixed(1) + " с")}
` : ""} + ${r.history.toFixed(0)} + ${pct(r.funding_pct, 4)} / ${r.interval_h} ч + ${r.depth == null ? '?' : kusd(r.depth)} + ${minEntryCell(r, s)}${kusd(r.turnover)} + ${open.has(r.base) ? 'в позиции' + : r.fits && !r.why ? 'подходит' + : r.fits ? `подходит — но ${r.why}` : `${r.why}`}`).join("") + || 'Нет связок под фильтры'; + document.getElementById("bxTrades").innerHTML = bx.trades.map(t => ` + ${mskFull(t.closed)}${t.base} ${t.spot_ex} → ${t.fut_ex} · ${({sf: "спот → фьюч", in: "внутри биржи", ss: "спот → спот"})[t.kind] || ""}${hold(t.closed - t.opened)} + ${pct(t.entry_gap)} → ${pct(t.exit_gap)} (обычная ${pct(t.usual)})${dollars(t.spot_pnl)} + ${dollars(t.fut_pnl)}${t.fees.toFixed(3)}${dollars(t.funding)} + ${dollars(t.net)}${t.amount ? pct(t.net / t.amount * 100, 2) : "—"} + ${t.reason}`).join("") || 'Сделок пока нет'; +} +function renderBasis() { + const s = bx.settings, st = bx.stats; + const run = document.getElementById("bxRun"); + run.textContent = s.running ? "■ Стоп" : "▶ Старт"; run.className = s.running ? "stop" : "start"; + const rb = document.getElementById("bxReal"); + rb.textContent = s.real ? "● РЕАЛЬНАЯ торговля — выключить" : "Бумажная торговля (включить реальную)"; + rb.className = s.real ? "realon" : ""; + document.getElementById("bxStatus").textContent = (bx.status === "ok" + ? `${bx.venue}: монет со спотом и фьючем ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (${bx.cycle_ms} мс)` + : bx.status) + ` · мемкойны: ${bx.memes_source} · ${s.running ? "новые сделки открываются" : "остановлено — новые сделки не открываются"}` + + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : ""); + const wr = st.trades ? `${(st.wins / st.trades * 100).toFixed(0)}% · ${st.wins} из ${st.trades}` : "—"; + const ex = st.real ? " (биржа)" : ""; + const tiles = [ + ["Итог закрытых, $" + ex, dollars(st.net), cls(st.net)], ["Итог, % от вложенного" + ex, st.net_pct == null ? "—" : pct(st.net_pct, 3), cls(st.net_pct || 0)], + ["Открыто", st.open, ""], ["Если закрыть открытые, $", dollars(st.unrealized), cls(st.unrealized)], + ["Сделок" + ex, st.trades, ""], ["Винрейт", wr, ""], ["Комиссии, $" + ex, st.fees.toFixed(4), "neg"], + ["Funding, $ (оценка)", dollars(st.funding), cls(st.funding)], ["Среднее удержание", st.avg_hold_min == null ? "—" : hold(st.avg_hold_min * 60), ""]]; + if (st.real && bx.mode === "cross") { + const b = bx.balances || {}; + tiles.unshift(["Баланс всех бирж, $", b.total == null ? "—" : b.total.toFixed(2), ""], + ["С запуска", b.change_pct == null ? 'жду балансы' + : `${pct(b.change_pct, 2)} (${dollars(b.change_usd)} $)`, cls(b.change_pct || 0)]); + if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные', "neg"]); + } else if (st.real) { + const bal = real && real.balances && real.balances[bxVenue]; + tiles.unshift(["Баланс на бирже", !bal ? "нет ключей" : bal.error ? `${bal.error}` + : Object.entries(bal.values).map(([k, v]) => `
${k}: ${typeof v === "number" ? v.toFixed(2) : v}
`).join(""), ""]); + if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные', "neg"]); + } + document.getElementById("bxStats").innerHTML = tiles + .map(([k, v, c]) => `
${k}
${v}
`).join(""); + if (bx.mode === "cross") { renderCross(); return; } + document.getElementById("bxPos").innerHTML = bx.positions.map(p => ` + ${mskFull(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.tp_order ? `
TP на бирже: ${price(p.tp_price)}` : ""}${p.error ? `
${p.error}` : ""}${p.base} спот · фьюч + ${p.qty.toPrecision(5)}${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)}` : ""} + ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)}` : ""} + ${pct(p.entry_gap)}${pct(p.gap_now)}${freshness(p)} + ${dollars(p.funding)}${(p.fees_total ?? p.fees).toFixed(3)} + ${dollars(p.net)} + `).join("") + || 'Нет открытых позиций'; + const key = bxSort, val = r => key === "depth" ? r.depth + : key === "turnover" ? Math.min(r.spot_turnover, r.fut_turnover) : r[key]; + const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9)); + document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key)); + document.getElementById("bxCount").textContent = `Монеты: ${rows.length} (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`; + const open = new Set(bx.positions.map(p => p.base)); + document.getElementById("bxRows").innerHTML = rows.map(r => { + const groups = [r.age_days != null && r.age_days <= s.new_days ? "новая" : "", r.innovation ? "инновации" : "", r.meme ? "мем" : ""].filter(Boolean).join(", "); + return ` + ${r.base}${r.mult > 1 ? ` фьюч ×${r.mult}` : ""} + ${price(r.spot_ask)} + ${price(r.fut_bid)} + ${pct(r.entry_gap)}${pct(r.exit_gap)} + ${pct(r.net_if_closed_pct)} + ${pct(r.funding_pct, 4)} / ${r.interval_h} ч + ${r.depth == null ? '?' : kusd(r.depth)} + ${minEntryCell(r, s)}${kusd(Math.min(r.spot_turnover, r.fut_turnover))} + ${r.age_days == null ? "—" : r.age_days.toFixed(0)}${groups} + ${open.has(r.base) ? 'в позиции' + : r.real_block ? `реально нельзя: ${r.real_block}` + : r.fits && !r.why ? 'подходит' + : r.fits ? `подходит — но ${r.why}` + : `${r.why || ""}`}`; + }).join("") || 'Нет монет под фильтры'; + document.getElementById("bxTrades").innerHTML = bx.trades.map(t => ` + ${mskFull(t.closed)}${t.base}${hold(t.closed - t.opened)} + ${pct(t.entry_gap)} → ${pct(t.exit_gap)}${dollars(t.spot_pnl)} + ${dollars(t.fut_pnl)}${t.fees.toFixed(3)}${dollars(t.funding)} + ${dollars(t.net)}${t.amount ? pct(t.net / t.amount * 100, 2) : "—"} + ${t.reason}`).join("") || 'Сделок пока нет'; +} +function setMarket(m) { + arbMarket = m; localStorage.setItem("arb.market", m); arb = null; feesFor = null; arbOpen.clear(); + document.getElementById("arbRows").innerHTML = 'загружаю цены…'; + loadArb(); +} +// spot always means moving the coin; futures only when asked +function transferOn() { return isSpot() || document.getElementById("afTransfer").checked; } +function fee(ex) { + const el = document.querySelector(`#afFees input[data-fee="${ex}"]`); + const v = el ? parseFloat(el.value) : NaN; + return isNaN(v) ? (arb?.taker?.[ex] ?? 0.1) : v; +} +function buildFees() { + const saved = JSON.parse(localStorage.getItem("arb.fees." + arbMarket) || "{}"); + document.getElementById("afFees").innerHTML = `Комиссия по рынку (${isSpot() ? "спот" : "фьючерсы"}), %:` + + Object.keys(arb.taker).map(e => `
`).join("") + + 'базовый уровень без скидок — поправьте под свой'; + document.querySelectorAll("#afFees input").forEach(el => el.addEventListener("input", () => { + const f = {}; document.querySelectorAll("#afFees input").forEach(i => f[i.dataset.fee] = i.value); + localStorage.setItem("arb.fees." + arbMarket, JSON.stringify(f)); renderArb(); })); + feesFor = arbMarket; +} +// filters, transfer time, amount… are remembered in this browser, so they survive reloads and restarts +const ARB_FIELDS = ["afCoin", "afVol", "afDepth", "afGross", "afNet", "afSuspect", "afTransfer", "afClosed", + "afTMin", "afAmount", "afTFee"]; +(function restoreArbSettings() { + let saved = {}; + try { saved = JSON.parse(localStorage.getItem("arb.settings") || "{}"); } catch (e) {} + for (const id of ARB_FIELDS) { + const el = document.getElementById(id); + if (!el || !(id in saved)) continue; + if (el.type === "checkbox") el.checked = !!saved[id]; else el.value = saved[id]; + } + const save = () => { + const out = {}; + for (const id of ARB_FIELDS) { const el = document.getElementById(id); if (el) out[id] = el.type === "checkbox" ? el.checked : el.value; } + try { localStorage.setItem("arb.settings", JSON.stringify(out)); } catch (e) {} + }; + ARB_FIELDS.forEach(id => { const el = document.getElementById(id); if (el) { el.addEventListener("input", save); el.addEventListener("change", save); } }); +})(); +async function arbRun() { + await api(`/api/arb/${arbMarket}/${arb && arb.paused ? "start" : "stop"}`, {}); + loadArb(); +} +async function loadArb() { + if (tab !== "arb") return; + const tmin = val("afTMin", 15); + arb = await api(`/api/arb?market=${arbMarket}` + (transferOn() ? `&transfer=${tmin}` : "")); + document.getElementById("mkSpot").classList.toggle("on", isSpot()); + document.getElementById("mkFut").classList.toggle("on", !isSpot()); + document.getElementById("afTransferBox").style.display = isSpot() ? "none" : ""; + document.getElementById("afClosedBox").style.display = isSpot() ? "" : "none"; + if (!arbExBuilt && arb.taker) { + const saved = JSON.parse(localStorage.getItem("arb.ex") || "null"); + document.getElementById("afEx").innerHTML = 'Биржи:' + Object.keys(arb.taker).map(e => + ``).join(""); + document.querySelectorAll("#afEx input, #arbView .controls input").forEach(el => el.addEventListener("input", renderArb)); + ["afTransfer", "afTMin"].forEach(id => document.getElementById(id).addEventListener("change", loadArb)); + document.querySelectorAll("#arbView th[data-s]").forEach(th => th.addEventListener("click", () => { + arbSort = th.dataset.s; localStorage.setItem("arb.sort", arbSort); renderArb(); })); + arbExBuilt = true; + } + if (arb.taker && feesFor !== arbMarket) buildFees(); + const run = document.getElementById("arbRun"); + run.textContent = arb.paused ? "▶ Старт сканирования" : "■ Стоп сканирования"; + run.className = arb.paused ? "start" : "stop"; + const unit = isSpot() ? "пар USDT" : "фьюч."; + const st = Object.entries(arb.status || {}).map(([e, s]) => `${e}: ${s === "ok" ? arb.counts[e] + " " + unit : s}`).join(" · "); + document.getElementById("arbStatus").textContent = (arb.paused ? "Сканирование остановлено — цены ниже последние полученные. " : "") + (arb.updated + ? `${st} · обновлено ${msk(arb.updated)} МСК (цикл ${(arb.cycle_ms / 1000).toFixed(1)} с, каждые ${arb.cycle_s} с)` : arb.paused ? "данных ещё нет" : "загружаю цены со всех бирж…"); + document.getElementById("arbTitle").textContent = `Арбитраж ${isSpot() ? "на споте" : "на фьючерсах"}: Bybit · MEXC · HTX · Gate`; + document.getElementById("arbFees").textContent = isSpot() + ? "спот: купить на одной бирже → вывести монету → продать на другой" : "фьючерсы: лонг на одной + шорт на другой, закрыть при схождении"; + renderArb(); +} +// What is left of the trade amount at current prices after every fee and the transfer, in $ (same sums as the plan). +function arbProfit(amount, buyPrice, sellPrice, feeA, feeB, transferFee) { + const coins = amount / buyPrice; + if (isSpot()) { + // buy fee comes out of the coins bought, the withdrawal fee too; the sell fee out of the USDT received + const arrive = Math.max(0, coins * (1 - feeA / 100) - transferFee / buyPrice); + return arrive * sellPrice * (1 - feeB / 100) - amount; + } + const fees = 2 * amount * feeA / 100 + amount * feeB / 100 + coins * sellPrice * feeB / 100 + transferFee; + return coins * (sellPrice - buyPrice) - fees; +} +function arbPairs() { + const ex = [...document.querySelectorAll("#afEx input:checked")].map(i => i.dataset.ex); + localStorage.setItem("arb.ex", JSON.stringify(ex)); + const amount = val("afAmount", 1000), tmin = val("afTMin", 15), userFee = val("afTFee", 1); + const out = []; + for (const r of arb.rows || []) { + const ps = Object.entries(r.prices).filter(([e]) => ex.includes(e)); + if (ps.length < 2) continue; + let best = null; + for (const [a, pa] of ps) for (const [b, pb] of ps) { + if (a === b) continue; + const gross = (pb.bid / pa.ask - 1) * 100; + if (!best || gross > best.gross) best = {gross, a, b, pa, pb}; + } + const fa_ = fee(best.a), fb_ = fee(best.b); + const cost = isSpot() ? fa_ + fb_ : 2 * (fa_ + fb_); // spot: two trades; futures: open + close + const same = best.a === r.buy && best.b === r.sell; + const usual = same ? r.usual : null; + const fa = best.pa.funding_8h, fb = best.pb.funding_8h; + const t = same ? r.transfer : null; + // transfer fee: the exchange's own withdrawal fee where it is public (HTX), otherwise the field value + const tfee = t && t.fee_usd != null ? t.fee_usd : userFee; + const feePct = transferOn() ? tfee / amount * 100 : 0; + const low = same ? r.window_low : null, enough = same && r.history_min != null && r.history_min >= tmin; + const closed = !!t && (t.withdraw === false || t.deposit === false); + const profit = arbProfit(amount, best.pa.ask, best.pb.bid, fa_, fb_, transferOn() ? tfee : 0); + out.push({profit_usd: profit, profit_pct: profit / amount * 100,...r, buy: best.a, sell: best.b, buy_price: best.pa.ask, sell_price: best.pb.bid, + buy_url: best.pa.url, sell_url: best.pb.url, gross: best.gross, round_cost: cost, net_now: best.gross - cost, + usual, expected: usual == null ? null : best.gross - Math.max(usual, 0) - cost, + funding_buy: fa, funding_sell: fb, carry_8h: fa == null || fb == null ? null : fb - fa, + depth_usd: same ? r.depth_usd : null, suspect: best.gross > 10 || (same && r.suspect), pa: best.pa, pb: best.pb, + fee_a: fa_, fee_b: fb_, held_min: same ? r.held_min : null, window_low: low, history_ok: enough, + history_have: same ? r.history_min : null, fee_pct: feePct, tfee, tfee_known: !!(t && t.fee_usd != null), + transfer: t, closed, + net_transfer: low == null || !enough ? null : low - cost - feePct}); + } + return out; +} +const usd = v => v == null ? "—" : v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(1) + "K" : v.toFixed(0); +const pct = (v, d = 3) => v == null ? "—" : (v >= 0 ? "+" : "") + v.toFixed(d) + "%"; +const yesno = (v, yes, no) => v === true ? `${yes}` : v === false ? `${no}` : 'неизвестно'; +function transferCell(r) { + const t = r.transfer; + if (!t) return '—'; + const nets = t.networks.length ? t.networks.slice(0, 4).join(", ") : 'сеть не известна'; + return `вывод ${r.buy}: ${yesno(t.withdraw, "открыт", "закрыт")}
ввод ${r.sell}: ${yesno(t.deposit, "открыт", "закрыт")}
` + + `сети: ${nets}${t.fee_usd != null ? `
комиссия вывода ≈ ${t.fee_usd.toFixed(2)} $ (${t.fee_net})` : ""}`; +} +// Step-by-step plan for one row, in dollars for the trade amount, every fee included. +function arbPlan(r) { + const amount = val("afAmount", 1000), tr = transferOn(), tmin = val("afTMin", 15); + const money = v => (v >= 0 ? "" : "−") + Math.abs(v).toFixed(2) + " $"; + const coins = amount / r.buy_price; + const steps = []; + const depthWarn = r.depth_usd != null && r.depth_usd < amount + ? `
  • По лучшим ценам доступно только ${r.depth_usd.toFixed(0)} $ из ${amount} $ — остальное исполнится хуже, уменьшите сумму
  • ` : ""; + const spreadUsed = tr && r.window_low != null && r.history_ok ? r.window_low : r.gross; + const holdNote = tr ? (r.history_ok ? ` Разница за последние ${tmin} мин не опускалась ниже ${pct(r.window_low)}.` + : ` Сканер видит связку меньше ${tmin} мин — неизвестно, продержится ли разница весь перевод.`) : ""; + if (isSpot()) { + const feeBuy = amount * r.fee_a / 100; // the fee is usually taken from the coins bought + const coinsNet = coins * (1 - r.fee_a / 100); + const tCoins = r.tfee / r.buy_price; // withdrawal fee in coins + const arrive = Math.max(0, coinsNet - tCoins); + const sellValue = arrive * r.sell_price, feeSell = sellValue * r.fee_b / 100; + const result$ = sellValue - feeSell - amount; + const resultAtLow$ = arrive * r.buy_price * (1 + spreadUsed / 100) * (1 - r.fee_b / 100) - amount; + const t = r.transfer || {}; + const nets = t.networks && t.networks.length ? t.networks.join(", ") : "общую сеть проверить на обеих биржах"; + steps.push(`На ${r.buy} иметь ${amount} USDT на спотовом счёте; на ${r.sell} узнать адрес пополнения ${r.coin} (сеть: ${nets}).` + + (t.withdraw === false || t.deposit === false ? ' Сейчас ввод или вывод закрыт — перевод невозможен.' + : (t.withdraw == null || t.deposit == null ? ' Статус ввода/вывода этой биржи не публикуется — проверьте на сайте.' : ""))); + steps.push(`${r.buy} ${r.pa.symbol}: купить по рынку ≈ ${price(r.buy_price)} на ${amount} $ ≈ ${coins.toPrecision(5)} ${r.coin}. Комиссия ${money(feeBuy)} (${r.fee_a}%) → на счёте ≈ ${coinsNet.toPrecision(5)} ${r.coin}.`); + steps.push(`Вывести ${r.coin} с ${r.buy} на ${r.sell}: комиссия вывода ≈ ${money(r.tfee)}${r.tfee_known ? "" : " (из поля «Комиссия перевода»)"}, дойдёт ≈ ${arrive.toPrecision(5)} ${r.coin}, ждать ≈ ${tmin} мин.${holdNote}`); + steps.push(`${r.sell} ${r.pb.symbol}: продать по рынку ≈ ${price(r.sell_price)} → ≈ ${money(sellValue)}, комиссия ${money(feeSell)} (${r.fee_b}%).`); + steps.push(`Итог по текущим ценам: ${money(sellValue - feeSell)} − ${money(amount)} = ${money(result$)}` + + (tr && r.history_ok ? `; если разница сожмётся до минимума за ${tmin} мин: ${money(resultAtLow$)}` : "") + + `. Все расходы: ${money(feeBuy + r.tfee + feeSell)}, безубыток при разнице ≥ ${((feeBuy + r.tfee + feeSell) / amount * 100).toFixed(3)}%.`); + return `
      ${steps.map(s => `
    1. ${s}
    2. `).join("")}${depthWarn}
    `; + } + const tfee = tr ? r.tfee : 0; + const unitsA = coins / (r.pa.mult || 1), unitsB = coins / (r.pb.mult || 1); + const qty = (u, m) => `${u >= 100 ? u.toFixed(0) : u.toPrecision(4)} ${m > 1 ? `ед. (×${m} монет)` : "монет"}`; + const feeInA = amount * r.fee_a / 100, feeInB = amount * r.fee_b / 100; + const feeOutA = amount * r.fee_a / 100, feeOutB = coins * r.sell_price * r.fee_b / 100; + const fees = feeInA + feeInB + feeOutA + feeOutB + tfee; + const usual = Math.max(r.usual ?? 0, 0), toUsual$ = amount * (r.gross - usual) / 100; + const carry$ = r.carry_8h == null ? null : amount * r.carry_8h / 100; + const result$ = amount * spreadUsed / 100 - fees; + if (tr) steps.push(`Перевести маржу: на ${r.buy} и ${r.sell} должно быть по ${amount} $ (плечо 1). Перевод ≈ ${tmin} мин, плата ${money(tfee)}.${holdNote}`); + else steps.push(`Проверить маржу: на ${r.buy} и на ${r.sell} заранее по ${amount} $ USDT на фьючерсном счёте (плечо 1).`); + steps.push(`${r.buy} ${r.pa.symbol}: открыть LONG по рынку ≈ ${price(r.buy_price)}, ${qty(unitsA, r.pa.mult || 1)} на ${amount} $. Комиссия ${money(feeInA)} (${r.fee_a}%).`); + steps.push(`Сразу же ${r.sell} ${r.pb.symbol}: открыть SHORT по рынку ≈ ${price(r.sell_price)}, ${qty(unitsB, r.pb.mult || 1)}. Комиссия ${money(feeInB)} (${r.fee_b}%).`); + steps.push(`Держать, пока разница не сузится${r.usual != null ? ` до обычной ${pct(usual)}` : " к нулю"}. Funding за 8 ч: ${carry$ == null ? "нет данных" : (carry$ >= 0 ? "получите " : "заплатите ") + money(Math.abs(carry$))} (лонг ${pct(r.funding_buy, 4)}, шорт ${pct(r.funding_sell, 4)}).`); + steps.push(`Закрыть обе позиции одновременно по рынку. Комиссии выхода ≈ ${money(feeOutA + feeOutB)}.`); + steps.push(`Итог при схождении к нулю: ${money(amount * spreadUsed / 100)} разницы − ${money(fees)} комиссий${tfee ? " и перевода" : ""} = ${money(result$)}` + + (r.usual != null ? `; к обычной: ${money(toUsual$ - fees)}` : "") + `. Безубыток при разнице ≥ ${(fees / amount * 100).toFixed(3)}%.`); + return `
      ${steps.map(s => `
    1. ${s}
    2. `).join("")}${depthWarn}
    `; +} +function renderArb() { + if (!arb || !arb.rows) return; + const q = document.getElementById("afCoin").value.trim().toUpperCase(); + const minVol = val("afVol", 0), minDepth = val("afDepth", 0), minGross = val("afGross", 0); + const onlyNet = document.getElementById("afNet").checked, hideSuspect = document.getElementById("afSuspect").checked; + const hideClosed = isSpot() && document.getElementById("afClosed").checked; + const tr = transferOn(), spot = isSpot(); + document.querySelectorAll("#arbView .tcol").forEach(el => el.style.display = tr ? "" : "none"); + document.querySelectorAll("#arbView .futcol").forEach(el => el.style.display = spot ? "none" : ""); + document.querySelectorAll("#arbView .spotcol").forEach(el => el.style.display = spot ? "" : "none"); + let rows = arbPairs().filter(r => (!q || r.coin.includes(q)) && r.volume_usd >= minVol && r.gross >= minGross + && (!minDepth || (r.depth_usd ?? 0) >= minDepth) && (!hideSuspect || !r.suspect) && (!hideClosed || !r.closed) + && (!onlyNet || (tr ? (r.net_transfer ?? r.net_now - r.fee_pct) > 0 : r.net_now > 0))); + const key = arbSort, num = v => v == null ? -Infinity : v; + rows.sort((a, b) => typeof a[key] === "string" ? a[key].localeCompare(b[key]) : num(b[key]) - num(a[key])); + document.querySelectorAll("#arbView th[data-s]").forEach(th => th.classList.toggle("sorted", th.dataset.s === key)); + document.getElementById("arbCount").textContent = `Пары: ${rows.length} (монет на 2+ биржах: ${arb.rows.length})`; + const cols = 14 + (tr ? 2 : 0); + const html = []; + for (const r of rows.slice(0, 300)) { + html.push(` 0 ? "leadrow" : ""}" onclick="toggleArb('${r.coin}')"> + + ${r.coin}${r.suspect ? ' разные монеты?' : ""}${r.closed ? ' перевод закрыт' : ""} + ${r.buy} ${price(r.buy_price)} + ${r.sell} ${price(r.sell_price)} + ${pct(r.gross)}${pct(r.net_now)} (−${r.round_cost.toFixed(2)}) + ${pct(r.profit_pct, 2)}
    ${r.profit_usd >= 0 ? "+" : "−"}${Math.abs(r.profit_usd).toFixed(2)} $ + ${pct(r.usual)}${pct(r.expected)} + ${spot ? `${transferCell(r)}` + : `${pct(r.carry_8h, 4)}`} + ${usd(r.depth_usd)}${usd(r.volume_usd)} + ${r.held_min == null ? '—' : r.held_min < 1 ? "<1 мин" : r.held_min.toFixed(0) + " мин"} + ${tr ? `${r.history_ok ? pct(r.window_low) : `мало истории ${(r.history_have ?? 0).toFixed(0)} из ${val("afTMin", 15)} мин`} + ${pct(r.net_transfer)}` : ""} + ${r.exchanges.length}`); + if (arbOpen.has(r.coin)) { + const cells = Object.entries(r.prices).map(([e, p]) => + `${e} bid ${price(p.bid)} / ask ${price(p.ask)}` + + (spot ? "" : ` · funding/8ч ${pct(p.funding_8h, 4)}`)).join("
    "); + html.push(`
    Что сделать (на сумму сделки, все комиссии): + ${arbPlan(r)}
    Цены на всех биржах:
    ${cells}
    `); + } + } + document.getElementById("arbRows").innerHTML = html.join("") || `Нет пар под фильтры`; +} +function toggleArb(coin) { arbOpen.has(coin) ? arbOpen.delete(coin) : arbOpen.add(coin); renderArb(); } +window.addEventListener("resize", drawChart); +window.addEventListener("unhandledrejection", event => { + commandNotice(event.reason?.userMessage || event.reason?.message || "Не удалось выполнить действие. Проверьте связь и состояние сервера.", true); + event.preventDefault(); +}); +window.addEventListener("beforeunload", event => { + rememberBasisDraft(); + if (settingsDirty || basisDrafts.size) { event.preventDefault(); event.returnValue = ""; } +}); +function startApplication() { + // Register recovery before the first request: a failed initial GET must never stop polling. + setInterval(() => poll(loadState), 2000); + setInterval(() => poll(loadDetail), 1000); + setInterval(() => poll(loadBasis), 500); + setInterval(() => poll(loadReal), 3000); + setInterval(() => poll(loadAccount), 2000); + setInterval(() => { if (selected === SCANNER) poll(loadScanner); }, 5000); + setInterval(refreshConnection, 1000); + poll(async () => { await loadState(true); await refreshCenter(); }); + poll(loadReal); poll(loadAccount); showTab(tab); +} +(async () => { + startApplication(); +})(); diff --git a/LinuxServer/web/help-data.js b/LinuxServer/web/help-data.js new file mode 100644 index 0000000..a87cbc4 --- /dev/null +++ b/LinuxServer/web/help-data.js @@ -0,0 +1,148 @@ +// Local reference content. Keys are checked against the controls in web_context.test.cjs. +const HELP_SETTINGS = { + sim: { + simulation_entry_delay_ms: "Пауза перед виртуальным входом: 600 мс по умолчанию, от 0 до 60000 мс. При исполнении проверяются свежая цена, остановка, занятость позиции, пинг, минимальный лот и виртуальные средства. TP/SL пересчитываются от цены исполнения.", + simulation_exit_delay_ms: "Пауза перед виртуальным закрытием: 600 мс по умолчанию. Исполнение по доступной свежей цене с тейкер-комиссией; при отсутствии цены позиция сохраняется. Это консервативная модель рыночного выхода, а не точная очередь биржевого лимитного TP.", + mode: "Алгоритм виртуальных входов и выходов. Настройки применяются ко всем монетам кнопкой «Применить ко всем монетам». Описание каждого доступного режима — в разделе «Режимы».", + stake: "Маржа одной позиции в долларах. Номинальный объём сделки = ставка × плечо. Для виртуального входа общий счёт резервирует маржу и должен покрывать комиссии.", + leverage: "Множитель номинального объёма относительно ставки: при ставке 10 $ и плече 3 объём равен 30 $. Прибыль, убыток и комиссии считаются от объёма. Допустимо от 1 до 100.", + min_target_pct: "Минимальная цель движения цены для тейк-профита, в процентах. Это процент изменения цены, а не гарантированная доходность счёта. При авто-TP используется вместе с прогнозом.", + stop_loss_pct: "Допустимое движение цены против позиции, в процентах, после которого стратегия запрашивает закрытие. Значение больше 0. Рыночное исполнение может отличаться от порога.", + max_hold_seconds: "Максимальная продолжительность позиции в секундах. По истечении этого времени стратегия закрывает её, даже если цель ещё не достигнута.", + max_positions: "Максимум одновременно открытых виртуальных позиций одной монеты. Целое число от 1. Общий виртуальный счёт дополнительно ограничивает все монеты доступными средствами.", + entry_gap_seconds: "Минимальный интервал между новыми входами одной монеты, в секундах. 0 отключает дополнительную задержку.", + min_confidence: "Минимальный внутренний показатель уверенности сигнала от 0 до 1; 0 отключает фильтр. Это оценка стратегии, а не вероятность прибыли.", + auto_stop_pct: "Порог автоматической остановки новых входов, когда биржа фьючерса начинает опережать выбранную ведущую. Задаётся в процентах показателя лидерства; 0 отключает автостоп.", + auto_tp: "Вычислять цель тейк-профита по прогнозу движения догоняющей цены. Доля догоняния и горизонт прогноза задаются в дополнительных настройках.", + require_leader: "Разрешать вход только когда измерения подтверждают, что выбранная ведущая биржа действительно ведёт. Проверка использует минимальный перевес ведущей.", + cooldown_ms: "Пауза после закрытия сделки этой монеты, в миллисекундах. Не путать с интервалом между входами. 0 означает без дополнительной паузы.", + lead_threshold_pct: "Минимальное отставание фьючерса от движения ведущей для входа в режиме «Ведущая биржа», в процентах.", + lead_window_ms: "Длина окна сравнения движения двух цен в режиме ведущей биржи, в миллисекундах. Не меньше 50 мс. Меньше окно — быстрее реакция и больше влияние шума.", + vector_window_seconds: "За сколько секунд измерять направление и величину движения ведущей в режиме «Вектор».", + vector_min_move_pct: "Минимальное движение ведущей за окно вектора для входа, в процентах. Отсекает слишком слабые движения; 0 убирает этот порог.", + auto_tp_share_pct: "Какую долю прогнозируемого догоняния использовать для автоматической цели. 100% — весь прогноз, 50% — половина. Допустимо больше 0 и до 300%.", + auto_tp_horizon_seconds: "На сколько секунд вперёд рассчитывается прогноз движения для автоматического тейк-профита. Значение больше 0.", + cut_loss_ticks: "Сколько неблагоприятных шагов цены должно пройти для раннего закрытия, когда включено «Сразу закрывать в минусе». Целое число от 1.", + max_data_age_ms: "Максимальный возраст цен для входа, в миллисекундах. Устаревшие котировки блокируют новые сделки; этот фильтр относится к рынку, а индикатор связи сверху — к связи браузера с программой.", + leader_min_edge: "Минимальная разница показателей направленной корреляции в пользу ведущей. Используется фильтром «Входить, только если ведущая правда ведёт».", + basis_window_seconds: "Окно в секундах для расчёта обычного разрыва между ведущей ценой и фьючерсом в режиме «Разрыв цен».", + basis_entry_z: "Насколько далеко разрыв должен уйти от среднего для входа: величина в стандартных отклонениях (σ). Больше порог — реже входы.", + basis_exit_z: "Порог возврата разрыва к обычному уровню, в стандартных отклонениях, при котором режим «Разрыв цен» закрывает позицию.", + basis_min_gap_pct: "Минимальный абсолютный разрыв цен в процентах для входа в режиме «Разрыв цен». Работает вместе с порогом σ.", + auto_tp_learn: "Оценивать долю догоняния на накопленной истории. Полученная оценка влияет на прогноз; прошлые наблюдения не гарантируют будущего движения.", + one_per_tick: "Не открывать повторную позицию на том же шаге цены. Ограничение уменьшает повторные входы по одному ценовому событию.", + cut_loss: "Дополнительно закрывать позицию при небольшом неблагоприятном движении, заданном числом шагов цены. Может приводить к частым закрытиям и расходам на комиссии." + }, + cross: { + block_negative_funding: "Запрещает вход при отрицательном funding в указанное окно перед выплатой.", + negative_funding_before_minutes: "Длительность окна перед выплатой funding в минутах. Применяется при включённом запрете отрицательного funding.", + min_funding_pct: "Нижний порог funding в процентах за период выплаты. Ставка ниже порога блокирует вход независимо от окна.", + simulation_entry_delay_ms: "Пауза перед проверкой и исполнением виртуального входа, по умолчанию 600 мс. После неё стакан проверяется дважды с интервалом подтверждения; исчезнувший сигнал отменяет вход.", + simulation_exit_delay_ms: "Пауза перед виртуальным закрытием, по умолчанию 600 мс. После неё запрашиваются свежие цены; при ошибке позиция остаётся открытой.", + simulation_execution_delay_ms: "Задержка виртуального входа и выхода в миллисекундах. Исполнение использует цены на момент окончания задержки; 0 отключает задержку.", + amount: "Номинальная сумма одной ноги сделки, в долларах. Общий виртуальный счёт должен покрыть обе ноги, резерв и комиссии. Это не размер всего счёта.", + min_net_pct: "Минимальная расчётная чистая прибыль для входа: превышение разницы над обычной минус запас выхода и комиссии обеих ног. Проценты от суммы одной ноги; фактический результат может отличаться.", + max_gap_pct: "Максимально допустимое расхождение цен, в процентах. Слишком большой разрыв может означать разные инструменты под похожим тикером или плохие котировки.", + history_min: "Минимальное время наблюдения связки перед входом, в минутах. Нужно для оценки обычной разницы цен.", + exit_over_usual_pct: "Добавка в процентных пунктах к обычной разнице для целевого выхода. Например, обычная 0,20% и добавка 0,05 дают условие выхода 0,25%.", + exit_hold_s: "Сколько секунд условие выхода должно выполняться непрерывно перед закрытием. 0 означает закрытие сразу при выполнении условия.", + stop_widen_pct: "Закрывать, если разница расширилась относительно входа на указанное число процентных пунктов. 0 отключает этот стоп.", + max_hold_hours: "Максимальное время удержания арбитражной позиции в часах; 0 отключает лимит времени.", + cooldown_s: "Пауза в секундах после закрытия сделки по монете перед следующим входом.", + min_turnover: "Минимальный торговый оборот за 24 часа в долларах для каждой ноги. Это фильтр ликвидности, а не доступный объём по текущей цене.", + limit_hold_s: "Сколько секунд ждать исполнения лимитной первой ноги, когда включён лимитный вход с ожиданием и выключен IOC.", + max_spread_pct: "Максимальная разница bid/ask каждой ноги, в процентах. 0 отключает этот фильтр. Широкий спред увеличивает стоимость входа и выхода.", + confirm_ms: "Пауза в миллисекундах между двумя проверками стакана перед входом. Помогает отсеивать кратковременные или исчезнувшие цены.", + min_liq_pct: "Минимальный запас роста цены до расчётной ликвидации шорта, в процентах, при входе. Чем выше запас, тем больше средств резервируется под фьючерсную ногу.", + liq_close_pct: "Закрывать позицию, когда оставшийся запас до ликвидации меньше указанного процента. 0 отключает дополнительное закрытие.", + search_sf: "Искать связки «покупка спота на бирже A + шорт фьючерса на бирже B». Средства нужны на обеих биржах; монеты между биржами программа не переводит.", + search_in: "Искать связки «покупка спота + шорт фьючерса» внутри одной биржи.", + search_ss: "Искать связки «покупка спота на A + продажа спота на B». Для реальной продажи на B нужен заранее размещённый запас монет; при закрытии запас выкупается обратно.", + auto_transfer: "Разрешать автоматический перевод USDT между спотовым и фьючерсным счетами внутри одной биржи в реальном режиме. Переводов между разными биржами нет.", + entry_ioc: "Первая нога входит лимитным IOC по подтверждённой цене: немедленно исполняется доступный объём, остаток отменяется. Имеет приоритет над лимитным входом с ожиданием.", + entry_limit: "Если IOC выключен, выставлять первую ногу лимитно и ждать не больше «Лимитный вход: ждать». Вторая нога зависит от подтверждённого исполнения первой.", + fees_auto: "Уточнять значения комиссии по данным завершённых реальных сделок. В таблице бирж виден источник комиссии." + }, + basis: { + block_negative_funding: "Запрещает новые входы при отрицательном funding.", + amount: "Номинальная сумма сделки спот-фьючерс в долларах.", + min_gap_pct: "Минимальная разница между фьючерсным bid и спотовым ask для входа, в процентах.", + max_gap_pct: "Максимально допустимая разница для входа, в процентах.", + exit_gap_pct: "Целевая разница фьючерсного ask и спотового bid для закрытия обеих ног, в процентах.", + stop_gap_pct: "Абсолютная разница цен, при достижении которой позиция закрывается по стопу. 0 отключает.", + max_hold_hours: "Максимальное удержание позиции в часах; 0 — без лимита времени.", + max_positions: "Максимальное число одновременно открытых позиций данного движка.", + cooldown_s: "Пауза после закрытия сделки по монете, в секундах.", + min_turnover: "Минимальный оборот за 24 часа каждой ноги, в долларах.", + min_depth: "Минимальная доступная сумма по лучшим ценам стакана, в долларах.", + new_days: "Сколько дней после появления фьючерса инструмент считается новым.", + limit_hold_s: "Сколько секунд ждать исполнения лимитной первой ноги.", + max_real_positions: "Максимальное число одновременных реальных позиций данного движка.", + spot_fee: "Тейкер-комиссия спота за одну операцию, в процентах от её объёма.", + fut_fee: "Тейкер-комиссия фьючерса за одну операцию, в процентах от её объёма.", + fut_fee_innovation: "Отдельная тейкер-комиссия фьючерсов зоны инноваций Bybit, в процентах.", + use_new: "Включать новые фьючерсы в список кандидатов.", + use_innovation: "Включать инструменты зоны инноваций или с меткой новой монеты.", + use_memes: "Включать монеты из списка мемкойнов.", + all_coins: "Рассматривать все монеты, у которых есть подходящий спот и фьючерс.", + auto_transfer: "Разрешать внутренний перевод USDT спот → фьючерсы в реальном режиме.", + entry_limit: "Входить первой ногой лимитно, вторую открывать после подтверждённого исполнения." + } +}; +const HELP_MODES = { + lead: "Сравнивает движение ведущей и фьючерса за выбранное окно. Вход появляется, когда фьючерс отстал достаточно сильно; ставка делается на догоняющее движение. Связанные поля: отставание для входа и окно сравнения.", + vector: "Измеряет направление движения ведущей за окно вектора и ищет вход в ту же сторону. Связанные поля: окно вектора и минимальное движение ведущей.", + basis: "Измеряет отклонение разрыва между ведущей и фьючерсом от его обычного уровня и делает ставку на возврат. Связанные поля: окно разрыва, пороги входа/выхода в σ и минимальный разрыв. Это отдельный режим монеты, а не двухногая вкладка «Арбитраж»." +}; +const HELP_EXTRA = [ + ["Как пользоваться", "workflow", "Симуляция и реальная торговля", "Сначала выберите вкладку и режим. Верхняя строка всегда показывает текущий режим и свежесть связи. В симуляции все монеты и бумажный арбитраж используют один виртуальный счёт. Реальная торговля использует счета бирж. Входы запускаются кнопкой «Старт» отдельно для монеты или режима арбитража; «Стоп» останавливает новые входы, но не является командой закрыть все позиции."], + ["Как пользоваться", "saving", "Применение настроек", "В симуляторе изменения отправляются кнопкой «Применить ко всем монетам». В арбитраже основные настройки и комиссии/лимиты имеют отдельные кнопки сохранения. До сохранения действует прежняя конфигурация. Черновики симуляции и реального арбитража сохраняются отдельно при переключении режима в этой вкладке браузера."], + ["Как пользоваться", "connection", "Нет связи / устарели данные", "Индикатор сверху относится к связи браузера с программой. При ошибке или отсутствии свежих данных больше 10 секунд команды блокируются; чтение автоматически восстанавливается. Отправленные торговые команды автоматически не повторяются: при потере ответа проверьте журнал и позиции. Возраст рыночных котировок показывается отдельно."], + ["Как пользоваться", "block_reason", "Почему нет входа", "Смотрите статус монеты, сообщение о ведущей и последнюю колонку таблицы связок. Причины включают остановленные входы, недостаточную историю, устаревшие котировки, фильтры прибыли/спреда, минимальный ордер, занятые лимиты и нехватку свободных средств общего счёта."], + ["Как пользоваться", "reset", "Сбросить статистику", "Очищает статистику выбранного режима только когда нет открытых позиций. У монеты сброс также блокируется при незавершённых реальных ордерах, восстановлении или ошибке хранения реального состояния. Не пополняет и не обнуляет общий виртуальный счёт. Для изменения виртуальных денег используйте «Пополнить» или «Списать»."], + ["Виртуальный счёт", "balance", "Баланс", "Проведённые пополнения и списания, закрытый торговый результат, комиссии и учтённый funding. Общий для всех виртуальных сделок; бюджет не копируется заново для каждой монеты. Историческая статистика сделок и баланс счёта — разные показатели."], + ["Виртуальный счёт", "equity", "Капитал (Equity)", "Баланс плюс текущий нереализованный результат открытых виртуальных позиций. Это оценка по последним доступным котировкам; при устаревших ценах помечается отдельно."], + ["Виртуальный счёт", "reserved", "Зарезервировано", "Для монеты резервируется маржа при входе (номинал / плечо). Для арбитража спот-фьючерс — стоимость спота и резерв под фьючерс, не меньше 103% номинала фьючерса либо больше для заданного запаса до ликвидации. Для спот-спот консервативно резервируются средства обеих ног. Резерв освобождается после закрытия."], + ["Виртуальный счёт", "free", "Свободно", "max(0, min(баланс, капитал) − резерв). Открытая прибыль не финансирует новые входы, а открытый убыток уменьшает доступные средства. Вход разрешён, только если хватает на резерв и комиссии."], + ["Виртуальный счёт", "accountDelta", "Сумма изменения / Пополнить / Списать", "Введите положительную сумму в долларах (точка или запятая, до 8 знаков после разделителя). «Пополнить» прибавляет её к общему виртуальному счёту; «Списать» вычитает в пределах свободных средств. При отсутствии оценки открытой позиции или её возрасте больше 30 секунд списание и новые входы блокируются. Пополнение при рабочей связи остаётся доступным. Эти операции не меняют торговую прибыль и не переводят реальные деньги."], + ["Виртуальный счёт", "accountJournal", "Журнал и повтор операции", "В журнале видны время, причина, сумма изменения и баланс после операции. Отображаются последние 100 записей, новые сверху. Если ответ о пополнении или списании потерян, повтор той же суммы в текущей открытой странице использует прежний идентификатор и не проводит операцию второй раз. После перезагрузки страницы сначала сверьте журнал: незавершённый запрос в браузере уже не сохранён."], + ["Виртуальный счёт", "migration", "Первый запуск общего счёта", "Начальный депозит переносится один раз из прежнего общего бюджета (по умолчанию 300 $). Начальные балансы отдельных монет не складываются. Старые закрытые сделки остаются в статистике; для перенесённых открытых позиций учитываются резерв и комиссия входа."], + ["Биржи и лимиты", "use_exchange", "Искать и торговать", "Галочка каждой биржи включает её в поиск и новые входы выбранного режима. Выключение не прекращает сопровождение уже открытых позиций. Изменение применяется сразу."], + ["Биржи и лимиты", "limits", "Сделок открыто / макс.", "Открытое число и максимальный лимит по каждой бирже. Сделка учитывается на участвующих биржах; новый вход требует свободного лимита у обеих ног. После редактирования нажмите «Сохранить комиссии и лимиты»."], + ["Биржи и лимиты", "fees.spot", "Комиссия спот, %", "Тейкер-комиссия одной рыночной операции на споте в процентах. Открытие и закрытие считаются отдельно. Значение участвует в расчёте ожидаемого и виртуального результата."], + ["Биржи и лимиты", "fees.fut", "Комиссия фьючерса, %", "Тейкер-комиссия одной операции фьючерсной ноги в процентах. Для Bybit ниже может задаваться отдельная комиссия зоны инноваций (fut_innovation)."], + ["Биржи и лимиты", "fees.fut_innovation", "Зона инноваций Bybit, %", "Отдельная ставка комиссии фьючерсов зоны инноваций. Источник значения отображается под полем; при включённой автокоррекции данные завершённых сделок уточняют ставку."], + ["Биржи и лимиты", "exchange_balance", "Балансы и «С запуска»", "Спот USDT и фьючерсы USDT — свободные денежные счета биржи; монеты в позициях показаны отдельно. Единый счёт не суммируется дважды. «С запуска» сравнивает оценку с запуском реального режима и может включать внешние изменения счёта, а не только результат программы."], + ["Реальная торговля", "api_key", "API key / API secret", "Ключ и секрет для выбранной биржи. «Сохранить» шифрует их на сервере AES-256-GCM; секрет не возвращается в браузер. «Проверить (баланс)» проверяет доступ чтением баланса, «Удалить» удаляет сохранённые ключи. Нужны права торговли; разрешение вывода средств для программы не требуется."], + ["Реальная торговля", "coinReal", "Включить реальную торговлю монеты", "Включается отдельно у каждой монеты после подтверждения. Перед переключением нужно завершить её текущие виртуальные и реальные позиции, включая сохранённые позиции выбранного режима; незавершённые ордера, восстановление и ошибки сохранения блокируют переход. Новые позиции повторяются реальными рыночными ордерами: номинал = ставка × плечо. Реальная позиция одна за раз, следующая — после подтверждённого закрытия предыдущей. Общий виртуальный счёт и его пополнения не меняют реальные средства, размер ордеров или разрешение реальных входов. Сохранение ключей само по себе торговлю не запускает."], + ["Реальная торговля", "simRealTpsl", "TP/SL на бирже", "Отправлять защитные ордера на поддерживаемые биржи (Bybit, MEXC). SL сопровождает вход, TP выставляется как reduce-only от фактической цены исполнения. Проверяйте подтверждение ордеров в журнале: сама включённая галочка не означает, что биржа приняла защиту."], + ["Реальная торговля", "simRealTransfer", "Автоперевод USDT спот → фьючерсы", "При нехватке фьючерсного баланса разрешать перевод со спотового счёта той же биржи. Меняет реальные счета внутри биржи; включается отдельно от арбитражной настройки автоперевода."], + ["Реальная торговля", "simRealSl", "Стоп-лосс на бирже, %", "Расстояние биржевого стоп-лосса от входа в процентах цены. Это отдельная защита реального ордера, отличная от общего стоп-лосса стратегии. Сохраняется после изменения поля."], + ["Реальная торговля", "simRealPing", "Макс. пинг до биржи, мс", "Блокировать новые виртуальные и реальные входы монеты, если измеренная задержка биржи выше порога. 0 отключает проверку. Это задержка до биржи, а не возраст котировки или связь браузера."], + ["Реальная торговля", "real_start", "Арбитраж → Реальная торговля → Старт", "Отдельный движок со своими настройками, лимитами и сделками. Перед запуском подтверждаются биржи, типы связок и сумма сделки. Работа бумажного арбитража не включает реальный режим."], + ["Сканер", "scMin", "Минут на цикл", "Длительность сбора цен одной группы монет в минутах. Результаты появляются после полного цикла, а не сразу после старта; подготовка может увеличить ожидание."], + ["Сканер", "scCoins", "Монет за цикл", "Размер группы проверяемых монет, до 13. Следующие группы проверяются по кругу."], + ["Сканер", "scAuto", "Добавлять найденные автоматически", "Автоматически переносить найденные подходящие монеты в список наблюдения. Добавление в список и разрешение реальной торговли — отдельные действия."], + ["Сканер", "scanner_add", "Добавить / Добавить для теста", "Переносит монету в левую панель остановленной. «Для теста» означает, что убедительного опережения DEX пока нет. Старт сделок выполняется на странице монеты."], + ["Калькулятор бюджета", "cStake", "Ставка (сумма сделки), $", "Номинал одной ноги спот-фьючерсной сделки. Калькулятор оценивает потребность в средствах; он не меняет ставку стратегии и не пополняет счёт."], + ["Калькулятор бюджета", "cCount", "Сделок одновременно на бирже", "Число позиций, под которые рассчитывается запас на каждой бирже. В калькуляторе используется целая часть введённого числа, минимум 1."], + ["Калькулятор бюджета", "cLiq", "Желаемый рост цены до ликвидации, %", "На какой рост цены против шорта рассчитывается запас. Это приближённая оценка, зависящая от поддерживающей маржи; реальная биржа может применять уровни маржи и дополнительные условия."], + ["Калькулятор бюджета", "cEx", "Бирж с деньгами", "Число бирж, между которыми распределён капитал. Используется целое число от 1 для оценки общей потребности."], + ["Калькулятор бюджета", "cMmr", "Поддерж. маржа, %", "Предполагаемая ставка поддерживающей маржи биржи. При расчёте берётся значение в процентах; его нужно сопоставить с условиями конкретного инструмента."], + ["Калькулятор бюджета", "cFee", "Запас на комиссии спота, %", "Дополнительная доля к стоимости покупки спота в расчёте бюджета. Не меняет таблицу торговых комиссий программы."], + ["Калькулятор бюджета", "calcFromSettings", "Взять из настроек реальной торговли", "Копирует сумму сделки, запас до ликвидации, максимальный лимит сделок и число активных бирж с ключами из реального арбитража только в калькулятор."], + ["Термины", "spot", "Спот", "Покупка или продажа самой монеты. В спот-фьючерсной связке купленная монета образует одну из двух ног."], + ["Термины", "futures", "Фьючерс / бессрочный контракт", "Производный инструмент на цену монеты. Бессрочный контракт не имеет даты погашения и может включать периодические платежи funding."], + ["Термины", "long_short", "LONG / SHORT", "LONG выигрывает от роста цены, SHORT — от снижения. В арбитраже позиции ног рассматриваются вместе: прибыль одной ноги может компенсироваться убытком другой."], + ["Термины", "bid_ask", "Bid / Ask / спред", "Bid — лучшая доступная цена продажи в рынок, ask — покупки. Спред — разница между ними. Покупка и немедленная продажа обычно теряют спред и комиссии."], + ["Термины", "dex_cex", "DEX / CEX / ведущая", "DEX — децентрализованная площадка, CEX — централизованная биржа. «Ведущая» — выбранный источник сигнала; факт опережения проверяется по истории и может измениться."], + ["Термины", "gap", "Разница / обычная / выше обычной", "Разница — наблюдаемое расхождение цен ног. Обычная — исторический базовый уровень связки. Выше обычной — превышение текущей разницы над этим уровнем. Возврат к среднему возможен, но не гарантирован."], + ["Термины", "pnl", "PNL / чистый результат / винрейт", "PNL — прибыль или убыток. Чистый результат учитывает комиссии и указанные в отчёте платежи; открытый PNL ещё не зафиксирован. Винрейт — доля прибыльных закрытых сделок, сам по себе не показывает общую доходность."], + ["Термины", "funding", "Funding", "Периодический платёж между держателями фьючерсных позиций. При положительной ставке шорт обычно получает, при отрицательной платит. Ставка может меняться, а расчётный funding в таблице может быть оценочным."], + ["Термины", "margin_liquidation", "Маржа / ликвидация", "Маржа — средства обеспечения позиции. Ликвидация — принудительное закрытие биржей при недостаточном обеспечении. Спот на другой бирже автоматически не защищает фьючерсную маржу."], + ["Термины", "ioc_reduce_only", "IOC / reduce-only / лимитный ордер", "Лимитный ордер ограничивает цену исполнения. IOC исполняет доступную часть сразу и отменяет остаток. Reduce-only разрешает только уменьшение существующей позиции, чтобы закрывающий ордер не открыл обратную."], + ["Термины", "depth_minorder", "Глубина / оборот / минимальный вход", "Глубина — доступный объём по рассматриваемым ценам, оборот — сумма торгов за период. Минимальный вход определяется требованиями обеих ног к сумме и шагу количества. Это разные ограничения."], + ["Термины", "sigma_corr", "σ / корреляция / уверенность", "σ — стандартное отклонение, мера разброса. Корреляция описывает совместное движение рядов. Уверенность и перевес ведущей — внутренние оценки алгоритма; они не равны вероятности будущей прибыли."], + ["Термины", "scanner_metrics", "Лаг / t+1→t+5 / попадания / t", "Лаг — измеренный сдвиг между движениями цен, в секундах. t+1→t+5 — наблюдаемое движение на указанном горизонте после сигнала; попадания — доля наблюдений нужного направления, t — статистический показатель силы эффекта. Эти метрики относятся к проверенному циклу сканера."], + ["Термины", "chart", "График и время", "Линии показывают изменение каждой цены в процентах от начала выбранного окна, а не абсолютный ценовой разрыв. ▲/▼ обозначают входы, ● — выходы. Переключатели 1/5/10 минут меняют только окно графика. Время на странице — московское (МСК)."] +]; diff --git a/LinuxServer/web/help.js b/LinuxServer/web/help.js new file mode 100644 index 0000000..368293f --- /dev/null +++ b/LinuxServer/web/help.js @@ -0,0 +1,78 @@ +let helpReturnFocus = null; +let helpFieldCounter = 0; +function helpEntries() { + const entries = HELP_EXTRA.map(([group, key, label, text]) => ({group, key, label, text})); + const groups = [ + ["Симулятор — настройки монет", "sim", [...MAIN_FIELDS, ...MORE_FIELDS]], + ["Арбитраж — симуляция и реальная торговля", "cross", [...CX_FIELDS, ...CX_CHECKS]], + ["Движок спот-фьюч — дополнительные параметры", "basis", [...BX_FIELDS, ...BX_CHECKS]] + ]; + for (const [group, scope, fields] of groups) { + for (const [key, label] of fields) entries.push({group, key, label, text: HELP_SETTINGS[scope][key] || "Описание этого нового параметра ещё не добавлено."}); + } + const modes = state?.modes || {lead: "Ведущая биржа", vector: "Вектор", basis: "Разрыв цен"}; + for (const [key, label] of Object.entries(modes)) entries.push({group: "Режимы симулятора", key, label, text: HELP_MODES[key] || "Режим предоставлен сервером. Условия входа, выхода и текущая причина блокировки показываются в карточке выбранной монеты."}); + return entries; +} +function filterHelp(entries, query) { + const normalize = value => String(value).toLocaleLowerCase("ru").replace(/ё/g, "е"); + const words = normalize(query).trim().split(/\s+/).filter(Boolean); + return entries.filter(entry => words.every(word => normalize(`${entry.group} ${entry.key} ${entry.label} ${entry.text}`).includes(word))); +} +function renderHelp() { + const search = document.getElementById("helpSearch"), content = document.getElementById("helpContent"); + if (!search || !content) return; + const entries = filterHelp(helpEntries(), search.value); + const fragment = document.createDocumentFragment(), groups = new Map(); + for (const entry of entries) { + if (!groups.has(entry.group)) { + const section = document.createElement("section"), heading = document.createElement("h3"); + heading.textContent = entry.group; section.append(heading); groups.set(entry.group, section); fragment.append(section); + } + const article = document.createElement("article"), heading = document.createElement("h4"), key = document.createElement("code"), body = document.createElement("p"); + article.className = "help-entry"; heading.textContent = entry.label; key.textContent = entry.key; body.textContent = entry.text; + heading.append(key); article.append(heading, body); groups.get(entry.group).append(article); + } + content.replaceChildren(fragment); + document.getElementById("helpCount").textContent = entries.length ? `Найдено разделов и параметров: ${entries.length}` : "Ничего не найдено. Попробуйте короткое название или ключ настройки."; +} +function helpOpen(query = "") { + const dialog = document.getElementById("helpDialog"); + helpReturnFocus = document.activeElement; + document.getElementById("helpSearch").value = query; + renderHelp(); + if (!dialog.open) dialog.showModal(); + document.getElementById("helpSearch").focus(); +} +function helpClose() { document.getElementById("helpDialog").close(); } +function applyHelpHints() { + document.querySelectorAll("[data-k], [data-bx]").forEach(el => { + const key = el.dataset.k || el.dataset.bx, scope = el.dataset.k ? "sim" : "cross"; + const text = HELP_SETTINGS[scope][key]; + if (text) el.title = text; + if (!el.id) el.id = `setting-${scope}-${key}`; + const label = el.closest(".field")?.querySelector("label"); + if (label) label.htmlFor = el.id; + if (el.tagName === "INPUT" && el.type !== "checkbox") el.inputMode = "decimal"; + }); + document.querySelectorAll("[data-cxfee], [data-cxlimit]").forEach(el => { + el.setAttribute("aria-label", el.dataset.cxfee ? `Комиссия ${el.dataset.cxfee}` : `Лимит сделок ${el.dataset.cxlimit}`); + el.inputMode = "decimal"; + }); + document.querySelectorAll(".field").forEach(field => { + const label = field.querySelector("label"), input = field.querySelector("input, select"); + if (!label || !input) return; + if (!input.id) input.id = `field-auto-${++helpFieldCounter}`; + label.htmlFor = input.id; + }); +} +const helpDialog = document.getElementById("helpDialog"); +if (helpDialog) { + helpDialog.addEventListener("close", () => { if (helpReturnFocus?.isConnected) helpReturnFocus.focus(); }); + // Native handles Escape and keeps keyboard focus inside the modal. + helpDialog.addEventListener("click", event => { + if (event.target !== helpDialog) return; + const bounds = helpDialog.getBoundingClientRect(); + if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) helpClose(); + }); +} diff --git a/LinuxServer/web_proxy.py b/LinuxServer/web_proxy.py new file mode 100644 index 0000000..4b21179 --- /dev/null +++ b/LinuxServer/web_proxy.py @@ -0,0 +1,404 @@ +"""Front of the web simulator: listens on 127.0.0.1:8765 (this PC only — the page can switch real trading and holds +exchange API keys) and forwards every request to the simulator engine on 127.0.0.1:8766. + +Why a separate process: the engine needs the VPN (the exchanges are not reachable without it), while answers to +visitors from outside must leave directly through the home connection. Run this file with pythonw.exe (a different +program than the engine's python.exe) and add pythonw.exe to the VPN's app exclusions; the engine stays in the VPN. + + pyw -3 web_proxy.py (run_web_sim.bat starts both) +""" + +from __future__ import annotations + +import sys +import html +import ipaddress +import json +import os +import shutil +import socket +import subprocess +import threading +import time +from collections import defaultdict, deque +from http.cookies import SimpleCookie +from pathlib import Path +from urllib.parse import parse_qs +from request_security import trusted_request +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from user_auth import AuthError, UserStore + +LISTEN = ("127.0.0.1", 8765) # local only: real trading and API keys are behind this page +ENGINE = "http://127.0.0.1:8766" +ROOT = Path(__file__).resolve().parent +DATA_ROOT = ROOT / "web_sim_data" +STORE = UserStore(DATA_ROOT) +SESSION_COOKIE = "crypto_scam_session" +COOKIE_SECURE = "; Secure" if os.environ.get("CRYPTO_SCAM_PUBLIC_HOST") else "" +HOP_HEADERS = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-authorization", + "proxy-authenticate", "host", "content-length"} + + +class TenantManager: + """One complete engine process and durable data folder per account.""" + + def __init__(self, store: UserStore): + self.store = store + self.lock = threading.RLock() + self.workers: dict[str, tuple[subprocess.Popen | None, int]] = {} + + @staticmethod + def _healthy(port: int, user_id: str) -> bool: + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=0.5) as resp: + return json.loads(resp.read()).get("tenant") == user_id + except Exception: + return False + + @staticmethod + def _port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + def ensure(self, user_id: str) -> str: + with self.lock: + old = self.workers.get(user_id) + if old and (old[0] is None or old[0].poll() is None) and self._healthy(old[1], user_id): + return f"http://127.0.0.1:{old[1]}" + data = self.store.data_dir(user_id) + marker = data / "worker.json" + try: + saved_port = int(json.loads(marker.read_text(encoding="utf-8")).get("port", 0)) + except (OSError, ValueError, TypeError): + saved_port = 0 + if saved_port and self._healthy(saved_port, user_id): + self.workers[user_id] = (None, saved_port) + return f"http://127.0.0.1:{saved_port}" + port = self._port() + env = os.environ.copy() + env["CRYPTO_SCAM_DATA_DIR"] = str(data) + py = Path(sys.executable) + if py.name.lower() == "pythonw.exe" and py.with_name("python.exe").exists(): + py = py.with_name("python.exe") + log_path = data / "backend.log" + data.mkdir(parents=True, exist_ok=True) + with log_path.open("ab") as log: + proc = subprocess.Popen([str(py), "-B", str(ROOT / "web_sim.py"), "--backend", "--port", str(port)], + cwd=ROOT, env=env, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + self.workers[user_id] = (proc, port) + marker.write_text(json.dumps({"pid": proc.pid, "port": port}), encoding="utf-8") + deadline = time.monotonic() + 15 + while proc.poll() is None and time.monotonic() < deadline: + if self._healthy(port, user_id): + return f"http://127.0.0.1:{port}" + time.sleep(0.1) + raise OSError("Личный движок не запустился за 15 секунд; посмотрите backend.log") + + def start_all(self) -> None: + for user_id in self.store.user_ids(): + try: + self.ensure(user_id) + except OSError: + continue + + def stop_all(self) -> None: + with self.lock: + workers = list(self.workers.values()) + self.workers.clear() + for proc, _ in workers: + if proc is not None and proc.poll() is None: + proc.terminate() + + +TENANTS = TenantManager(STORE) +ATTEMPTS: dict[str, deque[float]] = defaultdict(deque) +ATTEMPT_LOCK = threading.Lock() + + +def _login_page(message: str = "") -> bytes: + safe = html.escape(message) + page = f""" +Вход · Crypto Scam

    Crypto Scam

    Войдите в свой аккаунт

    {safe}
    +
    + +
    +
    """ + return page.encode("utf-8") + + +def _cookie(handler) -> str | None: + jar = SimpleCookie() + try: + jar.load(handler.headers.get("Cookie", "")) + except Exception: + return None + morsel = jar.get(SESSION_COOKIE) + return morsel.value if morsel else None + + +class Gateway(BaseHTTPRequestHandler): + """Authenticate every browser session, then route it only to that account's private engine.""" + + def log_message(self, *args) -> None: + pass + + def _send(self, status: int, body: bytes, kind: str = "text/html; charset=utf-8", headers=()) -> None: + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "same-origin") + self.send_header("Content-Length", str(len(body))) + for key, value in headers: + self.send_header(key, value) + self.end_headers() + self.wfile.write(body) + + def _json(self, status: int, data: dict, headers=()) -> None: + self._send(status, json.dumps(data, ensure_ascii=False).encode("utf-8"), + "application/json; charset=utf-8", headers) + + def _user(self) -> str | None: + return STORE.user_for_session(_cookie(self)) + + def _body(self) -> dict: + length = int(self.headers.get("Content-Length") or 0) + if length < 0 or length > 65536: + raise ValueError("Слишком большой запрос") + raw = self.rfile.read(length) + if "application/x-www-form-urlencoded" in self.headers.get("Content-Type", ""): + form = parse_qs(raw.decode("utf-8"), keep_blank_values=True) + return {k: v[-1] for k, v in form.items()} + obj = json.loads(raw or b"{}") + if not isinstance(obj, dict): + raise ValueError("Ожидается объект запроса") + return obj + + def _auth_attempt_allowed(self) -> bool: + key, now = self.client_address[0], time.time() + if self.client_address[0] == "127.0.0.1": + forwarded_ip = self.headers.get("X-Real-IP", "") + try: + key = str(ipaddress.ip_address(forwarded_ip)) + except ValueError: + pass + with ATTEMPT_LOCK: + q = ATTEMPTS[key] + while q and now - q[0] > 600: + q.popleft() + if len(q) >= 8: + return False + q.append(now) + return True + + def _start_session(self, user_id: str) -> None: + try: + TENANTS.ensure(user_id) + except OSError: + self._send(503, _login_page("Не удалось запустить личный движок. Проверьте свободные порты и журнал.")) + return + token = STORE.create_session(user_id) + self.send_response(303) + self.send_header("Location", "/") + self.send_header("Set-Cookie", f"{SESSION_COOKIE}={token}; Path=/; HttpOnly; SameSite=Strict{COOKIE_SECURE}; Max-Age={UserStore.SESSION_SECONDS}") + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", "0") + self.end_headers() + + def do_GET(self) -> None: + if not trusted_request(self): + self._json(403, {"error": "Недоверенный запрос"}) + return + path = self.path.partition("?")[0] + if path == "/health": + self._json(200, {"ok": True, "accounts": len(STORE.user_ids())}) + return + if path == "/system/status": + self._system_status() + return + if path == "/auth/logout": + STORE.delete_session(_cookie(self)) + self.send_response(303) + self.send_header("Location", "/") + self.send_header("Set-Cookie", f"{SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict{COOKIE_SECURE}; Max-Age=0") + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", "0") + self.end_headers() + return + user_id = self._user() + if user_id is None: + self._send(200, _login_page()) + return + self._forward("GET", user_id) + + def do_POST(self) -> None: + if not trusted_request(self): + self._json(403, {"ok": False, "error": "Недоверенный запрос"}) + return + path = self.path.partition("?")[0] + if path in ("/auth/login", "/auth/register"): + if not self._auth_attempt_allowed(): + self._send(429, _login_page("Слишком много попыток. Подождите 10 минут.")) + return + try: + body = self._body() + username, password = str(body.get("username", "")), str(body.get("password", "")) + if path == "/auth/register": + user_id = STORE.register(username, password) + if STORE.mark_legacy_imported(): + _import_legacy_data(STORE.data_dir(user_id)) + else: + user_id = STORE.authenticate(username, password) + if user_id is None: + raise AuthError("Неверный логин или пароль") + except (AuthError, ValueError, UnicodeError) as exc: + self._send(400, _login_page(str(exc))) + return + self._start_session(user_id) + return + if self._user() is None: + self._json(401, {"ok": False, "error": "Сначала войдите в аккаунт"}) + return + if self.headers.get("X-Sim") != "1": + self._json(403, {"ok": False, "error": "Недоверенный запрос"}) + return + self._forward("POST", self._user()) + + def _forward(self, method: str, user_id: str) -> None: + try: + engine = TENANTS.ensure(user_id) + length = int(self.headers.get("Content-Length") or 0) + if length < 0 or length > 65536: + self._json(413, {"error": "Слишком большой запрос"}) + return + 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 and k.lower() not in ("cookie",)} + headers["Host"] = self.headers.get("Host", "127.0.0.1:8765") + req = urllib.request.Request(engine + self.path, data=body, method=method, headers=headers) + with urllib.request.urlopen(req, timeout=60) as resp: + status, data, resp_headers = resp.status, resp.read(), resp.getheaders() + except urllib.error.HTTPError as exc: + status, data, resp_headers = exc.code, exc.read(), exc.headers.items() + except (urllib.error.URLError, OSError, ValueError) as exc: + status, data = 502, json.dumps({"error": f"Личный движок не отвечает: {exc}"}, ensure_ascii=False).encode() + resp_headers = [("Content-Type", "application/json; charset=utf-8")] + self.send_response(status) + for key, value in resp_headers: + if key.lower() not in HOP_HEADERS and key.lower() not in ("set-cookie",): + self.send_header(key, value) + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + + def _system_status(self) -> None: + open_trades = [] + for user_id in STORE.user_ids(): + try: + engine = TENANTS.ensure(user_id) + req = urllib.request.Request(engine + "/api/basis?ex=cross_real") + with urllib.request.urlopen(req, timeout=10) as resp: + data = json.loads(resp.read()) + open_trades.extend({"user": STORE.username(user_id), "coin": p.get("base"), + "closing": bool(p.get("closing"))} + for p in data.get("positions", []) if p.get("real")) + except Exception: + continue + self._json(200, {"real_positions": open_trades}) + + +def _import_legacy_data(target: Path) -> None: + """Copy the old single-account files into the first account without removing the originals.""" + try: + items = list(DATA_ROOT.iterdir()) + except OSError: + items = [] + for source in items: + if source.name in {"users", "accounts.sqlite3", "engine.lock"} or source.name.endswith((".log", ".tmp")): + continue + destination = target / source.name + try: + if source.is_file() and not destination.exists(): + shutil.copy2(source, destination) + elif source.is_dir() and source.name == "scalp_recordings": + shutil.copytree(source, destination, dirs_exist_ok=True) + except OSError: + continue + + # One old connection/removal file lived at the project root. Do not copy source code or config examples. + source = ROOT / "lead_connections_removed.json" + destination = target / source.name + try: + if source.is_file() and not destination.exists(): + shutil.copy2(source, destination) + except OSError: + pass + + +class Proxy(BaseHTTPRequestHandler): + def log_message(self, *args) -> None: + pass + + def _forward(self, method: str) -> None: + 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: + status, data, resp_headers = resp.status, resp.read(), resp.getheaders() + except urllib.error.HTTPError as exc: + status, data, resp_headers = exc.code, exc.read(), exc.headers.items() + except (urllib.error.URLError, OSError): + status, data = 502, "Движок симулятора не отвечает (web_sim.py --backend не запущен?)".encode("utf-8") + resp_headers = [("Content-Type", "text/plain; charset=utf-8")] + self.send_response(status) + for k, v in resp_headers: + if k.lower() not in HOP_HEADERS: + self.send_header(k, v) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self) -> None: + self._forward("GET") + + def do_POST(self) -> None: + self._forward("POST") + + +def main() -> None: + server = ThreadingHTTPServer(LISTEN, Gateway) + if sys.stdout: + print(f"Сервер с авторизацией: http://{LISTEN[0]}:{LISTEN[1]}", flush=True) + threading.Thread(target=TENANTS.start_all, daemon=True).start() + try: + server.serve_forever() + finally: + server.server_close() + TENANTS.stop_all() + + +if __name__ == "__main__": + main() diff --git a/LinuxServer/web_sim.html b/LinuxServer/web_sim.html new file mode 100644 index 0000000..6cdee85 --- /dev/null +++ b/LinuxServer/web_sim.html @@ -0,0 +1,171 @@ + + + + + +Симулятор опережения + + + + +
    + СИМУЛЯЦИЯ · общий виртуальный счёт + Подключение к серверу… +
    + + + +

    Справка

    Термины, режимы и все настройки интерфейса

    + + +

    +
    +
    + + + +
    +
    +
    +

    Симулятор опережения: ведущая биржа → ставки на фьючерсах

    + виртуальные сделки, ордера на биржи не отправляются +
    +
    + Реальная торговля + включается для каждой монеты отдельно — кнопкой на странице монеты; её позиции повторяются настоящими рыночными ордерами (сумма = «Ставка» × плечо) + + +
    +
    + + · по каждой монете одна реальная сделка за раз: следующая — только когда биржа подтвердила, что прошлая закрыта + +
    +
    +
    +
    + + + Выйти из аккаунта + +
    +
    +
    + +
    Выберите монету слева
    +
    +
    + + + + + diff --git a/LinuxServer/web_sim.py b/LinuxServer/web_sim.py new file mode 100644 index 0000000..cc90e2d --- /dev/null +++ b/LinuxServer/web_sim.py @@ -0,0 +1,1093 @@ +"""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 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. +* 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. +""" + +from __future__ import annotations + +import json +import os +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 +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 +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 = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT / "web_sim_data")).resolve() +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) + 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", "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: + 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}", + "mexc": f"https://futures.mexc.com/exchange/{ticker}"}.get(exchange) + if url: + name = {"bybit": "Bybit", "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.""" + 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: + 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, 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"{'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"{'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 + 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() + 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._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() + 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.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) + follower = sh.MexcFeed(ps.follow_ticker, self.events, size) + 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: + 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) + 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: + if on and self.removing: + self.message = "Подключение ожидает закрытия позиций и удаления" + return + self.paper.settings.enabled = on + self.paper.ledger.save() + if on: + self.auto_stop = "" + self.message = ("Старт: новые сделки открываются" if on else + "Стоп: новые сделки не открываются; открытые закроются по тейку, стопу или времени") + + def reset(self) -> str: + """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 + 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 = "" + 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: + 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 + 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) + 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: + """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, "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, + "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, 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() + 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()).""" + 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, self.account) + engine.removing = key in pending + if engine.removing: + engine.set_trading(False) + self.engines[key] = engine + if self.start_feeds: + engine.start() + if engine.removing: + engine.close(None) + engine.mirror.request_close() + + def remove(self, key: str) -> str: + """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 "нет такой монеты" + try: + self.removals.schedule(key, engine.conn) + except (OSError, ValueError) as exc: + return f"Удаление не начато: {exc}" + with engine.lock: + engine.removing = True + engine.set_trading(False) + closed = len(engine.paper.ledger.positions) + engine.close(None) # open positions at the current price + 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(1) + try: + 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 + 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 engines), + 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", "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(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 + 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 == "/health": + tenant_id = DATA_DIR.parent.name if DATA_DIR.parent.parent.name == "users" else "single-user" + self._json({"ok": True, "tenant": tenant_id}) + elif 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) + 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: + 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())) + 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 + 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"{}") + 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"]: + 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: + 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": + 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 + 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": not engine.removing, + "error": engine.message if engine.removing else ""}) + elif action == "stop": + engine.set_trading(False) + self._json({"ok": True}) + elif action == "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 + 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 + 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 + if "--backend" not in sys.argv: + import web_proxy + web_proxy.main() + return + 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) + if "--backend" in sys.argv: + host = "127.0.0.1" + port = int(sys.argv[sys.argv.index("--port") + 1]) if "--port" in sys.argv else 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 + # 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") + # Public market histories stay warm for the four supported venues even before the page opens the arb panel. + arb_view(market="spot") + arb_view(market="futures") + url = f"http://127.0.0.1:{PORT}" + print(f"Симулятор: {url} (движок слушает {host}:{port}, монет: {len(SIM.engines)})", flush=True) + if "--backend" not in sys.argv: + threading.Timer(1.0, lambda: webbrowser.open(url)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + for engine in SIM.engines.values(): + engine.shutdown() + + +if __name__ == "__main__": + main() diff --git a/README.md b/README.md index 9153460..327b4f0 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ > Важно: это исследовательский симулятор, а не рекомендация по торговле. Бумажные результаты не гарантируют прибыль в реальном рынке. +Для отдельного развёртывания веб-версии на Ubuntu 24.04 см. [LinuxServer/README.md](LinuxServer/README.md). Windows-запуск остаётся прежним. + ## Что умеет проект - **Симулятор опережения**: сравнивает цену ведущего источника с ценой фьючерса и моделирует входы/выходы.