Compare commits

...
Author SHA1 Message Date
listik 45b0b3044b 1
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
2026-10-24 00:07:25 +03:00
listik 730adb3ff2 1
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
2026-10-23 23:38:37 +03:00
listik 3ae4e18211 23
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
2026-10-23 21:42:13 +03:00
listik efd4e1dcf4 linux
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
2026-10-23 21:36:08 +03:00
listik f6f1ae20c2 система авторизации
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
2026-10-23 21:14:57 +03:00
listik 85425483c0 1
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
2026-10-23 20:49:12 +03:00
103 changed files with 32910 additions and 1934 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
name: Offline regression tests
on:
push:
pull_request:
permissions:
contents: read
jobs:
windows:
runs-on: windows-latest
strategy:
matrix:
python-version: ['3.11', '3.12', '3.13']
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: pip
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: python -m pip install -r requirements.txt
- run: python -B scripts/run_tests.py
- run: node --test tests/web_context.test.cjs
- run: python -B -c "import main, websocket, numpy"
+23
View File
@@ -0,0 +1,23 @@
__pycache__/
*.py[cod]
.venv/
*.log
*.tmp
web_sim_data/
scalp_recordings/
historical_reports/
*.sqlite3*
settings.json
account_state.json
*credentials*.json
*credentials*.bin
*keys*.bin
lead_connections.json
lead_paper_state.json
lead_paper_trades.csv
scalp_hint_journal.csv
scalp_paper_state.json
scalp_paper_trades.csv
meme_matcher/autoscan_state.json
meme_matcher/autoscan_history.csv
meme_matcher/autoscan_config.json
+23
View File
@@ -0,0 +1,23 @@
__pycache__/
*.py[cod]
.venv/
*.log
*.tmp
web_sim_data/
scalp_recordings/
historical_reports/
*.sqlite3*
settings.json
account_state.json
*credentials*.json
*credentials*.bin
*keys*.bin
lead_connections.json
lead_paper_state.json
lead_paper_trades.csv
scalp_hint_journal.csv
scalp_paper_state.json
scalp_paper_trades.csv
meme_matcher/autoscan_state.json
meme_matcher/autoscan_history.csv
meme_matcher/autoscan_config.json
+90
View File
@@ -0,0 +1,90 @@
# 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.
- В режиме Certbot напрямую разрешить входящие TCP 22 (SSH), 80 и 443. В режиме TLS-шлюза разрешить только настроенный вход через шлюз к внутреннему порту 80 контейнера; порт 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 логин/пароль сервера, затем — личный логин и пароль приложения. Создание аккаунтов через сайт выключено: новых пользователей добавляет только администратор по SSH.
Подключитесь по SSH и создайте аккаунт от имени служебного пользователя:
```bash
sudo -u cryptosim /opt/crypto-scam/.venv/bin/python /opt/crypto-scam/user_admin.py create alex
```
Пароль программа запросит дважды в SSH-терминале; он не попадает в аргументы процесса или историю команд. Логин: 3–32 символа — латиница, цифры, точка, дефис или подчёркивание. Список аккаунтов:
```bash
sudo -u cryptosim /opt/crypto-scam/.venv/bin/python /opt/crypto-scam/user_admin.py list
```
После создания пользователь может войти на сайт; его личный движок запустится при первом входе. Первый SSH-созданный аккаунт получает копию старых данных, если они были перенесены.
Общий Basic Auth пароль можно сменить командой `sudo htpasswd -B /etc/nginx/crypto-scam/htpasswd ИМЯ`, затем выполнить `sudo systemctl reload nginx`.
### HTTPS на шлюзе хостинга и нестандартный внешний порт
Если провайдер принимает TLS на внешнем адресе, например `https://zdfn.my.to:25590`, и завершает его до проксирования в контейнер, используйте режим TLS-шлюза. Сначала настройте шлюз на проксирование HTTPS-only трафика в `http://192.168.144.115:80` (или актуальный приватный IP контейнера), с заголовком `Host: zdfn.my.to`. Внешний HTTP должен перенаправляться на HTTPS, а незашифрованный обходной маршрут к контейнеру должен быть закрыт.
Затем выполните из каталога проекта:
```bash
sudo ./deploy.sh zdfn.my.to --tls-proxy https://zdfn.my.to:25590
```
В этом режиме TLS-сертификат обслуживает шлюз, а Certbot внутри контейнера не запускается. Внутренний Nginx требует Basic Auth и передаёт приложению признак HTTPS. Не используйте этот режим, пока шлюз действительно не настроен на TLS и внешний HTTP-маршрут не закрыт/перенаправлен.
Для временного HTTP-доступа (не рекомендуется для реальных аккаунтов и API-ключей) можно указать `--http-proxy http://zdfn.my.to:25590`. Этот режим отправляет приложению признак HTTP и снимает `Secure` с сессионной cookie, чтобы вход мог сохраниться в браузере. Пароли, cookies и ключи будут передаваться без шифрования.
## Учётные записи, данные и API-ключи
- Общая БД аккаунтов и хешей паролей, а также пользовательские хранилища расположены в `/var/lib/crypto-scam/`. Для каждого аккаунта создаётся отдельный движок.
- Первый аккаунт, созданный по SSH, получает копию старых данных, если они находились в переносимом `web_sim_data`; исходники не удаляются. Остальные аккаунты изолированы.
- История рыночных данных сейчас отдельная для каждого пользователя. Сканеры Bybit, Gate, MEXC и HTX запускаются для каждого существующего аккаунта при старте сервиса, в том числе без открытой вкладки.
- API-ключи на Linux шифруются AES-256-GCM ключом сервера `/etc/crypto-scam/master.key`; доступ к нему есть у системной службы. Для реальной торговли нужны новые ключи: Windows DPAPI-файлы расшифровать на Linux нельзя.
- Журнал реальных ордеров и арбитража отдельный для каждого аккаунта: `real_orders.jsonl` в каталоге данных пользователя. В событиях открытия/закрытия записываются время и цена решения, время подтверждённого исполнения и средняя цена fill; для парных сделок цены/время спота и фьючерса хранятся отдельно. В веб-журнале время отображается по Москве, в JSONL также сохраняется ISO-8601 UTC.
- Включайте на бирже только необходимые права, запрещайте вывод средств и сначала проверяйте в симуляции. Публичный 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 до включения реальных ключей.
+999
View File
@@ -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
+570
View File
@@ -0,0 +1,570 @@
"""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}
+1371
View File
File diff suppressed because it is too large. Load diff
+260
View File
@@ -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", "")
+119
View File
@@ -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
+2492
View File
File diff suppressed because it is too large. Load diff
+258
View File
@@ -0,0 +1,258 @@
#!/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:-}"
MODE="certbot"
EMAIL=""
PUBLIC_URL=""
if [[ "${2:-}" == "--tls-proxy" || "${2:-}" == "--http-proxy" ]]; then
MODE="${2#--}"
PUBLIC_URL="${3:-}"
else
EMAIL="${2:-}"
fi
if [[ ! "$DOMAIN" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then
echo "Укажите домен, уже направленный DNS-записями на этот сервер: $0 example.com admin@example.com" >&2
exit 2
fi
if [[ "$MODE" == "certbot" && ! "$EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]]; then
echo "Укажите email для уведомлений Let's Encrypt: $0 example.com admin@example.com" >&2
exit 2
fi
if [[ "$MODE" == "tls-proxy" && ! "$PUBLIC_URL" =~ ^https://$DOMAIN:[0-9]{1,5}$ ]]; then
echo "Для TLS-шлюза укажите внешний HTTPS URL с портом, например: $0 zdfn.my.to --tls-proxy https://zdfn.my.to:25590" >&2
exit 2
fi
if [[ "$MODE" == "http-proxy" && ! "$PUBLIC_URL" =~ ^http://$DOMAIN:[0-9]{1,5}$ ]]; then
echo "Для HTTP-шлюза укажите внешний HTTP URL с портом, например: $0 zdfn.my.to --http-proxy http://zdfn.my.to:25590" >&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
PACKAGES=(nginx python3-venv python3-tk python3-cryptography rsync apache2-utils)
if [[ "$MODE" == "certbot" ]]; then
PACKAGES+=(certbot python3-certbot-nginx)
fi
apt-get install -y "${PACKAGES[@]}"
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" <<EOF
# Managed by Crypto Scam deploy.sh
[Unit]
Description=Crypto Scam multi-user web simulator
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=$SERVICE_USER
Group=$SERVICE_USER
WorkingDirectory=$APP_DIR
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONDONTWRITEBYTECODE=1
Environment=CRYPTO_SCAM_PUBLIC_HOST=$DOMAIN
Environment=CRYPTO_SCAM_PUBLIC_PORT=$(if [[ "$MODE" == "tls-proxy" || "$MODE" == "http-proxy" ]]; then printf '%s' "${PUBLIC_URL##*:}"; else printf '443'; fi)
Environment=CRYPTO_SCAM_PUBLIC_SCHEME=$(if [[ "$MODE" == "http-proxy" ]]; then printf 'http'; else printf 'https'; fi)
Environment=CRYPTO_SCAM_MASTER_KEY_FILE=/etc/crypto-scam/master.key
UMask=0077
ExecStart=$APP_DIR/.venv/bin/python -B web_proxy.py
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=$DATA_DIR
ReadOnlyPaths=/etc/crypto-scam/master.key
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
CapabilityBoundingSet=
LockPersonality=true
MemoryDenyWriteExecute=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable crypto-scam.service
systemctl start crypto-scam.service
install -d -o root -g www-data -m 0750 /etc/nginx/crypto-scam
{ builtin printf '%s\n' "$GATE_PASSWORD"; } | htpasswd -B -i -c /etc/nginx/crypto-scam/htpasswd "$GATE_USER"
chown root:www-data /etc/nginx/crypto-scam/htpasswd
chmod 0640 /etc/nginx/crypto-scam/htpasswd
unset GATE_PASSWORD
if [[ "$MODE" != "certbot" ]]; then
# The hosting gateway forwards traffic to this private HTTP listener.
# Managed by Crypto Scam deploy.sh
cat > "$NGINX_SITE" <<EOF
# Managed by Crypto Scam deploy.sh
server {
listen 80;
listen [::]:80;
server_name $DOMAIN;
auth_basic "Crypto Scam server access";
auth_basic_user_file /etc/nginx/crypto-scam/htpasswd;
client_max_body_size 128k;
location / {
proxy_pass http://127.0.0.1:8765;
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Proto $(if [[ "$MODE" == "http-proxy" ]]; then printf 'http'; else printf 'https'; fi);
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header Connection "";
proxy_read_timeout 75s;
proxy_send_timeout 75s;
}
}
EOF
else
# Managed by Crypto Scam deploy.sh
cat > "$NGINX_SITE" <<EOF
# Managed by Crypto Scam deploy.sh
server {
listen 80;
listen [::]:80;
server_name $DOMAIN;
location / { return 404; }
}
EOF
fi
ln -sfn "$NGINX_SITE" /etc/nginx/sites-enabled/crypto-scam-app
nginx -t
systemctl reload nginx
if [[ "$MODE" == "certbot" ]]; then
certbot certonly --nginx --non-interactive --agree-tos --email "$EMAIL" -d "$DOMAIN"
# Managed by Crypto Scam deploy.sh
cat > "$NGINX_SITE" <<EOF
# Managed by Crypto Scam deploy.sh
server {
listen 80;
listen [::]:80;
server_name $DOMAIN;
return 301 https://\$host\$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name $DOMAIN;
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
client_max_body_size 128k;
auth_basic "Crypto Scam server access";
auth_basic_user_file /etc/nginx/crypto-scam/htpasswd;
location / {
proxy_pass http://127.0.0.1:8765;
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header Connection "";
proxy_read_timeout 75s;
proxy_send_timeout 75s;
}
}
EOF
fi
nginx -t
systemctl reload nginx
systemctl restart crypto-scam.service
echo
if [[ "$MODE" == "tls-proxy" || "$MODE" == "http-proxy" ]]; then
echo "Готово после настройки шлюза: $PUBLIC_URL"
echo "Шлюз должен передавать Host=$DOMAIN и проксировать на http://192.168.144.115:80."
if [[ "$MODE" == "http-proxy" ]]; then
echo "ВНИМАНИЕ: HTTP не шифрует логины, пароли, cookies и API-ключи."
fi
else
echo "Готово: https://$DOMAIN"
fi
echo "Сначала браузер спросит общий Basic Auth пароль, затем откроется форма входа Crypto Scam."
echo "Статус сервера: systemctl status crypto-scam nginx"
echo "Логи: journalctl -u crypto-scam -f"
echo "Данные и аккаунты: $DATA_DIR"
echo "Серверный ключ шифрования: /etc/crypto-scam/master.key — обязательно резервируйте отдельно и секретно."
+201
View File
@@ -0,0 +1,201 @@
"""Tk chart rendering and viewport interaction for the desktop simulator."""
from __future__ import annotations
from datetime import datetime
import tkinter as tk
import strategy
class ChartView:
def _draw_chart(self) -> None:
if not hasattr(self, "canvas"):
return
c = self.canvas
c.delete("all")
width, height = c.winfo_width(), c.winfo_height()
if width < 80 or height < 80:
return
left, right, top, bottom = 58, width - 82, 22, height - 34
c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей")
candles = list(self.candles)
if not candles:
c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…")
return
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
low -= pad
high += pad
t0 = candles[0][0]
t1 = max(candles[-1][0] + 60, t0 + 60)
view_end = self.chart_view_end if self.chart_view_end is not None else t1
view_start = view_end - self.chart_visible_seconds
visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end]
visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end]
if visible_candles:
candles = visible_candles
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
base_span = high - low
pad = base_span * .08 if base_span else max(high * .001, 1e-8)
natural_low, natural_high = low - pad, high + pad
if self.chart_price_center is None or self.chart_price_span is None:
low, high = natural_low, natural_high
if self.chart_price_center is not None and self.chart_price_span is not None:
span = self.chart_price_span
low = self.chart_price_center - span / 2
high = self.chart_price_center + span / 2
t0 = view_start
t1 = view_end
if t1 <= t0:
return
for i in range(5):
y = top + i * (bottom - top) / 4
value = high - i * (high - low) / 4
c.create_line(left, y, right, y, fill="#263746")
c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value))
c.create_line(left, bottom, right, bottom, fill="#6c7e8c")
candle_seconds = self.interval_minutes * 60
slot = (right - left) * candle_seconds / (t1 - t0)
body_width = max(2.0, min(16.0, slot * .62))
for candle in candles:
t, open_price, high_price, low_price, close_price = candle
if t < t0 - candle_seconds or t > t1:
continue
x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left)
y_high = bottom - (high_price - low) / (high - low) * (bottom - top)
y_low = bottom - (low_price - low) / (high - low) * (bottom - top)
y_open = bottom - (open_price - low) / (high - low) * (bottom - top)
y_close = bottom - (close_price - low) / (high - low) * (bottom - top)
color = "#38d996" if close_price >= open_price else "#ef5965"
c.create_line(x, y_high, x, y_low, fill=color, width=1)
body_top, body_bottom = sorted((y_open, y_close))
if body_bottom - body_top < 1:
body_bottom = body_top + 1
c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color)
for marker_time, marker_price, trade_id in visible_markers:
if not t0 <= marker_time <= t1:
continue
x = left + (marker_time - t0) / (t1 - t0) * (right - left)
y = bottom - (marker_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1)
c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}")
position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position
if position and position.mode != strategy.STRATEGY_CLASSIC:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom,
f"Вход {position.side.upper()}", "#63a8ff")
self._draw_level(c, position.stop_price, low, high, left, right, top, bottom,
"Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42")
if position.partial_target > 0 and not position.partial_done:
self._draw_level(c, position.partial_target, low, high, left, right, top, bottom,
"Частичная фиксация", "#40d6b0")
if position.final_target > 0:
self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0")
liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side)
if liquidation is not None:
self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d")
elif position:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff")
s = self.applied_settings or self._safe_read_settings()
if s["add_step"] > 0 and position.add_count < s["max_adds"]:
next_add = position.last_add_price * (1 - s["add_step"] / 100)
self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff")
if s["stop_loss"] > 0:
stop_price = position.entry_price * (1 - s["stop_loss"] / 100)
self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42")
if s["take_profit"] > 0:
effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"]))
take_profit_price = position.entry_price * (1 + effective_tp_pct / 100)
self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0")
if self.last_price:
y = bottom - (self.last_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3))
c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M"))
c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M"))
def _chart_bounds(self) -> tuple[int, int, int, int]:
width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
return 58, width - 82, 22, height - 34
def _on_chart_wheel(self, event: tk.Event) -> None:
direction = 1 if event.delta > 0 else -1
self._zoom_chart(event.x, event.y, direction)
def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None:
self._zoom_chart(event.x, event.y, direction)
def _zoom_chart(self, x: int, y: int, direction: int) -> None:
if not self.candles:
return
old_span = self.chart_visible_seconds
factor = 0.8 if direction > 0 else 1.25
self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor))
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
left, right, top, bottom = self._chart_bounds()
fraction_x = min(1, max(0, (x - left) / max(1, right - left)))
old_start = self.chart_view_end - old_span
anchor_time = old_start + fraction_x * old_span
self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
center = (max(prices) + min(prices)) / 2
self.chart_price_center = center
self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8)
fraction_y = min(1, max(0, (y - top) / max(1, bottom - top)))
anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span
self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor)
self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span
self._draw_chart()
def _on_chart_press(self, event: tk.Event) -> None:
if not self.candles:
return
left, right, top, bottom = self._chart_bounds()
if not left <= event.x <= right or not top <= event.y <= bottom:
return
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
self.chart_price_center = (high + low) / 2
self.chart_price_span = high - low + 2 * pad
self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center,
self.chart_price_span, self.chart_visible_seconds)
self.canvas.configure(cursor="fleur")
def _on_chart_drag(self, event: tk.Event) -> None:
if not self._drag_anchor:
return
x0, y0, end0, center0, price_span, time_span = self._drag_anchor
left, right, top, bottom = self._chart_bounds()
self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span
self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span
self.chart_price_span = price_span
self._draw_chart()
def _on_chart_release(self, _event: tk.Event) -> None:
self._drag_anchor = None
self.canvas.configure(cursor="")
def _reset_chart_view(self, _event: tk.Event | None = None) -> None:
self.chart_visible_seconds = self.interval_minutes * 60 * 30
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._drag_anchor = None
self._draw_chart()
def _go_to_live(self) -> None:
"""Return the chart's right edge to the newest market candle."""
if self.candles:
self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60
else:
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._draw_chart()
+74
View File
@@ -0,0 +1,74 @@
"""Desktop account and per-symbol state, independent of Tk widgets."""
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
import strategy
@dataclass
class Position:
trade_id: int
symbol: str
entry_price: float
qty: float
stake: float
entry_fee: float
opened_at: float
last_add_price: float
add_count: int = 0
# Strategy-mode fields; classic positions keep the defaults.
side: str = "long"
mode: str = strategy.STRATEGY_CLASSIC
leverage: float = 1.0
stop_price: float = 0.0
initial_stop: float = 0.0
atr: float = 0.0
extreme: float = 0.0
partial_target: float = 0.0 # 0 = none
final_target: float = 0.0 # 0 = none
partial_done: bool = False
realized_gross: float = 0.0
realized_fees: float = 0.0
opened_stake: float = 0.0
@dataclass
class ClosedTrade:
trade_id: int
symbol: str
entry_price: float
exit_price: float
qty: float
gross_pnl: float
fees: float
net_pnl: float
roi_pct: float
opened_at: float
closed_at: float
reason: str
@dataclass
class CurrencyState:
"""Independent market and position state for one concurrently traded symbol."""
prices: deque = field(default_factory=deque)
candles: deque = field(default_factory=deque)
entry_markers: deque = field(default_factory=deque)
last_price: float | None = None
baseline_close: float | None = None
last_signal_pct: float | None = None
last_signal_ready: bool = False
previous_entry_signal_pct: float | None = None
live_minute_prices: deque = field(default_factory=deque)
last_ws_message: float = 0.0
position: Position | None = None
live_position: Position | None = None
live_position_info: dict | None = None
live_order_busy: bool = False
live_transition_pending: bool = False
live_halted: bool = False
# Strategy modes A/B: last evaluated signal candle and the signal valid until the next close.
mode_signal: dict | None = None
mode_signal_bucket: int = 0
mode_eval_busy: bool = False
+176
View File
@@ -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:<key>`;
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_<coin>.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.
+159
View File
@@ -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}
File diff suppressed because it is too large. Load diff
+139
View File
@@ -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()}
+692
View File
@@ -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("<<ComboboxSelected>>", 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("<<ComboboxSelected>>", on_market)
follow_combo.bind("<<ComboboxSelected>>", 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("<<ComboboxSelected>>", 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()
+1453
View File
File diff suppressed because it is too large. Load diff
+4558
View File
File diff suppressed because it is too large. Load diff
+105
View File
@@ -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
```
+420
View File
@@ -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()
+591
View File
@@ -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()
+714
View File
@@ -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("<Double-1>", 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()
+224
View File
@@ -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)})"
+72
View File
@@ -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)
+45
View File
@@ -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
+27
View File
@@ -0,0 +1,27 @@
"""Atomic local JSON snapshots; callers must handle write failures explicitly."""
from __future__ import annotations
import json
import os
import tempfile
from pathlib import Path
def atomic_write_json(path: Path, payload) -> None:
"""Flush a new snapshot before replacing the old file, or leave the old file intact."""
path = Path(path)
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(fd, "wb") as stream:
stream.write(encoded)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
try:
os.unlink(temporary)
except FileNotFoundError:
pass
+683
View File
@@ -0,0 +1,683 @@
"""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_<coin>.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 datetime import datetime, timezone
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}
# Keep epoch seconds for calculations and an ISO-8601 UTC rendering for humans.
for key, value in tuple(event.items()):
if key.endswith("_time") and isinstance(value, (int, float)) and not isinstance(value, bool):
event[f"{key}_utc"] = datetime.fromtimestamp(value, timezone.utc).isoformat(timespec="milliseconds")
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(),
"decision_open_time": pos.opened, "decision_open_price": pos.entry / units,
# 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.position["decision_close_time"] = getattr(pos, "close_decision_time", time.time())
self.position["decision_close_price"] = getattr(pos, "close_decision_price", 0.0)
self.position["decision_close_reason"] = getattr(pos, "close_reason", "закрыта в симуляторе")
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.).
fill_time = time.time()
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, actual_open_time=fill_time,
actual_open_price=fill.price)
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,
decision_open_time=pos.get("decision_open_time"), decision_open_price=pos.get("decision_open_price"),
actual_open_time=pos.get("actual_open_time"), actual_open_price=pos.get("actual_open_price"))
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, "time": time.time()})
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, "time": time.time()})
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)
closed_at = time.time()
trade = {"side": pos["side"], "coins": coins, "entry": pos.get("entry", 0.0), "exit": exit_price,
"opened": pos["opened"], "closed": closed_at, "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"],
decision_open_time=pos.get("decision_open_time"), decision_open_price=pos.get("decision_open_price"),
actual_open_time=pos.get("actual_open_time"), actual_open_price=pos.get("actual_open_price"),
decision_close_time=pos.get("decision_close_time"), decision_close_price=pos.get("decision_close_price"),
actual_close_time=closed_at, actual_close_price=exit_price,
actual_close_fill_time=max((f.get("time", closed_at) for f in fills), default=closed_at))
# --- 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:]))}
+56
View File
@@ -0,0 +1,56 @@
"""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(".")
PUBLIC_PORT = int(os.environ.get("CRYPTO_SCAM_PUBLIC_PORT", "443"))
PUBLIC_SCHEME = os.environ.get("CRYPTO_SCAM_PUBLIC_SCHEME", "https").strip().lower()
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() != PUBLIC_SCHEME
or host[1] not in (80, 443, PUBLIC_PORT)):
return False
origins = handler.headers.get_all("Origin", [])
if len(origins) > 1:
return False
if origins:
try:
origin = urlsplit(origins[0])
expected_scheme = PUBLIC_SCHEME if is_public else "http"
origin_authority = _authority(origin.netloc)
if (origin.scheme != expected_scheme or origin.path or origin.query or origin.fragment
or origin_authority is None or origin_authority[0] != host[0]
or (not is_public and origin_authority != host)):
return False
except ValueError:
return False
if handler.headers.get("Sec-Fetch-Site") == "cross-site":
return False
return not command or handler.headers.get("X-Sim") == "1"
+3
View File
@@ -0,0 +1,3 @@
# Python 3.11+
websocket-client==1.8.0
numpy==2.3.5
+45
View File
@@ -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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+396
View File
@@ -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
+60
View File
@@ -0,0 +1,60 @@
"""SSH-only account administration for the Linux deployment."""
from __future__ import annotations
import argparse
import getpass
import os
import sys
from pathlib import Path
from user_auth import AuthError, UserStore
if os.name != "nt":
os.umask(0o077)
ROOT = Path(__file__).resolve().parent
STORE = UserStore(ROOT / "web_sim_data")
def create(username: str) -> int:
if os.name != "nt" and os.geteuid() == 0:
print("Не запускайте от root. Используйте sudo -u cryptosim.", file=sys.stderr)
return 2
password = getpass.getpass("Пароль (12–256 символов): ")
confirm = getpass.getpass("Повторите пароль: ")
if password != confirm:
print("Пароли не совпадают.", file=sys.stderr)
return 2
try:
user_id = STORE.register(username, password)
# Carry over legacy single-user data only for the first account, without deleting the source.
if STORE.mark_legacy_imported():
from web_proxy import _import_legacy_data
_import_legacy_data(STORE.data_dir(user_id))
except AuthError as exc:
print(f"Не удалось создать пользователя: {exc}", file=sys.stderr)
return 2
print(f"Создан пользователь {username}. Его личный движок запустится при первом входе на сайт.")
return 0
def main() -> int:
parser = argparse.ArgumentParser(description="Управление аккаунтами Crypto Scam (только SSH)")
commands = parser.add_subparsers(dest="command", required=True)
make = commands.add_parser("create", help="создать пользователя")
make.add_argument("username")
commands.add_parser("list", help="показать имена пользователей")
args = parser.parse_args()
if args.command == "create":
return create(args.username)
if os.name != "nt" and os.geteuid() == 0:
print("Выполните от пользователя cryptosim: sudo -u cryptosim ...", file=sys.stderr)
return 2
users = [STORE.username(user_id) for user_id in STORE.user_ids()]
print("\n".join(users) if users else "Пользователей пока нет.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+136
View File
@@ -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
+245
View File
@@ -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()
+179
View File
@@ -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; } }
File diff suppressed because it is too large. Load diff
+148
View File
@@ -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 минут меняют только окно графика. Время на странице — московское (МСК)."]
];
+78
View File
@@ -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 <dialog> 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();
});
}
+399
View File
@@ -0,0 +1,399 @@
"""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")
and os.environ.get("CRYPTO_SCAM_PUBLIC_SCHEME", "https").lower() == "https" 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"""<!doctype html><html lang="ru"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
<title>Вход · Crypto Scam</title><style>
body{{margin:0;background:#10141d;color:#e8eef9;font:16px system-ui;display:grid;place-items:center;min-height:100vh}}
main{{width:min(420px,calc(100% - 36px));background:#1a202c;border:1px solid #303a4a;border-radius:14px;padding:26px;box-sizing:border-box}}
h1{{font-size:22px;margin:0 0 6px}}p{{color:#9aa9bf;font-size:14px}}label{{display:block;margin:16px 0 6px;color:#b9c7db}}
input{{box-sizing:border-box;width:100%;padding:11px;border-radius:7px;border:1px solid #39475a;background:#10141d;color:white;font-size:16px}}
button{{margin-top:20px;width:100%;padding:11px;border:0;border-radius:7px;background:#3b82f6;color:white;font-size:16px;cursor:pointer}}
.error{{color:#ff8b8b;min-height:20px}}.note{{color:#9aa9bf;font-size:13px;margin-top:16px}}
</style><main><h1>Crypto Scam</h1><p id="modeText">Войдите в свой аккаунт</p><div class="error">{safe}</div>
<form method="post" action="/auth/login"><label>Логин</label><input name="username" required minlength="3" maxlength="32" autocomplete="username">
<label>Пароль</label><input name="password" type="password" required minlength="12" maxlength="256" autocomplete="current-password">
<button>Войти</button></form><p class="note">Нового пользователя может создать администратор через SSH.</p></main></html>"""
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 == "/auth/register":
self._send(403, _login_page("Регистрация через сайт отключена. Обратитесь к администратору."))
return
if path == "/auth/login":
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", ""))
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()
+171
View File
@@ -0,0 +1,171 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Симулятор опережения</title>
<link rel="stylesheet" href="/static/app.css">
</head>
<body>
<nav class="tabs">
<button id="tabSim" class="tab on" onclick="showTab('sim')">Симулятор</button>
<button id="tabArb" class="tab" onclick="showTab('basis')">Арбитраж</button>
<button id="tabReal" class="tab" onclick="showTab('real')">Реальная торговля · API-ключи</button>
<button id="helpBtn" class="help-btn" onclick="helpOpen()" aria-haspopup="dialog" aria-controls="helpDialog">Справка</button>
<button id="calcBtn" class="calcbtn" onclick="calcToggle()" title="Сколько денег нужно на бирже под ставку, число сделок и запас до ликвидации">🧮 Калькулятор бюджета</button>
</nav>
<div class="system-status" aria-live="polite">
<strong id="modeStatus" class="mode-status">СИМУЛЯЦИЯ · общий виртуальный счёт</strong>
<span id="connectionStatus" class="connection-status disconnected">Подключение к серверу…</span>
</div>
<div id="commandNotice" class="command-notice" role="status" hidden></div>
<section id="paperAccount" class="paper-account" aria-labelledby="accountTitle">
<div class="account-heading"><h2 id="accountTitle">Общий виртуальный счёт</h2><span class="paper-badge">ВИРТУАЛЬНЫЕ ДЕНЬГИ</span></div>
<div class="account-metrics">
<div><span>Баланс</span><strong id="account-balance">—</strong><small>Проведённые операции и результат</small></div>
<div><span>Капитал (Equity)</span><strong id="account-equity">—</strong><small>Баланс + результат открытых позиций</small></div>
<div><span>Зарезервировано</span><strong id="account-reserved">—</strong><small>Средства под открытые сделки</small></div>
<div><span>Свободно</span><strong id="account-free">—</strong><small>Доступно для следующих входов</small></div>
</div>
<p id="accountHealth" class="statusline">Один счёт для всех виртуальных сделок. Реальные деньги бирж учитываются отдельно.</p>
<div class="controls">
<div class="field"><label for="accountDelta">Сумма изменения, $</label><input id="accountDelta" inputmode="decimal" placeholder="Например 100" autocomplete="off"></div>
<button class="primary" data-command="account" data-account-direction="1" onclick="adjustAccount(1)">Пополнить</button>
<button data-command="account" data-account-direction="-1" onclick="adjustAccount(-1)">Списать</button>
<span id="accountMsg" class="statusline" role="status"></span>
</div>
<details class="account-journal"><summary>Журнал виртуального счёта</summary>
<div class="tablewrap"><table><thead><tr><th>Время (МСК)</th><th>Операция</th><th>Изменение, $</th><th>Баланс, $</th></tr></thead><tbody id="accountJournal"><tr><td colspan="4" class="empty">Загрузка…</td></tr></tbody></table></div>
</details>
</section>
<dialog id="helpDialog" class="help-dialog" aria-labelledby="helpTitle">
<div class="help-heading"><div><h2 id="helpTitle">Справка</h2><p>Термины, режимы и все настройки интерфейса</p></div><button class="help-close" onclick="helpClose()" aria-label="Закрыть справку">×</button></div>
<label for="helpSearch" class="help-search-label">Поиск по названию, термину или ключу настройки</label>
<input id="helpSearch" class="help-search" type="search" placeholder="Например: плечо, свободно, IOC, stop_loss_pct" autocomplete="off" oninput="renderHelp()">
<p id="helpCount" class="statusline" role="status"></p>
<div id="helpContent" class="help-content"></div>
</dialog>
<div id="calcPanel" class="calcpanel" style="display:none">
<div class="calchead"><b>Калькулятор бюджета</b><button class="x" onclick="calcToggle()" title="Закрыть">×</button></div>
<div class="calcgrid">
<div class="field"><label>Ставка (сумма сделки), $</label><input id="cStake" value="10"></div>
<div class="field"><label>Сделок одновременно на бирже</label><input id="cCount" value="3"></div>
<div class="field"><label>Желаемый рост цены до ликвидации, %</label><input id="cLiq" value="50"
title="На сколько % может вырасти монета, прежде чем биржа ликвидирует шорт"></div>
<div class="field"><label>Бирж с деньгами</label><input id="cEx" value="2"></div>
<div class="field"><label>Поддерж. маржа, %</label><input id="cMmr" value="1" title="Ставка поддерживающей маржи биржи; программа считает с 1%"></div>
<div class="field"><label>Запас на комиссии спота, %</label><input id="cFee" value="1"></div>
</div>
<button onclick="calcFromSettings()" style="margin-top:8px" title="Ставка, лимит сделок и мин. запас до ликвидации из «Арбитраж · Реальная торговля»">Взять из настроек реальной торговли</button>
<div id="calcOut" class="calcout"></div>
</div>
<div id="realView" style="display:none">
<section class="center">
<div class="card"><span class="name" style="font-size:18px;font-weight:700">Реальная торговля: API-ключи бирж</span>
<div class="statusline" style="margin-top:6px">Ключи хранятся в зашифрованном виде на сервере; на страницу секрет не возвращается.
В Linux-сборке защита API-ключей использует AES-256-GCM и системный ключ, доступный службе приложения. Доступ к сайту идёт через
HTTPS и внешний шлюз входа. Создавайте ключи <b>только с правами на торговлю, без вывода средств</b>, и по возможности
привязывайте их к своему IP. Реальный режим включается отдельно: во вкладке «Симулятор» (фьючерсы монеты) и во
вкладке «Арбитраж» → «Реальная торговля» (своя кнопка «Старт»).</div></div>
<div class="card"><div id="keyCards" class="keygrid"></div></div>
<div class="card"><h2>Журнал реальных ордеров (обе вкладки)</h2>
<div class="tablewrap" style="max-height:50vh"><table><thead><tr><th>Время (МСК)</th><th>Вкладка</th><th>Биржа</th>
<th>Монета</th><th>Действие</th><th>Результат</th></tr></thead><tbody id="realJournal"></tbody></table></div></div>
</section>
</div>
<div id="basisView" style="display:none">
<section class="center">
<div class="card coinhead"><div>
<span class="name" id="bxTitle">Спот-фьюч: купить спот дешевле фьючерса + шорт той же суммы, закрыть при схождении</span>
<div class="range" id="bxTabs" style="margin-top:8px"></div>
<div class="statusline" id="bxStatus" style="margin-top:6px">загружаю…</div></div>
<div class="controls"><button id="bxRun" onclick="basisRun()">…</button>
<button id="bxReal" onclick="basisReal()" title="Настоящие ордера с API-ключами этой биржи">…</button>
<button onclick="basisReset()" title="Очистить историю закрытых сделок; общий виртуальный счёт не меняется">↺ Сбросить статистику</button></div></div>
<div class="card">
<div class="controls" id="bxSettings"></div>
<div class="controls" style="margin-top:8px">
<button class="primary" onclick="basisSave()">Сохранить настройки</button>
<span class="statusline" id="bxMsg"></span></div>
<div class="statusline" style="margin-top:8px" id="bxHelp">Вход: фьючерс (bid) дороже спота (ask) на «Мин. расхождение» и не больше «Макс.» —
покупается монета на споте на «Сумму» и шортится столько же монет на бессрочном фьючерсе. Выход: когда разница
(фьючерс ask / спот bid) сойдётся до «Закрыть при» — обе ноги закрываются по рынку. Комиссии: 4 сделки по рынку;
funding шорт получает (если ставка > 0) на каждом расчёте, пока позиция открыта.</div>
</div>
<div class="card" id="cxBalCard" style="display:none"><h2>Биржи: балансы, комиссии, участие в поиске</h2>
<div class="tablewrap"><table><thead><tr><th>Биржа</th>
<th title="Выключенная биржа не участвует ни в поиске связок, ни в сделках; уже открытые позиции на ней закрываются как обычно">Искать и торговать</th>
<th>Спот USDT</th><th>Фьючерсы USDT</th>
<th title="Монеты, купленные открытыми реальными позициями (по текущей цене) — их нет в USDT-балансе">Монеты в позициях, $</th>
<th>Итого, $</th><th title="Изменение с момента запуска (кнопка «Старт» в реальном режиме)">С запуска</th>
<th title="Открытые сделки, где биржа участвует (спотом или шортом) / лимит. Сделка считается на обеих своих биржах. Новая сделка не откроется, если хотя бы на одной из двух её бирж лимит занят">Сделок открыто / макс.</th>
<th title="Тейкер-комиссия спота, %. После каждой реальной сделки сама становится той, что взяла биржа (если включено)">Комиссия спот, %</th>
<th title="Тейкер-комиссия фьючерса, %">Комиссия фьюч, %</th></tr></thead><tbody id="cxBal"></tbody>
<tfoot id="cxBalTotal"></tfoot></table></div>
<div class="controls" style="margin-top:8px"><button onclick="crossFeesSave()">Сохранить комиссии и лимиты</button>
<span class="statusline" id="cxBalMsg"></span></div>
</div>
<div class="card"><div class="stats" id="bxStats"></div></div>
<div class="card"><h2>Открытые позиции</h2>
<div class="controls" style="margin-bottom:8px" id="bxAdoptBox">
<div class="field"><label>Подхватить монету с баланса биржи</label><input id="bxAdopt" placeholder="например SI" style="width:110px"></div>
<div class="field"><label>Цена покупки (пусто — текущая)</label><input id="bxAdoptPrice" style="width:110px"></div>
<button onclick="basisAdopt()" title="Монеты, которые уже лежат на спотовом счёте, становятся позицией программы: она откроет к ним шорт и закроет обе ноги при схождении">Подхватить</button>
<span class="statusline" id="bxAdoptMsg"></span></div>
<div class="tablewrap"><table><thead id="bxPosHead"><tr><th>Время (МСК)</th><th>Монета</th><th>Монет</th><th>Спот куплен</th>
<th>Фьюч шорт</th><th>Разница при входе</th><th>Разница сейчас</th><th>Funding $</th><th>Комиссии $</th>
<th>Если закрыть сейчас</th><th></th></tr></thead><tbody id="bxPos"></tbody></table></div></div>
<div class="card"><h2 id="bxCount">Монеты</h2>
<div class="tablewrap" style="max-height:60vh"><table><thead id="bxRowsHead"><tr>
<th data-b="base">Монета</th><th data-b="spot_ask">Покупка (ask)</th><th data-b="fut_bid">Продажа (bid)</th>
<th data-b="entry_gap">Расхождение для входа</th><th data-b="exit_gap">Для выхода</th>
<th data-b="net_if_closed_pct" title="Если разница сойдётся до «Закрыть при»: вход минус выход минус 4 комиссии">Чистыми при схождении</th>
<th data-b="funding_pct">Funding</th><th data-b="depth">Объём по ценам, $</th>
<th data-b="min_entry" title="Минимальная сумма сделки, которую примут обе ноги: покупка на споте и шорт на фьючерсе (мин. ордер, мин. лот). Если «Сумма сделки» меньше — монета не торгуется ни на бумаге, ни реально">Мин. вход, $</th>
<th data-b="turnover">Оборот 24ч</th>
<th data-b="age_days">Фьючерсу, дней</th><th>Группа</th><th></th></tr></thead><tbody id="bxRows"></tbody></table></div></div>
<div class="card"><h2>Закрытые сделки</h2>
<div class="tablewrap"><table><thead><tr><th>Закрыта (МСК)</th><th>Монета</th><th>Держали</th><th>Вход → выход</th>
<th>Спот $</th><th>Фьюч $</th><th>Комиссии $</th><th>Funding $</th><th>Итог $</th><th>Итог %</th><th>Причина</th></tr></thead>
<tbody id="bxTrades"></tbody></table></div></div>
</section>
</div>
<div id="simView">
<header>
<div class="title">
<h1>Симулятор опережения: ведущая биржа → ставки на фьючерсах</h1>
<span class="hint" id="simRealHint">виртуальные сделки, ордера на биржи не отправляются</span>
</div>
<div class="realbar" id="simReal">
<b>Реальная торговля</b>
<span class="mut">включается для каждой монеты отдельно — кнопкой на странице монеты; её позиции повторяются настоящими рыночными ордерами (сумма = «Ставка» × плечо)</span>
<label class="check" title="Стоп-лосс уходит вместе со входом; тейк-профит — лимитный reduce-only ордер от реальной цены входа (не ближе двух комиссий). Позиция закроется, даже если программа или связь упадут"><input type="checkbox" id="simRealTpsl" onchange="simRealTpsl()">TP/SL на бирже (Bybit, MEXC)</label>
<label class="check" title="Если биржа ответила «не хватает баланса», недостающие USDT переводятся со спотового счёта на фьючерсный — следующая сделка пройдёт"><input type="checkbox" id="simRealTransfer" onchange="simRealTransfer()">Автоперевод USDT спот → фьючерсы</label>
<div class="field"><label>Стоп-лосс на бирже, %</label><input id="simRealSl" style="width:60px" onchange="simRealSl()"></div>
<div class="field" title="Пока задержка до биржи выше порога, сделка не открывается (ни бумажная, ни реальная): ордер пришёл бы поздно и исполнился бы далеко от цены сигнала. 0 — не проверять."><label>Макс. пинг до биржи, мс</label><input id="simRealPing" style="width:60px" onchange="simRealPing()"></div>
<span class="mut" id="simRealFees"></span>
<span class="mut">· по каждой монете одна реальная сделка за раз: следующая — только когда биржа подтвердила, что прошлая закрыта</span>
<span id="simRealMsg" class="statusline"></span>
</div>
<div class="settings" id="settingsMain"></div>
<div class="settings more" id="settingsMore"></div>
<div style="margin-top:8px; display:flex; gap:8px; align-items:center;">
<button class="primary" onclick="saveSettings()">Применить ко всем монетам</button>
<button onclick="toggleMore()" id="moreBtn">Ещё настройки ▾</button>
<a href="/auth/logout" style="margin-left:auto;color:#9dbdff">Выйти из аккаунта</a>
<span id="settingsMsg"></span>
</div>
</header>
<main>
<aside>
<h2>Монеты на проверке</h2>
<div id="tiles"></div>
</aside>
<section class="center" id="center"><div class="empty">Выберите монету слева</div></section>
</main>
</div>
<script src="/static/help-data.js"></script>
<script src="/static/help.js"></script>
<script src="/static/app.js"></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
+66 -16
View File
@@ -4,11 +4,13 @@
> Важно: это исследовательский симулятор, а не рекомендация по торговле. Бумажные результаты не гарантируют прибыль в реальном рынке.
Для отдельного развёртывания веб-версии на Ubuntu 24.04 см. [LinuxServer/README.md](LinuxServer/README.md). Windows-запуск остаётся прежним.
## Что умеет проект
- **Симулятор опережения**: сравнивает цену ведущего источника с ценой фьючерса и моделирует входы/выходы.
- **Автоподбор мем-монет**: сканирует поддерживаемые 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 +20,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` для страницы авторизации. Личные движки пользователей запускаются на отдельных локальных портах.
## Установка и первый запуск
@@ -28,20 +30,16 @@
### Установка вручную через PowerShell
Python 3.11+; dependencies are pinned in `requirements.txt`. Recovery semantics, module layout and offline tests: [docs/reliability.md](docs/reliability.md).
```powershell
cd C:\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`. При первом запуске создайте пользователя; далее входите с его логином и паролем. Шлюз автоматически поднимет отдельный движок.
## Запуск и остановка
@@ -58,11 +56,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` — общие настройки, `<coin>.json` — состояние бумажного счёта, `<coin>.csv` — журнал сделок, `backend.log` — журнал движка.
Данные учётных записей хранятся в `web_sim_data/accounts.sqlite3`. Данные каждого пользователя, включая настройки, сделки, состояния и сохранённые ключи, изолированы в `web_sim_data/users/<id>/data/`; журнал личного движка — `backend.log`. Публичные сканеры и накопление рыночных данных запускаются по Bybit, Gate, MEXC и HTX. Сейчас история тоже хранится отдельно для каждого пользователя; общий кэш может быть добавлен отдельно.
### Учётные записи и перенос старых данных
- Регистрация доступна на локальной странице при первом запуске. Пароль не хранится открытым текстом: в общей БД лежит PBKDF2-хеш; сессия ограничена по времени.
- Только самая первая учётная запись получает копию прежних однопользовательских данных. Исходные файлы не удаляются. Остальные пользователи начинают с чистого личного хранилища.
- Сохранённые API-ключи остаются защищены Windows DPAPI и доступны только той Windows-учётной записи, под которой запущена программа. Пользовательские папки не заменяют права доступа Windows.
- Перед обновлением остановите старую версию через `ОСТАНОВИТЬ_СЕРВЕР.bat` и проверьте активные реальные позиции. При остановке сервер предупредит об открытых позициях; сначала убедитесь, что их можно оставить без наблюдения.
- Веб-интерфейс по-прежнему слушает только `127.0.0.1`; внешний сетевой доступ не настроен. Рыночные данные собираются через Bybit, Gate, MEXC и HTX. Binance отключён.
## Основные режимы
@@ -88,6 +94,50 @@ py -3 -m venv .venv
`scalp_paper.py` и `algo_hunter.py` содержат экспериментальные модели по стакану, imbalance, микроцене и повторяющимся заявкам. Они предназначены для dry-run и анализа: видимый агрегированный стакан не позволяет надёжно доказать наличие конкретного маркет-мейкера или реальную очередь исполнения.
## Веб-интерфейс: виртуальный счёт, сделки и управление режимами
**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 «Арбитраж → Симуляция»
use **one virtual account**, persisted in `web_sim_data/virtual_account.json`. The Tk window
(`py -3 scalp_hint.py`) and the main desktop application keep their separate accounts.
The «Общий виртуальный счёт» panel shows balance, equity, reserved capital and free capital. Enter a positive
amount and click «Пополнить» to add it or «Списать» to subtract it; the journal shows recent operations newest
first. These are virtual adjustments, not exchange transfers, and do not change the recorded trading result.
Free capital is `max(0, min(balance, equity) - reserved)`: unrealized profits cannot fund another entry, while
unrealized losses reduce the available amount. Every paper entry must fit the shared capital limit, including
its reserve and fees. Withdrawals cannot exceed free capital and are refused if an open position's valuation
is older than 30 seconds. Deposits remain available with a working connection. The initial deposit comes once
from the old common budget (default 300 $); initial balances of individual coins are not added together.
Open paper positions, their reserved capital and strategy exit state survive a restart. The shared account
snapshot is authoritative for the attached coin and paper-arbitrage engines; old closed trades remain available
as history. Restored valuations remain stale until fresh quotes arrive. «Сбросить статистику» does not replenish
the virtual account and is refused while the selected engine has open positions or unfinished real execution.
Changing a coin between simulation and real trading also requires both modes to be free of open positions and
unfinished orders. Real mode uses a **separate private signal ledger**, not the common virtual wallet: virtual
top-ups, withdrawals and paper profits cannot change real order sizing or allow real entries. Exchange balances
and the real execution gate determine whether those orders can be sent.
The top status bar distinguishes the selected mode from connection health. A failed initial request is retried
by the read polling loop; missing or stale server data disables commands until reconnection. Submitted trading
commands are never automatically retried. The separate «Справка» button opens a searchable reference covering
terms, every exposed setting, strategy modes, account controls, API keys, the scanner and the budget calculator.
Common coin settings are applied with «Применить ко всем монетам» and stored in `web_sim_data/settings.json`;
the first start copies the Tk window's settings. The former editable per-coin budget is replaced by the shared
account controls. Arbitrage simulation and real trading retain separate settings and unsaved drafts when
switching between them in the current browser page. Coin tiles show the trading status, open positions, price,
result and win rate. The centre shows both prices as percentage changes over 1/5/10 minutes, entry/exit markers,
the selected coin's statistics, Start/Stop, «Закрыть все позиции» and the trade table. Open positions appear in
yellow with a close button; closed trades follow newest first.
The last tile «+» opens the **scanner panel**: start/stop of `meme_matcher/autoscan.py`, its log and checked coins.
«+ Добавить» adds a supported pool/futures pair stopped and ready to test. «Добавлять найденные автоматически»
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-ключи
Используйте реальную торговлю только после проверки в симуляции и на Testnet.
@@ -102,11 +152,11 @@ py -3 -m venv .venv
В проекте предусмотрены отдельные состояния виртуального и реального счёта. Они не смешиваются. Для реального режима учитывайте funding, проскальзывание, минимальный размер ордера, задержку сети и риск ликвидации при усреднении или плече.
## VPN, внешний доступ и безопасность
## Локальный адрес, VPN и безопасность
- Если биржи не отдают цены, проверьте VPN и доступ к публичным API.
- По умолчанию страница доступна только локально через `127.0.0.1`; это безопаснее, чем открывать её в интернет.
- Для внешнего доступа потребуется настройка прокси, проброс TCP-порта `8765` и правило Windows Firewall. Не публикуйте интерфейс без аутентификации.
- Шлюз и личные движки слушают только локальные адреса `127.0.0.1`; интерфейс не предназначен для публикации в интернете.
- Не пробрасывайте порт `8765` наружу: для удалённого доступа потребуются TLS, сетевой шлюз и дополнительная защита сессий.
- Не коммитьте API-ключи, файлы состояния и журналы с чувствительными данными в публичный репозиторий.
## Тесты
@@ -121,8 +171,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/<id>/data/backend.log`, затем выполните `ОСТАНОВИТЬ_СЕРВЕР.bat` и `ЗАПУСТИТЬ_СЕРВЕР.bat`.
- Нет цен: проверьте интернет, VPN и доступ к API бирж.
- Не ставятся зависимости: проверьте интернет и наличие Python, затем повторите установку.
- Реальная сделка открыта: не останавливайте приложение, пока не проверили позицию и защитные ордера на бирже.
+62 -8
View File
@@ -527,6 +527,38 @@ class AlgoHunterPolicy:
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)
@@ -669,6 +701,9 @@ class AlgoHunterPolicy:
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:
@@ -767,13 +802,14 @@ class AlgoHunterPolicy:
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)
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)
if trade.size > consumed or order.ahead <= 0:
self._fill(trader, trade.ts)
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:
@@ -790,6 +826,7 @@ class AlgoHunterPolicy:
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,
@@ -797,16 +834,26 @@ class AlgoHunterPolicy:
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) -> None:
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"
trader.ledger.open(self.ticker, order.side, order.price, now, sh.MAKER_FEE_PCT, 0.0, None, order.price,
order.scenario)
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 = order.price + (1 if long else -1) * self.cfg.tp_ticks * self.tick
self.stop = order.price - (1 if long else -1) * self.cfg.sl_ticks * self.tick
self.target, self.stop = target, stop
trader.ledger.position.target = self.target
trader.ledger.position.stop = self.stop
self.guard.on_entry(now)
@@ -815,6 +862,7 @@ class AlgoHunterPolicy:
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:
@@ -828,7 +876,10 @@ class AlgoHunterPolicy:
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
@@ -855,6 +906,7 @@ class AlgoHunterPolicy:
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)."""
@@ -874,6 +926,8 @@ class AlgoHunterPolicy:
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:
+9 -16
View File
@@ -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)
+2 -1
View File
@@ -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
+492 -88
View File
@@ -27,6 +27,8 @@ 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
import time
@@ -38,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
@@ -153,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
@@ -175,6 +177,8 @@ class CrossSettings:
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
@@ -217,6 +221,9 @@ class CrossPosition:
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:
@@ -394,14 +401,27 @@ def _quote_now(l: "Link", usd: float) -> tuple[float, float, float, float, float
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) -> None:
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] = []
@@ -431,6 +451,7 @@ class CrossEngine:
# 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
@@ -459,6 +480,22 @@ class CrossEngine:
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()
@@ -470,14 +507,28 @@ class CrossEngine:
# --- 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():
@@ -491,11 +542,16 @@ class CrossEngine:
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)."""
@@ -551,7 +607,11 @@ class CrossEngine:
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:
@@ -595,17 +655,92 @@ class CrossEngine:
except OSError:
pass
def save(self) -> None:
self.file.parent.mkdir(exist_ok=True)
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}}
tmp = self.file.with_suffix(".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(self.file)
"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):
@@ -641,7 +776,9 @@ class CrossEngine:
self.save()
return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под "
f"одним тикером). Установлено {basis.HARD_MAX_GAP_PCT:g}%, остальное сохранено")
self.save()
if not self.save():
return self.account_error
self.account_error = ""
return ""
def _set_fees(self, given) -> str:
@@ -669,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:
@@ -938,10 +1075,12 @@ class CrossEngine:
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 and base not in self.opening:
if (info.get("key") in self.links or info.get("link")) and base not in self.opening and time.time() >= info.get("retry_at", 0):
self.opening.add(base)
self.pending[base] = info
del self.recover[base]
self.jobs.put(("recover", base, info))
if s.real:
@@ -951,11 +1090,12 @@ class CrossEngine:
# links itself); the hot links are refreshed in between by the hot watch
rows = self.candidates(now)
self.cand, self.cand_time = {r["key"]: r for r in rows}, now
real_busy = s.real and (self.opening or now < self.real_pause_until or self.waiting_baseline(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()
self.save(event="Арбитраж: обновление позиций и funding")
BASELINE_WAIT_S = 60.0
@@ -977,8 +1117,8 @@ class CrossEngine:
for r in rows:
self.cand[r["key"]] = r
s = self.settings
if s.running and not (s.real and (self.opening or now < self.real_pause_until
or self.waiting_baseline(now))):
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()
@@ -997,10 +1137,18 @@ class CrossEngine:
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:
pos.funding += pos.qty * (l.fut_bid + l.fut_ask) / 2 * l.funding # the short receives positive
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
@@ -1043,48 +1191,85 @@ class CrossEngine:
else:
if self._schedule_paper_close(pos.uid, reason):
changed = True
elif self.account_error:
return False
return changed
def _paper_delay(self) -> float:
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
return max(0.0, float(self.settings.simulation_execution_delay_ms)) / 1000.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()
delay = self._paper_delay(closing=True)
if delay <= 0:
self._paper_close(uid, reason)
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) -> None:
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
return False
l = self.links.get(pos.key)
if l is None:
return
self._close(pos, l, time.time(), reason)
self.save()
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) -> None:
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
return False
l = self.links.get(key)
if l is None or l.spot_ask <= 0 or l.fut_bid <= 0:
return
now = time.time()
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
@@ -1094,12 +1279,21 @@ class CrossEngine:
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
self.save()
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] = {}
@@ -1113,6 +1307,8 @@ class CrossEngine:
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:
@@ -1124,12 +1320,15 @@ class CrossEngine:
self.paper_opening.add(l.base)
delay = self._paper_delay()
if delay <= 0:
self._paper_open(l.base, l.key, r["usual"], s.amount, now)
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
@@ -1172,8 +1371,9 @@ class CrossEngine:
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()
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 ---------
@@ -1239,7 +1439,7 @@ class CrossEngine:
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) -> None:
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,
@@ -1247,6 +1447,10 @@ class CrossEngine:
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:
@@ -1264,18 +1468,24 @@ class CrossEngine:
l = self.links.get(pos.key)
if l is None:
continue
self._schedule_paper_close(pos.uid, "вручную")
if self._schedule_paper_close(pos.uid, "вручную"):
n += 1
self.save()
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 {}
self.save()
if not self.save():
return self.account_error
return "статистика сброшена"
# --- real orders (worker thread; never under the engine lock while waiting for an exchange) ------------------
@@ -1309,8 +1519,91 @@ class CrossEngine:
elif kind in ("open", "recover"):
base = args[0].base if kind == "open" else args[0]
self.opening.discard(base)
if self.pending.pop(base, None) is not None:
info = self.pending.pop(base, None)
if info is not None:
# Only preparation is certainly unsent. Every later stage survives errors and restart.
if info.get("phase") != "prepared":
info["retry_at"] = time.time() + 5
self.recover[base] = info
try:
self.save()
except (OSError, ValueError) as exc:
self.real_pause_until = time.time() + 60
self.real_pause_reason = f"не удалось сохранить восстановление: {exc}"
def _pending_update(self, base: str, **values) -> None:
with self.lock:
before = dict(self.pending[base])
self.pending[base].update(values)
try:
self.save()
except Exception:
self.pending[base] = before
raise
def _pending_done(self, base: str) -> None:
with self.lock:
pending, recovering = self.pending.pop(base, None), self.recover.pop(base, None)
self.last_close[base] = time.time()
try:
self.save()
except Exception:
if pending is not None:
self.pending[base] = pending
if recovering is not None:
self.recover[base] = recovering
raise
def _pending_problem(self, base: str, text: str) -> None:
with self.lock:
info = self.pending[base]
changed = info.get("error") != text
info["error"] = text
self.save()
if changed:
self._journal(base, "recover", False, text + "; новые реальные входы заблокированы")
def _cancel_entry(self, l: Link, cb, oid: str) -> dict | None:
"""A cancel acknowledgement is not terminal confirmation; never hedge a still-working entry."""
import live
try:
state = cb.fut_order_status(l.fut_symbol, oid)
if state["final"]:
return state
except live.LiveError:
pass
try:
cb.fut_cancel(l.fut_symbol, oid)
except live.LiveError:
pass
try:
state = cb.fut_order_status(l.fut_symbol, oid)
if state["final"]:
return state
except live.LiveError:
pass
self._pending_problem(l.base, f"не подтверждена отмена входа {oid} на {l.fut_ex}; повторяю сверку")
return None
def _rollback_entry(self, l: Link, cb) -> None:
"""Retain the durable entry until the exchange confirms the short has actually gone."""
import live
try:
held = cb.fut_position(l.fut_symbol)
if held < -1e-12:
try:
cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True)
except live.LiveError as exc:
if not exc.sent:
raise
held = cb.fut_position(l.fut_symbol)
if abs(held) > 1e-12:
raise live.LiveError(f"на фьючерсе осталось {held:+g} {l.base}")
except live.LiveError as exc:
self._pending_problem(l.base, f"откат входа не завершён: {exc}; повторяю закрытие")
return
self._pending_done(l.base)
self._journal(l.base, "recover", True, "откат входа завершён: биржа подтвердила отсутствие позиции")
@staticmethod
def _api_closed(error: str) -> bool:
@@ -1370,10 +1663,11 @@ class CrossEngine:
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):
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}
"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))
@@ -1413,14 +1707,21 @@ class CrossEngine:
# leaves nothing filled and nothing is bought on A; otherwise it waits «Лимитный вход: ждать, с»
hold = 0.0 if s.entry_ioc else max(0.0, s.limit_hold_s)
name = "IOC-шорт" if s.entry_ioc else "лимитный шорт"
self._pending_update(l.base, phase="limit_submitted")
try:
oid = cb.fut_limit(l.fut_symbol, "sell", coins, l.fut_bid)
except (live.LiveError, AttributeError) as exc:
if getattr(exc, "sent", False):
self._pending_update(l.base, order_id=getattr(exc, "order_id", ""))
self._pending_problem(l.base, f"результат лимитного входа неизвестен: {exc}")
return
self._pending_done(l.base)
self._journal(l.base, "open", False, f"{name} на {l.fut_ex} не выставлен: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
self._pause_if_balance(str(exc), l.fut_ex)
return
self._pending_update(l.base, order_id=oid)
st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False}
end = time.time() + hold
while True: # one look a second: the exchange's request limit
@@ -1432,25 +1733,19 @@ class CrossEngine:
break
time.sleep(1.0)
if not st["final"]:
try:
cb.fut_cancel(l.fut_symbol, oid)
except live.LiveError:
pass
try:
st = cb.fut_order_status(l.fut_symbol, oid)
except live.LiveError:
try:
st = {**st, "coins": max(0.0, -cb.fut_position(l.fut_symbol))}
except live.LiveError:
pass
st = self._cancel_entry(l, cb, oid)
if st is None:
return
shorted, fut_price, fut_fee_usd = st["coins"], st["price"] or l.fut_bid, st["fee"]
if shorted <= 0:
self._pending_done(l.base)
self._journal(l.base, "open", False, f"{name} на {l.fut_ex} по {l.fut_bid:.10g} не исполнился"
f"{'' if s.entry_ioc else f' за {hold:g} с'} — снят, на {l.spot_ex} ничего не покупалось")
with self.lock:
self.last_close[l.base] = time.time()
return
else:
self._pending_update(l.base, phase="market_submitted")
try:
fut = cb.fut_order(l.fut_symbol, "sell", coins, reduce_only=False)
shorted, fut_price, fut_fee_usd, fut_exact = fut.coins, fut.price, fut.fee_usd, fut.exact
@@ -1462,6 +1757,11 @@ class CrossEngine:
except live.LiveError:
held = coins # unknown: assume open — the close is reduce-only
if held <= 0:
if getattr(exc, "sent", False):
self._pending_update(l.base, order_id=exc.order_id)
self._pending_problem(l.base, f"результат рыночного входа неизвестен: {exc}")
return
self._pending_done(l.base)
self._journal(l.base, "open", False, f"шорт на {l.fut_ex} не открыт: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
@@ -1469,6 +1769,7 @@ class CrossEngine:
return
shorted, fut_price = held, l.fut_bid
fut_fee_usd, fut_exact = held * l.fut_bid * fut_fee(l.fut_ex, self.fees, l.innovation) / 100, False
self._pending_update(l.base, phase="hedge_submitted", shorted=shorted)
# 2) the hedge: the same coins on spot on A (the buy fee is taken in coins: a little more USDT)
try:
buy = ca.spot_buy(l.base, shorted * l.spot_ask * (1 + a_fee / 100) * 1.003)
@@ -1480,25 +1781,24 @@ class CrossEngine:
except live.LiveError:
bought = 0.0
if bought <= 0:
try:
cb.fut_order(l.fut_symbol, "buy", shorted, reduce_only=True)
text = f"шорт {shorted:g} на {l.fut_ex} открыт, но спот на {l.spot_ex} не куплен ({exc}); шорт закрыт"
except live.LiveError as exc2:
text = (f"шорт {shorted:g} на {l.fut_ex} открыт, спот на {l.spot_ex} не куплен ({exc}); ШОРТ НЕ "
f"ЗАКРЫТ ({exc2}) — закройте вручную")
self._journal(l.base, "open", False, text)
with self.lock:
self.last_close[l.base] = time.time()
if self._api_closed(str(exc)): # PTB: tried 7 times, fees paid each time
if getattr(exc, "sent", False):
self._pending_problem(l.base, f"результат покупки спота неизвестен: {exc}; требуется сверка")
return
self._pending_update(l.base, phase="rollback")
self._rollback_entry(l, cb)
if self._api_closed(str(exc)):
self._not_tradable(l.base, f"биржа {l.spot_ex} не даёт торговать {l.base} через API: {exc}", 86400)
self._pause_if_balance(str(exc), l.spot_ex)
return
buy = live.Fill(bought, l.spot_ask, bought * l.spot_ask * a_fee / 100, exc.order_id, exact=False)
self._pending_update(l.base, phase="hedge_confirmed", buy=asdict(buy), shorted=shorted,
fut_price=fut_price, fut_fee=fut_fee_usd)
try:
free = ca.spot_free(l.base)
except live.LiveError:
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()
@@ -1511,9 +1811,18 @@ class CrossEngine:
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)
@@ -1590,10 +1899,11 @@ class CrossEngine:
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):
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}
"amount": amount, "link": asdict(l), "phase": "prepared"}
self.save()
if s.auto_transfer:
try:
@@ -1607,10 +1917,12 @@ class CrossEngine:
return
self._journal(l.base, "transfer", False, f"{l.spot_ex}: перевод не удался: {exc} — пробую без него")
# 1) sell the stock on B
self._pending_update(l.base, phase="spot_submitted", stock_before=have)
try:
sold = cb.spot_sell(l.base, coins)
except live.LiveError as exc:
if not getattr(exc, "sent", False):
self._pending_done(l.base)
self._journal(l.base, "open", False, f"продажа {l.base} на споте {l.fut_ex} не прошла: {exc}")
with self.lock:
self.last_close[l.base] = time.time()
@@ -1626,6 +1938,8 @@ class CrossEngine:
else:
try:
cb.spot_buy(l.base, sold.coins * l.fut_ask * (1 + b_fee_pct / 100) * 1.003)
if cb.spot_free(l.base) >= have - 1e-9:
self._pending_done(l.base)
text = (f"{l.base} продан на {l.fut_ex}, но на {l.spot_ex} не куплен ({exc}); запас на "
f"{l.fut_ex} выкуплен обратно")
except live.LiveError as exc2:
@@ -1651,6 +1965,7 @@ class CrossEngine:
[l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]])
self.next_uid += 1
self.positions.append(pos)
self.pending.pop(l.base, None)
self.save()
self._journal(l.base, "open", True, f"спот-спот: продано {sold.coins:g} на {l.fut_ex} по {sold.price:.10g}, "
f"куплено {got:g} на {l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% "
@@ -1680,6 +1995,62 @@ class CrossEngine:
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
@@ -1691,7 +2062,7 @@ class CrossEngine:
# 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 reason != "вручную" and "стоп:" not in reason and "ликвидац" not in reason:
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:
@@ -1727,23 +2098,8 @@ class CrossEngine:
try:
ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex)
if pos.ss and pos.closing != "fut_done":
# spot–spot: buy the coins sold on B back (the stock there is restored), a little over for the fee
stage = f"выкуп монет на споте {pos.fut_ex}"
l = self.links.get(pos.key)
ask_b = l.fut_ask if l else pos.fut_entry
usdt = pos.qty * ask_b * (1 + spot_fee(pos.fut_ex, self.fees) / 100) * 1.003
try:
back = cb.spot_buy(pos.base, usdt)
price, fee, exact = back.price, back.fee_usd, back.exact
except live.LiveError as exc:
if not getattr(exc, "sent", False):
raise
price, fee, exact = ask_b, usdt * spot_fee(pos.fut_ex, self.fees) / 100, False
with self.lock:
pos.fut_exit, pos.exit_fees, pos.closing = price, fee, "fut_done"
pos.exact = pos.exact and exact
pos.fills.append([pos.fut_ex, "spot", fee, usdt, exact])
self.save()
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:
@@ -1871,39 +2227,79 @@ class CrossEngine:
import live
with self.lock:
l = self.links.get(info.get("key", ""))
if l is None and info.get("link"):
l = Link(**info["link"])
already_owned = any(p.real and p.base == base for p in self.positions)
if already_owned or info.get("phase") == "prepared":
self._pending_done(base)
return
if l is None:
self._pending_problem(base, "нет сохранённых параметров незавершённой сделки")
return
phase = info.get("phase")
if not l.ss and phase in ("limit_submitted", "market_submitted", "rollback"):
cb = self.client_for(l.fut_ex)
if phase != "rollback":
oid = info.get("order_id")
if not oid:
self._pending_problem(base, "отправленный вход без ID: требуется ручная сверка ордеров биржи")
# Retain the intent even when flat; a delayed fill must not permit another entry.
held = cb.fut_position(l.fut_symbol)
if held < -1e-12:
cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True)
return
if self._cancel_entry(l, cb, oid) is None:
return
self._pending_update(base, phase="rollback")
self._rollback_entry(l, cb)
return
if phase == "hedge_submitted":
# Without an exchange order id, an unchanged spot balance does not prove rejection.
self._pending_problem(base, "незавершённая покупка спота: требуется ручная сверка обеих ног")
return
if l.ss: # a spot sale cannot be told apart from the user's own trades: say so, no guess
self._journal(base, "open", False, f"после перезапуска: незавершённый вход спот-спот {l.spot_ex} → "
self._pending_problem(base, f"незавершённый вход спот-спот {l.spot_ex} → "
f"{l.fut_ex} — проверьте {base} на обеих биржах вручную")
return
try:
ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex)
short = max(0.0, -cb.fut_position(l.fut_symbol))
coins = min(ca.spot_free(l.base), float(info.get("coins") or 0) * 1.05)
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,
l.spot_ask, l.fut_bid if short else 0.0, l.entry_gap, float(info.get("usual") or 0.0),
0.0, (now // step + 1) * step, real=True, spot_qty=coins, exact=False,
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="подхвачено после перезапуска — цены оценочные")
if short <= 0 or coins * l.spot_bid < 1.0: # one leg only: close what there is at once
pos.retry_at, pos.usual = 0.0, 1e9
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:
@@ -2061,11 +2457,19 @@ class CrossEngine:
"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,
"real_pause": (f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)"
"recovery": {base: dict(info) for base, info in {**self.recover, **self.pending}.items()},
"real_pause": ("сверка незавершённых ордеров: " + ", ".join({**self.recover, **self.pending})
if s.real and (self.pending or self.recover)
else "завершение закрытия: " + ", ".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
+201
View File
@@ -0,0 +1,201 @@
"""Tk chart rendering and viewport interaction for the desktop simulator."""
from __future__ import annotations
from datetime import datetime
import tkinter as tk
import strategy
class ChartView:
def _draw_chart(self) -> None:
if not hasattr(self, "canvas"):
return
c = self.canvas
c.delete("all")
width, height = c.winfo_width(), c.winfo_height()
if width < 80 or height < 80:
return
left, right, top, bottom = 58, width - 82, 22, height - 34
c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей")
candles = list(self.candles)
if not candles:
c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…")
return
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
low -= pad
high += pad
t0 = candles[0][0]
t1 = max(candles[-1][0] + 60, t0 + 60)
view_end = self.chart_view_end if self.chart_view_end is not None else t1
view_start = view_end - self.chart_visible_seconds
visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end]
visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end]
if visible_candles:
candles = visible_candles
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
base_span = high - low
pad = base_span * .08 if base_span else max(high * .001, 1e-8)
natural_low, natural_high = low - pad, high + pad
if self.chart_price_center is None or self.chart_price_span is None:
low, high = natural_low, natural_high
if self.chart_price_center is not None and self.chart_price_span is not None:
span = self.chart_price_span
low = self.chart_price_center - span / 2
high = self.chart_price_center + span / 2
t0 = view_start
t1 = view_end
if t1 <= t0:
return
for i in range(5):
y = top + i * (bottom - top) / 4
value = high - i * (high - low) / 4
c.create_line(left, y, right, y, fill="#263746")
c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value))
c.create_line(left, bottom, right, bottom, fill="#6c7e8c")
candle_seconds = self.interval_minutes * 60
slot = (right - left) * candle_seconds / (t1 - t0)
body_width = max(2.0, min(16.0, slot * .62))
for candle in candles:
t, open_price, high_price, low_price, close_price = candle
if t < t0 - candle_seconds or t > t1:
continue
x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left)
y_high = bottom - (high_price - low) / (high - low) * (bottom - top)
y_low = bottom - (low_price - low) / (high - low) * (bottom - top)
y_open = bottom - (open_price - low) / (high - low) * (bottom - top)
y_close = bottom - (close_price - low) / (high - low) * (bottom - top)
color = "#38d996" if close_price >= open_price else "#ef5965"
c.create_line(x, y_high, x, y_low, fill=color, width=1)
body_top, body_bottom = sorted((y_open, y_close))
if body_bottom - body_top < 1:
body_bottom = body_top + 1
c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color)
for marker_time, marker_price, trade_id in visible_markers:
if not t0 <= marker_time <= t1:
continue
x = left + (marker_time - t0) / (t1 - t0) * (right - left)
y = bottom - (marker_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1)
c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}")
position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position
if position and position.mode != strategy.STRATEGY_CLASSIC:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom,
f"Вход {position.side.upper()}", "#63a8ff")
self._draw_level(c, position.stop_price, low, high, left, right, top, bottom,
"Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42")
if position.partial_target > 0 and not position.partial_done:
self._draw_level(c, position.partial_target, low, high, left, right, top, bottom,
"Частичная фиксация", "#40d6b0")
if position.final_target > 0:
self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0")
liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side)
if liquidation is not None:
self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d")
elif position:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff")
s = self.applied_settings or self._safe_read_settings()
if s["add_step"] > 0 and position.add_count < s["max_adds"]:
next_add = position.last_add_price * (1 - s["add_step"] / 100)
self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff")
if s["stop_loss"] > 0:
stop_price = position.entry_price * (1 - s["stop_loss"] / 100)
self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42")
if s["take_profit"] > 0:
effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"]))
take_profit_price = position.entry_price * (1 + effective_tp_pct / 100)
self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0")
if self.last_price:
y = bottom - (self.last_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3))
c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M"))
c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M"))
def _chart_bounds(self) -> tuple[int, int, int, int]:
width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
return 58, width - 82, 22, height - 34
def _on_chart_wheel(self, event: tk.Event) -> None:
direction = 1 if event.delta > 0 else -1
self._zoom_chart(event.x, event.y, direction)
def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None:
self._zoom_chart(event.x, event.y, direction)
def _zoom_chart(self, x: int, y: int, direction: int) -> None:
if not self.candles:
return
old_span = self.chart_visible_seconds
factor = 0.8 if direction > 0 else 1.25
self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor))
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
left, right, top, bottom = self._chart_bounds()
fraction_x = min(1, max(0, (x - left) / max(1, right - left)))
old_start = self.chart_view_end - old_span
anchor_time = old_start + fraction_x * old_span
self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
center = (max(prices) + min(prices)) / 2
self.chart_price_center = center
self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8)
fraction_y = min(1, max(0, (y - top) / max(1, bottom - top)))
anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span
self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor)
self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span
self._draw_chart()
def _on_chart_press(self, event: tk.Event) -> None:
if not self.candles:
return
left, right, top, bottom = self._chart_bounds()
if not left <= event.x <= right or not top <= event.y <= bottom:
return
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
self.chart_price_center = (high + low) / 2
self.chart_price_span = high - low + 2 * pad
self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center,
self.chart_price_span, self.chart_visible_seconds)
self.canvas.configure(cursor="fleur")
def _on_chart_drag(self, event: tk.Event) -> None:
if not self._drag_anchor:
return
x0, y0, end0, center0, price_span, time_span = self._drag_anchor
left, right, top, bottom = self._chart_bounds()
self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span
self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span
self.chart_price_span = price_span
self._draw_chart()
def _on_chart_release(self, _event: tk.Event) -> None:
self._drag_anchor = None
self.canvas.configure(cursor="")
def _reset_chart_view(self, _event: tk.Event | None = None) -> None:
self.chart_visible_seconds = self.interval_minutes * 60 * 30
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._drag_anchor = None
self._draw_chart()
def _go_to_live(self) -> None:
"""Return the chart's right edge to the newest market candle."""
if self.candles:
self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60
else:
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._draw_chart()
+74
View File
@@ -0,0 +1,74 @@
"""Desktop account and per-symbol state, independent of Tk widgets."""
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
import strategy
@dataclass
class Position:
trade_id: int
symbol: str
entry_price: float
qty: float
stake: float
entry_fee: float
opened_at: float
last_add_price: float
add_count: int = 0
# Strategy-mode fields; classic positions keep the defaults.
side: str = "long"
mode: str = strategy.STRATEGY_CLASSIC
leverage: float = 1.0
stop_price: float = 0.0
initial_stop: float = 0.0
atr: float = 0.0
extreme: float = 0.0
partial_target: float = 0.0 # 0 = none
final_target: float = 0.0 # 0 = none
partial_done: bool = False
realized_gross: float = 0.0
realized_fees: float = 0.0
opened_stake: float = 0.0
@dataclass
class ClosedTrade:
trade_id: int
symbol: str
entry_price: float
exit_price: float
qty: float
gross_pnl: float
fees: float
net_pnl: float
roi_pct: float
opened_at: float
closed_at: float
reason: str
@dataclass
class CurrencyState:
"""Independent market and position state for one concurrently traded symbol."""
prices: deque = field(default_factory=deque)
candles: deque = field(default_factory=deque)
entry_markers: deque = field(default_factory=deque)
last_price: float | None = None
baseline_close: float | None = None
last_signal_pct: float | None = None
last_signal_ready: bool = False
previous_entry_signal_pct: float | None = None
live_minute_prices: deque = field(default_factory=deque)
last_ws_message: float = 0.0
position: Position | None = None
live_position: Position | None = None
live_position_info: dict | None = None
live_order_busy: bool = False
live_transition_pending: bool = False
live_halted: bool = False
# Strategy modes A/B: last evaluated signal candle and the signal valid until the next close.
mode_signal: dict | None = None
mode_signal_bucket: int = 0
mode_eval_busy: bool = False
+176
View File
@@ -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:<key>`;
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_<coin>.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.
+35 -24
View File
@@ -495,6 +495,24 @@ def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_
return windows, sorted(failed)
def _track_risk(risk: dict[str, float], equity: float) -> None:
risk["peak"] = max(risk["peak"], equity)
drawdown = risk["peak"] - equity
drawdown_pct = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
# The largest dollar loss and largest percentage loss may follow different peaks.
risk["max_dd_usdt"] = max(risk["max_dd_usdt"], drawdown)
risk["max_dd_pct"] = max(risk["max_dd_pct"], drawdown_pct)
risk["min_equity"] = min(risk["min_equity"], equity)
def _equity_floor_crossing(start: float, end: float, start_equity: float,
end_equity: float, floor: float) -> float | None:
"""Price where linearly marked equity first reaches the floor on this segment."""
if start_equity > floor >= end_equity:
return start + (end - start) * (floor - start_equity) / (end_equity - start_equity)
return None
def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
strategies: dict[str, dict[str, float]], initial_capital: float,
fee_pct: float = TAKER_FEE_PCT,
@@ -560,21 +578,12 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
equity += unrealized - estimated_exit_fee
return equity
def track_risk(equity: float) -> None:
if equity > risk["peak"]:
risk["peak"] = equity
drawdown = risk["peak"] - equity
if drawdown > risk["max_dd_usdt"]:
risk["max_dd_usdt"] = drawdown
risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
risk["min_equity"] = min(risk["min_equity"], equity)
def mark_and_check_stop(symbol: str, price: float, stamp: int) -> bool:
if equity_stop["triggered"]:
return True
marks[symbol] = price
equity = equity_at()
track_risk(equity)
_track_risk(risk, equity)
if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12):
equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
return True
@@ -742,12 +751,10 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
# Add the precise capital-floor crossing as an event so a later rebound
# inside the same candle cannot hide a drawdown breach.
if min_equity_pct > 0 and end < current:
current_equity = equity_at(symbol, current)
end_equity = equity_at(symbol, end)
if current_equity > equity_floor >= end_equity and current_equity != end_equity:
stop_level = current + (end - current) * (
(equity_floor - current_equity) / (end_equity - current_equity)
stop_level = _equity_floor_crossing(
current, end, equity_at(symbol, current), equity_at(symbol, end), equity_floor,
)
if stop_level is not None:
candidates.append((stop_level, "EQUITY_STOP"))
_tp, stop_level, liq_level = exit_levels(symbol, pos)
if stop_level is not None and end <= stop_level < current:
@@ -1118,10 +1125,11 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
def iso(stamp: int) -> str:
return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat()
def equity_at() -> float:
def equity_at(symbol: str | None = None, price: float | None = None) -> float:
equity = cash
for position_symbol, pos in positions.items():
mark = marks.get(position_symbol, pos.entry_price)
mark = (price if position_symbol == symbol and price is not None
else marks.get(position_symbol, pos.entry_price))
equity += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty)
- mark * pos.qty * fee_pct / 100)
return equity
@@ -1131,13 +1139,7 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
return True
marks[symbol] = price
equity = equity_at()
if equity > risk["peak"]:
risk["peak"] = equity
drawdown = risk["peak"] - equity
if drawdown > risk["max_dd_usdt"]:
risk["max_dd_usdt"] = drawdown
risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
risk["min_equity"] = min(risk["min_equity"], equity)
_track_risk(risk, equity)
if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12):
equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
return True
@@ -1296,6 +1298,12 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
return
liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side)
candidates = []
if min_equity_pct > 0:
floor_price = _equity_floor_crossing(
start, end, equity_at(symbol, start), equity_at(symbol, end), equity_floor,
)
if floor_price is not None:
candidates.append((floor_price, "EQUITY_STOP"))
lo, hi = min(start, end), max(start, end)
if lo <= pos.stop <= hi:
candidates.append((pos.stop, "STOP"))
@@ -1307,6 +1315,9 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
# The first level crossed on the way from ``start`` is the nearest one.
level, event = min(candidates, key=lambda item: abs(item[0] - start))
marks[symbol] = level
if event == "EQUITY_STOP":
mark_and_check_stop(symbol, level, stamp)
return
if event == "LIQ":
close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True)
else:
+3 -2
View File
@@ -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()
+9
View File
@@ -0,0 +1,9 @@
[
{
"lead_market": "raydium",
"lead_ticker": "CLAUDIAUSDTM",
"lead_pool": "Fe7bpDYCs74GqiCUF14HwgUMToPKV1d9mDYVX5BTohFr",
"follow_exchange": "mexc",
"follow_ticker": "CLAUDIA_USDT"
}
]
+8 -12
View File
@@ -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)
+7 -2
View File
@@ -167,8 +167,13 @@ def _http(method: str, url: str, headers: dict | None = None, body: bytes | None
else:
_give_back(parts.scheme, parts.netloc, conn)
if resp.status >= 400:
raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}")
raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}",
sent=method in ("POST", "DELETE") and resp.status >= 500)
try:
return json.loads(data or b"{}")
except (ValueError, UnicodeDecodeError) as exc:
raise LiveError(f"не удалось прочитать ответ биржи: {exc}",
sent=method in ("POST", "DELETE")) from None
raise LiveError("нет связи")
@@ -1431,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]] = {}
+8 -271
View File
@@ -12,7 +12,6 @@ import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
import tkinter as tk
@@ -22,6 +21,9 @@ from credential_store import CredentialStoreError, delete_credentials, load_cred
from historical_backtest import (fetch_funding_history, fetch_klines, prepare_universe, run_backtest,
run_mode_backtest, save_report)
import strategy
from desktop_models import Position, ClosedTrade, CurrencyState
from desktop_chart import ChartView
from persistence import atomic_write_json
try:
import websocket
@@ -59,75 +61,7 @@ MAX_EVENTS_PER_POLL = 2000
MANUAL_CLOSE_CONFIRM_SECONDS = 15
@dataclass
class Position:
trade_id: int
symbol: str
entry_price: float
qty: float
stake: float
entry_fee: float
opened_at: float
last_add_price: float
add_count: int = 0
# Strategy-mode fields; classic positions keep the defaults.
side: str = "long"
mode: str = strategy.STRATEGY_CLASSIC
leverage: float = 1.0
stop_price: float = 0.0
initial_stop: float = 0.0
atr: float = 0.0
extreme: float = 0.0
partial_target: float = 0.0 # 0 = none
final_target: float = 0.0 # 0 = none
partial_done: bool = False
realized_gross: float = 0.0
realized_fees: float = 0.0
opened_stake: float = 0.0
@dataclass
class ClosedTrade:
trade_id: int
symbol: str
entry_price: float
exit_price: float
qty: float
gross_pnl: float
fees: float
net_pnl: float
roi_pct: float
opened_at: float
closed_at: float
reason: str
@dataclass
class CurrencyState:
"""Independent market and position state for one concurrently traded symbol."""
prices: deque = field(default_factory=deque)
candles: deque = field(default_factory=deque)
entry_markers: deque = field(default_factory=deque)
last_price: float | None = None
baseline_close: float | None = None
last_signal_pct: float | None = None
last_signal_ready: bool = False
previous_entry_signal_pct: float | None = None
live_minute_prices: deque = field(default_factory=deque)
last_ws_message: float = 0.0
position: Position | None = None
live_position: Position | None = None
live_position_info: dict | None = None
live_order_busy: bool = False
live_transition_pending: bool = False
live_halted: bool = False
# Strategy modes A/B: last evaluated signal candle and the signal valid until the next close.
mode_signal: dict | None = None
mode_signal_bucket: int = 0
mode_eval_busy: bool = False
class PaperSimulator:
class PaperSimulator(ChartView):
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.root.title("Bybit — симулятор сделок в реальном времени")
@@ -2134,10 +2068,8 @@ class PaperSimulator:
"live_initial_deposits": self.live_initial_deposits,
}
try:
temp_path = STATE_FILE.with_suffix(".json.tmp")
temp_path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
os.replace(temp_path, STATE_FILE)
except OSError as exc:
atomic_write_json(STATE_FILE, state)
except (OSError, ValueError) as exc:
if hasattr(self, "status_var"):
self.status_var.set(f"Не удалось сохранить историю счёта: {exc}")
@@ -2154,10 +2086,8 @@ class PaperSimulator:
def _save_settings(self) -> None:
self._settings_save_job = None
try:
temp_path = SETTINGS_FILE.with_suffix(".json.tmp")
temp_path.write_text(json.dumps(self._settings_payload(), ensure_ascii=False, indent=2), encoding="utf-8")
os.replace(temp_path, SETTINGS_FILE)
except OSError as exc:
atomic_write_json(SETTINGS_FILE, self._settings_payload())
except (OSError, ValueError) as exc:
self.status_var.set(f"Не удалось сохранить настройки: {exc}")
@staticmethod
@@ -4513,199 +4443,6 @@ class PaperSimulator:
return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}"
return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}"
def _draw_chart(self) -> None:
if not hasattr(self, "canvas"):
return
c = self.canvas
c.delete("all")
width, height = c.winfo_width(), c.winfo_height()
if width < 80 or height < 80:
return
left, right, top, bottom = 58, width - 82, 22, height - 34
c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей")
candles = list(self.candles)
if not candles:
c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…")
return
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
low -= pad
high += pad
t0 = candles[0][0]
t1 = max(candles[-1][0] + 60, t0 + 60)
view_end = self.chart_view_end if self.chart_view_end is not None else t1
view_start = view_end - self.chart_visible_seconds
visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end]
visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end]
if visible_candles:
candles = visible_candles
prices = [p for candle in candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
base_span = high - low
pad = base_span * .08 if base_span else max(high * .001, 1e-8)
natural_low, natural_high = low - pad, high + pad
if self.chart_price_center is None or self.chart_price_span is None:
low, high = natural_low, natural_high
if self.chart_price_center is not None and self.chart_price_span is not None:
span = self.chart_price_span
low = self.chart_price_center - span / 2
high = self.chart_price_center + span / 2
t0 = view_start
t1 = view_end
if t1 <= t0:
return
for i in range(5):
y = top + i * (bottom - top) / 4
value = high - i * (high - low) / 4
c.create_line(left, y, right, y, fill="#263746")
c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value))
c.create_line(left, bottom, right, bottom, fill="#6c7e8c")
candle_seconds = self.interval_minutes * 60
slot = (right - left) * candle_seconds / (t1 - t0)
body_width = max(2.0, min(16.0, slot * .62))
for candle in candles:
t, open_price, high_price, low_price, close_price = candle
if t < t0 - candle_seconds or t > t1:
continue
x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left)
y_high = bottom - (high_price - low) / (high - low) * (bottom - top)
y_low = bottom - (low_price - low) / (high - low) * (bottom - top)
y_open = bottom - (open_price - low) / (high - low) * (bottom - top)
y_close = bottom - (close_price - low) / (high - low) * (bottom - top)
color = "#38d996" if close_price >= open_price else "#ef5965"
c.create_line(x, y_high, x, y_low, fill=color, width=1)
body_top, body_bottom = sorted((y_open, y_close))
if body_bottom - body_top < 1:
body_bottom = body_top + 1
c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color)
for marker_time, marker_price, trade_id in visible_markers:
if not t0 <= marker_time <= t1:
continue
x = left + (marker_time - t0) / (t1 - t0) * (right - left)
y = bottom - (marker_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1)
c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}")
position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position
if position and position.mode != strategy.STRATEGY_CLASSIC:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom,
f"Вход {position.side.upper()}", "#63a8ff")
self._draw_level(c, position.stop_price, low, high, left, right, top, bottom,
"Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42")
if position.partial_target > 0 and not position.partial_done:
self._draw_level(c, position.partial_target, low, high, left, right, top, bottom,
"Частичная фиксация", "#40d6b0")
if position.final_target > 0:
self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0")
liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side)
if liquidation is not None:
self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d")
elif position:
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff")
s = self.applied_settings or self._safe_read_settings()
if s["add_step"] > 0 and position.add_count < s["max_adds"]:
next_add = position.last_add_price * (1 - s["add_step"] / 100)
self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff")
if s["stop_loss"] > 0:
stop_price = position.entry_price * (1 - s["stop_loss"] / 100)
self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42")
if s["take_profit"] > 0:
effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"]))
take_profit_price = position.entry_price * (1 + effective_tp_pct / 100)
self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0")
if self.last_price:
y = bottom - (self.last_price - low) / (high - low) * (bottom - top)
if top <= y <= bottom:
c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3))
c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M"))
c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M"))
def _chart_bounds(self) -> tuple[int, int, int, int]:
width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
return 58, width - 82, 22, height - 34
def _on_chart_wheel(self, event: tk.Event) -> None:
direction = 1 if event.delta > 0 else -1
self._zoom_chart(event.x, event.y, direction)
def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None:
self._zoom_chart(event.x, event.y, direction)
def _zoom_chart(self, x: int, y: int, direction: int) -> None:
if not self.candles:
return
old_span = self.chart_visible_seconds
factor = 0.8 if direction > 0 else 1.25
self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor))
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
left, right, top, bottom = self._chart_bounds()
fraction_x = min(1, max(0, (x - left) / max(1, right - left)))
old_start = self.chart_view_end - old_span
anchor_time = old_start + fraction_x * old_span
self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
center = (max(prices) + min(prices)) / 2
self.chart_price_center = center
self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8)
fraction_y = min(1, max(0, (y - top) / max(1, bottom - top)))
anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span
self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor)
self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span
self._draw_chart()
def _on_chart_press(self, event: tk.Event) -> None:
if not self.candles:
return
left, right, top, bottom = self._chart_bounds()
if not left <= event.x <= right or not top <= event.y <= bottom:
return
if self.chart_view_end is None:
self.chart_view_end = self.candles[-1][0] + 60
if self.chart_price_center is None or self.chart_price_span is None:
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
low, high = min(prices), max(prices)
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
self.chart_price_center = (high + low) / 2
self.chart_price_span = high - low + 2 * pad
self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center,
self.chart_price_span, self.chart_visible_seconds)
self.canvas.configure(cursor="fleur")
def _on_chart_drag(self, event: tk.Event) -> None:
if not self._drag_anchor:
return
x0, y0, end0, center0, price_span, time_span = self._drag_anchor
left, right, top, bottom = self._chart_bounds()
self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span
self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span
self.chart_price_span = price_span
self._draw_chart()
def _on_chart_release(self, _event: tk.Event) -> None:
self._drag_anchor = None
self.canvas.configure(cursor="")
def _reset_chart_view(self, _event: tk.Event | None = None) -> None:
self.chart_visible_seconds = self.interval_minutes * 60 * 30
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._drag_anchor = None
self._draw_chart()
def _go_to_live(self) -> None:
"""Return the chart's right edge to the newest market candle."""
if self.candles:
self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60
else:
self.chart_view_end = None
self.chart_price_center = None
self.chart_price_span = None
self._draw_chart()
def _update_candle(self, timestamp: float, price: float) -> None:
interval_seconds = self.interval_minutes * 60
candle_start = int(timestamp // interval_seconds) * interval_seconds
+1 -1
View File
@@ -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",
-4
View File
@@ -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),
}
+72
View File
@@ -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)
+45
View File
@@ -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
+27
View File
@@ -0,0 +1,27 @@
"""Atomic local JSON snapshots; callers must handle write failures explicitly."""
from __future__ import annotations
import json
import os
import tempfile
from pathlib import Path
def atomic_write_json(path: Path, payload) -> None:
"""Flush a new snapshot before replacing the old file, or leave the old file intact."""
path = Path(path)
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(fd, "wb") as stream:
stream.write(encoded)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
try:
os.unlink(temporary)
except FileNotFoundError:
pass
+116 -26
View File
@@ -8,14 +8,16 @@ whose real order did not go through is closed at once, so paper and real trades
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_<coin>.json); paper positions do not survive a restart, so
a saved real position is closed right after a restart («осиротевшая»);
- real positions are saved (web_sim_data/real_positions_<coin>.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
@@ -24,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()
@@ -107,7 +109,7 @@ def save_settings(values: dict) -> str:
if values.get("reset_stats"):
c["since"] = time.time()
DATA_DIR.mkdir(exist_ok=True)
SETTINGS_FILE.write_text(json.dumps(s), encoding="utf-8")
atomic_write_json(SETTINGS_FILE, s)
return ""
@@ -191,6 +193,7 @@ class FuturesMirror:
self.position: dict | None = None # the one real position (opening / open / closing)
self.trades: list[dict] = []
self.state = "" # "" idle · "opening" · "open" · "closing" · "check" (verify zero)
self.storage_error = ""
self.problem = "" # last error that keeps the coin blocked
self.on_failed_open = None # callback(uid): close the paper twin of a real order that failed
self.exchange_trades: list[dict] | None = None # rebuilt from the exchange's fills (None: not synced yet)
@@ -207,24 +210,67 @@ class FuturesMirror:
def _load(self) -> None:
try:
d = json.loads(self.file.read_text(encoding="utf-8"))
except (OSError, ValueError):
except FileNotFoundError:
return
except (OSError, ValueError) as exc:
self.state, self.problem = "blocked", f"не прочитано состояние реальных ордеров: {exc}"
return
self.trades = d.get("trades", [])[-500:]
pos = d.get("position")
if pos:
# paper positions do not survive a restart: the saved real one is closed at once
pos["uid"] = None
self.position, self.state = pos, "closing"
self.position = pos
if pos.get("phase") in ("prepared", "submitted"):
self.state = "recover"
self.jobs.put(("recover", None))
else:
self.state = "closing"
self.jobs.put(("close", "осиротевшая после перезапуска"))
def _save(self) -> None:
try:
self.file.parent.mkdir(exist_ok=True)
pos = self.position if self.state in ("open", "closing", "check") else None
self.file.write_text(json.dumps({"position": pos, "trades": self.trades[-500:]}, ensure_ascii=False),
encoding="utf-8")
except OSError:
pass
atomic_write_json(self.file, {"version": 2, "state": self.state,
"position": self.position, "trades": self.trades[-500:]})
except (OSError, ValueError) as exc:
self.storage_error = f"не сохранено состояние ордеров: {exc}"
raise
self.storage_error = ""
def _recover_open(self) -> None:
"""Never replay an entry after a crash. Resolve known orders; contain unknown submissions."""
pos = self.position
if not pos:
return
if pos.get("phase") == "prepared":
self._failed_open("перезапуск до отправки ордера")
return
c = self.client_for(self.exchange)
oid = pos.get("order_in")
if pos.get("phase") != "filled":
if not oid:
# A lost submit response cannot be declared absent from one flat position snapshot.
held = c.fut_position(self.symbol)
if abs(held) > self.VERIFY_TOLERANCE:
expected = 1 if pos["side"] == "LONG" else -1
if held * expected <= 0:
self.problem = "позиция другого направления — требуется ручная сверка"
return
c.fut_order(self.symbol, "sell" if held > 0 else "buy", abs(held), reduce_only=True)
self.problem = "результат входа без ID неизвестен; новые входы заблокированы, сверяю и закрываю остаток"
return
status = c.fut_order_status(self.symbol, oid)
if not status["final"]:
c.fut_cancel(self.symbol, oid)
status = c.fut_order_status(self.symbol, oid)
if not status["final"]:
self.problem = "ожидаю окончательный статус входа"
return
pos.update(phase="filled", coins=status["coins"], entry=status["price"] or pos["paper_entry"],
fee_in=status["fee"], exact=False)
with self.lock:
self.state = "closing"
self._save()
self._close("восстановление незавершённого входа")
# --- the simulator's side ----------------------------------------------------------------------------------
def coin_settings(self) -> dict:
@@ -238,6 +284,8 @@ class FuturesMirror:
if not self.enabled():
return ""
with self.lock:
if self.storage_error:
return self.storage_error
left = self.paused_until - time.time()
if self.state == "" and left > 0:
# the exchange refused the last entry: no new trade (paper or real) until the pause ends
@@ -258,7 +306,7 @@ class FuturesMirror:
"""Paper events, called under the engine's lock: only queue work here."""
with self.lock:
if event == "open":
if not self.enabled() or self.state or time.time() < self.paused_until:
if not self.enabled() or self.state or self.storage_error or time.time() < self.paused_until:
return # real mode off, or a real trade still runs (gate was bypassed)
self.state = "opening"
units = symbol_units(self.symbol)
@@ -267,11 +315,26 @@ class FuturesMirror:
# the paper take-profit as a distance from the entry: the real TP is placed at
# the same distance from the REAL fill price, not at the paper price
"tp_pct": (pos.target / pos.entry - 1) * 100 if getattr(pos, "target", None) else None,
"ping": self.ping()}
"ping": self.ping(), "phase": "prepared"}
try:
self._save()
except (OSError, ValueError):
self.state, self.problem = "recover", self.storage_error
return
self.jobs.put(("open", None))
elif event == "close" and self.position and self.position.get("uid") == pos.uid:
self.jobs.put(("close", "закрыта в симуляторе"))
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
@@ -286,11 +349,15 @@ class FuturesMirror:
self._open()
elif kind == "close":
self._close(arg)
elif kind == "recover":
self._recover_open()
elif kind == "watch":
self._watch()
except Exception as exc: # never let the worker die
with self.lock:
self.problem = f"сбой: {exc}"
if kind == "open" and self.position:
self.state = "recover"
journal("simulator", self.exchange, self.coin, kind, False, f"сбой: {exc}")
if kind == "close":
self._retry_close(arg)
@@ -331,6 +398,12 @@ class FuturesMirror:
def _watch(self) -> None:
"""An open real position may be closed by the exchange itself (its TP / SL): then record it now.
Every SYNC_S seconds (and right after a close) the trades are synced with the exchange's history."""
if self.storage_error and self.position is None:
with self.lock:
self._save()
if self.state == "recover":
self._recover_open()
return
if (self.state in ("", "open") and time.time() - self.last_sync >= self.SYNC_S
and (self.enabled() or self.exchange_trades is None)):
self.sync()
@@ -359,6 +432,15 @@ class FuturesMirror:
def _open(self) -> None:
pos = self.position
if pos is None or self.state != "opening":
return
with self.lock:
pos["phase"] = "submitted"
try:
self._save() # must complete before an exchange request is allowed
except (OSError, ValueError):
pos["phase"] = "prepared" # no request was sent
raise
side = "buy" if pos["side"] == "LONG" else "sell"
sign = 1 if side == "buy" else -1
c = None
@@ -374,23 +456,27 @@ class FuturesMirror:
else:
fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False)
except live.LiveError as exc:
if getattr(exc, "sent", False) and c is not None:
# accepted, fill not confirmed: the exchange's position decides
if getattr(exc, "sent", False):
with self.lock:
pos["order_in"] = exc.order_id
self.state, self.problem = "recover", str(exc)
self._save()
try:
held = abs(c.fut_position(self.symbol))
held = c.fut_position(self.symbol)
except live.LiveError:
held = pos["coins"] # cannot tell: treat as open, the close is reduce-only
if held > self.VERIFY_TOLERANCE:
fill = live.Fill(held, pos["paper_entry"], 0.0, exc.order_id, exact=False)
journal("simulator", self.exchange, self.coin, "open", False,
f"{exc} — позиция на бирже есть ({held:g}), веду её", side=pos["side"])
else:
self._failed_open(f"{exc}; позиции на бирже нет")
return
if held * sign <= self.VERIFY_TOLERANCE:
return
fill = live.Fill(abs(held), pos["paper_entry"], 0.0, exc.order_id, exact=False)
else:
self._top_up_futures(c, str(exc), pos["coins"] * pos["paper_entry"])
self._failed_open(str(exc))
return
# Persist the accepted fill before any additional network call (TP, fee sync, etc.).
with self.lock:
pos.update(phase="filled", coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd,
exact=fill.exact, order_in=fill.order_id)
self._save()
# the exchange's real fee rate (it decides how far the TP has to be, and the paper model uses it too)
fee_pct = fill.fee_usd / (fill.coins * fill.price) * 100 if fill.exact and fill.coins and fill.price else None
if fee_pct:
@@ -478,6 +564,10 @@ class FuturesMirror:
self.on_failed_open(uid)
def _close(self, reason: str) -> None:
if self.position and self.position.get("phase") in ("prepared", "submitted"):
self.state = "recover"
self._recover_open()
return
with self.lock:
pos = self.position
if pos is None or self.state == "":
@@ -566,7 +656,7 @@ class FuturesMirror:
t for t in self.trades if t.get("closed", 0) >= (self.coin_settings().get("since") or 0)]
stats = trade_stats(trades)
pos = dict(self.position) if self.position and self.state else None
return {"open": 1 if pos else 0, "state": self.state, "problem": self.problem, "position": pos,
return {"open": 1 if pos else 0, "state": self.state, "problem": self.storage_error or self.problem, "position": pos,
**stats, "positions": [pos] if pos else [], "enabled": self.enabled(),
"source": "биржа" if self.exchange_trades is not None else "программа",
"synced": self.synced, "sync_error": self.sync_error, "since": self.coin_settings().get("since"),
+43
View File
@@ -0,0 +1,43 @@
"""Validate the original browser request before proxying or executing local commands."""
from __future__ import annotations
import ipaddress
from urllib.parse import urlsplit
LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"}
def _authority(value: str):
try:
url = urlsplit("http://" + value)
if (url.hostname not in LOCAL_HOSTS or url.username is not None or url.password is not None
or url.path or url.query or url.fragment or any(c.isspace() for c in value)):
return None
return url.hostname, url.port or 80
except ValueError:
return None
def trusted_request(handler, *, command: bool = False) -> bool:
try:
if not ipaddress.ip_address(handler.client_address[0]).is_loopback:
return False
except ValueError:
return False
hosts = handler.headers.get_all("Host", [])
if len(hosts) != 1 or (host := _authority(hosts[0])) is None:
return False
origins = handler.headers.get_all("Origin", [])
if len(origins) > 1:
return False
if origins:
try:
origin = urlsplit(origins[0])
if (origin.scheme != "http" or origin.path or origin.query or origin.fragment
or _authority(origin.netloc) != host):
return False
except ValueError:
return False
if handler.headers.get("Sec-Fetch-Site") == "cross-site":
return False
return not command or handler.headers.get("X-Sim") == "1"
+3 -2
View File
@@ -1,2 +1,3 @@
websocket-client>=1.8,<2
numpy>=1.26
# Python 3.11+
websocket-client==1.8.0
numpy==2.3.5
+3 -7
View File
@@ -1,9 +1,5 @@
@echo off
rem Web simulator in two parts:
rem engine - python.exe web_sim.py --backend (127.0.0.1:8766, exchange data, stays in the VPN)
rem page - pythonw.exe web_proxy.py (0.0.0.0:8765, public; add pythonw.exe to the VPN exclusions)
rem Validate/repair the environment, then start the local proxy and engine.
cd /d "%~dp0"
start "web_proxy" pyw -3 web_proxy.py
start "" http://127.0.0.1:8765
py -3 web_sim.py --backend
pause
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0server_control.ps1" start
if errorlevel 1 pause
+45
View File
@@ -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
+231 -36
View File
@@ -21,21 +21,24 @@ 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 dataclass, field
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
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)
@@ -53,6 +56,8 @@ MODES = {"simple": "Простая (вход по рынку, выход при
@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)
@@ -137,6 +142,7 @@ class Position:
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
@@ -178,20 +184,59 @@ class Ledger:
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"))
self.balance = float(state.get("balance", self.settings.budget))
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(self.settings, key):
setattr(self.settings, key, type(getattr(self.settings, key))(value))
except (OSError, ValueError, TypeError):
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
if self.trades_path:
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:
@@ -220,38 +265,109 @@ class Ledger:
except OSError:
pass
def save(self) -> None:
if self.state_path:
try:
self.state_path.write_text(json.dumps({"balance": self.balance, "settings": vars(self.settings)},
ensure_ascii=False, indent=2), encoding="utf-8")
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]}
def reset(self) -> None:
for pos in list(self.positions): # positions dropped by a reset are closed for real too
for hook in self.hooks:
hook("close", pos)
@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
self.save()
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) -> Position:
notional = self.settings.stake * self.settings.leverage
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)
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)
self.save()
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
@@ -266,12 +382,15 @@ class Ledger:
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:
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)
for hook in self.hooks:
hook("close", 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
@@ -281,6 +400,14 @@ class Ledger:
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:
@@ -294,7 +421,6 @@ class Ledger:
trade.reason, f"{trade.hold_seconds:.1f}", trade.regime])
except OSError:
pass
self.save()
return trade
@@ -337,7 +463,7 @@ class SimplePolicy:
trader.message = (f"Сигнал {hint.side}, но до цели {target_pct:.2f}% < {self.s.min_target_pct:g}% — "
"сделка не открыта")
return
if led.balance < self.s.stake:
if led.available < self.s.stake:
trader.message = "Баланс меньше ставки — сделки остановлены"
return
led.open(ticker, hint.side, entry, now, TAKER, hint.target, None, mid)
@@ -426,7 +552,7 @@ class AdaptivePolicy:
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.balance < self.s.stake):
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)
@@ -570,7 +696,7 @@ class PulsePolicy:
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.balance < self.s.stake:
if trader.ledger.available < self.s.stake:
self.status = "Баланс меньше ставки — сделки остановлены"
return
best_bid, best_ask = self.book.best()
@@ -671,7 +797,7 @@ class SumsPolicy:
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.balance < s.stake or now - trader.last_close < s.cooldown_seconds:
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,
@@ -982,7 +1108,7 @@ class LeadPolicy:
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.balance < self.s.stake * (open_n + 1):
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
@@ -1160,6 +1286,45 @@ class PaperTrader:
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":
@@ -1194,6 +1359,8 @@ class PaperTrader:
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)."""
@@ -1218,19 +1385,28 @@ class PaperTrader:
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"):
@@ -1241,9 +1417,12 @@ class PaperTrader:
self.close(price, now, reason, TAKER, pos=pos)
def reset(self) -> None:
self.ledger.reset()
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()
@@ -1251,9 +1430,25 @@ class PaperTrader:
for pos in self.ledger.positions:
price = best_bid if pos.side == "LONG" else best_ask
if price is not None:
total += (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty
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)
+34
View File
@@ -0,0 +1,34 @@
"""Run offline tests. Loopback HTTP fixtures are allowed; exchange connections are forbidden."""
from pathlib import Path
import os
import subprocess
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.dont_write_bytecode = True
def offline(event, args):
if event == 'socket.connect':
host = args[1][0]
elif event == 'socket.getaddrinfo':
host = args[0]
else:
return
if host not in (None, 'localhost', '::1') and not str(host).startswith('127.'):
raise RuntimeError('External network is disabled during tests')
if __name__ == '__main__':
if len(sys.argv) == 1:
for suite in ('tests', 'meme_matcher/tests'):
result = subprocess.run([sys.executable, '-B', __file__, suite], cwd=ROOT)
if result.returncode:
sys.exit(result.returncode)
else:
os.chdir(ROOT)
sys.path.insert(0, str(ROOT))
sys.addaudithook(offline)
suite = unittest.defaultTestLoader.discover(str(ROOT / sys.argv[1]))
sys.exit(not unittest.TextTestRunner(verbosity=1).run(suite).wasSuccessful())
+30 -12
View File
@@ -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 {
if (Server-Processes) {
Write-Host "Не удалось проверить открытые реальные сделки через сервер." -ForegroundColor Yellow
$ans = Read-Host "Всё равно остановить процессы? Открытые позиции временно останутся без контроля. (y — да, иначе — нет)"
if ($ans -ne "y") { Write-Host "Остановка отменена."; exit 1 }
}
}
} catch {}
Set-Watchdog $false
# сначала цикл перезапуска (иначе он поднимет движок), потом движок и страница
foreach ($round in 1..3) {
@@ -64,15 +72,25 @@ if ((Server-Processes) -and (Answers)) {
Start-Process $Url
exit 0
}
$haveVenv = Test-Path (Join-Path $Dir ".venv\Scripts\pythonw.exe")
$havePy = [bool](Get-Command py -ErrorAction SilentlyContinue)
if (-not $haveVenv -and -not $havePy) {
Write-Host "Python и библиотеки ещё не установлены — устанавливаю..."
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) {
try {
& $VenvPython -B -c "import sys, websocket, numpy; sys.exit(0 if sys.version_info >= (3, 11) else 1)" 2>$null
$haveVenv = $LASTEXITCODE -eq 0
} catch { $haveVenv = $false }
}
if (-not $haveVenv) {
Write-Host "Окружение отсутствует или повреждено — запускаю восстановление..."
& powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Dir "setup.ps1") /install-only
if ($LASTEXITCODE -ne 0) { exit 1 }
}
Write-Host "Запускаю сервер в фоне (без окон)..."
Start-Process -FilePath "wscript.exe" -ArgumentList "`"$(Join-Path $Dir 'web_sim_autostart.vbs')`"" -WorkingDirectory $Dir
Start-Process -FilePath "wscript.exe" -ArgumentList "`"$(Join-Path $Dir 'web_sim_autostart.vbs')`"" -WorkingDirectory $Dir -WindowStyle Hidden
Set-Watchdog $true
foreach ($i in 1..45) {
if (Answers) {
+10 -4
View File
@@ -15,8 +15,11 @@ $VenvPyw = Join-Path $Dir ".venv\Scripts\pythonw.exe"
function Find-Python {
foreach ($v in "3.13", "3.12", "3.11", "3.10") {
try {
$exe = & py "-$v" -c "import sys; print(sys.executable)" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() }
$exe = & py "-$v" -c "import sys, json; print(json.dumps(sys.executable, ensure_ascii=True))" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) {
$path = $exe | ConvertFrom-Json
if (Test-Path -LiteralPath $path -PathType Leaf) { return $path }
}
} catch {}
}
foreach ($d in "Python313", "Python312", "Python311", "Python310") {
@@ -24,8 +27,11 @@ function Find-Python {
if (Test-Path $p) { return $p }
}
try {
$exe = & python -c "import sys; assert sys.version_info >= (3, 10); print(sys.executable)" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) { return $exe.Trim() }
$exe = & python -c "import sys, json; assert sys.version_info >= (3, 10); print(json.dumps(sys.executable, ensure_ascii=True))" 2>$null
if ($LASTEXITCODE -eq 0 -and $exe) {
$path = $exe | ConvertFrom-Json
if (Test-Path -LiteralPath $path -PathType Leaf) { return $path }
}
} catch {}
return $null
}
+83
View File
@@ -0,0 +1,83 @@
"""Independent adversarial account checks: an outage must not erase a known loss."""
import tempfile
import unittest
import json
from dataclasses import replace
from pathlib import Path
from unittest import mock
import cross
from virtual_account import AccountError, VirtualAccount
class MissingQuoteAccountingTests(unittest.TestCase):
def setUp(self):
journal = mock.patch.object(cross.CrossEngine, "_journal")
journal.start()
self.addCleanup(journal.stop)
def test_later_legacy_import_is_accounted_before_engine_starts(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
account = VirtualAccount(root / "wallet.json", 300)
cross.CrossEngine(root, start=False, account=account)
legacy = {"positions": [{"base": "XYZ", "opened": 1000, "qty": 100,
"spot_entry": 1, "fut_entry": 1.02, "entry_gap": 2,
"fees": .15, "funding": .02}]}
(root / "basis_bybit.json").write_text(json.dumps(legacy), encoding="utf-8")
again = cross.CrossEngine(root, start=False, account=account)
self.assertEqual(len(again.positions), 1)
self.assertEqual(len(account.restore("cross")["positions"]), 1)
self.assertAlmostEqual(account.view()["balance"], 300 - .15 + .02)
self.assertGreater(account.view()["reserved"], 200)
def test_unaffordable_later_import_is_not_adopted_without_reserved_cash(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
account = VirtualAccount(root / "wallet.json", 10)
cross.CrossEngine(root, start=False, account=account)
legacy = {"positions": [{"base": "XYZ", "opened": 1000, "qty": 100,
"spot_entry": 1, "fut_entry": 1.02, "entry_gap": 2, "fees": .15}]}
path = root / "basis_bybit.json"
path.write_text(json.dumps(legacy), encoding="utf-8")
again = cross.CrossEngine(root, start=False, account=account)
self.assertTrue(again.account_error)
self.assertFalse(again.settings.running)
self.assertEqual(again.positions, [])
self.assertEqual(account.view()["balance"], 10)
self.assertEqual(account.view()["reserved"], 0)
self.assertEqual(json.loads(path.read_text(encoding="utf-8")), legacy)
def test_missing_quote_and_settings_save_cannot_make_known_loss_withdrawable(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
account = VirtualAccount(root / "wallet.json", 300)
engine = cross.CrossEngine(root, start=False, account=account)
quote = cross.Link("XYZ", "Gate", "Binance", "XYZUSDT", "XYZUSDT",
.999, 1, 1.02, 1.021, 1e5, 1e5, 1e7, 1e7, .0001, 8)
engine.settings.amount = 100
engine.links[quote.key] = quote
engine._entries(1000, [{"link": quote, "fits": True, "net": 1, "usual": .5}])
engine.links[quote.key] = replace(quote, spot_bid=.5)
engine._mark_account(snapshot_fresh=True)
loss, free = account.view()["unrealized"], account.view()["free"]
self.assertLess(loss, -50)
self.assertLess(free, 50)
engine.links.clear() # one exchange vanished from the fresh market snapshot
self.assertEqual(engine.set_settings({"running": False}), "")
self.assertAlmostEqual(account.view()["unrealized"], loss)
self.assertAlmostEqual(account.view()["free"], free)
with self.assertRaises(AccountError):
account.adjust(-80, "must-not-withdraw-lost-money")
# The loss is in the authoritative position snapshot, not just an in-memory aggregate.
restored_account = VirtualAccount(root / "wallet.json")
restored = cross.CrossEngine(root, start=False, account=restored_account)
self.assertAlmostEqual(restored.positions[0].paper_unrealized, loss)
restored.save()
self.assertAlmostEqual(restored_account.view()["unrealized"], loss)
self.assertIn("cross", restored_account.view()["stale"])
if __name__ == "__main__":
unittest.main()
+42
View File
@@ -310,5 +310,47 @@ class CacheTests(unittest.TestCase):
self.assertEqual(len(hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path)[0]), 5)
class RiskRegressionTests(unittest.TestCase):
def test_percentage_and_absolute_drawdown_have_independent_peaks(self):
rows = [[0, 90, 90, 90, 90], [MIN, 100, 100, 100, 100],
[2 * MIN, 100, 100, 80, 80], [3 * MIN, 80, 200, 80, 200],
[4 * MIN, 200, 200, 170, 170]]
result = run({'AAA': rows}, {'AAA': cfg(stake=100, take_profit=0, max_adds=0)})
self.assertAlmostEqual(result['summary']['max_drawdown_usdt'], 30)
self.assertAlmostEqual(result['summary']['max_drawdown_pct'], 20)
def test_mode_capital_floor_precedes_later_stop_with_fees(self):
fixture = ModeBacktestTests()
candles = fixture.breakout_rows([(102.5, 102.6, 90, 91, 10)])
params = fixture.params(stake_pct=50, leverage=10, partial_r=0, partial_pct=0)
for fee in (0, 0.055):
with self.subTest(fee=fee):
result = hb.run_mode_backtest(candles, strategy.STRATEGY_BREAKOUT, params,
100, fee_pct=fee, min_equity_pct=95)
self.assertTrue(result['summary']['equity_stop_triggered'])
self.assertAlmostEqual(result['summary']['equity_at_stop_usdt'], 95)
self.assertTrue(any(t['status'] != 'CLOSED' for t in result['trades']))
def test_position_stop_before_capital_floor_is_not_skipped(self):
fixture = ModeBacktestTests()
result = fixture.run_mode(fixture.breakout_rows([(102.5, 102.6, 90, 91, 10)]),
fixture.params(stake_pct=50, leverage=10), min_equity_pct=80)
self.assertFalse(result['summary']['equity_stop_triggered'])
self.assertTrue(result['trades'][0]['reason'].startswith('Стоп'))
def test_short_floor_is_crossed_on_rising_price(self):
params = mode_params(strategy.STRATEGY_FADE, timeframe_min=60, min_growth_24h=30,
min_funding_pct=0, high_lookback_hours=6, pullback_pct=3, vwap_hours=6, atr_period=3,
stop_buffer_atr=0.5, max_stop_pct=30, trail_atr=0, take_profit_r=0,
partial_r=0, partial_pct=0, max_hold_hours=48, stake_pct=50, leverage=10)
rows = [(100, 101, 99, 100, 1)] * 20
rows += [(p - 2, p + 2, p - 4, p, 5) for p in (110, 125, 140, 150, 146)]
rows += [(146, 147, 128, 130, 5), (130, 160, 129, 155, 5)]
result = hb.run_mode_backtest({'AAA': minute_rows(rows, tf_min=60)}, strategy.STRATEGY_FADE,
params, 100, fee_pct=0.055, min_equity_pct=95)
self.assertEqual(result['trades'][0]['side'], 'SHORT')
self.assertAlmostEqual(result['summary']['equity_at_stop_usdt'], 95)
if __name__ == "__main__":
unittest.main()
+7 -2
View File
@@ -56,16 +56,21 @@ class SimulatorRemoveTests(unittest.TestCase):
engine = mock.Mock(conn={"x": 1}, lock=threading.RLock())
engine.name = "TRUMP: test"
engine.paper.ledger.positions = [object(), object()]
engine.close.side_effect = lambda uid: calls.append(("close", uid))
def close(uid):
calls.append(("close", uid))
engine.paper.ledger.positions = []
engine.close.side_effect = close
engine.mirror.ready_to_remove.return_value = True
engine.shutdown.side_effect = lambda: calls.append("shutdown")
sim = ws.Simulator.__new__(ws.Simulator)
sim.engines, sim.lock = {"k": engine}, threading.Lock()
sim.removals = mock.Mock()
with mock.patch.object(ws.lw, "remove_connection") as removed:
message = sim.remove("k")
removed.assert_called_once_with({"x": 1})
self.assertEqual(calls, [("close", None), "shutdown"])
self.assertNotIn("k", sim.engines)
self.assertFalse(engine.paper.settings.enabled)
engine.set_trading.assert_called_once_with(False)
self.assertIn("закрыто позиций: 2", message)
self.assertEqual(sim.remove("k"), "нет такой монеты")
+217
View File
@@ -0,0 +1,217 @@
"""Shared paper cash/reservation accounting, independent of live clients."""
import json
import sys
import tempfile
import time
import unittest
from dataclasses import asdict, replace
from pathlib import Path
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import cross
import virtual_account
from test_cross_real import link
class CrossAccountTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.directory = Path(self.tmp.name)
self.account = virtual_account.VirtualAccount(self.directory / "account.json", initial_balance=300)
self.e = cross.CrossEngine(self.directory, start=False, account=self.account)
self.e.settings.amount = 100
self.e.settings.running = True
self.e.settings.max_hold_hours = self.e.settings.stop_widen_pct = 0
self.e.settings.exit_hold_s = 0
self.e.limits = {ex: 10 for ex in self.e.limits}
self.l = link()
self.e.links[self.l.key] = self.l
self.e.save()
def enter(self, l=None):
l = l or self.l
self.e.links[l.key] = l
return self.e._entries(1000, [{"link": l, "fits": True, "net": 1.0, "usual": 0.5}])
def test_entry_reserves_both_legs_and_close_settles_cash_once(self):
self.assertTrue(self.enter())
pos = self.e.positions[0]
metrics = self.account.view()
expected_reserve = 100 + max(102 * self.e.FUT_NEED, cross.equity_for(self.e.settings.min_liq_pct, 102))
self.assertAlmostEqual(metrics["balance"], 300 - pos.fees)
self.assertAlmostEqual(metrics["reserved"], expected_reserve)
self.assertEqual(len(self.account.restore("cross")["positions"]), 1)
self.assertTrue(self.e._close(pos, self.l, 1001, "test"))
net = self.e.trades[0].net
self.assertAlmostEqual(self.account.view()["balance"], 300 + net)
self.assertEqual(self.account.view()["reserved"], 0)
self.e.save()
self.assertAlmostEqual(self.account.view()["balance"], 300 + net)
def test_delayed_fill_charges_and_reserves_once_then_close_settles(self):
self.e.quote_now = mock.Mock(return_value=(self.l.spot_bid, self.l.spot_ask, self.l.fut_bid, self.l.fut_ask, 0, 0))
self.e._still_good = mock.Mock(return_value=self.l)
self.e.candidates = mock.Mock(return_value=[{"fits": True}])
with mock.patch.object(cross.threading, "Timer") as timer:
self.assertTrue(self.enter())
self.assertEqual(self.e.positions, [])
self.assertEqual(self.account.view()["balance"], 300)
self.assertFalse(self.enter())
self.assertEqual(timer.call_count, 1)
_, callback = timer.call_args.args
self.assertTrue(callback(*timer.call_args.kwargs["args"]))
pos = self.e.positions[0]
self.assertAlmostEqual(self.account.view()["balance"], 300 - pos.fees)
self.assertGreater(self.account.view()["reserved"], 200)
self.assertTrue(self.e._schedule_paper_close(pos.uid, "test"))
self.assertFalse(self.e._schedule_paper_close(pos.uid, "test"))
_, callback = timer.call_args.args
self.assertTrue(callback(*timer.call_args.kwargs["args"]))
self.assertEqual(self.account.view()["reserved"], 0)
self.assertAlmostEqual(self.account.view()["balance"], 300 + self.e.trades[0].net)
def test_delayed_fill_rechecks_shared_cash_at_execution(self):
self.e.quote_now = mock.Mock(return_value=(self.l.spot_bid, self.l.spot_ask, self.l.fut_bid, self.l.fut_ask, 0, 0))
self.e._still_good = mock.Mock(return_value=self.l)
self.e.candidates = mock.Mock(return_value=[{"fits": True}])
with mock.patch.object(cross.threading, "Timer") as timer:
self.assertTrue(self.enter())
self.account.commit("simulator:other", {}, cash_total=0, reserved=150)
_, callback = timer.call_args.args
self.assertFalse(callback(*timer.call_args.kwargs["args"]))
self.assertEqual(self.e.positions, [])
self.assertEqual(self.account.view()["balance"], 300)
self.assertEqual(self.account.view()["reserved"], 150)
self.assertFalse(self.e.settings.running)
def test_other_owner_reservation_blocks_entry_without_cash_or_state_change(self):
self.account.commit("simulator:other", {}, cash_total=0, reserved=150)
before = self.account.view()["balance"]
self.assertFalse(self.enter())
self.assertEqual(self.e.positions, [])
self.assertEqual(self.e.cash_total, 0)
self.assertEqual(self.account.restore("cross")["positions"], [])
self.assertEqual(self.account.view()["balance"], before)
self.assertEqual(self.account.view()["reserved"], 150)
self.assertFalse(self.e.settings.running)
self.assertIn("Недостаточно", self.e.account_error)
def test_top_up_and_explicit_start_clear_rejected_entry(self):
self.account.commit("simulator:other", {}, cash_total=0, reserved=150)
self.assertFalse(self.enter())
self.account.adjust(100, "topup-test-1")
self.assertEqual(self.e.set_settings({"running": True}), "")
self.assertEqual(self.e.account_error, "")
self.assertTrue(self.enter())
def test_funding_is_credited_once_and_not_credited_again_at_close(self):
self.enter()
pos = self.e.positions[0]
when = pos.next_funding
entry_balance = self.account.view()["balance"]
self.e._check_exits(when)
self.e.save(event="funding")
funding = pos.funding
self.assertGreater(funding, 0)
self.assertAlmostEqual(self.account.view()["balance"], entry_balance + funding)
self.e._check_exits(when)
self.e.save()
self.assertAlmostEqual(self.account.view()["balance"], entry_balance + funding)
self.e._close(pos, self.l, when + 1, "test")
self.assertAlmostEqual(self.account.view()["balance"], 300 + self.e.trades[0].net)
def test_failed_account_write_rolls_back_entry_and_close(self):
with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")):
self.assertFalse(self.enter())
self.assertEqual(self.e.positions, [])
self.assertEqual(self.account.view()["balance"], 300)
self.e.set_settings({"running": True})
self.enter()
before = self.account.view()
with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")):
self.assertFalse(self.e._close(self.e.positions[0], self.l, 1001, "test"))
self.assertEqual(len(self.e.positions), 1)
self.assertEqual(self.e.trades, [])
self.assertEqual(self.account.view()["balance"], before["balance"])
self.assertEqual(self.account.view()["reserved"], before["reserved"])
def test_restart_uses_authoritative_account_snapshot_not_legacy_file(self):
self.enter()
before = self.account.view()
self.e.file.write_text(json.dumps({"positions": [], "cash_total": 100000}), encoding="utf-8")
account = virtual_account.VirtualAccount(self.directory / "account.json")
again = cross.CrossEngine(self.directory, start=False, account=account)
self.assertEqual(len(again.positions), 1)
self.assertEqual(again.cash_total, self.e.cash_total)
self.assertEqual(account.view()["balance"], before["balance"])
self.assertEqual(account.view()["reserved"], before["reserved"])
def test_reset_preserves_cash_and_cannot_erase_reserved_positions(self):
self.enter()
self.assertIn("сначала закройте", self.e.reset())
self.assertEqual(len(self.e.positions), 1)
self.e._close(self.e.positions[0], self.l, 1001, "test")
before = self.account.view()["balance"]
cash = self.e.cash_total
self.assertEqual(self.e.reset(), "статистика сброшена")
self.assertEqual(self.e.trades, [])
self.assertEqual(self.e.cash_total, cash)
self.assertEqual(self.account.view()["balance"], before)
again = cross.CrossEngine(self.directory, start=False, account=self.account)
self.assertEqual(again.cash_total, cash)
def test_one_fresh_link_cannot_refresh_all_open_positions(self):
self.account.adjust(1000, "freshness-deposit")
self.enter()
other = replace(self.l, base="OTHER", spot_symbol="OTHERUSDT", fut_symbol="OTHERUSDT")
self.enter(other)
self.account.marks["cross"] = (self.e._unrealized(), 0)
self.e.updated = 0
self.e.fast_seen = {self.l.key: time.time()}
self.e._mark_account()
self.e.save() # a settings/checkpoint save is not a fresh price
self.assertIn("cross", self.account.view()["stale"])
self.e.fast_seen[other.key] = time.time()
self.e._mark_account()
self.assertNotIn("cross", self.account.view()["stale"])
def test_margin_setting_does_not_release_existing_position_collateral(self):
self.account.adjust(1000, "frozen-margin-deposit")
self.e.set_settings({"min_liq_pct": 300})
self.enter()
held = self.account.view()["reserved"]
self.assertGreater(held, 400)
self.assertEqual(self.e.positions[0].paper_reserve, held)
self.assertEqual(self.e.set_settings({"min_liq_pct": 0}), "")
self.assertEqual(self.account.view()["reserved"], held)
again = cross.CrossEngine(self.directory, start=False, account=self.account)
self.assertEqual(again._reserved(), held)
self.assertEqual(again.positions[0].paper_reserve, held)
other = replace(self.l, base="OTHER", spot_symbol="OTHERUSDT", fut_symbol="OTHERUSDT")
self.enter(other)
self.assertAlmostEqual(self.account.view()["reserved"] - held, 100 + 102 * self.e.FUT_NEED)
def test_first_legacy_migration_imports_open_costs_without_closed_history(self):
directory = self.directory / "legacy"
directory.mkdir()
old = cross.CrossEngine(directory, start=False)
old.settings.amount = 100
old.links[self.l.key] = self.l
old._entries(1000, [{"link": self.l, "fits": True, "net": 1.0, "usual": 0.5}])
old.positions[0].funding = 0.25
old.save()
account = virtual_account.VirtualAccount(directory / "account.json", initial_balance=10)
again = cross.CrossEngine(directory, start=False, account=account)
pos = again.positions[0]
self.assertAlmostEqual(account.view()["balance"], 10 + pos.funding - pos.fees)
self.assertGreater(account.view()["deficit"], 0)
self.assertEqual(len(again.positions), 1)
before = account.view()["balance"]
cross.CrossEngine(directory, start=False, account=account)
self.assertEqual(account.view()["balance"], before)
if __name__ == "__main__":
unittest.main()
+203
View File
@@ -0,0 +1,203 @@
"""Real execution reconciliation with fake clients only; no exchange requests."""
import json
import sys
import unittest
from dataclasses import asdict, replace
from pathlib import Path
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import cross
import live
import test_cross_real
class ExecutionSafetyTests(unittest.TestCase):
def setUp(self):
self.fixture = test_cross_real.CrossRealTests()
self.fixture.setUp()
self.addCleanup(self.fixture.tearDown)
self.e, self.a, self.b = self.fixture.e, self.fixture.a, self.fixture.b
def open_partial(self):
def buy(base, usdt):
self.a.spot_balance = 10.0
return live.Fill(10.0, 1.0, 0.01, "partial")
self.a.spot_buy = buy
self.e.step(1000)
self.fixture.run_jobs()
def restart(self):
again = cross.CrossEngine(Path(self.fixture.dir.name), start=False, real=True)
again.client_for = self.e.client_for
return again
def open_ss(self):
link = replace(test_cross_real.link(), ss=True)
self.e.links = {link.key: link}
self.b.spot_balance = 200.0
self.e._real_open_ss(link, 0.5, 100.0)
return self.e.positions[0]
def test_partial_spot_fill_unwinds_both_legs(self):
self.open_partial()
self.assertEqual(self.b.position, 0)
self.assertEqual(self.a.spot_balance, 0)
self.assertEqual(self.e.positions, [])
self.assertIn("частичный хедж", self.e.trades[0].reason)
def test_partial_hedge_intent_is_on_disk_before_unwind_order(self):
original = self.b.fut_order
def order(symbol, side, coins, reduce_only, **kwargs):
if reduce_only:
saved = json.loads(self.e.file.read_text(encoding="utf-8"))
self.assertEqual(saved["positions"][0]["closing"], "hedge_mismatch")
return original(symbol, side, coins, reduce_only, **kwargs)
self.b.fut_order = order
self.open_partial()
self.assertEqual(self.e.positions, [])
def test_failed_entry_handoff_retains_on_disk_intent_without_replaying_entry(self):
original = cross.atomic_write_json
def write(path, data):
if data.get("positions") and not data.get("pending"):
raise OSError("handoff write failed")
return original(path, data)
with mock.patch.object(cross, "atomic_write_json", side_effect=write):
self.e.step(1000)
self.fixture.run_jobs()
saved = json.loads(self.e.file.read_text(encoding="utf-8"))
self.assertEqual(saved["pending"]["XYZ"]["phase"], "hedge_confirmed")
a_count, b_count = len(self.a.orders), len(self.b.orders)
again = self.restart()
again.step(1001)
while not again.jobs.empty():
again.do_job(again.jobs.get())
self.assertEqual((len(self.a.orders), len(self.b.orders)), (a_count, b_count))
self.assertEqual(len(again.positions), 1)
self.assertEqual(again.recover, {})
def test_partial_hedge_close_rejection_survives_restart_without_listing(self):
self.b.fail_close = 1
self.open_partial()
saved = json.loads(self.e.file.read_text(encoding="utf-8"))
self.assertEqual(saved["positions"][0]["closing"], "hedge_mismatch")
self.assertEqual(self.b.position, -99)
again = self.restart()
again.positions[0].retry_at = 0
again.step(1001)
while not again.jobs.empty():
again.do_job(again.jobs.get())
self.assertEqual(again.positions, [])
self.assertEqual(self.b.position, 0)
self.assertEqual(self.a.spot_balance, 0)
def test_restart_between_confirmed_partial_fill_and_position_unwinds(self):
link = test_cross_real.link()
self.b.position, self.a.spot_balance = -99.0, 10.0
self.e.pending["XYZ"] = {"phase": "hedge_confirmed", "link": asdict(link), "key": link.key,
"coins": 99.0, "shorted": 99.0, "usual": 0.5,
"buy": asdict(live.Fill(10, 1, 0.01, "partial")),
"fut_price": 1.02, "fut_fee": 0.05}
self.e.save()
again = self.restart()
again.step(1001)
while not again.jobs.empty():
again.do_job(again.jobs.get())
self.assertEqual(self.b.position, 0)
self.assertEqual(self.a.spot_balance, 0)
self.assertEqual(again.positions, [])
self.assertEqual(again.recover, {})
def test_unknown_ss_buy_never_sells_a_or_repeats_buy_after_restart(self):
pos = self.open_ss()
before = self.a.spot_balance
self.b.spot_buy = mock.Mock(side_effect=live.LiveError("lost response", sent=True, order_id="lost"))
self.e._real_close(pos.uid, "test")
self.assertEqual(pos.close_buy["phase"], "unknown")
self.assertEqual(self.a.spot_balance, before)
self.assertEqual(len(self.e.positions), 1)
self.assertEqual(self.e.trades, [])
other = replace(test_cross_real.link(), base="OTHER")
self.assertFalse(self.e._entries(2000, [{"link": other, "fits": True, "net": 1.0, "usual": 0.5}]))
self.assertTrue(self.e.jobs.empty())
again = self.restart()
# Even a later balance increase alone is not proof that this particular order completed.
self.b.spot_balance += pos.qty
again._real_close(pos.uid, "retry")
self.assertEqual(self.b.spot_buy.call_count, 1)
self.assertEqual(self.a.spot_balance, before)
self.assertIn("ручная сверка", again.positions[0].error)
def test_ss_buy_intent_is_durable_before_submit(self):
pos = self.open_ss()
original = self.b.spot_buy
def buy(base, usdt):
saved = json.loads(self.e.file.read_text(encoding="utf-8"))
self.assertEqual(saved["positions"][0]["close_buy"]["phase"], "submitted")
return original(base, usdt)
self.b.spot_buy = buy
self.e._real_close(pos.uid, "test")
self.assertEqual(self.e.positions, [])
self.assertGreaterEqual(self.b.spot_balance, 200)
def test_ss_buy_not_sent_when_intent_save_fails(self):
pos = self.open_ss()
self.b.spot_buy = mock.Mock()
with mock.patch.object(self.e, "save", side_effect=OSError("disk full")):
with self.assertRaises(OSError):
self.e._real_close(pos.uid, "test")
self.b.spot_buy.assert_not_called()
self.assertEqual(pos.close_buy, {})
def test_ss_buy_response_checkpoint_failure_cannot_replay_after_restart(self):
pos = self.open_ss()
original = cross.atomic_write_json
original_buy = self.b.spot_buy
self.b.spot_buy = mock.Mock(side_effect=original_buy)
def write(path, data):
if any(p.get("close_buy", {}).get("phase") == "confirmed" for p in data.get("positions", [])):
raise OSError("fill checkpoint failed")
return original(path, data)
with mock.patch.object(cross, "atomic_write_json", side_effect=write):
with self.assertRaises(OSError):
self.e._real_close(pos.uid, "test")
saved = json.loads(self.e.file.read_text(encoding="utf-8"))
self.assertEqual(saved["positions"][0]["close_buy"]["phase"], "submitted")
self.assertGreater(self.b.spot_balance, 200)
again = self.restart()
again._real_close(pos.uid, "retry")
self.assertEqual(self.b.spot_buy.call_count, 1)
self.assertGreater(self.a.spot_balance, 0)
self.assertIn("ручная сверка", again.positions[0].error)
def test_partial_ss_repurchase_keeps_a_and_does_not_repeat(self):
pos = self.open_ss()
before = self.a.spot_balance
def buy(base, usdt):
self.b.spot_balance += 5
return live.Fill(5, 1.02, 0.0051, "partial")
self.b.spot_buy = mock.Mock(side_effect=buy)
self.e._real_close(pos.uid, "test")
again = self.restart()
again._real_close(pos.uid, "retry")
self.assertEqual(self.b.spot_buy.call_count, 1)
self.assertEqual(self.a.spot_balance, before)
self.assertEqual(len(again.positions), 1)
def test_confirmed_ss_buy_waits_for_balance_without_duplicate_order(self):
pos = self.open_ss()
before = self.a.spot_balance
self.b.spot_buy = mock.Mock(return_value=live.Fill(pos.qty * 1.01, 1.02, 0.1, "confirmed"))
self.e._real_close(pos.uid, "test")
self.assertEqual(self.a.spot_balance, before)
self.b.spot_balance += pos.qty
again = self.restart()
again._real_close(pos.uid, "retry")
self.assertEqual(self.b.spot_buy.call_count, 1)
self.assertEqual(again.positions, [])
self.assertEqual(self.a.spot_balance, 0)
if __name__ == "__main__":
unittest.main()
+95
View File
@@ -0,0 +1,95 @@
"""Durable recovery of rejected/partial rollback and uncertain entry cancellation."""
import json
import sys
import time
import unittest
from pathlib import Path
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import cross
import live
import test_cross_real
class RecoveryTests(unittest.TestCase):
def setUp(self):
self.fixture = test_cross_real.CrossRealTests()
self.fixture.setUp()
self.addCleanup(self.fixture.tearDown)
self.e, self.a, self.b = self.fixture.e, self.fixture.a, self.fixture.b
def open(self):
self.e.step(1000)
self.fixture.run_jobs()
def recover(self):
info = self.e.recover['XYZ']
info['retry_at'] = 0
self.e.step(1001)
self.fixture.run_jobs()
def test_failed_and_partial_rollback_remain_durable_until_confirmed_flat(self):
self.a.spot_buy = mock.Mock(side_effect=live.LiveError('rejected'))
self.b.fail_close = 1
self.open()
self.assertEqual(self.b.position, -99)
self.assertEqual(self.e.recover['XYZ']['phase'], 'rollback')
saved = json.loads(self.e.file.read_text(encoding='utf-8'))
self.assertEqual(saved['pending']['XYZ']['phase'], 'rollback')
self.b.partial_close = 5
self.recover()
self.assertEqual(self.b.position, -5)
self.assertIn('XYZ', self.e.recover)
self.recover()
self.assertEqual(self.b.position, 0)
self.assertEqual(self.e.recover, {})
self.assertEqual(self.e.pending, {})
def test_failed_cancel_blocks_entries_and_late_fill_is_closed_after_restart(self):
self.e.settings.entry_limit, self.e.settings.limit_hold_s = True, 0
self.b.limit_fill = 0
cancel = self.b.fut_cancel
self.b.fut_cancel = mock.Mock(side_effect=live.LiveError('timeout', sent=True))
self.open()
self.assertTrue(self.b.limits['L1']['open'])
self.assertEqual(self.e.recover['XYZ']['order_id'], 'L1')
self.assertEqual(self.a.orders, [])
self.e.step(2000)
self.assertTrue(self.e.jobs.empty())
self.b.fill_take_profit('L1') # fake exchange fills the still-working short
self.b.fut_cancel = cancel
again = cross.CrossEngine(Path(self.fixture.dir.name), start=False, real=True)
again.client_for = self.e.client_for
again.recover['XYZ']['retry_at'] = 0
# No current listing is needed: the intent contains its instrument snapshot.
again.step(2001)
while not again.jobs.empty():
again.do_job(again.jobs.get())
self.assertEqual(self.b.position, 0)
self.assertEqual(again.recover, {})
self.assertEqual(again.pending, {})
def test_unknown_submit_without_id_is_not_declared_absent_when_flat(self):
self.e.settings.entry_limit = True
self.b.fut_limit = mock.Mock(side_effect=live.LiveError('lost response', sent=True))
self.open()
self.assertIn('XYZ', self.e.recover)
self.recover()
self.assertIn('XYZ', self.e.recover)
self.assertEqual(self.b.fut_limit.call_count, 1)
self.assertIn('сверка', self.e.view()['real_pause'])
def test_no_order_when_intent_cannot_be_saved(self):
with mock.patch.object(cross, 'atomic_write_json', side_effect=OSError('disk full')):
# Queue directly: failing the pre-order durable intent must prevent every order.
self.e.do_job(('open', next(iter(self.e.links.values())), 0.5, 100))
self.assertEqual(self.a.orders + self.b.orders, [])
def test_successful_entry_is_handed_off_without_pending_recovery(self):
self.open()
self.assertEqual(len(self.e.positions), 1)
self.assertEqual(self.e.recover, {})
saved = json.loads(self.e.file.read_text(encoding='utf-8'))
self.assertEqual(saved['pending'], {})
self.assertEqual(len(saved['positions']), 1)
+30
View File
@@ -0,0 +1,30 @@
"""Ambiguous mutating HTTP responses must trigger reconciliation, not a fresh entry."""
import sys
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import live
class UncertainResponseTests(unittest.TestCase):
def request(self, method, status, body):
response = mock.Mock(status=status, will_close=True)
response.read.return_value = body
response.getheader.return_value = 'close'
connection = mock.Mock()
connection.getresponse.return_value = response
with mock.patch.object(live, '_take', return_value=(connection, False)):
with self.assertRaises(live.LiveError) as error:
live._http(method, 'https://exchange.invalid/order')
return error.exception
def test_server_error_on_submit_is_uncertain(self):
self.assertTrue(self.request('POST', 503, b'unavailable').sent)
self.assertTrue(self.request('DELETE', 500, b'error').sent)
self.assertFalse(self.request('GET', 503, b'unavailable').sent)
self.assertFalse(self.request('POST', 400, b'rejected').sent)
def test_unreadable_success_response_is_uncertain(self):
self.assertTrue(self.request('POST', 200, b'{truncated').sent)
+96
View File
@@ -0,0 +1,96 @@
"""Crash windows and filesystem failures must never cause a second entry."""
import json
import sys
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import real_mirror
from test_real import FakeClient
class MirrorRecoveryTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.client = FakeClient(price=1)
self.settings = {'coins': {'k': {'on': True}}, 'exchange_tpsl': True}
self.threads = mock.patch.object(real_mirror.threading.Thread, 'start')
self.threads.start()
self.addCleanup(self.threads.stop)
self.journal = mock.patch.object(real_mirror, 'journal')
self.journal.start()
self.addCleanup(self.journal.stop)
def mirror(self):
return real_mirror.FuturesMirror('k', 'X', 'bybit', 'XUSDT', Path(self.tmp.name),
client_for=lambda ex: self.client, settings=lambda: self.settings)
def prepare(self, m):
m.hook('open', SimpleNamespace(uid=1, side='LONG', qty=10, entry=1, target=1.02))
def test_restart_before_submission_never_replays_entry(self):
m = self.mirror()
self.prepare(m)
self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'prepared')
again = self.mirror()
again._recover_open()
self.assertEqual(self.client.orders, [])
self.assertIsNone(again.position)
def test_crash_after_exchange_accepts_is_contained_and_never_replayed(self):
m = self.mirror()
self.prepare(m)
order = self.client.fut_order
def crash(*args, **kwargs):
self.assertEqual(json.loads(m.file.read_text())['position']['phase'], 'submitted')
order(*args, **kwargs)
raise SystemExit('power loss')
with mock.patch.object(self.client, 'fut_order', side_effect=crash):
with self.assertRaises(SystemExit):
m._open()
again = self.mirror()
again._recover_open()
self.assertEqual(self.client.position, 0)
self.assertTrue(again.gate())
again._close('paper closed')
self.assertEqual(again.state, 'recover')
self.prepare(again)
self.assertEqual(sum(not o[3] for o in self.client.orders), 1)
def test_accepted_fill_is_saved_before_take_profit_request(self):
m = self.mirror()
self.prepare(m)
def crash(*args):
saved = json.loads(m.file.read_text())['position']
self.assertEqual(saved['phase'], 'filled')
self.assertEqual(saved['coins'], 10)
raise SystemExit('power loss')
with mock.patch.object(self.client, 'fut_take_profit', side_effect=crash):
with self.assertRaises(SystemExit):
m._open()
again = self.mirror()
again._close('restart')
self.assertEqual(self.client.position, 0)
self.assertIsNone(again.position)
def test_failed_persistence_blocks_order_and_is_visible(self):
m = self.mirror()
with mock.patch.object(real_mirror, 'atomic_write_json', side_effect=OSError('disk full')):
self.prepare(m)
self.assertEqual(self.client.orders, [])
self.assertTrue(m.jobs.empty())
self.assertIn('disk full', m.gate())
m._watch()
self.assertIsNone(m.position)
def test_corrupt_saved_state_blocks_new_entries(self):
Path(self.tmp.name, 'real_positions_k.json').write_text('{broken', encoding='utf-8')
m = self.mirror()
self.prepare(m)
self.assertEqual(m.state, 'blocked')
self.assertTrue(m.gate())
self.assertEqual(self.client.orders, [])
+54
View File
@@ -0,0 +1,54 @@
import threading
import time
import unittest
from types import SimpleNamespace as NS
from unittest.mock import Mock, patch
import paper_execution
class ExecutionTests(unittest.TestCase):
def setUp(self):
self.fills = []
def enter(ticker, side, price, now, fee_pct, target, stop, entry_mid,
regime='', features=None, notional_usd=None):
self.fills.append((price, target))
def close(price, now, reason, fee_pct, utc=None, pos=None):
self.fills.append(price)
settings = NS(simulation_entry_delay_ms=600, simulation_exit_delay_ms=800,
max_data_age_ms=2000, enabled=True, follow_exchange='bybit',
follow_ticker='TESTUSDT', stake=10, leverage=1)
self.trader = NS(settings=settings, ledger=NS(open=enter, positions=[]), close=close)
self.engine = NS(paper=self.trader, lock=threading.RLock(), stopped=threading.Event(),
last_follower=time.time(), book=NS(best=lambda: (109, 110)), removing=False,
mirror=NS(settings=lambda: {}, ping=lambda: 10))
paper_execution.install(self.engine)
def enqueue(self, timer):
self.trader.ledger.open('TEST', 'LONG', 100, time.time(), .05, 102, 99, 100)
self.assertEqual(timer.call_args.args[0], .6)
self.assertEqual(self.fills, [])
return timer.call_args.args[1]
def test_execution_uses_new_quote_and_rebases_targets(self):
with patch('paper_execution.threading.Timer') as timer, patch('minorder.RULES.fut', return_value={'usd': 5}):
self.enqueue(timer)()
self.assertEqual(len(self.fills), 1)
self.assertEqual(self.fills[0][0], 110)
self.assertAlmostEqual(self.fills[0][1], 112.2)
def test_stopped_or_stale_signal_never_spends(self):
with patch('paper_execution.threading.Timer') as timer:
callback = self.enqueue(timer)
self.trader.settings.enabled = False
callback()
self.assertEqual(self.fills, [])
self.trader.settings.enabled = True
callback = self.enqueue(timer)
self.engine.last_follower = 0
callback()
self.assertEqual(self.fills, [])
def test_missing_lot_blocks_entry(self):
with patch('paper_execution.threading.Timer') as timer, patch('minorder.RULES.fut', return_value=None):
self.enqueue(timer)()
self.assertEqual(self.fills, [])
+224
View File
@@ -0,0 +1,224 @@
"""Offline regression cases for recovery, shared collateral and partial paper fills."""
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import algo_hunter as ah
import scalp_hint as sh
import scalp_paper as sp
from virtual_account import VirtualAccount
def trader(folder=None, mode="simple", stake=6.0, leverage=1.0):
paths = (Path(folder) / "paper.json", Path(folder) / "trades.csv") if folder else (None, None)
return sp.PaperTrader(sp.PaperSettings(mode=mode, stake=stake, leverage=leverage), sh.HintSettings(), *paths)
def open_position(t, price=100, now=100):
return t.ledger.open("AAA", "LONG", price, now, 0.1, 110, 90, price)
def book(bid=100, ask=101):
result = sh.OrderBook()
result.bids, result.asks = {bid: 1000}, {ask: 1000}
return result
class RecoveryTests(unittest.TestCase):
def test_corrupt_snapshot_is_not_overwritten_by_new_entry(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "paper.json"
path.write_text('{"balance": 299, "positions": [', encoding="utf-8")
previous = path.read_bytes()
t = trader(folder)
self.assertIsNone(open_position(t))
self.assertEqual(path.read_bytes(), previous)
self.assertEqual(t.balance, 300)
self.assertIn("восстановить", t.ledger.storage_error)
def test_open_position_survives_restart_and_closes_once(self):
with tempfile.TemporaryDirectory() as folder:
first = trader(folder)
position = open_position(first)
restored = trader(folder)
self.assertEqual(restored.position, position)
restored.close(105, 110, "manual", 0.1)
again = trader(folder)
self.assertIsNone(again.position)
self.assertEqual(len(again.trades), 1)
self.assertAlmostEqual(again.balance, 300 + again.trades[0].net_usd)
next_position = open_position(again, now=120)
self.assertGreater(next_position.uid, position.uid)
def test_atomic_write_failure_preserves_snapshot_and_memory(self):
with tempfile.TemporaryDirectory() as folder:
t = trader(folder)
open_position(t)
path = Path(folder) / "paper.json"
previous = path.read_bytes()
previous_balance = t.balance
with patch("scalp_paper.atomic_write_json", side_effect=OSError("disk full")):
t.close(105, 110, "manual", 0.1)
self.assertEqual(path.read_bytes(), previous)
self.assertIsNotNone(t.position)
self.assertEqual(t.trades, [])
self.assertEqual(t.balance, previous_balance)
self.assertIn("disk full", t.message)
def test_hunter_restores_exit_levels_and_risk_guard(self):
with tempfile.TemporaryDirectory() as folder:
t = trader(folder, mode="algo_hunter")
policy = t.policy
policy.tick, policy.ticker = 1.0, "AAA"
policy.guard.daily_pnl = -7.5
policy.guard.pause_until = 1000
policy.guard.disabled_reason = "risk test"
policy.order = ah.HunterOrder("LONG", 100, 6, 99, 99, "test",
ah.AlgoSignature("bid", [100], [10], .9, 99, ["test"], 10), ahead=0)
policy._fill(t, 100, 2)
t.last_close = 80
t.ledger.save()
restored = trader(folder, mode="algo_hunter")
self.assertEqual(restored.position.qty, .02)
self.assertEqual(restored.policy.stop, t.policy.stop)
self.assertEqual(restored.policy.target, t.policy.target)
self.assertEqual(restored.policy.filled_at, 100)
self.assertEqual(restored.last_close, 80)
self.assertEqual(restored.policy.guard.daily_pnl, -7.5)
self.assertEqual(restored.policy.guard.pause_until, 1000)
self.assertEqual(restored.policy.guard.disabled_reason, "risk test")
self.assertIsNone(restored.policy.order)
restored.policy._close(restored, 101, 110, "manual", 0.1)
self.assertIsNone(restored.position)
class PartialFillTests(unittest.TestCase):
def pending(self, ahead=100):
t = trader(mode="algo_hunter", stake=20)
t.policy.tick, t.policy.ticker = 1, "AAA"
signature = ah.AlgoSignature("bid", [100], [ahead], .9, 99, ["test"], ahead)
t.policy.order = ah.HunterOrder("LONG", 100, 20, 99, 99, "test", signature, ahead=ahead)
return t
def test_trade_equal_to_queue_does_not_fill_us(self):
t = self.pending()
t.on_trade(sh.Trade(100, 100, 100, "Sell"))
self.assertIsNone(t.position)
self.assertEqual(t.policy.order.ahead, 0)
t.on_trade(sh.Trade(101, 100, 3, "Sell"))
self.assertAlmostEqual(t.position.qty * t.position.entry, 3)
self.assertAlmostEqual(t.position.fee_in, 3 * sh.MAKER_FEE_PCT / 100)
self.assertEqual(t.position.margin, 3)
self.assertIsNone(t.policy.order) # conservative cancellation of unfilled remainder
def test_only_volume_after_queue_can_fill(self):
t = self.pending()
t.on_trade(sh.Trade(100, 100, 102, "Sell"))
self.assertAlmostEqual(t.position.qty * t.position.entry, 2)
self.assertEqual(t.policy.entry_order.size_usd, 2)
def test_fill_cannot_exceed_requested_size(self):
t = self.pending()
t.on_trade(sh.Trade(100, 100, 200, "Sell"))
self.assertAlmostEqual(t.position.qty * t.position.entry, 20)
def test_wrong_trade_side_does_not_consume_queue(self):
t = self.pending()
t.on_trade(sh.Trade(100, 100, 200, "Buy"))
self.assertIsNone(t.position)
self.assertEqual(t.policy.order.ahead, 100)
class SharedAccountTests(unittest.TestCase):
def test_common_top_up_unblocks_policy_despite_old_local_balance(self):
with tempfile.TemporaryDirectory() as folder:
account = VirtualAccount(Path(folder) / "account.json", 1)
t = trader()
t.ledger.balance = 1
t.bind_account(account, "coin")
hint = sh.Hint("LONG", "test", .9, target=110)
t.on_tick(100, "AAA", hint, book(), 1)
self.assertIsNone(t.position)
account.adjust(10, "test-top-up")
t.on_tick(101, "AAA", hint, book(), 1)
self.assertIsNotNone(t.position)
self.assertLess(t.balance, 1) # accounting baseline is separate from the common spending limit
def test_two_coins_share_capital_and_close_releases_margin(self):
with tempfile.TemporaryDirectory() as folder:
account = VirtualAccount(Path(folder) / "account.json", 10)
first, second = trader(), trader()
first.bind_account(account, "first")
second.bind_account(account, "second")
self.assertIsNotNone(open_position(first))
first.mark_account(book())
self.assertIsNone(open_position(second))
self.assertIn("Недостаточно", second.ledger.storage_error)
self.assertEqual(second.ledger.positions, [])
self.assertEqual(account.view()["reserved"], 6)
first.close(100, 110, "manual", 0.1)
self.assertEqual(account.view()["reserved"], 0)
self.assertIsNotNone(open_position(second))
self.assertAlmostEqual(account.view()["balance"], 10 - .006 * 3)
def test_failed_shared_commit_does_not_trigger_hooks_or_change_exposure(self):
with tempfile.TemporaryDirectory() as folder:
account = VirtualAccount(Path(folder) / "account.json", 10)
t = trader()
t.bind_account(account, "coin")
events = []
t.ledger.hooks.append(lambda event, pos: events.append(event))
with patch("virtual_account.atomic_write_json", side_effect=OSError("disk full")):
self.assertIsNone(open_position(t))
self.assertEqual(events, [])
self.assertEqual(t.balance, 300)
self.assertEqual(account.view()["reserved"], 0)
self.assertEqual(account.view()["balance"], 10)
def test_account_snapshot_restores_position_and_is_idempotent(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "account.json"
account = VirtualAccount(path, 10)
t = trader()
t.bind_account(account, "coin")
position = open_position(t)
balance = account.view()["balance"]
restarted = VirtualAccount(path, 999)
again = trader()
again.bind_account(restarted, "coin")
again.ledger.save()
self.assertEqual(again.position, position)
self.assertEqual(restarted.view()["balance"], balance)
self.assertEqual(restarted.view()["reserved"], 6)
def test_reset_never_erases_shared_position_or_creates_money(self):
with tempfile.TemporaryDirectory() as folder:
account = VirtualAccount(Path(folder) / "account.json", 10)
t = trader(leverage=2)
t.bind_account(account, "coin")
position = open_position(t)
t.settings.leverage = 20
t.ledger.save()
self.assertEqual(account.view()["reserved"], 6)
self.assertFalse(t.ledger.reset())
self.assertEqual(t.position, position)
t.close(101, 110, "manual", .1)
previous = account.view()["balance"]
self.assertTrue(t.ledger.reset())
self.assertEqual(account.view()["balance"], previous)
def test_migration_debits_only_fees_of_existing_positions(self):
with tempfile.TemporaryDirectory() as folder:
account = VirtualAccount(Path(folder) / "account.json", 10)
t = trader()
t.ledger.balance = 321 # historic results do not seed the new common account
position = open_position(t)
t.bind_account(account, "coin")
self.assertAlmostEqual(account.view()["balance"], 10 - position.fee_in)
self.assertEqual(account.view()["reserved"], 6)
if __name__ == "__main__":
unittest.main()
+29
View File
@@ -0,0 +1,29 @@
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import persistence
class AtomicSnapshotTests(unittest.TestCase):
def test_failed_replace_keeps_previous_snapshot_and_cleans_temporary_file(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'state.json'
persistence.atomic_write_json(path, {'position': 1})
with mock.patch.object(persistence.os, 'replace', side_effect=OSError('disk error')):
with self.assertRaises(OSError):
persistence.atomic_write_json(path, {'position': 2})
self.assertEqual(json.loads(path.read_text()), {'position': 1})
self.assertEqual(list(Path(directory).iterdir()), [path])
def test_invalid_numbers_do_not_destroy_existing_snapshot(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'state.json'
persistence.atomic_write_json(path, {'balance': 100})
with self.assertRaises(ValueError):
persistence.atomic_write_json(path, {'balance': float('nan')})
self.assertEqual(json.loads(path.read_text()), {'balance': 100})
+81
View File
@@ -0,0 +1,81 @@
import tempfile
import threading
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
import web_sim as ws
from pending_removals import PendingRemovals
CONN = {'lead_market': 'raydium', 'lead_ticker': '', 'lead_pool': 'POOL1',
'follow_exchange': 'binance', 'follow_ticker': 'XYZUSDT'}
class RemovalRecoveryTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.path = Path(self.tmp.name) / 'pending.json'
self.key = ws.coin_key(CONN)
def simulator(self, real_pending=True):
sim = ws.Simulator.__new__(ws.Simulator)
sim.lock = threading.Lock()
sim.removals = PendingRemovals(self.path)
engine = mock.Mock(conn=CONN, lock=threading.RLock())
engine.name = 'XYZ'
engine.paper.ledger.positions = []
engine.mirror.ready_to_remove.return_value = not real_pending
sim.engines = {self.key: engine}
return sim, engine
def test_failed_real_close_retains_connection_and_intent_after_restart(self):
sim, engine = self.simulator()
with mock.patch.object(ws.lw, 'remove_connection') as remove:
message = sim.remove(self.key)
self.assertIn('ожидает', message)
remove.assert_not_called()
engine.shutdown.assert_not_called()
engine.mirror.request_close.assert_called_once()
self.assertEqual(PendingRemovals(self.path).connections(), {self.key: CONN})
self.assertIn(self.key, sim.engines)
def test_only_confirmed_close_finishes_removal(self):
sim, engine = self.simulator()
sim.removals.schedule(self.key, CONN)
with mock.patch.object(ws.lw, 'remove_connection') as remove:
self.assertFalse(sim._finish_removal(self.key))
engine.mirror.ready_to_remove.return_value = True
self.assertTrue(sim._finish_removal(self.key))
remove.assert_called_once_with(CONN)
engine.shutdown.assert_called_once()
self.assertEqual(PendingRemovals(self.path).connections(), {})
self.assertNotIn(self.key, sim.engines)
def test_restart_recreates_pending_connection_even_after_connection_file_deletion(self):
sim, engine = self.simulator()
sim.removals.schedule(self.key, CONN)
sim.engines = {}
sim.common, sim.account, sim.start_feeds = {}, object(), False
with mock.patch.object(ws.lw, 'load_connections', return_value=[]), \
mock.patch.object(ws, 'Engine', return_value=engine):
sim.sync_connections()
self.assertIs(sim.engines[self.key], engine)
self.assertTrue(engine.removing)
engine.set_trading.assert_called_with(False)
engine.mirror.request_close.assert_called_once()
def test_disk_failure_before_intent_does_not_close_or_remove(self):
sim, engine = self.simulator()
with mock.patch('pending_removals.atomic_write_json', side_effect=OSError('full')), \
mock.patch.object(ws.lw, 'remove_connection') as remove:
message = sim.remove(self.key)
self.assertIn('не начато', message)
engine.close.assert_not_called()
remove.assert_not_called()
if __name__ == '__main__':
unittest.main()
+83
View File
@@ -0,0 +1,83 @@
"""Requests retain their original authority through the local proxy."""
import json
import sys
import unittest
import urllib.error
import urllib.request
from email.message import Message
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import request_security as security
import test_web_proxy as fixtures
import web_proxy
import web_sim
class AuthorityTests(unittest.TestCase):
def request(self, host='localhost:8765', origin=None, peer='127.0.0.1'):
headers = Message()
headers['Host'] = host
headers['X-Sim'] = '1'
if origin is not None:
headers['Origin'] = origin
return SimpleNamespace(headers=headers, client_address=(peer, 1000))
def test_only_local_authorities_and_same_origin_are_accepted(self):
for host, origin in [('localhost:8765', 'http://localhost:8765'),
('127.0.0.1:8765', None), ('[::1]:8765', 'http://[::1]:8765')]:
self.assertTrue(security.trusted_request(self.request(host, origin), command=True))
for host in ['attacker.example:8765', 'localhost.attacker.example', 'attacker@localhost:8765',
'localhost:bad', 'localhost:8765/path', 'localhost:8765#x', 'localhost:8765,evil']:
self.assertFalse(security.trusted_request(self.request(host)))
for origin in ['null', 'http://attacker.example', 'http://localhost:1234', 'http://evil@localhost:8765']:
self.assertFalse(security.trusted_request(self.request(origin=origin), command=True))
self.assertFalse(security.trusted_request(self.request(peer='192.168.1.1')))
def test_duplicate_host_and_missing_command_header_are_rejected(self):
req = self.request()
req.headers['Host'] = 'evil.example'
self.assertFalse(security.trusted_request(req))
req = self.request()
del req.headers['X-Sim']
self.assertFalse(security.trusted_request(req, command=True))
class ProxyIntegrationTests(unittest.TestCase):
def setUp(self):
self.sim = mock.patch.object(web_sim, 'SIM', SimpleNamespace(state=lambda: {'ok': True}), create=True)
self.sim.start()
self.addCleanup(self.sim.stop)
self.engine = fixtures.serve(web_sim.Handler)
self.backend = mock.patch.object(web_proxy, 'ENGINE', f'http://127.0.0.1:{self.engine.server_port}')
self.backend.start()
self.addCleanup(self.backend.stop)
self.proxy = fixtures.serve(web_proxy.Proxy)
for server in (self.engine, self.proxy):
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
def test_host_is_checked_at_both_boundaries(self):
for server in (self.proxy, self.engine):
for method in ('GET', 'POST'):
req = urllib.request.Request(f'http://127.0.0.1:{server.server_port}/api/state',
data=b'{}' if method == 'POST' else None, method=method,
headers={'Host': 'attacker.example', 'X-Sim': '1'})
with self.assertRaises(urllib.error.HTTPError) as error:
urllib.request.urlopen(req)
self.assertEqual(error.exception.code, 403)
def test_proxy_preserves_browser_origin_and_static_assets_are_allowlisted(self):
base = f'http://127.0.0.1:{self.proxy.server_port}'
req = urllib.request.Request(base + '/api/state', headers={'Origin': base})
with urllib.request.urlopen(req) as response:
self.assertEqual(json.load(response), {'ok': True})
for asset, kind in [('app.js', 'text/javascript'), ('app.css', 'text/css')]:
with urllib.request.urlopen(base + '/static/' + asset) as response:
self.assertIn(kind, response.headers['Content-Type'])
self.assertGreater(len(response.read()), 10)
with self.assertRaises(urllib.error.HTTPError) as error:
urllib.request.urlopen(base + '/static/../keystore.py')
self.assertEqual(error.exception.code, 404)
+173
View File
@@ -0,0 +1,173 @@
import json
import tempfile
import threading
import unittest
from pathlib import Path
from unittest import mock
from virtual_account import AccountError, VirtualAccount
class VirtualAccountTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / 'account.json'
self.account = VirtualAccount(self.path, 100)
def test_one_balance_fees_reservations_profit_and_deposits(self):
a = self.account
a.commit('coin:a', {'positions': [1]}, cash_total=-1, reserved=60, event='entry')
self.assertEqual(a.view()['free'], 39)
with self.assertRaises(AccountError):
a.commit('cross', {}, cash_total=-1, reserved=40)
a.mark('coin:a', -10)
self.assertEqual(a.view()['free'], 29)
with self.assertRaises(AccountError):
a.adjust(-30, 'withdraw-1')
a.adjust(25, 'deposit-1')
self.assertEqual(a.view()['realized'], -1)
a.commit('coin:a', {'positions': []}, cash_total=9, reserved=0, event='close')
self.assertEqual(a.view()['balance'], 134)
self.assertEqual(a.view()['free'], 134)
self.assertEqual(a.view()['realized'], 9)
def test_repeat_adjustment_is_idempotent_across_restart(self):
self.account.adjust(50, 'deposit-123')
again = VirtualAccount(self.path, 9999)
again.adjust(50, 'deposit-123')
self.assertEqual(again.view()['balance'], 150)
with self.assertRaises(AccountError):
again.adjust(60, 'deposit-123')
def test_owner_snapshot_and_cash_are_committed_together(self):
self.account.commit('a', {'position': 12}, cash_total=-2, reserved=50)
again = VirtualAccount(self.path)
self.assertEqual(again.restore('a'), {'position': 12})
again.commit('a', {'position': 12}, cash_total=-2, reserved=50)
self.assertEqual(again.view()['balance'], 98)
with mock.patch('virtual_account.atomic_write_json', side_effect=OSError('disk full')):
with self.assertRaises(AccountError):
again.commit('a', {'position': None}, cash_total=8, reserved=0)
self.assertEqual(again.restore('a'), {'position': 12})
self.assertEqual(again.view()['balance'], 98)
self.assertEqual(VirtualAccount(self.path).restore('a'), {'position': 12})
def test_concurrent_entries_cannot_spend_same_free_money(self):
barrier = threading.Barrier(2)
results = []
def enter(owner):
barrier.wait()
try:
self.account.commit(owner, {'open': True}, cash_total=-1, reserved=60)
results.append(True)
except AccountError:
results.append(False)
jobs = [threading.Thread(target=enter, args=(name,)) for name in ('a', 'b')]
for job in jobs:
job.start()
for job in jobs:
job.join()
self.assertEqual(sorted(results), [False, True])
self.assertEqual(self.account.view()['reserved'], 60)
def test_existing_exposure_imported_but_new_risk_blocked(self):
self.account.commit('old', {'open': True}, cash_total=0, reserved=150, allow_existing=True)
with self.assertRaises(AccountError):
self.account.commit('old', {}, cash_total=0, reserved=160, allow_existing=True)
self.account.commit('old', {'open': False}, cash_total=-120, reserved=0)
self.assertEqual(self.account.view()['balance'], -20)
self.assertEqual(self.account.view()['free'], 0)
def test_invalid_values_do_not_change_balance(self):
for value in (0, True, 'NaN', 'inf', '-inf', 'abc', None, -101):
with self.subTest(value=value), self.assertRaises(AccountError):
self.account.adjust(value, 'request-123')
self.assertEqual(self.account.view()['balance'], 100)
def test_corrupt_file_blocks_without_overwriting(self):
self.path.write_text('{broken', encoding='utf-8')
broken = VirtualAccount(self.path)
self.assertTrue(broken.view()['error'])
with self.assertRaises(AccountError):
broken.adjust(10, 'deposit-321')
self.assertEqual(self.path.read_text(), '{broken')
def test_stale_open_position_blocks_withdrawal_but_allows_close(self):
self.account.commit('a', {}, cash_total=-1, reserved=60)
again = VirtualAccount(self.path)
self.assertEqual(again.view()['stale'], ['a'])
with self.assertRaises(AccountError):
again.adjust(-1, 'withdraw-321')
again.commit('a', {}, cash_total=-3, reserved=0)
self.assertEqual(again.view()['free'], 97)
def test_second_instance_cannot_overwrite_prior_adjustment(self):
other = VirtualAccount(self.path)
self.account.adjust(50, 'first-123')
other.adjust(25, 'second-123')
self.assertEqual(VirtualAccount(self.path).view()['balance'], 175)
def test_external_owner_change_invalidates_old_valuation(self):
self.account.commit('x', {}, cash_total=0, reserved=20, unrealized=-10)
other = VirtualAccount(self.path)
other.commit('x', {'changed': True}, cash_total=0, reserved=20, unrealized=-60)
with self.assertRaises(AccountError):
self.account.adjust(-70, 'withdraw-xyz')
self.assertEqual(self.account.view()['equity'], 40)
def test_structurally_corrupt_account_reports_error(self):
original = json.loads(self.path.read_text())
for patch in ({'balance': '100'}, {'owners': {'broken': []}}, {'balance': True}):
self.path.write_text(json.dumps({**original, **patch}), encoding='utf-8')
account = VirtualAccount(self.path)
self.assertTrue(account.view()['error'])
def test_runtime_lock_prevents_two_engines_for_same_directory(self):
from runtime_lock import RuntimeLock
path = Path(self.temp.name) / 'engine.lock'
with RuntimeLock(path):
with self.assertRaises(RuntimeError):
with RuntimeLock(path):
self.fail('second engine acquired directory')
with RuntimeLock(path):
pass
def test_repeated_large_adjustment_cannot_write_unreadable_totals(self):
path = Path(self.temp.name) / 'large-account.json'
account = VirtualAccount(path, 0)
account.adjust(1e12, 'large-deposit-1')
before = path.read_bytes()
with self.assertRaises(AccountError):
account.adjust(1e12, 'large-deposit-2')
self.assertEqual(path.read_bytes(), before)
self.assertEqual(account.view()['balance'], 1e12)
self.assertEqual(account.view()['error'], '')
restarted = VirtualAccount(path)
self.assertEqual(restarted.view()['error'], '')
self.assertEqual(restarted.view()['balance'], 1e12)
self.assertNotIn('large-deposit-2', restarted.data['adjustments'])
def test_commit_and_net_deposits_are_validated_before_persistence(self):
path = Path(self.temp.name) / 'large-account.json'
account = VirtualAccount(path, 1e12)
before = path.read_bytes()
with self.assertRaises(AccountError):
account.commit('profit', {}, cash_total=1, reserved=0)
self.assertEqual(path.read_bytes(), before)
self.assertIsNone(account.restore('profit'))
account.commit('loss', {}, cash_total=-1000, reserved=0)
before = path.read_bytes()
with self.assertRaises(AccountError):
# Balance would stay below the cap, but cumulative net deposits would exceed it.
account.adjust(500, 'net-deposits-overflow')
self.assertEqual(path.read_bytes(), before)
restarted = VirtualAccount(path)
self.assertEqual(restarted.view()['error'], '')
self.assertEqual(restarted.view()['balance'], 1e12 - 1000)
self.assertEqual(restarted.view()['net_deposits'], 1e12)
if __name__ == '__main__':
unittest.main()
+445
View File
@@ -0,0 +1,445 @@
"""Shared-wallet integration through web engines and HTTP handlers, without threads or exchanges."""
import io
import json
import tempfile
import time
import unittest
from email.message import Message
from pathlib import Path
from unittest import mock
import cross
import scalp_hint as sh
import scalp_paper as sp
import virtual_account
import web_sim as ws
class NoRealMirror:
def __init__(self, *args, **kwargs):
self.trades = []
self.state = ""
self.position = None
self.storage_error = ""
self.events = []
def hook(self, event, pos):
self.events.append(event)
def gate(self):
return ""
def enabled(self):
return False
def request_close(self):
pass
def ready_to_remove(self):
return self.position is None
def reset_stats(self):
pass
def view(self):
return {"open": 0, "trades": 0, "net": 0.0, "wins": 0, "positions": [], "state": "",
"problem": "", "enabled": False, "trade_list": []}
def connection(symbol):
return {"lead_market": "spot", "lead_ticker": symbol + "-USDT", "lead_pool": "",
"follow_exchange": "bybit", "follow_ticker": symbol + "USDT"}
def book(mid=.08):
b = sh.OrderBook()
b.bids, b.asks = {round(mid - .00002, 5): 1000}, {round(mid + .00002, 5): 1000}
return b
class WebAccountTests(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.directory = Path(temporary.name)
self.account_path = self.directory / "account.json"
self.account = virtual_account.VirtualAccount(self.account_path, 10)
self.common = dict(ws.load_common(), mode="vector", stake=6, budget=300, leverage=1,
vector_window_seconds=2, vector_min_move_pct=.05, max_positions=5,
entry_gap_seconds=0, cooldown_ms=0, stop_loss_pct=.3,
min_confidence=0, auto_tp=False, one_per_tick=False, require_leader=False)
patches = [mock.patch.object(ws, "DATA_DIR", self.directory),
mock.patch.object(ws, "SETTINGS_FILE", self.directory / "settings.json"),
mock.patch.object(ws, "paper_account", return_value=self.account),
mock.patch.object(ws.real_mirror, "FuturesMirror", NoRealMirror),
mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {}}),
mock.patch.object(ws.real_mirror, "save_settings", side_effect=AssertionError("real settings touched")),
mock.patch.object(ws.live, "client", side_effect=AssertionError("real client requested")),
mock.patch.object(cross.arb, "_get", side_effect=AssertionError("network request"))]
for item in patches:
item.start()
self.addCleanup(item.stop)
def engine(self, symbol="AAA", common=None, account=True):
engine = ws.Engine(connection(symbol), common or self.common, self.account if account else None)
engine.tick, engine.book = .00001, book()
return engine
def warm(self, engine):
engine.set_trading(True)
for index in range(31):
stamp = 1000 + index / 10
engine.paper.on_leader(stamp, .08, .08)
engine.paper.on_book(stamp, engine.book, engine.tick)
def direct_open(self, engine):
return engine.paper.ledger.open(engine.paper.settings.follow_ticker, "LONG", .08002, 1003,
.055, .09, .07, .08)
def post(self, body, *, raw=False, path="/api/account/adjust", headers=None):
data = body if raw else json.dumps(body).encode()
handler = ws.Handler.__new__(ws.Handler)
handler.path = path
handler.client_address = ("127.0.0.1", 12345)
handler.rfile = io.BytesIO(data)
handler.headers = Message()
for name, value in {"Host": "127.0.0.1:8765", "Origin": "http://127.0.0.1:8765", "X-Sim": "1",
"Content-Length": str(len(data)), **(headers or {})}.items():
handler.headers[name] = value
responses = []
handler._json = lambda payload, status=200: responses.append((status, payload))
handler.do_POST()
self.assertEqual(len(responses), 1)
return responses[0]
def test_competing_coins_topup_and_close_through_engine(self):
first, second = self.engine("AAA"), self.engine("BBB")
self.warm(first)
self.warm(second)
first.paper.on_leader(1003.1, .08016, .08016)
self.assertEqual(len(first.paper.ledger.positions), 1)
second.paper.on_leader(1003.1, .08016, .08016)
self.assertEqual(second.paper.ledger.positions, [])
self.assertAlmostEqual(self.account.view()["reserved"], 6)
status, reply = self.post({"amount": 10, "request_id": "topup-for-second"})
self.assertEqual(status, 200)
self.assertTrue(reply["ok"])
second.paper.on_leader(1003.2, .08032, .08032)
self.assertEqual(len(second.paper.ledger.positions), 1)
self.assertAlmostEqual(self.account.view()["reserved"], 12)
self.assertIn("1", first.close(None))
self.assertIsNone(first.paper.position)
self.assertAlmostEqual(self.account.view()["reserved"], 6)
expected = 20 + first.paper.trades[0].net_usd - second.paper.position.fee_in
self.assertAlmostEqual(self.account.view()["balance"], expected)
def test_restart_restores_common_owner_and_policy_despite_common_mode_change(self):
settings = dict(self.common, mode="basis")
first = self.engine(common=settings)
first.paper.policy.b_mean, first.paper.policy.b_var, first.paper.policy.b_count = 1.25, .04, 100
first.paper.policy.last_entry = 900
pos = self.direct_open(first)
first.paper.ledger.save()
before = self.account.view()
self.account = virtual_account.VirtualAccount(self.account_path, 999)
again = self.engine(common=self.common)
self.assertEqual(again.paper.position, pos)
self.assertIsInstance(again.paper.policy, sp.BasisPolicy)
self.assertEqual(again.paper.policy.b_mean, 1.25)
self.assertEqual(again.paper.policy.last_entry, 900)
self.assertEqual(self.account.view()["balance"], before["balance"])
self.assertEqual(self.account.view()["reserved"], before["reserved"])
def test_first_legacy_migration_keeps_policy_state(self):
settings = dict(self.common, mode="basis")
old = self.engine(common=settings, account=False)
old.paper.policy.b_mean, old.paper.policy.b_var, old.paper.policy.b_count = 1.25, .04, 100
self.direct_open(old)
old.paper.ledger.save()
migrated = self.engine(common=settings)
self.assertEqual(migrated.paper.policy.b_mean, 1.25)
self.assertEqual(migrated.paper.policy.b_var, .04)
self.assertEqual(migrated.paper.policy.b_count, 100)
def test_restart_checkpoint_keeps_last_known_unrealized_without_refreshing_quote_age(self):
engine = self.engine()
self.direct_open(engine)
engine.paper.mark_account(book(.079))
engine.paper.ledger.save()
previous = self.account.view()["unrealized"]
self.assertLess(previous, 0)
self.account = virtual_account.VirtualAccount(self.account_path, 999)
again = self.engine()
again.set_trading(False) # a settings save is not a new market price
self.assertAlmostEqual(self.account.view()["unrealized"], previous)
self.assertIn("coin:" + again.key, self.account.view()["stale"])
def test_reset_refuses_open_exposure_and_preserves_wallet_after_close(self):
engine = self.engine()
self.direct_open(engine)
self.assertIn("закройте", engine.reset())
self.assertIsNotNone(engine.paper.position)
self.assertEqual(self.account.view()["reserved"], 6)
engine.close(None)
before = self.account.view()["balance"]
self.assertEqual(engine.reset(), "Статистика сброшена")
self.assertEqual(self.account.view()["balance"], before)
def test_failed_reset_retains_history_and_reports_error(self):
engine = self.engine()
self.direct_open(engine)
engine.close(None)
trades = list(engine.paper.trades)
with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")):
result = engine.reset()
self.assertIn("disk full", result)
self.assertEqual(engine.paper.trades, trades)
def test_failed_close_does_not_report_a_closed_position(self):
engine = self.engine()
self.direct_open(engine)
before = self.account.view()
with mock.patch.object(virtual_account, "atomic_write_json", side_effect=OSError("disk full")):
message = engine.close(None)
self.assertIsNotNone(engine.paper.position)
self.assertNotIn("закрыто позиций: 1", message)
self.assertIn("disk full", message)
self.assertEqual(self.account.view()["balance"], before["balance"])
self.assertEqual(self.account.view()["reserved"], before["reserved"])
def test_close_without_a_quote_preserves_position_and_common_reserve(self):
engine = self.engine()
position = self.direct_open(engine)
engine.book = sh.OrderBook()
engine.last_follower = 0
previous = self.account.view()
snapshot = self.account_path.read_bytes()
message = engine.close(None)
self.assertIn("Нет свежей цены", message)
self.assertEqual(engine.close_error, message)
self.assertEqual(engine.paper.ledger.positions, [position])
self.assertEqual(engine.paper.trades, [])
self.assertEqual(self.account.view()["reserved"], previous["reserved"])
self.assertEqual(self.account.view()["balance"], previous["balance"])
self.assertEqual(self.account_path.read_bytes(), snapshot)
def test_stale_close_is_rejected_then_fresh_quote_settles_once(self):
engine = self.engine()
position = self.direct_open(engine)
previous = self.account.view()["balance"]
now = time.time()
engine.last_follower = now - engine.paper.settings.max_data_age_ms / 1000 - 1
with mock.patch.object(ws.time, "time", return_value=now):
message = engine.close(position.uid)
self.assertIn("Нет свежей цены", message)
self.assertEqual(engine.paper.ledger.positions, [position])
self.assertEqual(self.account.view()["balance"], previous)
self.assertEqual(self.account.view()["reserved"], position.margin)
engine.book = book(.081)
engine.last_follower = now
self.assertEqual(engine.close(position.uid), "закрыто позиций: 1")
self.assertEqual(engine.close_error, "")
self.assertIsNone(engine.paper.position)
self.assertEqual(len(engine.paper.trades), 1)
self.assertAlmostEqual(engine.paper.trades[0].exit, .08098)
self.assertAlmostEqual(self.account.view()["balance"], 10 + engine.paper.trades[0].net_usd)
self.assertEqual(self.account.view()["reserved"], 0)
self.assertEqual(engine.close(position.uid), "закрыто позиций: 0")
self.assertEqual(len(engine.paper.trades), 1)
def test_corrupt_account_leaves_simulator_available_for_error_display(self):
self.account_path.write_text("{broken", encoding="utf-8")
broken = virtual_account.VirtualAccount(self.account_path)
with mock.patch.object(ws.lw, "load_connections", return_value=[connection("AAA")]):
simulator = ws.Simulator(account=broken, start=False)
self.assertTrue(simulator.state()["account"]["error"])
self.assertTrue(simulator.state()["coins"][0]["account_error"])
self.assertIsNone(self.direct_open(next(iter(simulator.engines.values()))))
self.assertEqual(self.account_path.read_text(), "{broken")
def test_cross_and_coin_share_the_same_reservation_limit(self):
engine = self.engine()
self.direct_open(engine)
engine.paper.mark_account(engine.book)
arbitrage = cross.CrossEngine(self.directory, start=False, account=self.account)
self.assertEqual(arbitrage.set_settings({"amount": 6, "running": True}), "")
link = cross.Link("XYZ", "Gate", "Binance", "XYZUSDT", "XYZUSDT", .999, 1, 1.02, 1.021,
1e5, 1e5, 1e7, 1e7, .0001, 8)
arbitrage.links[link.key] = link
row = {"link": link, "fits": True, "net": 1.0, "usual": .5}
self.assertFalse(arbitrage._entries(1000, [row]))
self.assertEqual(arbitrage.positions, [])
self.assertEqual(self.account.view()["reserved"], 6)
self.account.adjust(20, "cross-topup")
self.assertEqual(arbitrage.set_settings({"running": True}), "")
self.assertTrue(arbitrage._entries(1001, [row]))
self.assertGreater(self.account.view()["reserved"], 12)
def test_http_adjustment_is_idempotent_and_only_virtual(self):
body = {"amount": 3, "request_id": "same-request-123"}
self.assertTrue(self.post(body)[1]["ok"])
self.assertTrue(self.post(body)[1]["ok"])
self.assertEqual(self.account.view()["balance"], 13)
self.assertFalse(self.post({**body, "amount": 4})[1]["ok"])
self.assertEqual(self.account.view()["balance"], 13)
def test_http_invalid_adjustments_and_json_do_not_mutate_account(self):
for amount in (None, True, "NaN", "inf", -11, 0, "wrong"):
with self.subTest(amount=amount):
self.assertFalse(self.post({"amount": amount, "request_id": "invalid-value"})[1]["ok"])
for payload in (b"[]", b"null", b'{"amount":'):
self.assertEqual(self.post(payload, raw=True)[0], 400)
self.assertEqual(self.post({}, headers={"Content-Length": "65537"})[0], 413)
self.assertEqual(self.post({"amount": 2, "request_id": "request-x"}, headers={"X-Sim": "0"})[0], 403)
self.assertEqual(self.account.view()["balance"], 10)
self.assertEqual(self.account.view()["journal"], [])
def test_virtual_entry_and_topup_never_reach_real_mirror_hooks(self):
engine = self.engine()
self.assertEqual(engine.paper.ledger.hooks, [])
self.direct_open(engine)
self.post({"amount": 5, "request_id": "paper-only-deposit"})
engine.close(None)
self.assertEqual(engine.mirror.events, [])
def test_real_switch_is_refused_while_any_exposure_is_open(self):
engine = self.engine()
self.direct_open(engine)
self.assertIn("закройте", engine.switch_real(True))
self.assertFalse(engine.signal_mode)
self.assertIs(engine.paper.ledger.account, self.account)
engine.close(None)
engine.mirror.position = {"uid": 9}
self.assertIn("закройте", engine.switch_real(True))
self.assertFalse(engine.signal_mode)
def test_reset_cannot_close_private_real_signals_or_erase_pending_real_exposure(self):
engine = self.engine()
with mock.patch.object(ws.real_mirror, "save_settings", return_value=""):
self.assertEqual(engine.switch_real(True), "")
position = self.direct_open(engine)
self.assertEqual(engine.mirror.events, ["open"])
self.assertIn("закройте", engine.reset())
self.assertEqual(engine.paper.ledger.positions, [position])
self.assertEqual(engine.mirror.events, ["open"])
engine.close(None)
self.assertIsNone(engine.paper.position)
engine.mirror.position = {"uid": position.uid}
trades = list(engine.paper.trades)
self.assertIn("закройте", engine.reset())
self.assertEqual(engine.paper.trades, trades)
def test_real_signal_ledger_is_isolated_and_return_restores_paper_history(self):
engine = self.engine()
self.direct_open(engine)
engine.close(None)
paper_trade = engine.paper.trades[0]
balance = self.account.view()["balance"]
with mock.patch.object(ws.real_mirror, "save_settings", return_value="") as settings:
self.assertEqual(engine.switch_real(True), "")
self.assertTrue(engine.signal_mode)
self.assertIsNone(engine.paper.ledger.account)
self.assertEqual(engine.paper.trades, [])
self.direct_open(engine)
self.assertEqual(engine.mirror.events, ["open"])
self.assertEqual(self.account.view()["balance"], balance)
self.assertEqual(self.account.view()["reserved"], 0)
engine.close(None)
self.assertEqual(engine.mirror.events, ["open", "close"])
self.assertEqual(self.account.view()["balance"], balance)
self.assertEqual(engine.switch_real(False), "")
self.assertFalse(engine.signal_mode)
self.assertIs(engine.paper.ledger.account, self.account)
self.assertEqual(engine.paper.trades, [paper_trade])
self.assertEqual(engine.paper.ledger.hooks, [])
self.assertEqual(self.account.view()["balance"], balance)
self.assertEqual(settings.call_args_list,
[mock.call({"coin": engine.key, "enabled": True}),
mock.call({"coin": engine.key, "enabled": False})])
def test_new_real_signal_ledger_uses_configured_standalone_budget(self):
engine = self.engine(common=dict(self.common, budget=1000, stake=500))
with mock.patch.object(ws.real_mirror, "save_settings", return_value=""):
self.assertEqual(engine.switch_real(True), "")
self.assertEqual(engine.paper.ledger.balance, 1000)
self.assertEqual(engine.paper.ledger.available, float("inf"))
def test_real_signal_policy_ignores_virtual_balance_and_legacy_paper_budget(self):
engine = self.engine(common=dict(self.common, budget=300, stake=500))
with mock.patch.object(ws.real_mirror, "save_settings", return_value=""):
self.assertEqual(engine.switch_real(True), "")
# Empty the virtual wallet: private real-signal bookkeeping must remain independent.
self.assertTrue(self.post({"amount": -10, "request_id": "withdraw-paper-all"})[1]["ok"])
self.warm(engine)
engine.paper.on_leader(1003.1, .08016, .08016)
self.assertIsNotNone(engine.paper.position)
self.assertEqual(engine.mirror.events, ["open"])
self.assertEqual(self.account.view()["balance"], 0)
self.assertEqual(self.account.view()["reserved"], 0)
def test_startup_selects_private_signal_ledger_for_saved_real_mode(self):
key = ws.coin_key(connection("AAA"))
with mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {key: {"on": True}}}):
engine = self.engine()
self.assertTrue(engine.signal_mode)
self.assertIsNone(engine.paper.ledger.account)
self.assertIsNone(self.account.restore("coin:" + key))
self.assertEqual(engine.paper.ledger.state_path.name, "signal_" + key + ".json")
def test_private_signal_restart_restores_open_position_without_reemitting_entry(self):
key = ws.coin_key(connection("AAA"))
settings = dict(self.common, mode="basis")
with mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {key: {"on": True}}}):
first = self.engine(common=settings)
first.paper.policy.b_mean, first.paper.policy.b_var = 1.25, .04
pos = self.direct_open(first)
first.paper.ledger.save()
again = self.engine(common=settings)
self.assertEqual(again.paper.position, pos)
self.assertIsNone(again.paper.ledger.account)
self.assertTrue(again.paper.ledger.signal_only)
self.assertEqual(again.paper.policy.b_mean, 1.25)
self.assertEqual(again.paper.policy.b_var, .04)
self.assertEqual(again.mirror.events, [])
self.assertEqual(self.account.view()["balance"], 10)
self.assertEqual(self.account.view()["reserved"], 0)
def test_private_signal_restart_keeps_open_basis_policy_until_settings_change_after_close(self):
key = ws.coin_key(connection("AAA"))
with mock.patch.object(ws.real_mirror, "load_settings", return_value={"coins": {key: {"on": True}}}):
first = self.engine(common=dict(self.common, mode="basis"))
first.paper.policy.b_mean, first.paper.policy.b_var = 1.25, .04
position = self.direct_open(first)
first.paper.ledger.save()
again = self.engine(common=dict(self.common, mode="vector"))
self.assertEqual(again.paper.position, position)
self.assertEqual(again.paper.settings.mode, "basis")
self.assertIsInstance(again.paper.policy, sp.BasisPolicy)
self.assertEqual(again.paper.policy.b_mean, 1.25)
self.assertEqual(again.paper.policy.b_var, .04)
self.assertEqual(again.mirror.events, [])
self.assertEqual(again.close(None), "закрыто позиций: 1")
again.apply({"mode": "vector"})
self.assertEqual(again.paper.settings.mode, "vector")
self.assertIsInstance(again.paper.policy, sp.VectorPolicy)
self.assertEqual(self.account.view()["balance"], 10)
self.assertEqual(self.account.view()["reserved"], 0)
def test_paper_reset_does_not_clear_real_mirror_statistics(self):
engine = self.engine()
with mock.patch.object(engine.mirror, "reset_stats") as reset_real:
self.assertEqual(engine.reset(), "Статистика сброшена")
reset_real.assert_not_called()
def test_failed_real_mode_setting_keeps_active_paper_ledger(self):
engine = self.engine()
original = engine.paper
with mock.patch.object(ws.real_mirror, "save_settings", return_value="settings write failed"):
self.assertEqual(engine.switch_real(True), "settings write failed")
self.assertIs(engine.paper, original)
self.assertFalse(engine.signal_mode)
self.assertEqual(self.account.view()["balance"], 10)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -53,7 +53,7 @@ class ProxyTests(unittest.TestCase):
got = json.loads(urllib.request.urlopen(base + "/api/state?x=1").read())
self.assertEqual(got, {"method": "GET", "path": "/api/state?x=1"})
req = urllib.request.Request(base + "/api/coin/A/start", data=json.dumps({"a": 1}).encode(),
method="POST", headers={"Content-Type": "application/json"})
method="POST", headers={"Content-Type": "application/json", "X-Sim": "1"})
got = json.loads(urllib.request.urlopen(req).read())
self.assertEqual(got["body"], {"a": 1})
finally:
+7
View File
@@ -37,6 +37,9 @@ class _NoReal:
def reset_stats(self):
pass
def ready_to_remove(self):
return True
def view(self):
return {"open": 0, "trades": 0, "net": 0.0, "wins": 0, "positions": [], "state": "", "problem": "",
"enabled": False, "trade_list": []}
@@ -124,6 +127,9 @@ class WebSimTests(unittest.TestCase):
e.paper.last_close = 0.0 # close() stamps the wall clock; this test runs on its own clock
e.paper.on_leader(t + 0.05, 0.08016, 0.08016)
self.assertEqual((len(e.paper.trades), len(e.paper.ledger.positions)), (1, 1))
self.assertIn("закройте", e.reset())
self.assertEqual((len(e.paper.trades), len(e.paper.ledger.positions)), (1, 1))
e.close(None)
e.reset()
self.assertEqual((e.paper.trades, e.paper.ledger.positions), ([], []))
self.assertEqual(e.paper.ledger.balance, 1000.0)
@@ -167,6 +173,7 @@ class WebSimTests(unittest.TestCase):
def test_trading_pairs_are_listed_first(self):
sim = ws.Simulator.__new__(ws.Simulator)
sim.lock = threading.Lock()
sim.common = ws.load_common()
a = ws.Engine(dict(CONN, follow_ticker="AAA_USDT"), sim.common)
z = ws.Engine(dict(CONN, follow_ticker="ZZZ_USDT"), sim.common)
+320
View File
@@ -0,0 +1,320 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
function page() {
// Load actual application functions; omit DOM bootstrap and periodic polling only.
let source = fs.readFileSync(path.join(__dirname, '../web/app.js'), 'utf8');
source = source.replace(/^\(function (calcInit|restoreArbSettings)\(\) \{[\s\S]*?^\}\)\(\);/gm, '');
source = source.slice(0, source.indexOf('\n(async () => {'));
const elements = new Map();
const intervals = [];
const context = vm.createContext({
console, Intl, localStorage: {getItem: () => null, setItem() {}},
AbortController, setTimeout, clearTimeout, setInterval(fn, ms) { intervals.push({fn, ms}); },
document: {getElementById(id) {
if (!elements.has(id)) elements.set(id, {textContent: '', innerHTML: '', value: '', dataset: {}, style: {}, disabled: false, classList: {toggle() {}}, addEventListener() {}, getAttribute() { return ''; }});
return elements.get(id);
}, querySelectorAll: () => [], querySelector: () => null},
window: {addEventListener() {}}, confirm: () => true,
});
vm.runInContext(source, context);
vm.runInContext(`
var originalApi = api, pending = [], commands = [], rendered = [];
api = (url, body) => body === undefined
? new Promise(resolve => pending.push({url, resolve}))
: (commands.push(url), Promise.resolve({ok: true, message: 'ok'}));
renderBasis = () => rendered.push({venue: bxVenue, source: bx.source});
bxBuild = () => { bxBuilt = true; };
renderTiles = () => {};
tab = 'basis'; bxVenue = 'cross';
`, context);
return {context, elements, intervals, run: code => vm.runInContext(code, context)};
}
const tick = () => new Promise(resolve => setImmediate(resolve));
test('late simulation response cannot populate real mode or send a real close', async () => {
const {context: c, run} = page();
const old = run('loadBasis()');
run("bxSelect('cross_real')");
await run("basisClose(1, 'cross')");
assert.equal(c.commands.length, 0);
c.pending[1].resolve({source: 'real', settings: {}, positions: [{uid: 1}]});
await tick();
c.pending[0].resolve({source: 'paper', settings: {}, positions: [{uid: 1}]});
await old;
assert.equal(run('bx.source'), 'real');
await run("basisClose(1, 'cross')");
assert.equal(c.commands.length, 0);
await run("basisClose(1, 'cross_real')");
assert.equal(c.commands[0], '/api/basis/cross_real/close/1');
});
test('responses from an earlier visit to the same venue are discarded', async () => {
const {context: c, run} = page();
const old = run('loadBasis()');
run("bxSelect('cross_real'); bxSelect('cross')");
c.pending[2].resolve({source: 'current', settings: {}});
await tick();
c.pending[0].resolve({source: 'old', settings: {}});
await old;
assert.equal(run('bx.source'), 'current');
});
test('older poll cannot overwrite a newer completed poll', async () => {
const {context: c, run} = page();
const old = run('loadBasis()'), fresh = run('loadBasis()');
c.pending[1].resolve({source: 'fresh', settings: {}});
await fresh;
c.pending[0].resolve({source: 'old', settings: {}});
await old;
assert.equal(run('bx.source'), 'fresh');
});
test('coin switch rejects stale details and stale row actions', async () => {
const {context: c, run} = page();
run("tab = 'sim'; selected = 'A'; detail = {key: 'A'}");
const old = run('loadDetail()');
run("selectCoin('B')");
await run("closePos(1, 'A'); trade('start')");
assert.equal(c.commands.length, 0);
c.pending[0].resolve({key: 'A'});
await old;
assert.equal(run('detail'), null);
run("detail = {key: 'B'}");
await run("closePos(1, 'A')");
assert.equal(c.commands.length, 0);
await run("closePos(1, 'B')");
assert.equal(c.commands[0], '/api/coin/B/close/1');
});
test('a failed first state request still schedules retries and can recover', async () => {
const {run, intervals} = page();
run(`
var attempts = 0, recovered = false;
loadState = async () => { if (++attempts === 1) throw new Error('offline'); recovered = true; };
loadDetail = loadBasis = loadReal = loadAccount = async () => {};
refreshCenter = showTab = () => {};
startApplication();
`);
await tick();
assert.equal(intervals.length, 7);
assert.equal(run('attempts'), 1);
await intervals.find(t => t.ms === 2000).fn();
assert.equal(run('recovered'), true);
});
test('late scanner refresh never replaces a selected coin', async () => {
const {run, context: c} = page();
run(`
tab = 'sim'; selected = 'BTC'; var skeletons = 0;
scannerSkeleton = () => skeletons++;
document.getElementById = () => null;
`);
await run('loadScanner()');
assert.equal(run('skeletons'), 0);
assert.equal(c.pending.length, 0);
});
test('late scanner response from an earlier visit is discarded', async () => {
const {run, context: c, elements} = page();
run("tab = 'sim'; selected = SCANNER;");
const old = run('loadScanner()');
run('detailEpoch += 2'); // Leaving and returning is a new visit, even to the same scanner.
c.pending[0].resolve({running: false, auto_add: false, cycles: 1, log: [], coins: []});
await old;
assert.equal(elements.has('scState'), false);
});
test('HTTP errors surface their message, with no automatic POST retry', async () => {
const {run, context: c, elements} = page();
c.fetch = async () => ({ok: false, status: 503, json: async () => ({error: 'maintenance'})});
run("api = originalApi; readHealth.set('/api/state', {time: Date.now(), error: ''});");
await assert.rejects(run("api('/api/settings', {})"), /maintenance/);
assert.match(elements.get('commandNotice').textContent, /не подтверждён/);
let calls = 0;
c.fetch = async () => { calls++; throw new Error('connection lost'); };
await assert.rejects(run("api('/api/settings', {})"), /connection lost/);
assert.equal(calls, 1);
assert.equal(run('pendingCommands.size'), 0);
});
test('stale controls block commands until a fresh read succeeds', async () => {
const {run, context: c} = page();
const control = {dataset: {command: 'state'}, disabled: false};
c.document.querySelectorAll = selector => selector === '[data-command]' ? [control] : [];
let calls = 0;
c.fetch = async () => { calls++; return {ok: true, status: 200, json: async () => ({ok: true})}; };
run("api = originalApi; tab = 'sim'; selected = null; readHealth.set('/api/state', {time: Date.now() - 11000, error: ''}); refreshConnection();");
assert.equal(control.disabled, true);
await assert.rejects(run("api('/api/settings', {})"), /не отправлена/);
assert.equal(calls, 0);
await run("api('/api/state')");
assert.equal(control.disabled, false);
await run("api('/api/settings', {})");
assert.equal(calls, 2);
});
test('concurrent polling for the same endpoint makes one GET', async () => {
const {run, context: c} = page();
let calls = 0, resolve;
c.fetch = () => { calls++; return new Promise(done => { resolve = done; }); };
run('api = originalApi');
const first = run("api('/api/state')"), second = run("api('/api/state')");
assert.equal(calls, 1);
resolve({ok: true, status: 200, json: async () => ({coins: []})});
await Promise.all([first, second]);
assert.equal(run('pendingReads.size'), 0);
});
test('slow poll tasks do not accumulate duplicate render work', async () => {
const {run} = page();
run('var pollCalls = 0, finishPoll; var slowTask = () => { pollCalls++; return new Promise(resolve => finishPoll = resolve); };');
const first = run('poll(slowTask)'), second = run('poll(slowTask)');
assert.equal(run('pollCalls'), 1);
run('finishPoll()');
await Promise.all([first, second]);
assert.equal(run('pendingPolls.size'), 0);
});
test('context invalidation starts a fresh GET and ignores old connection failures', async () => {
const {run, context: c} = page();
const fetches = [];
c.fetch = () => new Promise((resolve, reject) => fetches.push({resolve, reject}));
run('api = originalApi');
const old = run("api('/api/basis?ex=cross')");
const oldRejected = assert.rejects(old, /old request failed/);
run("invalidateRead('/api/basis?ex=cross')");
const fresh = run("api('/api/basis?ex=cross')");
assert.equal(fetches.length, 2);
fetches[1].resolve({ok: true, status: 200, json: async () => ({settings: {}})});
await fresh;
fetches[0].reject(new Error('old request failed'));
await oldRejected;
assert.equal(run("freshRead('/api/basis?ex=cross')"), true);
});
test('reset refusal is visible instead of silently discarded', async () => {
const {run, elements} = page();
run(`
bx = {settings: {}}; bxDataVenue = 'cross';
api = async () => ({ok: false, error: 'Сначала закройте открытые позиции'});
loadBasis = async () => {};
`);
await run('basisReset()');
assert.match(elements.get('bxMsg').textContent, /закройте открытые позиции/);
});
test('account snapshot ordering prevents an older poll from undoing a deposit', () => {
const {run, elements} = page();
run(`
renderAccount({version: 2, updated_at: 20, balance: 400, equity: 400, reserved: 0, free: 400, journal: []});
renderAccount({version: 1, updated_at: 21, balance: 300, journal: []});
renderAccount({version: 2, updated_at: 19, balance: 350, journal: []});
`);
assert.equal(elements.get('account-balance').textContent, '400.00 $');
});
test('uncertain account adjustment reuses its identifier on explicit retry', async () => {
const {run, elements} = page();
run(`
var adjustments = [];
readHealth.set('/api/account', {time: Date.now(), error: ''});
loadAccount = async () => {};
api = async (url, body) => {
adjustments.push({...body});
if (adjustments.length === 1) throw new Error('response lost');
return {ok: true, account: {version: 2, balance: 325, equity: 325, reserved: 0, free: 325, journal: []}};
};
`);
elements.set('accountDelta', {value: '25,00'});
await run('adjustAccount(1)');
assert.match(elements.get('accountMsg').textContent, /Ответ не получен/);
await run('adjustAccount(1)');
assert.equal(run('adjustments.length'), 2);
assert.equal(run('adjustments[0].amount'), '25');
assert.equal(run('adjustments[0].request_id === adjustments[1].request_id'), true);
assert.equal(elements.get('account-balance').textContent, '325.00 $');
});
test('account does not send invalid amounts or stale withdrawals', async () => {
const {run, context: c, elements} = page();
run("readHealth.set('/api/account', {time: Date.now(), error: ''});");
elements.set('accountDelta', {value: '-10'});
await run('adjustAccount(-1)');
assert.equal(c.commands.length, 0);
elements.get('accountDelta').value = '10';
run("accountData = {stale: ['coin:BTC']}");
await run('adjustAccount(-1)');
assert.equal(c.commands.length, 0);
assert.match(elements.get('accountMsg').textContent, /устарела/);
});
test('account controls send signed withdrawals and hide in real arbitrage', async () => {
const {run, elements} = page();
run(`
var savedAdjustment;
accountData = {stale: [], error: ''};
readHealth.set('/api/account', {time: Date.now(), error: ''});
loadAccount = async () => {};
api = async (url, body) => { savedAdjustment = body; return {ok: true}; };
`);
elements.set('accountDelta', {value: '15.50'});
await run('adjustAccount(-1)');
assert.equal(run('savedAdjustment.amount'), '-15.5');
run("tab = 'basis'; bxVenue = 'cross_real'; updateAccountVisibility();");
assert.equal(elements.get('paperAccount').hidden, true);
run("bxVenue = 'cross'; updateAccountVisibility();");
assert.equal(elements.get('paperAccount').hidden, false);
});
test('account journal preserves the server newest-first order and stale owner semantics', () => {
const {run, elements} = page();
run(`renderAccount({balance: 300, equity: 300, reserved: 0, free: 300, stale: [], error: '', journal: [
{time: 200, amount: 10, balance: 300, reason: 'Newest'},
{time: 100, amount: -10, balance: 290, reason: 'Older'}
]});`);
const html = elements.get('accountJournal').innerHTML;
assert.ok(html.indexOf('Newest') < html.indexOf('Older'));
assert.equal(run('accountIsStale(accountData)'), false);
assert.equal(run("accountIsStale({stale: ['coin:BTC']})"), true);
});
test('saving main arbitrage settings preserves separately unsaved fee edits', async () => {
const {run, context: c} = page();
const main = {dataset: {bx: 'amount'}, type: 'text', value: '25'};
const fee = {dataset: {cxfee: 'Bybit|spot', dirty: '1'}, type: 'text', value: '0.123'};
c.document.querySelectorAll = selector => selector === '#bxSettings input' ? [main]
: selector.includes('#cxBal input[data-cxfee]') ? [main, fee] : [];
run("bx = {settings: {}}; bxDataVenue = 'cross'; bxBuilt = true; bxDirty = true; loadBasis = async () => {};");
await run('basisSave()');
assert.equal(run("basisDrafts.get('cross')['fee:Bybit|spot']"), '0.123');
assert.equal(run("'bx:amount' in basisDrafts.get('cross')"), false);
});
test('scanner rejects invalid cycle inputs before sending any command', async () => {
const {run, elements, context: c} = page();
elements.set('scMin', {value: '15'}); elements.set('scCoins', {value: '14'});
await run("scanner('start')");
assert.equal(c.commands.length, 0);
assert.match(elements.get('scMsg').textContent, /от 1 до 13/);
});
test('help covers every declared setting, all modes and account controls', () => {
const {run, context: c} = page();
vm.runInContext(fs.readFileSync(path.join(__dirname, '../web/help-data.js'), 'utf8'), c);
vm.runInContext(fs.readFileSync(path.join(__dirname, '../web/help.js'), 'utf8'), c);
const missing = run(`[
...[...MAIN_FIELDS, ...MORE_FIELDS].filter(([k]) => !HELP_SETTINGS.sim[k]).map(([k]) => 'sim.' + k),
...[...CX_FIELDS, ...CX_CHECKS].filter(([k]) => !HELP_SETTINGS.cross[k]).map(([k]) => 'cross.' + k),
...[...BX_FIELDS, ...BX_CHECKS].filter(([k]) => !HELP_SETTINGS.basis[k]).map(([k]) => 'basis.' + k),
...['lead', 'vector', 'basis'].filter(k => !HELP_MODES[k]),
...[...CALC_IDS, 'scMin', 'scCoins', 'scAuto', 'simRealTpsl', 'simRealTransfer', 'simRealSl', 'simRealPing', 'accountDelta'].filter(k => !HELP_EXTRA.some(row => row[1] === k))
]`);
assert.equal(missing.length, 0, `Missing help: ${missing.join(', ')}`);
assert.equal(run("MAIN_FIELDS.concat(MORE_FIELDS).some(([k]) => k === 'budget')"), false);
assert.ok(run("filterHelp(helpEntries(), 'свободно').some(e => e.key === 'free')"));
assert.ok(run("filterHelp(helpEntries(), 'stop_loss_pct').length") > 0);
});
+136
View File
@@ -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
+245
View File
@@ -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()
+179
View File
@@ -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; } }
+1499
View File
File diff suppressed because it is too large. Load diff
+148
View File
@@ -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", "Ключ и секрет для выбранной биржи. «Сохранить» записывает их локально в защищённое хранилище; секрет не возвращается в браузер. «Проверить (баланс)» проверяет доступ чтением баланса, «Удалить» удаляет сохранённые ключи. Нужны права торговли; разрешение вывода средств для программы не требуется."],
["Реальная торговля", "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 минут меняют только окно графика. Время на странице — московское (МСК)."]
];
+78
View File
@@ -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 <dialog> 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();
});
}
+332 -3
View File
@@ -11,27 +11,351 @@ 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"""<!doctype html><html lang="ru"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
<title>Вход · Crypto Scam</title><style>
body{{margin:0;background:#10141d;color:#e8eef9;font:16px system-ui;display:grid;place-items:center;min-height:100vh}}
main{{width:min(420px,calc(100% - 36px));background:#1a202c;border:1px solid #303a4a;border-radius:14px;padding:26px;box-sizing:border-box}}
h1{{font-size:22px;margin:0 0 6px}}p{{color:#9aa9bf;font-size:14px}}label{{display:block;margin:16px 0 6px;color:#b9c7db}}
input{{box-sizing:border-box;width:100%;padding:11px;border-radius:7px;border:1px solid #39475a;background:#10141d;color:white;font-size:16px}}
button{{margin-top:20px;width:100%;padding:11px;border:0;border-radius:7px;background:#3b82f6;color:white;font-size:16px;cursor:pointer}}
.error{{color:#ff8b8b;min-height:20px}}.switch{{background:none;color:#80aaff;cursor:pointer;border:0}}
</style><main><h1>Crypto Scam</h1><p id="modeText">Войдите в свой аккаунт</p><div class="error">{safe}</div>
<form method="post" action="/auth/login" id="authForm"><label>Логин</label><input name="username" required minlength="3" maxlength="32" autocomplete="username">
<label>Пароль</label><input name="password" type="password" required minlength="12" maxlength="256" autocomplete="current-password">
<button id="submit">Войти</button></form><button class="switch" type="button" onclick="toggleMode()" id="switch">Создать аккаунт</button>
<script>let reg=false;function toggleMode(){{reg=!reg;document.getElementById('authForm').action=reg?'/auth/register':'/auth/login';
document.getElementById('submit').textContent=reg?'Зарегистрироваться':'Войти';document.getElementById('switch').textContent=reg?'Уже есть аккаунт? Войти':'Создать аккаунт';
document.getElementById('modeText').textContent=reg?'Создайте отдельный аккаунт с собственными сделками и API-ключами':'Войдите в свой аккаунт';
document.querySelector('[autocomplete="current-password"]').autocomplete=reg?'new-password':'current-password';}}</script></main></html>"""
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
def _forward(self, method: str) -> None:
if not self.client_address[0].startswith("127.") and self.client_address[0] != "::1":
if not trusted_request(self, command=method == "POST"):
self.send_error(403, "only from this computer")
return
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else None
headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_HEADERS}
# Preserve the validated authority so the engine can compare the browser Origin.
headers["Host"] = self.headers["Host"]
req = urllib.request.Request(ENGINE + self.path, data=body, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
@@ -57,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)
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__":
+39 -1326
View File
File diff suppressed because it is too large. Load diff
+299 -55
View File
@@ -4,15 +4,17 @@
* Common trade settings at the top apply to every coin (web_sim_data/settings.json).
* Each coin (a connection from lead_connections.json: leader = KuCoin futures/spot or a Solana DEX pool, follower =
Bybit/Binance/MEXC futures) has its own feeds, its own paper account and journal (web_sim_data/<coin>.json/.csv)
Bybit/Binance/MEXC futures) has its own feeds and journal (web_sim_data/<coin>.json/.csv)
and its own Start/Stop. Stop only forbids new entries: prices, the comparison and the forecast learning go on.
* Paper coins and paper arbitrage share one durable virtual account. Real signal ledgers are separate;
explicitly enabled real trading submits orders through the configured exchange clients.
* Coins added later to lead_connections.json (e.g. by meme_matcher/autoscan.py) appear within 30 s.
Nothing is ever sent to an exchange.
"""
from __future__ import annotations
import json
import os
import queue
import re
import statistics
@@ -24,6 +26,11 @@ from dataclasses import fields
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from request_security import trusted_request
from persistence import atomic_write_json
from pending_removals import PendingRemovals
from virtual_account import VirtualAccount, AccountError
from runtime_lock import RuntimeLock
import keystore
import lead_window as lw
import live
@@ -108,9 +115,15 @@ 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 = {
"/static/app.js": (ROOT / "web" / "app.js", "text/javascript"),
"/static/app.css": (ROOT / "web" / "app.css", "text/css"),
"/static/help.js": (ROOT / "web" / "help.js", "text/javascript"),
"/static/help-data.js": (ROOT / "web" / "help-data.js", "text/javascript"),
}
PORT = 8765
CONNECTION_FIELDS = set(lw.CONNECTION_KEYS)
COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings)
@@ -120,10 +133,20 @@ COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings)
"vector_min_move_pct", "auto_tp", "auto_tp_share_pct", "auto_tp_learn",
"auto_tp_horizon_seconds", "one_per_tick", "cut_loss", "cut_loss_ticks",
"max_data_age_ms", "require_leader", "leader_min_edge", "auto_stop_pct",
"basis_window_seconds",
"basis_window_seconds", "simulation_entry_delay_ms", "simulation_exit_delay_ms",
"basis_entry_z", "basis_exit_z", "basis_min_gap_pct"}]
SERIES_STEP = 0.5 # chart sampling, s
SERIES_KEEP = 1200 # 10 minutes
ACCOUNT: VirtualAccount | None = None
ACCOUNT_LOCK = threading.Lock()
def paper_account() -> VirtualAccount:
global ACCOUNT
with ACCOUNT_LOCK:
if ACCOUNT is None:
ACCOUNT = VirtualAccount(DATA_DIR / "virtual_account.json", load_common().get("budget", 300.0))
return ACCOUNT
def coin_key(conn: dict) -> str:
@@ -147,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
@@ -185,6 +207,15 @@ def load_common() -> dict:
def check_common(values: dict) -> tuple[dict, str]:
"""Cast and validate settings coming from the page."""
import math
for name in ('simulation_entry_delay_ms', 'simulation_exit_delay_ms'):
if name in values:
try:
value = float(str(values[name]).replace(',', '.'))
if not math.isfinite(value) or not 0 <= value <= 60000:
raise ValueError()
except (ValueError, TypeError):
return {}, 'Задержка должна быть от 0 до 60000 мс'
out = {}
defaults = sp.PaperSettings()
for k in COMMON_FIELDS:
@@ -216,16 +247,21 @@ def check_common(values: dict) -> tuple[dict, str]:
class Engine:
"""One coin: leader + follower feeds, a paper trader and a price history for the chart."""
def __init__(self, conn: dict, common: dict) -> None:
def __init__(self, conn: dict, common: dict, account: VirtualAccount | None = None) -> None:
self.conn = dict(conn)
self.key = coin_key(conn)
self.symbol = coin_symbol(conn)
self.name = lw.connection_name(conn)
self.common = dict(common)
self.account = account
self.signal_mode = bool(account is not None and
real_mirror.load_settings().get("coins", {}).get(self.key, {}).get("on"))
DATA_DIR.mkdir(exist_ok=True)
settings = sp.PaperSettings(mode=common.get("mode", "lead"), enabled=False)
state_file = DATA_DIR / f"{self.key}.json"
state_file = DATA_DIR / f"{'signal_' if self.signal_mode else ''}{self.key}.json"
new_account = not state_file.exists()
self.paper = sp.PaperTrader(settings, sh.HintSettings(), state_file, DATA_DIR / f"{self.key}.csv")
self.paper = sp.PaperTrader(settings, sh.HintSettings(), state_file,
DATA_DIR / f"{'signal_' if self.signal_mode else ''}{self.key}.csv")
enabled = self.paper.settings.enabled # the coin's own Start/Stop survives restarts
self.apply(common, initial=True)
self.paper.settings.enabled = enabled
@@ -234,11 +270,21 @@ class Engine:
for k in CONNECTION_FIELDS:
setattr(self.paper.settings, k, conn[k])
self.paper.policy = self.paper._make_policy()
self.paper._restore_policy()
if account is not None and not self.signal_mode:
try:
self.paper.bind_account(account, "coin:" + self.key)
except (OSError, ValueError, TypeError, KeyError) as exc:
# Keep the diagnostics page available; never silently fall back to
# an independent account when the shared recovery source is broken.
led = self.paper.ledger
led.account, led.account_owner = account, "coin:" + self.key
led.storage_error = led._recovery_error = f"Счёт не восстановлен: {exc}"
self.paper.settings.enabled = False
# real trading: the same orders on the coin's futures exchange while the tab's real mode is on
ps = self.paper.settings
self.mirror = real_mirror.FuturesMirror(self.key, self.symbol, ps.follow_exchange, ps.follow_ticker)
self.paper.ledger.hooks.append(self.mirror.hook)
self.paper.gate = self.mirror.gate # one real trade at a time, confirmed closed
self._connect_trader()
self.mirror.on_failed_open = lambda uid: self.close(uid, "реальный ордер не прошёл")
self.mirror.ping = lambda ex=ps.follow_exchange: ping_for(ex) # no entry while the ping is above the limit
self.lock = threading.RLock()
@@ -254,21 +300,75 @@ class Engine:
self.lead_status = "подключаюсь…"
self.follow_status = "подключаюсь…"
self.message = ""
self.close_error = ""
self.removing = False
self.auto_stop = "" # why the pair was stopped automatically (cleared by Start)
self.checked_at = None # time of the last leader measurement looked at
self.feeds: list = []
self.stopped = threading.Event()
self.thread = threading.Thread(target=self._pump, daemon=True)
def _connect_trader(self) -> None:
# Pure paper operations never call the real mirror, even if a virtual
# deposit makes a previously unaffordable paper entry possible.
real_signals = self.signal_mode or self.account is None
self.paper.ledger.signal_only = self.signal_mode
self.paper.ledger.hooks = [self.mirror.hook] if real_signals else []
self.paper.gate = self.mirror.gate if real_signals else None
if not real_signals and getattr(self, 'execution_live', False):
import paper_execution
paper_execution.install(self)
def switch_real(self, enabled: bool) -> str:
"""Switch only while flat, using independent real-signal and paper ledgers."""
with self.lock:
if self.removing:
return "Подключение ожидает удаления"
if self.paper.ledger.positions or not self.mirror.ready_to_remove():
return "Перед сменой режима закройте бумажные и реальные позиции этой монеты"
if self.signal_mode == enabled:
return real_mirror.save_settings({"coin": self.key, "enabled": enabled})
prefix = "signal_" if enabled else ""
settings = sp.PaperSettings(mode=self.common.get("mode", "lead"), enabled=False)
trader = sp.PaperTrader(settings, sh.HintSettings(), DATA_DIR / f"{prefix}{self.key}.json",
DATA_DIR / f"{prefix}{self.key}.csv")
new_ledger = not (DATA_DIR / f"{prefix}{self.key}.json").exists()
try:
if not enabled and self.account is not None:
trader.bind_account(self.account, "coin:" + self.key)
if trader.ledger.positions:
return "В выбранном режиме сохранены открытые позиции; сначала завершите их сопровождение"
if trader.ledger.storage_error:
return trader.ledger.storage_error
for key, value in self.common.items():
setattr(trader.settings, key, value)
if enabled and new_ledger:
trader.ledger.balance = trader.settings.budget
for key in CONNECTION_FIELDS:
setattr(trader.settings, key, self.conn[key])
trader.policy = trader._make_policy()
trader._restore_policy()
trader.settings.enabled = self.paper.settings.enabled
if not trader.ledger.save():
return trader.ledger.storage_error
problem = real_mirror.save_settings({"coin": self.key, "enabled": enabled})
if problem:
return problem
except (OSError, ValueError, TypeError, KeyError) as exc:
return f"Режим не переключён: {exc}"
self.paper, self.signal_mode = trader, enabled
self._connect_trader()
self.message = "Реальная торговля" if enabled else "Симуляция: общий виртуальный счёт"
return ""
# --- lifecycle ---------------------------------------------------------------------------
def start(self) -> None:
self.execution_live = True
self._connect_trader()
ps = self.paper.settings
if ps.follow_exchange == "mexc":
self.tick, size = sh.mexc_contract(ps.follow_ticker)
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)
@@ -289,10 +389,16 @@ class Engine:
self.paper.ledger.save()
def apply(self, common: dict, initial: bool = False) -> None:
self.common.update(common)
ps = self.paper.settings
lock = self.lock if not initial else threading.RLock()
with lock:
mode = common.get("mode", ps.mode)
if initial and self.paper.ledger.positions:
# A recovered position keeps the policy that opened it. In
# particular, private real-signal ledgers have no shared-wallet
# restore step that could undo an initial global-mode override.
mode = ps.mode
for k, v in common.items():
if k != "mode":
setattr(ps, k, v)
@@ -304,6 +410,9 @@ class Engine:
def set_trading(self, on: bool) -> None:
with self.lock:
if on and self.removing:
self.message = "Подключение ожидает закрытия позиций и удаления"
return
self.paper.settings.enabled = on
self.paper.ledger.save()
if on:
@@ -312,12 +421,17 @@ class Engine:
"Стоп: новые сделки не открываются; открытые закроются по тейку, стопу или времени")
def reset(self) -> str:
"""Clear this coin's statistics: open positions dropped, journal emptied, balance back to the budget.
Start/Stop, prices, the leader check and the forecast learning are kept."""
"""Clear statistics only while both the paper/signal ledger and the real mirror are flat."""
with self.lock:
if self.paper.ledger.positions or not self.mirror.ready_to_remove():
self.message = "Сначала закройте бумажные и реальные позиции этой монеты"
return self.message
enabled = self.paper.settings.enabled
self.paper.ledger.reset() # positions, trades, CSV; balance = budget
self.mirror.reset_stats() # real figures start again from now too
if self.paper.ledger.reset() is False:
self.message = self.paper.ledger.storage_error
return self.message
if self.signal_mode or self.account is None:
self.mirror.reset_stats()
self.paper.settings.enabled = enabled
self.paper.ledger.save()
self.paper.message = ""
@@ -327,14 +441,26 @@ class Engine:
def close(self, uid: int | None, reason: str = "вручную") -> str:
"""Close one position (uid) or all of them at the follower's current best price."""
with self.lock:
self.close_error = ""
best_bid, best_ask = self.book.best()
closed = 0
for pos in list(self.paper.ledger.positions):
if uid is not None and pos.uid != uid:
continue
price = (best_bid if pos.side == "LONG" else best_ask) or pos.entry
price = best_bid if pos.side == "LONG" else best_ask
if not price or (self.last_follower and time.time() - self.last_follower >
self.paper.settings.max_data_age_ms / 1000):
self.close_error = "Нет свежей цены для закрытия; позиция и резерв сохранены"
self.message = self.close_error
return self.close_error
self.paper.close(price, time.time(), reason, self.paper.policy.taker, pos=pos)
if pos not in self.paper.ledger.positions:
closed += 1
if self.paper.ledger.storage_error:
self.close_error = self.paper.ledger.storage_error
return f"Закрыто позиций: {closed}; ошибка: {self.paper.ledger.storage_error}"
if not closed and getattr(self.paper, '_execution_installed', False) and self.paper.ledger.positions:
return 'Запрос закрытия поставлен в очередь с заданной задержкой'
return f"закрыто позиций: {closed}"
def _auto_stop(self, now: float) -> None:
@@ -413,13 +539,14 @@ class Engine:
return {
"key": self.key, "symbol": self.symbol, "name": self.name,
"leader": pol.L, "follower": pol.F, "follow_ticker": self.conn["follow_ticker"],
"running": self.paper.settings.enabled,
"running": self.paper.settings.enabled, "removing": self.removing,
"price": (bid + ask) / 2 if bid and ask else None,
"lead_price": sum(self.leader) / 2 if self.leader else None,
"signal": getattr(pol, "signal", 0.0), "confidence": getattr(pol, "conf", 0.0),
"open": len(led.positions), "trades": len(trades), "wins": wins,
"net": sum(t.net_usd for t in trades), "fees": sum(t.fee_usd for t in trades),
"unrealized": self.paper.unrealized(self.book), "balance": led.balance,
"account_error": getattr(led, "storage_error", ""),
"leadership": getattr(pol, "leadership", {}), "leader_block": pol.leader_block()
if hasattr(pol, "leader_block") else "", "min_edge": self.paper.settings.leader_min_edge,
"now": now, "auto_stop": self.auto_stop,
@@ -464,62 +591,120 @@ class Engine:
class Simulator:
def __init__(self) -> None:
def __init__(self, account: VirtualAccount | None = None, start: bool = True) -> None:
self.common = load_common()
self.account = account if account is not None else paper_account()
self.engines: dict[str, Engine] = {}
self.lock = threading.Lock()
self.removals = PendingRemovals(DATA_DIR / "pending_removals.json")
self.error = self.removals.error
self.start_feeds = start
self.sync_connections()
if start:
threading.Thread(target=self._watch, daemon=True).start()
def sync_connections(self) -> None:
"""Start an engine for every connection in the list (new ones appear; removal is only via remove())."""
for conn in lw.load_connections():
key = coin_key(conn)
pending = self.removals.connections()
connections = {coin_key(c): c for c in lw.load_connections()}
connections.update(pending) # survives a crash between connection deletion and final acknowledgement
for key, conn in connections.items():
with self.lock:
if key in self.engines:
continue
engine = Engine(conn, self.common)
engine = Engine(conn, self.common, self.account)
engine.removing = key in pending
if engine.removing:
engine.set_trading(False)
self.engines[key] = engine
if self.start_feeds:
engine.start()
if engine.removing:
engine.close(None)
engine.mirror.request_close()
def remove(self, key: str) -> str:
"""Delete a pair: close its open positions, stop all its data feeds and forget the connection."""
"""Keep the connection recoverable until both paper and real exposure is closed."""
with self.lock:
engine = self.engines.get(key)
if engine is None:
return "нет такой монеты"
lw.remove_connection(engine.conn)
del self.engines[key]
try:
self.removals.schedule(key, engine.conn)
except (OSError, ValueError) as exc:
return f"Удаление не начато: {exc}"
with engine.lock:
engine.paper.settings.enabled = False
engine.removing = True
engine.set_trading(False)
closed = len(engine.paper.ledger.positions)
engine.close(None) # open positions at the current price
engine.shutdown() # feeds (exchange + DEX/KuCoin) and the pump thread stop
engine.mirror.request_close()
if self._finish_removal(key):
return f"{engine.name} удалена, сбор данных остановлен" + (f", закрыто позиций: {closed}" if closed else "")
engine.message = "Удаление ожидает подтверждённого закрытия всех позиций; подключение сохранено"
return engine.message
def _finish_removal(self, key: str) -> bool:
with self.lock:
engine = self.engines.get(key)
if engine is None:
return False
with engine.lock:
if engine.paper.ledger.positions or not engine.mirror.ready_to_remove():
return False
try:
lw.remove_connection(engine.conn)
self.removals.complete(key)
except (OSError, ValueError) as exc:
engine.message = f"Не удалось завершить удаление: {exc}"
return False
del self.engines[key]
engine.shutdown()
return True
def _watch(self) -> None:
next_sync = 0.0
while True:
time.sleep(30)
time.sleep(1)
try:
if time.time() >= next_sync:
self.sync_connections()
except Exception:
pass
next_sync = time.time() + 30
for key in self.removals.connections():
with self.lock:
engine = self.engines.get(key)
if engine is not None and engine.paper.ledger.positions:
engine.close(None)
self._finish_removal(key)
except Exception as exc:
self.error = f"Обновление подключений: {exc}"
def save_common(self, values: dict) -> str:
if "budget" in values and getattr(self, "account", None) is not None:
return "Изменяйте баланс через «Виртуальный счёт»: Пополнить / Списать"
clean, problem = check_common(values)
if problem:
return problem
self.common.update(clean)
DATA_DIR.mkdir(exist_ok=True)
SETTINGS_FILE.write_text(json.dumps(self.common, ensure_ascii=False, indent=2), encoding="utf-8")
for engine in list(self.engines.values()):
updated = {**self.common, **clean}
try:
atomic_write_json(SETTINGS_FILE, updated)
except (OSError, ValueError) as exc:
return f"Настройки не сохранены: {exc}"
self.common = updated
with self.lock:
engines = list(self.engines.values())
for engine in engines:
engine.apply(clean)
return ""
def state(self) -> dict:
with self.lock:
engines = list(self.engines.values())
return {"settings": self.common, "modes": lw.MODES,
"account": self.account.view() if getattr(self, "account", None) else None,
"error": getattr(self, "error", ""),
# pairs enabled for trades first, then by name
"coins": sorted((e.summary() for e in self.engines.values()),
"coins": sorted((e.summary() for e in engines),
key=lambda c: (not c["running"], c["symbol"], c["name"]))}
@@ -548,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"}
@@ -615,7 +800,7 @@ def basis_engine(venue: str):
with BASIS_LOCK:
if "cross" not in BASIS:
import cross
BASIS["cross"] = cross.CrossEngine()
BASIS["cross"] = cross.CrossEngine(account=paper_account())
BASIS["cross"].balances = BALANCES # the accounts of every exchange with keys (read every 10 s)
if venue == "cross_real" and "cross_real" not in BASIS:
import cross
@@ -640,11 +825,22 @@ class Handler(BaseHTTPRequestHandler):
self._send(code, json.dumps(data, ensure_ascii=False).encode("utf-8"))
def do_GET(self) -> None:
if not trusted_request(self):
self._json({"error": "недоверенный адрес страницы"}, 403)
return
path, _, query = self.path.partition("?")
if path in ("/", "/index.html"):
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)
@@ -660,7 +856,10 @@ class Handler(BaseHTTPRequestHandler):
if engine is None:
self._json({"error": "эта биржа пока не подключена"}, 404)
else:
self._json(engine.view())
payload = engine.view()
if not getattr(engine, "is_real", False):
payload["paper_account"] = paper_account().view()
self._json(payload)
elif path == "/api/scanner":
try:
self._json(scanner_view(lw.load_connections()))
@@ -683,17 +882,42 @@ class Handler(BaseHTTPRequestHandler):
if not local_request(self):
self._json({"error": "команды принимаются только со страницы симулятора на этом компьютере"}, 403)
return
length = int(self.headers.get("Content-Length") or 0)
try:
length = int(self.headers.get("Content-Length") or 0)
if not 0 <= length <= 65536:
self._json({"ok": False, "error": "Слишком большой запрос"}, 413)
return
body = json.loads(self.rfile.read(length) or b"{}")
except ValueError:
body = {}
if not isinstance(body, dict):
raise ValueError("ожидается объект JSON")
except (ValueError, UnicodeError):
self._json({"ok": False, "error": "Некорректный JSON запроса"}, 400)
return
parts = self.path.strip("/").split("/")
try:
self._command(parts, body)
except AccountError as exc:
self._json({"ok": False, "error": str(exc), "account": paper_account().view()})
except (ValueError, TypeError, KeyError) as exc:
self._json({"ok": False, "error": f"Некорректная команда: {exc}"}, 400)
except OSError as exc:
self._json({"ok": False, "error": f"Операция не сохранена: {exc}"}, 500)
def _command(self, parts: list[str], body: dict) -> None:
if parts == ["api", "account", "adjust"]:
account = paper_account().adjust(body.get("amount"), body.get("request_id"))
self._json({"ok": True, "account": account})
return
if parts == ["api", "settings"]:
problem = SIM.save_common(body)
self._json({"ok": not problem, "error": problem})
return
if parts[:3] == ["api", "real", "simulator"]:
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
@@ -732,7 +956,9 @@ class Handler(BaseHTTPRequestHandler):
uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None
self._json({"ok": True, "message": engine.close(uid)})
elif parts[3] == "reset":
self._json({"ok": True, "message": engine.reset()})
message = engine.reset()
self._json({"ok": message.lower() == "статистика сброшена", "message": message,
"error": "" if message.lower() == "статистика сброшена" else message})
elif parts[3] == "adopt":
try:
price = float(body["price"]) if body.get("price") not in (None, "") else None
@@ -781,17 +1007,22 @@ class Handler(BaseHTTPRequestHandler):
action = parts[3]
if action == "start":
engine.set_trading(True)
self._json({"ok": True})
self._json({"ok": not engine.removing,
"error": engine.message if engine.removing else ""})
elif action == "stop":
engine.set_trading(False)
self._json({"ok": True})
elif action == "reset":
self._json({"ok": True, "message": engine.reset()})
message = engine.reset()
self._json({"ok": message.lower() == "статистика сброшена", "message": message,
"error": "" if message.lower() == "статистика сброшена" else message})
elif action == "remove":
self._json({"ok": True, "message": SIM.remove(parts[2])})
elif action == "close":
uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None
self._json({"ok": True, "message": engine.close(uid)})
message = engine.close(uid)
error = engine.close_error or engine.paper.ledger.storage_error
self._json({"ok": not bool(error), "message": message, "error": error})
else:
self._json({"error": "unknown action"}, 404)
return
@@ -804,21 +1035,30 @@ LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"}
def local_request(handler) -> bool:
"""A command from this simulator's own page: the Host is the local address (no DNS rebinding) and the request
carries the X-Sim header — another web site open in the browser cannot add it without a CORS preflight, which
this server never allows, so it cannot press buttons here (real trading, keys)."""
host = (handler.headers.get("Host") or "").rsplit(":", 1)[0].lower()
return host in LOCAL_HOSTS and handler.headers.get("X-Sim") == "1"
return trusted_request(handler, command=True)
def main() -> None:
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, 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.
server = ThreadingHTTPServer((host, port), Handler)
real_mirror.load_recent()
import minorder
minorder.AUTOLOAD = True # the exchanges' smallest orders (spot and perp), loaded and renewed hourly
@@ -832,15 +1072,19 @@ def main() -> None:
# «Арбитраж»: the simulation and the real engine run from the start (open real positions are watched at once)
basis_engine("cross")
basis_engine("cross_real")
server = ThreadingHTTPServer((host, port), Handler)
# 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()
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more