diff --git a/README.md b/README.md index 6b4660f..42d6e28 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,96 @@ -# Bybit Realtime Simulator +# Crypto Scam / Realtime Paper Simulator -Standalone real-time simulator and optional Bybit USDT-perpetual trading bot. +Программа для исследования криптовалютных стратегий на публичных рыночных данных. В проекте есть веб-интерфейс, бумажная торговля, исторический прогон, поиск арбитражных возможностей и отдельный экспериментальный режим реальной торговли через API бирж. -## Run on Windows +> Важно: это исследовательский симулятор, а не рекомендация по торговле. Бумажные результаты не гарантируют прибыль в реальном рынке. + +## Что умеет проект + +- **Симулятор опережения**: сравнивает цену ведущего источника с ценой фьючерса и моделирует входы/выходы. +- **Автоподбор мем-монет**: сканирует поддерживаемые DEX-пулы и добавляет подходящие пары в веб-интерфейс. +- **Арбитраж**: сравнивает bid/ask, комиссии, funding, оборот и доступную ликвидность на Bybit, Binance, MEXC, HTX и Gate, не отправляя ордера в режиме просмотра. +- **Исторический прогон и backtest**: использует кэш свечей, считает PnL, комиссии, funding, просадку, ликвидации и открытые позиции. +- **Стратегии**: классическая LONG-стратегия с усреднением, пробой максимума с ATR, шорт затухающего пампа, basis-trading и экспериментальные режимы по стакану/потоку. +- **Реальная торговля**: доступна только после явного подключения API-ключей и запуска соответствующего режима. + +## Требования + +- Windows 10/11. +- Python 3.10–3.13. Если Python не найден, установщик пытается поставить Python 3.12 через `winget`. +- Интернет. Для доступа к отдельным биржам может потребоваться VPN. +- Свободный порт `127.0.0.1:8765` для веб-страницы и `127.0.0.1:8766` для внутреннего движка. + +## Установка и первый запуск + +Рекомендуемый вариант — двойной щелчок по `ЗАПУСТИТЬ_СЕРВЕР.bat`. + +Скрипт автоматически находит Python или предлагает установить Python 3.12, создаёт локальное окружение `.venv`, устанавливает зависимости из `requirements.txt` (`websocket-client`, `numpy`), запускает веб-сервер в фоне и открывает `http://127.0.0.1:8765`. Библиотеки ставятся только в `.venv`, системный Python не изменяется. + +### Установка вручную через 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:\arb\RealtimePaperSimulator -py -3 -m pip install -r requirements.txt -py -3 main.py +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 ``` -The default mode is **Симуляция**. It reads public Bybit linear-contract trades and does not need API credentials. The home screen contains the currency tiles, trading-mode selector and Bybit connection controls. Add currencies as square tiles and turn on **В торгах** for each symbol; all enabled symbols are subscribed together and trade in parallel. Click a tile to open that currency's chart, market characteristics and its own strategy settings. Stake, leverage, entry trigger, averaging step and limit, TP and stop are saved per symbol. The virtual balance, margin usage, fees and closed-trade history are shared across symbols. The strategy opens a virtual LONG when the current price rises through that currency's configured percentage from the previous closed candle. Each configured decline from the latest fill adds the same margin stake, up to that currency's add limit and while shared free balance allows. Set the maximum count or drop step to `0` to disable averaging. Each position closes at TP or stop-loss measured from its weighted average entry. TP is raised as needed to cover the account's round-trip taker fee estimate. +В отдельном окне запустите прокси: -In simulation and real trading, the **Автоподбор** threshold controls automatic currency rotation. Every ten minutes the app ranks USDT perpetual contracts by 24-hour turnover, checks the top 100, and enables pairs whose 24-hour price change is strictly greater than the configured percentage (20% by default). A pair that falls below the threshold stops receiving new entries; if it has a position, the app keeps managing it and disables the pair after that position closes. Newly qualifying pairs are added automatically and use their saved per-currency strategy, or the default strategy for a currency without saved settings. In real mode, added pairs are prepared through the connected Bybit API and then receive their own worker. This uses 24-hour turnover as the liquidity ranking and Bybit's `price24hPcnt` as the growth test. Public ticker loading tries both official global REST hosts (`api.bybit.com` and `api.bytick.com`); failures appear beside the threshold instead of being hidden. +```powershell +.venv\Scripts\python.exe web_proxy.py +``` -Simulation has its own main-window controls for the starting deposit and maximum number of simultaneously open positions (1–100, default 5). The limit gates new entries while existing positions remain managed; lowering it does not forcibly close trades. Apply a changed deposit while simulation is stopped and all simulation positions are closed. The new deposit adjusts the account balance by the same amount, preserving the accumulated simulation P&L. +После этого откройте `http://127.0.0.1:8765`. -To replay the enabled symbols, select **Исторический прогон**, choose the number of days (1–365), a dedicated starting deposit in USDT, the minimum 24-hour growth percentage, and the capital-stop threshold (1–100%, default 10%) in the historical settings row, then click **Запустить прогон**. The historical deposit is independent of the paper/live account balance, and each currency's stake percentage is calculated from this historical deposit. These values are saved in `settings.json`. Downloaded candles are saved in `historical_candles.sqlite3` next to the app; later runs reuse covered ranges and request only missing/new candles. The app fetches closed one-minute public candles from Bybit in bounded pages, including an extra day for the rolling-growth filter, and shows the current page/retry in the status bar. Transient page timeouts and Bybit errors `10006`/`10016` are retried up to five times. New entries pause when the 24-hour price change falls below the configured threshold and resume only after it exceeds that threshold by 1 percentage point. If the filter pauses while a position is open, no further averaging is added; the position remains managed by its configured TP and stop. The backtest stops at the configured capital floor using cash plus open-position unrealized P&L after estimated closing fees; still-open positions are shown at their mark price when the floor is reached. The result window shows closed and still-open positions and saves CSV and JSON reports under `historical_reports`. Candle data contains OHLC only, so the test estimates the intraminute price path; it does not include funding, slippage, or order-book execution. Historical mode does not read API credentials or submit orders. +## Запуск и остановка -Each currency detail window has **Сделать дефолтными и применить ко всем** next to its individual strategy apply button. It copies the displayed stake, adds, leverage, entry, TP and stop values to every configured currency and saves them; when live trading is running, each symbol's worker receives the updated settings. +| Файл | Назначение | +|---|---| +| `ЗАПУСТИТЬ_СЕРВЕР.bat` | Запуск в фоне без окон; если сервер уже работает, просто открывает страницу | +| `ОСТАНОВИТЬ_СЕРВЕР.bat` | Полная остановка страницы, движка и цикла автоперезапуска | +| `УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat` | Установка и запуск с видимым окном движка для диагностики | +| `run_web_sim.bat` | Запуск веб-симулятора в обычном режиме | +| `run.bat` | Запуск основного Tk-интерфейса | +| `run_hint.bat` | Запуск интерфейса leader/follower | -The default strategy for new currencies is stake 5% of deposit, 2 averaging entries, leverage 1, entry growth 0.2%, averaging step 1.5%, stop disabled, and TP 10%. **Сделать дефолтными и применить ко всем** updates the shared template and all existing currencies; an individual apply keeps a per-currency override. Older saved templates are upgraded once while preserving those individual overrides. +Если движок аварийно завершится, фоновый запуск пытается поднять его снова. При остановке скрипт также временно отключает задачу Планировщика Windows `RealtimePaperSimulator watchdog`, если она существует. -### Historical selection like live mode +## Веб-интерфейс -Enable **Отбор валют как в реальном режиме** in the historical row to remove the look-ahead bias of testing only today's gainers. The app downloads hourly candles with turnover for every USDT perpetual (including delisted contracts that Bybit still serves), and after each closed hour ranks pairs by trailing 24-hour turnover. Among the top 100, pairs whose 24-hour change is above the **Автоподбор** threshold may open entries during the next hour; outside the selection a pair only manages its open position and averaging is paused — the same rule as a pair waiting for retirement in simulation and live trading. The first run downloads a lot of data (hourly data for several hundred contracts plus minute data for every pair that ever qualified); later runs reuse the cache. +Основной запуск: `py -3 web_sim.py` или `py -3 web_sim.py --backend`. Откройте `http://127.0.0.1:8765`. -Both historical modes apply the shared **Макс. одновременных позиций** limit, model gaps at the candle open (stop/TP/averaging execute at the open price) and liquidation for leverage above 1 (loss of the position margin, maintenance margin 0.5%). The report shows maximum drawdown, minimum equity, stops, liquidations, losing open positions and the longest holding time. A high share of winning trades without a stop-loss is not evidence of low risk: check open positions and drawdown. +В веб-интерфейсе доступны карточки монет, отдельные бумажные счета и журналы сделок, общие настройки, графики изменения цен, запуск/остановка торговли по каждой паре и панель автоматического сканера `meme_matcher/autoscan.py`. -## Strategy modes +Данные веб-симулятора сохраняются в `web_sim_data/`: `settings.json` — общие настройки, `.json` — состояние бумажного счёта, `.csv` — журнал сделок, `backend.log` — журнал движка. -The **Режим стратегии** row selects the strategy used by simulation and the historical run; **Настройки режима…** opens a window whose fields switch with the selected mode, and each mode keeps its own saved values (`strategy_mode` and `strategy_mode_settings` in `settings.json`). Real trading accepts only the classic mode. The mode can be changed only while trading and backtests are stopped; open positions keep being managed by the mode that opened them. +## Основные режимы -- **Классика** — the original per-currency strategy described above. In the mode window its fields are the shared template, applied to all currencies. -- **A: пробой N-часового максимума (ATR)** — LONG when a closed signal candle (5/15/30/60 min) closes above the high of the previous N hours with turnover at least K× the average. Optional filters: BTCUSDT closed hour above its EMA and funding not above a threshold. Stop = entry − ATR × multiplier, no averaging. -- **B: шорт затухающего пампа** — SHORT when 24h growth and funding are above their thresholds, the recent high is already behind, the close is a set percentage below it and below the turnover-weighted average price (VWAP). Stop above the high + ATR buffer; the signal is skipped when the stop is farther than the allowed percentage. +### Классическая стратегия -Modes A and B share the exit engine in `strategy.py`: partial take-profit at R (R = distance to the initial stop), stop to breakeven after it, ATR trailing stop, optional final target at R and a maximum holding time. A signal is evaluated when its candle closes (the simulation polls Bybit klines for every enabled pair) and stays valid until the next candle closes; the entry fills on the next trade (simulation) or the next minute open (backtest). Mode parameters are shared by all currencies; the stake is a percentage of the simulation or historical deposit. The simulation does not apply funding to open positions. +Открывает виртуальный LONG при росте цены выше заданного порога от предыдущей свечи. При снижении от последнего входа может добавлять позиции до лимита усреднений. Выход выполняется по take-profit или stop-loss от взвешенной средней цены. Ставка, плечо, вход, шаг усреднения, TP и SL настраиваются отдельно для валюты. -## Funding in the backtest +### Исторический прогон -With **Учитывать funding** (historical row, on by default) the run downloads Bybit's settled funding history for every tested pair (cached in `historical_candles.sqlite3`, table `funding`). At each settlement minute an open position pays or receives `qty × minute open × rate`: LONG pays a positive rate, SHORT receives it. Funding is part of each trade's Net, appears in its own report column, and the summary shows the total and the number of settlements. Pairs without funding history are listed in the report and tested without funding. +В интерфейсе выберите `Исторический прогон`, задайте период, депозит, фильтр роста и порог остановки по капиталу, затем нажмите `Запустить прогон`. Свечи сохраняются в `historical_candles.sqlite3`, отчёты — в `historical_reports/`. Данные OHLC не содержат внутриминутный порядок сделок, поэтому путь цены внутри свечи моделируется приближённо. -## Leader exchange: KuCoin → paper trades on Bybit +Опция `Отбор валют как в реальном режиме` уменьшает look-ahead bias: пары отбираются по доступной на тот момент 24-часовой динамике и обороту, а не по сегодняшним результатам. -`py -3 scalp_hint.py` now opens only this mode (`lead_window.py`); the previous window with every strategy below -is still available as `py -3 scalp_hint.py --legacy` (the strategy code is kept, only hidden). +### Арбитраж -Both feeds are read directly: KuCoin futures public WebSocket (`tickerV2`, best bid/ask; default contract -`MARSCOINUSDTM`) and Bybit public WebSocket (`orderbook.50` + trades; default `MARSCOINUSDT`). When KuCoin's mid -price has moved by at least «Отставание Bybit для входа» (default 0.05%) over «Окно сравнения» (500 ms) and Bybit's -mid has moved that much less in the same direction, a virtual **market** order (taker fee) is opened on Bybit in -KuCoin's direction. Bybit moving first is never traded. Exits: take-profit (limit, maker fee, filled when Bybit -trades through it), stop-loss (market on Bybit's best price), «Макс. удержание, с» (market). Also: budget, stake, -leverage, pause after a trade; no entry when either feed is older than 2 s. The account and journal are separate -(`lead_paper_state.json`, `lead_paper_trades.csv`); the first start copies budget, stake and leverage from the old -window. The stream (Bybit book/trades + KuCoin quotes as `L` rows) is recorded to `scalp_recordings\`, and -`scalp_paper.replay` replays it. +Модуль `arb.py` показывает потенциальные расхождения между биржами с учётом входных/выходных комиссий, funding, объёма и ликвидности. По умолчанию он только анализирует рынок: ничего не покупает и не продаёт. -Measured on 2026-10-16 (10 min, local receive time, 100 ms grid): KuCoin and Bybit move together (return -correlation 0.18 at lag 0, 0.10 with Bybit 0.2 s ahead; ≈ 0 with KuCoin ahead). After a KuCoin move of ≥ 2–4 ticks -Bybit follows by only ~0.002–0.003% over the next 1–5 s, far below the ~0.1% round-trip fees; KuCoin's spread is -~16 ticks vs Bybit's ~5. A replay of that recording loses with every tried threshold (0.03–0.12%) and TP/SL. +### Leader/follower и DEX -**Mode «Вектор KuCoin»** (same window, mode selector): the direction of KuCoin's mid over the last -«Вектор KuCoin за, с» (default 5 s); once it moved at least «Мин. движение KuCoin» (default 0.1%), a virtual market -order is opened on Bybit the same way (rising → LONG, falling → SHORT), regardless of whether Bybit has moved too, -with the same take-profit (e.g. +0.2%), stop-loss and holding time. Note the break-even: +0.2% target minus ~0.075% -fees (taker in, maker out) against −0.3% stop plus ~0.11% fees needs about 77% winners. On ~20 min of recorded -KuCoin+Bybit MARSCOIN data every tried variant (window 5/10/30 s, move 0.05–0.2%, SL 0.2–0.3%, hold 60–300 s) lost; -the best had 40–57% winners. +`scalp_hint.py` запускает режим ведущего рынка. Источниками могут быть KuCoin, Raydium и другие поддерживаемые потоки, а исполнение моделируется на фьючерсном рынке. `scalp_paper.py` умеет записывать поток и повторно проигрывать записи для сравнения параметров. -«Ведущая: KuCoin фьючерсы / KuCoin спот» (`lead_market`): the leader can also be a KuCoin spot pair (public spot -WebSocket `/market/ticker`); the ticker is converted automatically (MARSCOINUSDTM ↔ MARSCOIN-USDT). Measured on -2026-10-16 (10 min, MARSCOIN spot vs Bybit perpetual): the spot follows Bybit rather than leads it (after a Bybit move -the spot catches up +0.04–0.055% within 5 s in 81–91% of cases); after a spot move Bybit adds only ~+0.024% in 5 s, -below fees. KuCoin's MARSCOIN spot step is 0.0001 (~0.13% of the price, ten times Bybit's). +### Режимы стакана -**Raydium (DEX) as the leader, Binance futures for the paper trades.** «Ведущая: Raydium пул (Solana)» + the pool -address (e.g. from Meme Matcher; Raydium AMM v4 or CPMM — CLMM pools are not supported): the pool's two token vaults -are watched over the public Solana RPC WebSocket (`accountSubscribe`, `processed` commitment), and on every swap the -price = quote vault / token vault (in USD through Binance's live SOLUSDT price when the pool is quoted in SOL; a price -is taken only when both vaults come from the same slot, and SOL moves alone never produce a leader update). This is -real time (well under a second), unlike GeckoTerminal's 1–2 minute delay. «Ставки на: Binance фьючерс» reads Binance -USDⓈ-M `bookTicker` (`fstream…/public/stream`) as a one-level book and `aggTrade` (`…/market/stream`) as trades; the -paper fees stay Bybit's (0.055% taker / 0.02% maker; Binance's are 0.05% / 0.02%). +`scalp_paper.py` и `algo_hunter.py` содержат экспериментальные модели по стакану, imbalance, микроцене и повторяющимся заявкам. Они предназначены для dry-run и анализа: видимый агрегированный стакан не позволяет надёжно доказать наличие конкретного маркет-мейкера или реальную очередь исполнения. +<<<<<<< HEAD **Web interface** (`py -3 web_sim.py` or `run_web_sim.bat` → [local page](http://127.0.0.1:8765), opens in the browser): every coin has its own feeds, trade history and Start/Stop. A new coin starts stopped; Stop forbids new entries while existing positions remain managed. All paper coins in «Симулятор» and «Арбитраж → Симуляция» @@ -130,141 +133,71 @@ The last tile «+» opens the **scanner panel**: start/stop of `meme_matcher/aut allows automatic additions (off by default; `meme_matcher/autoscan_config.json`); new connections appear within 30 seconds. Removing a pair first stops new entries and requests closing its exposure. If execution or recovery is unfinished, the connection stays available for management; the removal intent survives restart. +======= +## Реальная торговля и API-ключи +>>>>>>> main -**Live leader check** (`require_leader`, on by default, all lead modes): the policy samples both prices every 0.5 s -and every 10 s measures, over up to the last 20 minutes, the positive correlations of price changes with the follower -moving after the leader (lags 0.5–5 s) and before it; the difference is the leader's edge. Entries are blocked while -the edge is below `leader_min_edge` (0.1) or before 2 minutes of prices exist. The web page shows «кто ведёт» on each -tile. Measured live on 2026-10-17 (11 min): CLAUDIA DEX→MEXC edge +0.55 (the DEX leads), ZEREBRO DEX→Binance −0.62 -(Binance leads the DEX), SI −0.15, MARSCOIN ≈ 0. +Используйте реальную торговлю только после проверки в симуляции и на Testnet. -**Mode «Разрыв цен» (basis)**: the gap ln(leader) − ln(follower) against its usual level (exponential mean and -spread over `basis_window_seconds`, 60 s). A gap `basis_entry_z` (2) standard deviations and at least -`basis_min_gap_pct` (0.15%) away from usual opens a market order on the follower toward the leader; it is closed when -the gap is back within `basis_exit_z` (0.5) deviations («разрыв закрылся»), or by take-profit / stop / time. On the -same 11 minutes (0.5 s samples, rough): CLAUDIA basis + leader check 11 trades, 8 winners, +2.48 $ at a 100 $ stake, -while the lead mode lost 9.02 $; the leader check removed every trade on SI, ZEREBRO and MARSCOIN. +1. Создайте API-ключ с правами чтения аккаунта и торговли фьючерсами. +2. Отключите право вывода средств. +3. В интерфейсе откройте настройки API и включите Testnet для первой проверки. +4. Сохраните ключи и нажмите `Подключиться` — это только чтение баланса и позиций. +5. Только кнопка `Старт` запускает торговый цикл и может отправить реальные ордера. -Web page indicators: each tile says whether the pair suits trades now — «● подходит» (the leader leads by at least -`leader_min_edge`; the tile glows green and pulses for the first 2 minutes, «с ЧЧ:ММ»), «◐ почти», «○ не подходит» -(the futures lead) or «◌ проверяю» (less than 2 minutes of prices); the lead is shown in % = (leader→follower − -follower→leader) / (sum) × 100. Pairs enabled for trades are listed first. **Auto-stop** («Автостоп: CEX опережает -на, %», `auto_stop_pct`, default 20, 0 = off): on each new measurement (every 10 s), a trading pair whose futures lead -the leader by that % or more is stopped (no new entries; open positions close by their own exits); the tile shows -«⏸ автостоп …» with the time until Start is pressed again. +Ключи шифруются Windows DPAPI и доступны только текущему пользователю Windows на этом компьютере. Для Bybit требуется Unified USDT account и режим позиций One-Way. Реальные позиции должны дополнительно контролироваться в кабинете биржи: окно программы не является единственным механизмом защиты. -**«Арбитраж» tab** (`arb.py`): every 10 s the best bid/ask, funding and 24 h turnover of every USDT perpetual on -Bybit, Binance, MEXC, HTX and Gate (one public request per exchange; HTX/Gate contract sizes from their contract -lists, refreshed hourly). Coins are matched by base ticker (1000PEPE → PEPE ×1000). For each coin on 2+ exchanges the -page shows the best «buy at ask / sell at bid» pair among the ticked exchanges: the spread, net of market-order fees on -entry and exit on both sides (Bybit 0.055%, Binance 0.05%, MEXC 0.02%, HTX 0.05%, Gate 0.05%), the usual spread of that -pair (exponential average over ~30 min of the scanner's own readings, so it fills in after a while), the part above -the usual one net of fees, funding per 8 h (short receives its rate, long pays its rate), the money available at the -best prices (not reported by MEXC) and the smaller 24 h turnover. Filters: coin, turnover, depth, minimum spread, only -profitable after fees, hide spreads above 10% («разные монеты?»). Click a row for every exchange's prices and links. -Nothing is traded; the scanner starts on the first visit of the tab. «Держится в плюсе»: how long the pair's spread has -been above the round-trip costs without a break. «Учитывать перевод денег между биржами» (time, trade amount, transfer -fee): the scanner keeps the lowest spread of each pair per minute (last 3 hours, in memory — it starts again after a -restart), and the page uses the lowest spread over the transfer time instead of the current one: net with transfer = -that minimum − round-trip fees − transfer fee / amount. Pairs watched for less than the transfer time show «мало -истории». The first column is a step-by-step plan for the «Сумма сделки» amount: margin on both exchanges (or the -transfer with its time and fee), the LONG leg (exchange, symbol, price, quantity in coins or contract units, fee in $), -the SHORT leg, funding per 8 h in $, the exit fees, a warning when the best prices hold less money than the amount, -and the result in $ if the spread closes to zero / to its usual level, with the break-even spread (all fees: entry -and exit on both exchanges, plus the transfer fee when the transfer is taken into account). +В проекте предусмотрены отдельные состояния виртуального и реального счёта. Они не смешиваются. Для реального режима учитывайте funding, проскальзывание, минимальный размер ордера, задержку сети и риск ликвидации при усреднении или плече. +<<<<<<< HEAD **Local proxy with a VPN on**: `run_web_sim.bat` starts the engine on `127.0.0.1:8766` (`python.exe`) and the page proxy on `127.0.0.1:8765` (`pythonw.exe`). The page remains local even when `pythonw.exe` is excluded from the VPN. Both processes validate the original local Host and browser Origin; POST commands require the page's `X-Sim` header. The app is not configured for public internet hosting. `py -3 web_sim.py` serves the page directly on `127.0.0.1:8765`. +======= +## VPN, внешний доступ и безопасность +>>>>>>> main -**Saved connections** («Подключение»): every leader + follower combination used is kept in `lead_connections.json` -(coin, KuCoin market/ticker or DEX pool, follower exchange and ticker) and can be picked again from the list; a new one -is added automatically on «Применить», nothing is ever removed. Pre-filled: ZEREBRO (Raydium → Binance), -SI (Meteora → MEXC), MARSCOIN (KuCoin futures → Bybit, KuCoin spot → Bybit). +- Если биржи не отдают цены, проверьте VPN и доступ к публичным API. +- По умолчанию страница доступна только локально через `127.0.0.1`; это безопаснее, чем открывать её в интернет. +- Для внешнего доступа потребуется настройка прокси, проброс TCP-порта `8765` и правило Windows Firewall. Не публикуйте интерфейс без аутентификации. +- Не коммитьте API-ключи, файлы состояния и журналы с чувствительными данными в публичный репозиторий. -**Meteora DLMM pools and MEXC futures.** The DEX option («DEX пул Solana (Raydium / Meteora DLMM)») detects the pool's -program: for a Meteora DLMM pair the LbPair account is watched and the price is the active bin's -`(1 + bin_step/10000) ** active_id × 10^(decimals_x − decimals_y)` — it moves in whole bins (e.g. 0.3% for SI's -`8uwFMF…` pool). «Ставки на: MEXC фьючерс» reads `push.depth.full` (top 5, ~2 a second) and `push.deal` from -`wss://contract.mexc.com/edge`; contract size and price step come from `/api/v1/contract/detail`; the ticker is -converted automatically (SI_USDT ↔ SIUSDT). Paper fees now follow the exchange: Bybit 0.055% / 0.02%, Binance -0.05% / 0.02%, MEXC 0.02% / 0% (taker / maker). +## Тесты -**Automatic take-profit** («Авто тейк-профит по прогнозу», off by default): at a signal the follower's lag behind the -leader is measured over the comparison window (leader move − follower move, in the signal's direction); the forecast -of the follower's coming move = share × lag, and the take-profit is placed there from the follower's mid. The share -is «Доля догоняния, %» (default 100%) or, with «Учить долю на истории», the median of what the follower actually -caught up «Горизонт прогноза» seconds after each past signal (at most one sample a second; used after 10 samples, -capped at 300%). A signal whose forecast does not pay the spread and the fees (0.055% + 0.02%) is not entered. The -stop-loss and the holding time stay as set. - -The entry also refuses a trade whose stop-loss is inside the follower's spread (it would be stopped at once), and -«одна позиция на шаг цены» now also blocks re-entering at the price of the last entry after that position was -closed, until the price moves to another step. - -«Позиций одновременно» / «Между входами, с» (`max_positions`, `entry_gap_seconds`): up to N parallel positions of one -stake each, a new one not sooner than the gap after the previous entry; every position has its own take-profit, -stop and time; «Закрыть позицию» closes all. «Не больше одной позиции на один шаг цены Bybit» (`one_per_tick`, on by -default): a new position is not opened at a price where a position of the same side is already open, so one move does -not stack many identical positions on every data update; positions at other prices are still opened in parallel. - -«Мин. уверенность (0–1)» (`min_confidence`, 0 = off): confidence of a signal = average of (a) the KuCoin move's -strength (1 at twice the threshold), (b) how one-way it was (net move / path length of KuCoin's mid over the window), -and, in the vector mode, (c) how far Bybit already moved the same way (1 when as far as KuCoin). The lead mode uses -(a) and (b) only, because Bybit lagging is its signal. On ~45 min of recordings (5 parallel positions, TP 0.2 / -SL 0.3 / 300 s) higher thresholds gave fewer trades but not better ones: vector 0 → 138 trades, −0.112 $/trade; -0.7 → 65 trades, −0.149 $/trade. - -«Сразу закрывать, если ушло в минус на N шаг(а)» (`cut_loss`, `cut_loss_ticks`, both modes): the position is closed at -market as soon as Bybit's mid is N price steps against the mid at entry (mid vs mid, so the spread paid on entry does -not trigger it by itself), and the next signal is taken without the pause. On ~30 min of recordings (vector 5 s / -0.1%) it turned 17 trades / −2.07 $ into 59 trades / −8.05 $ at N = 1 (fees 6.11 $); N = 5 gave 33 trades / −3.38 $. - -## Scalping hint for MetaScalp - -`run_hint.bat` (or `py -3 scalp_hint.py`) opens a small always-on-top window that reads the order book and tape from the local MetaScalp API (`127.0.0.1:17845–17855`) for the order book currently open in the terminal, and follows the terminal when you switch tickers. It never sends orders. Every half second it combines book imbalance (near the price and within ±0.3%), tape delta and momentum over the last 60 seconds, and absorption (heavy market selling that does not move the price, or the mirror case) into a smoothed score. Above the threshold it shows LONG or SHORT with a limit entry next to the density on that side, a stop behind that density (at least 0.1% and half the recent range), and a target just before the opposite density; it shows WAIT when there is no edge or when the move would not cover costs (0.15%) or reward/risk is below 1:1.5. Each actionable hint is checked against later trades (limit filled only when traded through, then stop, target, or a 5-minute time stop, with maker/taker fees) and appended to `scalp_hint_journal.csv`; the window shows the running statistics. `py -3 scalp_hint.py --console 60` prints hints for a minute without the window. - -The **Тестовые сделки** panel runs a virtual account from those hints (`scalp_paper.py`; defaults: budget 300 USDT, 5 USDT per trade, leverage 1, target at least 0.2%). No order is ever sent to an exchange. Two decision schemes can be selected: - -- **Простая** — market entry when the hint is actionable; exit at the target (limit, maker fee, filled only when the market trades through it), at market as soon as the mid price moves the configured number of ticks against the entry, or after the maximum holding time. -- **Адаптивная** — measures the typical 30-second swing (noise) and how directionally the last 5 minutes moved. In a trend it joins the move with a passive limit at the touch; in a range it fades only the outer quarter of the range, confirmed by the order book (imbalance near the price and absorption — tape and momentum always point into the edge, so they are not used there), and never trades the middle or a range narrower than two noise swings. The stop sits beyond the noise (≥ 1.5 × noise, two spreads and 0.1%), the target is the opposite edge or at least 2 × the risk, and a trade is placed only if the reward after fees is at least 1.5 × the risk after fees and slippage. Limit orders expire after 60 s. After three losses in a row it pauses for 3 minutes and raises the entry threshold; the weights of the hint components are nudged towards those that preceded winning trades. - -- **Импульс + стакан** — when the price impulse and the book imbalance point the same way, a limit order is placed `pulse_offset_pct` (default 0.15%) away from the mid price in that direction (a buy below the price for LONG, a sell above it for SHORT). A tick is the next trade at a different price: an unfilled order is then cancelled and re-placed from the new price, and a filled position is closed at market on the next tick, whatever its result. There are no time limits. On the recorded PUFFERUSDT stream offsets of 0.05–0.25% lost money after fees, while 0.35–0.75% (orders that fill only on sharp one-tick spikes) were positive on few trades; treat that as a hypothesis to confirm on new recordings. - -- **Суммы значимых заявок** — takes the book levels within ±`sums_depth_pct` (default 0.3%) of the mid, drops the smallest 20% and the largest 10% of levels by count (dust and outsized walls; the cut is by count so many equal sizes are handled), and sums the rest per side (MetaScalp reports level sizes in USDT). When the imbalance (bids − asks) / (bids + asks) reaches ±`sums_threshold` (default 0.2) it rests a limit at the best bid/ask in that direction, moving with the best price while the imbalance holds and cancelling when it weakens. A position closes at the take-profit (`min_target_pct`, limit), at market when the imbalance flips past the threshold, or after the maximum holding time. On the recorded PUFFERUSDT stream (~8 h) the stronger settings (threshold 0.4, or a ±0.6% window) were slightly positive before fees and slightly negative after them. - -- **Algo Hunter** (`algo_hunter.py`) — looks for market-maker / HFT quoting in the book and trades it virtually with limit orders only. Layers: `AlgoDetector` (six signals over a 2 s window: periodic re-appearance of the same size within 80–500 ms, symmetric bid/ask quotes within 3 ticks, a cluster of equal-size best levels, re-quotes right after market orders, a dominant stable order size, batch add/cancel of that size; confidence 0.25 + 0.15 × signals, confirmed at ≥ 3 signals and 0.7), `AlgoTracker` (lifetime, replace frequency, typical offset from the touch, predicted re-quote level; the mode switches itself off when confidence stays below 0.3 for 4 s after a confirmed algo), the executor (front-run the algo's level 0–2 ticks behind the touch, or pre-place on its predicted re-quote, only with tape pressure in that direction; queue position modelled from the visible level size, fills when the queue in front is traded or the price trades through; TP/SL in ticks, optional breakeven trailing, time exit, emergency exit when the algo pulls a batch on our side) and `RiskGuard` (max position, daily loss, trades per minute, losing-streak pause, latency limits, cool-down after exit). Only aggregated levels are visible, so "the algo's order" is inferred from level sizes and queue priority is a model, not an observation. All parameters live in `algo_hunter_config.json` (see `algo_hunter_config.example.json`); the window exposes confidence, TP/SL, holding time and the **dry-run** switch (on by default: detection and logging only). Events go to `algo_hunter.log` with the `[ALGO_HUNTER]` tag, trades to `algo_hunter_trades.csv` (signature, algo levels, order times, queue in front, front-run flag, pnl in ticks, hold, exit reason). **Fast mode** (window checkboxes): «Закрывать на следующем тике» (`quick_exit`) closes the position at market on the first trade at a price other than the entry, up or down — no TP, SL or time limit (the emergency exit on a batch pull stays); «Переставлять заявку за стаканом» (`requote`) re-places the order on every book update wherever the algo now is, instead of cancelling it when confirmation flickers. «Без алгоса: микроцена + сдвиги спреда» (`fallback`): when no algo is confirmed (or its side has no candidate), the order is still placed — direction = sign of the microprice tilt (best bid size − best ask size) / (sum) plus the best-price moves of the last `fallback_window_ms` (bid up / ask up = +1, bid down / ask down = −1, capped at ±1 after dividing by 3); ties keep the previous direction; the price is one tick inside the spread on that side (at the touch when the spread is one tick). With it on, the "algo adapted" shutdown is skipped; spread, volatility and RiskGuard limits still apply. «Мин. спред для входа» (`min_entry_spread_ticks`, 0 = off) blocks entries — and cancels a resting order — while the spread is narrower than that many ticks; the upper bound `max_entry_spread_ticks` stays in the JSON. JSON-only helpers for more orders: `require_tape_pressure` (false: an empty tape does not block the entry) and `front_run_max_ticks` (how far behind the touch an algo level may be to front-run it). Two extra settings exist only in the JSON: `size_tolerance` (how close two order sizes must be to count as the algo's "same size", default 2%) and `rearm_after_ms` (when > 0, the mode switches back on by itself once the algo has been confirmed again for that long after an "adapted" shutdown; 0 = only the Apply button re-arms it). - - *Tuned for UBUSDT* (the current `algo_hunter_config.json`, profiled on 25 min of Bybit-direct recordings): the "algo" there is a ladder of ~20 $ orders (160/170 UB) one to four ticks apart, plus 300 UB and 970 UB orders 3–6 ticks from the touch; spread 7–15 ticks (median 11); only ~12 trades a minute. Settings: size tolerance 10%, 2 signals / confidence 0.55, near-touch window 12 ticks, entry spread ≤ 16 ticks, 1 s range ≤ 20 ticks, tape window 10 s, auto re-arm after 1 s, TP 4 / SL 6 ticks, hold 10 s, order 5 s. The order-latency limit is raised to 300 ms **for the simulation only**: at ~140 ms real data latency the queue race with the algo cannot be won, so the virtual results are optimistic. On the recordings this gave about 6 virtual trades in 25 min, mostly stops. The current config adds the fast mode (next-tick exit, re-quoting, 1 signal / confidence 0.4, no tape requirement, front-run up to 10 ticks, RiskGuard: 0.2 s cool-down, 60 trades/min, pause 1 min after 10 losses): about 2,800 orders and 41 trades in 25 min, but almost all lose (−2 ticks on average, −0.56 $ in total at a 15 $ stake): the order fills only when the market trades through it, and the market exit crosses an ~11-tick spread. UB prints only ~12 trades a minute, which caps how often any limit order can fill. - -**Источник стакана** (top of the window): MetaScalp (book updates about every 200 ms) or **Bybit напрямую** (public WebSocket `orderbook.50` about every 20 ms plus public trades, sizes converted to USDT; only for Bybit USDT perpetuals — other connections fall back to MetaScalp). Both feeds measure data latency against Bybit's server clock (re-synchronised every minute because the PC clock drifts) and show it in the window. Measured from this PC: Bybit direct ≈ 130–140 ms, MetaScalp ≈ 240–290 ms — above Algo Hunter's 50 ms data / 100 ms order limits, so the window warns at start and RiskGuard blocks virtual entries; the mode is then useful as a dry-run detector only. - -The panel shows balance, the pending limit or open position, the current regime and weights, and a trade table like MetaScalp's “Ваши сделки”; trades go to `scalp_paper_trades.csv`, balance and settings to `scalp_paper_state.json`. With **Записывать поток** on, the raw MetaScalp stream is saved to `scalp_recordings\*.jsonl.gz` (receive time, book snapshot/updates, trades). `py -3 scalp_paper.py compare` replays every recording through the simple scheme (1/3/5/10-tick exits) and the adaptive scheme (with and without self-tuning) and prints trades, win share, net result and exit reasons, so schemes are compared on identical data instead of live. The book copy drops levels in front of MetaScalp's best-price marks, and no hint is given while the book disagrees with the last trade by more than 0.3%. - -## Shared rules across modes - -`strategy.py` holds the formulas used by simulation, live trading and the backtest (TP with fee cover, stop, averaging level, liquidation estimate). The limit on simultaneous positions (main window, auto-selection row) applies to simulation, live trading and the backtest. A skipped add (not enough free margin) consumes that level in every mode; the next add is measured from it. Pairs waiting for retirement get no new entries and no averaging. In simulation a TP is filled at the TP level (not at the overshooting trade price). - -## Free balance - -The fourth box on the home screen shows money available for new trades. In simulation it is the balance minus margin locked in open positions plus their current unrealized P&L after the estimated closing fee (losing trades reduce it, profitable ones increase it); the same figure decides whether a new entry or add is allowed, and the backtest uses the same definition. In live mode it is Bybit's own available balance. Below it the app shows how many more default-size entries fit into that money and the simultaneous-position limit. - -## Tests +Запуск из корня проекта: ```powershell py -3 -m unittest discover -s tests ``` -## Real trading mode +Тесты покрывают backtest, веб-прокси, веб-симулятор, арбитраж, real/live-логику, ограничения позиций, funding и отдельные экспериментальные режимы. -Select **Реальная торговля**, open **API Bybit…**, paste the API key and secret, and leave **Testnet** enabled for initial checks. Click **Сохранить ключи** to store them encrypted with Windows DPAPI for the current Windows user; the app loads them automatically next time. Then click **Подключиться** to read the USDT wallet, unrealized P&L, recent realized P&L, up to 50 recent linear orders, and open USDT-settled positions. This is a read-only account refresh and does not start the bot or place orders. The loaded orders and positions appear in their own history tabs. Create a key with account read and linear-contract trading permissions only; disable withdrawals. The account must use Unified USDT balance and One-Way position mode. Each enabled symbol has its own strategy and management worker. +## Где искать проблемы -The stake setting is a percentage of the initial deposit snapshot for that API key and network. The first successful **Подключиться** or live **Старт** saves the current USDT wallet balance as that baseline; it stays fixed across later P&L changes and app restarts. In simulation, the percentage is applied to the configured starting capital. On Testnet, press **Старт** to verify each enabled market, balance, fee, leverage and position state. On Mainnet, the app asks for confirmation before connecting the trading loop. Starting the live bot can place real market orders. Every enabled currency gets its own monitoring and execution worker; entry orders share an account-wide lock and recheck available margin before submission. Existing positions for enabled symbols are reconciled and managed independently. Bybit's exchange-side full-position market TP/SL is attached, updated after fills, and remains active if the app is stopped. If an accepted order cannot yet be reconciled, that symbol's worker waits for the exchange state and blocks duplicate entries. The app also monitors positions and records completed PnL from Bybit. The **Закрыть сделку** button sends a reduce-only market close for the selected tile. Never rely on the app window as the only risk control; verify open positions and TP/SL in Bybit. +- Веб-страница не открывается: проверьте порт `8765` и запустите `УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat`, чтобы увидеть окно движка. +- Сервер не отвечает: изучите `web_sim_data/backend.log`, затем выполните `ОСТАНОВИТЬ_СЕРВЕР.bat` и `ЗАПУСТИТЬ_СЕРВЕР.bat`. +- Нет цен: проверьте интернет, VPN и доступ к API бирж. +- Не ставятся зависимости: проверьте интернет и наличие Python, затем повторите установку. +- Реальная сделка открыта: не останавливайте приложение, пока не проверили позицию и защитные ордера на бирже. -A signal skipped for insufficient margin or a too-small order no longer halts the symbol: the app reports it and keeps managing the pair. A manual close is confirmed by polling Bybit for up to 15 seconds. When a symbol's worker ends (for example after auto-rotation disables it), its queue is released so the pair gets a new worker when it qualifies again. Changing the subscribed pairs updates the WebSocket subscription in place instead of reconnecting. On Mainnet the app warns before starting when a currency has the stop-loss disabled. +## Структура проекта -The API account must have enough available margin for every add. Repeated averaging can increase exposure and liquidation risk. Funding and slippage depend on actual exchange fills. The history panel combines virtual rows and rows prefixed `LIVE`; the virtual balance is never mixed with the exchange wallet. **Сбросить статистику** applies only to the virtual account. +| Путь | Назначение | +|---|---| +| `web_sim.py`, `web_sim.html` | веб-движок и интерфейс симулятора | +| `web_proxy.py` | локальный HTTP-прокси | +| `main.py` | основной интерфейс симулятора | +| `strategy.py` | общие формулы и логика стратегий | +| `historical_backtest.py` | исторический прогон | +| `arb.py` | сканер арбитража | +| `cross.py`, `live.py`, `real_mirror.py` | live/real торговая логика | +| `scalp_hint.py`, `lead_window.py` | leader/follower режимы | +| `scalp_paper.py`, `algo_hunter.py` | бумажные и стаканные эксперименты | +| `meme_matcher/` | поиск и отбор мем-монет | +| `tests/` | автоматические тесты | -The app persists virtual and live closed-trade history, the live position shadow, and the initial-deposit baseline per API-key/network fingerprint in `account_state.json`. `settings.json` stores strategy inputs and the Testnet preference only. API credentials are encrypted with Windows DPAPI in the current user's local app data and can be removed from the Bybit settings window. In the strategy settings, an add-step value of `0` disables all follow-up entries. Bybit's order-history endpoint returns recent records with exchange retention rules; the window displays the latest 50 returned records. +## Удаление + +Сначала остановите сервер через `ОСТАНОВИТЬ_СЕРВЕР.bat`, затем удалите папку проекта. Если настраивали автозапуск через `web_sim_autostart.vbs`, удалите соответствующий ярлык из `shell:startup`.