diff --git a/README.md b/README.md index 42d6e28..9153460 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ - **Симулятор опережения**: сравнивает цену ведущего источника с ценой фьючерса и моделирует входы/выходы. - **Автоподбор мем-монет**: сканирует поддерживаемые DEX-пулы и добавляет подходящие пары в веб-интерфейс. -- **Арбитраж**: сравнивает bid/ask, комиссии, funding, оборот и доступную ликвидность на Bybit, Binance, MEXC, HTX и Gate, не отправляя ордера в режиме просмотра. +- **Арбитраж**: сравнивает bid/ask, комиссии, funding, оборот и доступную ликвидность на Bybit, Gate, MEXC и HTX, не отправляя ордера в режиме просмотра. Binance не используется. - **Исторический прогон и backtest**: использует кэш свечей, считает PnL, комиссии, funding, просадку, ликвидации и открытые позиции. - **Стратегии**: классическая LONG-стратегия с усреднением, пробой максимума с ATR, шорт затухающего пампа, basis-trading и экспериментальные режимы по стакану/потоку. - **Реальная торговля**: доступна только после явного подключения API-ключей и запуска соответствующего режима. @@ -18,7 +18,7 @@ - Windows 10/11. - Python 3.10–3.13. Если Python не найден, установщик пытается поставить Python 3.12 через `winget`. - Интернет. Для доступа к отдельным биржам может потребоваться VPN. -- Свободный порт `127.0.0.1:8765` для веб-страницы и `127.0.0.1:8766` для внутреннего движка. +- Свободный порт `127.0.0.1:8765` для страницы авторизации. Личные движки пользователей запускаются на отдельных локальных портах. ## Установка и первый запуск @@ -34,16 +34,10 @@ Python 3.11+; dependencies are pinned in `requirements.txt`. Recovery semantics, cd C:\Crypto_Scam py -3 -m venv .venv .venv\Scripts\python.exe -m pip install -r requirements.txt -.venv\Scripts\python.exe web_sim.py --backend -``` - -В отдельном окне запустите прокси: - -```powershell .venv\Scripts\python.exe web_proxy.py ``` -После этого откройте `http://127.0.0.1:8765`. +Откройте `http://127.0.0.1:8765`. При первом запуске создайте пользователя; далее входите с его логином и паролем. Шлюз автоматически поднимет отдельный движок. ## Запуск и остановка @@ -60,11 +54,19 @@ py -3 -m venv .venv ## Веб-интерфейс -Основной запуск: `py -3 web_sim.py` или `py -3 web_sim.py --backend`. Откройте `http://127.0.0.1:8765`. +Основной запуск: `py -3 web_sim.py` (или `py -3 web_proxy.py`). Откройте `http://127.0.0.1:8765`, зарегистрируйте пользователя и войдите. Не запускайте `web_sim.py --backend` вручную: личные движки запускает шлюз. В веб-интерфейсе доступны карточки монет, отдельные бумажные счета и журналы сделок, общие настройки, графики изменения цен, запуск/остановка торговли по каждой паре и панель автоматического сканера `meme_matcher/autoscan.py`. -Данные веб-симулятора сохраняются в `web_sim_data/`: `settings.json` — общие настройки, `.json` — состояние бумажного счёта, `.csv` — журнал сделок, `backend.log` — журнал движка. +Данные учётных записей хранятся в `web_sim_data/accounts.sqlite3`. Данные каждого пользователя, включая настройки, сделки, состояния и сохранённые ключи, изолированы в `web_sim_data/users//data/`; журнал личного движка — `backend.log`. Публичные сканеры и накопление рыночных данных запускаются по Bybit, Gate, MEXC и HTX. Сейчас история тоже хранится отдельно для каждого пользователя; общий кэш может быть добавлен отдельно. + +### Учётные записи и перенос старых данных + +- Регистрация доступна на локальной странице при первом запуске. Пароль не хранится открытым текстом: в общей БД лежит PBKDF2-хеш; сессия ограничена по времени. +- Только самая первая учётная запись получает копию прежних однопользовательских данных. Исходные файлы не удаляются. Остальные пользователи начинают с чистого личного хранилища. +- Сохранённые API-ключи остаются защищены Windows DPAPI и доступны только той Windows-учётной записи, под которой запущена программа. Пользовательские папки не заменяют права доступа Windows. +- Перед обновлением остановите старую версию через `ОСТАНОВИТЬ_СЕРВЕР.bat` и проверьте активные реальные позиции. При остановке сервер предупредит об открытых позициях; сначала убедитесь, что их можно оставить без наблюдения. +- Веб-интерфейс по-прежнему слушает только `127.0.0.1`; внешний сетевой доступ не настроен. Рыночные данные собираются через Bybit, Gate, MEXC и HTX. Binance отключён. ## Основные режимы @@ -90,7 +92,7 @@ py -3 -m venv .venv `scalp_paper.py` и `algo_hunter.py` содержат экспериментальные модели по стакану, imbalance, микроцене и повторяющимся заявкам. Они предназначены для dry-run и анализа: видимый агрегированный стакан не позволяет надёжно доказать наличие конкретного маркет-мейкера или реальную очередь исполнения. -<<<<<<< HEAD +## Веб-интерфейс: виртуальный счёт, сделки и управление режимами **Web interface** (`py -3 web_sim.py` or `run_web_sim.bat` → [local page](http://127.0.0.1:8765), opens in the browser): every coin has its own feeds, trade history and Start/Stop. A new coin starts stopped; Stop forbids new entries while existing positions remain managed. All paper coins in «Симулятор» and «Арбитраж → Симуляция» @@ -133,9 +135,8 @@ The last tile «+» opens the **scanner panel**: start/stop of `meme_matcher/aut allows automatic additions (off by default; `meme_matcher/autoscan_config.json`); new connections appear within 30 seconds. Removing a pair first stops new entries and requests closing its exposure. If execution or recovery is unfinished, the connection stays available for management; the removal intent survives restart. -======= + ## Реальная торговля и API-ключи ->>>>>>> main Используйте реальную торговлю только после проверки в симуляции и на Testnet. @@ -149,19 +150,11 @@ is unfinished, the connection stays available for management; the removal intent В проекте предусмотрены отдельные состояния виртуального и реального счёта. Они не смешиваются. Для реального режима учитывайте funding, проскальзывание, минимальный размер ордера, задержку сети и риск ликвидации при усреднении или плече. -<<<<<<< HEAD -**Local proxy with a VPN on**: `run_web_sim.bat` starts the engine on `127.0.0.1:8766` -(`python.exe`) and the page proxy on `127.0.0.1:8765` (`pythonw.exe`). The page remains local even when -`pythonw.exe` is excluded from the VPN. Both processes validate the original local Host and browser Origin; -POST commands require the page's `X-Sim` header. The app is not configured for public internet hosting. -`py -3 web_sim.py` serves the page directly on `127.0.0.1:8765`. -======= -## VPN, внешний доступ и безопасность ->>>>>>> main +## Локальный адрес, VPN и безопасность - Если биржи не отдают цены, проверьте VPN и доступ к публичным API. -- По умолчанию страница доступна только локально через `127.0.0.1`; это безопаснее, чем открывать её в интернет. -- Для внешнего доступа потребуется настройка прокси, проброс TCP-порта `8765` и правило Windows Firewall. Не публикуйте интерфейс без аутентификации. +- Шлюз и личные движки слушают только локальные адреса `127.0.0.1`; интерфейс не предназначен для публикации в интернете. +- Не пробрасывайте порт `8765` наружу: для удалённого доступа потребуются TLS, сетевой шлюз и дополнительная защита сессий. - Не коммитьте API-ключи, файлы состояния и журналы с чувствительными данными в публичный репозиторий. ## Тесты @@ -176,8 +169,8 @@ py -3 -m unittest discover -s tests ## Где искать проблемы -- Веб-страница не открывается: проверьте порт `8765` и запустите `УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat`, чтобы увидеть окно движка. -- Сервер не отвечает: изучите `web_sim_data/backend.log`, затем выполните `ОСТАНОВИТЬ_СЕРВЕР.bat` и `ЗАПУСТИТЬ_СЕРВЕР.bat`. +- Веб-страница не открывается: проверьте порт `8765` и изучите `web_sim_data/gateway.log`. +- Личный движок не отвечает: изучите `web_sim_data/users//data/backend.log`, затем выполните `ОСТАНОВИТЬ_СЕРВЕР.bat` и `ЗАПУСТИТЬ_СЕРВЕР.bat`. - Нет цен: проверьте интернет, VPN и доступ к API бирж. - Не ставятся зависимости: проверьте интернет и наличие Python, затем повторите установку. - Реальная сделка открыта: не останавливайте приложение, пока не проверили позицию и защитные ордера на бирже. diff --git a/arb.py b/arb.py index 443dc51..cf25927 100644 --- a/arb.py +++ b/arb.py @@ -17,6 +17,7 @@ A spread above 10 % is flagged «разные монеты?» (the same ticker o from __future__ import annotations import json +import os import re import threading import time @@ -25,10 +26,10 @@ from pathlib import Path from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass -EXCHANGES = ["Bybit", "Binance", "MEXC", "HTX", "Gate"] -TAKER = {"Bybit": 0.055, "Binance": 0.05, "MEXC": 0.02, "HTX": 0.05, "Gate": 0.05} # % per market order, futures +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, "Binance": 0.1, "MEXC": 0.05, "HTX": 0.2, "Gate": 0.1} +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 @@ -109,18 +110,13 @@ class Fetchers: def refresh_reference(self) -> None: if time.time() - self.ref_time < 3600 and self.ref: return - ref: dict[str, dict] = {"bybit_interval": {}, "binance_interval": {}, "htx_size": {}, "htx_interval": {}, + 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://fapi.binance.com/fapi/v1/fundingInfo"): - ref["binance_interval"][it["symbol"]] = _f(it.get("fundingIntervalHours"), 8) - 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) @@ -232,10 +228,6 @@ class SpotFetchers: if time.time() - self.volume_time < 60 and self.volume: return vol = {} - try: - vol["Binance"] = {t["symbol"]: _f(t.get("quoteVolume")) for t in _get("https://api.binance.com/api/v3/ticker/24hr")} - except Exception: - pass try: vol["MEXC"] = {t["symbol"]: _f(t.get("quoteVolume")) for t in _get("https://api.mexc.com/api/v3/ticker/24hr")} except Exception: @@ -433,7 +425,8 @@ def best_pairs(quotes: list[Quote], usual: dict, taker: dict | None = None, mark return rows -PAUSED_FILE = Path(__file__).resolve().parent / "web_sim_data" / "arb_paused.json" +PAUSED_FILE = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", Path(__file__).resolve().parent / "web_sim_data")) \\ + / "arb_paused.json" def load_paused() -> dict: @@ -499,7 +492,7 @@ class ArbScanner: getattr(self.fetchers, refresh)() except Exception: pass - calls = {"Bybit": self.fetchers.bybit, "Binance": self.fetchers.binance, "MEXC": self.fetchers.mexc, + calls = {"Bybit": self.fetchers.bybit, "MEXC": self.fetchers.mexc, "HTX": self.fetchers.htx, "Gate": self.fetchers.gate} quotes, status, counts = [], {}, {} @@ -510,7 +503,7 @@ class ArbScanner: except Exception as exc: return name, [], f"ошибка: {str(exc)[:80]}" - with ThreadPoolExecutor(max_workers=5) as pool: + 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) diff --git a/basis.py b/basis.py index 812f21c..2639765 100644 --- a/basis.py +++ b/basis.py @@ -13,6 +13,7 @@ Result of one trade = spot leg + perp leg − 4 taker fees + funding the short r from __future__ import annotations import json +import os import queue import threading import time @@ -24,7 +25,7 @@ from pathlib import Path from arb import _f, _get, split_base ROOT = Path(__file__).resolve().parent -DATA_DIR = ROOT / "web_sim_data" +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 diff --git a/cross.py b/cross.py index b4ba3c7..61aa385 100644 --- a/cross.py +++ b/cross.py @@ -27,6 +27,7 @@ after each real trade they are replaced by what the exchanges actually charged, from __future__ import annotations import json +import os from persistence import atomic_write_json import queue import threading @@ -39,7 +40,7 @@ import arb import minorder ROOT = Path(__file__).resolve().parent -DATA_DIR = ROOT / "web_sim_data" +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 @@ -154,7 +155,7 @@ class CrossSettings: 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 = True + use_binance: bool = False use_mexc: bool = True use_htx: bool = True use_gate: bool = True @@ -527,6 +528,7 @@ class CrossEngine: 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(): @@ -804,7 +806,7 @@ class CrossEngine: def exchanges(self) -> set[str]: s = self.settings - return {name for name, on in (("Bybit", s.use_bybit), ("Binance", s.use_binance), ("MEXC", s.use_mexc), + 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: diff --git a/keystore.py b/keystore.py index c23b157..04a6386 100644 --- a/keystore.py +++ b/keystore.py @@ -8,13 +8,14 @@ from __future__ import annotations import ctypes import json +import os import threading from ctypes import wintypes from pathlib import Path ROOT = Path(__file__).resolve().parent -KEYS_FILE = ROOT / "web_sim_data" / "api_keys.bin" -EXCHANGES = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC", "htx": "HTX", "gate": "Gate"} +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() diff --git a/lead_window.py b/lead_window.py index 9178fd8..3f0cacf 100644 --- a/lead_window.py +++ b/lead_window.py @@ -37,8 +37,8 @@ FIELDS = COMMON_FIELDS + MODE_FIELDS["lead"] + MODE_FIELDS["vector"] + MODE_FIEL 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.ROOT / "lead_paper_state.json" -TRADES_FILE = sp.ROOT / "lead_paper_trades.csv" +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: @@ -56,15 +56,13 @@ def inherit_settings(paper: sp.PaperTrader) -> None: LEAD_MARKETS = {"futures": "KuCoin фьючерсы", "spot": "KuCoin спот", "raydium": "DEX пул Solana (Raydium / PumpSwap / Meteora / Orca / PancakeSwap)"} -FOLLOW_EXCHANGES = {"bybit": "Bybit фьючерс", "binance": "Binance фьючерс", "mexc": "MEXC фьючерс"} +FOLLOW_EXCHANGES = {"bybit": "Bybit фьючерс", "mexc": "MEXC фьючерс"} -CONNECTIONS_FILE = sp.ROOT / "lead_connections.json" +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": "ZEREBROUSDTM", "lead_pool": "3sjNoCnkkhWPVXYGDtem8rCciHSGc9jSFZuUAzKbvRVp", - "follow_exchange": "binance", "follow_ticker": "ZEREBROUSDT"}, {"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", @@ -82,7 +80,7 @@ def connection_name(c: dict) -> str: lead = f"DEX пул {c['lead_pool'][:6]}…" else: lead = f"KuCoin {'спот' if c['lead_market'] == 'spot' else 'фьючерс'} {c['lead_ticker']}" - follow = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC"}.get(c["follow_exchange"], c["follow_exchange"]) + follow = {"bybit": "Bybit", "mexc": "MEXC"}.get(c["follow_exchange"], c["follow_exchange"]) return f"{coin}: {lead} → {follow} {c['follow_ticker']}" @@ -92,7 +90,7 @@ def same_connection(a: dict, b: dict) -> bool: return all(a.get(k) == b.get(k) for k in keys) -REMOVED_FILE = sp.ROOT / "lead_connections_removed.json" # deleted by the user (× on a web tile) +REMOVED_FILE = sp.DATA_DIR / "lead_connections_removed.json" # deleted by the user (× on a web tile) def _read_list(path) -> list[dict]: @@ -116,7 +114,8 @@ def is_removed(conn: dict, removed_path=None) -> bool: 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 not any(same_connection(c, r) for r in removed)] + 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)) @@ -440,9 +439,6 @@ def run() -> None: if ps.follow_exchange == "mexc": state["tick"], size = sh.mexc_contract(ps.follow_ticker) state["follower_feed"] = sh.MexcFeed(ps.follow_ticker, events, size) - elif ps.follow_exchange == "binance": - state["tick"] = sh.binance_tick(ps.follow_ticker) - state["follower_feed"] = sh.BinanceFeed(ps.follow_ticker, events) else: state["tick"] = sh.bybit_tick(ps.follow_ticker) state["follower_feed"] = sh.BybitFeed(ps.follow_ticker, events) diff --git a/live.py b/live.py index c9db10b..3eec55e 100644 --- a/live.py +++ b/live.py @@ -1436,7 +1436,7 @@ def ensure_usdt(c, spot_need: float, futures_need: float) -> str: return f"переведено {amount:.2f} USDT {'со спота на фьючерсы' if to == 'futures' else 'с фьючерсов на спот'}" -CLIENTS = {"bybit": Bybit, "binance": Binance, "mexc": Mexc, "htx": Htx, "gate": Gate} +CLIENTS = {"bybit": Bybit, "mexc": Mexc, "htx": Htx, "gate": Gate} _cache: dict[str, tuple[tuple[str, str], object]] = {} diff --git a/meme_matcher/autoscan.py b/meme_matcher/autoscan.py index 3097d21..f6b6b25 100644 --- a/meme_matcher/autoscan.py +++ b/meme_matcher/autoscan.py @@ -37,7 +37,7 @@ HISTORY_CSV = ROOT / "autoscan_history.csv" LOG_FILE = ROOT / "autoscan.log" LOCK_FILE = ROOT / "autoscan.lock" LEAD_VERDICT = "DEX опережает ≥1 с" -SIM_EXCHANGES = ["Binance", "Bybit", "MEXC"] # futures the simulator can paper-trade on +SIM_EXCHANGES = ["Bybit", "MEXC"] # futures the simulator can paper-trade on SUPPORTED_OWNERS = { "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8": "Raydium AMM v4", "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C": "Raydium CPMM", diff --git a/meme_matcher/meme_matcher.py b/meme_matcher/meme_matcher.py index f49d47e..83ebe15 100644 --- a/meme_matcher/meme_matcher.py +++ b/meme_matcher/meme_matcher.py @@ -194,12 +194,8 @@ def parse_bingx(data) -> list[Listing]: CEX_SOURCES = { "Bybit": ("https://api.bybit.com/v5/market/tickers?category=linear", parse_bybit), - "Binance": ("https://fapi.binance.com/fapi/v1/ticker/24hr", parse_binance), - "OKX": ("https://www.okx.com/api/v5/market/tickers?instType=SWAP", parse_okx), "Gate": ("https://api.gateio.ws/api/v4/futures/usdt/tickers", parse_gate), "MEXC": ("https://contract.mexc.com/api/v1/contract/ticker", parse_mexc), - "Bitget": ("https://api.bitget.com/api/v2/mix/market/tickers?productType=USDT-FUTURES", parse_bitget), - "BingX": ("https://open-api.bingx.com/openApi/swap/v2/quote/ticker", parse_bingx), } diff --git a/real_mirror.py b/real_mirror.py index a6fce30..e15cee9 100644 --- a/real_mirror.py +++ b/real_mirror.py @@ -16,6 +16,7 @@ Results (prices, fees) are the exchange's own fills; `exact` is False where the from __future__ import annotations import json +import os from persistence import atomic_write_json import queue import threading @@ -25,7 +26,7 @@ from pathlib import Path import live ROOT = Path(__file__).resolve().parent -DATA_DIR = ROOT / "web_sim_data" +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() diff --git a/scalp_paper.py b/scalp_paper.py index 99ecb60..1d90f49 100644 --- a/scalp_paper.py +++ b/scalp_paper.py @@ -21,6 +21,7 @@ from __future__ import annotations import csv import gzip import json +import os import math import statistics import sys @@ -34,9 +35,10 @@ import scalp_hint as sh from persistence import atomic_write_json ROOT = Path(__file__).resolve().parent -STATE_FILE = ROOT / "scalp_paper_state.json" -TRADES_FILE = ROOT / "scalp_paper_trades.csv" -RECORD_DIR = ROOT / "scalp_recordings" +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) diff --git a/server_control.ps1 b/server_control.ps1 index 762322c..03fd404 100644 --- a/server_control.ps1 +++ b/server_control.ps1 @@ -17,7 +17,7 @@ function Server-Processes { } function Answers { - try { Invoke-RestMethod "$Url/api/state" -TimeoutSec 3 | Out-Null; return $true } catch { return $false } + try { Invoke-RestMethod "$Url/health" -TimeoutSec 3 | Out-Null; return $true } catch { return $false } } function Set-Watchdog([bool] $On) { @@ -31,18 +31,26 @@ if ($Action -eq "stop") { if (-not (Server-Processes)) { Write-Host "Сервер не запущен." -ForegroundColor Yellow; Set-Watchdog $false; exit 0 } # реальная торговля: закрытие, которое идёт прямо сейчас, лучше не прерывать try { - $real = Invoke-RestMethod "$Url/api/basis?ex=cross_real" -TimeoutSec 5 - $closing = @($real.positions | Where-Object { $_.real -and $_.closing }) - $open = @($real.positions | Where-Object { $_.real }) + $real = Invoke-RestMethod "$Url/system/status" -TimeoutSec 20 + $closing = @($real.real_positions | Where-Object { $_.closing }) + $open = @($real.real_positions) if ($closing.Count) { - Write-Host ("Сейчас закрывается реальная сделка: " + (($closing | ForEach-Object { $_.base }) -join ", ")) -ForegroundColor Red + Write-Host ("Сейчас закрываются реальные сделки: " + (($closing | ForEach-Object { $_.user + ":" + $_.coin }) -join ", ")) -ForegroundColor Red $ans = Read-Host "Всё равно остановить? (y — да, иначе — нет)" if ($ans -ne "y") { Write-Host "Остановка отменена."; exit 1 } } elseif ($open.Count) { - Write-Host ("Открытые реальные сделки: " + (($open | ForEach-Object { $_.base }) -join ", ") + + Write-Host ("Открытые реальные сделки: " + (($open | ForEach-Object { $_.user + ":" + $_.coin }) -join ", ") + " — пока сервер остановлен, за ними никто не следит; после запуска программа продолжит их вести.") -ForegroundColor Yellow + $ans = Read-Host "Остановить сервер с открытыми реальными позициями? (y — да, иначе — нет)" + if ($ans -ne "y") { Write-Host "Остановка отменена."; exit 1 } } - } catch {} + } catch { + if (Server-Processes) { + Write-Host "Не удалось проверить открытые реальные сделки через сервер." -ForegroundColor Yellow + $ans = Read-Host "Всё равно остановить процессы? Открытые позиции временно останутся без контроля. (y — да, иначе — нет)" + if ($ans -ne "y") { Write-Host "Остановка отменена."; exit 1 } + } + } Set-Watchdog $false # сначала цикл перезапуска (иначе он поднимет движок), потом движок и страница foreach ($round in 1..3) { @@ -64,6 +72,10 @@ if ((Server-Processes) -and (Answers)) { Start-Process $Url exit 0 } +if (Server-Processes) { + Write-Host "Обнаружена старая версия сервера без новой авторизации. Сначала запустите ОСТАНОВИТЬ_СЕРВЕР.bat, проверьте активные позиции и подтвердите остановку; затем запустите этот файл снова." -ForegroundColor Red + exit 1 +} $VenvPython = Join-Path $Dir ".venv\Scripts\python.exe" $haveVenv = $false if (Test-Path -LiteralPath $VenvPython) { diff --git a/user_auth.py b/user_auth.py new file mode 100644 index 0000000..8867602 --- /dev/null +++ b/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/web/app.js b/web/app.js index cc92cd9..b4bcb6c 100644 --- a/web/app.js +++ b/web/app.js @@ -854,7 +854,7 @@ const CX_CHECKS = [["search_sf", "Искать: спот → фьючерс ме ["entry_limit", "Вход лимитным шортом с ожиданием «Лимитный вход: ждать, с» (если IOC выключен)"], ["block_negative_funding", "Не открывать сделку при отрицательном funding"], ["fees_auto", "Комиссии сами корректируются по завершённым реальным сделкам"]]; -const CX_EX = ["Bybit", "Binance", "MEXC", "HTX", "Gate"]; +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 => ` @@ -1312,7 +1312,7 @@ async function loadArb() { const st = Object.entries(arb.status || {}).map(([e, s]) => `${e}: ${s === "ok" ? arb.counts[e] + " " + unit : s}`).join(" · "); document.getElementById("arbStatus").textContent = (arb.paused ? "Сканирование остановлено — цены ниже последние полученные. " : "") + (arb.updated ? `${st} · обновлено ${msk(arb.updated)} МСК (цикл ${(arb.cycle_ms / 1000).toFixed(1)} с, каждые ${arb.cycle_s} с)` : arb.paused ? "данных ещё нет" : "загружаю цены со всех бирж…"); - document.getElementById("arbTitle").textContent = `Арбитраж ${isSpot() ? "на споте" : "на фьючерсах"}: Bybit · Binance · MEXC · HTX · Gate`; + document.getElementById("arbTitle").textContent = `Арбитраж ${isSpot() ? "на споте" : "на фьючерсах"}: Bybit · MEXC · HTX · Gate`; document.getElementById("arbFees").textContent = isSpot() ? "спот: купить на одной бирже → вывести монету → продать на другой" : "фьючерсы: лонг на одной + шорт на другой, закрыть при схождении"; renderArb(); diff --git a/web/help-data.js b/web/help-data.js index c594f74..e27c593 100644 --- a/web/help-data.js +++ b/web/help-data.js @@ -115,7 +115,7 @@ const HELP_EXTRA = [ ["Биржи и лимиты", "exchange_balance", "Балансы и «С запуска»", "Спот USDT и фьючерсы USDT — свободные денежные счета биржи; монеты в позициях показаны отдельно. Единый счёт не суммируется дважды. «С запуска» сравнивает оценку с запуском реального режима и может включать внешние изменения счёта, а не только результат программы."], ["Реальная торговля", "api_key", "API key / API secret", "Ключ и секрет для выбранной биржи. «Сохранить» записывает их локально в защищённое хранилище; секрет не возвращается в браузер. «Проверить (баланс)» проверяет доступ чтением баланса, «Удалить» удаляет сохранённые ключи. Нужны права торговли; разрешение вывода средств для программы не требуется."], ["Реальная торговля", "coinReal", "Включить реальную торговлю монеты", "Включается отдельно у каждой монеты после подтверждения. Перед переключением нужно завершить её текущие виртуальные и реальные позиции, включая сохранённые позиции выбранного режима; незавершённые ордера, восстановление и ошибки сохранения блокируют переход. Новые позиции повторяются реальными рыночными ордерами: номинал = ставка × плечо. Реальная позиция одна за раз, следующая — после подтверждённого закрытия предыдущей. Общий виртуальный счёт и его пополнения не меняют реальные средства, размер ордеров или разрешение реальных входов. Сохранение ключей само по себе торговлю не запускает."], - ["Реальная торговля", "simRealTpsl", "TP/SL на бирже", "Отправлять защитные ордера на поддерживаемые биржи (Bybit, Binance, MEXC). SL сопровождает вход, TP выставляется как reduce-only от фактической цены исполнения. Проверяйте подтверждение ордеров в журнале: сама включённая галочка не означает, что биржа приняла защиту."], + ["Реальная торговля", "simRealTpsl", "TP/SL на бирже", "Отправлять защитные ордера на поддерживаемые биржи (Bybit, MEXC). SL сопровождает вход, TP выставляется как reduce-only от фактической цены исполнения. Проверяйте подтверждение ордеров в журнале: сама включённая галочка не означает, что биржа приняла защиту."], ["Реальная торговля", "simRealTransfer", "Автоперевод USDT спот → фьючерсы", "При нехватке фьючерсного баланса разрешать перевод со спотового счёта той же биржи. Меняет реальные счета внутри биржи; включается отдельно от арбитражной настройки автоперевода."], ["Реальная торговля", "simRealSl", "Стоп-лосс на бирже, %", "Расстояние биржевого стоп-лосса от входа в процентах цены. Это отдельная защита реального ордера, отличная от общего стоп-лосса стратегии. Сохраняется после изменения поля."], ["Реальная торговля", "simRealPing", "Макс. пинг до биржи, мс", "Блокировать новые виртуальные и реальные входы монеты, если измеренная задержка биржи выше порога. 0 отключает проверку. Это задержка до биржи, а не возраст котировки или связь браузера."], diff --git a/web_proxy.py b/web_proxy.py index 0f74cf9..5e6bd38 100644 --- a/web_proxy.py +++ b/web_proxy.py @@ -11,17 +11,338 @@ program than the engine's python.exe) and add pythonw.exe to the VPN's app exclu from __future__ import annotations import sys +import html +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" 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() + 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; 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; 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 @@ -60,10 +381,15 @@ class Proxy(BaseHTTPRequestHandler): def main() -> None: - server = ThreadingHTTPServer(LISTEN, Proxy) + server = ThreadingHTTPServer(LISTEN, Gateway) if sys.stdout: - print(f"Прокси страницы: {LISTEN[0]}:{LISTEN[1]} → {ENGINE}", flush=True) - server.serve_forever() + 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__": diff --git a/web_sim.html b/web_sim.html index a25b951..951aa0e 100644 --- a/web_sim.html +++ b/web_sim.html @@ -139,7 +139,7 @@
Реальная торговля включается для каждой монеты отдельно — кнопкой на странице монеты; её позиции повторяются настоящими рыночными ордерами (сумма = «Ставка» × плечо) - +
@@ -152,6 +152,7 @@
+ Выйти из аккаунта
diff --git a/web_sim.py b/web_sim.py index 41d5fda..cc90e2d 100644 --- a/web_sim.py +++ b/web_sim.py @@ -14,6 +14,7 @@ from __future__ import annotations import json +import os import queue import re import statistics @@ -114,7 +115,7 @@ def scanner_add(symbol: str, connections: list[dict]) -> tuple[dict | None, str] lw.unremove_connection(conn) # deleted earlier and now added again by hand au.add_connection(conn, lw.CONNECTIONS_FILE) return conn, f"{symbol} добавлена ({au.SUPPORTED_OWNERS[owner]}) — монета остановлена, нажмите «Старт»" -DATA_DIR = ROOT / "web_sim_data" +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 = { @@ -169,10 +170,9 @@ def exchange_links(conn: dict) -> list[dict]: "url": f"https://www.kucoin.com/futures/trade/{conn['lead_ticker']}"}) ticker, exchange = conn["follow_ticker"], conn["follow_exchange"] url = {"bybit": f"https://www.bybit.com/trade/usdt/{ticker}", - "binance": f"https://www.binance.com/en/futures/{ticker}", "mexc": f"https://futures.mexc.com/exchange/{ticker}"}.get(exchange) if url: - name = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC"}[exchange] + name = {"bybit": "Bybit", "mexc": "MEXC"}[exchange] links.append({"label": f"{name} фьючерс {ticker}", "url": url}) return links @@ -369,9 +369,6 @@ class Engine: if ps.follow_exchange == "mexc": self.tick, size = sh.mexc_contract(ps.follow_ticker) follower = sh.MexcFeed(ps.follow_ticker, self.events, size) - elif ps.follow_exchange == "binance": - self.tick = sh.binance_tick(ps.follow_ticker) - follower = sh.BinanceFeed(ps.follow_ticker, self.events) else: self.tick = sh.bybit_tick(ps.follow_ticker) follower = sh.BybitFeed(ps.follow_ticker, self.events) @@ -736,7 +733,7 @@ def apply_real_fee(exchange: str, pct: float) -> None: PING_SAMPLES: dict = {} # host → deque of (time, ms) -FUTURES_HOST = {"bybit": "api.bybit.com", "binance": "fapi.binance.com", "mexc": "contract.mexc.com", +FUTURES_HOST = {"bybit": "api.bybit.com", "mexc": "contract.mexc.com", "htx": "api.hbdm.com", "gate": "api.gateio.ws"} @@ -832,7 +829,10 @@ class Handler(BaseHTTPRequestHandler): self._json({"error": "недоверенный адрес страницы"}, 403) return path, _, query = self.path.partition("?") - if path in ("/", "/index.html"): + 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] @@ -1039,6 +1039,11 @@ def local_request(handler) -> bool: 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() @@ -1048,7 +1053,8 @@ def _serve() -> None: global SIM # --backend: only for this PC on BACKEND_PORT, the public page is served by web_proxy.py (outside the VPN) if "--backend" in sys.argv: - host, port = "127.0.0.1", BACKEND_PORT + 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. @@ -1066,9 +1072,13 @@ def _serve() -> None: # «Арбитраж»: the simulation and the real engine run from the start (open real positions are watched at once) basis_engine("cross") basis_engine("cross_real") + # 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) - threading.Timer(1.0, lambda: webbrowser.open(url)).start() + if "--backend" not in sys.argv: + threading.Timer(1.0, lambda: webbrowser.open(url)).start() try: server.serve_forever() except KeyboardInterrupt: diff --git a/web_sim_autostart.vbs b/web_sim_autostart.vbs index f602024..e908e6d 100644 --- a/web_sim_autostart.vbs +++ b/web_sim_autostart.vbs @@ -1,7 +1,6 @@ ' Starts the web simulator without windows (Windows autostart: shortcut in the Startup folder). -' page - pythonw.exe web_proxy.py (0.0.0.0:8765, public; pythonw.exe excluded from the VPN) -' engine - python.exe web_sim.py --backend via web_sim_service.bat (127.0.0.1:8766, restarted if it stops) -' A part that is already running is not started twice. +' gateway - web_sim_service.bat (authenticated local page and private engines per account) +' A gateway already running is not started twice. Set sh = CreateObject("WScript.Shell") Set fso = CreateObject("Scripting.FileSystemObject") dir = fso.GetParentFolderName(WScript.ScriptFullName) @@ -17,10 +16,6 @@ Function Running(pattern) Next End Function -' the program's own environment (.venv, made by УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat) when there is one -pyw = "pyw -3" -If fso.FileExists(dir & "\.venv\Scripts\pythonw.exe") Then pyw = """" & dir & "\.venv\Scripts\pythonw.exe""" -If Not Running("web_proxy.py") Then sh.Run pyw & " """ & dir & "\web_proxy.py""", 0, False If Not Running("web_sim_service.bat") And Not Running("web_sim.py") Then sh.Run "cmd /c """ & dir & "\web_sim_service.bat""", 0, False End If diff --git a/web_sim_service.bat b/web_sim_service.bat index c1b713e..14ba525 100644 --- a/web_sim_service.bat +++ b/web_sim_service.bat @@ -1,16 +1,16 @@ @echo off -rem Engine of the web simulator, restarted automatically if it stops (crash, network loss at boot, manual kill). -rem Started hidden by web_sim_autostart.vbs; output goes to web_sim_data\backend.log. +rem Authenticated multi-user gateway, restarted automatically if it stops. +rem Per-user engines write logs to web_sim_data\users\\data\backend.log. cd /d "%~dp0" set PYTHONIOENCODING=utf-8 if not exist web_sim_data mkdir web_sim_data :loop -echo [%date% %time%] start >> web_sim_data\backend.log +echo [%date% %time%] gateway start >> web_sim_data\gateway.log if exist ".venv\Scripts\python.exe" ( - ".venv\Scripts\python.exe" web_sim.py --backend >> web_sim_data\backend.log 2>&1 + ".venv\Scripts\python.exe" web_proxy.py >> web_sim_data\gateway.log 2>&1 ) else ( - py -3 web_sim.py --backend >> web_sim_data\backend.log 2>&1 + py -3 web_proxy.py >> web_sim_data\gateway.log 2>&1 ) -echo [%date% %time%] stopped, restart in 5 s >> web_sim_data\backend.log +echo [%date% %time%] gateway stopped, restart in 5 s >> web_sim_data\gateway.log timeout /t 5 /nobreak >nul goto loop diff --git a/ПРОЧТИ_МЕНЯ.txt b/ПРОЧТИ_МЕНЯ.txt index 68983b0..66b3dbd 100644 --- a/ПРОЧТИ_МЕНЯ.txt +++ b/ПРОЧТИ_МЕНЯ.txt @@ -11,6 +11,8 @@ - Нужные библиотеки ставятся в папку .venv внутри программы, в систему ничего не ставится. 3. Сервер запускается в фоне, без окон, и открывается страница http://127.0.0.1:8765 . Если движок программы упадёт, он сам перезапустится через 5 секунд. +4. При первом открытии создайте учётную запись (логин 3–32 символа, пароль не короче 12 символов). + Для каждого пользователя создаются отдельные сделки, настройки, ключи и личный движок. ЗАПУСК И ОСТАНОВКА - «ЗАПУСТИТЬ_СЕРВЕР.bat» — запустить сервер (если уже работает — просто откроет страницу). @@ -29,7 +31,7 @@ - Кнопка «Калькулятор бюджета» справа вверху — сколько денег держать на биржах. ВАЖНО -- Из России биржи (Bybit, Binance, MEXC…) без VPN часто не отвечают — тогда на странице не будет цен. +- Для котировок и сканирования используются Bybit, Gate, MEXC и HTX. Binance программа не использует. Включите VPN для программы. - Сайт открывается только на этом компьютере (127.0.0.1), снаружи он недоступен — так задумано. - Реальные ордера отправляются ТОЛЬКО если вы сами сохраните API-ключи во вкладке @@ -37,6 +39,9 @@ (или включите реальный режим монеты во вкладке «Симулятор»). Ключи создавайте только с правами на торговлю, без права вывода средств. Ключи шифруются средствами Windows и читаются только вашей учётной записью на этом компьютере. +- Общая база `web_sim_data\accounts.sqlite3` хранит учётные записи и хеши паролей; личные данные лежат в + `web_sim_data\users\\data`. Первая учётная запись получает копию старых данных; остальные начинают + с отдельных пустых хранилищ. Исходные файлы при переносе не удаляются. - Спот → спот в реальном режиме продаёт монету из запаса, который лежит на бирже продажи: без запаса такие сделки не открываются. Деньги и монеты между биржами программа не переводит. - Реальная торговля — на ваш риск: начинайте с минимальных сумм. @@ -46,7 +51,8 @@ (Win+R → shell:startup → Enter). Программа будет запускаться без окон. ЕСЛИ ЧТО-ТО НЕ РАБОТАЕТ -- Страница не открывается — посмотрите журнал движка web_sim_data\backend.log +- Страница не открывается — посмотрите `web_sim_data\gateway.log`, затем личный журнал + `web_sim_data\users\\data\backend.log` (или запустите «УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat», чтобы видеть окно движка). - Нет цен — проверьте VPN. - Удалить программу — остановите сервер и удалите папку (и ярлык из автозагрузки, если ставили).