commit 5c6b0dc54a0c0738d22f0baf13df7523d5509e13 Author: listik Date: Thu Oct 22 20:19:52 2026 +0300 update diff --git a/README.md b/README.md new file mode 100644 index 0000000..ddcd8b3 --- /dev/null +++ b/README.md @@ -0,0 +1,240 @@ +# Bybit Realtime Simulator + +Standalone real-time simulator and optional Bybit USDT-perpetual trading bot. + +## Run on Windows + +```powershell +cd C:\arb\RealtimePaperSimulator +py -3 -m pip install -r requirements.txt +py -3 main.py +``` + +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. + +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. + +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. + +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. + +### 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. + +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. + +## Strategy modes + +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. + +## 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. + +## Leader exchange: KuCoin → paper trades on Bybit + +`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. + +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. + +**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. + +«Ведущая: 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%). + +**Web interface** (`py -3 web_sim.py` or `run_web_sim.bat` → http://127.0.0.1:8765, opens in the browser): every +coin of the connection list runs at the same time with its own feeds, its own paper account and journal +(`web_sim_data/.json/.csv`) and its own Start/Stop (a new coin starts stopped; Stop only forbids new entries). +Top: the common trade settings («Применить ко всем монетам», saved in `web_sim_data/settings.json`; the first start +copies the Tk window's). Left: coin tiles (green dot = trading, open positions, price, result). Centre: a chart of both +exchanges' prices as % change over the last 1/5/10 minutes with entry/exit markers, the coin's statistics, Start/Stop, +«Закрыть все позиции», and the trade table — open positions on top in yellow with ✕ (close that one at the current +price), then closed trades, newest first. Tiles also show the win rate. The last tile «+» opens the **scanner panel**: +start/stop of the autonomous search (meme_matcher/autoscan.py, runs in the background), its log, and the coins it +checked (how often the DEX led, the latest figures); «+ Добавить» puts a coin where the DEX led into the left panel +(stopped, ready to test) when its pool and futures are supported. «Добавлять найденные автоматически» lets the search +add them by itself (off by default; meme_matcher/autoscan_config.json). Coins added to the list appear within 30 s. The Tk window +(`py -3 scalp_hint.py`) keeps its own separate account. + +**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. + +**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. + +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. + +**«Арбитраж» 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). + +**Access from outside with a VPN on**: `run_web_sim.bat` starts two processes — the engine +`py -3 web_sim.py --backend` (python.exe, 127.0.0.1:8766, needs the VPN for the exchanges) and the public page +`pyw -3 web_proxy.py` (pythonw.exe, 0.0.0.0:8765, forwards everything to the engine). Add +`…\Python312\pythonw.exe` to the VPN's app exclusions so answers to outside visitors leave through the home +connection; forward TCP 8765 in the router and allow it in Windows Firewall. `py -3 web_sim.py` alone still serves +the page itself on 0.0.0.0:8765 (`--local`: 127.0.0.1 only). + +**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). + +**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 + +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. + +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. + +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. diff --git a/algo_hunter.py b/algo_hunter.py new file mode 100644 index 0000000..5fa90e9 --- /dev/null +++ b/algo_hunter.py @@ -0,0 +1,945 @@ +"""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 _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 + 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) + 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) + 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) + 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) -> None: + order = self.order + 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) + 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 + 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) + + 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 + trader.close(price, now, reason, fee_pct) + 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 + + 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) + sig = self.sig + n = len(sig.signals) if sig else 0 + if cfg.fallback: + pass # without a confirmed algo the microprice + spread fallback places the order + elif n < cfg.min_signals_to_confirm: + out.append(f"алгос не подтверждён: признаков {n} из {cfg.min_signals_to_confirm}") + elif sig.confidence < cfg.min_confidence: + out.append(f"уверенность {sig.confidence:.2f} < {cfg.min_confidence:g}") + best_bid, best_ask = book.best() + if best_bid is not None and best_ask is not None and self.tick > 0: + spread = (best_ask - best_bid) / self.tick + if spread > cfg.max_entry_spread_ticks + 1e-9: + out.append(f"спред {spread:.0f} шаг. > {cfg.max_entry_spread_ticks}") + if spread < cfg.min_entry_spread_ticks - 1e-9: + out.append(f"спред {spread:.0f} шаг. < {cfg.min_entry_spread_ticks}") + if self._vol_ticks(now) > cfg.vol_cap_ticks: + out.append(f"волатильность за 1 с {self._vol_ticks(now):.0f} шаг. > {cfg.vol_cap_ticks:g}") + problem = self.guard.latency_problem(self._latency(trader)) + if problem: + out.append(problem.split(" — ")[0]) + allowed, reason = self.guard.allow(now, self.s.stake * self.s.leverage, None) + if not allowed and reason not in out: + out.append(reason) + return out + + # --- periodic: status for the window ---------------------------------------------------- + def on_tick(self, trader, now: float, ticker: str, hint, book: sh.OrderBook, tick: float) -> None: + if ticker != self.ticker and self.ticker: + self.detector = AlgoDetector(self.cfg) + self.tracker = AlgoTracker(self.cfg) + self.rearm() + self.ticker = ticker + if tick > 0: + self.tick = tick + sig = self.sig + latency = self._latency(trader) + parts = [] + if latency is not None: + parts.append(f"задержка данных ~{latency:.0f} мс" + (" (больше 50 мс: гонку за очередь не выиграть)" + if latency > self.cfg.max_data_latency_ms else "")) + if sig: + parts.append(f"уверенность {sig.confidence:.2f} ({', '.join(sig.signals)})") + if sig.price_levels: + shown = ", ".join(f"{p:.10g}×{v:,.0f}$" for p, v in list(zip(sig.price_levels, sig.volumes))[:4]) + parts.append(f"уровни алгоса [{sig.side}]: {shown}") + else: + parts.append("алгос не найден") + if self.order is not None and self.order.scenario == "микроцена + спред": + parts.append(self.fallback_info) + lifetime = self.tracker.avg_lifetime_ms + if lifetime: + offset_b = self.tracker.typical_offset_ticks("bid") + offset_a = self.tracker.typical_offset_ticks("ask") + parts.append(f"живёт {lifetime:.0f} мс · перестановок {self.tracker.replace_frequency(now):.1f}/с · отступ " + f"bid {offset_b if offset_b is not None else '—'} / ask {offset_a if offset_a is not None else '—'} шаг.") + e = self.stats["entries"] + parts.append(f"находок {self.stats['detections']} · заявок {self.stats['orders']} · входов {e} · в плюс " + f"{(self.stats['wins'] / e * 100 if e else 0):.0f}% · ср. {self.stats['pnl_ticks'] / e if e else 0:+.2f} шаг. · " + f"впереди алгоса {(self.stats['front_run'] / e * 100 if e else 0):.0f}%") + if self.cfg.dry_run: + parts.append("ПРОВЕРОЧНЫЙ РЕЖИМ: только детект и лог") + status = " · ".join(parts) + if trader.ledger.position is None and self.order is None: + blockers = self.entry_blockers(trader, now, book) + if not blockers and self.status_reason: + blockers = [self.status_reason] + if blockers: + status += "\nПочему нет входа: " + " · ".join(f"✗ {b}" for b in blockers) + self.status = status diff --git a/algo_hunter_config.example.json b/algo_hunter_config.example.json new file mode 100644 index 0000000..18a1f78 --- /dev/null +++ b/algo_hunter_config.example.json @@ -0,0 +1,42 @@ +{ + "algo_hunter": { + "detection_window_ms": 2000, + "min_interval_ms": 80, + "max_interval_ms": 500, + "max_spread_ticks": 3, + "min_levels_cluster": 2, + "max_volume_cv": 0.15, + "batch_size_threshold": 3, + "reaction_latency_ms": 150, + "min_signals_to_confirm": 3, + "depth_levels": 10, + "size_tolerance": 0.02, + "adaptive_exit_threshold": 0.3, + "adaptive_exit_ms": 4000, + "rearm_after_ms": 0, + "prediction_confidence": 0.75, + "dry_run": true, + "min_confidence": 0.7, + "entry_tape_window_ms": 1000, + "max_entry_spread_ticks": 2, + "vol_cap_ticks": 4, + "tp_ticks": 2, + "sl_ticks": 3, + "trailing": false, + "tp_partial_ticks": 1, + "max_hold_ms": 2000, + "order_ttl_ms": 2000, + "quick_exit": false, + "requote": false, + "require_tape_pressure": true, + "front_run_max_ticks": 2, + "max_position_usd": 50.0, + "max_daily_loss_usd": 5.0, + "max_trades_per_minute": 20, + "max_consecutive_losses": 3, + "pause_minutes": 5.0, + "max_order_latency_ms": 100, + "max_data_latency_ms": 50, + "cooldown_after_exit_ms": 1000 + } +} \ No newline at end of file diff --git a/arb.py b/arb.py new file mode 100644 index 0000000..443dc51 --- /dev/null +++ b/arb.py @@ -0,0 +1,576 @@ +"""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 re +import threading +import time +import urllib.request +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 +# 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} +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": {}, "binance_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) + 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["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: + 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(__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, "Binance": self.fetchers.binance, "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=5) as pool: + for name, qs, st in pool.map(one, EXCHANGES): + quotes += qs + status[name], counts[name] = st, len(qs) + rows = best_pairs(quotes, self.usual, market=self.market, wallet=getattr(self.fetchers, "wallet", None)) + alpha = min(1.0, CYCLE_S / USUAL_WINDOW_S) + now = time.time() + minute = int(now // 60) + for r in rows: # the usual spread of the chosen pair (updated after use) + prev = self.usual.get(r["key"]) + self.usual[r["key"]] = r["gross"] if prev is None else prev + alpha * (r["gross"] - prev) + self.record(r["key"], r["gross"], r["net_now"] > 0, now, minute) + self._prune(minute) + with self.lock: + self.rows, self.status, self.counts = rows, status, counts + self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000) + + HISTORY_MIN = 180 + + def record(self, key: str, gross: float, profitable: bool, now: float, minute: int) -> None: + h = self.history.setdefault(key, {}) + h[minute] = min(h.get(minute, gross), gross) + if profitable: + self.profitable_since.setdefault(key, now) + else: + self.profitable_since.pop(key, None) + + def _prune(self, minute: int) -> None: + if minute % 10: + return + for key in list(self.history): + h = self.history[key] + for m in [m for m in h if m < minute - self.HISTORY_MIN]: + del h[m] + if not h: + del self.history[key] + + def window_min(self, key: str, minutes: float, now: float) -> tuple[float | None, float]: + """(lowest spread over the last `minutes`, minutes of history actually available for this pair).""" + h = self.history.get(key, {}) + current = int(now // 60) + span = int(max(1, round(minutes))) + recent = [v for m, v in h.items() if m > current - span] + have = len([m for m in h if m > current - self.HISTORY_MIN]) + return (min(recent) if recent else None), float(have) + + def view(self, transfer_min: float | None = None) -> dict: + self.ensure_running() + with self.lock: + now = time.time() + rows = [] + for r in self.rows: + r = dict(r) + since = self.profitable_since.get(r["key"]) + r["held_min"] = None if since is None else (now - since) / 60 + if transfer_min: + low, have = self.window_min(r["key"], transfer_min, now) + r["window_low"] = low + r["history_min"] = have + rows.append(r) + return {"rows": rows, "status": self.status, "counts": self.counts, "updated": self.updated, + "cycle_ms": self.cycle_ms, "taker": SPOT_TAKER if self.market == "spot" else TAKER, + "market": self.market, "cycle_s": CYCLE_S, "paused": self.paused, + "usual_minutes": USUAL_WINDOW_S / 60, "transfer_min": transfer_min} diff --git a/basis.py b/basis.py new file mode 100644 index 0000000..812f21c --- /dev/null +++ b/basis.py @@ -0,0 +1,1334 @@ +"""Spot–futures basis trades on one exchange (paper): buy the coin on spot while it is cheaper than the perpetual, +short the same amount of coins on the perpetual, close both legs when the gap has closed (≈ 0). + +Coins: new listings, the exchange's innovation zone and memecoins that have both a USDT spot pair and a USDT +perpetual. Only Bybit is implemented; other exchanges plug in as another Venue. + + entry gap = perp bid / spot ask − 1 (buy spot at the ask, short the perp at the bid) + exit gap = perp ask / spot bid − 1 (sell spot at the bid, buy the perp back at the ask) + +Result of one trade = spot leg + perp leg − 4 taker fees + funding the short received while it was open. +""" + +from __future__ import annotations + +import json +import queue +import threading +import time +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from dataclasses import asdict, dataclass, field, fields +from pathlib import Path + +from arb import _f, _get, split_base + +ROOT = Path(__file__).resolve().parent +DATA_DIR = ROOT / "web_sim_data" +POLL_S = 1.0 +INSTRUMENTS_S = 3600.0 +MEMES_S = 6 * 3600.0 +KEEP_TRADES = 500 + +# used when CoinGecko's meme-token list cannot be fetched (it rate-limits often) +MEME_FALLBACK = set("""DOGE SHIB PEPE FLOKI BONK WIF BOME MEW POPCAT BRETT MOG TURBO NEIRO NEIROCTO PNUT GOAT MOODENG ACT +CHILLGUY FARTCOIN TRUMP MELANIA PENGU SPX GIGA PONKE MYRO SLERF BABYDOGE DOGS NOT CAT MEME BAN AI16Z ZEREBRO +LADYS WEN SATS ORDI RATS COQ TOSHI MICHI BILLY DEGEN HIPPO SUNDOG HMSTR CATI MOTHER DADDY RETARDIO SIGMA LUCE +FWOG SC DOG BOOK BOOKOFMEME KEKIUS VINE TST BROCCOLI MUBARAK JELLYJELLY HOUSE USELESS PUMP TROLL ANSEM CLAUDIA +MANYU BUTTCOIN ELON KISHU BONE LEASH SNEK GME AIDOGE PEOPLE WOJAK HPOS10I APU MAGA LOBO QUBIC SHIB2""".split()) + + +@dataclass +class Pair: + """One coin with both a spot pair and a perpetual on the venue; prices per coin.""" + base: str + spot_symbol: str + fut_symbol: str + mult: float + spot_bid: float + spot_ask: float + fut_bid: float + fut_ask: float + spot_bid_usd: float | None # $ at the best price (None: the exchange does not report it) + spot_ask_usd: float | None + fut_bid_usd: float | None + fut_ask_usd: float | None + funding: float # per interval, fraction (0.0001 = 0.01%) + next_funding: float # unix seconds + interval_h: float + spot_turnover: float + fut_turnover: float + age_days: float | None + innovation: bool + meme: bool + + @property + def entry_gap(self) -> float: + return (self.fut_bid / self.spot_ask - 1) * 100 + + @property + def exit_gap(self) -> float: + return (self.fut_ask / self.spot_bid - 1) * 100 + + +class BybitVenue: + name = "Bybit" + spot_fee = 0.1 + fut_fee = 0.055 + innovation_fee = 0.11 # perps of the Innovation Zone: their own taker rate (bybit.com/fee, regular user) + + def __init__(self) -> None: + self.instruments: dict[str, dict] = {} # base → {fut_symbol, spot_symbol, mult, launch, innovation} + self.instruments_time = 0.0 + + @staticmethod + def spot_url(p: Pair) -> str: + return f"https://www.bybit.com/trade/spot/{p.base}/USDT" + + @staticmethod + def fut_url(p: Pair) -> str: + return f"https://www.bybit.com/trade/usdt/{p.fut_symbol}" + + def refresh_instruments(self) -> None: + if self.instruments and time.time() - self.instruments_time < INSTRUMENTS_S: + return + spot = {s["symbol"] for s in _get("https://api.bybit.com/v5/market/instruments-info?category=spot")["result"] + ["list"] if s.get("status") == "Trading" and s.get("quoteCoin") == "USDT" + and s.get("symbolType") in ("", "adventure")} + out = {} + cursor = "" + while True: + res = _get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000" + + (f"&cursor={cursor}" if cursor else ""))["result"] + for x in res["list"]: + # stock / ETF / commodity / forex perps are not the same thing as a spot coin + if (x.get("status") != "Trading" or x.get("contractType") != "LinearPerpetual" + or x.get("quoteCoin") != "USDT" or x.get("symbolType") not in ("", "innovation")): + continue + base, mult = split_base(x["baseCoin"]) + spot_symbol = f"{base}USDT" + if spot_symbol not in spot: + continue + out[base] = {"fut_symbol": x["symbol"], "spot_symbol": spot_symbol, "mult": mult, + "launch": int(x.get("launchTime") or 0) / 1000 or None, + "innovation": x.get("symbolType") == "innovation", + "interval_h": int(x.get("fundingInterval") or 480) / 60} + cursor = res.get("nextPageCursor") or "" + if not cursor or not res["list"]: + break + self.instruments, self.instruments_time = out, time.time() + + def pairs(self, memes: set[str]) -> list[Pair]: + self.refresh_instruments() + spot = {t["symbol"]: t for t in _get("https://api.bybit.com/v5/market/tickers?category=spot")["result"]["list"]} + fut = {t["symbol"]: t for t in _get("https://api.bybit.com/v5/market/tickers?category=linear")["result"]["list"]} + now = time.time() + out = [] + for base, ins in self.instruments.items(): + s, f = spot.get(ins["spot_symbol"]), fut.get(ins["fut_symbol"]) + if not s or not f: + continue + m = ins["mult"] + sb, sa, fb, fa = _f(s.get("bid1Price")), _f(s.get("ask1Price")), _f(f.get("bid1Price")), _f(f.get("ask1Price")) + if min(sb, sa, fb, fa) <= 0: + continue + out.append(Pair( + base, ins["spot_symbol"], ins["fut_symbol"], m, sb, sa, fb / m, fa / m, + sb * _f(s.get("bid1Size")), sa * _f(s.get("ask1Size")), fb * _f(f.get("bid1Size")), + fa * _f(f.get("ask1Size")), _f(f.get("fundingRate")), _f(f.get("nextFundingTime")) / 1000, + _f(f.get("fundingIntervalHour"), ins["interval_h"]) or ins["interval_h"], + _f(s.get("turnover24h")), _f(f.get("turnover24h")), + None if not ins["launch"] else (now - ins["launch"]) / 86400, ins["innovation"], base in memes)) + return out + + +def _listing_binance() -> dict[str, dict]: + out = {} + for s in _get("https://fapi.binance.com/fapi/v1/exchangeInfo")["symbols"]: + # TradFi perps (stocks, gold…) are not the spot coin of the same name + if (s.get("contractType") != "PERPETUAL" or s.get("status") != "TRADING" or s.get("quoteAsset") != "USDT" + or s.get("underlyingType") != "COIN" or "TradFi" in (s.get("underlyingSubType") or [])): + continue + out[s["symbol"]] = {"launch": _f(s.get("onboardDate")) / 1000 or None, + "meme": "Meme" in (s.get("underlyingSubType") or []), "innovation": False} + return out + + +def _listing_mexc() -> dict[str, dict]: + out = {} + for c in _get("https://contract.mexc.com/api/v1/contract/detail")["data"]: + if c.get("quoteCoin") != "USDT" or c.get("state") not in (0, None) or c.get("futureType") not in (1, None): + continue + zones = " ".join(c.get("conceptPlate") or []).lower() + out[c["symbol"]] = {"launch": _f(c.get("openingTime") or c.get("createTime")) / 1000 or None, + "meme": "meme" in zones, "innovation": bool(c.get("isNew"))} + return out + + +def _listing_htx() -> dict[str, dict]: + out = {} + for c in _get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]: + if c.get("contract_status") != 1 or not c["contract_code"].endswith("-USDT"): + continue + try: + launch = time.mktime(time.strptime(c.get("create_date", ""), "%Y%m%d")) + except ValueError: + launch = None + labels = [x.lower() for x in c.get("labels") or []] + out[c["contract_code"]] = {"launch": launch, "meme": "meme" in labels, "innovation": "new" in labels} + return out + + +def _listing_gate() -> dict[str, dict]: + out = {} + for c in _get("https://api.gateio.ws/api/v4/futures/usdt/contracts"): + if c.get("in_delisting") or (c.get("status") not in (None, "trading")): + continue + out[c["name"]] = {"launch": _f(c.get("launch_time") or c.get("create_time")) or None, "meme": False, + "innovation": False} + return out + + +class ArbVenue: + """Binance, MEXC, HTX, Gate: prices from the arbitrage scanner's fetchers (one request per market), listing + date / meme tag from the exchange's contract list (hourly). Funding is settled every `interval_h` hours on the + UTC grid. Where an exchange does not report the size at the best price (MEXC futures, Gate spot) the depth is + unknown (None) and not checked.""" + + innovation_fee = 0.0 # their «new» label is not a fee group + + SETUP = {"binance": ("Binance", 0.1, 0.05, _listing_binance), + "mexc": ("MEXC", 0.05, 0.02, _listing_mexc), + "htx": ("HTX", 0.2, 0.05, _listing_htx), + "gate": ("Gate", 0.1, 0.05, _listing_gate)} + + def __init__(self, key: str) -> None: + import arb + self.arb = arb + self.key = key + self.name, self.spot_fee, self.fut_fee, self._listing = self.SETUP[key] + self.fut, self.spot = arb.Fetchers(), arb.SpotFetchers() + self.listing: dict[str, dict] = {} + self.listing_time = 0.0 + + def spot_url(self, p: Pair) -> str: + return self.arb.spot_url(self.name, p.spot_symbol, p.base) + + def fut_url(self, p: Pair) -> str: + return self.arb.exchange_url(self.name, p.fut_symbol) + + def pairs(self, memes: set[str]) -> list[Pair]: + if not self.listing or time.time() - self.listing_time > INSTRUMENTS_S: + try: + self.listing, self.listing_time = self._listing(), time.time() + self.fut.refresh_reference() # funding intervals, contract sizes + except Exception: + if not self.listing: + raise + if self.key in ("binance", "mexc"): + self.spot.refresh_volume() + # both markets at once: a slow exchange (Gate) then costs one wait, not two + with ThreadPoolExecutor(max_workers=2) as pool: + fut_job = pool.submit(getattr(self.fut, self.key)) + spot_job = pool.submit(getattr(self.spot, self.key)) + futs = fut_job.result() + spots = {q.base: q for q in spot_job.result() if q.mult == 1} + now = time.time() + out = [] + for f in futs: + info = self.listing.get(f.symbol) + s = spots.get(f.base) + if info is None or s is None: + continue + interval = f.interval_h or 8.0 + step = interval * 3600 + out.append(Pair( + f.base, s.symbol, f.symbol, f.mult, s.bid, s.ask, f.bid, f.ask, s.bid_usd, s.ask_usd, f.bid_usd, + f.ask_usd, f.funding or 0.0, (now // step + 1) * step, interval, s.volume_usd, f.volume_usd, + None if not info["launch"] else (now - info["launch"]) / 86400, info["innovation"], + info["meme"] or f.base in memes)) + return out + + +VENUES = {"bybit": BybitVenue, "binance": lambda: ArbVenue("binance"), "mexc": lambda: ArbVenue("mexc"), + "htx": lambda: ArbVenue("htx"), "gate": lambda: ArbVenue("gate")} +PLANNED: list[str] = [] + + +@dataclass +class BasisSettings: + running: bool = False # open new trades (prices and exits go on when stopped) + amount: float = 100.0 # $ per trade: spent on spot, the same coins shorted on the perp + min_gap_pct: float = 0.6 # open when perp is at least this much above spot (after the spread) + max_gap_pct: float = 10.0 # …and not more (bigger = broken price, delisting, different coin) + exit_gap_pct: float = 0.05 # close both legs when the gap is back to this or below + stop_gap_pct: float = 0.0 # close at a loss when the gap widens to this (0 = off) + max_hold_hours: float = 0.0 # close after this long whatever the gap (0 = off) + max_positions: int = 10 + cooldown_s: float = 60.0 # no new entry on the same coin this soon after a close + new_days: float = 90.0 # «new coin»: perpetual listed within this many days + use_new: bool = True + use_innovation: bool = True + use_memes: bool = True + all_coins: bool = False # ignore the three above and take every coin with spot + perp + min_turnover: float = 200000.0 # 24h turnover of the thinner market, $ + min_depth: float = 0.0 # $ at the best prices on both legs (0 = only the trade amount itself) + spot_fee: float = 0.1 + fut_fee: float = 0.055 + fut_fee_innovation: float = 0.0 # perp taker rate of the Innovation Zone coins (Bybit 0.11); 0 = as «fut_fee» + real: bool = False # new trades as real orders with the exchange's API keys + auto_transfer: bool = True # move USDT between the spot and futures accounts when one of them is short + max_real_positions: int = 1 # real positions held at the same time (entries still go one after another) + entry_limit: bool = True # real entry: LIMIT short at the signal's perp bid first, then the spot hedge + limit_hold_s: float = 10.0 # …kept this long, then removed (nothing bought if it did not fill) + exchange_tp: bool = False # (off: the program watches the prices itself; kept for old settings files) + + +@dataclass +class Position: + uid: int + base: str + opened: float + qty: float # coins bought on spot = coins shorted + spot_entry: float + fut_entry: float + entry_gap: float + fees: float + next_funding: float + funding: float = 0.0 # $ received by the short (negative = paid) + # real positions: actual coins of each leg (the perp is rounded down to its lot), the perp symbol, and the + # close in progress (perp bought back first, then the spot sold; a failed spot sale is retried) + real: bool = False + spot_qty: float = 0.0 + fut_symbol: str = "" + closing: str = "" # "" / "fut_done" (perp bought back, spot still to sell) + fut_exit: float = 0.0 + exit_fees: float = 0.0 + retry_at: float = 0.0 + error: str = "" + sold_coins: float = 0.0 # spot sold so far by the close (from the exchange's fills) + sold_value: float = 0.0 + sold_fees: float = 0.0 + short_pending: bool = False # the spot leg is held but the perp short is not open yet (adopted coins…) + tp_order: str = "" # TP on the exchange (reduce-only limit buy of the short), "" = none + tp_price: float = 0.0 + exact: bool = True # all prices and fees are the exchange's own figures + innovation: bool = False # an Innovation Zone perp: its own fee rate + + +@dataclass +class Trade: + uid: int + base: str + opened: float + closed: float + qty: float + spot_entry: float + spot_exit: float + fut_entry: float + fut_exit: float + entry_gap: float + exit_gap: float + spot_pnl: float + fut_pnl: float + fees: float + funding: float + net: float + reason: str + amount: float = 0.0 + real: bool = False # done with real orders (figures from the exchange's fills) + exact: bool = True + + +def fut_rate(s: BasisSettings, innovation: bool) -> float: + """Perp taker rate, %: the Innovation Zone coins of Bybit have their own (higher) rate.""" + return s.fut_fee_innovation if innovation and s.fut_fee_innovation > 0 else s.fut_fee + + +def entry_fees(qty: float, spot_ask: float, fut_bid: float, s: BasisSettings, innovation: bool = False) -> float: + return qty * spot_ask * s.spot_fee / 100 + qty * fut_bid * fut_rate(s, innovation) / 100 + + +def close_result(pos: Position, spot_bid: float, fut_ask: float, s: BasisSettings) -> tuple[float, float, float, float]: + """(spot leg $, perp leg $, all fees $, net $) of closing `pos` at these prices.""" + spot_qty = pos.spot_qty or pos.qty # real: the spot leg can hold a little more than the perp's lot + if pos.closing == "fut_done": # real close half done: the perp is already bought back + fut_ask = pos.fut_exit + spot_pnl = spot_qty * (spot_bid - pos.spot_entry) + fut_pnl = pos.qty * (pos.fut_entry - fut_ask) + fees = pos.fees + spot_qty * spot_bid * s.spot_fee / 100 + pos.qty * fut_ask * fut_rate(s, pos.innovation) / 100 + return spot_pnl, fut_pnl, fees, spot_pnl + fut_pnl - fees + pos.funding + + +ENGINES: list = [] # every running spot–futures engine (each exchange and «between exchanges») +# A gap this large is not a premium but two different instruments under one ticker (MEXC EWT: spot 0.34 $, perp +# 104.84 $): never traded, whatever «Макс. расхождение» says. +HARD_MAX_GAP_PCT = 20.0 +# Right before an order: the perp leg may not be worth more than the trade amount × this (same coins on both legs). +MAX_LEG_RATIO = 1.25 + + +def busy_elsewhere(base: str, me) -> str: + """Name of another spot–futures engine where this coin is already in a trade (or being entered), "" if none: + one coin is never traded twice at the same time, whichever exchange or mode.""" + for e in list(ENGINES): + if e is me: + continue + if any(p.base == base for p in list(e.positions)) or base in getattr(e, "opening", set()): + return getattr(getattr(e, "venue", None), "name", None) or "Между биржами" + return "" + + +def live_client(exchange: str): + import live + return live.client(exchange) + + +def entry_depth(p: Pair) -> float | None: + """$ available at the entry prices on both legs (spot ask, perp bid); None when either is not reported.""" + known = [v for v in (p.spot_ask_usd, p.fut_bid_usd) if v is not None] + return min(known) if len(known) == 2 else None + + +def depth_ok(p: Pair, s: BasisSettings) -> bool: + need = max(s.amount, s.min_depth) + return all(v is None or v >= need for v in (p.spot_ask_usd, p.fut_bid_usd)) + + +def in_universe(p: Pair, s: BasisSettings) -> bool: + if s.all_coins: + return True + return ((s.use_new and p.age_days is not None and p.age_days <= s.new_days) + or (s.use_innovation and p.innovation) or (s.use_memes and p.meme)) + + +class BasisEngine: + def __init__(self, venue_key: str = "bybit", data_dir: Path = DATA_DIR, start: bool = True) -> None: + self.key = venue_key + self.venue = VENUES[venue_key]() + self.file = data_dir / f"basis_{venue_key}.json" + self.lock = threading.RLock() + self.settings = BasisSettings(spot_fee=self.venue.spot_fee, fut_fee=self.venue.fut_fee, + fut_fee_innovation=self.venue.innovation_fee) + self.positions: list[Position] = [] + self.trades: list[Trade] = [] + self.next_uid = 1 + self.last_close: dict[str, float] = {} + self.pairs: dict[str, Pair] = {} + self.memes: set[str] = set(MEME_FALLBACK) + self.memes_source = "встроенный список" + self.status, self.updated, self.cycle_ms = "загружаю…", 0.0, 0 + self.message = "" + self.opening: set[str] = set() # coins with a real entry in progress + self.jobs: queue.Queue = queue.Queue() # real orders, sent one by one from a worker thread + self.client_for = live_client + self.busy: set[int] = set() # real positions whose close is being sent right now + self.real_block: dict[str, tuple[str, float]] = {} # coin → (why it cannot be traded for real, until) + self.real_pause_until, self.real_pause_reason = 0.0, "" # the whole exchange (e.g. balance too small) + self.pending: dict[str, dict] = {} # coin → real entry in progress (written BEFORE the spot is bought) + self.recover: set[str] = set() # pending entries found after a restart: adopt what was bought + self.adopting: set[str] = set() # coins being taken over from the spot balance right now + self.tp_checked: dict[int, float] = {} # position → when its TP on the exchange was last looked at + self.tp_tried: set[int] = set() # positions a TP was tried for in this run + self.fast_seen: dict[str, float] = {} # coin → when the fast watch last priced it + self.fast_ms = 0 # how long the last fast look took + self._load() + if start: + threading.Thread(target=self._loop, daemon=True).start() + threading.Thread(target=self._memes_loop, daemon=True).start() + threading.Thread(target=self._worker, daemon=True).start() + threading.Thread(target=self._fast_loop, daemon=True).start() + ENGINES.append(self) + + # --- persistence --------------------------------------------------------------------------- + def _load(self) -> None: + try: + d = json.loads(self.file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + known = {f.name for f in fields(BasisSettings)} + for k, v in (d.get("settings") or {}).items(): + if k in known: + setattr(self.settings, k, type(getattr(self.settings, k))(v)) + self.settings.exchange_tp = False # no TP orders on the exchange any more: the program closes by itself + self.settings.max_gap_pct = min(self.settings.max_gap_pct, HARD_MAX_GAP_PCT) + self.positions = [Position(**p) for p in d.get("positions", [])] + self.trades = [Trade(**t) for t in d.get("trades", [])] + self.next_uid = d.get("next_uid", 1) + # entries that were in progress when the program stopped: the coins may be on the spot account now + self.recover = set(d.get("pending") or {}) + + def save(self) -> None: + self.file.parent.mkdir(exist_ok=True) + data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions], + "trades": [asdict(t) for t in self.trades[-KEEP_TRADES:]], "next_uid": self.next_uid, + "pending": self.pending} + tmp = self.file.with_suffix(".tmp") + tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") + tmp.replace(self.file) + + def set_settings(self, values: dict) -> str: + with self.lock: + for f in fields(BasisSettings): + if f.name not in values: + continue + try: + v = values[f.name] + v = (v in (True, "true", "1", 1, "on")) if f.type in ("bool", bool) else type(getattr(self.settings, f.name))(float(v)) + except (TypeError, ValueError): + return f"неверное значение: {f.name}" + setattr(self.settings, f.name, v) + s = self.settings + if s.amount <= 0 or s.max_positions < 0: + return "сумма и число позиций должны быть больше 0" + if s.max_gap_pct > HARD_MAX_GAP_PCT: + s.max_gap_pct = HARD_MAX_GAP_PCT + self.save() + return (f"«Макс. расхождение» не может быть больше {HARD_MAX_GAP_PCT:g}%: такая разница — это разные " + f"инструменты под одним тикером, а не премия. Установлено {HARD_MAX_GAP_PCT:g}%, остальное сохранено") + if s.min_gap_pct <= s.exit_gap_pct: + return "разница для входа должна быть больше разницы для выхода" + if set(values) - {"running"}: + # new settings (a bigger amount, a topped-up account…): coins and the exchange are checked anew + self.real_block.clear() + self.real_pause_until, self.real_pause_reason = 0.0, "" + self.save() + return "" + + # --- data ---------------------------------------------------------------------------------- + def _memes_loop(self) -> None: + while True: + got: set[str] = set() + try: + for page in (1, 2, 3, 4): + req = urllib.request.Request( + "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=meme-token" + f"&per_page=250&page={page}", headers={"User-Agent": "Mozilla/5.0"}) + with urllib.request.urlopen(req, timeout=30) as resp: + items = json.loads(resp.read()) + got |= {x["symbol"].upper() for x in items} + if len(items) < 250: + break + time.sleep(8) + except Exception: + pass + if len(got) > 100: + self.memes, self.memes_source = got | MEME_FALLBACK, f"CoinGecko meme-token ({len(got)})" + time.sleep(MEMES_S) + else: + time.sleep(600) + + def _loop(self) -> None: + while True: + start = time.time() + try: + pairs = self.venue.pairs(self.memes) + with self.lock: + fresh_now = time.time() + new = {p.base: p for p in pairs} + for b, seen in self.fast_seen.items(): # the fast watch's prices are newer than this list + if b in new and b in self.pairs and fresh_now - seen < 2.0: + new[b] = self.pairs[b] + self.pairs = new + self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000) + self.status = "ok" + self.step(self.updated) + except Exception as exc: + self.status = f"нет данных: {exc}" + time.sleep(max(0.2, POLL_S - (time.time() - start))) + + # --- trading ------------------------------------------------------------------------------- + def candidates(self) -> list[Pair]: + s = self.settings + return [p for p in self.pairs.values() if in_universe(p, s) + and min(p.spot_turnover, p.fut_turnover) >= s.min_turnover] + + def step(self, now: float) -> None: + """Exits first (gap closed, stop, time), funding on the shorts, then new entries.""" + s = self.settings + changed = False + for base in list(self.recover): + # an entry cut off by a stop of the program: whatever spot it bought becomes a position again + if base in self.pairs and base not in self.opening: + self.opening.add(base) + self.recover.discard(base) + self.jobs.put(("adopt", base)) + changed = self._check_exits(now) + # real: one entry at a time (never two buys in parallel), and no more open real positions than allowed + real_busy = s.real and (self.opening or self.adopting or now < self.real_pause_until + or sum(pos.real for pos in self.positions) >= max(1, s.max_real_positions)) + if s.running and not real_busy: # real: the next trade only after the previous is confirmed closed + changed = self._entries(now) or changed + if changed: + self.save() + + def _check_exits(self, now: float) -> bool: + """Every open position against the latest prices: funding, then the exit rules. Called by the market cycle + AND by the fast watch of open positions (several times a second) — the program, not a TP on the exchange, + decides the close, whichever way the gap converges.""" + s = self.settings + changed = False + for pos in list(self.positions): + p = self.pairs.get(pos.base) + if p is None: + continue + if pos.real and pos.short_pending: + # spot held without its hedge: open the short (retried while the exchange refuses); no auto exit — + # the gap logic needs both legs; «×» sells the spot + if pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + self.jobs.put(("short", pos.uid)) + continue + while pos.next_funding and now >= pos.next_funding: + pos.funding += pos.qty * (p.fut_bid + p.fut_ask) / 2 * p.funding # short receives positive funding + pos.next_funding = p.next_funding if p.next_funding > pos.next_funding else pos.next_funding + p.interval_h * 3600 + changed = True + gap = p.exit_gap + reason = ("разница сошлась" if gap <= s.exit_gap_pct + else "стоп: разница расширилась" if s.stop_gap_pct > 0 and gap >= s.stop_gap_pct + else "время удержания" if s.max_hold_hours > 0 and now - pos.opened >= s.max_hold_hours * 3600 + else "") + if pos.real and pos.closing == "fut_done" and now >= pos.retry_at: + reason = reason or "продажа спота после выкупа шорта" + if reason: + if pos.real: + if pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + self.jobs.put(("close", pos.uid, reason)) + else: + self._close(pos, p, now, reason) + changed = True + elif pos.real and pos.tp_order and not pos.closing and pos.uid not in self.busy: + self.busy.add(pos.uid) # a TP left on the exchange by the older version: remove it + self.jobs.put(("untp", pos.uid)) + return changed + + def _entries(self, now: float) -> bool: + s = self.settings + changed = False + if True: + busy = {pos.base for pos in self.positions} | self.opening + for p in sorted(self.candidates(), key=lambda p: -p.entry_gap): + if len(self.positions) + len(self.opening) >= s.max_positions: + break + if p.base in busy or now - self.last_close.get(p.base, 0) < s.cooldown_s: + continue + if busy_elsewhere(p.base, self): + continue # the same coin is already in a trade on another exchange / mode + if not (s.min_gap_pct <= p.entry_gap <= min(s.max_gap_pct, HARD_MAX_GAP_PCT)): + continue + if not depth_ok(p, s): + continue + if self._too_small(p): + continue # paper too: only trades the exchange would accept on both legs + if s.real and self.real_block.get(p.base, ("", 0.0))[1] > now: + continue # known: cannot be traded for real (lot too big for the amount…) + if s.real: + self.opening.add(p.base) + self.jobs.put(("open", p, s.amount)) + break # one real trade at a time + qty = s.amount / p.spot_ask + inno = self._innovation(p) + self.positions.append(Position(self.next_uid, p.base, now, qty, p.spot_ask, p.fut_bid, p.entry_gap, + entry_fees(qty, p.spot_ask, p.fut_bid, s, inno), p.next_funding, + innovation=inno)) + self.next_uid += 1 + busy.add(p.base) + changed = True + return changed + + # --- fast watch of open positions ------------------------------------------------------------------------ + FAST_S = 0.25 # target pause between two looks at the open positions' prices + + def _fast_loop(self) -> None: + """While positions are open: their spot and perp best prices, several times a second (one symbol each, + kept-alive connections), and the exit rules on those fresh prices.""" + import dataclasses + import fastquote + pool = ThreadPoolExecutor(max_workers=8) + while True: + start = time.time() + with self.lock: + watch = {pos.base: self.pairs[pos.base] for pos in self.positions + if pos.base in self.pairs and not pos.short_pending} + if not watch: + time.sleep(0.5) + continue + ex = self.venue.name + jobs = {b: (pool.submit(fastquote.spot_top, ex, p.spot_symbol), pool.submit(fastquote.fut_top, ex, p.fut_symbol)) + for b, p in watch.items()} + fresh = {} + for b, (sj, fj) in jobs.items(): + try: + sb, sa, sbu, sau = sj.result() + fb, fa, fbu, fau = fj.result() + except Exception: + continue + p, m = watch[b], watch[b].mult + if min(sb, sa, fb, fa) <= 0: + continue + fresh[b] = dataclasses.replace(p, spot_bid=sb, spot_ask=sa, fut_bid=fb / m, fut_ask=fa / m, + spot_bid_usd=sbu, spot_ask_usd=sau, + fut_bid_usd=fbu if fbu is not None else p.fut_bid_usd, + fut_ask_usd=fau if fau is not None else p.fut_ask_usd) + if fresh: + now = time.time() + with self.lock: + self.pairs.update(fresh) + for b in fresh: + self.fast_seen[b] = now + self.fast_ms = int((now - start) * 1000) + if self._check_exits(now): + self.save() + time.sleep(max(0.05, self.FAST_S - (time.time() - start))) + + def _min_entry(self, p: Pair) -> dict | None: + """The smallest amount both the spot buy and the perp short of this coin accept (exchange rules).""" + import minorder + return minorder.RULES.min_entry(self.venue.name, p.base, p.spot_ask, self.venue.name, p.fut_symbol, p.fut_bid, + self.settings.spot_fee) + + def _too_small(self, p: Pair) -> str: + import minorder + return minorder.too_small(self.settings.amount, self._min_entry(p), self.venue.name, self.venue.name) + + def _innovation(self, p: Pair) -> bool: + """The coin's perp pays the Innovation Zone rate (Bybit only: other exchanges' «new» label is no fee group).""" + return bool(p.innovation and self.venue.innovation_fee) + + def _fut_rate(self, p: Pair | None) -> float: + return fut_rate(self.settings, bool(p) and self._innovation(p)) + + def _close(self, pos: Position, p: Pair, now: float, reason: str) -> Trade: + spot_pnl, fut_pnl, fees, net = close_result(pos, p.spot_bid, p.fut_ask, self.settings) + t = Trade(pos.uid, pos.base, pos.opened, now, pos.qty, pos.spot_entry, p.spot_bid, pos.fut_entry, p.fut_ask, + pos.entry_gap, p.exit_gap, spot_pnl, fut_pnl, fees, pos.funding, net, reason, + pos.qty * pos.spot_entry) + self.positions.remove(pos) + self.trades.append(t) + self.last_close[pos.base] = now + return t + + def close(self, uid: int | None) -> str: + with self.lock: + n = real = 0 + for pos in list(self.positions): + if uid is not None and pos.uid != uid: + continue + if pos.real: + if pos.uid not in self.busy: + self.busy.add(pos.uid) + pos.retry_at = 0.0 + self.jobs.put(("close", pos.uid, "вручную")) + real += 1 + continue + p = self.pairs.get(pos.base) + if p is None: + continue + self._close(pos, p, time.time(), "вручную") + n += 1 + self.save() + return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "") + + # --- real orders (worker thread; never under the engine lock while waiting for the exchange) ----------------- + def _journal(self, coin: str, action: str, ok: bool, text: str, **extra) -> None: + import real_mirror + real_mirror.journal("basis", self.key, coin, action, ok, text, **extra) + + def _worker(self) -> None: + while True: + kind, *args = self.jobs.get() + try: + if kind == "open": + self._real_open(*args) + elif kind == "close": + self._real_close(*args) + elif kind == "short": + self._real_short(*args) + elif kind == "watch": + self._watch_tp(*args) + elif kind == "untp": + self._remove_tp(*args) + elif kind == "tp": + pos = next((x for x in self.positions if x.uid == args[0]), None) + if pos is not None and not pos.tp_order: + self._place_tp(self.client_for(self.key), pos) + elif kind == "adopt": + msg = self.adopt(args[0]) + if "подхвачено" not in msg: + self._journal(args[0], "open", True, f"после перезапуска: незавершённый вход — {msg}") + except Exception as exc: # the worker must survive anything + self._journal(getattr(args[0], "base", "?") if args else "?", kind, False, f"сбой: {exc}") + if kind == "open" and args: + with self.lock: + self.opening.discard(args[0].base) + finally: + if kind in ("close", "short", "watch", "tp", "untp") and args: + with self.lock: + self.busy.discard(args[0]) + if kind == "open" and args and args[0].base in self.pending: + with self.lock: # the entry is finished (position, sold back or refused) + self.pending.pop(args[0].base, None) + self.save() + if kind == "adopt" and args: + with self.lock: + self.recover.discard(args[0]) + self.opening.discard(args[0]) + self.pending.pop(args[0], None) + self.save() + + SHORT_RETRY_S = 300.0 + + def _real_short(self, uid: int) -> None: + """Open the missing perp short for a held spot leg (the same coins, rounded down to the lot).""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + p = self.pairs.get(pos.base) if pos else None + if pos is None or not pos.short_pending or p is None: + return + fut = None + try: + c = self.client_for(self.key) + coins = c.fut_round(pos.fut_symbol, pos.spot_qty) + if coins <= 0: + raise live.LiveError(f"монет {pos.spot_qty:g} меньше минимального лота фьючерса") + if coins * p.fut_bid > pos.spot_qty * pos.spot_entry * MAX_LEG_RATIO: + raise live.LiveError(f"шорт стоил бы {coins * p.fut_bid:.2f} $ при споте на " + f"{pos.spot_qty * pos.spot_entry:.2f} $ — разные инструменты под одним тикером") + if self.settings.auto_transfer: + try: # margin for the short, from the spot USDT if needed + moved = live.ensure_usdt(c, 0.0, coins * p.fut_bid * 1.03) + if moved: + self._journal(pos.base, "transfer", True, moved) + except (live.LiveError, AttributeError) as exc: + self._journal(pos.base, "transfer", False, f"перевод не удался: {exc}") + fut = c.fut_order(pos.fut_symbol, "sell", coins, reduce_only=False) + except live.LiveError as exc: + if getattr(exc, "sent", False): + fut = None # may be open: the position check decides + try: + held = -c.fut_position(pos.fut_symbol) + except live.LiveError: + held = 0.0 + if held > 0: + fut = live.Fill(held, p.fut_bid, held * p.fut_bid * self._fut_rate(p) / 100, exc.order_id, + exact=False) + if fut is None: + with self.lock: + changed = pos.error != f"шорт не открыт: {exc}" + pos.error, pos.retry_at = f"шорт не открыт: {exc}", time.time() + self.SHORT_RETRY_S + self.save() + if changed: + self._journal(pos.base, "open", False, f"шорт не открыт: {exc} — спот {pos.spot_qty:g} держится " + f"без хеджа, повтор через {self.SHORT_RETRY_S / 60:.0f} мин (× у позиции — продать спот)") + self._pause_if_balance(str(exc)) + return + with self.lock: + pos.qty, pos.fut_entry, pos.short_pending, pos.error = fut.coins, fut.price, False, "" + pos.fees += fut.fee_usd + pos.entry_gap = (fut.price / pos.spot_entry - 1) * 100 + pos.next_funding = p.next_funding + pos.exact = pos.exact and fut.exact + self.save() + self._journal(pos.base, "open", True, f"шорт к споту открыт: {fut.coins:g} по {fut.price:.10g}, разница к цене " + f"покупки спота {pos.entry_gap:+.3f}% — дальше обычное закрытие при схождении") + self._place_tp(c, pos) + + def adopt(self, base: str, price: float | None = None, fee_usd: float | None = None) -> str: + """Take coins that are on the spot account into the program as a real position (spot leg; the short is + opened next). `price` — what they were bought at (from the exchange's history), else the current ask.""" + import live + base = base.upper().strip() + with self.lock: + p = self.pairs.get(base) + if any(pos.base == base and pos.real for pos in self.positions): + return f"{base} уже ведётся программой" + if p is not None: + self.adopting.add(base) # «busy» for the entry logic while the balance is read + if p is None: + return f"{base}: нет пары спот + фьючерс на {self.venue.name}" + try: + free = self.client_for(self.key).spot_free(base) + except live.LiveError as exc: + with self.lock: + self.adopting.discard(base) + return f"не удалось прочитать баланс: {exc}" + if free * p.spot_bid < 1.0: + with self.lock: + self.adopting.discard(base) + return f"на споте нет {base} (свободно {free:g})" + price = price or p.spot_ask + fee = fee_usd if fee_usd is not None else free * price * self.settings.spot_fee / 100 + with self.lock: + pos = Position(self.next_uid, base, time.time(), 0.0, price, 0.0, 0.0, fee, p.next_funding, real=True, + spot_qty=free, fut_symbol=p.fut_symbol, short_pending=True, + error="подхвачена с баланса: шорт ещё не открыт", innovation=self._innovation(p)) + self.next_uid += 1 + self.positions.append(pos) + self.adopting.discard(base) + self.save() + self._journal(base, "open", True, f"подхвачено со спота {free:g} {base} по {price:.10g} — открываю шорт") + return f"{base}: подхвачено {free:g} монет, шорт откроется следующим шагом" + + def _real_open(self, p: Pair, amount: float) -> None: + import live + notes = [] + # BEFORE buying anything: can the perp be shorted for this amount at all (its minimum lot)? + try: + c = self.client_for(self.key) + min_coins = c.fut_min_coins(p.fut_symbol) + except (live.LiveError, AttributeError) as exc: + self._not_tradable(p.base, f"нет правил контракта: {exc}", 300) + return + coins_est = amount / p.spot_ask * (1 - self.settings.spot_fee / 100) + if not self._legs_match(p, coins_est, amount): + return + if coins_est < min_coins: + need = min_coins * p.spot_ask / (1 - self.settings.spot_fee / 100) * 1.02 + self._not_tradable(p.base, f"сумма {amount:g} $ меньше минимального лота фьючерса ({min_coins:g} монет ≈ " + f"{need:.2f} $)", 1800) + return + with self.lock: + # last check right before money is spent: no other entry in progress, the limit of real positions kept + held = [x.base for x in self.positions if x.real] + if (p.base in held or self.adopting or self.opening - {p.base} or busy_elsewhere(p.base, self) + or len(held) >= max(1, self.settings.max_real_positions)): + self.opening.discard(p.base) + return + self.pending[p.base] = {"time": time.time(), "amount": amount} # a stop now: found again at start + self.save() + # money where it is needed: the amount on spot for the buy, the same on futures for the short's margin + # (leverage 1 assumed — the safe side); moved from the other account when one of them is short + if self.settings.auto_transfer: + try: + moved = live.ensure_usdt(c, amount * 1.01, amount * 1.03) + if moved: + self._journal(p.base, "transfer", True, moved) + except (live.LiveError, AttributeError) as exc: + if "в сумме" in str(exc): + self._journal(p.base, "open", False, f"не открываю: {exc} — спот не покупался") + self._pause_if_balance(str(exc)) + with self.lock: + self.opening.discard(p.base) + return + self._journal(p.base, "transfer", False, f"перевод не удался: {exc} — пробую без него") + if self.settings.entry_limit: + self._open_limit_first(c, p, amount) + return + try: + buy = c.spot_buy(p.base, amount) + except live.LiveError as exc: + # accepted but not confirmed: what is on the account decides whether the coin was bought + bought = 0.0 + if getattr(exc, "sent", False): + try: + bought = min(c.spot_free(p.base), amount / p.spot_ask * 1.02) + except live.LiveError: + bought = 0.0 + if bought <= 0: + self._journal(p.base, "open", False, f"покупка на споте: {exc}") + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() # pause before trying this coin again + self._pause_if_balance(str(exc)) + return + buy = live.Fill(bought, p.spot_ask, amount * self.settings.spot_fee / 100, exc.order_id) + notes.append("покупка не подтверждена биржей — цена оценочная") + try: + free = c.spot_free(p.base) + except live.LiveError: + free = 0.0 + held = min(buy.coins, free) if free > 0 else buy.coins * (1 - self.settings.spot_fee / 100) + fut, failure, coins = None, "", 0.0 + try: + coins = c.fut_round(p.fut_symbol, held) + if coins <= 0: + raise live.LiveError("монет меньше минимального лота фьючерса") + fut = c.fut_order(p.fut_symbol, "sell", coins, reduce_only=False) + except live.LiveError as exc: + failure = str(exc) + if getattr(exc, "sent", False) and coins > 0: + # the short may be open: keep the position (estimated price) — closing it is reduce-only + fut = live.Fill(coins, p.fut_bid, coins * p.fut_bid * self._fut_rate(p) / 100, exc.order_id) + notes.append("шорт не подтверждён биржей — проверьте позицию, цена оценочная") + if fut is None: + # no hedge → sell the spot back at once + try: + back = c.spot_sell(p.base, held) + text = f"шорт не открылся ({failure}); спот продан обратно по {back.price:.10g}" + except live.LiveError as exc2: + text = f"шорт не открылся ({failure}); СПОТ НЕ ПРОДАН ({exc2}) — продайте {held:g} {p.base} вручную" + self._journal(p.base, "open", False, text) + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + self._pause_if_balance(failure) + return + with self.lock: + self.opening.discard(p.base) + pos = Position(self.next_uid, p.base, time.time(), fut.coins, buy.price, fut.price, + (fut.price / buy.price - 1) * 100, buy.fee_usd + fut.fee_usd, p.next_funding, + real=True, spot_qty=held, fut_symbol=p.fut_symbol, error="; ".join(notes), + exact=buy.exact and fut.exact and not notes, innovation=self._innovation(p)) + self.next_uid += 1 + self.positions.append(pos) + self.save() + self._journal(p.base, "open", True, f"куплено {held:g} по {buy.price:.10g}, шорт {fut.coins:g} по " + f"{fut.price:.10g}, разница {pos.entry_gap:+.3f}%" + (f" ({'; '.join(notes)})" if notes else ""), + amount=amount) + self._place_tp(c, pos) + + def _open_limit_first(self, c, p: Pair, amount: float) -> None: + """Entry with a LIMIT short at the signal's perp bid, kept up to `limit_hold_s` seconds; whatever part of it + fills is hedged at once by buying the same coins on spot. Nothing filled → the order is removed, no spot.""" + import live + s = self.settings + coins = c.fut_round(p.fut_symbol, amount / p.spot_ask * (1 - s.spot_fee / 100)) + if not self._legs_match(p, coins, amount): + return + try: + oid = c.fut_limit(p.fut_symbol, "sell", coins, p.fut_bid) + except (live.LiveError, AttributeError) as exc: + self._journal(p.base, "open", False, f"лимитный шорт не выставлен: {exc}") + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + self._pause_if_balance(str(exc)) + return + st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False} + end = time.time() + max(0.0, s.limit_hold_s) + while True: # one look a second: the exchange's request limit + try: + st = c.fut_order_status(p.fut_symbol, oid) + except live.LiveError: + pass + if st["final"] or st["coins"] >= coins * 0.999 or time.time() >= end: + break + time.sleep(1.0) + if not st["final"]: + try: + c.fut_cancel(p.fut_symbol, oid) + except live.LiveError: + pass + try: # what filled until the cancel + st = c.fut_order_status(p.fut_symbol, oid) + except live.LiveError: + try: + st = {**st, "coins": max(0.0, -c.fut_position(p.fut_symbol))} + except live.LiveError: + pass + shorted = st["coins"] + if shorted <= 0: + self._journal(p.base, "open", False, f"лимитный шорт по {p.fut_bid:.10g} не исполнился за " + f"{s.limit_hold_s:g} с — снят, спот не покупался") + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + return + fut_price = st["price"] or p.fut_bid + # hedge: the same coins on spot (the buy fee is taken in coins: a little more USDT) + try: + buy = c.spot_buy(p.base, shorted * p.spot_ask * (1 + s.spot_fee / 100) * 1.003) + except live.LiveError as exc: + try: + c.fut_order(p.fut_symbol, "buy", shorted, reduce_only=True) + text = f"шорт {shorted:g} исполнился, но спот не куплен ({exc}); шорт закрыт" + except live.LiveError as exc2: + text = f"шорт {shorted:g} исполнился, спот не куплен ({exc}); ШОРТ НЕ ЗАКРЫТ ({exc2}) — закройте вручную" + self._journal(p.base, "open", False, text) + with self.lock: + self.opening.discard(p.base) + self.last_close[p.base] = time.time() + self._pause_if_balance(str(exc)) + return + try: + free = c.spot_free(p.base) + except live.LiveError: + free = 0.0 + held = min(buy.coins, free) if free > 0 else buy.coins * (1 - s.spot_fee / 100) + with self.lock: + self.opening.discard(p.base) + pos = Position(self.next_uid, p.base, time.time(), shorted, buy.price, fut_price, + (fut_price / buy.price - 1) * 100, buy.fee_usd + st["fee"], p.next_funding, + real=True, spot_qty=held, fut_symbol=p.fut_symbol, exact=buy.exact, + innovation=self._innovation(p)) + self.next_uid += 1 + self.positions.append(pos) + self.save() + self._journal(p.base, "open", True, f"лимитный шорт {shorted:g} по {fut_price:.10g} (заявка {p.fut_bid:.10g}), " + f"спот куплен {held:g} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}%", amount=amount) + self._place_tp(c, pos) + + def _place_tp(self, c, pos: Position) -> None: + """TP on the exchange: a reduce-only LIMIT buy of the short at the price where the gap has closed against + the spot bought (perp = spot entry + «Закрыть при»). When it fills, the program sells the spot.""" + import live + if not self.settings.exchange_tp or pos.qty <= 0: + return + tp = pos.spot_entry * (1 + self.settings.exit_gap_pct / 100) + if tp >= pos.fut_entry: + return # the gap is already as small as the exit level + try: + oid = c.fut_take_profit(pos.fut_symbol, "buy", pos.qty, tp) + except (live.LiveError, AttributeError) as exc: + self._journal(pos.base, "open", False, f"TP на бирже не выставлен: {exc} — закрытие по схождению программой") + return + with self.lock: + pos.tp_order, pos.tp_price = str(oid), tp + self.save() + self._journal(pos.base, "open", True, f"TP на бирже: выкуп шорта лимитом по {tp:.10g} " + f"({(tp / pos.fut_entry - 1) * 100:+.3f}% от входа)") + + def _remove_tp(self, uid: int) -> None: + """Take a TP order off the exchange (the program watches the gap itself now). If it filled meanwhile, the + position is closed through the usual path, which counts what the TP bought back.""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or not pos.tp_order or pos.closing: + return + c = self.client_for(self.key) + try: + c.fut_cancel(pos.fut_symbol, pos.tp_order) + except (live.LiveError, AttributeError): + pass + try: + filled = c.fut_order_status(pos.fut_symbol, pos.tp_order)["coins"] + except (live.LiveError, AttributeError): + filled = 0.0 + if filled > 0: + self._real_close(uid, "TP на бирже исполнился до снятия") + return + with self.lock: + pos.tp_order, pos.tp_price = "", 0.0 + self.save() + self._journal(pos.base, "open", True, "TP на бирже снят — закрытие решает программа по свежим ценам") + + WATCH_TP_S = 3.0 + + def _watch_tp(self, uid: int) -> None: + """Has the TP on the exchange bought the short back? Then the spot is sold now (via the usual close).""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or not pos.tp_order or pos.closing: + return + try: + held = self.client_for(self.key).fut_position(pos.fut_symbol) + except live.LiveError: + return + if held > -pos.qty * 1e-6: # no short left: the TP has filled + self._real_close(uid, "TP на бирже") + + def _legs_match(self, p: Pair, coins: float, amount: float) -> bool: + """Last guard before an order: the same coins on spot and perp must be worth about the same. A perp leg + worth far more than the amount means two different instruments under one ticker — no order at all.""" + fut_value = coins * p.fut_bid + if p.entry_gap > HARD_MAX_GAP_PCT or fut_value > amount * MAX_LEG_RATIO: + self._not_tradable(p.base, f"шорт {coins:g} монет стоил бы {fut_value:.2f} $ при сумме {amount:g} $ — " + f"спот и фьючерс под этим тикером разные инструменты", 86400) + return False + return True + + def _not_tradable(self, base: str, why: str, seconds: float) -> None: + """The coin cannot be traded for real now: skip it (no spot bought) and say why in the table, once.""" + with self.lock: + known = self.real_block.get(base, ("", 0.0))[0] == why + self.real_block[base] = (why, time.time() + seconds) + self.opening.discard(base) + if not known: + self._journal(base, "open", False, f"не открываю: {why} — спот не покупался") + + BALANCE_PAUSE_S = 900.0 + + def _pause_if_balance(self, error: str) -> None: + """Not enough money on the account (MEXC 2005 «Balance insufficient», …): no real entries on this exchange + for a while — every new try would only buy the spot and sell it back.""" + if any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно", "не хватает")): + with self.lock: + self.real_pause_until = time.time() + self.BALANCE_PAUSE_S + self.real_pause_reason = ("не хватает баланса на бирже — пополните счёт (фьючерсы и спот) " + "или уменьшите «Сумму сделки»") + self._journal("—", "open", False, f"{self.real_pause_reason}; реальные входы на паузе 15 мин") + + def _real_close(self, uid: int, reason: str) -> None: + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None: + return + stage = "выкуп шорта" + try: + c = self.client_for(self.key) + if pos.qty <= 0 and pos.closing != "fut_done": + with self.lock: # no short was ever opened: only the spot is sold + pos.closing, pos.fut_exit = "fut_done", pos.fut_entry + self.save() + # 1) buy the short back (reduce-only: it can never open anything); what the TP on the exchange has + # already bought back counts, the rest is bought at market + if pos.closing != "fut_done": + tp_coins = tp_price = tp_fee = 0.0 + if pos.tp_order: + try: + c.fut_cancel(pos.fut_symbol, pos.tp_order) + except (live.LiveError, AttributeError): + pass # already filled or gone + try: + st = c.fut_order_status(pos.fut_symbol, pos.tp_order) + tp_coins, tp_price, tp_fee = st["coins"], st["price"], st["fee"] + except (live.LiveError, AttributeError): + pass + with self.lock: + pos.tp_order = "" + self.save() + rest = pos.qty - tp_coins + fut_coins, fut_price, fut_fee, exact = 0.0, 0.0, 0.0, True + if rest > pos.qty * 1e-6: + try: + fut = c.fut_order(pos.fut_symbol, "buy", rest, reduce_only=True) + fut_coins, fut_price, fut_fee, exact = fut.coins, fut.price, fut.fee_usd, fut.exact + except live.LiveError as exc: + if not getattr(exc, "sent", False): + raise + p = self.pairs.get(pos.base) # accepted, not confirmed: the position check decides + fut_coins, fut_price = rest, (p.fut_ask if p else pos.fut_entry) + fut_fee, exact = rest * fut_price * fut_rate(self.settings, pos.innovation) / 100, False + done = tp_coins + fut_coins + avg = (tp_coins * tp_price + fut_coins * fut_price) / done if done else pos.fut_entry + with self.lock: + pos.fut_exit, pos.exit_fees, pos.closing = avg, tp_fee + fut_fee, "fut_done" + pos.exact = pos.exact and exact + self.save() + # 2) the exchange must show no short left; a remainder is bought back too + stage = "проверка фьючерса" + held = c.fut_position(pos.fut_symbol) if pos.qty > 0 else 0.0 + if held < -1e-12: + c.fut_order(pos.fut_symbol, "buy", -held, reduce_only=True) + raise live.LiveError(f"на фьючерсе оставалось {held:+g} — докуплено, проверяю ещё раз") + # 3) sell the coins this trade bought (never more: other coins on the account are not ours) + stage = "продажа спота" + p = self.pairs.get(pos.base) + price_now = p.spot_bid if p else pos.spot_entry + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0: # more than dust left to sell + free = c.spot_free(pos.base) + if free * price_now > 1.0: + sell = c.spot_sell(pos.base, min(free, left)) + with self.lock: + pos.sold_coins += sell.coins + pos.sold_value += sell.coins * sell.price + pos.sold_fees += sell.fee_usd + pos.exact = pos.exact and sell.exact + self.save() + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0 and c.spot_free(pos.base) * price_now > 1.0: + raise live.LiveError(f"на споте ещё {left:g} {pos.base} — продам при следующей попытке") + if pos.sold_coins <= 0: + raise live.LiveError("спот не продан") + except live.LiveError as exc: + with self.lock: + pos.retry_at, pos.error = time.time() + 15, f"{stage}: {exc}" + self.save() + self._journal(pos.base, "close", False, f"{stage}: {exc} — следующая сделка не откроется, пока эта не " + f"закрыта; повтор через 15 с") + return + with self.lock: + now = time.time() + sell_price = pos.sold_value / pos.sold_coins + spot_pnl = pos.sold_value - pos.sold_coins * pos.spot_entry + fut_pnl = pos.qty * (pos.fut_entry - pos.fut_exit) + fees = pos.fees + pos.exit_fees + pos.sold_fees + net = spot_pnl + fut_pnl - fees + pos.funding + t = Trade(pos.uid, pos.base, pos.opened, now, pos.qty, pos.spot_entry, sell_price, pos.fut_entry, + pos.fut_exit, pos.entry_gap, (pos.fut_exit / sell_price - 1) * 100 if pos.qty > 0 else 0.0, + spot_pnl, fut_pnl, fees, + pos.funding, net, f"{reason} (реально{'' if pos.exact else ', часть цифр оценочная'})", + pos.spot_qty * pos.spot_entry, real=True, exact=pos.exact) + if pos in self.positions: + self.positions.remove(pos) + self.trades.append(t) + self.last_close[pos.base] = now + self.save() + self._journal(pos.base, "close", True, f"шорт выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет), спот " + f"продан по {sell_price:.10g}, итог {net:+.4f} $, комиссии {fees:.4f} $ ({reason})", net=net) + + def reset(self) -> str: + with self.lock: + if any(p.real for p in self.positions): + return "есть открытые реальные позиции — сначала закройте их" + self.positions, self.trades, self.last_close = [], [], {} + self.save() + return "статистика сброшена" + + # --- view ---------------------------------------------------------------------------------- + def view(self) -> dict: + with self.lock: + s = self.settings + now = time.time() + rows = [] + real_open = [x.base for x in self.positions if x.real] + for p in self.candidates(): + m = self._min_entry(p) + import minorder + small = minorder.too_small(s.amount, m, self.venue.name, self.venue.name) + fits = (s.min_gap_pct <= p.entry_gap <= min(s.max_gap_pct, HARD_MAX_GAP_PCT) and depth_ok(p, s) + and not small) + # why this coin is not entered now — shown in the table instead of an empty cell + elsewhere = busy_elsewhere(p.base, self) + why = (f"разница больше {HARD_MAX_GAP_PCT:g}% — это разные инструменты под одним тикером, не торгуется" + if p.entry_gap > HARD_MAX_GAP_PCT + else f"уже в сделке: {elsewhere}" if elsewhere + else "разница ниже «Мин. расхождения»" if p.entry_gap < s.min_gap_pct + else "разница выше «Макс.»" if p.entry_gap > s.max_gap_pct + else "мало объёма по лучшей цене" if not depth_ok(p, s) + else small if small + else "торговля остановлена (кнопка «Старт»)" if not s.running + else (f"открыто реальных позиций {len(real_open)} из {max(1, s.max_real_positions)} " + f"({', '.join(real_open)}) — ждёт закрытия" + if s.real and len(real_open) >= max(1, s.max_real_positions) and p.base not in real_open else + "сейчас открывается другая реальная сделка" if s.real and (self.opening - {p.base}) else + f"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until else + f"пауза по монете после закрытия ({s.cooldown_s:g} с)" + if now - self.last_close.get(p.base, 0) < s.cooldown_s else "")) + rows.append({**asdict(p), "entry_gap": p.entry_gap, "exit_gap": p.exit_gap, "why": why, + "funding_pct": p.funding * 100, "spot_url": self.venue.spot_url(p), + "fut_url": self.venue.fut_url(p), + "net_if_closed_pct": p.entry_gap - s.exit_gap_pct - 2 * (s.spot_fee + self._fut_rate(p)), + "fut_fee_pct": self._fut_rate(p), + "min_entry": m["usd"] if m else None, "min_spot": m["spot"] if m else None, + "min_fut": m["fut"] if m else None, + "depth": entry_depth(p), + "real_block": (self.real_block.get(p.base, ("", 0.0))[0] + if s.real and self.real_block.get(p.base, ("", 0.0))[1] > now else ""), + "fits": fits}) + rows.sort(key=lambda r: -r["entry_gap"]) + positions = [] + for pos in self.positions: + p = self.pairs.get(pos.base) + d = asdict(pos) + if p: + spot_pnl, fut_pnl, fees, net = close_result(pos, p.spot_bid, p.fut_ask, s) + seen = self.fast_seen.get(pos.base) + d.update(price_age=None if seen is None else now - seen, fast_ms=self.fast_ms) + d.update(gap_now=p.exit_gap, spot_now=p.spot_bid, fut_now=p.fut_ask, net=net, fees_total=fees, + spot_url=self.venue.spot_url(p), fut_url=self.venue.fut_url(p)) + positions.append(d) + # real mode: the figures are those of the real trades only (prices and fees from the exchange's fills) + closed = [t for t in self.trades if t.real] if s.real else self.trades + opened = [p for p in positions if p.get("real")] if s.real else positions + wins = sum(t.net > 0 for t in closed) + invested = sum(t.amount for t in closed) + stats = {"trades": len(closed), "wins": wins, "net": sum(t.net for t in closed), + "net_pct": sum(t.net for t in closed) / invested * 100 if invested else None, + "fees": sum(t.fees for t in closed), "funding": sum(t.funding for t in closed), + "open": len(opened), "unrealized": sum(p.get("net", 0) for p in opened), + "real": s.real, "exact": all(t.exact for t in closed), + "avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None} + return {"venue": self.venue.name, "key": self.key, "settings": asdict(s), "status": self.status, + "updated": self.updated, "cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.pairs), + "memes_source": self.memes_source, "rows": rows, "positions": positions, + "real_pause": (f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)" + if s.real and now < self.real_pause_until else ""), + "trades": [asdict(t) for t in reversed(closed[-200:])], "stats": stats, + "planned": PLANNED} diff --git a/bybit_live.py b/bybit_live.py new file mode 100644 index 0000000..da9ea91 --- /dev/null +++ b/bybit_live.py @@ -0,0 +1,260 @@ +"""Small signed Bybit V5 client used by the optional live-trading mode. + +API credentials are held only in memory and are never written to disk or logs. +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from decimal import Decimal, ROUND_DOWN, ROUND_UP + + +class BybitAPIError(RuntimeError): + pass + + +class BybitLiveClient: + def __init__(self, api_key: str, api_secret: str, testnet: bool = True) -> None: + if not api_key.strip() or not api_secret.strip(): + raise ValueError("Введите API key и API secret") + self.api_key = api_key.strip() + self._secret = api_secret.strip().encode("utf-8") + self.testnet = testnet + self.base_url = "https://api-testnet.bybit.com" if testnet else "https://api.bybit.com" + self.recv_window = "5000" + + def _request(self, method: str, path: str, params: dict | None = None) -> dict: + params = params or {} + timestamp = str(int(time.time() * 1000)) + if method == "GET": + query = urllib.parse.urlencode(sorted((key, str(value)) for key, value in params.items())) + body = "" + payload = None + else: + query = "" + body = json.dumps(params, separators=(",", ":"), ensure_ascii=False) + payload = body.encode("utf-8") + signature_input = f"{timestamp}{self.api_key}{self.recv_window}{query or body}" + signature = hmac.new(self._secret, signature_input.encode("utf-8"), hashlib.sha256).hexdigest() + headers = { + "X-BAPI-API-KEY": self.api_key, + "X-BAPI-SIGN": signature, + "X-BAPI-TIMESTAMP": timestamp, + "X-BAPI-RECV-WINDOW": self.recv_window, + "Content-Type": "application/json", + "User-Agent": "RealtimePaperSimulator/1.0", + } + url = f"{self.base_url}{path}" + (f"?{query}" if query else "") + request = urllib.request.Request(url, data=payload, headers=headers, method=method) + try: + with urllib.request.urlopen(request, timeout=10) as response: + result = json.loads(response.read().decode("utf-8")) + except urllib.error.HTTPError as exc: + raw_details = exc.read() + try: + details = json.loads(raw_details.decode("utf-8")) + except Exception: + details = {} + + # Keep the useful Bybit error code and request context, but never + # include request headers, signatures, API keys, or secrets. + ret_code = details.get("retCode") if isinstance(details, dict) else None + ret_msg = details.get("retMsg") if isinstance(details, dict) else None + endpoint = "тестовой сети" if self.testnet else "основной сети" + context = f"{method} {path} ({endpoint})" + if ret_code is not None: + message = f"Bybit API HTTP {exc.code}, retCode {ret_code}: {ret_msg or 'ошибка запроса'}" + hints = { + 10002: "Проверьте синхронизацию часов Windows.", + 10003: "Ключ не подходит к выбранному домену: сверьте Testnet/Mainnet с сетью, где создан API-ключ.", + 10004: "Bybit отклонил подпись. Проверьте API Secret и отсутствие лишних пробелов при вставке.", + 10005: "Проверьте права API-ключа для чтения аккаунта и торговли контрактами.", + 10009: "Bybit ограничил доступ к API для региона аккаунта или подключения.", + 10010: "IP компьютера не совпадает с IP, разрешённым в настройках API-ключа.", + } + if ret_code in hints: + message += f" {hints[ret_code]}" + elif exc.code == 401: + message = ( + f"Bybit вернул HTTP 401 для {context}: запрос авторизации отклонён. " + "Проверьте, что API-ключ создан в выбранной сети (Testnet/Mainnet), " + "ключ и секрет скопированы полностью без пробелов, а IP компьютера " + "разрешён в настройках ключа. Секрет приложения не выводит." + ) + else: + message = f"Bybit API HTTP {exc.code} для {context}" + raise BybitAPIError(message) from None + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc: + raise BybitAPIError(f"Не удалось связаться с Bybit: {exc}") from None + if result.get("retCode") != 0: + raise BybitAPIError(f"Bybit API {result.get('retCode')}: {result.get('retMsg', 'ошибка запроса')}") + return result.get("result", {}) + + def get_wallet(self) -> dict[str, float]: + result = self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"}) + rows = result.get("list", []) + if not rows: + raise BybitAPIError("Bybit не вернул Unified USDT-баланс; проверьте тип аккаунта и права API") + row = rows[0] + available_raw = row.get("totalAvailableBalance") + if available_raw in (None, ""): + equity = float(row.get("totalEquity") or 0) + initial_margin = float(row.get("totalInitialMargin") or 0) + available = max(0.0, equity - initial_margin) + else: + available = float(available_raw) + return { + "wallet": float(row.get("totalWalletBalance") or 0), + "equity": float(row.get("totalEquity") or 0), + "available": available, + "unrealized_pnl": float(row.get("totalPerpUPL") or 0), + } + + def get_instrument(self, symbol: str) -> dict[str, str]: + result = self._request("GET", "/v5/market/instruments-info", {"category": "linear", "symbol": symbol}) + rows = result.get("list", []) + if not rows: + raise BybitAPIError(f"Контракт {symbol} не найден на Bybit linear") + row = rows[0] + lot = row.get("lotSizeFilter", {}) + if row.get("status") != "Trading": + raise BybitAPIError(f"Контракт {symbol} сейчас не торгуется") + return { + "qty_step": lot.get("qtyStep", "0"), + "min_qty": lot.get("minOrderQty", "0"), + "min_notional": lot.get("minNotionalValue", "0"), + "max_market_qty": lot.get("maxMktOrderQty", lot.get("maxMarketOrderQty", "0")), + "tick_size": row.get("priceFilter", {}).get("tickSize", "0"), + } + + def get_taker_fee_pct(self, symbol: str) -> float: + result = self._request("GET", "/v5/account/fee-rate", {"category": "linear", "symbol": symbol}) + rows = result.get("list", []) + if not rows: + raise BybitAPIError(f"Bybit не вернул комиссию для {symbol}") + return float(rows[0]["takerFeeRate"]) * 100 + + def get_positions(self, symbol: str) -> list[dict]: + result = self._request("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}) + return result.get("list", []) + + def get_open_positions(self) -> list[dict]: + """Return all open USDT-settled linear positions for account overview.""" + result = self._request("GET", "/v5/position/list", { + "category": "linear", "settleCoin": "USDT", "limit": 200, + }) + return [row for row in result.get("list", []) if float(row.get("size") or 0) > 0] + + def get_order_history(self, limit: int = 50) -> list[dict]: + """Return recent linear-contract order records (read-only).""" + result = self._request("GET", "/v5/order/history", { + "category": "linear", "settleCoin": "USDT", "limit": max(1, min(int(limit), 50)), + }) + return result.get("list", []) + + def get_closed_pnl_history(self, limit: int = 50) -> list[dict]: + """Return recent realized PnL records for linear contracts.""" + result = self._request("GET", "/v5/position/closed-pnl", { + "category": "linear", "limit": max(1, min(int(limit), 100)), + }) + return result.get("list", []) + + def get_open_position(self, symbol: str) -> dict | None: + for row in self.get_positions(symbol): + if float(row.get("size") or 0) > 0: + return row + return None + + def get_order(self, symbol: str, order_id: str) -> dict | None: + """Read the exchange state of an accepted order for safe reconciliation.""" + params = {"category": "linear", "symbol": symbol, "orderId": order_id} + for path in ("/v5/order/realtime", "/v5/order/history"): + result = self._request("GET", path, params) + rows = result.get("list", []) + if rows: + return rows[0] + return None + + def get_latest_closed_pnl(self, symbol: str, opened_at_ms: int) -> dict | None: + result = self._request("GET", "/v5/position/closed-pnl", { + "category": "linear", "symbol": symbol, "startTime": opened_at_ms, "limit": 50, + }) + rows = result.get("list", []) + return max(rows, key=lambda row: int(row.get("updatedTime", 0))) if rows else None + + def set_leverage(self, symbol: str, leverage: float) -> None: + try: + self._request("POST", "/v5/position/set-leverage", { + "category": "linear", "symbol": symbol, + "buyLeverage": str(leverage), "sellLeverage": str(leverage), + }) + except BybitAPIError as exc: + # Bybit returns 110043 if the requested leverage is already active. + if "110043" not in str(exc): + raise + + @staticmethod + def floor_qty(raw_qty: float, spec: dict[str, str]) -> str: + step = Decimal(spec["qty_step"]) + if step <= 0: + raise BybitAPIError("Bybit вернул некорректный шаг количества") + qty = (Decimal(str(raw_qty)) / step).to_integral_value(rounding=ROUND_DOWN) * step + if qty < Decimal(spec["min_qty"]): + raise BybitAPIError(f"Размер заявки меньше минимального: {spec['min_qty']}") + maximum = Decimal(spec.get("max_market_qty") or "0") + if maximum > 0 and qty > maximum: + raise BybitAPIError(f"Рыночная заявка превышает максимум {maximum}; уменьшите ставку или плечо") + return format(qty, "f") + + @staticmethod + def format_price(raw_price: float, tick_size: str) -> str: + tick = Decimal(tick_size) + if tick <= 0: + return format(Decimal(str(raw_price)), "f") + price = (Decimal(str(raw_price)) / tick).to_integral_value(rounding=ROUND_UP) * tick + return format(price, "f") + + def place_market_buy(self, symbol: str, qty: str, take_profit: float, stop_loss: float, + tick_size: str, order_id: str | None = None) -> str: + body = { + "category": "linear", "symbol": symbol, "side": "Buy", "orderType": "Market", + "qty": qty, "positionIdx": 0, "timeInForce": "IOC", + "tpslMode": "Full", "tpOrderType": "Market", "slOrderType": "Market", + "takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0", + "stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0", + "tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice", + "orderLinkId": order_id or f"rps-{uuid.uuid4().hex[:28]}", + } + result = self._request("POST", "/v5/order/create", body) + return result.get("orderId", "") + + def update_position_stops(self, symbol: str, take_profit: float, stop_loss: float, + tick_size: str) -> None: + try: + self._request("POST", "/v5/position/trading-stop", { + "category": "linear", "symbol": symbol, "tpslMode": "Full", "positionIdx": 0, + "takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0", + "stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0", + "tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice", + "tpOrderType": "Market", "slOrderType": "Market", + }) + except BybitAPIError as exc: + # Bybit's 34040 is an idempotent response: the requested TP/SL is + # already active (or no value changed), so there is nothing to do. + if "34040" not in str(exc): + raise + + def close_long_market(self, symbol: str, qty: str) -> str: + result = self._request("POST", "/v5/order/create", { + "category": "linear", "symbol": symbol, "side": "Sell", "orderType": "Market", + "qty": qty, "positionIdx": 0, "timeInForce": "IOC", "reduceOnly": True, + "closeOnTrigger": True, "orderLinkId": f"rps-close-{uuid.uuid4().hex[:24]}", + }) + return result.get("orderId", "") diff --git a/credential_store.py b/credential_store.py new file mode 100644 index 0000000..e3b7a37 --- /dev/null +++ b/credential_store.py @@ -0,0 +1,119 @@ +"""Store Bybit credentials encrypted for the current Windows user with DPAPI.""" + +from __future__ import annotations + +import base64 +import ctypes +import json +import os +from ctypes import wintypes +from pathlib import Path + + +class CredentialStoreError(RuntimeError): + """Raised when credentials cannot be safely stored or loaded.""" + + +class _DataBlob(ctypes.Structure): + _fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_byte))] + + +def _default_path() -> Path: + local_app_data = os.environ.get("LOCALAPPDATA") + if not local_app_data: + raise CredentialStoreError("Не удалось определить папку профиля Windows для защищённого хранения") + return Path(local_app_data) / "RealtimePaperSimulator" / "bybit_credentials.dpapi" + + +def _protect(data: bytes) -> bytes: + if os.name != "nt": + raise CredentialStoreError("Защищённое хранение ключей доступно только в Windows") + crypt32 = ctypes.WinDLL("crypt32", use_last_error=True) + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + source_buffer = ctypes.create_string_buffer(data) + source = _DataBlob(len(data), ctypes.cast(source_buffer, ctypes.POINTER(ctypes.c_byte))) + encrypted = _DataBlob() + crypt32.CryptProtectData.argtypes = [ + ctypes.POINTER(_DataBlob), wintypes.LPCWSTR, ctypes.POINTER(_DataBlob), + ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob), + ] + crypt32.CryptProtectData.restype = wintypes.BOOL + kernel32.LocalFree.argtypes = [ctypes.c_void_p] + kernel32.LocalFree.restype = ctypes.c_void_p + if not crypt32.CryptProtectData(ctypes.byref(source), "Bybit API credentials", None, None, None, 1, + ctypes.byref(encrypted)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + return ctypes.string_at(encrypted.pbData, encrypted.cbData) + finally: + kernel32.LocalFree(encrypted.pbData) + + +def _unprotect(data: bytes) -> bytes: + if os.name != "nt": + raise CredentialStoreError("Защищённое хранение ключей доступно только в Windows") + crypt32 = ctypes.WinDLL("crypt32", use_last_error=True) + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + source_buffer = ctypes.create_string_buffer(data) + source = _DataBlob(len(data), ctypes.cast(source_buffer, ctypes.POINTER(ctypes.c_byte))) + decrypted = _DataBlob() + crypt32.CryptUnprotectData.argtypes = [ + ctypes.POINTER(_DataBlob), ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(_DataBlob), + ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob), + ] + crypt32.CryptUnprotectData.restype = wintypes.BOOL + kernel32.LocalFree.argtypes = [ctypes.c_void_p] + kernel32.LocalFree.restype = ctypes.c_void_p + if not crypt32.CryptUnprotectData(ctypes.byref(source), None, None, None, None, 1, + ctypes.byref(decrypted)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + return ctypes.string_at(decrypted.pbData, decrypted.cbData) + finally: + kernel32.LocalFree(decrypted.pbData) + + +def save_credentials(api_key: str, api_secret: str, path: Path | None = None) -> None: + api_key, api_secret = api_key.strip(), api_secret.strip() + if not api_key or not api_secret: + raise CredentialStoreError("Введите API key и API secret перед сохранением") + target = path or _default_path() + try: + encrypted = _protect(json.dumps( + {"api_key": api_key, "api_secret": api_secret}, separators=(",", ":") + ).encode("utf-8")) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(base64.b64encode(encrypted).decode("ascii"), encoding="ascii") + except CredentialStoreError: + raise + except (OSError, ValueError, TypeError) as exc: + raise CredentialStoreError(f"Не удалось сохранить API-ключи: {exc}") from None + + +def load_credentials(path: Path | None = None) -> dict[str, str] | None: + target = path or _default_path() + if not target.exists(): + return None + try: + encrypted = base64.b64decode(target.read_text(encoding="ascii"), validate=True) + payload = json.loads(_unprotect(encrypted).decode("utf-8")) + api_key = str(payload["api_key"]) + api_secret = str(payload["api_secret"]) + if not api_key or not api_secret: + raise ValueError("пустые ключи") + return {"api_key": api_key, "api_secret": api_secret} + except CredentialStoreError: + raise + except Exception: + raise CredentialStoreError( + "Не удалось расшифровать сохранённые ключи текущим пользователем Windows. " + "Сохраните ключи заново в окне API Bybit." + ) from None + + +def delete_credentials(path: Path | None = None) -> None: + target = path or _default_path() + try: + target.unlink(missing_ok=True) + except OSError as exc: + raise CredentialStoreError(f"Не удалось удалить сохранённые ключи: {exc}") from None diff --git a/cross.py b/cross.py new file mode 100644 index 0000000..82a1472 --- /dev/null +++ b/cross.py @@ -0,0 +1,1950 @@ +"""The one arbitrage mode (paper or real): buy the coin on spot on exchange A where it is cheap and sell the same coins +where they are dear — close both legs when the gap is back to its usual level. Three kinds of link, each switched on +in the settings: + «sf» spot of A → perpetual of B (A ≠ B): the coins bought on A, the same coins shorted on B's perp; + «in» spot → perpetual inside one exchange (A = B): the classic spot–futures basis; + «ss» spot of A → spot of B: the coins bought on A, the same coins sold on B from a stock the user keeps there + (spot cannot be shorted); the close sells A and buys the stock back on B. + +Between two exchanges nothing ties the perp of B to the spot of A (within one exchange the funding/index does), so +the gap may stay wide for a long time: an offset between the exchanges, a coin whose deposits are closed on A, or a +different token under the same ticker. That is why the entry is not «gap above X» but «gap above its USUAL level by +X»: the usual gap of every (coin, spot exchange, perp exchange) is followed over the last ~30 minutes, and the +position is closed when the gap returns to the usual level it had at the entry. + + entry gap = perp bid (B) / spot ask (A) − 1 + exit gap = perp ask (B) / spot bid (A) − 1 + usual = average of the mid gap over the last USUAL_WINDOW_S seconds (EMA), per coin|A|B + +Result of a trade = spot leg (A) + perp leg (B) − the four taker fees of the two exchanges + funding on B. + +Real mode: the short is opened first on B (a limit order at the signal's bid, or at market), then the same coins are +bought on spot on A; the close buys the short back on B, checks that B shows no short left, then sells the coins on +A. One entry at a time, the next only after the previous is confirmed. The fee rates of every exchange are settings; +after each real trade they are replaced by what the exchanges actually charged, so the table counts with them. +""" + +from __future__ import annotations + +import json +import queue +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from dataclasses import asdict, dataclass, field, fields +from pathlib import Path + +import arb +import minorder + +ROOT = Path(__file__).resolve().parent +DATA_DIR = ROOT / "web_sim_data" +POLL_S = 3.0 +USUAL_WINDOW_S = 1800.0 +KEEP_TRADES = 500 +SPOT_FEE = dict(arb.SPOT_TAKER) +FUT_FEE = {"Bybit": 0.055, "Binance": 0.05, "MEXC": 0.02, "HTX": 0.05, "Gate": 0.05} +# perps of an exchange's own fee group with a higher rate: Bybit's Innovation Zone (bybit.com/fee, regular user) +FUT_FEE_INNOVATION = {"Bybit": 0.11} +INNOVATION_S = 3600.0 +MAX_LEARNED_FEE = 1.0 # a «rate» above this from a fill is a misread, not a fee +# Liquidation of the short on B: nothing on B hedges it (the coins are on A), so B's futures money alone carries +# its loss when the coin rises. Cross margin, one short of N $ at P0 with E $ of futures money behind it: +# liquidation when E − N·x = mmr·N·(1 + x) → x = (E/N − mmr) / (1 + mmr) (x = price rise to liquidation) +DEFAULT_LIMIT = 3 # open trades per exchange (a trade counts on its spot exchange and its perp one) +LIQ_MMR_PCT = 1.0 # maintenance margin rate assumed, % (small coins' tiers: 0.5–1 %, safe side) +LIQ_CHECK_S = 30.0 # the exchange's own liquidation price of an open short is read this often + + +def liq_distance(equity: float, notional: float, mmr_pct: float = LIQ_MMR_PCT) -> float: + """Price rise, %, at which a short of `notional` $ backed by `equity` $ of futures money is liquidated.""" + if notional <= 0: + return float("inf") + mmr = mmr_pct / 100 + return (equity / notional - mmr) / (1 + mmr) * 100 + + +def equity_for(distance_pct: float, notional: float, mmr_pct: float = LIQ_MMR_PCT) -> float: + """Futures money, $, a short of `notional` $ needs to be liquidated only `distance_pct` % above the entry.""" + mmr = mmr_pct / 100 + return notional * ((1 + mmr) * distance_pct / 100 + mmr) + + +def bybit_innovation_symbols() -> set[str]: + """Bybit USDT perps of the Innovation Zone (symbolType «innovation»).""" + out, cursor = set(), "" + while True: + res = arb._get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000" + + (f"&cursor={cursor}" if cursor else ""))["result"] + out |= {x["symbol"] for x in res["list"] if x.get("symbolType") == "innovation"} + cursor = res.get("nextPageCursor") or "" + if not cursor or not res["list"]: + return out + + +def fut_fee(exchange: str, fees: dict | None = None, innovation: bool = False) -> float: + """The perp taker rate: the engine's table if given, else measured from the user's real fills where known + (MEXC charges them 0.08 %), else the exchange's base rate. `innovation`: the coin is in the exchange's + Innovation Zone, which has its own rate (Bybit 0.11 %).""" + if innovation: + if fees and "fut_innovation" in fees.get(exchange, {}): + return fees[exchange]["fut_innovation"] + if exchange in FUT_FEE_INNOVATION: + return FUT_FEE_INNOVATION[exchange] + if fees and exchange in fees: + return fees[exchange]["fut"] + try: + import real_mirror + return real_mirror.FEES.get(exchange.lower()) or FUT_FEE.get(exchange, 0.05) + except Exception: + return FUT_FEE.get(exchange, 0.05) + + +def spot_fee(exchange: str, fees: dict | None = None) -> float: + if fees and exchange in fees: + return fees[exchange]["spot"] + return SPOT_FEE.get(exchange, 0.1) + + +def b_fee(exchange: str, fees: dict | None = None, innovation: bool = False, ss: bool = False) -> float: + """Taker rate of the second leg: B's spot for a spot–spot link, B's perp otherwise.""" + return spot_fee(exchange, fees) if ss else fut_fee(exchange, fees, innovation) + + +def link_key(base: str, a: str, b: str, ss: bool = False) -> str: + return f"{base}|{a}|{b}" + ("|ss" if ss else "") + + +KIND_NAMES = {"sf": "спот → фьюч", "in": "внутри биржи", "ss": "спот → спот"} + + +def kind_of(a: str, b: str, ss: bool) -> str: + return "ss" if ss else "in" if a == b else "sf" + + +def default_fees() -> dict: + try: + import real_mirror + measured = set(real_mirror.FEES) + except Exception: + measured = set() + out = {ex: {"spot": spot_fee(ex), "fut": fut_fee(ex), "spot_src": "", + "fut_src": "по реальным сделкам" if ex.lower() in measured else ""} for ex in arb.EXCHANGES} + for ex, rate in FUT_FEE_INNOVATION.items(): + out[ex].update(fut_innovation=rate, fut_innovation_src="") + return out + + +FEE_LEGS = ("spot", "fut", "fut_innovation") + + +@dataclass +class CrossSettings: + running: bool = False + amount: float = 100.0 # $ spent on spot (A); the same coins shorted on the perp (B) + # THE entry criterion: net profit % if the gap returns to its usual level = + # (gap now − usual) − exit margin − the four taker fees of the two exchanges + min_net_pct: float = 0.2 + max_gap_pct: float = 10.0 # above: a broken price or a different token + history_min: float = 15.0 # minutes of watching the pair before its «usual» is trusted + exit_over_usual_pct: float = 0.05 # close when the gap is back to (usual at the entry + this) + stop_widen_pct: float = 2.0 # close at a loss when the gap widens this much over the entry (0 = off) + max_hold_hours: float = 24.0 # close after this long whatever the gap (0 = off) + cooldown_s: float = 300.0 + min_turnover: float = 200000.0 # 24h turnover of each leg, $ + use_bybit: bool = True # an exchange switched off is neither searched nor traded + use_binance: bool = True + use_mexc: bool = True + use_htx: bool = True + use_gate: bool = True + search_sf: bool = True # spot of A → perp of B between exchanges + search_in: bool = True # spot → perp inside one exchange + search_ss: bool = True # spot of A → spot of B (real: needs the coin's stock on B) + real: bool = False # new trades as real orders with the API keys of both exchanges + auto_transfer: bool = True # USDT moved between spot and futures WITHIN an exchange when one is short + entry_limit: bool = True # real entry: LIMIT short at the signal's perp bid on B first, then spot on A + limit_hold_s: float = 10.0 # …kept this long, then removed (nothing bought if it did not fill) + fees_auto: bool = True # after a real trade the fee rates become what the exchanges charged + exit_hold_s: float = 3.0 # «back to usual» closes only after the gap has stayed there this long (0 = at once) + max_spread_pct: float = 0.5 # a leg whose bid–ask spread is wider is not traded (0 = no check) + entry_ioc: bool = True # real: the first leg is a limit order at the confirmed price, the rest cancelled + confirm_ms: float = 400.0 # real: the signal is checked twice on the order books, this far apart + min_liq_pct: float = 50.0 # no short whose liquidation would be less than this % above the entry + liq_close_pct: float = 20.0 # close both legs when the price is this close to the liquidation, % (0 = off) + + +@dataclass +class CrossPosition: + uid: int + base: str + spot_ex: str + fut_ex: str + spot_symbol: str + fut_symbol: str + opened: float + qty: float # coins shorted on B (real: rounded to B's lot) + spot_entry: float + fut_entry: float + entry_gap: float + usual: float # the usual gap at the entry: the level the position waits for + fees: float + next_funding: float + funding: float = 0.0 + # real positions: the coins held on A, the close in progress (short bought back first, then the spot sold) + real: bool = False + spot_qty: float = 0.0 + closing: str = "" # "" / "fut_done" + fut_exit: float = 0.0 + exit_fees: float = 0.0 + retry_at: float = 0.0 + error: str = "" + sold_coins: float = 0.0 + sold_value: float = 0.0 + sold_fees: float = 0.0 + exact: bool = True + fills: list = field(default_factory=list) # [exchange, fee leg, fee $, value $, exact] of every order + innovation: bool = False # the perp is in B's Innovation Zone: its own fee rate + liq_price: float = 0.0 # liquidation price of the short on B, per coin (the exchange's when it reports one) + liq_calc: float = 0.0 # the program's own estimate at the entry + liq_src: str = "" # "биржа" / "расчёт" + liq_checked: float = 0.0 # when the exchange's figure was last read + ss: bool = False # spot–spot: the B leg is a sale of the stock on B's spot (fut_* = B's spot) + # the prices the decisions were taken at: [time, A price, B price, gap %] — to compare with the fills + entry_signal: list = field(default_factory=list) # A ask, B bid confirmed right before the entry orders + exit_signal: list = field(default_factory=list) # A bid, B ask when the close was decided + exit_since: float = 0.0 # when the gap last came back to the usual level (0 = it is not there now) + + @property + def kind(self) -> str: + return kind_of(self.spot_ex, self.fut_ex, self.ss) + + @property + def key(self) -> str: + return link_key(self.base, self.spot_ex, self.fut_ex, self.ss) + + +@dataclass +class CrossTrade: + uid: int + base: str + spot_ex: str + fut_ex: str + opened: float + closed: float + qty: float + spot_entry: float + spot_exit: float + fut_entry: float + fut_exit: float + entry_gap: float + exit_gap: float + usual: float + spot_pnl: float + fut_pnl: float + fees: float + funding: float + net: float + reason: str + amount: float + real: bool = False + exact: bool = True + kind: str = "sf" + entry_signal: list = field(default_factory=list) # [time, A ask, B bid, gap %] of the entry decision + exit_signal: list = field(default_factory=list) # [time, A bid, B ask, gap %] of the close decision + + +@dataclass +class Link: + """One coin, spot on A, perp on B (or B's spot for a spot–spot link), at this moment (prices per coin).""" + base: str + spot_ex: str + fut_ex: str + spot_symbol: str + fut_symbol: str + spot_bid: float + spot_ask: float + fut_bid: float + fut_ask: float + spot_depth: float | None # $ at the spot ask + fut_depth: float | None # $ at the perp bid + spot_turnover: float + fut_turnover: float + funding: float # per interval, fraction + interval_h: float + fut_mult: float = 1.0 # coins in one unit of the perp symbol (1000PEPE → 1000) + innovation: bool = False # the perp is in B's Innovation Zone (Bybit): a higher fee rate + ss: bool = False # spot–spot: fut_* are B's SPOT prices / symbol + + @property + def fut_leg(self) -> str: + """Which fee rate of B applies: B's spot (spot–spot), "fut_innovation" for an Innovation Zone coin, else + "fut".""" + return "spot" if self.ss else "fut_innovation" if self.innovation else "fut" + + @property + def kind(self) -> str: + return kind_of(self.spot_ex, self.fut_ex, self.ss) + + @property + def key(self) -> str: + return link_key(self.base, self.spot_ex, self.fut_ex, self.ss) + + @property + def entry_gap(self) -> float: + return (self.fut_bid / self.spot_ask - 1) * 100 + + @property + def exit_gap(self) -> float: + return (self.fut_ask / self.spot_bid - 1) * 100 + + @property + def mid_gap(self) -> float: + return ((self.fut_bid + self.fut_ask) / (self.spot_bid + self.spot_ask) - 1) * 100 + + +def build_links(spots: list, futs: list, exchanges: set[str], + innovation: set[str] | frozenset = frozenset(), kinds=("sf", "in", "ss")) -> dict[str, Link]: + """Every link of the five exchanges' quotes: spot on A with a perp on B (A ≠ B: «sf», A = B: «in») and spot on + A with spot on B (A ≠ B: «ss»). `innovation`: "exchange|perp symbol" of the Innovation Zone perps.""" + by_base_spot: dict[str, list] = {} + for q in spots: + # a ticker in other letters (龙虾…) cannot be put into the exchanges' signed requests: not traded + if q.exchange in exchanges and q.mult == 1 and q.base.isascii() and \ + not (arb.LEVERAGED.search(q.base) and len(q.base) > 3): + by_base_spot.setdefault(q.base, []).append(q) + by_base_fut: dict[str, list] = {} + for q in futs: + if q.exchange in exchanges: + by_base_fut.setdefault(q.base, []).append(q) + out = {} + for base, ss in by_base_spot.items(): + for s in ss: + if min(s.bid, s.ask) <= 0: + continue + for f in by_base_fut.get(base, []): + kind = "in" if s.exchange == f.exchange else "sf" + if kind not in kinds or min(f.bid, f.ask) <= 0: + continue + link = Link(base, s.exchange, f.exchange, s.symbol, f.symbol, s.bid, s.ask, f.bid, f.ask, s.ask_usd, + f.bid_usd, s.volume_usd or 0.0, f.volume_usd or 0.0, f.funding or 0.0, f.interval_h or 8.0, + f.mult or 1.0, f"{f.exchange}|{f.symbol}" in innovation) + out[link.key] = link + if "ss" not in kinds: + continue + for b in ss: # sold on B's spot from the stock kept there + if b.exchange == s.exchange or min(b.bid, b.ask) <= 0: + continue + link = Link(base, s.exchange, b.exchange, s.symbol, b.symbol, s.bid, s.ask, b.bid, b.ask, s.ask_usd, + b.bid_usd, s.volume_usd or 0.0, b.volume_usd or 0.0, 0.0, 8.0, 1.0, False, ss=True) + out[link.key] = link + return out + + +def close_result(pos: CrossPosition, spot_bid: float, fut_ask: float, + fees_table: dict | None = None) -> tuple[float, float, float, float]: + """(spot leg $, perp leg $, all fees $, net $) of closing at these prices.""" + spot_qty = pos.spot_qty or pos.qty # real: the spot leg can hold a little more than the perp's lot + if pos.closing == "fut_done": # real close half done: the short is already bought back + fut_ask = pos.fut_exit + spot_pnl = spot_qty * (spot_bid - pos.spot_entry) + fut_pnl = pos.qty * (pos.fut_entry - fut_ask) + fees = pos.fees + spot_qty * spot_bid * spot_fee(pos.spot_ex, fees_table) / 100 \ + + pos.qty * fut_ask * b_fee(pos.fut_ex, fees_table, pos.innovation, pos.ss) / 100 + return spot_pnl, fut_pnl, fees, spot_pnl + fut_pnl - fees + pos.funding + + +def round_trip_fee_pct(spot_ex: str, fut_ex: str, fees: dict | None = None, innovation: bool = False, + ss: bool = False) -> float: + return 2 * (spot_fee(spot_ex, fees) + b_fee(fut_ex, fees, innovation, ss)) + + +def net_pct(l: "Link", usual: float | None, s: "CrossSettings", fees: dict | None = None) -> float | None: + """Net profit, % of the amount, if the gap returns to its usual level: (entry gap − usual) − exit margin − + the four taker fees (spot of A in and out, perp of B in and out). None while the usual gap is unknown.""" + if usual is None: + return None + return l.entry_gap - usual - s.exit_over_usual_pct - round_trip_fee_pct(l.spot_ex, l.fut_ex, fees, l.innovation, + l.ss) + + +def _client(exchange: str): + import live + return live.client(exchange.lower()) + + +class ThinBook(Exception): + """The order book holds less than the trade amount at the moment.""" + + +def _quote_now(l: "Link", usd: float) -> tuple[float, float, float, float, float, float]: + """This link from the ORDER BOOKS right now, for a trade of `usd` $, per coin: (A best bid, A average buy price for + the amount, B average sale price for the amount, B best ask, A spread %, B spread %).""" + import fastquote + a = fastquote.execution(l.spot_ex, "spot", l.spot_symbol, usd) + b = fastquote.execution(l.fut_ex, "spot" if l.ss else "fut", l.fut_symbol, usd) + if a["ask"] is None: + raise ThinBook(f"на споте {l.spot_ex} в стакане меньше {usd:g} $") + if b["bid"] is None: + raise ThinBook(f"на {'споте' if l.ss else 'фьючерсе'} {l.fut_ex} в стакане меньше {usd:g} $") + return (a["best_bid"], a["ask"], b["bid"] / l.fut_mult, b["best_ask"] / l.fut_mult, a["spread_pct"], + b["spread_pct"]) + + +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: + self.is_real = real + self.key = "cross_real" if real else "cross" + self.file = data_dir / ("basis_cross_real.json" if real else "basis_cross.json") + self.followers: list[CrossEngine] = [] + self.leader: CrossEngine | None = None + self.lock = threading.RLock() + self.settings = CrossSettings() + self.positions: list[CrossPosition] = [] + self.trades: list[CrossTrade] = [] + self.next_uid = 1 + self.last_close: dict[str, float] = {} + self.links: dict[str, Link] = {} + self.usual: dict[str, float] = {} # key → EMA of the mid gap + self.seen_since: dict[str, float] = {} # key → when the pair was first seen (for the history check) + self.last_seen: dict[str, float] = {} + self.status, self.updated, self.cycle_ms = "загружаю цены пяти бирж…", 0.0, 0 + self.ex_status: dict[str, str] = {} + self.fut, self.spot = arb.Fetchers(), arb.SpotFetchers() + self.usual_file = data_dir / "basis_cross_usual.json" + self.usual_saved = 0.0 + self.fast_seen: dict[str, float] = {} # link → when the fast watch last priced it + self.fast_ms = 0 + # fee rates of every exchange, %: {"MEXC": {"spot": .., "fut": .., "spot_src": "", "fut_src": ""}} + self.fees: dict[str, dict] = default_fees() + self.limits: dict[str, int] = {ex: DEFAULT_LIMIT for ex in arb.EXCHANGES} # open trades per exchange + self.innovation: set[str] = set() # "Bybit|SYMBOL" of the Innovation Zone perps + self.innovation_time = 0.0 + # real trading + self.client_for = _client + self.quote_now = _quote_now if start else None # fresh prices right before a real entry (tests: none) + self.balances: dict = {} # web_sim's BALANCES (exchange key → account figures) + self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"} + self.opening: set[str] = set() # coins with a real entry in progress + self.jobs: queue.Queue = queue.Queue() + self.busy: set[int] = set() # real positions whose close is being sent right now + self.real_block: dict[str, tuple[str, float]] = {} # coin → (why it cannot be traded for real, until) + self.real_pause_until, self.real_pause_reason = 0.0, "" + self.pending: dict[str, dict] = {} # coin → real entry in progress (written BEFORE any order) + self.recover: dict[str, dict] = {} # pending entries found after a restart + self.funds_low: dict[str, str] = {} # exchange → why it is out of the search (too little money) + self.migrated: list[str] = [] # single-exchange tabs whose positions were taken over + self.cand: dict[str, dict] = {} # key → its row from the last cycle (+ hot refreshes) + self.cand_time = 0.0 + self.hot: list[str] = [] # links with a net profit > 0, priced every HOT_S + if real and not self.file.exists(): + self._seed_from(data_dir / "basis_cross.json") # the first real engine starts from the paper settings + self._load() + self.settings.real = real # fixed by the tab, not a setting + self._migrate_venues(data_dir) + if leader is None: + self._load_usual() + else: # the same learnt gaps, the same price list + self.leader = leader + self.usual, self.seen_since, self.last_seen = leader.usual, leader.seen_since, leader.last_seen + self.innovation = leader.innovation + leader.followers.append(self) + if start: + if leader is None: + threading.Thread(target=self._loop, daemon=True).start() + threading.Thread(target=self._hot_loop, daemon=True).start() + threading.Thread(target=self._fast_loop, daemon=True).start() + threading.Thread(target=self._worker, daemon=True).start() + import basis + basis.ENGINES.append(self) + + # --- persistence ----------------------------------------------------------------------------------------- + def _load(self) -> None: + try: + d = json.loads(self.file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + 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)) + import basis + self.settings.max_gap_pct = min(self.settings.max_gap_pct, basis.HARD_MAX_GAP_PCT) + for ex, f in (d.get("fees") or {}).items(): + if ex in self.fees: + self.fees[ex].update({k: f[k] for leg in FEE_LEGS for k in (leg, f"{leg}_src") + if k in f and leg in self.fees[ex]}) + # open trades per exchange; before, one limit for all: it becomes the limit of every exchange + old = (d.get("settings") or {}).get("max_positions") + for ex in self.limits: + v = (d.get("limits") or {}).get(ex, old) + if v is not None: + self.limits[ex] = int(v) + self.positions = [CrossPosition(**p) for p in d.get("positions", [])] + 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 []) + + def _seed_from(self, paper_file: Path) -> None: + """The real engine's first settings, fee table and limits: those of the simulation (stopped).""" + try: + d = json.loads(paper_file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + settings = {**(d.get("settings") or {}), "running": False, "real": True} + self.file.parent.mkdir(exist_ok=True) + self.file.write_text(json.dumps({"settings": settings, "fees": d.get("fees") or {}, + "limits": d.get("limits") or {}, "next_uid": d.get("next_uid", 1), + "migrated": []}, ensure_ascii=False, indent=1), encoding="utf-8") + + def elsewhere(self, base: str) -> str: + """Another engine of the same kind (paper / real) already trading this coin — "" if none. Paper and real + are independent of each other.""" + import basis + for e in list(basis.ENGINES): + if e is not self and getattr(e, "is_real", None) == self.is_real and \ + (any(p.base == base for p in list(e.positions)) or base in getattr(e, "opening", set())): + return "другой движок" + return "" + + VENUE_FILES = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC", "htx": "HTX", "gate": "Gate"} + + def _migrate_venues(self, data_dir: Path) -> None: + """The spot–futures tabs of single exchanges are now the «inside one exchange» links of this mode: their + open positions (real ones included — the program keeps closing them) and their closed trades move here, and + the old file is renamed so it is never read again.""" + moved, done = [], False + for key, ex in self.VENUE_FILES.items(): + f = data_dir / f"basis_{key}.json" + if key in self.migrated: + continue + try: + d = json.loads(f.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + done = True + self.migrated.append(key) + old_exit = float((d.get("settings") or {}).get("exit_gap_pct", 0.05)) + for p in d.get("positions", []): + if bool(p.get("real", False)) != self.is_real: # paper ones to the simulation, real ones here + continue + # the old rule closed at «gap ≤ exit_gap_pct»: the same level here (usual + exit margin) + pos = CrossPosition( + self.next_uid, p["base"], ex, ex, "", p.get("fut_symbol", ""), p["opened"], p["qty"], + p["spot_entry"], p["fut_entry"], p["entry_gap"], old_exit - self.settings.exit_over_usual_pct, + p.get("fees", 0.0), p.get("next_funding", 0.0), p.get("funding", 0.0), real=p.get("real", False), + spot_qty=p.get("spot_qty", 0.0), closing=p.get("closing", ""), fut_exit=p.get("fut_exit", 0.0), + exit_fees=p.get("exit_fees", 0.0), retry_at=p.get("retry_at", 0.0), error=p.get("error", ""), + sold_coins=p.get("sold_coins", 0.0), sold_value=p.get("sold_value", 0.0), + sold_fees=p.get("sold_fees", 0.0), exact=p.get("exact", True), + innovation=p.get("innovation", False)) + self.next_uid += 1 + self.positions.append(pos) + moved.append(f"{p['base']} ({ex}{', реальная' if pos.real else ''})") + for t in d.get("trades", []): + if bool(t.get("real", False)) != self.is_real: + continue + self.trades.append(CrossTrade( + self.next_uid, t["base"], ex, ex, t["opened"], t["closed"], t["qty"], t["spot_entry"], + t["spot_exit"], t["fut_entry"], t["fut_exit"], t["entry_gap"], t["exit_gap"], 0.0, t["spot_pnl"], + t["fut_pnl"], t["fees"], t["funding"], t["net"], t["reason"], t.get("amount", 0.0), + real=t.get("real", False), exact=t.get("exact", True), kind="in")) + self.next_uid += 1 + self.trades.sort(key=lambda t: t.closed) + if d.get("pending") and self.is_real: + self._journal("—", "open", False, f"{ex}: незавершённый вход из старой вкладки ({', '.join(d['pending'])})" + f" не перенесён — проверьте баланс монет на {ex}") + if done: + self.save() + if moved: + self._journal("—", "open", True, "позиции вкладок «Спот-фьюч» отдельных бирж перенесены в «Арбитраж · " + f"{'реальная торговля' if self.is_real else 'симуляция'}» (внутри биржи): " + ", ".join(moved)) + + def _load_usual(self) -> None: + """The usual gaps learnt before a restart, if they are recent (otherwise 15 min of watching again).""" + try: + d = json.loads(self.usual_file.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + if time.time() - d.get("time", 0) > 600: + return + self.usual, self.seen_since, self.last_seen = d.get("usual", {}), d.get("since", {}), d.get("seen", {}) + + def _save_usual(self, now: float) -> None: + if now - self.usual_saved < 60: + return + self.usual_saved = now + try: + self.usual_file.parent.mkdir(exist_ok=True) + tmp = self.usual_file.with_suffix(".tmp") + tmp.write_text(json.dumps({"time": now, "usual": self.usual, "since": self.seen_since, + "seen": self.last_seen}), encoding="utf-8") + tmp.replace(self.usual_file) + except OSError: + pass + + def save(self) -> None: + self.file.parent.mkdir(exist_ok=True) + data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions], + "trades": [asdict(t) for t in self.trades[-KEEP_TRADES:]], "next_uid": self.next_uid, + "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) + + def set_settings(self, values: dict) -> str: + with self.lock: + was = (self.settings.running, self.settings.real) + for f in fields(CrossSettings): + if f.name not in values: + continue + try: + v = values[f.name] + v = (v in (True, "true", "1", 1, "on")) if f.type in ("bool", bool) \ + else type(getattr(self.settings, f.name))(float(v)) + except (TypeError, ValueError): + return f"неверное значение: {f.name}" + setattr(self.settings, f.name, v) + self.settings.real = self.is_real # which tab it is, not a setting + if "fees" in values: + problem = self._set_fees(values["fees"]) + if problem: + return problem + if "limits" in values: + problem = self._set_limits(values["limits"]) + if problem: + return problem + s = self.settings + if s.amount <= 0: + return "сумма должна быть больше 0" + if s.running and s.real and (not was[0] or not was[1]): + self.baseline = {"time": time.time(), "total": None, "by_ex": {}} # «since the start» from here + if set(values) - {"running"}: + self.real_block.clear() # new settings: coins and exchanges are checked anew + self.real_pause_until, self.real_pause_reason = 0.0, "" + import basis + if s.max_gap_pct > basis.HARD_MAX_GAP_PCT: + s.max_gap_pct = basis.HARD_MAX_GAP_PCT + self.save() + return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под " + f"одним тикером). Установлено {basis.HARD_MAX_GAP_PCT:g}%, остальное сохранено") + self.save() + return "" + + def _set_fees(self, given) -> str: + """Fee rates typed on the page: {"MEXC": {"spot": "0.05", "fut": "0.02"}, …}.""" + if not isinstance(given, dict): + return "неверные комиссии" + new = {} + for ex, legs in given.items(): + if ex not in self.fees or not isinstance(legs, dict): + continue + for leg in FEE_LEGS: + if leg not in legs or leg not in self.fees[ex]: + continue + try: + v = float(legs[leg]) + except (TypeError, ValueError): + return f"неверная комиссия: {ex} {leg}" + if not 0 <= v <= MAX_LEARNED_FEE: + return f"комиссия {ex} должна быть от 0 до {MAX_LEARNED_FEE:g}%" + new[(ex, leg)] = v + for (ex, leg), v in new.items(): + if abs(self.fees[ex][leg] - v) > 1e-9: + self.fees[ex][leg], self.fees[ex][f"{leg}_src"] = v, "вручную" + return "" + + def exchanges(self) -> set[str]: + s = self.settings + return {name for name, on in (("Bybit", s.use_bybit), ("Binance", s.use_binance), ("MEXC", s.use_mexc), + ("HTX", s.use_htx), ("Gate", s.use_gate)) if on} + + def has_keys(self, exchange: str) -> bool: + """The exchange has API keys (the balance reader keeps an entry for exactly those exchanges).""" + return exchange.lower() in self.balances + + # --- open trades per exchange: a trade counts on both of its exchanges (spot on A, short on B) --------------- + def limit(self, exchange: str) -> int: + return int(self.limits.get(exchange, DEFAULT_LIMIT)) + + def open_on(self, exchange: str) -> list[str]: + """Coins of the open trades of this mode (real ones in real mode, paper ones otherwise) that use the + exchange, plus a real entry in progress there.""" + real = self.settings.real + out = [p.base for p in self.positions if p.real == real and exchange in (p.spot_ex, p.fut_ex)] + out += [b for b, info in self.pending.items() if exchange in str(info.get("key", "")).split("|")[1:]] + return out + + def full(self, l: Link) -> str: + """Why a new trade on this link must wait (one of its exchanges has its limit of open trades), "" if not.""" + for ex in (l.spot_ex, l.fut_ex): + held = self.open_on(ex) + if len(held) >= self.limit(ex): + return f"на {ex} открыто сделок {len(held)} из {self.limit(ex)} ({', '.join(held) or '—'}) — ждёт закрытия" + return "" + + def _set_limits(self, given) -> str: + if not isinstance(given, dict): + return "неверные лимиты" + new = {} + for ex, v in given.items(): + if ex not in self.limits: + continue + try: + n = int(float(v)) + except (TypeError, ValueError): + return f"неверный лимит сделок: {ex}" + if not 0 <= n <= 100: + return f"лимит сделок {ex} должен быть от 0 до 100" + new[ex] = n + self.limits.update(new) + return "" + + SPOT_NEED, FUT_NEED = 1.01, 1.03 # × the amount: the spot buy (+ fee) / the short's margin (leverage 1) + + def funds(self, exchange: str) -> dict | None: + """Can the exchange take a leg of a real trade of «Сумма» now? {"spot": bool (buy the coin, role A), + "fut": bool (short, role B), "free": $, "need": $}; None while its free USDT is not known. + With the auto-transfer (or one unified account) both accounts of the exchange count for either leg.""" + b = self.balances.get(exchange.lower()) + f = (b or {}).get("free") + if not isinstance(f, dict): + return None + s = self.settings + spot, fut = float(f.get("spot") or 0), float(f.get("futures") or 0) + unified = bool(b.get("unified")) + total = spot if unified else spot + fut + pool = unified or s.auto_transfer + need_spot, need_fut = s.amount * self.SPOT_NEED, s.amount * self.FUT_NEED + return {"spot": (total if pool else spot) >= need_spot, "fut": (total if pool else fut) >= need_fut, + "free": total, "free_spot": spot, "free_fut": fut, "need": min(need_spot, need_fut), + "need_spot": need_spot, "need_fut": need_fut, "pool": pool} + + def stock(self, exchange: str, base: str) -> float | None: + """Free coins of `base` on the exchange's spot account (from the balance reader), None when not known.""" + coins = (self.balances.get(exchange.lower()) or {}).get("coins") + return float(coins.get(base, 0.0)) if isinstance(coins, dict) else None + + def _short_of_money(self, l: Link, funds: dict) -> list[str]: + """What a real trade on this link lacks: USDT for the spot buy on A, money for the short on B (or both on + one exchange), or the coin's stock on B for a spot–spot sale.""" + s = self.settings + fa, fb = funds.get(l.spot_ex), funds.get(l.fut_ex) + out = [] + if l.kind == "in": # both legs on one exchange: both needs at once + if fa is not None: + both = fa["need_spot"] + fa["need_fut"] + if (fa["free"] < both) if fa["pool"] else not (fa["spot"] and fa["fut"]): + out.append(f"средств на {l.spot_ex} (обе ноги: нужно {both:.2f} $)") + return out + if fa is not None and not fa["spot"]: + out.append(f"средств на споте {l.spot_ex}") + if l.ss: + have = self.stock(l.fut_ex, l.base) + need = s.amount / l.spot_ask + if have is not None and have < need: + out.append(f"запаса {l.base} на {l.fut_ex} (есть {have:g}, нужно {need:.6g})") + elif fb is not None and not fb["fut"]: + out.append(f"средств на фьючерсах {l.fut_ex}") + return out + + def low_funds(self, exchange: str) -> str: + """Why the exchange is out of the search for now (it cannot take either leg), "" when it can.""" + f = self.funds(exchange) if self.settings.real else None + if f is None or f["spot"] or f["fut"]: + return "" + if f["pool"]: + return f"мало средств: свободно {f['free']:.2f} $, нужно от {f['need']:.2f} $" + return (f"мало средств: спот {f['free_spot']:.2f} $ (нужно {f['need_spot']:.2f}), фьючерсы " + f"{f['free_fut']:.2f} $ (нужно {f['need_fut']:.2f})") + + def _watch_funds(self) -> None: + """Journal when an exchange drops out for lack of money and when it is back (money arrived).""" + for ex in arb.EXCHANGES: + low = self.low_funds(ex) + if bool(low) != bool(self.funds_low.get(ex)): + self._journal("—", "funds", not low, f"{ex}: {low} — выключена из поиска и сделок до пополнения" + if low else f"{ex}: средств достаточно — снова в поиске и сделках") + if low: + self.funds_low[ex] = low + else: + self.funds_low.pop(ex, None) + + # --- data ------------------------------------------------------------------------------------------------ + def _fetch(self) -> tuple[list, list]: + for refresh in (self.fut.refresh_reference, self.spot.refresh_volume): + try: + refresh() + except Exception: + pass + jobs = {} + status = {} + with ThreadPoolExecutor(max_workers=10) as pool: + for ex in arb.EXCHANGES: + jobs[pool.submit(getattr(self.spot, ex.lower()))] = (ex, "спот") + jobs[pool.submit(getattr(self.fut, ex.lower()))] = (ex, "фьюч") + spots, futs = [], [] + for job, (ex, kind) in jobs.items(): + try: + (spots if kind == "спот" else futs).extend(job.result()) + except Exception as exc: + status[f"{ex} {kind}"] = f"нет данных: {str(exc)[:60]}" + self.ex_status = status + return spots, futs + + def _loop(self) -> None: + while True: + start = time.time() + try: + spots, futs = self._fetch() + if time.time() - self.innovation_time > INNOVATION_S: + try: # which Bybit perps pay the Innovation Zone rate + self.innovation = {f"Bybit|{s}" for s in bybit_innovation_symbols()} + self.innovation_time = time.time() + except Exception: + self.innovation_time = time.time() - INNOVATION_S + 300 # again in 5 min + links = build_links(spots, futs, set(arb.EXCHANGES), self.innovation) + with self.lock: + fresh_now = time.time() + for k, seen in self.fast_seen.items(): # the fast watch's prices are newer than this list + if k in links and k in self.links and fresh_now - seen < 2.0: + links[k] = self.links[k] + self.links = links + self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000) + self.status = "ok" + self.learn(self.updated) + self.step(self.updated) + self._save_usual(self.updated) + for e in self.followers: # the real engine: the same prices, its own trades + e.take_prices(links, self) + except Exception as exc: + self.status = f"нет данных: {exc}" + for e in self.followers: + e.status = self.status + time.sleep(max(0.5, POLL_S - (time.time() - start))) + + def take_prices(self, links: dict, leader: "CrossEngine") -> None: + """A follower's cycle: the leader's fresh price list (its own fast prices kept where newer), then its own + exits and entries.""" + with self.lock: + fresh = dict(links) + now = time.time() + for k, seen in self.fast_seen.items(): + if k in fresh and k in self.links and now - seen < 2.0: + fresh[k] = self.links[k] + self.links = fresh + self.innovation = leader.innovation + self.ex_status, self.updated, self.cycle_ms = leader.ex_status, leader.updated, leader.cycle_ms + self.status = "ok" + self.step(self.updated) + + def learn(self, now: float) -> None: + """The usual gap of every pair: an EMA over ~USUAL_WINDOW_S of the mid gap, updated each cycle.""" + alpha_base = POLL_S / USUAL_WINDOW_S + for key, link in self.links.items(): + gap = link.mid_gap + if abs(gap) > 50: # garbage (a different token, a dead book) + continue + prev = self.usual.get(key) + last = self.last_seen.get(key) + if prev is None or last is None or now - last > 600: + self.usual[key], self.seen_since[key] = gap, now # (re)start after a long absence + else: + alpha = min(1.0, alpha_base * max(1.0, (now - last) / POLL_S)) + self.usual[key] = prev + alpha * (gap - prev) + self.last_seen[key] = now + + def history_min(self, key: str, now: float) -> float: + return (now - self.seen_since[key]) / 60 if key in self.seen_since else 0.0 + + # --- trading --------------------------------------------------------------------------------------------- + def candidates(self, now: float, keys=None) -> list[dict]: + """Every link (or only `keys`) with what it would earn and why it is or is not entered now.""" + import basis + s = self.settings + on = self.exchanges() + if s.real: # an exchange without money for either leg: out until topped up + on -= {ex for ex in on if self.low_funds(ex)} + funds = {ex: self.funds(ex) for ex in on} if s.real else {} + kinds = {k for k, flag in (("sf", s.search_sf), ("in", s.search_in), ("ss", s.search_ss)) if flag} + hard_max = min(s.max_gap_pct, basis.HARD_MAX_GAP_PCT) + rows = [] + items = self.links.items() if keys is None else [(k, self.links[k]) for k in keys if k in self.links] + for key, l in items: + if l.spot_ex not in on or l.fut_ex not in on or l.kind not in kinds: + continue + if min(l.spot_turnover, l.fut_turnover) < s.min_turnover: + continue + short = self._short_of_money(l, funds) if s.real else [] + usual = self.usual.get(key) + hist = self.history_min(key, now) + excess = None if usual is None else l.entry_gap - usual + net = net_pct(l, usual, s, self.fees) + depth_ok = all(v is None or v >= s.amount for v in (l.spot_depth, l.fut_depth)) + elsewhere = self.elsewhere(l.base) + no_keys = [ex for ex in (l.spot_ex, l.fut_ex) if s.real and not self.has_keys(ex)] + # the smallest amount the spot of A and the perp of B both accept (paper too: only real-able trades) + m = (minorder.RULES.min_entry_ss(l.spot_ex, l.base, l.spot_ask, l.fut_ex, l.fut_bid, + spot_fee(l.spot_ex, self.fees)) if l.ss else + minorder.RULES.min_entry(l.spot_ex, l.base, l.spot_ask, l.fut_ex, l.fut_symbol, l.fut_bid, + spot_fee(l.spot_ex, self.fees))) + small = minorder.too_small(s.amount, m, l.spot_ex, l.fut_ex, "спот" if l.ss else "фьюч") + # a wide bid–ask spread: the quotes are thin and the fills land far from them (ZCAT 2.8 %, GSTOCKBSC 1.9 %) + spread_a = (l.spot_ask / l.spot_bid - 1) * 100 if l.spot_bid > 0 else 100.0 + spread_b = (l.fut_ask / l.fut_bid - 1) * 100 if l.fut_bid > 0 else 100.0 + wide = (f"широкий спред: {l.spot_ex} {spread_a:.2f}%, {l.fut_ex} {spread_b:.2f}% (макс. {s.max_spread_pct:g}%)" + if s.max_spread_pct > 0 and max(spread_a, spread_b) > s.max_spread_pct else "") + # either way: −34 % (SIREN MEXC spot vs Gate perp) is as much «two different coins» as +30 000 % (EWT) + fits = (net is not None and hist >= s.history_min and abs(l.entry_gap) <= hard_max + and net >= s.min_net_pct and depth_ok and not elsewhere and not no_keys and not short + and not small and not wide) + why = ("" if fits else f"уже в сделке: {elsewhere}" if elsewhere + else f"нет API-ключей {', '.join(no_keys)}" if no_keys + else wide if wide + else small if small + else f"мало {' и '.join(short)} для суммы {s.amount:g} $" if short + else "мало истории" if hist < s.history_min + else f"разница больше ±{basis.HARD_MAX_GAP_PCT:g}% — разные инструменты под одним тикером" + if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT + else "разница больше максимальной (по модулю)" if abs(l.entry_gap) > hard_max + else "чистая прибыль ниже порога" if net is None or net < s.min_net_pct else "мало объёма") + rows.append({"key": key, "link": l, "usual": usual, "excess": excess, "net": net, "history": hist, + "fits": fits, "why": why, "min": m}) + return rows + + def step(self, now: float) -> None: + s = self.settings + 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: + self.opening.add(base) + del self.recover[base] + self.jobs.put(("recover", base, info)) + if s.real: + self._watch_funds() + changed = self._check_exits(now) + # every link once per cycle: the table and the entries both use this (the page never recomputes 17 000 + # links itself); the hot links are refreshed in between by the hot watch + rows = self.candidates(now) + self.cand, self.cand_time = {r["key"]: r for r in rows}, now + real_busy = s.real and (self.opening or now < self.real_pause_until) + 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() + + def hot_step(self, keys: list[str], now: float) -> None: + """The hot links have fresh prices: their rows again, and an entry if one of them fits now.""" + with self.lock: + rows = self.candidates(now, keys) + for r in rows: + self.cand[r["key"]] = r + s = self.settings + if s.running and not (s.real and (self.opening or now < self.real_pause_until)): + if self._entries(now, rows): + self.save() + + def exit_level(self, pos: CrossPosition) -> tuple[float, float | None]: + """(the usual gap the position closes at, the usual gap now). The usual of the entry, unless the market has + moved it UP since (a regime shift: the old level may never come back) — then the current one; a usual that + went down does not make the exit harder.""" + now_usual = self.usual.get(pos.key) + return (pos.usual if now_usual is None else max(pos.usual, now_usual)), now_usual + + def _check_exits(self, now: float) -> bool: + """Open positions against the latest prices (the market cycle and the fast watch both call this).""" + s = self.settings + changed = False + for pos in list(self.positions): + l = self.links.get(pos.key) + 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 + step = l.interval_h * 3600 + pos.next_funding += step + changed = True + gap = l.exit_gap + # «back to usual» must hold `exit_hold_s` without a break: a one-tick spike of one leg (SHROOM: a burst + # of trades on MEXC that was gone 1.4 s later) does not close the position + back = False + level, now_usual = self.exit_level(pos) + if gap <= level + s.exit_over_usual_pct: + if not pos.exit_since: + pos.exit_since = now + back = now - pos.exit_since >= s.exit_hold_s + elif not pos.closing: + pos.exit_since = 0.0 + shifted = (f" (обычная сместилась: при входе {pos.usual:+.2f}%, сейчас {now_usual:+.2f}%)" + if level > pos.usual else "") + reason = ((f"разница вернулась к обычной и держалась {now - pos.exit_since:.1f} с{shifted}" + if s.exit_hold_s > 0 else f"разница вернулась к обычной{shifted}") if back + else "стоп: разница расширилась" if s.stop_widen_pct > 0 and gap >= pos.entry_gap + s.stop_widen_pct + else "время удержания" if s.max_hold_hours > 0 and now - pos.opened >= s.max_hold_hours * 3600 + else "") + if pos.real and pos.closing == "fut_done" and now >= pos.retry_at: + reason = reason or "продажа спота после выкупа шорта" + if pos.qty > 0 and not pos.closing and not pos.ss: # a spot sale on B has no liquidation + to_liq = (pos.liq_price / l.fut_ask - 1) * 100 if pos.liq_price > 0 else None + if to_liq is not None and s.liq_close_pct > 0 and to_liq < s.liq_close_pct: + # the coin has risen: B would liquidate the short and leave the spot on A naked — close now + reason = reason or f"до ликвидации шорта {to_liq:.1f}% < {s.liq_close_pct:g}%" + if pos.real and not reason and now - pos.liq_checked >= LIQ_CHECK_S: + pos.liq_checked = now # cross margin: it moves with B's whole account + self.jobs.put(("liq", pos.uid)) + if not reason: + continue + if pos.real: + if pos.uid not in self.busy and now >= pos.retry_at: + self.busy.add(pos.uid) + if not pos.exit_signal: # the prices of the decision (a retry keeps the first) + pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap] + self.jobs.put(("close", pos.uid, reason)) + else: + self._close(pos, l, now, reason) + changed = True + return changed + + def _entries(self, now: float, rows: list[dict] | None = None) -> bool: + import basis + s = self.settings + changed = False + busy = {p.base for p in self.positions} | self.opening + best: dict[str, dict] = {} + for r in (self.candidates(now) if rows is None else rows): # per coin: the link with the highest net + if r["fits"] and (r["link"].base not in best or r["net"] > best[r["link"].base]["net"]) \ + and not self.full(r["link"]): # a link whose exchange is full gives way to the next one + best[r["link"].base] = r + for r in sorted(best.values(), key=lambda r: -r["net"]): + l = r["link"] + if self.full(l): # filled by an entry made a moment ago in this loop + continue + if l.base in busy or now - self.last_close.get(l.base, 0.0) < s.cooldown_s: + continue + if self.elsewhere(l.base): + continue # the coin is already in a trade on a spot–futures tab + if s.real: + if self.real_block.get(l.base, ("", 0.0))[1] > now: + continue # known: cannot be traded for real now (lot, instrument…) + self.opening.add(l.base) + self.jobs.put(("open", l, r["usual"], s.amount)) + break # one real entry at a time + qty = s.amount / l.spot_ask + fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \ + + qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100 + step = l.interval_h * 3600 + # paper: B holds the amount + 3 % as futures money (what the real entry makes sure of) + liq = 0.0 if l.ss else l.fut_bid * (1 + liq_distance(self.FUT_NEED, 1.0) / 100) + self.positions.append(CrossPosition( + self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, qty, l.spot_ask, + l.fut_bid, l.entry_gap, r["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.next_uid += 1 + busy.add(l.base) + changed = True + return changed + + # --- fast watch of open positions ------------------------------------------------------------------------ + FAST_S = 0.25 + + def _fast_loop(self) -> None: + """While positions are open: spot of A and perp of B of each, several times a second, and the exit rules.""" + import dataclasses + import fastquote + pool = ThreadPoolExecutor(max_workers=8) + while True: + start = time.time() + with self.lock: + watch = {k: self.links[k] for k in (p.key for p in self.positions) + if k in self.links} + if not watch: + time.sleep(0.5) + continue + jobs = {k: (pool.submit(fastquote.spot_top, l.spot_ex, l.spot_symbol), + pool.submit(fastquote.spot_top if l.ss else fastquote.fut_top, l.fut_ex, l.fut_symbol)) + for k, l in watch.items()} + fresh = {} + for k, (sj, fj) in jobs.items(): + try: + sb, sa, _, sau = sj.result() + fb, fa, fbu, _ = fj.result() + except Exception: + continue + l = watch[k] + if min(sb, sa, fb, fa) <= 0: + continue + fresh[k] = dataclasses.replace(l, spot_bid=sb, spot_ask=sa, fut_bid=fb / l.fut_mult, + fut_ask=fa / l.fut_mult) + if fresh: + now = time.time() + with self.lock: + self.links.update(fresh) + for k in fresh: + self.fast_seen[k] = now + self.fast_ms = int((now - start) * 1000) + if self._check_exits(now): + self.save() + time.sleep(max(0.05, self.FAST_S - (time.time() - start))) + + # --- hot watch: links already in profit on paper, priced every HOT_S so an entry point is not missed --------- + HOT_S = 0.5 + HOT_MAX = 8 # links at most (2 price requests each, legs shared are asked once): the exchanges' limits + + def pick_hot(self, engines: list) -> list[str]: + """The links with the highest net profit > 0 of the running engines (not those already in a position).""" + best: dict[str, float] = {} + now = time.time() + for e in engines: + if not e.settings.running: + continue + held = {p.key for p in e.positions} + for k, r in list(e.cand.items()): + if e.settings.real and e.real_block.get(r["link"].base, ("", 0.0))[1] > now: + continue # waiting after a failed book check: no slot for it + if r["net"] is not None and r["net"] > 0 and k not in held: + best[k] = max(best.get(k, -1e9), r["net"]) + return sorted(best, key=lambda k: -best[k])[:self.HOT_MAX] + + def _hot_loop(self) -> None: + import dataclasses + import fastquote + pool = ThreadPoolExecutor(max_workers=8) + while True: + start = time.time() + engines = [self] + self.followers + keys = [k for k in self.pick_hot(engines) if k in self.links] + self.hot = keys + if not keys: + time.sleep(1.0) + continue + legs = {} # (spot?, exchange, symbol) → job: each leg asked once + for k in keys: + l = self.links[k] + legs.setdefault((True, l.spot_ex, l.spot_symbol), None) + legs.setdefault((l.ss, l.fut_ex, l.fut_symbol), None) + jobs = {leg: pool.submit(fastquote.spot_top if leg[0] else fastquote.fut_top, leg[1], leg[2]) for leg in legs} + quotes = {} + for leg, job in jobs.items(): + try: + bid, ask, _, _ = job.result() + if min(bid, ask) > 0: + quotes[leg] = (bid, ask) + except Exception: + pass + now = time.time() + done = [] + for e in engines: + with e.lock: + for k in keys: + l = e.links.get(k) + a, b = quotes.get((True, l.spot_ex, l.spot_symbol)) if l else None, \ + quotes.get((l.ss, l.fut_ex, l.fut_symbol)) if l else None + if not a or not b: + continue + e.links[k] = dataclasses.replace(l, spot_bid=a[0], spot_ask=a[1], fut_bid=b[0] / l.fut_mult, + fut_ask=b[1] / l.fut_mult) + e.fast_seen[k] = now + if e is self: + done.append(k) + e.hot_step(done or keys, now) + time.sleep(max(0.05, self.HOT_S - (time.time() - start))) + + def _close(self, pos: CrossPosition, l: Link, now: float, reason: str) -> None: + spot_pnl, fut_pnl, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees) + self.trades.append(CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty, + pos.spot_entry, l.spot_bid, pos.fut_entry, l.fut_ask, pos.entry_gap, l.exit_gap, + pos.usual, spot_pnl, fut_pnl, fees, pos.funding, net, reason, + pos.qty * pos.spot_entry, kind=pos.kind)) + self.positions.remove(pos) + self.last_close[pos.base] = now + + def close(self, uid: int | None) -> str: + with self.lock: + n = real = 0 + for pos in list(self.positions): + if uid is not None and pos.uid != uid: + continue + if pos.real: + if pos.uid not in self.busy: + self.busy.add(pos.uid) + pos.retry_at = 0.0 + self.jobs.put(("close", pos.uid, "вручную")) + real += 1 + continue + l = self.links.get(pos.key) + if l is None: + continue + self._close(pos, l, time.time(), "вручную") + n += 1 + self.save() + 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 "есть открытые реальные позиции — сначала закройте их" + self.positions, self.trades, self.last_close = [], [], {} + self.baseline = {"time": time.time(), "total": None, "by_ex": {}} if self.settings.real else {} + self.save() + return "статистика сброшена" + + # --- real orders (worker thread; never under the engine lock while waiting for an exchange) ------------------ + def _journal(self, coin: str, action: str, ok: bool, text: str, **extra) -> None: + import real_mirror + real_mirror.journal("basis", "cross", coin, action, ok, text, **extra) + + def _worker(self) -> None: + while True: + self.do_job(self.jobs.get()) + + def do_job(self, job: tuple) -> None: + kind, *args = job + if True: + try: + if kind == "open": + self._real_open(*args) + elif kind == "close": + self._real_close(*args) + elif kind == "recover": + self._recover(*args) + elif kind == "liq": + self._refresh_liq(*args) + except Exception as exc: # the worker must survive anything + base = args[0].base if kind == "open" else args[0] if kind == "recover" else "?" + self._journal(str(base), kind, False, f"сбой: {exc}") + finally: + with self.lock: + if kind == "close": + self.busy.discard(args[0]) + elif kind in ("open", "recover"): + base = args[0].base if kind == "open" else args[0] + self.opening.discard(base) + if self.pending.pop(base, None) is not None: + self.save() + + @staticmethod + def _api_closed(error: str) -> bool: + """The exchange refuses the symbol to API orders for good (not a passing problem): MEXC 10007 «symbol not + support api», «api trading is not enabled»…""" + e = error.lower() + return "not support api" in e or "10007" in e or "api trading" in e and "not" in e + + def _not_tradable(self, base: str, why: str, seconds: float) -> None: + with self.lock: + known = self.real_block.get(base, ("", 0.0))[0] == why + self.real_block[base] = (why, time.time() + seconds) + self.opening.discard(base) + if not known: + self._journal(base, "open", False, f"не открываю: {why} — ордеров не было") + + BALANCE_PAUSE_S = 900.0 + + def _pause_if_balance(self, error: str, exchange: str) -> None: + if any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно", "не хватает")): + with self.lock: + self.real_pause_until = time.time() + self.BALANCE_PAUSE_S + self.real_pause_reason = (f"не хватает баланса на {exchange} — пополните счёт или уменьшите " + f"«Сумму сделки»") + self._journal("—", "open", False, f"{self.real_pause_reason}; реальные входы на паузе 15 мин") + + def _real_open(self, l: Link, usual: float, amount: float) -> None: + """Short on B first (limit at the signal's bid, or at market), then the same coins bought on spot on A. + Nothing is bought on A when the short did not fill; the short is bought back when A's buy fails.""" + import basis + import live + l = self._still_good(l, usual, amount) + if l is None: + return + if l.ss: + self._real_open_ss(l, usual, amount) + return + s = self.settings + a_fee = spot_fee(l.spot_ex, self.fees) + try: + ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) + min_coins = cb.fut_min_coins(l.fut_symbol) + coins = cb.fut_round(l.fut_symbol, amount / l.spot_ask * (1 - a_fee / 100)) + except (live.LiveError, AttributeError) as exc: + self._not_tradable(l.base, f"нет правил контракта {l.fut_ex}: {exc}", 300) + return + # the same coins on both legs must be worth about the same: otherwise two different instruments + if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT or coins * l.fut_bid > amount * basis.MAX_LEG_RATIO: + self._not_tradable(l.base, f"шорт {coins:g} монет на {l.fut_ex} стоил бы {coins * l.fut_bid:.2f} $ при " + f"сумме {amount:g} $ — разные инструменты под одним тикером", 86400) + return + if coins <= 0 or coins < min_coins: + need = min_coins * l.spot_ask / (1 - a_fee / 100) * 1.02 + self._not_tradable(l.base, f"сумма {amount:g} $ меньше минимального лота фьючерса {l.fut_ex} " + f"({min_coins:g} монет ≈ {need:.2f} $)", 1800) + return + with self.lock: + # last check right before money is spent + held = [x.base for x in self.positions if x.real] + if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l): + return + self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, + "amount": amount} + self.save() + notional = coins * l.fut_bid + fut_need = max(notional * self.FUT_NEED, equity_for(s.min_liq_pct, notional)) + if s.auto_transfer: + # one exchange for both legs: one transfer that leaves enough on spot AND on futures + plan = (((ca, l.spot_ex, amount * 1.01, fut_need),) if l.spot_ex == l.fut_ex else + ((ca, l.spot_ex, amount * 1.01, 0.0), (cb, l.fut_ex, 0.0, fut_need))) + for c, ex, spot_need, fut_need in plan: + try: + moved = live.ensure_usdt(c, spot_need, fut_need) + if moved: + self._journal(l.base, "transfer", True, f"{ex}: {moved}") + except (live.LiveError, AttributeError) as exc: + if "в сумме" in str(exc): + self._journal(l.base, "open", False, f"не открываю: {ex}: {exc} — ордеров не было") + self._pause_if_balance("не хватает", ex) + return + self._journal(l.base, "transfer", False, f"{ex}: перевод не удался: {exc} — пробую без него") + # the liquidation of the short, from B's futures money right before it: far enough above the entry? + try: + fut_money = float(cb.usdt_free()["futures"]) + except (live.LiveError, AttributeError, KeyError, TypeError, ValueError) as exc: + self._not_tradable(l.base, f"не прочитан фьючерсный баланс {l.fut_ex} для расчёта ликвидации: {exc}", 120) + return + to_liq = liq_distance(fut_money, notional) + if to_liq < s.min_liq_pct: + self._not_tradable(l.base, f"ликвидация шорта на {l.fut_ex} была бы всего на {to_liq:.0f}% выше входа " + f"(на фьючерсах {fut_money:.2f} $ при шорте {notional:.2f} $, нужно " + f"{equity_for(s.min_liq_pct, notional):.2f} $ для запаса " + f"{s.min_liq_pct:g}%)", 300) + return + # 1) the short on B + shorted, fut_price, fut_fee_usd, fut_exact = 0.0, 0.0, 0.0, True + if s.entry_limit or s.entry_ioc: + # a limit order at the confirmed price (the average sale price of the amount in B's book): it fills + # only at that price or better. IOC: looked at once, the rest cancelled at once — a gap that has gone + # leaves nothing filled and nothing is bought on A; otherwise it waits «Лимитный вход: ждать, с» + hold = 0.0 if s.entry_ioc else max(0.0, s.limit_hold_s) + name = "IOC-шорт" if s.entry_ioc else "лимитный шорт" + try: + oid = cb.fut_limit(l.fut_symbol, "sell", coins, l.fut_bid) + except (live.LiveError, AttributeError) as exc: + 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 + st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False} + end = time.time() + hold + while True: # one look a second: the exchange's request limit + try: + st = cb.fut_order_status(l.fut_symbol, oid) + except live.LiveError: + pass + if st["final"] or st["coins"] >= coins * 0.999 or time.time() >= end: + break + time.sleep(1.0) + if not st["final"]: + 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 + shorted, fut_price, fut_fee_usd = st["coins"], st["price"] or l.fut_bid, st["fee"] + if shorted <= 0: + 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: + try: + fut = cb.fut_order(l.fut_symbol, "sell", coins, reduce_only=False) + shorted, fut_price, fut_fee_usd, fut_exact = fut.coins, fut.price, fut.fee_usd, fut.exact + except live.LiveError as exc: + held = 0.0 + if getattr(exc, "sent", False): + try: + held = max(0.0, -cb.fut_position(l.fut_symbol)) + except live.LiveError: + held = coins # unknown: assume open — the close is reduce-only + if held <= 0: + self._journal(l.base, "open", False, f"шорт на {l.fut_ex} не открыт: {exc}") + with self.lock: + self.last_close[l.base] = time.time() + self._pause_if_balance(str(exc), l.fut_ex) + return + shorted, fut_price = held, l.fut_bid + fut_fee_usd, fut_exact = held * l.fut_bid * fut_fee(l.fut_ex, self.fees, l.innovation) / 100, False + # 2) the hedge: the same coins on spot on A (the buy fee is taken in coins: a little more USDT) + try: + buy = ca.spot_buy(l.base, shorted * l.spot_ask * (1 + a_fee / 100) * 1.003) + except live.LiveError as exc: + bought = 0.0 + if getattr(exc, "sent", False): + try: + bought = min(ca.spot_free(l.base), shorted * 1.02) + except live.LiveError: + bought = 0.0 + if bought <= 0: + 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 + 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) + 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) + with self.lock: + step = l.interval_h * 3600 + now = time.time() + pos = CrossPosition(self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, shorted, + buy.price, fut_price, (fut_price / buy.price - 1) * 100, usual, + buy.fee_usd + fut_fee_usd, (now // step + 1) * step, real=True, spot_qty=held, + exact=buy.exact and fut_exact, innovation=l.innovation, + liq_price=fut_price * (1 + to_liq / 100), liq_calc=fut_price * (1 + to_liq / 100), + liq_src="расчёт", liq_checked=now, + entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], + fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact], + [l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]]) + self.next_uid += 1 + self.positions.append(pos) + self.save() + self._journal(l.base, "open", True, f"шорт {shorted:g} на {l.fut_ex} по {fut_price:.10g}, спот {held:g} на " + f"{l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% (обычная {usual:+.3f}%), " + f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount) + self._refresh_liq(pos.uid, first=True) + + CONFIRM_CHECKS = 2 + BOOK_BLOCK_S = 120.0 # a wide spread / thin book at the check: the coin is not tried again for this long + SIGNAL_BLOCK_S = 30.0 # the gap was gone at the check + + def _still_good(self, l: Link, usual: float, amount: float) -> Link | None: + """The signal came from the market cycle's list (tickers, seconds old): before real orders it is confirmed + on the ORDER BOOKS twice, `confirm_ms` apart — each time the whole amount priced through the book (the + average buy price on A, the average sale price on B), both spreads within «Макс. спред», and the net profit + above the threshold. A gap that is only a lagging ticker on a fast move does not survive this.""" + import dataclasses + if self.quote_now is None: + return l + s = self.settings + fresh = l + for check in range(1, self.CONFIRM_CHECKS + 1): + if check > 1: + time.sleep(max(0.0, s.confirm_ms) / 1000) + try: + sb, sa, fb, fa, spread_a, spread_b = self.quote_now(l, amount) + except ThinBook as exc: + why = f"{exc}" + except Exception as exc: + why = f"нет стакана: {str(exc)[:80]}" + else: + why = "" + if min(sb, sa, fb, fa) <= 0: + why = "пустой стакан" + elif s.max_spread_pct > 0 and max(spread_a, spread_b) > s.max_spread_pct: + why = (f"широкий спред: {l.spot_ex} {spread_a:.2f}%, {l.fut_ex} {spread_b:.2f}% " + f"(макс. {s.max_spread_pct:g}%)") + else: + fresh = dataclasses.replace(l, spot_bid=sb, spot_ask=sa, fut_bid=fb, fut_ask=fa) + net = net_pct(fresh, usual, s, self.fees) + if net is None or net < s.min_net_pct: + why = (f"по стакану разница {fresh.entry_gap:+.3f}% (в сигнале {l.entry_gap:+.3f}%), чистая " + f"прибыль {net if net is not None else 0:+.3f}% ниже порога {s.min_net_pct:g}%") + if why: + # the coin waits (the table shows why as «реально нельзя: …»): a wide or thin book does not change + # in a second — without this the next cycle would ask the books again and again + self._not_tradable(l.base, f"по стакану (проверка {check} из {self.CONFIRM_CHECKS}): {why}", + self.BOOK_BLOCK_S if "стакан" in why or "спред" in why else self.SIGNAL_BLOCK_S) + return None + with self.lock: + self.links[l.key] = fresh + self.fast_seen[l.key] = time.time() + return fresh + + def _real_open_ss(self, l: Link, usual: float, amount: float) -> None: + """Spot–spot: sell coins from the stock on B's spot first (they are there: nothing can fail half-way on a + missing coin), then buy the same coins on A's spot. A failed buy on A buys the stock back on B at once.""" + import basis + import live + s = self.settings + a_fee, b_fee_pct = spot_fee(l.spot_ex, self.fees), spot_fee(l.fut_ex, self.fees) + coins = amount / l.spot_ask * (1 - a_fee / 100) + if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT: + self._not_tradable(l.base, f"разница {l.entry_gap:.1f}% — разные монеты под одним тикером на " + f"{l.spot_ex} и {l.fut_ex}", 86400) + return + try: + ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) + have = cb.spot_free(l.base) + except (live.LiveError, AttributeError) as exc: + self._not_tradable(l.base, f"не прочитан запас {l.base} на {l.fut_ex}: {exc}", 120) + return + if have < coins: + self._not_tradable(l.base, f"на споте {l.fut_ex} {have:g} {l.base}, а для продажи нужно {coins:.6g} — " + f"положите монету на {l.fut_ex}", 300) + return + with self.lock: + held = [x.base for x in self.positions if x.real] + if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l): + return + self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, + "amount": amount} + self.save() + if s.auto_transfer: + try: + moved = live.ensure_usdt(ca, amount * 1.01, 0.0) + if moved: + self._journal(l.base, "transfer", True, f"{l.spot_ex}: {moved}") + except (live.LiveError, AttributeError) as exc: + if "в сумме" in str(exc): + self._journal(l.base, "open", False, f"не открываю: {l.spot_ex}: {exc} — ордеров не было") + self._pause_if_balance("не хватает", l.spot_ex) + return + self._journal(l.base, "transfer", False, f"{l.spot_ex}: перевод не удался: {exc} — пробую без него") + # 1) sell the stock on B + try: + sold = cb.spot_sell(l.base, coins) + except live.LiveError as exc: + if not getattr(exc, "sent", False): + self._journal(l.base, "open", False, f"продажа {l.base} на споте {l.fut_ex} не прошла: {exc}") + with self.lock: + self.last_close[l.base] = time.time() + return + sold = live.Fill(coins, l.fut_bid, coins * l.fut_bid * b_fee_pct / 100, exc.order_id, exact=False) + # 2) buy the same coins on A + try: + buy = ca.spot_buy(l.base, sold.coins * l.spot_ask * (1 + a_fee / 100) * 1.003) + except live.LiveError as exc: + if getattr(exc, "sent", False): + buy = live.Fill(sold.coins, l.spot_ask, sold.coins * l.spot_ask * a_fee / 100, exc.order_id, + exact=False) + else: + try: + cb.spot_buy(l.base, sold.coins * l.fut_ask * (1 + b_fee_pct / 100) * 1.003) + text = (f"{l.base} продан на {l.fut_ex}, но на {l.spot_ex} не куплен ({exc}); запас на " + f"{l.fut_ex} выкуплен обратно") + except live.LiveError as exc2: + text = (f"{l.base} продан на {l.fut_ex}, на {l.spot_ex} не куплен ({exc}); ЗАПАС НЕ ВЫКУПЛЕН " + f"({exc2}) — купите {sold.coins:g} {l.base} на {l.fut_ex} вручную") + self._journal(l.base, "open", False, text) + with self.lock: + self.last_close[l.base] = time.time() + self._pause_if_balance(str(exc), l.spot_ex) + return + try: + free = ca.spot_free(l.base) + except live.LiveError: + free = 0.0 + got = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100) + with self.lock: + now = time.time() + pos = CrossPosition(self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, + sold.coins, buy.price, sold.price, (sold.price / buy.price - 1) * 100, usual, + buy.fee_usd + sold.fee_usd, 0.0, real=True, spot_qty=got, ss=True, + exact=buy.exact and sold.exact, entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], + fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact], + [l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]]) + self.next_uid += 1 + self.positions.append(pos) + self.save() + self._journal(l.base, "open", True, f"спот-спот: продано {sold.coins:g} на {l.fut_ex} по {sold.price:.10g}, " + f"куплено {got:g} на {l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% " + f"(обычная {usual:+.3f}%)", amount=amount) + + def _refresh_liq(self, uid: int, first: bool = False) -> None: + """The exchange's own liquidation price of the short replaces the estimate (cross margin: it moves with + everything on B's futures account). The first look is compared with the program's estimate.""" + import live + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or pos.qty <= 0 or pos.closing or pos.ss: + return + try: + liq = self.client_for(pos.fut_ex).fut_liq_price(pos.fut_symbol) + except (live.LiveError, AttributeError): + return + with self.lock: + pos.liq_checked = time.time() + if not liq or liq <= 0: + return + pos.liq_price, pos.liq_src = liq, "биржа" + self.save() + if first and pos.liq_calc: + diff = (liq / pos.liq_calc - 1) * 100 + self._journal(pos.base, "liq", abs(diff) < 10, f"ликвидация шорта на {pos.fut_ex}: биржа {liq:.10g} " + f"(+{(liq / pos.fut_entry - 1) * 100:.0f}% от входа), расчёт {pos.liq_calc:.10g} — " + f"расхождение {diff:+.1f}%") + + def _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 + with self.lock: + pos = next((x for x in self.positions if x.uid == uid), None) + if pos is None or not pos.real: + return + stage = f"выкуп шорта на {pos.fut_ex}" + try: + ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex) + if pos.ss and pos.closing != "fut_done": + # 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() + if pos.closing != "fut_done": + fut_coins, fut_price, fee, exact = 0.0, 0.0, 0.0, True + if pos.qty > 0: + try: + fut = cb.fut_order(pos.fut_symbol, "buy", pos.qty, reduce_only=True) + fut_coins, fut_price, fee, exact = fut.coins, fut.price, fut.fee_usd, fut.exact + except live.LiveError as exc: + if not getattr(exc, "sent", False): + raise + l = self.links.get(pos.key) + fut_coins, fut_price = pos.qty, (l.fut_ask if l else pos.fut_entry) + fee, exact = pos.qty * fut_price * fut_fee(pos.fut_ex, self.fees, pos.innovation) / 100, False + with self.lock: + pos.fut_exit = fut_price if fut_coins else pos.fut_entry + pos.exit_fees, pos.closing = fee, "fut_done" + pos.exact = pos.exact and exact + if fut_coins: + pos.fills.append([pos.fut_ex, "fut_innovation" if pos.innovation else "fut", fee, + fut_coins * fut_price, exact]) + self.save() + stage = f"проверка фьючерса {pos.fut_ex}" + held = cb.fut_position(pos.fut_symbol) if pos.qty > 0 and not pos.ss else 0.0 + if held < -1e-12: + cb.fut_order(pos.fut_symbol, "buy", -held, reduce_only=True) + raise live.LiveError(f"на фьючерсе оставалось {held:+g} — докуплено, проверяю ещё раз") + stage = f"продажа спота на {pos.spot_ex}" + l = self.links.get(pos.key) + price_now = l.spot_bid if l else pos.spot_entry + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0: # more than dust left to sell + free = ca.spot_free(pos.base) + if free * price_now > 1.0: + sell = ca.spot_sell(pos.base, min(free, left)) + with self.lock: + pos.sold_coins += sell.coins + pos.sold_value += sell.coins * sell.price + pos.sold_fees += sell.fee_usd + pos.exact = pos.exact and sell.exact + pos.fills.append([pos.spot_ex, "spot", sell.fee_usd, sell.coins * sell.price, sell.exact]) + self.save() + left = pos.spot_qty - pos.sold_coins + if left * price_now > 1.0 and ca.spot_free(pos.base) * price_now > 1.0: + raise live.LiveError(f"на споте ещё {left:g} {pos.base} — продам при следующей попытке") + if pos.sold_coins <= 0 and pos.spot_qty * price_now > 1.0: + raise live.LiveError("спот не продан") + except live.LiveError as exc: + with self.lock: + pos.retry_at, pos.error = time.time() + 15, f"{stage}: {exc}" + self.save() + self._journal(pos.base, "close", False, f"{stage}: {exc} — следующая сделка не откроется, пока эта не " + f"закрыта; повтор через 15 с") + return + with self.lock: + now = time.time() + sell_price = pos.sold_value / pos.sold_coins if pos.sold_coins else pos.spot_entry + spot_pnl = pos.sold_value - pos.sold_coins * pos.spot_entry + fut_pnl = pos.qty * (pos.fut_entry - pos.fut_exit) + fees = pos.fees + pos.exit_fees + pos.sold_fees + net = spot_pnl + fut_pnl - fees + pos.funding + exit_gap = (pos.fut_exit / sell_price - 1) * 100 if pos.qty > 0 and sell_price else 0.0 + t = CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty, pos.spot_entry, + sell_price, pos.fut_entry, pos.fut_exit, pos.entry_gap, exit_gap, pos.usual, spot_pnl, + fut_pnl, fees, pos.funding, net, + f"{reason} (реально{'' if pos.exact else ', часть цифр оценочная'})", + pos.spot_qty * pos.spot_entry, real=True, exact=pos.exact, kind=pos.kind, + entry_signal=list(pos.entry_signal), exit_signal=list(pos.exit_signal)) + if pos in self.positions: + self.positions.remove(pos) + self.trades.append(t) + self.last_close[pos.base] = now + learned = self._learn_fees(pos, now) if self.settings.fees_auto else [] + self.save() + first = (f"монеты на споте {pos.fut_ex} выкуплены по {pos.fut_exit:.10g}" if pos.ss else + f"шорт на {pos.fut_ex} выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет)") + self._journal(pos.base, "close", True, f"{first}, спот на {pos.spot_ex} продан по {sell_price:.10g}, итог " + f"{net:+.4f} $, комиссии {fees:.4f} $ ({reason}){self._slippage_text(t)}", net=net) + + @staticmethod + def _slippage_text(t: CrossTrade) -> str: + """The prices of the decisions against the fills: how much each leg lost or won on the way to the exchange.""" + def leg(name, want, got, sell): + if not want or not got: + return "" + d = (got / want - 1) * 100 * (1 if sell else -1) # + = better than decided, − = worse + return f"{name} {want:.8g} → {got:.8g} ({d:+.2f}%)" + parts = [] + if t.entry_signal: + _, a, b, gap = t.entry_signal + parts.append(f"вход: решение при разнице {gap:+.3f}%, факт {t.entry_gap:+.3f}% — " + f"{leg('покупка A', a, t.spot_entry, False)}, {leg('продажа B', b, t.fut_entry, True)}") + if t.exit_signal: + _, a, b, gap = t.exit_signal + parts.append(f"выход: решение при разнице {gap:+.3f}%, факт {t.exit_gap:+.3f}% — " + f"{leg('продажа A', a, t.spot_exit, True)}, {leg('выкуп B', b, t.fut_exit, False)}") + return ("; " + "; ".join(parts)) if parts else "" + if learned: + self._journal(pos.base, "fee", True, "комиссии по этой сделке: " + "; ".join(learned)) + + def _learn_fees(self, pos: CrossPosition, now: float) -> list[str]: + """The rates the exchanges really charged in this trade (fee $ / value $ of its orders, the exchange's own + figures only) become the rates of the table. A zero fee (paid in another token) is not taken: the table + would then promise more than is earned.""" + sums: dict[tuple[str, str], list[float]] = {} + for ex, leg, fee, value, exact in pos.fills: + if exact and value > 0 and fee > 0: + acc = sums.setdefault((ex, leg), [0.0, 0.0]) + acc[0] += fee + acc[1] += value + out = [] + stamp = time.strftime("%d.%m %H:%M", time.localtime(now)) + for (ex, leg), (fee, value) in sums.items(): + rate = fee / value * 100 + if ex not in self.fees or leg not in self.fees[ex] or not 0 < rate <= MAX_LEARNED_FEE: + continue + old = self.fees[ex][leg] + self.fees[ex][leg] = round(rate, 5) + self.fees[ex][f"{leg}_src"] = f"по сделке {pos.base} {stamp}" + name = {"spot": "спот", "fut": "фьюч", "fut_innovation": "фьюч зоны инноваций"}[leg] + out.append(f"{ex} {name} {old:g}% → {rate:.4f}%") + return out + + def _recover(self, base: str, info: dict) -> None: + """After a restart in the middle of an entry: the short on B and the coins on A that were opened become a + real position (estimated prices), which the usual close then takes care of.""" + import live + with self.lock: + l = self.links.get(info.get("key", "")) + if l is None: + 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} → " + 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) + 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._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, + 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 + self.next_uid += 1 + self.positions.append(pos) + self.save() + self._journal(base, "open", True, f"после перезапуска: найден незавершённый вход — шорт {short:g} на " + f"{l.fut_ex}, спот {coins:g} на {l.spot_ex}; ведётся программой") + + # --- balances -------------------------------------------------------------------------------------------- + def coins_value(self, exchange: str) -> float: + """$ of the coins that real positions of every spot–futures engine hold on this exchange's spot account + (the account figures count USDT only).""" + import basis + total = 0.0 + for e in list(basis.ENGINES) + ([] if self in basis.ENGINES else [self]): + for pos in list(e.positions): + if not getattr(pos, "real", False): + continue + if getattr(pos, "spot_ex", None) is not None: + if pos.spot_ex != exchange: + continue + l = e.links.get(pos.key) + price = l.spot_bid if l else pos.spot_entry + else: + if getattr(getattr(e, "venue", None), "name", "") != exchange: + continue + p = e.pairs.get(pos.base) + price = p.spot_bid if p else pos.spot_entry + total += max(0.0, pos.spot_qty - pos.sold_coins) * price + return total + + def balance_view(self, now: float) -> dict: + """Per exchange: spot USDT, futures USDT (equity), coins of open positions, total — and the change since + trading was started (the first balance read after the start is the reference).""" + on = self.exchanges() + rows, total, newest_ok = [], 0.0, True + for ex in arb.EXCHANGES: + k = ex.lower() + b = self.balances.get(k) + row = {"exchange": ex, "on": ex in on, "keys": b is not None, "spot": None, "futures": None, + "low_funds": self.low_funds(ex) if ex in on else "", + "limit": self.limit(ex), "open_count": len(self.open_on(ex)), + "coins": None, "total": None, "error": "", "age": None, + "fee_spot": self.fees[ex]["spot"], "fee_fut": self.fees[ex]["fut"], + "fee_spot_src": self.fees[ex]["spot_src"], "fee_fut_src": self.fees[ex]["fut_src"], + "fee_fut_innovation": self.fees[ex].get("fut_innovation"), + "fee_fut_innovation_src": self.fees[ex].get("fut_innovation_src", "")} + if b is not None: + vals = b.get("values") or {} + row["error"] = b.get("error", "") + row["age"] = now - b["time"] if b.get("time") else None + if not row["age"] or b["time"] <= (self.baseline.get("time") or 0): + newest_ok = False + unified = vals.get("Единый счёт USDT") + spot = unified if isinstance(unified, (int, float)) else vals.get("Спот USDT") + fut = None if isinstance(unified, (int, float)) else vals.get("Фьючерсы USDT") + row["unified"] = isinstance(unified, (int, float)) + row["spot"] = spot if isinstance(spot, (int, float)) else None + row["futures"] = fut if isinstance(fut, (int, float)) else None + if not row["error"] and isinstance(vals.get("Фьючерсы"), str): + row["error"] = vals["Фьючерсы"] + if row["spot"] is not None: + row["coins"] = self.coins_value(ex) + row["total"] = row["spot"] + (row["futures"] or 0.0) + row["coins"] + total += row["total"] + rows.append(row) + keyed = [r for r in rows if r["keys"]] + base = self.baseline + if base and base.get("total") is None and keyed and newest_ok and all(r["total"] is not None for r in keyed): + with self.lock: # the reference: first full read after the start + base["total"] = total + base["by_ex"] = {r["exchange"]: r["total"] for r in keyed} + base["read"] = now + self.save() + for r in rows: + ref = (base.get("by_ex") or {}).get(r["exchange"]) + r["start"] = ref + r["change_pct"] = (r["total"] - ref) / ref * 100 if ref and r["total"] is not None else None + ref_total = base.get("total") + return {"rows": rows, "total": total if keyed else None, "start_total": ref_total, + "start_time": base.get("time"), + "change_usd": total - ref_total if ref_total and keyed else None, + "change_pct": (total - ref_total) / ref_total * 100 if ref_total and keyed else None} + + # --- view ------------------------------------------------------------------------------------------------ + def view(self) -> dict: + with self.lock: + s, now = self.settings, time.time() + best: dict[str, dict] = {} + # the last cycle's rows (the hot links refreshed every HOT_S); computed here only before the first cycle + source = list(self.cand.values()) if now - self.cand_time < 60 else self.candidates(now) + for r in source: + b = r["link"].base + score = r["net"] if r["net"] is not None else -1e9 + if b not in best or score > best[b]["score"]: + best[b] = {**r, "score": score} + real_open = [p.base for p in self.positions if p.real] + rows = [] + for r in best.values(): + l = r["link"] + why = r["why"] + block = self.real_block.get(l.base, ("", 0.0)) + if r["fits"]: + full = self.full(l) if l.base not in real_open else "" + why = ("торговля остановлена (кнопка «Старт»)" if not s.running + else f"реально нельзя: {block[0]}" if s.real and block[1] > now + else full if full + else "сейчас открывается другая реальная сделка" if s.real and (self.opening - {l.base}) + else f"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until + else f"пауза по монете после закрытия ({s.cooldown_s:g} с)" + if now - self.last_close.get(l.base, 0) < s.cooldown_s else "") + rows.append({"base": l.base, "spot_ex": l.spot_ex, "fut_ex": l.fut_ex, "kind": l.kind, + "kind_name": KIND_NAMES[l.kind], + "spot_ask": l.spot_ask, "fut_bid": l.fut_bid, "entry_gap": l.entry_gap, + "exit_gap": l.exit_gap, "usual": r["usual"], "excess": r["excess"], + "history": r["history"], "fits": r["fits"], "why": why, + "funding_pct": l.funding * 100, "interval_h": l.interval_h, + "depth": None if l.spot_depth is None or l.fut_depth is None else min(l.spot_depth, l.fut_depth), + "turnover": min(l.spot_turnover, l.fut_turnover), + "net_pct": r["net"], "innovation": l.innovation, + "hot": r["key"] in self.hot or r["key"] in getattr(self.leader, "hot", ()), + "price_age": (now - self.fast_seen[r["key"]]) if r["key"] in self.fast_seen else None, + "min_entry": r["min"]["usd"] if r["min"] else None, + "min_spot": r["min"]["spot"] if r["min"] else None, + "min_fut": r["min"]["fut"] if r["min"] else None, + "fees_pct": round_trip_fee_pct(l.spot_ex, l.fut_ex, self.fees, l.innovation, l.ss), + "spot_url": arb.spot_url(l.spot_ex, l.spot_symbol, l.base), + "fut_url": (arb.spot_url(l.fut_ex, l.fut_symbol, l.base) if l.ss + else arb.exchange_url(l.fut_ex, l.fut_symbol))}) + rows.sort(key=lambda r: -(r["net_pct"] if r["net_pct"] is not None else -1e9)) + positions = [] + for pos in self.positions: + d = asdict(pos) + d.pop("fills", None) + d.update(kind=pos.kind, kind_name=KIND_NAMES[pos.kind]) + level, now_usual = self.exit_level(pos) + d.update(exit_level=level, usual_now=now_usual, exit_target=level + s.exit_over_usual_pct) + l = self.links.get(pos.key) + if l: + _, _, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees) + seen = self.fast_seen.get(pos.key) + d.update(price_age=None if seen is None else now - seen, fast_ms=self.fast_ms) + d.update(liq_pct=(pos.liq_price / l.fut_ask - 1) * 100 if pos.liq_price > 0 else None) + if pos.exit_since and not pos.closing: # counting down to a «back to usual» close + d["exit_held"] = now - pos.exit_since + d.update(gap_now=l.exit_gap, spot_now=l.spot_bid, fut_now=l.fut_ask, net=net, fees_total=fees, + spot_url=arb.spot_url(l.spot_ex, l.spot_symbol, l.base), + fut_url=(arb.spot_url(l.fut_ex, l.fut_symbol, l.base) if l.ss + else arb.exchange_url(l.fut_ex, l.fut_symbol))) + positions.append(d) + # real mode: the figures are those of the real trades only (prices and fees from the exchanges' fills) + closed = [t for t in self.trades if t.real] if s.real else self.trades + opened = [p for p in positions if p.get("real")] if s.real else positions + wins = sum(t.net > 0 for t in closed) + invested = sum(t.amount for t in closed) + stats = {"trades": len(closed), "wins": wins, "net": sum(t.net for t in closed), + "net_pct": sum(t.net for t in closed) / invested * 100 if invested else None, + "fees": sum(t.fees for t in closed), "funding": sum(t.funding for t in closed), + "open": len(opened), "unrealized": sum(p.get("net", 0) for p in opened), + "real": s.real, "exact": all(t.exact for t in closed), + "avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None} + out = {"mode": "cross", "venue": "Арбитраж", "key": "cross", "settings": asdict(s), + "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} мин)" + if s.real and now < self.real_pause_until else "")} + out["balances"] = self.balance_view(now) + return out diff --git a/fastquote.py b/fastquote.py new file mode 100644 index 0000000..b1478bf --- /dev/null +++ b/fastquote.py @@ -0,0 +1,159 @@ +"""Best bid / ask of ONE symbol, fast (public REST, kept-alive connections): used to watch open positions several +times a second, instead of the whole-market lists that take 1–20 s per cycle. + + spot_top(exchange, symbol) -> (bid, ask, bid $ size or None, ask $ size or None) + fut_top(exchange, symbol) -> the same for the USDT perpetual, prices per the symbol's unit (1000PEPE…) + +`exchange` is "Bybit" / "Binance" / "MEXC" / "HTX" / "Gate"; symbols are the exchange's own (as the scanners have them). +""" + +from __future__ import annotations + +import urllib.parse + +from live import LiveError, _http + + +def _f(v) -> float: + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _q(s: str) -> str: + return urllib.parse.quote(s, safe="") + + +def spot_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]: + if exchange == "Bybit": + t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=spot&symbol={_q(symbol)}")["result"]["list"][0] + b, a = _f(t["bid1Price"]), _f(t["ask1Price"]) + return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size")) + if exchange in ("Binance", "MEXC"): + host = "https://api.binance.com" if exchange == "Binance" else "https://api.mexc.com" + t = _http("GET", f"{host}/api/v3/ticker/bookTicker?symbol={_q(symbol)}") + b, a = _f(t["bidPrice"]), _f(t["askPrice"]) + return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty")) + if exchange == "HTX": + t = _http("GET", f"https://api.huobi.pro/market/detail/merged?symbol={_q(symbol.lower())}")["tick"] + return _f(t["bid"][0]), _f(t["ask"][0]), _f(t["bid"][0]) * _f(t["bid"][1]), _f(t["ask"][0]) * _f(t["ask"][1]) + if exchange == "Gate": + t = _http("GET", f"https://api.gateio.ws/api/v4/spot/tickers?currency_pair={_q(symbol)}")[0] + return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None + raise LiveError(f"нет быстрых цен для {exchange}") + + +def fut_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]: + if exchange == "Bybit": + t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=linear&symbol={_q(symbol)}")["result"]["list"][0] + b, a = _f(t["bid1Price"]), _f(t["ask1Price"]) + return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size")) + if exchange == "Binance": + t = _http("GET", f"https://fapi.binance.com/fapi/v1/ticker/bookTicker?symbol={_q(symbol)}") + b, a = _f(t["bidPrice"]), _f(t["askPrice"]) + return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty")) + if exchange == "MEXC": + t = _http("GET", f"https://contract.mexc.com/api/v1/contract/ticker?symbol={_q(symbol)}")["data"] + return _f(t["bid1"]), _f(t["ask1"]), None, None + if exchange == "HTX": + t = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/detail/merged?contract_code={_q(symbol)}")["tick"] + return _f(t["bid"][0]), _f(t["ask"][0]), None, None + if exchange == "Gate": + t = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/tickers?contract={_q(symbol)}")[0] + return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None + raise LiveError(f"нет быстрых цен для {exchange}") + + +# --- order books: what an order of N $ would really get -------------------------------------------------------------- +# The tickers above can lag the book by a second or two on a fast move (seen on Gate: a «gap» that was gone when the +# orders arrived). Before a real entry the program reads the books themselves and prices the whole trade amount. +_SIZES: dict[tuple[str, str], float] = {} # (exchange, perp symbol) → coins (of the symbol's unit) per contract + + +def _contract_size(exchange: str, symbol: str) -> float: + key = (exchange, symbol) + if key not in _SIZES: + if exchange == "MEXC": + d = _http("GET", f"https://contract.mexc.com/api/v1/contract/detail?symbol={_q(symbol)}")["data"] + _SIZES[key] = _f(d.get("contractSize")) or 1.0 + elif exchange == "HTX": + d = _http("GET", f"https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?contract_code={_q(symbol)}")["data"] + _SIZES[key] = _f(d[0].get("contract_size")) or 1.0 + elif exchange == "Gate": + d = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/contracts/{_q(symbol)}") + _SIZES[key] = _f(d.get("quanto_multiplier")) or 1.0 + else: + _SIZES[key] = 1.0 + return _SIZES[key] + + +def book(exchange: str, market: str, symbol: str) -> tuple[list, list]: + """(bids, asks) of the order book, best first, as [(price per symbol unit, quantity in symbol units)]; + market "spot" or "fut".""" + fut = market == "fut" + if exchange == "Bybit": + r = _http("GET", f"https://api.bybit.com/v5/market/orderbook?category={'linear' if fut else 'spot'}" + f"&symbol={_q(symbol)}&limit=50")["result"] + bids, asks = r["b"], r["a"] + elif exchange == "Binance": + host = "https://fapi.binance.com/fapi/v1" if fut else "https://api.binance.com/api/v3" + r = _http("GET", f"{host}/depth?symbol={_q(symbol)}&limit=20") + bids, asks = r["bids"], r["asks"] + elif exchange == "MEXC": + if fut: + r = _http("GET", f"https://contract.mexc.com/api/v1/contract/depth/{_q(symbol)}?limit=20")["data"] + size = _contract_size(exchange, symbol) + bids = [(b[0], _f(b[1]) * size) for b in r["bids"]] + asks = [(a[0], _f(a[1]) * size) for a in r["asks"]] + else: + r = _http("GET", f"https://api.mexc.com/api/v3/depth?symbol={_q(symbol)}&limit=20") + bids, asks = r["bids"], r["asks"] + elif exchange == "HTX": + if fut: + r = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/depth?contract_code={_q(symbol)}&type=step0")["tick"] + size = _contract_size(exchange, symbol) + bids = [(b[0], _f(b[1]) * size) for b in r["bids"]] + asks = [(a[0], _f(a[1]) * size) for a in r["asks"]] + else: + r = _http("GET", f"https://api.huobi.pro/market/depth?symbol={_q(symbol.lower())}&depth=20&type=step0")["tick"] + bids, asks = r["bids"], r["asks"] + elif exchange == "Gate": + if fut: + r = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/order_book?contract={_q(symbol)}&limit=20") + size = _contract_size(exchange, symbol) + bids = [(b["p"], abs(_f(b["s"])) * size) for b in r["bids"]] + asks = [(a["p"], abs(_f(a["s"])) * size) for a in r["asks"]] + else: + r = _http("GET", f"https://api.gateio.ws/api/v4/spot/order_book?currency_pair={_q(symbol)}&limit=20") + bids, asks = r["bids"], r["asks"] + else: + raise LiveError(f"нет стакана для {exchange}") + return [(_f(p), _f(q)) for p, q in bids[:50]], [(_f(p), _f(q)) for p, q in asks[:50]] + + +def fill_price(levels: list, usd: float) -> float | None: + """Average price of an order for `usd` $ walking the book from the best level; None when the book (as read) + holds less than that.""" + left, cost, qty = usd, 0.0, 0.0 + for price, q in levels: + if price <= 0 or q <= 0: + continue + take = min(left, price * q) + cost += take + qty += take / price + left -= take + if left <= 1e-9: + return cost / qty + return None + + +def execution(exchange: str, market: str, symbol: str, usd: float) -> dict: + """What an order of `usd` $ gets now: {"bid": average sale price, "ask": average purchase price (None: not + enough in the book), "best_bid", "best_ask", "spread_pct"} — prices per symbol unit.""" + bids, asks = book(exchange, market, symbol) + if not bids or not asks: + raise LiveError(f"{exchange}: пустой стакан {symbol}") + bb, ba = bids[0][0], asks[0][0] + return {"bid": fill_price(bids, usd), "ask": fill_price(asks, usd), "best_bid": bb, "best_ask": ba, + "spread_pct": (ba / bb - 1) * 100 if bb > 0 else 100.0} diff --git a/historical_backtest.py b/historical_backtest.py new file mode 100644 index 0000000..3a59efc --- /dev/null +++ b/historical_backtest.py @@ -0,0 +1,1534 @@ +from __future__ import annotations + +import bisect +import csv +import heapq +import itertools +import json +import math +import sqlite3 +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Callable + +import strategy + +TAKER_FEE_PCT = 0.055 +API_URL = "https://api.bybit.com/v5/market/kline" +PAGE_TIMEOUT_SECONDS = 20 +PAGE_RETRY_DELAYS_SECONDS = (1, 2, 4, 8) +CANDLE_CACHE_DB = Path(__file__).with_name("historical_candles.sqlite3") +_CACHE_INIT_LOCK = threading.Lock() +TOP_N_DEFAULT = 100 + + +class RetryableBybitError(RuntimeError): + """A temporary Bybit API response that can succeed on a later attempt.""" + + +def _open_candle_cache(path: Path) -> sqlite3.Connection: + path.parent.mkdir(parents=True, exist_ok=True) + with _CACHE_INIT_LOCK: + connection = sqlite3.connect(str(path), timeout=30) + connection.execute("PRAGMA busy_timeout = 30000") + connection.execute( + "CREATE TABLE IF NOT EXISTS candles (" + "symbol TEXT NOT NULL, interval INTEGER NOT NULL, start_ms INTEGER NOT NULL, " + "open REAL NOT NULL, high REAL NOT NULL, low REAL NOT NULL, close REAL NOT NULL, " + "PRIMARY KEY(symbol, interval, start_ms))" + ) + connection.execute( + "CREATE TABLE IF NOT EXISTS coverage (" + "symbol TEXT NOT NULL, interval INTEGER NOT NULL, start_ms INTEGER NOT NULL, " + "end_ms INTEGER NOT NULL, PRIMARY KEY(symbol, interval, start_ms))" + ) + columns = {row[1] for row in connection.execute("PRAGMA table_info(candles)").fetchall()} + if "turnover" not in columns: + # Older caches stored OHLC only; turnover is needed for the liquidity ranking. + connection.execute("ALTER TABLE candles ADD COLUMN turnover REAL") + connection.execute( + "CREATE TABLE IF NOT EXISTS funding (" + "symbol TEXT NOT NULL, stamp_ms INTEGER NOT NULL, rate REAL NOT NULL, " + "PRIMARY KEY(symbol, stamp_ms))" + ) + connection.commit() + return connection + + +def _missing_ranges(start_ms: int, end_ms: int, coverage: list[tuple[int, int]], step_ms: int + ) -> list[tuple[int, int]]: + missing: list[tuple[int, int]] = [] + cursor = start_ms + for covered_start, covered_end in coverage: + if covered_end < cursor: + continue + if covered_start > cursor: + gap_end = min(end_ms, covered_start - step_ms) + if cursor <= gap_end: + missing.append((cursor, gap_end)) + cursor = max(cursor, covered_end + step_ms) + if cursor > end_ms: + break + if cursor <= end_ms: + missing.append((cursor, end_ms)) + return missing + + +def _cache_page(connection: sqlite3.Connection, symbol: str, interval: int, + page_start: int, page_end: int, rows: list[list[float]], step_ms: int) -> None: + connection.execute("BEGIN IMMEDIATE") + try: + connection.executemany( + "INSERT INTO candles(symbol, interval, start_ms, open, high, low, close, turnover) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT(symbol, interval, start_ms) DO UPDATE SET " + "open=excluded.open, high=excluded.high, low=excluded.low, close=excluded.close, " + "turnover=COALESCE(excluded.turnover, candles.turnover)", + [(symbol, interval, int(row[0]), *map(float, row[1:5]), + float(row[5]) if len(row) > 5 and row[5] is not None else None) for row in rows], + ) + coverage_rows = connection.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? " + "AND end_ms >= ? AND start_ms <= ?", + (symbol, interval, page_start - step_ms, page_end + step_ms), + ).fetchall() + merged_start, merged_end = page_start, page_end + for old_start, old_end in coverage_rows: + merged_start = min(merged_start, int(old_start)) + merged_end = max(merged_end, int(old_end)) + connection.executemany( + "DELETE FROM coverage WHERE symbol=? AND interval=? AND start_ms=?", + [(symbol, interval, int(old_start)) for old_start, _ in coverage_rows], + ) + connection.execute( + "INSERT OR REPLACE INTO coverage(symbol, interval, start_ms, end_ms) VALUES (?, ?, ?, ?)", + (symbol, interval, merged_start, merged_end), + ) + connection.commit() + except Exception: + connection.rollback() + raise + + +@dataclass +class SimPosition: + symbol: str + entry_price: float + qty: float + margin: float + entry_fees: float + opened_at: int + last_add_price: float + add_count: int = 0 + averaging_frozen: bool = False + funding: float = 0.0 # received (+) or paid (−) funding, USDT + + +FUNDING_URL = "https://api.bybit.com/v5/market/funding/history" +FUNDING_PAGE_LIMIT = 200 +# Coverage rows of the funding history use this pseudo-interval in the shared coverage table. +FUNDING_COVERAGE_INTERVAL = -1 + + +def _request_funding_page(symbol: str, start_ms: int, end_ms: int) -> list[tuple[int, float]]: + params = urllib.parse.urlencode({ + "category": "linear", "symbol": symbol, "startTime": str(start_ms), + "endTime": str(end_ms), "limit": str(FUNDING_PAGE_LIMIT), + }) + request = urllib.request.Request(f"{FUNDING_URL}?{params}", headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response: + payload = json.loads(response.read().decode("utf-8")) + ret_code = payload.get("retCode") + if ret_code != 0: + message = f"Bybit funding {symbol}: {ret_code} {payload.get('retMsg', '')}" + if str(ret_code) in {"10006", "10016"}: + raise RetryableBybitError(message) + raise RuntimeError(message) + rows = [] + for row in payload.get("result", {}).get("list", []): + try: + rows.append((int(row["fundingRateTimestamp"]), float(row["fundingRate"]))) + except (KeyError, TypeError, ValueError): + continue + return rows + + +def _cache_funding_page(connection: sqlite3.Connection, symbol: str, page_start: int, page_end: int, + rows: list[tuple[int, float]]) -> None: + connection.execute("BEGIN IMMEDIATE") + try: + connection.executemany( + "INSERT OR REPLACE INTO funding(symbol, stamp_ms, rate) VALUES (?, ?, ?)", + [(symbol, stamp, rate) for stamp, rate in rows], + ) + coverage_rows = connection.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? " + "AND end_ms >= ? AND start_ms <= ?", + (symbol, FUNDING_COVERAGE_INTERVAL, page_start - 1, page_end + 1), + ).fetchall() + merged_start, merged_end = page_start, page_end + for old_start, old_end in coverage_rows: + merged_start = min(merged_start, int(old_start)) + merged_end = max(merged_end, int(old_end)) + connection.executemany( + "DELETE FROM coverage WHERE symbol=? AND interval=? AND start_ms=?", + [(symbol, FUNDING_COVERAGE_INTERVAL, int(old_start)) for old_start, _ in coverage_rows], + ) + connection.execute( + "INSERT OR REPLACE INTO coverage(symbol, interval, start_ms, end_ms) VALUES (?, ?, ?, ?)", + (symbol, FUNDING_COVERAGE_INTERVAL, merged_start, merged_end), + ) + connection.commit() + except Exception: + connection.rollback() + raise + + +def fetch_funding_history(symbol: str, start_ms: int, end_ms: int, + cancel: Callable[[], bool] = lambda: False, + cache_path: Path | None = None) -> dict[int, float]: + """Settled funding rates {settlement_ms: rate as a fraction}; cached like the candles. + + A positive rate means LONG positions pay and SHORT positions receive + ``position value × rate`` at the settlement time. + """ + cache = _open_candle_cache(cache_path or CANDLE_CACHE_DB) + try: + coverage = [(int(row[0]), int(row[1])) for row in cache.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? ORDER BY start_ms", + (symbol, FUNDING_COVERAGE_INTERVAL), + ).fetchall()] + for gap_start, gap_end in _missing_ranges(start_ms, end_ms, coverage, 1): + cursor = gap_end + while cursor >= gap_start: + if cancel(): + raise InterruptedError("Исторический прогон отменён") + page = None + last_error: Exception | None = None + for attempt in range(len(PAGE_RETRY_DELAYS_SECONDS) + 1): + if cancel(): + raise InterruptedError("Исторический прогон отменён") + try: + page = _request_funding_page(symbol, gap_start, cursor) + break + except (RetryableBybitError, TimeoutError, urllib.error.URLError, + ConnectionError, OSError) as exc: + last_error = exc + if attempt >= len(PAGE_RETRY_DELAYS_SECONDS): + break + time.sleep(PAGE_RETRY_DELAYS_SECONDS[attempt]) + if page is None: + raise RuntimeError(f"Не удалось загрузить funding {symbol}: {last_error}") from last_error + page = [(stamp, rate) for stamp, rate in page if gap_start <= stamp <= cursor] + full_page = len(page) >= FUNDING_PAGE_LIMIT + page_start = min(stamp for stamp, _ in page) if full_page else gap_start + _cache_funding_page(cache, symbol, page_start, cursor, page) + if not full_page: + break + cursor = page_start - 1 + time.sleep(0.1) + return {int(row[0]): float(row[1]) for row in cache.execute( + "SELECT stamp_ms, rate FROM funding WHERE symbol=? AND stamp_ms BETWEEN ? AND ? ORDER BY stamp_ms", + (symbol, start_ms, end_ms), + ).fetchall()} + finally: + cache.close() + + +def _request_page(symbol: str, interval: int, start_ms: int, end_ms: int) -> list[list[float]]: + params = urllib.parse.urlencode({ + "category": "linear", "symbol": symbol, "interval": str(interval), + "start": str(start_ms), "end": str(end_ms), "limit": "1000", + }) + request = urllib.request.Request(f"{API_URL}?{params}", headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response: + payload = json.loads(response.read().decode("utf-8")) + ret_code = payload.get("retCode") + if ret_code != 0: + message = f"Bybit {symbol}: {ret_code} {payload.get('retMsg', '')}" + if str(ret_code) in {"10006", "10016"}: + raise RetryableBybitError(message) + raise RuntimeError(message) + output = [] + for row in payload.get("result", {}).get("list", []): + stamp = int(row[0]) + turnover = float(row[6]) if len(row) > 6 and row[6] not in (None, "") else None + output.append([stamp, float(row[1]), float(row[2]), float(row[3]), float(row[4]), turnover]) + return output + + +def fetch_klines(symbol: str, interval: int, start_ms: int, end_ms: int, + cancel: Callable[[], bool] = lambda: False, + progress: Callable[..., None] = lambda *_: None, + cache_path: Path | None = None, with_turnover: bool = False) -> list[list[float]]: + """Return cached candles and fetch only uncovered ranges, persisting every API page. + + Rows are [start_ms, open, high, low, close] or, with ``with_turnover``, + [start_ms, open, high, low, close, turnover]. + """ + step_ms = interval * 60_000 + first_open = ((start_ms + step_ms - 1) // step_ms) * step_ms + last_open = (end_ms // step_ms) * step_ms + if last_open < first_open: + raise RuntimeError(f"Пустой диапазон свечей для {symbol}") + estimated_total = (last_open - first_open) // step_ms + 1 + cache = _open_candle_cache(cache_path or CANDLE_CACHE_DB) + page_number = 0 + try: + coverage = [(int(row[0]), int(row[1])) for row in cache.execute( + "SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? ORDER BY start_ms", + (symbol, interval), + ).fetchall()] + gaps = _missing_ranges(first_open, last_open, coverage, step_ms) + cached_count = int(cache.execute( + "SELECT COUNT(*) FROM candles WHERE symbol=? AND interval=? AND start_ms BETWEEN ? AND ?", + (symbol, interval, first_open, last_open), + ).fetchone()[0]) + pages_total = sum(math.ceil(((gap_end - gap_start) // step_ms + 1) / 1000) + for gap_start, gap_end in gaps) + progress(symbol, cached_count, estimated_total, + f"локальный кэш: {cached_count:,} свечей; докачать страниц: {pages_total}") + + for gap_start, gap_end in gaps: + cursor = gap_end + while cursor >= gap_start: + if cancel(): + raise InterruptedError("Исторический прогон отменён") + page_number += 1 + # Query a bounded, non-overlapping block of up to 1,000 candle opens. + page_start = max(gap_start, cursor - 999 * step_ms) + progress(symbol, cached_count, estimated_total, + f"страница {page_number}/{pages_total}: запрос Bybit") + page = None + last_error: Exception | None = None + for attempt in range(len(PAGE_RETRY_DELAYS_SECONDS) + 1): + if cancel(): + raise InterruptedError("Исторический прогон отменён") + try: + page = _request_page(symbol, interval, page_start, cursor) + break + except (RetryableBybitError, TimeoutError, urllib.error.URLError, + ConnectionError, OSError) as exc: + last_error = exc + if attempt >= len(PAGE_RETRY_DELAYS_SECONDS): + break + progress(symbol, cached_count, estimated_total, + f"страница {page_number}/{pages_total}: повтор {attempt + 2}/5 ({exc})") + time.sleep(PAGE_RETRY_DELAYS_SECONDS[attempt]) + if page is None: + raise RuntimeError( + f"Не удалось загрузить страницу свечей {symbol} после " + f"{len(PAGE_RETRY_DELAYS_SECONDS) + 1} попыток: {last_error}" + ) from last_error + page_rows = [row for row in page if page_start <= int(row[0]) <= cursor] + _cache_page(cache, symbol, interval, page_start, cursor, page_rows, step_ms) + cached_count += len(page_rows) + progress(symbol, min(cached_count, estimated_total), estimated_total, + f"страница {page_number}/{pages_total} сохранена в кэш") + cursor = page_start - step_ms + if cursor >= gap_start: + time.sleep(0.25) + + result = [[int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4])] + + ([float(row[5] or 0.0)] if with_turnover else []) + for row in cache.execute( + "SELECT start_ms, open, high, low, close, turnover FROM candles " + "WHERE symbol=? AND interval=? AND start_ms BETWEEN ? AND ? ORDER BY start_ms", + (symbol, interval, first_open, last_open), + ).fetchall()] + finally: + cache.close() + if len(result) < 2: + raise RuntimeError(f"Bybit вернул только {len(result)} закрытых свечей для {symbol}") + return result + + +INSTRUMENTS_URL = "https://api.bybit.com/v5/market/instruments-info" +UNIVERSE_SCAN_INTERVAL_MINUTES = 60 + + +def _fee_cover_pct(fee_pct: float) -> float: + return strategy.fee_cover_pct(fee_pct) + + +def fetch_linear_usdt_symbols(end_ms: int | None = None) -> list[str]: + """Return USDT perpetual tickers, including delisted ones when Bybit still lists them. + + Including ``Closed`` contracts reduces survivorship bias: coins that pumped and were + later delisted stay in the historical universe whenever Bybit still serves their candles. + """ + symbols: set[str] = set() + errors: list[str] = [] + for status in ("Trading", "Closed"): + cursor = "" + for _ in range(20): + params = {"category": "linear", "limit": "1000", "status": status} + if cursor: + params["cursor"] = cursor + request = urllib.request.Request( + f"{INSTRUMENTS_URL}?{urllib.parse.urlencode(params)}", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}, + ) + try: + with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception as exc: # the Closed list is optional + errors.append(f"{status}: {exc}") + break + if payload.get("retCode") != 0: + errors.append(f"{status}: {payload.get('retCode')} {payload.get('retMsg', '')}") + break + result = payload.get("result", {}) + for row in result.get("list", []): + symbol = str(row.get("symbol") or "").upper() + if (row.get("quoteCoin") != "USDT" or row.get("contractType") != "LinearPerpetual" + or not symbol.endswith("USDT")): + continue + launch = int(row.get("launchTime") or 0) + if end_ms is not None and launch and launch > end_ms: + continue + symbols.add(symbol) + cursor = result.get("nextPageCursor") or "" + if not cursor: + break + if not symbols: + raise RuntimeError("Bybit не вернул список USDT-контрактов. " + " · ".join(errors)) + return sorted(symbols) + + +def build_universe_windows(hourly_by_symbol: dict[str, list[list[float]]], start_ms: int, end_ms: int, + min_growth_24h_pct: float, top_n: int = 100 + ) -> dict[str, list[tuple[int, int]]]: + """Point-in-time replica of the live auto-selection on hourly data. + + After each hourly candle closes, every symbol is ranked by its trailing 24-hour turnover; + of the ``top_n`` most liquid ones, those whose 24-hour change is strictly above + ``min_growth_24h_pct`` may open new entries during the following hour. + Returns merged ``[from_ms, to_ms)`` entry windows per symbol. + """ + hour_ms = 60 * 60 * 1000 + series: dict[str, dict[int, tuple[float, float]]] = { + symbol: {int(row[0]): (float(row[4]), float(row[5]) if len(row) > 5 else 0.0) for row in rows} + for symbol, rows in hourly_by_symbol.items() + } + first_hour = (start_ms // hour_ms) * hour_ms - hour_ms + windows: dict[str, list[tuple[int, int]]] = {} + rolling: dict[str, float] = {symbol: 0.0 for symbol in series} + # Prime trailing turnover sums with the 23 hours before the first decision. + for symbol, rows in series.items(): + rolling[symbol] = sum(rows.get(first_hour - k * hour_ms, (0.0, 0.0))[1] for k in range(1, 24)) + hour = first_hour + while hour <= end_ms: + decision_from = hour + hour_ms # the candle [hour, hour+1h) has closed + decision_to = decision_from + hour_ms + ranked: list[tuple[float, str, float]] = [] + for symbol, rows in series.items(): + current = rows.get(hour) + rolling[symbol] += current[1] if current else 0.0 + if current: + prior = rows.get(hour - 24 * hour_ms) + if prior and prior[0] > 0 and rolling[symbol] > 0: + ranked.append((rolling[symbol], symbol, (current[0] / prior[0] - 1) * 100)) + dropped = rows.get(hour - 23 * hour_ms) + rolling[symbol] -= dropped[1] if dropped else 0.0 + ranked.sort(reverse=True) + for _turnover, symbol, change in ranked[:top_n]: + if change > min_growth_24h_pct and decision_to > start_ms and decision_from <= end_ms: + spans = windows.setdefault(symbol, []) + lo = max(decision_from, start_ms) + if spans and spans[-1][1] >= lo: + spans[-1] = (spans[-1][0], decision_to) + else: + spans.append((lo, decision_to)) + hour += hour_ms + return windows + + +def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_n: int = TOP_N_DEFAULT, + cancel: Callable[[], bool] = lambda: False, + progress: Callable[..., None] = lambda *_: None, + cache_path: Path | None = None, workers: int = 4 + ) -> tuple[dict[str, list[tuple[int, int]]], list[str]]: + """Download hourly candles with turnover for every USDT perpetual and build entry windows. + + Returns (windows per symbol, symbols that could not be loaded). Hourly data is cached in the + same SQLite file, so later runs only download new hours. + """ + hour_ms = UNIVERSE_SCAN_INTERVAL_MINUTES * 60_000 + hourly_start = (start_ms // hour_ms) * hour_ms - 2 * 24 * hour_ms + hourly_end = (end_ms // hour_ms) * hour_ms - 1 + symbols = fetch_linear_usdt_symbols(end_ms) + hourly: dict[str, list[list[float]]] = {} + failed: list[str] = [] + done = 0 + + def load(symbol: str) -> list[list[float]]: + return fetch_klines(symbol, UNIVERSE_SCAN_INTERVAL_MINUTES, hourly_start, hourly_end, cancel, + cache_path=cache_path, with_turnover=True) + + with ThreadPoolExecutor(max_workers=max(1, workers)) as pool: + futures = {pool.submit(load, symbol): symbol for symbol in symbols} + for future in as_completed(futures): + symbol = futures[future] + if cancel(): + for pending in futures: + pending.cancel() + raise InterruptedError("Исторический прогон отменён") + try: + hourly[symbol] = future.result() + except InterruptedError: + raise + except Exception: + # Contracts listed after the period or with no candles are simply skipped. + failed.append(symbol) + done += 1 + progress("Отбор валют", done, len(symbols), + f"часовые свечи и оборот: {done}/{len(symbols)} контрактов") + windows = build_universe_windows(hourly, start_ms, end_ms, min_growth_24h_pct, top_n) + return windows, sorted(failed) + + +def run_backtest(candles_by_symbol: dict[str, list[list[float]]], + strategies: dict[str, dict[str, float]], initial_capital: float, + fee_pct: float = TAKER_FEE_PCT, + cancel: Callable[[], bool] = lambda: False, + trading_start_ms: int | None = None, + pause_below_24h_pct: float = 30.0, + resume_above_24h_pct: float = 31.0, + min_equity_pct: float = 10.0, + max_open_positions: int | None = None, + universe_windows: dict[str, list[tuple[int, int]]] | None = None, + funding_by_symbol: dict[str, dict[int, float]] | None = None) -> dict: + """Replay minute OHLC bars; the assumed path is O-L-H-C for green and O-H-L-C for red. + + ``max_open_positions`` mirrors the live/simulation limit on simultaneous positions. + ``universe_windows`` replaces the per-symbol 24-hour filter with the point-in-time + auto-selection: entries are allowed only inside a symbol's windows and averaging is + paused outside them, exactly like a pair waiting for retirement in live mode. + ``funding_by_symbol`` holds settled funding rates; an open LONG pays + ``qty × open price × rate`` at each settlement minute (receives it when the rate is negative). + """ + symbols = sorted(set(candles_by_symbol) & set(strategies)) + if not symbols: + raise ValueError("Нет свечей для прогона") + universe_mode = universe_windows is not None + # Stream candles in (time, ticker) order instead of building a full timeline in memory: + # the live-like selection can involve dozens of pairs with months of minute data. + first_stamp = min(int(candles_by_symbol[symbol][0][0]) for symbol in symbols) + def tagged(symbol: str): + for candle in candles_by_symbol[symbol]: + yield int(candle[0]), symbol, candle + + stream = heapq.merge(*(tagged(symbol) for symbol in symbols), key=lambda item: (item[0], item[1])) + grouped = ((stamp, [(symbol, candle) for _stamp, symbol, candle in items]) + for stamp, items in itertools.groupby(stream, key=lambda item: item[0])) + # The per-symbol 24-hour lookup is only needed by the classic growth filter. + lookup = ({} if universe_mode else + {symbol: {int(row[0]): row for row in candles_by_symbol[symbol]} for symbol in symbols}) + positions: dict[str, SimPosition] = {} + previous_close: dict[str, float] = {} + entry_allowed = {symbol: False for symbol in symbols} + filter_triggered = {symbol: False for symbol in symbols} + window_cursor = {symbol: 0 for symbol in symbols} + marks: dict[str, float] = {} + cash = float(initial_capital) + closed: list[dict] = [] + next_id = 1 + equity_floor = initial_capital * min_equity_pct / 100 if min_equity_pct > 0 else 0.0 + equity_stop: dict[str, object] = {"triggered": False, "timestamp": None, "equity": None} + processed_candles = {symbol: 0 for symbol in symbols} + risk = {"peak": float(initial_capital), "max_dd_usdt": 0.0, "max_dd_pct": 0.0, + "min_equity": float(initial_capital), "max_margin": 0.0, "max_positions": 0, + "skipped_limit": 0, "skipped_margin": 0} + funding_total = {"sum": 0.0, "events": 0} + last_stamp = first_stamp + + def equity_at(symbol: str | None = None, price: float | None = None) -> float: + equity = cash + for position_symbol, position in positions.items(): + mark = (price if position_symbol == symbol and price is not None + else marks.get(position_symbol, position.entry_price)) + unrealized = (mark - position.entry_price) * position.qty + estimated_exit_fee = mark * position.qty * fee_pct / 100 + equity += unrealized - estimated_exit_fee + return equity + + def 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) + if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12): + equity_stop.update(triggered=True, timestamp=stamp, equity=equity) + return True + return False + + def used_margin() -> float: + return sum(p.margin for p in positions.values()) + + def free_margin() -> float: + # Same definition as simulation/live: equity (cash + unrealized P&L after the + # estimated closing fee) minus margin locked in open positions. + return equity_at() - used_margin() + + def note_exposure() -> None: + risk["max_margin"] = max(risk["max_margin"], used_margin()) + risk["max_positions"] = max(risk["max_positions"], len(positions)) + + def open_position(symbol: str, price: float, stamp: int) -> bool: + nonlocal cash, next_id + cfg = strategies[symbol] + stake, leverage = cfg["stake"], cfg["leverage"] + if max_open_positions is not None and len(positions) >= max_open_positions: + risk["skipped_limit"] += 1 + return False + if stake > max(0.0, free_margin()): + risk["skipped_margin"] += 1 + return False + notional = stake * leverage + qty = notional / price + entry_fee = notional * fee_pct / 100 + cash -= entry_fee + positions[symbol] = SimPosition(symbol, price, qty, stake, entry_fee, stamp, price) + positions[symbol]._trade_id = next_id + next_id += 1 + note_exposure() + return True + + def add_to_position(symbol: str, pos: SimPosition, level: float) -> bool: + nonlocal cash + cfg = strategies[symbol] + cfg_stake = cfg["stake"] + if cfg_stake > max(0.0, free_margin()): + # Skipped for lack of margin; a later, deeper level may still be filled. + risk["skipped_margin"] += 1 + return False + notional = cfg_stake * cfg["leverage"] + added_qty = notional / level + fee = notional * fee_pct / 100 + total_qty = pos.qty + added_qty + pos.entry_price = (pos.entry_price * pos.qty + level * added_qty) / total_qty + pos.qty = total_qty + pos.margin += cfg_stake + pos.entry_fees += fee + pos.last_add_price = level + pos.add_count += 1 + cash -= fee + note_exposure() + return True + + def close_position(symbol: str, price: float, stamp: int, reason: str, + liquidation: bool = False) -> None: + nonlocal cash + pos = positions.pop(symbol) + if liquidation: + # Isolated-margin liquidation forfeits the whole margin of the position. + gross = -pos.margin + exit_fee = 0.0 + else: + gross = (price - pos.entry_price) * pos.qty + exit_fee = price * pos.qty * fee_pct / 100 + fees = pos.entry_fees + exit_fee + # Funding already moved the cash while the position was open. + net = gross - fees + pos.funding + cash += gross - exit_fee + closed.append({ + "id": pos._trade_id, "symbol": symbol, "side": "LONG", + "opened_at": datetime.fromtimestamp(pos.opened_at / 1000, timezone.utc).isoformat(), + "closed_at": datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat(), + "entry": pos.entry_price, "exit": price, "entries": pos.add_count + 1, + "margin": pos.margin, "gross_usdt": gross, "fees_usdt": fees, "funding_usdt": pos.funding, + "net_usdt": net, "roi_pct": net / pos.margin * 100 if pos.margin else 0, + "hold_hours": (stamp - pos.opened_at) / 3_600_000, + "reason": reason, "status": "CLOSED", + }) + + def exit_levels(symbol: str, pos: SimPosition) -> tuple[float | None, float | None, float | None]: + cfg = strategies[symbol] + return (strategy.take_profit_price(pos.entry_price, cfg["take_profit"], fee_pct), + strategy.stop_loss_price(pos.entry_price, cfg["stop_loss"]), + strategy.liquidation_price(pos.entry_price, cfg["leverage"])) + + def handle_gap(symbol: str, price: float, stamp: int) -> None: + """Apply TP/stop/liquidation/adds when a candle opens beyond a level (price gap).""" + cfg = strategies[symbol] + for _ in range(int(cfg["max_adds"]) + 2): + pos = positions.get(symbol) + if pos is None: + return + tp, stop, liq = exit_levels(symbol, pos) + if liq is not None and price <= liq: + close_position(symbol, price, stamp, "Ликвидация (разрыв цены)", liquidation=True) + return + if stop is not None and price <= stop: + loss_pct = (pos.entry_price - price) / pos.entry_price * 100 + close_position(symbol, price, stamp, f"Стоп −{loss_pct:.3f}% (разрыв цены)") + return + if tp is not None and price >= tp: + gain_pct = (price / pos.entry_price - 1) * 100 + close_position(symbol, price, stamp, f"TP +{gain_pct:.3f}% (разрыв цены)") + return + level = strategy.add_level(pos.last_add_price, cfg["add_step"]) + if (level is None or not strategy.can_add(pos.add_count, cfg["max_adds"], cfg["add_step"], + pos.averaging_frozen) or price > level): + return + if not add_to_position(symbol, pos, price): + return + + def walk_segment(symbol: str, start: float, end: float, stamp: int, + baseline: float, armed: list[bool], allow_entry: bool) -> None: + cfg = strategies[symbol] + entry_level = strategy.entry_level(baseline, cfg["trigger"]) + current = start + rising = end > start + for _ in range(16 + 2 * int(cfg["max_adds"])): + if mark_and_check_stop(symbol, current, stamp): + return + if abs(end - current) <= max(abs(end), 1.0) * 1e-14: + mark_and_check_stop(symbol, end, stamp) + return + pos = positions.get(symbol) + if rising: + if pos is None: + if armed[0] and current < entry_level <= end: + if allow_entry and open_position(symbol, entry_level, stamp): + armed[0] = False + current = entry_level + if mark_and_check_stop(symbol, current, stamp): + return + continue + # Mark the trigger as crossed even when the filter blocks it; + # a new entry then needs a fresh cross or candle. + armed[0] = False + mark_and_check_stop(symbol, end, stamp) + return + tp_level, _stop, _liq = exit_levels(symbol, pos) + if tp_level is not None and current < tp_level <= end: + marks[symbol] = tp_level + tp_pct = strategy.effective_take_profit_pct(cfg["take_profit"], fee_pct) + close_position(symbol, tp_level, stamp, f"TP +{tp_pct:.3f}%") + armed[0] = False + current = tp_level + if mark_and_check_stop(symbol, current, stamp): + return + continue + mark_and_check_stop(symbol, end, stamp) + return + # Falling segment: once price is below the entry threshold, a later rebound may enter. + if pos is None: + if end < entry_level: + armed[0] = True + mark_and_check_stop(symbol, end, stamp) + return + candidates: list[tuple[float, str]] = [] + # Equity moves linearly with this symbol's price between strategy events. + # Add the precise capital-floor crossing as an event so a later rebound + # inside the same candle cannot hide a drawdown breach. + if min_equity_pct > 0 and end < current: + 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) + ) + candidates.append((stop_level, "EQUITY_STOP")) + _tp, stop_level, liq_level = exit_levels(symbol, pos) + if stop_level is not None and end <= stop_level < current: + candidates.append((stop_level, "STOP")) + if liq_level is not None and end <= liq_level < current: + candidates.append((liq_level, "LIQ")) + if strategy.can_add(pos.add_count, cfg["max_adds"], cfg["add_step"], pos.averaging_frozen): + add_level = strategy.add_level(pos.last_add_price, cfg["add_step"]) + if add_level is not None and end <= add_level < current: + candidates.append((add_level, "ADD")) + if not candidates: + mark_and_check_stop(symbol, end, stamp) + return + level, event = max(candidates, key=lambda item: item[0]) + marks[symbol] = level + if event == "EQUITY_STOP": + mark_and_check_stop(symbol, level, stamp) + return + if event in ("STOP", "LIQ"): + if event == "LIQ": + close_position(symbol, level, stamp, f"Ликвидация (плечо {cfg['leverage']:g}x)", + liquidation=True) + else: + loss_pct = (pos.entry_price - level) / pos.entry_price * 100 + close_position(symbol, level, stamp, f"Стоп −{loss_pct:.3f}%") + armed[0] = False + current = level + if mark_and_check_stop(symbol, current, stamp): + return + continue + if not add_to_position(symbol, pos, level): + # Not enough free margin: consume this level so the next one is measured from it. + pos.last_add_price = level + current = level + if mark_and_check_stop(symbol, current, stamp): + return + + def update_entry_filter(symbol: str, stamp: int, close: float) -> None: + if universe_mode: + return + prior_day = lookup[symbol].get(stamp - 24 * 60 * 60 * 1000) + if not prior_day or prior_day[4] <= 0: + return + change_24h = (close / float(prior_day[4]) - 1) * 100 + if change_24h < pause_below_24h_pct: + entry_allowed[symbol] = False + filter_triggered[symbol] = True + # Once the market weakens below the pause threshold, do not increase + # exposure on the existing position while it waits for TP or stop. + position = positions.get(symbol) + if position is not None: + position.averaging_frozen = True + elif change_24h > resume_above_24h_pct: + entry_allowed[symbol] = True + + def update_universe(symbol: str, stamp: int) -> None: + spans = universe_windows.get(symbol, []) if universe_windows else [] + index = window_cursor[symbol] + while index < len(spans) and spans[index][1] <= stamp: + index += 1 + window_cursor[symbol] = index + inside = index < len(spans) and spans[index][0] <= stamp < spans[index][1] + if not inside and entry_allowed[symbol]: + filter_triggered[symbol] = True + entry_allowed[symbol] = inside + position = positions.get(symbol) + if position is not None: + # Outside the selection the pair only manages its position (no averaging), + # and averaging resumes if the pair qualifies again — as in live rotation. + position.averaging_frozen = not inside + + for stamp, minute_candles in grouped: + if equity_stop["triggered"]: + break + if cancel(): + raise InterruptedError("Исторический прогон отменён") + last_stamp = stamp + for symbol, candle in minute_candles: + if equity_stop["triggered"]: + break + if trading_start_ms is None or stamp >= trading_start_ms: + processed_candles[symbol] += 1 + if universe_mode: + update_universe(symbol, stamp) + funded = positions.get(symbol) + if funded is not None and funding_by_symbol: + rate = funding_by_symbol.get(symbol, {}).get(stamp) + if rate: + payment = funded.qty * float(candle[1]) * rate + cash -= payment + funded.funding -= payment + funding_total["sum"] -= payment + funding_total["events"] += 1 + previous = previous_close.get(symbol) + if previous is None: + previous_close[symbol] = float(candle[4]) + update_entry_filter(symbol, stamp, float(candle[4])) + continue + _, open_price, high, low, close = candle[:5] + open_price, high, low, close = float(open_price), float(high), float(low), float(close) + if symbol not in positions: + allow_entry = entry_allowed[symbol] and (trading_start_ms is None or stamp >= trading_start_ms) + limit_full = max_open_positions is not None and len(positions) >= max_open_positions + if not allow_entry or limit_full: + # Fast path: without a position and with entries impossible this candle + # cannot change cash, equity or any position, so only the baseline moves. + if allow_entry and high >= strategy.entry_level(previous, strategies[symbol]["trigger"]): + risk["skipped_limit"] += 1 + previous_close[symbol] = close + update_entry_filter(symbol, stamp, close) + continue + marks[symbol] = open_price + handle_gap(symbol, open_price, stamp) + if mark_and_check_stop(symbol, open_price, stamp): + break + cfg = strategies[symbol] + entry_level = strategy.entry_level(previous, cfg["trigger"]) + armed = [True] + allow_entry = entry_allowed[symbol] and (trading_start_ms is None or stamp >= trading_start_ms) + if symbol not in positions and open_price >= entry_level: + if allow_entry: + open_position(symbol, open_price, stamp) + armed[0] = False + if mark_and_check_stop(symbol, open_price, stamp): + break + # Heuristic intrabar ordering from candle direction; OHLC cannot reveal the true path. + path = [open_price, low, high, close] if close >= open_price else [open_price, high, low, close] + for a, b in zip(path, path[1:]): + walk_segment(symbol, a, b, stamp, previous, armed, allow_entry) + if equity_stop["triggered"]: + break + previous_close[symbol] = close + if equity_stop["triggered"]: + break + update_entry_filter(symbol, stamp, close) + + end_stamp = int(equity_stop["timestamp"] if equity_stop["triggered"] else last_stamp) + open_rows = [] + open_net = 0.0 + for symbol, pos in positions.items(): + last_candle = candles_by_symbol[symbol][-1] + mark = marks.get(symbol, float(last_candle[4])) + gross = (mark - pos.entry_price) * pos.qty + estimated_exit_fee = mark * pos.qty * fee_pct / 100 + net = gross - pos.entry_fees - estimated_exit_fee + pos.funding + open_net += net + open_rows.append({ + "id": pos._trade_id, "symbol": symbol, "side": "LONG", + "opened_at": datetime.fromtimestamp(pos.opened_at / 1000, timezone.utc).isoformat(), + "closed_at": "", "entry": pos.entry_price, "exit": mark, + "entries": pos.add_count + 1, "margin": pos.margin, "funding_usdt": pos.funding, + "gross_usdt": gross, "fees_usdt": pos.entry_fees + estimated_exit_fee, + "net_usdt": net, "roi_pct": net / pos.margin * 100 if pos.margin else 0, + "hold_hours": (end_stamp - pos.opened_at) / 3_600_000, + "reason": ("Открытая позиция на момент остановки по порогу капитала; выходная комиссия оценена" + if equity_stop["triggered"] else + "Открытая позиция на конце периода; выходная комиссия оценена"), + "status": "OPEN", + }) + + realized = sum(row["net_usdt"] for row in closed) + equity_net = realized + open_net + wins = sum(row["net_usdt"] > 0 for row in closed) + all_rows = closed + open_rows + stops = sum(row["reason"].startswith("Стоп") for row in closed) + liquidations = sum(row["reason"].startswith("Ликвидация") for row in closed) + open_losing = sum(row["net_usdt"] < 0 for row in open_rows) + if universe_mode: + filter_text = ( + "Отбор валют как в реальном режиме: после каждого закрытого часа валюты ранжируются по " + f"обороту за 24 ч, из топ-{TOP_N_DEFAULT} входы разрешены тем, чей рост за 24 ч выше порога. " + "Вне отбора позиция только сопровождается до TP/стопа, доливки приостанавливаются." + ) + else: + filter_text = ( + f"При росте за 24 ч ниже {pause_below_24h_pct:g}% новые входы блокируются, а усреднение " + "открытых позиций замораживается до их закрытия по TP/стопу. Новые входы разрешаются снова " + f"только выше {resume_above_24h_pct:g}%." + ) + summary = { + "symbols": symbols, + "period_start_utc": datetime.fromtimestamp((trading_start_ms if trading_start_ms is not None else first_stamp) / 1000, timezone.utc).isoformat(), + "period_end_utc": datetime.fromtimestamp(end_stamp / 1000, timezone.utc).isoformat(), + "candles": processed_candles, + "warmup_candles": {symbol: sum(1 for row in candles_by_symbol[symbol] + if trading_start_ms is not None and int(row[0]) < trading_start_ms) + for symbol in symbols}, + "initial_capital": initial_capital, + "closed_trades": len(closed), + "wins": wins, + "losses": len(closed) - wins, + "win_rate_pct": wins / len(closed) * 100 if closed else 0.0, + "stops": stops, + "liquidations": liquidations, + "realized_net_usdt": realized, + "open_positions": len(open_rows), + "open_losing_positions": open_losing, + "open_net_estimate_usdt": open_net, + "total_net_including_open_usdt": equity_net, + "ending_equity_estimate": initial_capital + equity_net, + "max_drawdown_pct": risk["max_dd_pct"], + "max_drawdown_usdt": risk["max_dd_usdt"], + "min_equity_usdt": risk["min_equity"], + "peak_equity_usdt": risk["peak"], + "max_margin_used_usdt": risk["max_margin"], + "max_simultaneous_positions": risk["max_positions"], + "max_open_positions_limit": max_open_positions, + "skipped_entries_position_limit": risk["skipped_limit"], + "skipped_orders_margin": risk["skipped_margin"], + "longest_hold_hours": max((row["hold_hours"] for row in all_rows), default=0.0), + "universe_mode": universe_mode, + "equity_stop_pct": min_equity_pct, + "equity_stop_triggered": bool(equity_stop["triggered"]), + "equity_stop_value_usdt": equity_floor if min_equity_pct > 0 else None, + "equity_at_stop_usdt": equity_stop["equity"], + "return_pct": equity_net / initial_capital * 100 if initial_capital else 0.0, + "fees_usdt": sum(row["fees_usdt"] for row in closed) + sum(row["fees_usdt"] for row in open_rows), + "fee_pct_per_side": fee_pct, + "strategy_mode": strategy.STRATEGY_CLASSIC, + "strategy_title": strategy.STRATEGY_TITLES[strategy.STRATEGY_CLASSIC], + "funding_included": funding_by_symbol is not None, + "funding_usdt": funding_total["sum"], + "funding_events": funding_total["events"], + "entry_filter": filter_text, + "filter_was_triggered": filter_triggered, + "entry_allowed_at_end": {symbol: entry_allowed[symbol] for symbol in symbols}, + "assumptions": ( + ("Отбор валют повторяет автоподбор по часовым свечам (в реальном режиме скан каждые 10 мин). " + if universe_mode else + "Рост за 24 ч считается по минутным закрытиям относительно закрытия ровно 1440 минут назад; " + "порог фильтра обновляется после закрытия свечи и действует со следующей. ") + + "Прогон останавливается при падении капитала (баланс с учётом нереализованного P&L открытых " + "позиций и оценочной комиссии закрытия) до установленного порога; открытые позиции остаются в " + "отчёте по цене остановки. Минутные OHLC; внутри свечи путь O-L-H-C для зелёной и O-H-L-C для " + "красной свечи; разрывы цены на открытии свечи исполняются по цене открытия. Комиссия taker по " + "заданной ставке. При плече выше 1 моделируется ликвидация с потерей всей маржи позиции " + f"(ставка поддерживающей маржи {strategy.MAINTENANCE_MARGIN_RATE_PCT:g}%). " + + _funding_assumption(funding_by_symbol is not None) + + "Проскальзывание и очередь исполнения не моделируются. Общий капитал распределяется между " + "сигналами в пределах одной минуты в алфавитном порядке тикеров. Высокий процент прибыльных " + "сделок без стоп-лосса не означает отсутствия убытков: смотрите открытые позиции и максимальную просадку." + ), + } + return {"summary": summary, "trades": all_rows} + + +def _funding_assumption(included: bool) -> str: + if not included: + return "Funding не учитывается (выключен в настройках прогона). " + return ("Funding учитывается по истории ставок Bybit: в минуту расчёта открытая позиция платит " + "(LONG при положительной ставке) или получает (SHORT при положительной ставке) " + "объём × цена открытия минуты × ставка; сумма входит в Net сделки. ") + + +@dataclass +class ModePosition: + symbol: str + side: str + entry_price: float + qty: float + margin: float + entry_fees: float + opened_at: int + stop: float + atr: float + extreme: float + partial_target: float | None + final_target: float | None + leverage: float + trade_id: int + initial_margin: float = 0.0 + initial_stop: float = 0.0 + partial_done: bool = False + realized_gross: float = 0.0 + realized_fees: float = 0.0 + funding: float = 0.0 + + +def _hourly_btc_regime(btc_hourly: list[list[float]] | None, ema_period: int + ) -> tuple[list[int], list[bool | None]]: + """BTC regime per closed hour: (hour end times, close above EMA).""" + if not btc_hourly: + return [], [] + ends: list[int] = [] + regime: list[bool | None] = [] + alpha = 2 / (ema_period + 1) + seed: list[float] = [] + value: float | None = None + for row in btc_hourly: + close = float(row[4]) + if value is None: + seed.append(close) + if len(seed) == ema_period: + value = sum(seed) / ema_period + else: + value = alpha * close + (1 - alpha) * value + ends.append(int(row[0]) + 3_600_000) + regime.append(None if value is None else close > value) + return ends, regime + + +def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str, + params: dict[str, float], initial_capital: float, + fee_pct: float = TAKER_FEE_PCT, + cancel: Callable[[], bool] = lambda: False, + trading_start_ms: int | None = None, + min_growth_24h_pct: float | None = None, + min_equity_pct: float = 10.0, + max_open_positions: int | None = None, + universe_windows: dict[str, list[tuple[int, int]]] | None = None, + funding_by_symbol: dict[str, dict[int, float]] | None = None, + btc_hourly: list[list[float]] | None = None) -> dict: + """Replay minute bars for strategy mode A (breakout) or B (fade). + + Minute rows [start, o, h, l, c, turnover] are grouped into signal candles of + ``params["timeframe_min"]``. A signal is evaluated when its candle closes and stays valid + until the next candle closes; the entry fills at the open of a later minute (no look-ahead). + Exits share the simulation rules: stop, partial take-profit on R with breakeven, + ATR trailing stop, optional final target and maximum holding time. + Without ``universe_windows`` entries need the 24h growth above ``min_growth_24h_pct`` + (when given), measured on closed signal candles. + """ + if mode not in (strategy.STRATEGY_BREAKOUT, strategy.STRATEGY_FADE): + raise ValueError(f"Неизвестный режим стратегии: {mode}") + symbols = sorted(symbol for symbol, rows in candles_by_symbol.items() if rows) + if not symbols: + raise ValueError("Нет свечей для прогона") + universe_mode = universe_windows is not None + tf_ms = int(params["timeframe_min"]) * 60_000 + stake = initial_capital * params["stake_pct"] / 100 + leverage = params["leverage"] + bars_24h = strategy.bars_for_hours(24, params["timeframe_min"]) + history_len = max(strategy.required_bars(mode, params), bars_24h + 1) + 2 + btc_ends, btc_regime = _hourly_btc_regime(btc_hourly, int(params.get("btc_ema", 200))) + funding_stamps = {symbol: sorted((funding_by_symbol or {}).get(symbol, {})) + for symbol in symbols} + + def tagged(symbol: str): + for candle in candles_by_symbol[symbol]: + yield int(candle[0]), symbol, candle + + first_stamp = min(int(candles_by_symbol[symbol][0][0]) for symbol in symbols) + stream = heapq.merge(*(tagged(symbol) for symbol in symbols), key=lambda item: (item[0], item[1])) + grouped = ((stamp, [(symbol, candle) for _stamp, symbol, candle in items]) + for stamp, items in itertools.groupby(stream, key=lambda item: item[0])) + + positions: dict[str, ModePosition] = {} + marks: dict[str, float] = {} + history: dict[str, list[list[float]]] = {symbol: [] for symbol in symbols} + bucket: dict[str, list[float] | None] = {symbol: None for symbol in symbols} + pending: dict[str, tuple[dict, int, bool]] = {} # signal, valid-until ms, already counted as skipped + entry_allowed = {symbol: not universe_mode and min_growth_24h_pct is None for symbol in symbols} + filter_triggered = {symbol: False for symbol in symbols} + window_cursor = {symbol: 0 for symbol in symbols} + processed_candles = {symbol: 0 for symbol in symbols} + signals_total = {"count": 0, "rejected_at_fill": 0} + cash = float(initial_capital) + closed: list[dict] = [] + next_id = 1 + equity_floor = initial_capital * min_equity_pct / 100 if min_equity_pct > 0 else 0.0 + equity_stop: dict[str, object] = {"triggered": False, "timestamp": None, "equity": None} + risk = {"peak": float(initial_capital), "max_dd_usdt": 0.0, "max_dd_pct": 0.0, + "min_equity": float(initial_capital), "max_margin": 0.0, "max_positions": 0, + "skipped_limit": 0, "skipped_margin": 0} + funding_total = {"sum": 0.0, "events": 0} + last_stamp = first_stamp + + def iso(stamp: int) -> str: + return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat() + + def equity_at() -> float: + equity = cash + for position_symbol, pos in positions.items(): + mark = marks.get(position_symbol, pos.entry_price) + equity += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) + - mark * pos.qty * fee_pct / 100) + return equity + + def mark_and_check_stop(symbol: str, price: float, stamp: int) -> bool: + if equity_stop["triggered"]: + return True + marks[symbol] = price + equity = equity_at() + 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) + if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12): + equity_stop.update(triggered=True, timestamp=stamp, equity=equity) + return True + return False + + def free_margin() -> float: + return equity_at() - sum(pos.margin for pos in positions.values()) + + def funding_rate_pct_at(symbol: str, stamp: int) -> float | None: + stamps = funding_stamps.get(symbol) or [] + index = bisect.bisect_right(stamps, stamp) - 1 + if index < 0: + return None + return funding_by_symbol[symbol][stamps[index]] * 100 + + def btc_ok_at(stamp: int) -> bool | None: + index = bisect.bisect_right(btc_ends, stamp) - 1 + return btc_regime[index] if index >= 0 else None + + def open_position(symbol: str, signal: dict, price: float, stamp: int) -> str: + nonlocal cash, next_id + if max_open_positions is not None and len(positions) >= max_open_positions: + return "limit" + if stake > max(0.0, free_margin()): + return "margin" + plan = strategy.entry_plan(signal, price, params) + if plan is None: + return "invalid" + notional = stake * leverage + qty = notional / price + entry_fee = notional * fee_pct / 100 + cash -= entry_fee + positions[symbol] = ModePosition( + symbol, plan["side"], price, qty, stake, entry_fee, stamp, plan["stop"], plan["atr"], price, + plan["partial_target"], plan["final_target"], leverage, next_id, + initial_margin=stake, initial_stop=plan["stop"], + ) + next_id += 1 + risk["max_margin"] = max(risk["max_margin"], sum(p.margin for p in positions.values())) + risk["max_positions"] = max(risk["max_positions"], len(positions)) + return "opened" + + def row_for(pos: ModePosition, exit_price: float, stamp: int, gross: float, fees: float, + reason: str, status: str) -> dict: + net = gross - fees + pos.funding + return { + "id": pos.trade_id, "symbol": pos.symbol, "side": pos.side.upper(), "status": status, + "opened_at": iso(pos.opened_at), "closed_at": iso(stamp) if status == "CLOSED" else "", + "entry": pos.entry_price, "exit": exit_price, "entries": 1, + "margin": pos.initial_margin, "gross_usdt": gross, "fees_usdt": fees, + "funding_usdt": pos.funding, "net_usdt": net, + "roi_pct": net / pos.initial_margin * 100 if pos.initial_margin else 0.0, + "hold_hours": (stamp - pos.opened_at) / 3_600_000, "stop_initial": pos.initial_stop, + "reason": reason, + } + + def close_position(symbol: str, price: float, stamp: int, reason: str, liquidation: bool = False) -> None: + nonlocal cash + pos = positions.pop(symbol) + if liquidation: + gross_final, exit_fee = -pos.margin, 0.0 + else: + gross_final = strategy.unrealized_pnl(pos.side, pos.entry_price, price, pos.qty) + exit_fee = price * pos.qty * fee_pct / 100 + cash += gross_final - exit_fee + closed.append(row_for(pos, price, stamp, pos.realized_gross + gross_final, + pos.entry_fees + pos.realized_fees + exit_fee, reason, "CLOSED")) + pending.pop(symbol, None) + + def partial_close(pos: ModePosition, price: float) -> None: + nonlocal cash + fraction = min(1.0, params["partial_pct"] / 100) + qty = pos.qty * fraction + gross = strategy.unrealized_pnl(pos.side, pos.entry_price, price, qty) + fee = price * qty * fee_pct / 100 + cash += gross - fee + pos.realized_gross += gross + pos.realized_fees += fee + pos.qty -= qty + pos.margin *= 1 - fraction + pos.partial_done = True + if params["breakeven"] >= 1: + pos.stop = strategy.tighten_stop(pos.side, pos.stop, + strategy.breakeven_price(pos.side, pos.entry_price, fee_pct)) + + def stop_reason(pos: ModePosition) -> str: + if pos.stop != pos.initial_stop: + return "Стоп (трейлинг/безубыток)" + return "Стоп" + + def take_target(symbol: str, pos: ModePosition, level: float, stamp: int, gap: bool) -> bool: + """Apply the nearest profit target at ``level``; True when the position closed.""" + suffix = " (разрыв цены)" if gap else "" + if (not pos.partial_done and pos.partial_target is not None + and strategy.target_hit(pos.side, level, pos.partial_target)): + fill = level if gap else pos.partial_target + if params["partial_pct"] >= 100: + close_position(symbol, fill, stamp, f"Частичный TP 100% на {params['partial_r']:g}R{suffix}") + return True + partial_close(pos, fill) + return False + if strategy.target_hit(pos.side, level, pos.final_target): + fill = level if gap else pos.final_target + close_position(symbol, fill, stamp, f"TP на {params['take_profit_r']:g}R{suffix}") + return True + return False + + def handle_open(symbol: str, price: float, stamp: int) -> None: + pos = positions.get(symbol) + if pos is None: + return + liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side) + if liq is not None and strategy.stop_hit(pos.side, price, liq): + close_position(symbol, price, stamp, "Ликвидация (разрыв цены)", liquidation=True) + return + if strategy.stop_hit(pos.side, price, pos.stop): + close_position(symbol, price, stamp, stop_reason(pos) + " (разрыв цены)") + return + for _ in range(2): + pos = positions.get(symbol) + if pos is None or not (strategy.target_hit(pos.side, price, pos.partial_target if not pos.partial_done else None) + or strategy.target_hit(pos.side, price, pos.final_target)): + break + if take_target(symbol, pos, price, stamp, gap=True): + return + pos = positions.get(symbol) + if pos is not None and params["max_hold_hours"] > 0 \ + and stamp - pos.opened_at >= params["max_hold_hours"] * 3_600_000: + close_position(symbol, price, stamp, f"Время удержания {params['max_hold_hours']:g} ч") + + def walk(symbol: str, start: float, end: float, stamp: int) -> None: + pos = positions.get(symbol) + if pos is None or start == end: + mark_and_check_stop(symbol, end, stamp) + return + favourable = (end > start) == (pos.side == "long") + if favourable: + for _ in range(3): + pos = positions.get(symbol) + if pos is None: + break + targets = [t for t in ((pos.partial_target if not pos.partial_done else None), pos.final_target) + if t is not None and (start < t <= end if pos.side == "long" else end <= t < start)] + if not targets: + break + level = min(targets) if pos.side == "long" else max(targets) + marks[symbol] = level + if take_target(symbol, pos, level, stamp, gap=False): + break + pos = positions.get(symbol) + if pos is not None: + pos.extreme = max(pos.extreme, end) if pos.side == "long" else min(pos.extreme, end) + if strategy.trailing_active(pos.partial_done, params): + pos.stop = strategy.trailing_stop(pos.side, pos.stop, pos.extreme, pos.atr, params["trail_atr"]) + mark_and_check_stop(symbol, end, stamp) + return + liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side) + candidates = [] + lo, hi = min(start, end), max(start, end) + if lo <= pos.stop <= hi: + candidates.append((pos.stop, "STOP")) + if liq is not None and lo <= liq <= hi: + candidates.append((liq, "LIQ")) + if not candidates: + mark_and_check_stop(symbol, end, stamp) + return + # The first level crossed on the way from ``start`` is the nearest one. + level, event = min(candidates, key=lambda item: abs(item[0] - start)) + marks[symbol] = level + if event == "LIQ": + close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True) + else: + close_position(symbol, level, stamp, stop_reason(pos)) + mark_and_check_stop(symbol, end, stamp) + + def update_universe(symbol: str, stamp: int) -> None: + spans = universe_windows.get(symbol, []) if universe_windows else [] + index = window_cursor[symbol] + while index < len(spans) and spans[index][1] <= stamp: + index += 1 + window_cursor[symbol] = index + inside = index < len(spans) and spans[index][0] <= stamp < spans[index][1] + if not inside and entry_allowed[symbol]: + filter_triggered[symbol] = True + entry_allowed[symbol] = inside + + def close_bucket(symbol: str) -> None: + candle = bucket[symbol] + if candle is None: + return + rows = history[symbol] + rows.append(candle) + if len(rows) > history_len: + del rows[:len(rows) - history_len] + decided_at = int(candle[0]) + tf_ms + if not universe_mode and min_growth_24h_pct is not None and len(rows) > bars_24h: + day_ago = float(rows[-bars_24h - 1][4]) + if day_ago > 0: + allowed = (float(candle[4]) / day_ago - 1) * 100 > min_growth_24h_pct + if entry_allowed[symbol] and not allowed: + filter_triggered[symbol] = True + entry_allowed[symbol] = allowed + if symbol in positions: + return + signal = strategy.evaluate_signal(mode, rows, params, funding_rate_pct_at(symbol, decided_at), + btc_ok_at(decided_at)) + if signal is not None: + signals_total["count"] += 1 + pending[symbol] = (signal, decided_at + tf_ms, False) + + for stamp, minute_candles in grouped: + if equity_stop["triggered"]: + break + if cancel(): + raise InterruptedError("Исторический прогон отменён") + last_stamp = stamp + for symbol, candle in minute_candles: + if equity_stop["triggered"]: + break + trading = trading_start_ms is None or stamp >= trading_start_ms + if trading: + processed_candles[symbol] += 1 + if universe_mode: + update_universe(symbol, stamp) + open_price, high, low, close = (float(value) for value in candle[1:5]) + turnover = float(candle[5]) if len(candle) > 5 and candle[5] is not None else 0.0 + start = (stamp // tf_ms) * tf_ms + current = bucket[symbol] + if current is not None and int(current[0]) != start: + close_bucket(symbol) + current = None + if current is None: + bucket[symbol] = [start, open_price, high, low, close, turnover] + else: + current[2] = max(current[2], high) + current[3] = min(current[3], low) + current[4] = close + current[5] += turnover + pos = positions.get(symbol) + if pos is not None and funding_by_symbol: + rate = funding_by_symbol.get(symbol, {}).get(stamp) + if rate: + payment = -strategy.side_sign(pos.side) * pos.qty * open_price * rate + cash += payment + pos.funding += payment + funding_total["sum"] += payment + funding_total["events"] += 1 + if pos is None: + waiting = pending.get(symbol) + if waiting is not None and stamp >= waiting[1]: + pending.pop(symbol, None) + waiting = None + if waiting is None or not trading or not entry_allowed[symbol]: + marks[symbol] = close + continue + signal, valid_until, counted = waiting + outcome = open_position(symbol, signal, open_price, stamp) + if outcome in ("limit", "margin"): + if not counted: + risk["skipped_limit" if outcome == "limit" else "skipped_margin"] += 1 + pending[symbol] = (signal, valid_until, True) + marks[symbol] = close + continue + pending.pop(symbol, None) + if outcome == "invalid": + signals_total["rejected_at_fill"] += 1 + marks[symbol] = close + continue + else: + marks[symbol] = open_price + handle_open(symbol, open_price, stamp) + if mark_and_check_stop(symbol, open_price, stamp): + break + path = [open_price, low, high, close] if close >= open_price else [open_price, high, low, close] + for a, b in zip(path, path[1:]): + walk(symbol, a, b, stamp) + if equity_stop["triggered"]: + break + if equity_stop["triggered"]: + break + pos = positions.get(symbol) + if pos is not None and params["max_hold_hours"] > 0 \ + and stamp + 60_000 - pos.opened_at >= params["max_hold_hours"] * 3_600_000: + close_position(symbol, close, stamp + 60_000, f"Время удержания {params['max_hold_hours']:g} ч") + + end_stamp = int(equity_stop["timestamp"] if equity_stop["triggered"] else last_stamp) + open_rows = [] + for symbol, pos in positions.items(): + mark = marks.get(symbol, float(candles_by_symbol[symbol][-1][4])) + gross = pos.realized_gross + strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) + fees = pos.entry_fees + pos.realized_fees + mark * pos.qty * fee_pct / 100 + open_rows.append(row_for(pos, mark, end_stamp, gross, fees, + "Открытая позиция на момент остановки по порогу капитала; выходная комиссия оценена" + if equity_stop["triggered"] else + "Открытая позиция на конце периода; выходная комиссия оценена", "OPEN")) + realized = sum(row["net_usdt"] for row in closed) + open_net = sum(row["net_usdt"] for row in open_rows) + equity_net = realized + open_net + wins = sum(row["net_usdt"] > 0 for row in closed) + all_rows = closed + open_rows + gains = [row["net_usdt"] for row in closed if row["net_usdt"] > 0] + losses = [row["net_usdt"] for row in closed if row["net_usdt"] <= 0] + if universe_mode: + filter_text = ( + "Отбор валют как в реальном режиме: после каждого закрытого часа валюты ранжируются по " + f"обороту за 24 ч, из топ-{TOP_N_DEFAULT} сигналы режима разрешены тем, чей рост за 24 ч выше порога." + ) + elif min_growth_24h_pct is not None: + filter_text = f"Сигналы режима разрешены при росте за 24 ч выше {min_growth_24h_pct:g}%." + else: + filter_text = "Сигналы режима без дополнительного фильтра роста за 24 ч." + summary = { + "symbols": symbols, + "strategy_mode": mode, + "strategy_title": strategy.STRATEGY_TITLES[mode], + "strategy_params": dict(params), + "period_start_utc": iso(trading_start_ms if trading_start_ms is not None else first_stamp), + "period_end_utc": iso(end_stamp), + "candles": processed_candles, + "initial_capital": initial_capital, + "closed_trades": len(closed), + "wins": wins, + "losses": len(closed) - wins, + "win_rate_pct": wins / len(closed) * 100 if closed else 0.0, + "avg_win_usdt": sum(gains) / len(gains) if gains else 0.0, + "avg_loss_usdt": sum(losses) / len(losses) if losses else 0.0, + "profit_factor": (sum(gains) / -sum(losses)) if losses and sum(losses) < 0 else None, + "signals": signals_total["count"], + "signals_rejected_at_fill": signals_total["rejected_at_fill"], + "stops": sum(row["reason"].startswith("Стоп") for row in closed), + "liquidations": sum(row["reason"].startswith("Ликвидация") for row in closed), + "realized_net_usdt": realized, + "open_positions": len(open_rows), + "open_losing_positions": sum(row["net_usdt"] < 0 for row in open_rows), + "open_net_estimate_usdt": open_net, + "total_net_including_open_usdt": equity_net, + "ending_equity_estimate": initial_capital + equity_net, + "max_drawdown_pct": risk["max_dd_pct"], + "max_drawdown_usdt": risk["max_dd_usdt"], + "min_equity_usdt": risk["min_equity"], + "peak_equity_usdt": risk["peak"], + "max_margin_used_usdt": risk["max_margin"], + "max_simultaneous_positions": risk["max_positions"], + "max_open_positions_limit": max_open_positions, + "skipped_entries_position_limit": risk["skipped_limit"], + "skipped_orders_margin": risk["skipped_margin"], + "longest_hold_hours": max((row["hold_hours"] for row in all_rows), default=0.0), + "universe_mode": universe_mode, + "equity_stop_pct": min_equity_pct, + "equity_stop_triggered": bool(equity_stop["triggered"]), + "equity_stop_value_usdt": equity_floor if min_equity_pct > 0 else None, + "equity_at_stop_usdt": equity_stop["equity"], + "return_pct": equity_net / initial_capital * 100 if initial_capital else 0.0, + "fees_usdt": sum(row["fees_usdt"] for row in all_rows), + "fee_pct_per_side": fee_pct, + "funding_included": funding_by_symbol is not None, + "funding_usdt": funding_total["sum"], + "funding_events": funding_total["events"], + "entry_filter": filter_text, + "filter_was_triggered": filter_triggered, + "entry_allowed_at_end": dict(entry_allowed), + "assumptions": ( + f"Режим {strategy.STRATEGY_TITLES[mode]}. Сигнальные свечи {int(params['timeframe_min'])} мин " + "собираются из минутных; сигнал считается после закрытия свечи и действует до закрытия следующей, " + "вход — по цене открытия минуты (без заглядывания вперёд). Внутри минуты путь O-L-H-C для зелёной и " + "O-H-L-C для красной свечи; разрывы на открытии исполняются по цене открытия; частичный TP и " + "финальный TP — по своему уровню, стоп — по уровню стопа. " + + ("Фильтр BTC: закрытие часа BTCUSDT выше EMA. " if mode == strategy.STRATEGY_BREAKOUT + and params.get("btc_filter", 0) >= 1 else "") + + "Funding-фильтр сигнала использует последнюю расчётную ставку на момент закрытия свечи. " + + _funding_assumption(funding_by_symbol is not None) + + f"Комиссия taker {fee_pct:g}% за сторону. Ликвидация при плече выше 1 (у SHORT и при 1x) " + f"с потерей маржи позиции, поддерживающая маржа {strategy.MAINTENANCE_MARGIN_RATE_PCT:g}%. " + "Проскальзывание не моделируется. Капитал распределяется между сигналами одной минуты в " + "алфавитном порядке тикеров." + ), + } + return {"summary": summary, "trades": all_rows} + + +def save_report(result: dict, output_dir: Path) -> tuple[Path, Path]: + output_dir.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + csv_path = output_dir / f"backtest_{stamp}.csv" + json_path = output_dir / f"backtest_{stamp}.json" + columns = ["id", "symbol", "side", "status", "opened_at", "closed_at", "entry", "exit", "entries", + "margin", "gross_usdt", "fees_usdt", "funding_usdt", "net_usdt", "roi_pct", "hold_hours", + "reason"] + with csv_path.open("w", encoding="utf-8-sig", newline="") as file: + writer = csv.DictWriter(file, fieldnames=columns, extrasaction="ignore") + writer.writeheader() + writer.writerows(result["trades"]) + json_path.write_text(json.dumps(result["summary"], ensure_ascii=False, indent=2), encoding="utf-8") + return csv_path, json_path diff --git a/keystore.py b/keystore.py new file mode 100644 index 0000000..c23b157 --- /dev/null +++ b/keystore.py @@ -0,0 +1,108 @@ +"""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 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"} +_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: + 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: + 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 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(exist_ok=True) + tmp = path.with_suffix(".tmp") + tmp.write_bytes(protect(json.dumps(data).encode("utf-8"))) + tmp.replace(path) + + +def set_keys(exchange: str, api_key: str, api_secret: str, path: Path | None = None) -> str: + if exchange not in EXCHANGES: + return "неизвестная биржа" + api_key, api_secret = (api_key or "").strip(), (api_secret or "").strip() + if not api_key or not api_secret: + return "нужны и API key, и secret" + if len(api_key) > 200 or len(api_secret) > 400 or any(c.isspace() for c in api_key + api_secret): + return "ключ выглядит неверно (пробелы или слишком длинный)" + with _lock: + data = load(path) + data[exchange] = {"key": api_key, "secret": api_secret} + _save(data, path or KEYS_FILE) + return "" + + +def delete_keys(exchange: str, path: Path | None = None) -> None: + with _lock: + data = load(path) + if data.pop(exchange, None) is not None: + _save(data, path or KEYS_FILE) + + +def get(exchange: str, path: Path | None = None) -> tuple[str, str] | None: + d = load(path).get(exchange) + return (d["key"], d["secret"]) if d and d.get("key") and d.get("secret") else None + + +def mask(key: str) -> str: + return key[:4] + "…" + key[-4:] if len(key) > 10 else "…" + key[-2:] + + +def summary(path: Path | None = None) -> dict[str, dict]: + """What the page may see: whether keys are set and a masked key — never the secret.""" + data = load(path) + return {ex: {"name": name, "set": ex in data, "key": mask(data[ex]["key"]) if ex in data else ""} + for ex, name in EXCHANGES.items()} diff --git a/lead_window.py b/lead_window.py new file mode 100644 index 0000000..9178fd8 --- /dev/null +++ b/lead_window.py @@ -0,0 +1,696 @@ +"""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.ROOT / "lead_paper_state.json" +TRADES_FILE = sp.ROOT / "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 фьючерс", "binance": "Binance фьючерс", "mexc": "MEXC фьючерс"} + + +CONNECTIONS_FILE = sp.ROOT / "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", + "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", "binance": "Binance", "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.ROOT / "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 not any(same_connection(c, r) for r in removed)] + for c in DEFAULT_CONNECTIONS: + if not any(same_connection(c, s) for s in out) and not any(same_connection(c, r) for r in removed): + out.append(dict(c)) + return out + + +def remove_connection(conn: dict, path=None, removed_path=None) -> None: + """Delete a connection on the user's request: out of the list, and remembered as removed so neither the + built-in defaults nor the autonomous search bring it back (adding it again by hand undoes this).""" + path, removed_path = path or CONNECTIONS_FILE, removed_path or REMOVED_FILE + _write_list(path, [c for c in _read_list(path) if not same_connection(c, conn)]) + removed = _read_list(removed_path) + if not any(same_connection(conn, r) for r in removed): + removed.append({k: conn[k] for k in CONNECTION_KEYS}) + _write_list(removed_path, removed) + + +def unremove_connection(conn: dict, removed_path=None) -> None: + removed_path = removed_path or REMOVED_FILE + removed = _read_list(removed_path) + keep = [r for r in removed if not same_connection(conn, r)] + if len(keep) != len(removed): + _write_list(removed_path, keep) + + +def remember_connection(connections: list[dict], current: dict, path=None) -> list[dict]: + """Add the current connection to the list (if new) and save; nothing is ever removed. The file is re-read + first, so connections added meanwhile by the autonomous search (meme_matcher/autoscan.py) are kept.""" + current = {k: current[k] for k in CONNECTION_KEYS} + if path is None: + unremove_connection(current) # picked again by hand: no longer deleted + for c in load_connections(path): + if not any(same_connection(c, x) for x in connections): + connections.append(c) + if not any(same_connection(current, c) for c in connections): + connections.append(current) + try: + (path or CONNECTIONS_FILE).write_text(json.dumps(connections, ensure_ascii=False, indent=2), encoding="utf-8") + except OSError: + pass + return connections + + +def futures_ticker(ticker: str, exchange: str) -> str: + """SI_USDT on MEXC, SIUSDT on Bybit / Binance.""" + t = ticker.strip().upper().replace("-", "") + base = t.removesuffix("_USDT").removesuffix("USDT") + return f"{base}_USDT" if exchange == "mexc" else f"{base}USDT" + + +def kucoin_ticker(ticker: str, market: str) -> str: + """MARSCOINUSDTM (futures) ↔ MARSCOIN-USDT (spot).""" + t = ticker.strip().upper() + base = t.removesuffix("-USDT") if t.endswith("-USDT") else t.removesuffix("USDTM").removesuffix("USDT") + return f"{base}-USDT" if market == "spot" else f"{base}USDTM" + + +def validate(values: dict[str, float]) -> str: + if values["stake"] <= 0 or values["budget"] <= 0 or not 1 <= values["leverage"] <= 100: + return "ставка и бюджет больше 0, плечо от 1 до 100" + if values["min_target_pct"] <= 0 or values["stop_loss_pct"] <= 0: + return "тейк-профит и стоп-лосс больше 0" + if values["max_hold_seconds"] <= 0 or values["cooldown_ms"] < 0: + return "удержание больше 0, пауза не меньше 0" + if values["lead_threshold_pct"] <= 0 or values["lead_window_ms"] < 50: + return "порог больше 0, окно не меньше 50 мс" + if values["vector_window_seconds"] <= 0 or values["vector_min_move_pct"] < 0: + return "окно вектора больше 0, мин. движение не меньше 0" + if values["max_positions"] < 1 or values["max_positions"] != int(values["max_positions"]) \ + or values["entry_gap_seconds"] < 0: + return "позиций одновременно — целое число от 1, интервал между входами не меньше 0" + if not 0 <= values["min_confidence"] <= 1: + return "мин. уверенность от 0 до 1 (0 — не проверять)" + if not 0 < values["auto_tp_share_pct"] <= 300 or values["auto_tp_horizon_seconds"] <= 0: + return "доля догоняния от 0 до 300%, горизонт прогноза больше 0" + if values.get("basis_entry_z", 2) <= 0 or values.get("basis_min_gap_pct", 0.15) < 0 \ + or values.get("basis_window_seconds", 60) < 5 or values.get("basis_exit_z", 0.5) < 0 \ + or values.get("basis_exit_z", 0.5) >= values.get("basis_entry_z", 2): + return "разрыв: вход больше 0σ и больше выхода, мин. разрыв ≥ 0, окно не меньше 5 с" + return "" + + +def run() -> None: + import tkinter as tk + from tkinter import ttk + + settings = sp.PaperSettings(mode="lead") + first_run = not STATE_FILE.exists() + paper = sp.PaperTrader(settings, sh.HintSettings(), STATE_FILE, TRADES_FILE) + if first_run: + inherit_settings(paper) + try: + saved = json.loads(STATE_FILE.read_text(encoding="utf-8")).get("settings", {}) + except (OSError, ValueError): + saved = {} + if "cooldown_ms" not in saved: + settings.cooldown_ms = settings.cooldown_seconds * 1000 # the pause used to be in seconds + paper.set_mode(settings.mode if settings.mode in MODES else "lead") + paper.policy = paper._make_policy() + ps = paper.settings + events: queue.Queue = queue.Queue() + book = sh.OrderBook() + state = {"leader_feed": None, "follower_feed": None, "recorder": None, "tick": 0.0, "leader": None, + "leader_status": "KuCoin: подключаюсь…", "follower_status": "Bybit: подключаюсь…", + "last_leader": 0.0, "last_follower": 0.0} + lat_follow: deque[float] = deque(maxlen=200) + lat_lead: deque[float] = deque(maxlen=200) + + root = tk.Tk() + root.title("Ведущая биржа → тестовые ставки на фьючерсе") + root.geometry("1080x860") + body = ttk.Frame(root, padding=10) + body.pack(fill="both", expand=True) + header = tk.StringVar() + ttk.Label(body, textvariable=header, font=("Segoe UI", 10, "bold"), wraplength=940).pack(anchor="w") + + panel = ttk.LabelFrame(body, text="Цены сейчас", padding=6) + panel.pack(fill="x", pady=(6, 4)) + lead_var, follow_var, signal_var = tk.StringVar(), tk.StringVar(), tk.StringVar() + for var in (lead_var, follow_var): + ttk.Label(panel, textvariable=var, font=("Consolas", 11)).pack(anchor="w") + signal_label = tk.Label(panel, textvariable=signal_var, font=("Segoe UI", 13, "bold"), anchor="w") + signal_label.pack(fill="x", pady=(4, 0)) + bar = tk.Canvas(panel, height=16, width=600, highlightthickness=0, background="#e8e8e8") + bar.pack(anchor="w", pady=(2, 0)) + + box = ttk.LabelFrame(body, text="Тестовые сделки на Bybit (виртуальный счёт, ордера на биржу не уходят)", + padding=6) + box.pack(fill="both", expand=True, pady=(4, 0)) + connections = load_connections() + conn_row = ttk.Frame(box) + conn_row.pack(fill="x", pady=(0, 4)) + ttk.Label(conn_row, text="Подключение:").pack(side="left") + conn_var = tk.StringVar() + conn_combo = ttk.Combobox(conn_row, textvariable=conn_var, state="readonly", width=90) + conn_combo.pack(side="left", padx=6) + ttk.Label(conn_row, text="(новые добавляются сами при «Применить», старые не удаляются)", + foreground="#777").pack(side="left") + + def show_connections() -> None: + conn_combo.configure(values=[connection_name(c) for c in connections]) + current = {k: getattr(ps, k) for k in CONNECTION_KEYS} + match = next((c for c in connections if same_connection(c, current)), None) + conn_var.set(connection_name(match) if match else "") + + def on_connection(_event=None) -> None: + c = next((c for c in connections if connection_name(c) == conn_var.get()), None) + if c is None: + return + market_var.set(LEAD_MARKETS[c["lead_market"]]) + follow_ex_var.set(FOLLOW_EXCHANGES[c["follow_exchange"]]) + for key in ("lead_ticker", "lead_pool", "follow_ticker"): + vars_[key].set(c[key]) + apply() + + conn_combo.bind("<>", on_connection) + mode_row = ttk.Frame(box) + mode_row.pack(fill="x", pady=(0, 4)) + ttk.Label(mode_row, text="Режим:").pack(side="left") + mode_var = tk.StringVar(value=MODES[ps.mode]) + mode_combo = ttk.Combobox(mode_row, textvariable=mode_var, values=list(MODES.values()), state="readonly", + width=58) + mode_combo.pack(side="left", padx=6) + ttk.Label(mode_row, text=" Ведущая:").pack(side="left") + market_var = tk.StringVar(value=LEAD_MARKETS.get(ps.lead_market, LEAD_MARKETS["futures"])) + market_combo = ttk.Combobox(mode_row, textvariable=market_var, values=list(LEAD_MARKETS.values()), + state="readonly", width=16) + market_combo.pack(side="left", padx=6) + + ttk.Label(mode_row, text=" Ставки на:").pack(side="left") + follow_ex_var = tk.StringVar(value=FOLLOW_EXCHANGES.get(ps.follow_exchange, FOLLOW_EXCHANGES["bybit"])) + follow_combo = ttk.Combobox(mode_row, textvariable=follow_ex_var, values=list(FOLLOW_EXCHANGES.values()), + state="readonly", width=16) + follow_combo.pack(side="left", padx=6) + + def on_market(_event=None) -> None: + market = next(k for k, v in LEAD_MARKETS.items() if v == market_var.get()) + if market in ("futures", "spot"): + vars_["lead_ticker"].set(kucoin_ticker(vars_["lead_ticker"].get(), market)) + apply() + + market_combo.bind("<>", on_market) + follow_combo.bind("<>", lambda _e: apply()) + form = ttk.Frame(box) + form.pack(fill="x") + vars_: dict[str, tk.StringVar] = {} + mode_cells: dict[str, list] = {m: [] for m in MODES} + + def add_field(key: str, label: str, row: int, column: int): + cell = ttk.Frame(form) + cell.grid(row=row, column=column, sticky="w", padx=(0, 8), pady=(0, 4)) + ttk.Label(cell, text=label).pack(anchor="w") + value = getattr(ps, key) + var = tk.StringVar(value=value if isinstance(value, str) else f"{value:g}") + ttk.Entry(cell, textvariable=var, width=16 if isinstance(value, str) else 12).pack(anchor="w") + vars_[key] = var + return cell + + for i, (key, label) in enumerate(COMMON_FIELDS): + add_field(key, label, i // 6, i % 6) + mode_row_index = (len(COMMON_FIELDS) + 5) // 6 + for mode, items in MODE_FIELDS.items(): + for i, (key, label) in enumerate(items): + mode_cells[mode].append(add_field(key, label, mode_row_index, i)) + for i, (key, label) in enumerate(TEXT_FIELDS): + add_field(key, label, mode_row_index, 2 + i) + auto_var = tk.BooleanVar(value=ps.auto_tp) + learn_var = tk.BooleanVar(value=ps.auto_tp_learn) + auto_cell = ttk.Frame(form) + auto_cell.grid(row=mode_row_index + 1, column=0, columnspan=2, sticky="w", pady=(0, 4)) + ttk.Checkbutton(auto_cell, text="Авто тейк-профит по прогнозу:\nтейк = доля × отставание фьючерса от ведущей", + variable=auto_var, command=lambda: apply()).pack(anchor="w") + for i, (key, label) in enumerate(AUTO_FIELDS): + add_field(key, label, mode_row_index + 1, 2 + i) + learn_cell = ttk.Frame(form) + learn_cell.grid(row=mode_row_index + 1, column=4, columnspan=2, sticky="w", pady=(0, 4)) + ttk.Checkbutton(learn_cell, text="Учить долю на истории сигналов\n(после 10 сигналов — вместо ручной)", + variable=learn_var, command=lambda: apply()).pack(anchor="w") + + def current_mode() -> str: + return next(k for k, v in MODES.items() if v == mode_var.get()) + + def show_mode_fields() -> None: + for mode, cells in mode_cells.items(): + for cell in cells: + cell.grid() if mode == current_mode() else cell.grid_remove() + + def on_mode(_event=None) -> None: + show_mode_fields() + apply() + + mode_combo.bind("<>", on_mode) + show_mode_fields() + actions = ttk.Frame(box) + actions.pack(fill="x", pady=(2, 2)) + enabled_var = tk.BooleanVar(value=ps.enabled) + start_btn = tk.Button(actions, text="▶ Старт", width=9, command=lambda: set_trading(True)) + start_btn.pack(side="left") + stop_btn = tk.Button(actions, text="■ Стоп", width=9, command=lambda: set_trading(False)) + stop_btn.pack(side="left", padx=(4, 0)) + trading_label = tk.Label(actions, text="", font=("Segoe UI", 9, "bold")) + trading_label.pack(side="left", padx=8) + + def show_trading() -> None: + on = ps.enabled + start_btn.configure(state="disabled" if on else "normal", bg="#d8f0dc" if on else "SystemButtonFace") + stop_btn.configure(state="normal" if on else "disabled", bg="SystemButtonFace" if on else "#f6d6d6") + trading_label.configure(text="Сделки открываются" if on else + "Новые сделки остановлены · цены, сравнение и прогноз продолжают работать", + fg="#1f8a4c" if on else "#c23b3b") + + def set_trading(on: bool) -> None: + """Start/stop opening new paper positions only; the feeds, the comparison, the forecast learning and the + exits of positions already open keep running.""" + enabled_var.set(on) + ps.enabled = on + paper.ledger.save() + show_trading() + message.set("Старт: новые сделки открываются" if on else + "Стоп: новые сделки не открываются; открытые позиции закроются по тейку, стопу или времени") + + ttk.Button(actions, text="Применить", command=lambda: apply()).pack(side="left", padx=6) + ttk.Button(actions, text="Закрыть позицию", command=lambda: paper.close_now(book, time.time(), "вручную")).pack( + side="left") + ttk.Button(actions, text="Сбросить счёт", command=lambda: reset()).pack(side="left", padx=6) + cut_row = ttk.Frame(box) + cut_row.pack(fill="x", pady=(0, 2)) + cut_var = tk.BooleanVar(value=ps.cut_loss) + ttk.Checkbutton(cut_row, text="Сразу закрывать, если ушло в минус на", variable=cut_var, + command=lambda: apply()).pack(side="left") + cut_ticks_var = tk.StringVar(value=str(ps.cut_loss_ticks)) + ttk.Entry(cut_row, textvariable=cut_ticks_var, width=4).pack(side="left", padx=4) + ttk.Label(cut_row, text="шаг(а) цены (середина Bybit против цены при входе) — и сразу брать следующий сигнал " + "без паузы").pack(side="left") + tick_row = ttk.Frame(box) + tick_row.pack(fill="x", pady=(0, 2)) + one_tick_var = tk.BooleanVar(value=ps.one_per_tick) + ttk.Checkbutton(tick_row, text="Не больше одной позиции на один шаг цены Bybit (в каждую сторону); всего " + "параллельно — до «Позиций одновременно»", variable=one_tick_var, + command=lambda: apply()).pack(side="left") + record_var = tk.BooleanVar(value=True) + ttk.Checkbutton(actions, text=f"Записывать поток в {sp.RECORD_DIR.name}\\", variable=record_var).pack( + side="left", padx=10) + summary, status, position, message = (tk.StringVar() for _ in range(4)) + ttk.Label(box, textvariable=summary, font=("Segoe UI", 10, "bold")).pack(anchor="w") + ttk.Label(box, textvariable=status, foreground="#1d4f91", wraplength=940).pack(anchor="w") + ttk.Label(box, textvariable=position, wraplength=940).pack(anchor="w") + ttk.Label(box, textvariable=message, foreground="#555", wraplength=940).pack(anchor="w") + columns = ("time", "ticker", "side", "qty", "usd", "entry", "exit", "pct", "net", "fee", "reason", "hold", "why") + heads = {"time": "Закрыта (UTC)", "ticker": "Тикер", "side": "Напр.", "qty": "Объём", "usd": "Объём в $", + "entry": "Цена откр.", "exit": "Цена закр.", "pct": "Процент", "net": "Чистая, $", "fee": "Комиссия, $", + "reason": "Причина", "hold": "Сек.", "why": "Почему вошли"} + widths = {"time": 115, "ticker": 95, "side": 45, "qty": 65, "usd": 60, "entry": 75, "exit": 75, "pct": 60, + "net": 70, "fee": 65, "reason": 60, "hold": 40, "why": 200} + table = ttk.Frame(box) + table.pack(fill="both", expand=True, pady=(4, 0)) + tree = ttk.Treeview(table, columns=columns, show="headings", height=10) + for col in columns: + tree.heading(col, text=heads[col]) + tree.column(col, width=widths[col], anchor="center") + tree.tag_configure("win", foreground="#13843b") + tree.tag_configure("loss", foreground="#c62828") + scroll = ttk.Scrollbar(table, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scroll.set) + tree.pack(side="left", fill="both", expand=True) + scroll.pack(side="right", fill="y") + shown = {"count": -1} + + def start_feeds() -> None: + for key in ("leader_feed", "follower_feed"): + if state[key]: + state[key].stop() + if state["recorder"]: + state["recorder"].close() + state["recorder"] = None + book.clear() + lat_follow.clear() + lat_lead.clear() + state["leader"] = None + paper.policy = paper._make_policy() + if ps.follow_exchange == "mexc": + state["tick"], size = sh.mexc_contract(ps.follow_ticker) + state["follower_feed"] = sh.MexcFeed(ps.follow_ticker, events, size) + 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) + if state["tick"] <= 0: + message.set(f"{FOLLOW_EXCHANGES[ps.follow_exchange]}: нет тикера {ps.follow_ticker} — проверьте настройку") + state["follower_status"] = f"{FOLLOW_EXCHANGES[ps.follow_exchange]}: подключаюсь…" + if ps.lead_market == "raydium": + if not ps.lead_pool: + message.set("Укажите адрес пула Raydium (например, из Meme Matcher)") + state["leader_feed"] = None + else: + state["leader_feed"] = sh.RaydiumFeed(ps.lead_pool, events) + else: + state["leader_feed"] = sh.KucoinFeed(ps.lead_ticker, events, spot=ps.lead_market == "spot") + state["leader_status"] = f"{LEAD_MARKETS[ps.lead_market]}: подключаюсь…" + state["follower_feed"].start() + if state["leader_feed"]: + state["leader_feed"].start() + + def apply() -> None: + try: + values = {key: float(vars_[key].get().replace(",", ".")) for key, _ in FIELDS} + except ValueError: + message.set("Проверьте настройки: нужны числа") + return + problem = validate(values) + try: + cut_ticks = int(cut_ticks_var.get()) + if cut_ticks < 1: + raise ValueError + except ValueError: + problem = problem or "минус для закрытия — целое число шагов, не меньше 1" + if problem: + message.set(f"Проверьте настройки: {problem}") + return + ps.cut_loss = bool(cut_var.get()) + ps.one_per_tick = bool(one_tick_var.get()) + ps.auto_tp = bool(auto_var.get()) + ps.auto_tp_learn = bool(learn_var.get()) + ps.cut_loss_ticks = cut_ticks + # tickers upper case; a Solana pool address is case-sensitive + tickers = {key: vars_[key].get().strip() if key == "lead_pool" else vars_[key].get().strip().upper() + for key, _ in TEXT_FIELDS} + budget_changed = values["budget"] != ps.budget + for key, value in values.items(): + setattr(ps, key, int(value) if key in INT_FIELDS else value) + ps.enabled = bool(enabled_var.get()) + market = next(k for k, v in LEAD_MARKETS.items() if v == market_var.get()) + follow = next(k for k, v in FOLLOW_EXCHANGES.items() if v == follow_ex_var.get()) + tickers["follow_ticker"] = futures_ticker(tickers["follow_ticker"], follow) + vars_["follow_ticker"].set(tickers["follow_ticker"]) + if market in ("futures", "spot"): + tickers["lead_ticker"] = kucoin_ticker(tickers["lead_ticker"], market) + vars_["lead_ticker"].set(tickers["lead_ticker"]) + restart = (tickers["lead_ticker"] != ps.lead_ticker or tickers["follow_ticker"] != ps.follow_ticker + or tickers["lead_pool"] != ps.lead_pool or market != ps.lead_market + or follow != ps.follow_exchange) + if restart: + paper.close_now(book, time.time(), "смена тикера") + ps.lead_ticker, ps.follow_ticker = tickers["lead_ticker"], tickers["follow_ticker"] + ps.lead_pool, ps.lead_market, ps.follow_exchange = tickers["lead_pool"], market, follow + if budget_changed and not paper.trades and paper.position is None: + paper.ledger.balance = ps.budget + mode = current_mode() + if mode != ps.mode: + paper.close_now(book, time.time(), "смена режима") + paper.set_mode(mode) # the new policy gathers its own window of prices first + paper.ledger.save() + remember_connection(connections, {k: getattr(ps, k) for k in CONNECTION_KEYS}) + show_connections() + if restart: + start_feeds() + message.set("Настройки применены" + (" · новый бюджет начнёт действовать после «Сбросить счёт»" + if budget_changed and (paper.trades or paper.position) else "")) + + def reset() -> None: + apply() + paper.reset() + shown["count"] = -1 + message.set(f"Счёт сброшен: {ps.budget:g}$") + + def pump() -> None: + if record_var.get() and state["recorder"] is None and state["tick"] > 0: + try: + state["recorder"] = sp.Recorder(ps.follow_ticker, 111 if ps.follow_exchange == "bybit" else 0, + state["tick"]) + except OSError: + pass + recorder = state["recorder"] if record_var.get() else None + for _ in range(5000): + try: + kind, data = events.get_nowait() + except queue.Empty: + break + now = time.time() + if kind == "book_snapshot": + book.apply_snapshot(data) + state["last_follower"] = now + if recorder: + recorder.write("S", {"asks": data.get("asks", []), "bids": data.get("bids", [])}, now) + paper.on_book(now, book, state["tick"]) + elif kind == "book_update": + book.apply_updates(data) + state["last_follower"] = now + if recorder: + recorder.write("U", data, now) + paper.on_book(now, book, state["tick"]) + elif kind == "trades": + if recorder: + recorder.write("T", data, now) + for raw in data: + try: + trade = sh.Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) + except (KeyError, TypeError, ValueError): + continue + paper.on_trade(trade) + elif kind == "leader": + bid, ask = data + state["leader"] = (bid, ask) + state["last_leader"] = now + if recorder: + recorder.write("L", [bid, ask], now) + paper.on_leader(now, bid, ask) + elif kind == "latency": + lat_follow.append(float(data)) + elif kind == "leader_latency": + lat_lead.append(float(data)) + elif kind == "status": + state["follower_status"] = data + elif kind == "leader_status": + state["leader_status"] = data + root.after(50, pump) + + def threshold() -> float: + return ps.vector_min_move_pct if ps.mode == "vector" else ps.lead_threshold_pct + + def draw_signal(value: float) -> None: + bar.delete("all") + width, mid = 600, 300 + thr = threshold() + scale = mid / max(thr * 3, 0.01) + x = mid + max(-mid, min(mid, value * scale)) + bar.create_rectangle(min(mid, x), 3, max(mid, x), 13, fill="#2e9d57" if value >= 0 else "#d04a4a", + outline="") + for t in (thr, -thr): + tx = mid + t * scale + bar.create_line(tx, 0, tx, 16, fill="#333", dash=(2, 2)) + bar.create_line(mid, 0, mid, 16, fill="#999") + + def refresh() -> None: + now = time.time() + lf = f" · задержка ~{statistics.median(lat_follow):.0f} мс" if len(lat_follow) >= 5 else "" + ll = f" · задержка ~{statistics.median(lat_lead):.0f} мс" if len(lat_lead) >= 5 else "" + header.set(f"{state['leader_status']}{ll} | {state['follower_status']}{lf}") + pol = paper.policy + if state["leader"]: + bid, ask = state["leader"] + age = (now - state["last_leader"]) * 1000 + if ps.lead_market == "raydium": + lead_var.set(f"{pol.L:8s} пул {ps.lead_pool[:10]}… цена {bid:<12.10g} (по последнему обмену) · " + f"{age:.0f} мс назад") + else: + lead_var.set(f"{pol.L:8s} {ps.lead_ticker:16s} bid {bid:<12.10g} ask {ask:<12.10g} mid " + f"{(bid + ask) / 2:<12.10g} спред {(ask - bid) / ((bid + ask) / 2) * 100:.3f}% · " + f"{age:.0f} мс назад") + best_bid, best_ask = book.best() + if best_bid and best_ask: + age = (now - state["last_follower"]) * 1000 + follow_var.set(f"{pol.F:8s} {ps.follow_ticker:16s} bid {best_bid:<12.10g} ask {best_ask:<12.10g} mid " + f"{(best_bid + best_ask) / 2:<12.10g} спред {(best_ask - best_bid) / ((best_ask + best_bid) / 2) * 100:.3f}%" + f" · {age:.0f} мс назад") + sig = getattr(pol, "signal", 0.0) + thr = threshold() + if ps.mode == "vector": + active = f"{'LONG' if sig > 0 else 'SHORT'}: {pol.L} {'растёт' if sig > 0 else 'падает'} " \ + f"{sig:+.3f}% за {ps.vector_window_seconds:g} с" + idle = f"Ждём направление: {pol.L} {sig:+.3f}% за {ps.vector_window_seconds:g} с (порог ±{thr:g}%)" + else: + active = f"{'LONG' if sig > 0 else 'SHORT'}: {pol.F} отстаёт от {pol.L} на {sig:+.3f}%" + idle = f"Ждём: отставание {sig:+.3f}% (порог ±{thr:g}%)" + conf = getattr(pol, "conf", 0.0) + conf_text = f" · уверенность {conf:.2f} (порог {ps.min_confidence:g})" + active += conf_text + idle += conf_text + if abs(sig) >= thr and thr > 0 and conf >= ps.min_confidence: + signal_var.set(active) + signal_label.configure(fg="#1f8a4c" if sig > 0 else "#c23b3b") + else: + signal_var.set(idle) + signal_label.configure(fg="#666") + draw_signal(sig) + status.set(pol.status) + positions = paper.ledger.positions + if positions: + best_bid, best_ask = book.best() + lines = [f"Открыто позиций: {len(positions)} из {ps.max_positions} · вместе сейчас " + f"{paper.unrealized(book):+.4f}$"] + for pos in positions[:8]: + price = best_bid if pos.side == "LONG" else best_ask + pnl = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty if price else 0.0 + lines.append(f" {pos.side} {pos.qty:.6g} по {pos.entry:.10g} · тейк {pos.target:.10g} · стоп " + f"{pos.stop:.10g} · {now - pos.opened:.0f} из {ps.max_hold_seconds:g} с · {pnl:+.4f}$") + if len(positions) > 8: + lines.append(f" … и ещё {len(positions) - 8}") + position.set("\n".join(lines)) + else: + position.set("Позиции нет" + ("" if ps.enabled else " · новые сделки остановлены (кнопка «Старт»)")) + summary.set(paper.summary()) + if paper.message: + message.set(paper.message) + if shown["count"] != len(paper.trades): + shown["count"] = len(paper.trades) + tree.delete(*tree.get_children()) + for t in reversed(paper.trades[-300:]): + tree.insert("", "end", values=( + t.closed_utc[:19].replace("T", " "), t.ticker, t.side, f"{t.qty:.6g}", f"{t.notional_usd:.2f}", + f"{t.entry:.10g}", f"{t.exit:.10g}", f"{t.pct:+.3f}%", f"{t.net_usd:+.4f}", f"{t.fee_usd:.4f}", + t.reason, f"{t.hold_seconds:.0f}", t.regime), tags=("win" if t.net_usd > 0 else "loss",)) + if now - state.get("conn_check", 0.0) > 30: + # pick up connections added by the autonomous search without a restart + state["conn_check"] = now + before = len(connections) + for c in load_connections(): + if not any(same_connection(c, x) for x in connections): + connections.append(c) + if len(connections) != before: + show_connections() + message.set(f"Автопоиск добавил подключений: {len(connections) - before} — смотрите список «Подключение»") + root.after(300, refresh) + + def on_close() -> None: + if state["recorder"]: + state["recorder"].close() + for key in ("leader_feed", "follower_feed"): + if state[key]: + state[key].stop() + paper.ledger.save() + root.destroy() + + root.protocol("WM_DELETE_WINDOW", on_close) + start_feeds() + show_trading() + remember_connection(connections, {k: getattr(ps, k) for k in CONNECTION_KEYS}) + show_connections() + pump() + refresh() + root.mainloop() + + +if __name__ == "__main__": + run() diff --git a/live.py b/live.py new file mode 100644 index 0000000..43ba67e --- /dev/null +++ b/live.py @@ -0,0 +1,1448 @@ +"""Real orders on the exchanges (signed REST): balances, market orders on spot and on USDT perpetuals. + +Every client speaks in coins and per-coin prices, whatever the exchange's own units are (1000PEPE units on Bybit / +Binance, contracts on MEXC / HTX / Gate); quantities are rounded down to the exchange's lot step. + + spot_buy(base, usdt) market buy for a USDT amount + spot_sell(base, coins) market sell + spot_free(base) coins available on the spot / unified account + fut_order(symbol, side, coins, reduce_only) market order on the perpetual ("buy" / "sell") + fut_round(symbol, coins) the coins an order can actually have (lot step) + balances() USDT on spot and futures, for the «Проверить» button + +Errors from the exchange are raised as LiveError with the exchange's own message. +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import http.client +import json +import math +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from datetime import datetime, timezone + +from arb import split_base + +TIMEOUT = 15 + + +class LiveError(Exception): + """sent=True: the order may have reached the exchange (no answer, or its fill could not be confirmed) — + the caller must treat the position as possibly open and close it later; sent=False: certainly not placed.""" + + def __init__(self, message: str, sent: bool = False, order_id: str = "") -> None: + super().__init__(message) + self.sent, self.order_id = sent, order_id + + +class CircuitBreaker(LiveError): + """The exchange cancelled a market order unfilled to protect it from a wide spread (HTX 410): nothing was + traded — the same order can go as a limit at the book's price.""" + + +def _unsent(fn): + """Run the preparation of an order (rules, rounding): any failure there means nothing was sent.""" + try: + return fn() + except LiveError as exc: + raise LiveError(str(exc), sent=False) from None + + +def _placed(order_id: str, fn): + """Confirm the fill of an order the exchange has accepted: a failure here leaves the order possibly filled.""" + try: + return fn() + except LiveError as exc: + raise LiveError(f"ордер {order_id} принят биржей, но исполнение не подтверждено: {exc}", sent=True, + order_id=order_id) from None + + +@dataclass +class Fill: + coins: float # filled, in coins + price: float # average per coin + fee_usd: float # fee in $ as charged by the exchange (estimated from the taker rate only if exact=False) + order_id: str + raw: dict = field(default_factory=dict, repr=False) + exact: bool = True # price and fee are the exchange's own figures + tpsl: str = "" # opening order: "на бирже" — TP/SL set on the exchange; otherwise why not + + +def _floor(value: float, step: float) -> float: + if step <= 0: + return value + n = math.floor(value / step + 1e-9) + decimals = max(0, -int(math.floor(math.log10(step)))) if step < 1 else 0 + return round(n * step, decimals + 2) + + +def _tick(price: float, tick: float) -> float: + """Price rounded to the exchange's price step.""" + if tick <= 0: + return price + decimals = max(0, -int(math.floor(math.log10(tick)))) if tick < 1 else 0 + return round(round(price / tick) * tick, decimals + 2) + + +def _liq(rows: list, key: str, units: float, size) -> float | None: + """Liquidation price per coin from the exchange's position rows (the first row with a size); None when there + is no position or the exchange reports none (0 / empty: e.g. too much margin to ever be liquidated).""" + for r in rows or []: + if not isinstance(r, dict) or size(r) <= 0: + continue + try: + v = float(r.get(key) or 0) + except (TypeError, ValueError): + return None + return v / units if v > 0 else None + return None + + +def _num(text: float) -> str: + """A number for an order: its shortest exact decimal form, never an exponent. (12 fixed decimals printed the + float's noise on large amounts: 27481.05 → «27481.049999999999», refused by MEXC as a wrong quantity scale.)""" + from decimal import Decimal + s = format(Decimal(repr(round(float(text), 12))), "f") # 0.1 + 0.2 → «0.3», not «0.30000000000000004» + return s.rstrip("0").rstrip(".") if "." in s else s + + +# --- persistent connections ---------------------------------------------------------------------------------- +# A new HTTPS connection costs a TCP + TLS handshake (~70 ms more per order through the VPN, measured to MEXC); +# connections are kept open per host and reused, and warm_up() keeps one per exchange alive between orders. +IDLE_S = 15.0 # a connection idle longer than this is not reused (servers drop idle keep-alive ones) +_pool: dict[tuple[str, str], list[tuple[http.client.HTTPConnection, float]]] = {} +_pool_lock = threading.Lock() + + +def _take(scheme: str, host: str) -> tuple[http.client.HTTPConnection, bool]: + """(connection, reused) — an idle open connection to the host, or a new one.""" + now = time.monotonic() + with _pool_lock: + idle = _pool.get((scheme, host), []) + while idle: + conn, last = idle.pop() + if now - last < IDLE_S: + return conn, True + conn.close() + cls = http.client.HTTPSConnection if scheme == "https" else http.client.HTTPConnection + return cls(host, timeout=TIMEOUT), False + + +def _give_back(scheme: str, host: str, conn: http.client.HTTPConnection) -> None: + with _pool_lock: + idle = _pool.setdefault((scheme, host), []) + if len(idle) < 4: + idle.append((conn, time.monotonic())) + return + conn.close() + + +def _http(method: str, url: str, headers: dict | None = None, body: bytes | None = None) -> dict | list: + parts = urllib.parse.urlsplit(url) + target = parts.path + (f"?{parts.query}" if parts.query else "") + hdrs = {"User-Agent": "Mozilla/5.0", "Connection": "keep-alive", **(headers or {})} + for attempt in (1, 2): + conn, reused = _take(parts.scheme, parts.netloc) + try: + conn.request(method, target, body=body, headers=hdrs) + resp = conn.getresponse() + data = resp.read() + except (http.client.HTTPException, OSError) as exc: + conn.close() + # a reused connection the server had already closed: a read is simply repeated on a new one + if reused and method == "GET" and attempt == 1: + continue + # no answer: a POST may still have been executed by the exchange + raise LiveError(f"нет связи: {exc}", sent=method in ("POST", "DELETE")) from None + if resp.getheader("Connection", "").lower() == "close" or resp.will_close: + conn.close() + else: + _give_back(parts.scheme, parts.netloc, conn) + if resp.status >= 400: + raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}") + return json.loads(data or b"{}") + raise LiveError("нет связи") + + +WARM_URLS = {"bybit": ["https://api.bybit.com/v5/market/time"], + "binance": ["https://fapi.binance.com/fapi/v1/ping", "https://api.binance.com/api/v3/ping"], + "mexc": ["https://contract.mexc.com/api/v1/contract/ping", "https://api.mexc.com/api/v3/ping"], + "htx": ["https://api.hbdm.com/api/v1/timestamp", "https://api.huobi.pro/v1/common/timestamp"], + "gate": ["https://api.gateio.ws/api/v4/spot/time"]} + + +def warm_up(exchanges) -> dict[str, float]: + """One cheap public request per API host of these exchanges, so an open connection is waiting for the next + order; returns the round trip per host in ms (shown on the page).""" + out = {} + for ex in exchanges: + for url in WARM_URLS.get(ex, []): + t = time.perf_counter() + try: + _http("GET", url) + out[urllib.parse.urlsplit(url).netloc] = (time.perf_counter() - t) * 1000 + except LiveError: + pass + return out + + +def _units(symbol_base: str) -> float: + """Coins in one unit of the symbol: 1000PEPE → 1000.""" + return split_base(symbol_base)[1] + + +# -------------------------------------------------------------------------------------------------------------- +class Bybit: + name, host = "Bybit", "https://api.bybit.com" + spot_fee, fut_fee = 0.1, 0.055 + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + + def _call(self, method: str, path: str, params: dict | None = None) -> dict: + ts, recv = str(int(time.time() * 1000)), "10000" + if method == "GET": + query = urllib.parse.urlencode(params or {}) + payload, url, body = ts + self.key + recv + query, f"{self.host}{path}?{query}", None + else: + text = json.dumps(params or {}) + payload, url, body = ts + self.key + recv + text, self.host + path, text.encode() + sign = hmac.new(self.secret.encode(), payload.encode(), hashlib.sha256).hexdigest() + d = _http(method, url, {"X-BAPI-API-KEY": self.key, "X-BAPI-TIMESTAMP": ts, "X-BAPI-RECV-WINDOW": recv, + "X-BAPI-SIGN": sign, "Content-Type": "application/json"}, body) + if d.get("retCode") != 0: + raise LiveError(f"Bybit {d.get('retCode')}: {d.get('retMsg')}") + return d["result"] + + def _rule(self, category: str, symbol: str) -> dict: + k = f"{category}:{symbol}" + if k not in self.rules: + items = _http("GET", f"{self.host}/v5/market/instruments-info?category={category}&symbol={symbol}") + items = items.get("result", {}).get("list") or [] + if not items: + raise LiveError(f"Bybit: нет инструмента {symbol}") + lot = items[0]["lotSizeFilter"] + self.rules[k] = {"step": float(lot.get("qtyStep") or lot.get("basePrecision") or 0), + "min": float(lot.get("minOrderQty") or 0), + "tick": float((items[0].get("priceFilter") or {}).get("tickSize") or 0)} + return self.rules[k] + + def _fill(self, category: str, order_id: str) -> dict: + for attempt in range(10): + for path in ("/v5/order/realtime", "/v5/order/history"): + items = self._call("GET", path, {"category": category, "orderId": order_id}).get("list") or [] + if items and items[0].get("orderStatus") in ("Filled", "PartiallyFilledCanceled", "Cancelled", + "Rejected", "Deactivated"): + return items[0] + time.sleep(0.3) + raise LiveError(f"Bybit: ордер {order_id} не исполнился за 3 с") + + # The perp account's position mode: one-way (positionIdx 0) or hedge (1 = the long side, 2 = the short side). + # Learned from the exchange: an order with the wrong index is refused (10001 «position idx not match position + # mode») — nothing was placed, so it is sent once more with the other mode's index. + hedge = False + + def _idx(self, side: str, reduce_only: bool) -> int: + if not self.hedge: + return 0 + short = (side == "Sell") != bool(reduce_only) # a sale opens a short, a reduce-only buy closes one + return 2 if short else 1 + + def _create(self, params: dict) -> dict: + if params.get("category") == "linear": + params["positionIdx"] = self._idx(params["side"], params.get("reduceOnly", False)) + try: + return self._call("POST", "/v5/order/create", params) + except LiveError as exc: + if params.get("category") != "linear" or "10001" not in str(exc) or "position idx" not in str(exc).lower(): + raise + self.hedge = not self.hedge + params["positionIdx"] = self._idx(params["side"], params.get("reduceOnly", False)) + return self._call("POST", "/v5/order/create", params) + + def _order(self, category: str, params: dict, fee_rate: float, mult: float = 1.0) -> Fill: + oid = self._create({"category": category, "orderType": "Market", **params})["orderId"] + o = _placed(oid, lambda: self._fill(category, oid)) + units, value = float(o.get("cumExecQty") or 0), float(o.get("cumExecValue") or 0) + if units <= 0: + raise LiveError(f"Bybit: ордер не исполнен ({o.get('orderStatus')})") + coins = units * mult + fee = float(o.get("cumExecFee") or 0) + fee_usd = fee * value / units if category == "spot" and params["side"] == "Buy" else fee # buy fee is in coins + return Fill(coins, value / coins, fee_usd or value * fee_rate / 100, oid, o) + + def spot_buy(self, base: str, usdt: float) -> Fill: + return self._order("spot", {"symbol": f"{base}USDT", "side": "Buy", "qty": _num(round(usdt, 2)), + "marketUnit": "quoteCoin"}, self.spot_fee) + + def spot_sell(self, base: str, coins: float) -> Fill: + qty = _unsent(lambda: _floor(coins, self._rule("spot", f"{base}USDT")["step"])) + return self._order("spot", {"symbol": f"{base}USDT", "side": "Sell", "qty": _num(qty), + "marketUnit": "baseCoin"}, self.spot_fee) + + def spot_coins(self) -> dict[str, float]: + """Free coins on the spot account, all at once (the stock spot–spot trades sell from).""" + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})["list"] + return {c["coin"]: float(c.get("walletBalance") or 0) - float(c.get("locked") or 0) + for c in ((acc[0].get("coin") or []) if acc else []) if c.get("coin") != "USDT"} + + def spot_free(self, base: str) -> float: + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": base})["list"] + coins = acc[0].get("coin") or [] if acc else [] + return float(coins[0].get("walletBalance") or 0) - float(coins[0].get("locked") or 0) if coins else 0.0 + + def fut_round(self, symbol: str, coins: float) -> float: + mult = _units(symbol[:-4]) + r = self._rule("linear", symbol) + units = _floor(coins / mult, r["step"]) + return units * mult if units >= r["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + """The smallest perp order, in coins.""" + r = self._rule("linear", symbol) + return max(r["min"], r["step"]) * _units(symbol[:-4]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + """tp / sl (per coin): take-profit and stop-loss of the whole position, kept by the exchange itself and + executed at market when the last price reaches them (removed by Bybit when the position closes).""" + mult = _units(symbol[:-4]) + rule = _unsent(lambda: self._rule("linear", symbol)) + units = _floor(coins / mult, rule["step"]) + if units <= 0: + raise LiveError("Bybit: количество меньше шага лота") + params = {"symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "qty": _num(units), + "reduceOnly": reduce_only} + if not reduce_only and (tp or sl): + params["tpslMode"] = "Full" + if tp: + params.update(takeProfit=_num(_tick(tp * mult, rule["tick"])), tpTriggerBy="LastPrice") + if sl: + params.update(stopLoss=_num(_tick(sl * mult, rule["tick"])), slTriggerBy="LastPrice") + fill = self._order("linear", params, self.fut_fee, mult) + if not reduce_only and (tp or sl): + fill.tpsl = "на бирже" + return fill + + def fut_position(self, symbol: str) -> float: + """Coins of the open perp position on the exchange: + long, − short, 0 none.""" + items = self._call("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}).get("list") or [] + mult = _units(symbol[:-4]) + return sum(float(i.get("size") or 0) * mult * (1 if i.get("side") == "Buy" else -1) for i in items) + + def fut_liq_price(self, symbol: str) -> float | None: + """The exchange's liquidation price of the open position, per coin (None: no position / not reported).""" + items = self._call("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}).get("list") or [] + return _liq(items, "liqPrice", _units(symbol[:-4]), lambda i: float(i.get("size") or 0)) + + def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]: + """Fills on `side` ("buy" / "sell") of the symbol since `since` (unix s): how the exchange closed it.""" + items = self._call("GET", "/v5/execution/list", {"category": "linear", "symbol": symbol, "limit": 100, + "startTime": int(since * 1000)}).get("list") or [] + mult, want = _units(symbol[:-4]), "Buy" if side == "buy" else "Sell" + return [Fill(float(e["execQty"]) * mult, float(e["execPrice"]) / mult, float(e.get("execFee") or 0), + e.get("orderId", "")) for e in items if e.get("side") == want and e.get("execType", "Trade") == "Trade"] + + def fut_cancel_all(self, symbol: str) -> None: + self._call("POST", "/v5/order/cancel-all", {"category": "linear", "symbol": symbol}) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + """Reduce-only LIMIT order closing the position at `price` (per coin) or better; `side` closes it.""" + mult = _units(symbol[:-4]) + rule = self._rule("linear", symbol) + return self._create({ + "category": "linear", "symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "orderType": "Limit", + "qty": _num(_floor(coins / mult, rule["step"])), "price": _num(_tick(price * mult, rule["tick"])), + "timeInForce": "GTC", "reduceOnly": True})["orderId"] + + # --- resting limit orders on the perp: placed, watched, cancelled --------------------------------------- + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + mult = _units(symbol[:-4]) + rule = _unsent(lambda: self._rule("linear", symbol)) + units = _floor(coins / mult, rule["step"]) + if units <= 0: + raise LiveError("Bybit: количество меньше шага лота") + return self._create({ + "category": "linear", "symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "orderType": "Limit", + "qty": _num(units), "price": _num(_tick(price * mult, rule["tick"])), "timeInForce": "GTC", + "reduceOnly": reduce_only})["orderId"] + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + """{"coins": filled, "price": average per coin, "fee": $, "final": no longer working}.""" + mult = _units(symbol[:-4]) + for path in ("/v5/order/realtime", "/v5/order/history"): + items = self._call("GET", path, {"category": "linear", "symbol": symbol, "orderId": order_id}).get("list") or [] + if items: + o = items[0] + units, value = float(o.get("cumExecQty") or 0), float(o.get("cumExecValue") or 0) + return {"coins": units * mult, "price": value / (units * mult) if units else 0.0, + "fee": float(o.get("cumExecFee") or 0), + "final": o.get("orderStatus") not in ("New", "PartiallyFilled", "Untriggered")} + raise LiveError(f"Bybit: ордер {order_id} не найден") + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._call("POST", "/v5/order/cancel", {"category": "linear", "symbol": symbol, "orderId": order_id}) + + def fut_fills(self, symbol: str, since: float) -> list[dict]: + """Every fill of the symbol since `since` as the exchange recorded it (for trades and statistics).""" + mult, out, cursor = _units(symbol[:-4]), [], "" + for _ in range(10): + params = {"category": "linear", "symbol": symbol, "limit": 100, "startTime": int(since * 1000)} + if cursor: + params["cursor"] = cursor + res = self._call("GET", "/v5/execution/list", params) + for e in res.get("list") or []: + if e.get("execType", "Trade") != "Trade": + continue + out.append({"time": int(e["execTime"]) / 1000, "side": "buy" if e["side"] == "Buy" else "sell", + "coins": float(e["execQty"]) * mult, "price": float(e["execPrice"]) / mult, + "fee": float(e.get("execFee") or 0), "pnl": None, "order": e.get("orderId", ""), + "close": float(e.get("closedSize") or 0) > 0}) + cursor = res.get("nextPageCursor") or "" + if not cursor: + break + return sorted(out, key=lambda f: f["time"]) + + def balances(self) -> dict: + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"})["list"] + coin = (acc[0].get("coin") or [{}])[0] if acc else {} + usdt = float(coin.get("equity") or coin.get("walletBalance") or 0) # incl. unrealized result + return {"Единый счёт USDT": usdt} + + unified = True # one account for spot and perps: nothing to move between them + + def usdt_free(self) -> dict: + acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"})["list"] + coin = (acc[0].get("coin") or [{}])[0] if acc else {} + free = float(coin.get("walletBalance") or 0) - float(coin.get("locked") or 0) - float(coin.get("totalPositionIM") or 0) + return {"spot": free, "futures": free} + + def transfer_usdt(self, to: str, amount: float) -> None: + raise LiveError("Bybit: единый счёт — перевод не нужен") + + +# -------------------------------------------------------------------------------------------------------------- +class _BinanceLike: + """Binance spot / USDⓈ-M futures and MEXC spot share the signing scheme: HMAC-SHA256 of the query string.""" + name = "" + key_header = "X-MBX-APIKEY" + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + + def _signed(self, method: str, url: str, params: dict | None = None) -> dict | list: + q = dict(params or {}) + q["timestamp"] = int(time.time() * 1000) + q["recvWindow"] = 10000 + query = urllib.parse.urlencode(q) + query += "&signature=" + hmac.new(self.secret.encode(), query.encode(), hashlib.sha256).hexdigest() + return _http(method, f"{url}?{query}", {self.key_header: self.key}) + + +class Binance(_BinanceLike): + name = "Binance" + spot_fee, fut_fee = 0.1, 0.05 + SPOT, FUT = "https://api.binance.com", "https://fapi.binance.com" + + def _rule(self, market: str, symbol: str) -> dict: + k = f"{market}:{symbol}" + if k not in self.rules: + url = f"{self.SPOT}/api/v3/exchangeInfo?symbol={symbol}" if market == "spot" else f"{self.FUT}/fapi/v1/exchangeInfo" + info = next((s for s in _http("GET", url)["symbols"] if s["symbol"] == symbol), None) + if info is None: + raise LiveError(f"Binance: нет инструмента {symbol}") + f = {x["filterType"]: x for x in info["filters"]} + lot = f.get("MARKET_LOT_SIZE") if float((f.get("MARKET_LOT_SIZE") or {}).get("stepSize") or 0) > 0 else f["LOT_SIZE"] + self.rules[k] = {"step": float(lot["stepSize"]), "min": float(lot["minQty"]), + "tick": float((f.get("PRICE_FILTER") or {}).get("tickSize") or 0)} + return self.rules[k] + + def spot_buy(self, base: str, usdt: float) -> Fill: + o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"symbol": f"{base}USDT", "side": "BUY", "type": "MARKET", + "quoteOrderQty": _num(round(usdt, 2)), + "newOrderRespType": "FULL"}) + return self._spot_fill(o, base) + + def spot_sell(self, base: str, coins: float) -> Fill: + qty = _unsent(lambda: _floor(coins, self._rule("spot", f"{base}USDT")["step"])) + o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"symbol": f"{base}USDT", "side": "SELL", "type": "MARKET", + "quantity": _num(qty), "newOrderRespType": "FULL"}) + return self._spot_fill(o, base) + + def _spot_fill(self, o: dict, base: str) -> Fill: + qty, quote = float(o.get("executedQty") or 0), float(o.get("cummulativeQuoteQty") or 0) + if qty <= 0: + raise LiveError(f"Binance: ордер не исполнен ({o.get('status')})") + price = quote / qty + fee = 0.0 + for f in o.get("fills") or []: + c, asset = float(f.get("commission") or 0), f.get("commissionAsset") + fee += c if asset == "USDT" else c * price if asset == base else quote * self.spot_fee / 100 / max(1, len(o["fills"])) + return Fill(qty, price, fee, str(o.get("orderId")), o) + + def spot_coins(self) -> dict[str, float]: + return {b["asset"]: float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account", + {"omitZeroBalances": "true"})["balances"] + if b["asset"] != "USDT" and float(b["free"]) > 0} + + def spot_free(self, base: str) -> float: + for b in self._signed("GET", f"{self.SPOT}/api/v3/account", {"omitZeroBalances": "true"})["balances"]: + if b["asset"] == base: + return float(b["free"]) + return 0.0 + + def fut_round(self, symbol: str, coins: float) -> float: + mult = _units(symbol[:-4]) + r = self._rule("fut", symbol) + units = _floor(coins / mult, r["step"]) + return units * mult if units >= r["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + r = self._rule("fut", symbol) + return max(r["min"], r["step"]) * _units(symbol[:-4]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + fill = self._fut_market(symbol, side, coins, reduce_only) + if not reduce_only and (tp or sl): + # Binance has no TP/SL on a market order: two conditional orders that close the whole position + mult, tick = _units(symbol[:-4]), self._rule("fut", symbol)["tick"] + close_side = "SELL" if side == "buy" else "BUY" + problems = [] + for kind, price in (("TAKE_PROFIT_MARKET", tp), ("STOP_MARKET", sl)): + if not price: + continue + try: + self._signed("POST", f"{self.FUT}/fapi/v1/order", { + "symbol": symbol, "side": close_side, "type": kind, "stopPrice": _num(_tick(price * mult, tick)), + "closePosition": "true", "workingType": "CONTRACT_PRICE"}) + except LiveError as exc: + problems.append(f"{'TP' if kind.startswith('TAKE') else 'SL'}: {exc}") + fill.tpsl = "; ".join(problems) if problems else "на бирже" + return fill + + def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]: + rows = self._signed("GET", f"{self.FUT}/fapi/v1/userTrades", {"symbol": symbol, "startTime": int(since * 1000)}) + mult = _units(symbol[:-4]) + return [Fill(float(t["qty"]) * mult, float(t["price"]) / mult, float(t.get("commission") or 0), + str(t.get("orderId", ""))) for t in rows if t.get("side") == side.upper()] + + def fut_cancel_all(self, symbol: str) -> None: + self._signed("DELETE", f"{self.FUT}/fapi/v1/allOpenOrders", {"symbol": symbol}) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + mult = _units(symbol[:-4]) + rule = self._rule("fut", symbol) + o = self._signed("POST", f"{self.FUT}/fapi/v1/order", { + "symbol": symbol, "side": side.upper(), "type": "LIMIT", "timeInForce": "GTC", "reduceOnly": "true", + "quantity": _num(_floor(coins / mult, rule["step"])), "price": _num(_tick(price * mult, rule["tick"]))}) + return str(o.get("orderId")) + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + mult = _units(symbol[:-4]) + rule = _unsent(lambda: self._rule("fut", symbol)) + units = _floor(coins / mult, rule["step"]) + if units <= 0: + raise LiveError("Binance: количество меньше шага лота") + params = {"symbol": symbol, "side": side.upper(), "type": "LIMIT", "timeInForce": "GTC", + "quantity": _num(units), "price": _num(_tick(price * mult, rule["tick"]))} + if reduce_only: + params["reduceOnly"] = "true" + return str(self._signed("POST", f"{self.FUT}/fapi/v1/order", params).get("orderId")) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + o = self._signed("GET", f"{self.FUT}/fapi/v1/order", {"symbol": symbol, "orderId": order_id}) + mult = _units(symbol[:-4]) + units, quote = float(o.get("executedQty") or 0), float(o.get("cumQuote") or 0) + return {"coins": units * mult, "price": quote / (units * mult) if units else 0.0, + "fee": quote * self.fut_fee / 100, "final": o.get("status") not in ("NEW", "PARTIALLY_FILLED")} + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._signed("DELETE", f"{self.FUT}/fapi/v1/order", {"symbol": symbol, "orderId": order_id}) + + def fut_fills(self, symbol: str, since: float) -> list[dict]: + rows = self._signed("GET", f"{self.FUT}/fapi/v1/userTrades", + {"symbol": symbol, "startTime": int(since * 1000), "limit": 1000}) + mult = _units(symbol[:-4]) + return sorted(({"time": t["time"] / 1000, "side": t["side"].lower(), "coins": float(t["qty"]) * mult, + "price": float(t["price"]) / mult, "fee": float(t.get("commission") or 0), + "pnl": float(t.get("realizedPnl") or 0), "order": str(t.get("orderId", "")), + "close": float(t.get("realizedPnl") or 0) != 0} + for t in rows), key=lambda f: f["time"]) + + def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill: + mult = _units(symbol[:-4]) + units = _unsent(lambda: _floor(coins / mult, self._rule("fut", symbol)["step"])) + if units <= 0: + raise LiveError("Binance: количество меньше шага лота") + params = {"symbol": symbol, "side": side.upper(), "type": "MARKET", "quantity": _num(units), + "newOrderRespType": "RESULT"} + if reduce_only: + params["reduceOnly"] = "true" + o = self._signed("POST", f"{self.FUT}/fapi/v1/order", params) + units_done, quote = float(o.get("executedQty") or 0), float(o.get("cumQuote") or 0) + if units_done <= 0: + raise LiveError(f"Binance: ордер не исполнен ({o.get('status')})") + coins_done = units_done * mult + # no extra request for the fee: the estimate is replaced by the charged one at the next history sync + return Fill(coins_done, quote / coins_done, quote * self.fut_fee / 100, str(o.get("orderId")), o, False) + + def fut_position(self, symbol: str) -> float: + rows = self._signed("GET", f"{self.FUT}/fapi/v2/positionRisk", {"symbol": symbol}) + return sum(float(r.get("positionAmt") or 0) for r in rows) * _units(symbol[:-4]) + + def fut_liq_price(self, symbol: str) -> float | None: + rows = self._signed("GET", f"{self.FUT}/fapi/v2/positionRisk", {"symbol": symbol}) + return _liq(rows, "liquidationPrice", _units(symbol[:-4]), lambda r: abs(float(r.get("positionAmt") or 0))) + + def balances(self) -> dict: + spot = next((float(b["free"]) + float(b.get("locked") or 0) # incl. USDT held by open orders + for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] if b["asset"] == "USDT"), 0.0) + fut = next((float(b.get("balance") or 0) + float(b.get("crossUnPnl") or 0) + for b in self._signed("GET", f"{self.FUT}/fapi/v2/balance") + if b["asset"] == "USDT"), 0.0) + return {"Спот USDT": spot, "Фьючерсы USDT": fut} + + unified = False + + def usdt_free(self) -> dict: + spot = next((float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] + if b["asset"] == "USDT"), 0.0) + fut = next((float(b.get("availableBalance") or 0) for b in self._signed("GET", f"{self.FUT}/fapi/v2/balance") + if b["asset"] == "USDT"), 0.0) + return {"spot": spot, "futures": fut} + + def transfer_usdt(self, to: str, amount: float) -> None: + """Between the spot (MAIN) and USDⓈ-M futures accounts; the key needs «Permits Universal Transfer».""" + self._signed("POST", f"{self.SPOT}/sapi/v1/asset/transfer", { + "type": "MAIN_UMFUTURE" if to == "futures" else "UMFUTURE_MAIN", "asset": "USDT", "amount": _num(amount)}) + + +# -------------------------------------------------------------------------------------------------------------- +def mexc_order_id(data) -> str: + """MEXC futures answer a submit with the id itself or with {"orderId": "...", "ts": ...} (the newer form).""" + if isinstance(data, dict): + data = data.get("orderId") or data.get("order_id") + if not data: + raise LiveError("MEXC: биржа не вернула номер ордера", sent=True) + return str(data) + + +class Mexc(_BinanceLike): + name = "MEXC" + key_header = "X-MEXC-APIKEY" + spot_fee, fut_fee = 0.05, 0.02 + SPOT, FUT = "https://api.mexc.com", "https://contract.mexc.com" + + def _spot_rule(self, symbol: str) -> dict: + if symbol not in self.rules: + info = (_http("GET", f"{self.SPOT}/api/v3/exchangeInfo?symbol={symbol}").get("symbols") or [None])[0] + if info is None: + raise LiveError(f"MEXC: нет пары {symbol}") + self.rules[symbol] = {"step": 10 ** -int(info.get("baseAssetPrecision") or 2)} + return self.rules[symbol] + + def _spot_order(self, params: dict, base: str) -> Fill: + o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"type": "MARKET", **params}) + oid = str(o.get("orderId")) + + def poll(): + for _ in range(10): + d = self._signed("GET", f"{self.SPOT}/api/v3/order", {"symbol": params["symbol"], "orderId": oid}) + if d.get("status") in ("FILLED", "CANCELED", "PARTIALLY_CANCELED", "REJECTED"): + return d + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + d = _placed(oid, poll) + qty, quote = float(d.get("executedQty") or 0), float(d.get("cummulativeQuoteQty") or 0) + if qty <= 0: + raise LiveError(f"MEXC: ордер не исполнен ({d.get('status')})") + price = quote / qty + fee, exact = quote * self.spot_fee / 100, False + try: # commission actually charged, from the order's trades + trades = self._signed("GET", f"{self.SPOT}/api/v3/myTrades", {"symbol": params["symbol"], "orderId": oid}) + if isinstance(trades, list) and trades: + fee, exact = 0.0, True + for t in trades: + c, asset = float(t.get("commission") or 0), t.get("commissionAsset") + fee += c if asset == "USDT" else c * price if asset == base else 0.0 + except LiveError: + pass + return Fill(qty, price, fee, oid, d, exact) + + def spot_buy(self, base: str, usdt: float) -> Fill: + return self._spot_order({"symbol": f"{base}USDT", "side": "BUY", "quoteOrderQty": _num(round(usdt, 2))}, base) + + def spot_sell(self, base: str, coins: float) -> Fill: + symbol = f"{base}USDT" + rule = _unsent(lambda: self._spot_rule(symbol)) + while True: + qty = _floor(coins, rule["step"]) + try: + return self._spot_order({"symbol": symbol, "side": "SELL", "quantity": _num(qty)}, base) + except LiveError as exc: + # MEXC's exchangeInfo does not always tell the real quantity step (SUE: 2 decimals listed, refused + # with 400 «quantity scale is invalid»): the order was not taken — one decimal fewer, remembered + if "scale is invalid" not in str(exc) or getattr(exc, "sent", False) or rule["step"] >= 1: + raise + rule["step"] = min(1.0, rule["step"] * 10) + + def spot_coins(self) -> dict[str, float]: + return {b["asset"]: float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] + if b["asset"] != "USDT" and float(b["free"]) > 0} + + def spot_free(self, base: str) -> float: + for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"]: + if b["asset"] == base: + return float(b["free"]) + return 0.0 + + # futures: contract.mexc.com, signature = HMAC-SHA256(key + time + params); order placing through the API is + # closed for most accounts by MEXC itself — the exchange's refusal is shown as is + def _fut(self, method: str, path: str, params: dict | None = None) -> dict: + # MEXC answers reads now and then with 513 «try again later»: a read is simply repeated (never an order) + for attempt in range(3): + try: + return self._fut_once(method, path, params) + except LiveError as exc: + if method != "GET" or "513" not in str(exc) or attempt == 2: + raise + time.sleep(0.4 * (attempt + 1)) + + def _fut_once(self, method: str, path: str, params: dict | None = None) -> dict: + ts = str(int(time.time() * 1000)) + if method == "GET": + query = urllib.parse.urlencode(sorted((params or {}).items())) + text, url, body = query, f"{self.FUT}{path}" + (f"?{query}" if query else ""), None + else: + text = json.dumps(params or {}) + url, body = self.FUT + path, text.encode() + sign = hmac.new(self.secret.encode(), (self.key + ts + text).encode(), hashlib.sha256).hexdigest() + d = _http(method, url, {"ApiKey": self.key, "Request-Time": ts, "Signature": sign, + "Content-Type": "application/json"}, body) + if not d.get("success"): + raise LiveError(f"MEXC фьючерсы {d.get('code')}: {d.get('message')}") + return d.get("data") + + def _contract(self, symbol: str) -> dict: + k = f"fut:{symbol}" + if k not in self.rules: + d = _http("GET", f"{self.FUT}/api/v1/contract/detail?symbol={symbol}").get("data") or {} + if not d: + raise LiveError(f"MEXC: нет контракта {symbol}") + self.rules[k] = {"size": float(d["contractSize"]) * _units(symbol[:-5]), "min": float(d.get("minVol") or 1), + "tick": float(d.get("priceUnit") or 0)} + return self.rules[k] + + def fut_round(self, symbol: str, coins: float) -> float: + c = self._contract(symbol) + vol = math.floor(coins / c["size"] + 1e-9) + return vol * c["size"] if vol >= c["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + c = self._contract(symbol) + return c["size"] * max(1.0, c["min"]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + c = _unsent(lambda: self._contract(symbol)) + vol = math.floor(coins / c["size"] + 1e-9) + if vol <= 0: + raise LiveError("MEXC: количество меньше одного контракта") + # side: 1 open long, 2 close short, 3 open short, 4 close long; type 5 = market; openType 2 = cross + code = (2 if side == "buy" else 4) if reduce_only else (1 if side == "buy" else 3) + params = {"symbol": symbol, "vol": vol, "side": code, "type": 5, "openType": 2} + units = _units(symbol[:-5]) + if not reduce_only: # TP / SL attached to the opening order, kept by MEXC + if tp: + params["takeProfitPrice"] = _tick(tp * units, c["tick"]) + if sl: + params["stopLossPrice"] = _tick(sl * units, c["tick"]) + oid = mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", params)) + + def check(): + # ONE look at the order (a market order is filled by now): MEXC limits private requests, a series of + # polls ran into «510 too frequent»; if it is not confirmed, the caller checks the position instead + time.sleep(0.15) + o = self._fut("GET", f"/api/v1/private/order/get/{oid}") + if float(o.get("dealVol") or 0) > 0 and o.get("state") in (3, 4): + return o + raise LiveError(f"исполнение ещё не видно (state {o.get('state')})") + o = _placed(oid, check) + coins_done = float(o.get("dealVol") or 0) * c["size"] + if coins_done <= 0: + raise LiveError("MEXC: фьючерсный ордер не исполнен") + price = float(o.get("dealAvgPrice") or 0) / _units(symbol[:-5]) + charged = [o.get(k) for k in ("takerFee", "makerFee") if o.get(k) not in (None, "")] + tpsl = "на бирже" if not reduce_only and ("takeProfitPrice" in params or "stopLossPrice" in params) else "" + if charged: + return Fill(coins_done, price, sum(abs(float(x)) for x in charged), oid, o, tpsl=tpsl) + return Fill(coins_done, price, coins_done * price * self.fut_fee / 100, oid, o, False, tpsl) + + def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]: + """Closing orders (side 4 closes a long by selling, 2 closes a short by buying) since `since`.""" + size, units = self._contract(symbol)["size"], _units(symbol[:-5]) + want = 2 if side == "buy" else 4 + d = self._fut("GET", "/api/v1/private/order/list/history_orders", + {"symbol": symbol, "start_time": int(since * 1000), "page_num": 1, "page_size": 50}) or [] + rows = d if isinstance(d, list) else d.get("resultList") or [] + out = [] + for o in rows: + if o.get("side") == want and float(o.get("dealVol") or 0) > 0: + fee = sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")) + out.append(Fill(float(o["dealVol"]) * size, float(o.get("dealAvgPrice") or 0) / units, fee, + str(o.get("orderId", "")))) + return out + + def fut_cancel_all(self, symbol: str) -> None: + """Every open order of the symbol: limit orders (the TP) and the TP/SL plans.""" + problems = [] + for path in ("/api/v1/private/order/cancel_all", "/api/v1/private/stoporder/cancel_all"): + try: + self._fut("POST", path, {"symbol": symbol}) + except LiveError as exc: + problems.append(str(exc)) + if len(problems) == 2: + raise LiveError("; ".join(problems)) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + """Reduce-only limit close: side 2 closes a short (buy), 4 closes a long (sell); type 1 = limit.""" + c = self._contract(symbol) + vol = math.floor(coins / c["size"] + 1e-9) + return mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", { + "symbol": symbol, "vol": vol, "side": 2 if side == "buy" else 4, "type": 1, "openType": 2, + "price": _tick(price * _units(symbol[:-5]), c["tick"])})) + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + """Resting limit order (type 1): opens (1 long / 3 short) or, reduce-only, closes (2 short / 4 long).""" + c = _unsent(lambda: self._contract(symbol)) + vol = math.floor(coins / c["size"] + 1e-9) + if vol <= 0: + raise LiveError("MEXC: количество меньше одного контракта") + code = (2 if side == "buy" else 4) if reduce_only else (1 if side == "buy" else 3) + return mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", { + "symbol": symbol, "vol": vol, "side": code, "type": 1, "openType": 2, + "price": _tick(price * _units(symbol[:-5]), c["tick"])})) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + c = self._contract(symbol) + o = self._fut("GET", f"/api/v1/private/order/get/{order_id}") + coins = float(o.get("dealVol") or 0) * c["size"] + return {"coins": coins, "price": float(o.get("dealAvgPrice") or 0) / _units(symbol[:-5]), + "fee": sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")), + "final": o.get("state") in (3, 4, 5)} # 1/2 waiting · 3 filled · 4 cancelled · 5 invalid + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._fut("POST", "/api/v1/private/order/cancel", [order_id]) + + def fut_fills(self, symbol: str, since: float) -> list[dict]: + """Filled orders of the symbol since `since` (MEXC: per order — side 1/2 buy, 3/4 sell; `profit` is the + realized result of a closing order before fees, as in the exchange's trade history).""" + size, units = self._contract(symbol)["size"], _units(symbol[:-5]) + out = [] + for page in range(1, 11): + d = self._fut("GET", "/api/v1/private/order/list/history_orders", + {"symbol": symbol, "start_time": int(since * 1000), "page_num": page, "page_size": 100}) or [] + rows = d if isinstance(d, list) else d.get("resultList") or [] + for o in rows: + vol = float(o.get("dealVol") or 0) + if vol <= 0: + continue + code = o.get("side") + out.append({"time": (o.get("updateTime") or o.get("createTime") or 0) / 1000, + "side": "buy" if code in (1, 2) else "sell", "coins": vol * size, + "price": float(o.get("dealAvgPrice") or 0) / units, + "fee": sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")), + "pnl": float(o["profit"]) if code in (2, 4) and o.get("profit") not in (None, "") else None, + "close": code in (2, 4), + "order": str(o.get("orderId", ""))}) + if len(rows) < 100: + break + return sorted(out, key=lambda f: f["time"]) + + def fut_position(self, symbol: str) -> float: + size = self._contract(symbol)["size"] + rows = self._fut("GET", "/api/v1/private/position/open_positions", {"symbol": symbol}) or [] + return sum(float(r.get("holdVol") or 0) * size * (1 if r.get("positionType") == 1 else -1) for r in rows) + + def fut_liq_price(self, symbol: str) -> float | None: + rows = self._fut("GET", "/api/v1/private/position/open_positions", {"symbol": symbol}) or [] + return _liq(rows, "liquidatePrice", _units(symbol[:-5]), lambda r: float(r.get("holdVol") or 0)) + + def balances(self) -> dict: + spot = next((float(b["free"]) + float(b.get("locked") or 0) # incl. USDT held by open orders + for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] if b["asset"] == "USDT"), 0.0) + out = {"Спот USDT": spot} + try: + acc = next((a for a in self._fut("GET", "/api/v1/private/account/assets") if a.get("currency") == "USDT"), {}) + # equity: what the account is worth now (free + margin in positions + their unrealized result) + out["Фьючерсы USDT"] = float(acc.get("equity") or acc.get("availableBalance") or 0) + except LiveError as exc: + out["Фьючерсы"] = str(exc) + return out + + unified = False + + def usdt_free(self) -> dict: + spot = next((float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] + if b["asset"] == "USDT"), 0.0) + acc = next((a for a in self._fut("GET", "/api/v1/private/account/assets") if a.get("currency") == "USDT"), {}) + return {"spot": spot, "futures": float(acc.get("availableBalance") or 0)} + + def transfer_usdt(self, to: str, amount: float) -> None: + """Between the spot and futures accounts (spot API capital/transfer; the key needs the transfer right).""" + self._signed("POST", f"{self.SPOT}/api/v3/capital/transfer", { + "fromAccountType": "SPOT" if to == "futures" else "FUTURES", + "toAccountType": "FUTURES" if to == "futures" else "SPOT", "asset": "USDT", "amount": _num(amount)}) + + +# -------------------------------------------------------------------------------------------------------------- +class Htx: + name = "HTX" + spot_fee, fut_fee = 0.2, 0.05 + SPOT, FUT = "api.huobi.pro", "api.hbdm.com" + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + self.account_id: str | None = None + + def _call(self, method: str, host: str, path: str, params: dict | None = None, body: dict | None = None): + q = {"AccessKeyId": self.key, "SignatureMethod": "HmacSHA256", "SignatureVersion": "2", + "Timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S"), **(params or {})} + query = urllib.parse.urlencode(sorted(q.items()), quote_via=urllib.parse.quote) + payload = f"{method}\n{host}\n{path}\n{query}" + sign = base64.b64encode(hmac.new(self.secret.encode(), payload.encode(), hashlib.sha256).digest()).decode() + url = f"https://{host}{path}?{query}&Signature={urllib.parse.quote(sign, safe='')}" + data = None if body is None else json.dumps(body).encode() + d = _http(method, url, {"Content-Type": "application/json"}, data) + if d.get("status") not in ("ok", None) or (d.get("code") not in (None, 200) and "data" not in d): + raise LiveError(f"HTX {d.get('err-code') or d.get('err_code') or d.get('code')}: " + f"{d.get('err-msg') or d.get('err_msg') or d.get('message')}") + return d.get("data") + + def _account(self) -> str: + if self.account_id is None: + acc = next((a for a in self._call("GET", self.SPOT, "/v1/account/accounts") if a.get("type") == "spot"), None) + if acc is None: + raise LiveError("HTX: спотовый счёт не найден") + self.account_id = str(acc["id"]) + return self.account_id + + def _spot_order(self, base: str, kind: str, amount: str, fee_rate: float, price: str | None = None) -> Fill: + body = {"account-id": self._account(), "symbol": f"{base.lower()}usdt", "type": kind, "amount": amount, + "source": "spot-api"} + if price is not None: + body["price"] = price + oid = self._call("POST", self.SPOT, "/v1/order/orders/place", body=body) + + def poll(): + for _ in range(10): + o = self._call("GET", self.SPOT, f"/v1/order/orders/{oid}") + if o.get("state") in ("filled", "partial-canceled", "canceled"): + return o + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + o = _placed(str(oid), poll) + qty, quote = float(o.get("field-amount") or o.get("filled-amount") or 0), float( + o.get("field-cash-amount") or o.get("filled-cash-amount") or 0) + if qty <= 0: + # a market order cancelled with nothing filled: HTX's circuit breaker on a wide spread (410 — the order + # detail does not report the source, only the history does); nothing traded, a limit can go instead + if kind.endswith("-market") and o.get("state") == "canceled": + raise CircuitBreaker("HTX: рыночный ордер отменён защитой биржи (широкий спред)") + raise LiveError(f"HTX: ордер не исполнен ({o.get('state')})") + fee = float(o.get("field-fees") or o.get("filled-fees") or 0) + fee_usd = fee * quote / qty if kind.startswith("buy") else fee # a buy pays its fee in coins + return Fill(qty, quote / qty, fee_usd or quote * fee_rate / 100, str(oid), o) + + def _spot_rule(self, base: str) -> dict: + k = f"spot:{base}" + if k not in self.rules: + sym = next((s for s in _http("GET", f"https://{self.SPOT}/v1/common/symbols")["data"] + if s["symbol"] == f"{base.lower()}usdt"), None) + if sym is None: + raise LiveError(f"HTX: нет пары {base}/USDT") + self.rules[k] = {"step": 10 ** -int(sym.get("amount-precision", 4)), + "tick": 10 ** -int(sym.get("price-precision", 8))} + return self.rules[k] + + def _spot_step(self, base: str) -> float: + return self._spot_rule(base)["step"] + + def _book_price(self, base: str, side: str, size: float, in_quote: bool) -> float: + """The price an IOC limit order needs to fill `size` (coins, or USDT for a buy) from the book now: the last + level it reaches. For when HTX refuses a market order (its circuit breaker on a wide spread).""" + import fastquote + bids, asks = fastquote.book("HTX", "spot", f"{base.lower()}usdt") + levels, got = (asks if side == "buy" else bids), 0.0 + for p, q in levels: + got += p * q if in_quote else q + if got >= size: + return p + raise LiveError(f"HTX: в стакане {base} меньше нужного объёма") + + def spot_buy(self, base: str, usdt: float) -> Fill: + try: + return self._spot_order(base, "buy-market", _num(round(usdt, 2)), self.spot_fee) + except CircuitBreaker: + r = _unsent(lambda: self._spot_rule(base)) + price = _unsent(lambda: self._book_price(base, "buy", usdt, True)) + price = math.ceil(price / r["tick"] - 1e-9) * r["tick"] + coins = _floor(usdt / price, r["step"]) + return self._spot_order(base, "buy-ioc", _num(coins), self.spot_fee, _num(price)) + + def spot_sell(self, base: str, coins: float) -> Fill: + step = _unsent(lambda: self._spot_step(base)) + amount = _num(_floor(coins, step)) + try: + return self._spot_order(base, "sell-market", amount, self.spot_fee) + except CircuitBreaker: + # nothing was sold: the same coins as an IOC limit at the book price that takes them all + r = _unsent(lambda: self._spot_rule(base)) + price = _unsent(lambda: self._book_price(base, "sell", float(amount), False)) + price = math.floor(price / r["tick"] + 1e-9) * r["tick"] + return self._spot_order(base, "sell-ioc", amount, self.spot_fee, _num(price)) + + def spot_coins(self) -> dict[str, float]: + out: dict[str, float] = {} + for i in self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"]: + if i["type"] == "trade" and i["currency"] != "usdt" and float(i["balance"]) > 0: + out[i["currency"].upper()] = out.get(i["currency"].upper(), 0.0) + float(i["balance"]) + return out + + def spot_free(self, base: str) -> float: + items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"] + return sum(float(i["balance"]) for i in items if i["currency"] == base.lower() and i["type"] == "trade") + + def _contract(self, code: str) -> dict: + k = f"fut:{code}" + if k not in self.rules: + d = _http("GET", f"https://{self.FUT}/linear-swap-api/v1/swap_contract_info?contract_code={code}")["data"] + if not d: + raise LiveError(f"HTX: нет контракта {code}") + self.rules[k] = {"size": float(d[0]["contract_size"]) * _units(code[:-5])} + return self.rules[k] + + def fut_round(self, symbol: str, coins: float) -> float: + size = self._contract(symbol)["size"] + return math.floor(coins / size + 1e-9) * size + + def fut_min_coins(self, symbol: str) -> float: + return self._contract(symbol)["size"] + + # A futures account in the Multi-Assets Collateral mode (asset_mode 2) answers the v1 interface with 6023 + # «The current API version has expired»: it is traded through the V5 interface (same signature, host api.hbdm.com). + _v5_mode: bool | None = None + + def _v5(self) -> bool: + if self._v5_mode is None: + try: + self._v5_mode = int((self._call("GET", self.FUT, "/v5/account/asset_mode") or {}).get("asset_mode") + or 0) == 2 + except LiveError: + return False # not known yet: v1, asked again next time + return self._v5_mode + + V5_FINAL = ("filled", "partially_canceled", "canceled") + + def _v5_order(self, symbol: str, oid: str) -> dict: + o = self._call("GET", self.FUT, "/v5/trade/order", {"contract_code": symbol, "order_id": oid}) or {} + return o[0] if isinstance(o, list) and o else o if isinstance(o, dict) else {} + + def _v5_place(self, symbol: str, side: str, vol: int, reduce_only: bool, price: float | None) -> str: + body = {"contract_code": symbol, "margin_mode": "cross", "side": side, "volume": vol, + "type": "limit" if price else "market"} + if price: + body["price"] = price * _units(symbol[:-5]) + body["time_in_force"] = "gtc" + if reduce_only: + body["reduce_only"] = 1 + d = self._call("POST", self.FUT, "/v5/trade/order", body=body) or {} + oid = str(d.get("order_id") or d.get("order_id_str") or "") + if not oid: + raise LiveError(f"HTX: биржа не вернула номер ордера ({d})", sent=True) + return oid + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + fill = self._fut_market(symbol, side, coins, reduce_only) + if not reduce_only and (tp or sl): + fill.tpsl = "HTX: TP/SL на бирже не поддерживается программой — закрывает программа" + return fill + + def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill: + size = _unsent(lambda: self._contract(symbol))["size"] + vol = math.floor(coins / size + 1e-9) + if vol <= 0: + raise LiveError("HTX: количество меньше одного контракта") + if _unsent(self._v5): + oid = self._v5_place(symbol, side, vol, reduce_only, None) + + def poll_v5(): + for _ in range(10): + o = self._v5_order(symbol, oid) + if o.get("state") in self.V5_FINAL: + return o + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + o = _placed(oid, poll_v5) + done = float(o.get("trade_volume") or 0) * size + if done <= 0: + raise LiveError(f"HTX: фьючерсный ордер не исполнен ({o.get('state')})") + price = float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]) + fee = abs(float(o.get("fee") or 0)) + return Fill(done, price, fee or done * price * self.fut_fee / 100, oid, o, bool(fee)) + d = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order", body={ + "contract_code": symbol, "volume": vol, "direction": side, "offset": "close" if reduce_only else "open", + "lever_rate": 1, "order_price_type": "optimal_20"}) + oid = d["order_id_str"] + + def poll(): + for _ in range(10): + info = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order_info", + body={"order_id": oid, "contract_code": symbol}) + o = info[0] if info else {} + if o.get("status") in (6, 5, 7): # filled / partially filled then cancelled / cancelled + return o + time.sleep(0.3) + raise LiveError("ордер не исполнился за 3 с") + o = _placed(oid, poll) + done = float(o.get("trade_volume") or 0) * size + if done <= 0: + raise LiveError("HTX: фьючерсный ордер не исполнен") + price = float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]) + fee = abs(float(o.get("fee") or 0)) + return Fill(done, price, fee or done * price * self.fut_fee / 100, oid, o, bool(fee)) + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + size = _unsent(lambda: self._contract(symbol))["size"] + vol = math.floor(coins / size + 1e-9) + if vol <= 0: + raise LiveError("HTX: количество меньше одного контракта") + if _unsent(self._v5): + return self._v5_place(symbol, side, vol, reduce_only, price) + d = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order", body={ + "contract_code": symbol, "volume": vol, "direction": side, "offset": "close" if reduce_only else "open", + "lever_rate": 1, "order_price_type": "limit", "price": price * _units(symbol[:-5])}) + return str(d["order_id_str"]) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + return self.fut_limit(symbol, side, coins, price, reduce_only=True) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + size = self._contract(symbol)["size"] + if self._v5(): + o = self._v5_order(symbol, order_id) + return {"coins": float(o.get("trade_volume") or 0) * size, + "price": float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]), + "fee": abs(float(o.get("fee") or 0)), "final": o.get("state") in self.V5_FINAL} + info = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order_info", + body={"order_id": order_id, "contract_code": symbol}) + o = info[0] if info else {} + return {"coins": float(o.get("trade_volume") or 0) * size, + "price": float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]), + "fee": abs(float(o.get("fee") or 0)), "final": o.get("status") in (5, 6, 7)} + + def fut_cancel(self, symbol: str, order_id: str) -> None: + if self._v5(): + self._call("POST", self.FUT, "/v5/trade/cancel_order", body={"order_id": order_id, "contract_code": symbol}) + return + self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_cancel", + body={"order_id": order_id, "contract_code": symbol}) + + def fut_cancel_all(self, symbol: str) -> None: + if self._v5(): + self._call("POST", self.FUT, "/v5/trade/cancel_all_orders", body={"contract_code": symbol}) + return + self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_cancelall", body={"contract_code": symbol}) + + def fut_position(self, symbol: str) -> float: + size = self._contract(symbol)["size"] + if self._v5(): + rows = self._call("GET", self.FUT, "/v5/trade/position/opens", {"contract_code": symbol}) or [] + + def sign(r: dict) -> int: # one-way mode: position_side "both", the side is direction + side = r.get("position_side") + return 1 if side == "long" or (side not in ("long", "short") and r.get("direction") == "buy") else -1 + return sum(float(r.get("volume") or 0) * size * sign(r) for r in rows + if r.get("contract_code", symbol) == symbol) + rows = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_position_info", + body={"contract_code": symbol}) or [] + return sum(float(r.get("volume") or 0) * size * (1 if r.get("direction") == "buy" else -1) for r in rows) + + def fut_liq_price(self, symbol: str) -> float | None: + if self._v5(): + rows = self._call("GET", self.FUT, "/v5/trade/position/opens", {"contract_code": symbol}) or [] + else: + rows = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_position_info", + body={"contract_code": symbol}) or [] + return _liq([r for r in rows if r.get("contract_code", symbol) == symbol], "liquidation_price", + _units(symbol[:-5]), lambda r: float(r.get("volume") or 0)) + + def _fut_account(self) -> tuple[float, float]: + """(equity, free margin) of the USDT futures account, $.""" + if self._v5(): + acc = self._call("GET", self.FUT, "/v5/account/balance") or {} + return float(acc.get("equity") or 0), float(acc.get("available_margin") or 0) + acc = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_account_info", body={"margin_account": "USDT"}) + a = acc[0] if acc else {} + return float(a.get("margin_balance") or 0), float(a.get("withdraw_available") or a.get("margin_available") or 0) + + def balances(self) -> dict: + items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"] + spot = sum(float(i["balance"]) for i in items if i["currency"] == "usdt" and i["type"] in ("trade", "frozen")) + out = {"Спот USDT": spot} + try: + out["Фьючерсы USDT"] = self._fut_account()[0] + except LiveError as exc: + out["Фьючерсы"] = str(exc) + return out + + unified = False + + def usdt_free(self) -> dict: + items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"] + spot = sum(float(i["balance"]) for i in items if i["currency"] == "usdt" and i["type"] == "trade") + return {"spot": spot, "futures": self._fut_account()[1]} + + def transfer_usdt(self, to: str, amount: float) -> None: + self._call("POST", self.SPOT, "/v2/account/transfer", body={ + "from": "spot" if to == "futures" else "linear-swap", "to": "linear-swap" if to == "futures" else "spot", + "currency": "usdt", "amount": float(_num(amount)), "margin-account": "USDT"}) + + +# -------------------------------------------------------------------------------------------------------------- +class Gate: + name = "Gate" + spot_fee, fut_fee = 0.1, 0.05 + HOST, PREFIX = "https://api.gateio.ws", "/api/v4" + + def __init__(self, key: str, secret: str) -> None: + self.key, self.secret = key, secret + self.rules: dict[str, dict] = {} + + def _call(self, method: str, path: str, params: dict | None = None, body: dict | None = None): + query = urllib.parse.urlencode(params or {}) + text = "" if body is None else json.dumps(body) + ts = str(int(time.time())) + payload = "\n".join([method, self.PREFIX + path, query, hashlib.sha512(text.encode()).hexdigest(), ts]) + sign = hmac.new(self.secret.encode(), payload.encode(), hashlib.sha512).hexdigest() + url = self.HOST + self.PREFIX + path + (f"?{query}" if query else "") + d = _http(method, url, {"KEY": self.key, "Timestamp": ts, "SIGN": sign, "Content-Type": "application/json", + "Accept": "application/json"}, text.encode() if body is not None else None) + if isinstance(d, dict) and d.get("label"): + raise LiveError(f"Gate {d.get('label')}: {d.get('message')}") + return d + + def _spot_step(self, base: str) -> float: + k = f"spot:{base}" + if k not in self.rules: + d = _http("GET", f"{self.HOST}{self.PREFIX}/spot/currency_pairs/{base}_USDT") + self.rules[k] = {"step": 10 ** -int(d.get("amount_precision", 4))} + return self.rules[k]["step"] + + def _spot_order(self, base: str, side: str, amount: str, fee_rate: float) -> Fill: + o = self._call("POST", "/spot/orders", body={"currency_pair": f"{base}_USDT", "type": "market", "side": side, + "amount": amount, "time_in_force": "ioc"}) + quote = float(o.get("filled_total") or 0) + price = float(o.get("avg_deal_price") or 0) + qty = float(o.get("filled_amount") or 0) or (quote / price if price else 0) + if qty <= 0: + raise LiveError(f"Gate: ордер не исполнен ({o.get('status')})") + fee, cur = float(o.get("fee") or 0), (o.get("fee_currency") or "").upper() + fee_usd = fee if cur == "USDT" else fee * quote / qty if cur == base else quote * fee_rate / 100 + return Fill(qty, quote / qty, fee_usd, str(o.get("id")), o) + + def spot_buy(self, base: str, usdt: float) -> Fill: + return self._spot_order(base, "buy", _num(round(usdt, 2)), self.spot_fee) + + def spot_sell(self, base: str, coins: float) -> Fill: + step = _unsent(lambda: self._spot_step(base)) + return self._spot_order(base, "sell", _num(_floor(coins, step)), self.spot_fee) + + def spot_coins(self) -> dict[str, float]: + return {a["currency"]: float(a.get("available") or 0) for a in self._call("GET", "/spot/accounts") or [] + if a.get("currency") != "USDT" and float(a.get("available") or 0) > 0} + + def spot_free(self, base: str) -> float: + items = self._call("GET", "/spot/accounts", {"currency": base}) + return float(items[0]["available"]) if items else 0.0 + + def _contract(self, symbol: str) -> dict: + k = f"fut:{symbol}" + if k not in self.rules: + d = _http("GET", f"{self.HOST}{self.PREFIX}/futures/usdt/contracts/{symbol}") + self.rules[k] = {"size": float(d.get("quanto_multiplier") or 1) * _units(symbol[:-5]), + "min": float(d.get("order_size_min") or 1)} + return self.rules[k] + + def fut_round(self, symbol: str, coins: float) -> float: + c = self._contract(symbol) + n = math.floor(coins / c["size"] + 1e-9) + return n * c["size"] if n >= c["min"] else 0.0 + + def fut_min_coins(self, symbol: str) -> float: + c = self._contract(symbol) + return c["size"] * max(1.0, c["min"]) + + def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None, + sl: float | None = None) -> Fill: + fill = self._fut_market(symbol, side, coins, reduce_only) + if not reduce_only and (tp or sl): + fill.tpsl = "Gate: TP/SL на бирже не поддерживается программой — закрывает программа" + return fill + + def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill: + c = _unsent(lambda: self._contract(symbol)) + n = math.floor(coins / c["size"] + 1e-9) + if n <= 0: + raise LiveError("Gate: количество меньше одного контракта") + o = self._call("POST", "/futures/usdt/orders", body={"contract": symbol, "size": n if side == "buy" else -n, + "price": "0", "tif": "ioc", "reduce_only": reduce_only}) + done = (abs(int(o.get("size") or 0)) - abs(int(o.get("left") or 0))) * c["size"] + if done <= 0: + raise LiveError(f"Gate: фьючерсный ордер не исполнен ({o.get('finish_as')})") + price = float(o.get("fill_price") or 0) / _units(symbol[:-5]) + fee, exact = self._order_fee(symbol, str(o.get("id"))) + return Fill(done, price, fee if exact else done * price * self.fut_fee / 100, str(o.get("id")), o, exact) + + def _order_fee(self, symbol: str, order_id: str) -> tuple[float, bool]: + """The fee Gate charged for the order, from its fills (the order answer has none); (0, False) if unread.""" + try: + fills = self._call("GET", "/futures/usdt/my_trades", {"contract": symbol, "order": order_id, "limit": 100}) + except LiveError: + return 0.0, False + fills = [f for f in fills or [] if str(f.get("order_id")) == order_id] + if not fills: + return 0.0, False + return sum(abs(float(f.get("fee") or 0)) for f in fills), True + + def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str: + c = _unsent(lambda: self._contract(symbol)) + n = math.floor(coins / c["size"] + 1e-9) + if n <= 0: + raise LiveError("Gate: количество меньше одного контракта") + o = self._call("POST", "/futures/usdt/orders", body={ + "contract": symbol, "size": n if side == "buy" else -n, "price": _num(price * _units(symbol[:-5])), + "tif": "gtc", "reduce_only": reduce_only}) + return str(o.get("id")) + + def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str: + return self.fut_limit(symbol, side, coins, price, reduce_only=True) + + def fut_order_status(self, symbol: str, order_id: str) -> dict: + c = self._contract(symbol) + o = self._call("GET", f"/futures/usdt/orders/{order_id}") + done = (abs(int(o.get("size") or 0)) - abs(int(o.get("left") or 0))) * c["size"] + price = float(o.get("fill_price") or 0) / _units(symbol[:-5]) + fee, exact = self._order_fee(symbol, str(order_id)) if done > 0 else (0.0, False) + return {"coins": done, "price": price, "fee": fee if exact else done * price * self.fut_fee / 100, + "final": o.get("status") == "finished"} + + def fut_cancel(self, symbol: str, order_id: str) -> None: + self._call("DELETE", f"/futures/usdt/orders/{order_id}") + + def fut_cancel_all(self, symbol: str) -> None: + self._call("DELETE", "/futures/usdt/orders", {"contract": symbol}) + + def _position_rows(self, symbol: str) -> list[dict]: + """The symbol's position rows: one in the single mode; two (dual_long + dual_short) when the account is in + the hedge (dual) mode — then Gate answers with a LIST, which must not read as «no position».""" + try: + d = self._call("GET", f"/futures/usdt/positions/{symbol}") + except LiveError as exc: + if "POSITION_NOT_FOUND" in str(exc): # never traded on this account: no position + return [] + raise + if isinstance(d, list): + return [r for r in d if isinstance(r, dict)] + return [d] if isinstance(d, dict) else [] + + def fut_position(self, symbol: str) -> float: + """Coins of the open position: + long, − short (both sides summed in the hedge mode).""" + size = self._contract(symbol)["size"] + return sum(float(r.get("size") or 0) for r in self._position_rows(symbol)) * size + + def fut_liq_price(self, symbol: str) -> float | None: + return _liq(self._position_rows(symbol), "liq_price", _units(symbol[:-5]), + lambda r: abs(float(r.get("size") or 0))) + + def balances(self) -> dict: + spot = self._call("GET", "/spot/accounts", {"currency": "USDT"}) + out = {"Спот USDT": float(spot[0]["available"]) + float(spot[0].get("locked") or 0) if spot else 0.0} + try: + # equity: the balance plus the open positions' unrealized result (not only the free part) + acc = self._fut_account() + out["Фьючерсы USDT"] = float(acc.get("total") or 0) + float(acc.get("unrealised_pnl") or 0) + except LiveError as exc: + out["Фьючерсы"] = str(exc) + return out + + unified = False + + def usdt_free(self) -> dict: + spot = self._call("GET", "/spot/accounts", {"currency": "USDT"}) + return {"spot": float(spot[0]["available"]) if spot else 0.0, + "futures": float(self._fut_account().get("available") or 0)} + + def _fut_account(self) -> dict: + """The USDT futures account; {} while it does not exist (Gate creates it with the first transfer: + USER_NOT_FOUND «please transfer funds first») — an empty account, not an error.""" + try: + return self._call("GET", "/futures/usdt/accounts") or {} + except LiveError as exc: + if "USER_NOT_FOUND" in str(exc): + return {} + raise + + def transfer_usdt(self, to: str, amount: float) -> None: + self._call("POST", "/wallet/transfers", body={ + "currency": "USDT", "from": "spot" if to == "futures" else "futures", + "to": "futures" if to == "futures" else "spot", "amount": _num(amount), "settle": "usdt"}) + + +def ensure_usdt(c, spot_need: float, futures_need: float) -> str: + """Make `spot_need` USDT free on the spot account and `futures_need` on the futures one by moving the shortfall + from the other account. Returns what was done ("" = nothing needed); LiveError when the total is not enough.""" + if getattr(c, "unified", False): + return "" + free = c.usdt_free() + spot_gap = max(0.0, spot_need - free["spot"]) + fut_gap = max(0.0, futures_need - free["futures"]) + if spot_gap <= 0 and fut_gap <= 0: + return "" + if spot_gap > 0 and fut_gap > 0 or free["spot"] + free["futures"] < spot_need + futures_need: + raise LiveError(f"не хватает USDT в сумме: нужно {spot_need:.2f} на споте и {futures_need:.2f} на фьючерсах, " + f"есть {free['spot']:.2f} и {free['futures']:.2f}") + to, gap = ("futures", fut_gap) if fut_gap > 0 else ("spot", spot_gap) + amount = math.ceil(gap * 100) / 100 + 0.01 # a cent of margin for rounding + c.transfer_usdt(to, amount) + return f"переведено {amount:.2f} USDT {'со спота на фьючерсы' if to == 'futures' else 'с фьючерсов на спот'}" + + +CLIENTS = {"bybit": Bybit, "binance": Binance, "mexc": Mexc, "htx": Htx, "gate": Gate} +_cache: dict[str, tuple[tuple[str, str], object]] = {} + + +def client(exchange: str): + """Client with the exchange's saved keys (rebuilt when the keys change); LiveError when no keys.""" + import keystore + keys = keystore.get(exchange) + if keys is None: + raise LiveError(f"{keystore.EXCHANGES.get(exchange, exchange)}: API-ключи не заданы") + cached = _cache.get(exchange) + if cached is None or cached[0] != keys: + cached = (keys, CLIENTS[exchange](*keys)) + _cache[exchange] = cached + return cached[1] diff --git a/main.py b/main.py new file mode 100644 index 0000000..ac594ad --- /dev/null +++ b/main.py @@ -0,0 +1,4821 @@ +from __future__ import annotations + +import json +import hashlib +import math +import os +import queue +import re +import threading +import time +import urllib.parse +import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed +from collections import deque +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +import tkinter as tk +from tkinter import messagebox, ttk +from bybit_live import BybitAPIError, BybitLiveClient +from credential_store import CredentialStoreError, delete_credentials, load_credentials, save_credentials +from historical_backtest import (fetch_funding_history, fetch_klines, prepare_universe, run_backtest, + run_mode_backtest, save_report) +import strategy + +try: + import websocket +except ImportError: + websocket = None + + +WS_URL = "wss://stream.bybit.com/v5/public/linear" +WINDOW_MS = 60_000 +CHART_SECONDS = 30 * 60 +CANDLE_INTERVAL_MINUTES = 1 +TAKER_FEE_PCT = 0.055 +AUTO_CURRENCY_SCAN_SECONDS = 10 * 60 +TOP_LIQUID_SYMBOLS = 100 +PUBLIC_MARKET_API_HOSTS = ("https://api.bybit.com", "https://api.bytick.com") +STRATEGY_DEFAULTS_VERSION = 2 +DEFAULT_CURRENCY_STRATEGY = { + "stake_pct": "5", + "max_adds": "2", + "leverage": "1", + "trigger_pct": "0.2", + "add_step_pct": "1.5", + "stop_loss_pct": "0", + "take_profit_pct": "10", +} +SETTINGS_FILE = Path(__file__).with_name("settings.json") +STATE_FILE = Path(__file__).with_name("account_state.json") +BACKTEST_REPORTS_DIR = Path(__file__).with_name("historical_reports") +HISTORICAL_MODE = "Исторический прогон" +UI_REDRAW_INTERVAL_MS = 250 +TILE_WIDTH = 184 +TILE_HEIGHT = 186 +TILE_GAP = 8 +MAX_EVENTS_PER_POLL = 2000 +MANUAL_CLOSE_CONFIRM_SECONDS = 15 + + +@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: + def __init__(self, root: tk.Tk) -> None: + self.root = root + self.root.title("Bybit — симулятор сделок в реальном времени") + self.root.geometry("1200x850") + self.root.minsize(900, 650) + self.events: queue.Queue[tuple] = queue.Queue() + self.ws_app = None + self.ws_thread: threading.Thread | None = None + self.running = False + self.historical_running = False + self._backtest_cancel = threading.Event() + self.symbol = "BTCUSDT" + self.symbol_states: dict[str, CurrencyState] = {} + self.currencies: list[str] = [] + self.enabled_symbols: set[str] = set() + self.currency_settings: dict[str, dict[str, str]] = {} + self.strategy_by_symbol: dict[str, dict[str, float]] = {} + self._has_saved_enabled_symbols = False + self.tile_widgets: dict[str, dict] = {} + self.detail_windows: dict[str, tk.Toplevel] = {} + self.ticker_24h: dict[str, float] = {} + self.ticker_turnover_24h: dict[str, float] = {} + self.ticker_prices: dict[str, float] = {} + self._ticker_poll_busy = False + self.ws_symbols: list[str] = [] + self.session_started_at = time.time() + self.prices: deque[tuple[float, float]] = deque() + # Candle fields: minute timestamp, open, high, low, close. + self.candles: deque[list[float]] = deque() + self.entry_markers: deque[tuple[float, float, int]] = deque() + self.last_price: float | None = None + self.balance = 5000.0 + self.initial_balance = 5000.0 + self.total_fees = 0.0 + self.position: Position | None = None + self.trades: list[ClosedTrade] = [] + self.next_id = 1 + self.last_signal_pct: float | None = None + self.last_signal_ready = False + self._previous_entry_signal_pct: float | None = None + self.applied_settings: dict[str, float] | None = None + self.baseline_close: float | None = None + self.interval_minutes = CANDLE_INTERVAL_MINUTES + self._last_signal_refresh_at = 0.0 + self._live_minute_prices: deque[tuple[float, float]] = deque() + self.last_ws_message = 0.0 + self.chart_visible_seconds = CHART_SECONDS + self.chart_view_end: float | None = None + self.chart_price_center: float | None = None + self.chart_price_span: float | None = None + self._drag_anchor: tuple[int, int, float, float, float, float] | None = None + self._settings_save_job: str | None = None + self.mode_var = tk.StringVar(value="Симуляция") + self.auto_currency_growth_var = tk.StringVar(value="20") + self.auto_currency_status_var = tk.StringVar(value="Загружаю список Bybit…") + self.ticker_data_source = "" + self.max_active_sim_positions_var = tk.StringVar(value="5") + self.rotation_pending_disable: set[str] = set() + self.auto_enabling_symbols: set[str] = set() + self.auto_symbol_retry_after: dict[str, float] = {} + self.next_auto_currency_scan_at = 0.0 + self.startup_currency_filter_busy = False + self.startup_currency_filter_approved_for: str | None = None + self.historical_days_var = tk.StringVar(value="30") + self.historical_initial_capital_var = tk.StringVar(value="5000") + self.historical_growth_var = tk.StringVar(value="30") + self.historical_min_equity_var = tk.StringVar(value="10") + self.api_key_var = tk.StringVar(value="") + self.api_secret_var = tk.StringVar(value="") + self.credentials_status_var = tk.StringVar(value="Ключи ещё не сохранены на этом компьютере.") + self.testnet_var = tk.BooleanVar(value=True) + self.live_account_var = tk.StringVar(value="") + self.live_position: Position | None = None + self.live_position_info: dict | None = None + self.live_trades: list[ClosedTrade] = [] + self.next_live_id = 1 + self.live_wallet: dict[str, float] | None = None + self.live_positions: list[dict] = [] + self.live_orders: list[dict] = [] + self.live_closed_pnl: list[dict] = [] + self.live_initial_deposits: dict[str, float] = {} + self.api_connecting = False + self.live_client: BybitLiveClient | None = None + self.live_spec: dict[str, str] | None = None + self.live_fee_pct = TAKER_FEE_PCT + self.live_commands: queue.Queue[tuple] = queue.Queue() + self.live_commands_by_symbol: dict[str, queue.Queue] = {} + self.live_workers: dict[str, threading.Thread] = {} + self.live_preparing_symbols: set[str] = set() + self.live_order_lock = threading.Lock() + # Trade ids are allocated from worker threads and the UI thread. + self._live_id_lock = threading.Lock() + self._redraw_job: str | None = None + self._dirty_symbols: set[str] = set() + self._dirty_main = False + self.ws_subscribed: set[str] = set() + self._ws_lock = threading.Lock() + self.historical_universe_var = tk.BooleanVar(value=False) + self.historical_funding_var = tk.BooleanVar(value=True) + # Strategy mode (classic / A / B) for simulation and the historical run. + self.strategy_mode = strategy.STRATEGY_CLASSIC + self.strategy_mode_var = tk.StringVar(value=strategy.STRATEGY_TITLES[self.strategy_mode]) + self.mode_settings: dict[str, dict[str, str]] = { + mode: {key: f"{value:g}" for key, value in defaults.items()} + for mode, defaults in strategy.MODE_DEFAULTS.items() + } + self.strategy_window: tk.Toplevel | None = None + self.ticker_funding_pct: dict[str, float] = {} + self._btc_regime_cache: tuple[float, int, bool | None] = (0.0, 0, None) + self._btc_regime_lock = threading.Lock() + self._signal_pool = ThreadPoolExecutor(max_workers=4) + self.live_control_thread: threading.Thread | None = None + self.live_order_busy = False + self.live_preflight = False + self.live_halted = False + self.live_transition_pending = False + self._build_ui() + self.default_currency_settings = { + "stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + } + self._load_saved_settings() + self._load_saved_credentials() + self._load_saved_state() + self._load_currency_settings(self.symbol) + if not self.currencies: + self._ensure_symbol(self.symbol) + if not self.enabled_symbols and not self._has_saved_enabled_symbols: + self.enabled_symbols.add(self.symbol) + self._ensure_symbol(self.symbol) + if self.position: + self._ensure_symbol(self.position.symbol).position = self.position + self.enabled_symbols.add(self.position.symbol) + if self.live_position: + self._ensure_symbol(self.live_position.symbol).live_position = self.live_position + self.enabled_symbols.add(self.live_position.symbol) + self._render_currency_tiles() + if self.live_position is not None: + self.mode_var.set("Реальная торговля") + self._refresh_settings_summary() + self.root.after(100, self._poll_events) + self.root.after(5000, self._refresh_rolling_change) + self.root.after(5000, self._poll_mode_signals) + self.root.protocol("WM_DELETE_WINDOW", self._on_close) + self._refresh_ui() + self._poll_ticker_24h() + + def _build_ui(self) -> None: + outer = ttk.Frame(self.root, padding=10) + outer.pack(fill="both", expand=True) + + header = ttk.Frame(outer) + header.pack(fill="x") + historical_controls = ttk.Frame(outer) + self.historical_controls_frame = historical_controls + self.auto_currency_controls_frame = ttk.Frame(outer) + self.simulation_controls_frame = ttk.Frame(outer) + self.start_btn = ttk.Button(header, text="Старт", command=self.start) + self.start_btn.pack(side="left") + self.stop_btn = ttk.Button(header, text="Стоп", command=self.stop, state="disabled") + self.stop_btn.pack(side="left", padx=6) + ttk.Label(header, text="Режим:").pack(side="left", padx=(12, 3)) + self.mode_combo = ttk.Combobox(header, textvariable=self.mode_var, + values=("Симуляция", HISTORICAL_MODE, "Реальная торговля"), + state="readonly", width=22) + self.mode_combo.pack(side="left") + self.mode_combo.bind("<>", self._on_mode_change) + strategy_row = ttk.Frame(outer) + strategy_row.pack(fill="x", pady=(4, 0)) + ttk.Label(strategy_row, text="Режим стратегии (симуляция и исторический прогон):").pack(side="left", padx=(0, 4)) + self.strategy_combo = ttk.Combobox( + strategy_row, textvariable=self.strategy_mode_var, state="readonly", width=42, + values=[strategy.STRATEGY_TITLES[mode] for mode in strategy.STRATEGY_MODES], + ) + self.strategy_combo.pack(side="left") + self.strategy_combo.bind("<>", self._on_strategy_mode_selected) + self.strategy_settings_btn = ttk.Button(strategy_row, text="Настройки режима…", + command=self.open_strategy_settings) + self.strategy_settings_btn.pack(side="left", padx=6) + self.strategy_hint_var = tk.StringVar(value="") + ttk.Label(strategy_row, textvariable=self.strategy_hint_var, foreground="#55606b").pack(side="left", padx=6) + self.historical_days_spin = ttk.Spinbox( + historical_controls, from_=1, to=365, textvariable=self.historical_days_var, width=5, + command=self._schedule_settings_save, + ) + self.historical_days_var.trace_add("write", self._schedule_settings_save) + self.historical_days_label = ttk.Label(historical_controls, text="Дней:") + self.historical_capital_label = ttk.Label(historical_controls, text="Депозит, USDT:") + self.historical_capital_entry = ttk.Entry( + historical_controls, textvariable=self.historical_initial_capital_var, width=9, + ) + self.historical_initial_capital_var.trace_add("write", self._schedule_settings_save) + self.historical_growth_label = ttk.Label(historical_controls, text="Рост 24 ч, мин. %:") + self.historical_growth_spin = ttk.Spinbox( + historical_controls, from_=0, to=1000, increment=0.1, + textvariable=self.historical_growth_var, width=7, + command=self._schedule_settings_save, + ) + self.historical_growth_var.trace_add("write", self._schedule_settings_save) + self.historical_equity_label = ttk.Label(historical_controls, text="Стоп капитала, %:") + self.historical_equity_spin = ttk.Spinbox( + historical_controls, from_=1, to=100, increment=1, + textvariable=self.historical_min_equity_var, width=5, + command=self._schedule_settings_save, + ) + self.historical_min_equity_var.trace_add("write", self._schedule_settings_save) + self.historical_days_label.pack(side="left", padx=(0, 2)) + self.historical_days_spin.pack(side="left") + self.historical_capital_label.pack(side="left", padx=(8, 2)) + self.historical_capital_entry.pack(side="left") + self.historical_growth_label.pack(side="left", padx=(8, 2)) + self.historical_growth_spin.pack(side="left") + self.historical_equity_label.pack(side="left", padx=(8, 2)) + self.historical_equity_spin.pack(side="left") + self.historical_universe_check = ttk.Checkbutton( + historical_controls, + text="Отбор валют как в реальном режиме (топ-100 по обороту, порог автоподбора, лимит позиций)", + variable=self.historical_universe_var, command=self._schedule_settings_save, + ) + self.historical_universe_check.pack(side="left", padx=(12, 0)) + ttk.Checkbutton( + historical_controls, text="Учитывать funding", + variable=self.historical_funding_var, command=self._schedule_settings_save, + ).pack(side="left", padx=(12, 0)) + ttk.Label( + self.auto_currency_controls_frame, + text="Автоподбор: топ-100 USDT perpetual по обороту · скан каждые 10 мин · рост за 24 ч выше:", + ).pack(side="left") + self.auto_currency_growth_spin = ttk.Spinbox( + self.auto_currency_controls_frame, from_=0, to=1000, increment=0.1, + textvariable=self.auto_currency_growth_var, width=7, + command=self._schedule_settings_save, + ) + self.auto_currency_growth_spin.pack(side="left", padx=(5, 2)) + ttk.Label(self.auto_currency_controls_frame, text="%").pack(side="left") + ttk.Label( + self.auto_currency_controls_frame, + textvariable=self.auto_currency_status_var, + ).pack(side="left", padx=(10, 0)) + self.auto_currency_growth_var.trace_add("write", self._schedule_settings_save) + self.live_settings_btn = ttk.Button(header, text="API Bybit…", command=self.open_live_settings) + self.live_settings_btn.pack(side="left", padx=5) + self.connect_btn = ttk.Button(header, text="Подключиться", command=self.connect_bybit) + self.connect_btn.pack(side="left", padx=5) + self.status_var = tk.StringVar(value="Остановлен") + ttk.Label(header, textvariable=self.status_var).pack(side="left", padx=8) + + self._build_settings_window() + self._build_live_settings_window() + + ttk.Label(self.simulation_controls_frame, text="Депозит симуляции, USDT:").pack(side="left") + self.simulation_deposit_entry = ttk.Entry( + self.simulation_controls_frame, textvariable=self.initial_var, width=9, + ) + self.simulation_deposit_entry.pack(side="left", padx=(4, 10)) + # The simultaneous-position limit is shared by simulation, live trading and the + # backtest, so it lives in the auto-selection row shown in both trading modes. + ttk.Label(self.auto_currency_controls_frame, text=" Макс. одновременных позиций:").pack(side="left") + self.max_active_sim_positions_spin = ttk.Spinbox( + self.auto_currency_controls_frame, from_=1, to=100, increment=1, + textvariable=self.max_active_sim_positions_var, width=5, + command=self._schedule_settings_save, + ) + self.max_active_sim_positions_spin.pack(side="left", padx=(4, 8)) + self.max_active_sim_positions_var.trace_add("write", self._schedule_settings_save) + ttk.Button( + self.simulation_controls_frame, text="Применить", + command=self.apply_simulation_controls, + ).pack(side="left") + + self.strategy_summary_var = tk.StringVar(value="") + self.strategy_summary_label = ttk.Label( + outer, + textvariable=self.strategy_summary_var, + padding=(8, 5), + relief="groove", + justify="left", + ) + # Legacy account/chart/history views stay instantiated for the existing + # refresh and persistence code, but are no longer part of the home screen. + + self.currencies_frame = ttk.LabelFrame(outer, text="Валюты · независимые параллельные стратегии", padding=6) + self.currencies_frame.pack(fill="both", expand=True, pady=(6, 0)) + self.main_metrics_frame = ttk.Frame(outer) + self.main_metrics_frame.pack(fill="x", pady=(6, 0), before=self.currencies_frame) + self.main_metric_vars: dict[str, tk.StringVar] = {} + self.main_metric_titles: dict[str, ttk.LabelFrame] = {} + for key, title in (("balance", "Баланс"), ("pnl", "P&L"), ("equity", "Общий баланс с P&L"), + ("free", "Свободно для новых сделок")): + box = ttk.LabelFrame(self.main_metrics_frame, text=title, padding=(8, 5)) + box.pack(side="left", fill="x", expand=True, padx=(0, 6)) + value_var = tk.StringVar(value="—") + ttk.Label(box, textvariable=value_var, font=("Segoe UI", 12, "bold")).pack(anchor="w") + self.main_metric_vars[key] = value_var + self.main_metric_titles[key] = box + # Tiles are laid out as a grid that wraps to the window width and scrolls vertically. + self.tiles_canvas = tk.Canvas(self.currencies_frame, highlightthickness=0, background="#eef2f5") + tiles_scroll = ttk.Scrollbar(self.currencies_frame, orient="vertical", command=self.tiles_canvas.yview) + self.tiles_canvas.configure(yscrollcommand=tiles_scroll.set) + tiles_scroll.pack(side="right", fill="y") + self.tiles_canvas.pack(side="left", fill="both", expand=True) + self.tiles_inner = ttk.Frame(self.tiles_canvas) + self.tiles_canvas_window = self.tiles_canvas.create_window((0, 0), window=self.tiles_inner, anchor="nw") + self.tiles_inner.bind("", lambda _event: self.tiles_canvas.configure(scrollregion=self.tiles_canvas.bbox("all"))) + self.tiles_canvas.bind("", lambda _event: self._layout_currency_tiles()) + for sequence in ("", "", ""): + self.tiles_canvas.bind_all(sequence, self._on_tiles_wheel, add="+") + self.tile_frames: dict[str, ttk.Frame] = {} + self.tile_add_button: ttk.Button | None = None + self._tile_layout_key: tuple | None = None + self._render_currency_tiles() + + self._legacy_views = ttk.Frame(outer) + metrics = ttk.Frame(self._legacy_views) + metrics.pack(fill="x", pady=5) + self.metric_vars: dict[str, tk.StringVar] = {} + self.metric_title_vars: dict[str, tk.StringVar] = {} + self.metric_boxes: dict[str, ttk.LabelFrame] = {} + for title, key in (("Баланс", "balance"), ("Бюджет всего", "equity"), ("Без стартового", "pnl"), ("Свободно", "free"), ("Комиссии", "fees")): + box = ttk.LabelFrame(metrics, text=title, padding=(8, 5)) + box.pack(side="left", fill="x", expand=True, padx=(0, 6)) + var = tk.StringVar(value="—") + self.metric_vars[key] = var + title_var = tk.StringVar(value=title) + self.metric_title_vars[key] = title_var + self.metric_boxes[key] = box + box.configure(text=title) + ttk.Label(box, textvariable=var, font=("Segoe UI", 12, "bold")).pack(anchor="w") + + chart_frame = ttk.LabelFrame(self._legacy_views, text="Рыночная цена · публичные сделки Bybit", padding=4) + chart_frame.pack(fill="both", expand=True, pady=(5, 8)) + chart_toolbar = ttk.Frame(chart_frame) + chart_toolbar.pack(fill="x", pady=(0, 3)) + self.market_price_var = tk.StringVar(value="Ожидание цены…") + ttk.Label(chart_toolbar, textvariable=self.market_price_var, font=("Segoe UI", 12, "bold")).pack(side="left", padx=4) + self.live_button = ttk.Button(chart_toolbar, text="К текущему времени", command=self._go_to_live) + self.live_button.pack(side="right", padx=4) + self.canvas = tk.Canvas(chart_frame, background="#101820", highlightthickness=0, height=340) + self.canvas.pack(fill="both", expand=True) + self.canvas.bind("", lambda _event: self._draw_chart()) + self.canvas.bind("", self._on_chart_wheel) + self.canvas.bind("", lambda event: self._on_chart_wheel_linux(event, 1)) + self.canvas.bind("", lambda event: self._on_chart_wheel_linux(event, -1)) + self.canvas.bind("", self._on_chart_press) + self.canvas.bind("", self._on_chart_drag) + self.canvas.bind("", self._on_chart_release) + self.canvas.bind("", self._reset_chart_view) + self.chart_hint_var = tk.StringVar(value="Колесо: масштаб · перетаскивание: перемещение · двойной щелчок: сброс масштаба") + ttk.Label(chart_frame, textvariable=self.chart_hint_var).pack(anchor="w") + + pos_frame = ttk.LabelFrame(self._legacy_views, text="Открытая сделка", padding=5) + pos_frame.pack(fill="x", pady=(0, 6)) + self.position_var = tk.StringVar(value="Нет открытой сделки") + ttk.Label(pos_frame, textvariable=self.position_var).pack(side="left", anchor="w", fill="x", expand=True) + self.close_trade_btn = ttk.Button(pos_frame, text="Закрыть сделку", command=self._manual_close_position, state="disabled") + self.close_trade_btn.pack(side="right", padx=(8, 0)) + + history_frame = ttk.LabelFrame(self._legacy_views, text="История и данные Bybit", padding=5) + history_frame.pack(fill="both", expand=False) + self.history_tabs = ttk.Notebook(history_frame) + self.history_tabs.pack(fill="both", expand=True) + trades_tab = ttk.Frame(self.history_tabs, padding=3) + orders_tab = ttk.Frame(self.history_tabs, padding=3) + positions_tab = ttk.Frame(self.history_tabs, padding=3) + self.history_tabs.add(trades_tab, text="Сделки / P&L") + self.history_tabs.add(orders_tab, text="Ордера Bybit") + self.history_tabs.add(positions_tab, text="Открытые позиции") + cols = ("id", "symbol", "entry", "exit", "roi", "gross", "fees", "net", "reason") + self.table = ttk.Treeview(trades_tab, columns=cols, show="headings", height=5) + self.table.tag_configure("profit", foreground="#13843b") + self.table.tag_configure("loss", foreground="#c62828") + headings = {"id": "#", "symbol": "Тикер", "entry": "Вход", "exit": "Выход", "roi": "ROI %", "gross": "Gross USDT", "fees": "Комиссии", "net": "Net USDT", "reason": "Причина"} + widths = {"id": 45, "symbol": 100, "entry": 115, "exit": 115, "roi": 80, "gross": 105, "fees": 100, "net": 100, "reason": 115} + for col in cols: + self.table.heading(col, text=headings[col]) + self.table.column(col, width=widths[col], anchor="center") + scrollbar = ttk.Scrollbar(trades_tab, orient="vertical", command=self.table.yview) + self.table.configure(yscrollcommand=scrollbar.set) + self.table.pack(side="left", fill="both", expand=True) + scrollbar.pack(side="right", fill="y") + + order_cols = ("time", "symbol", "side", "type", "qty", "price", "fill", "status", "id") + self.bybit_orders_table = ttk.Treeview(orders_tab, columns=order_cols, show="headings", height=5) + order_heads = {"time": "Время", "symbol": "Тикер", "side": "Сторона", "type": "Тип", "qty": "Количество", "price": "Цена", "fill": "Средняя исполнения", "status": "Статус", "id": "Order ID"} + order_widths = {"time": 135, "symbol": 90, "side": 70, "type": 95, "qty": 95, "price": 95, "fill": 130, "status": 110, "id": 210} + for col in order_cols: + self.bybit_orders_table.heading(col, text=order_heads[col]) + self.bybit_orders_table.column(col, width=order_widths[col], anchor="center") + order_scroll = ttk.Scrollbar(orders_tab, orient="vertical", command=self.bybit_orders_table.yview) + self.bybit_orders_table.configure(yscrollcommand=order_scroll.set) + self.bybit_orders_table.pack(side="left", fill="both", expand=True) + order_scroll.pack(side="right", fill="y") + + position_cols = ("symbol", "side", "size", "entry", "mark", "upl", "leverage", "tp", "sl") + self.bybit_positions_table = ttk.Treeview(positions_tab, columns=position_cols, show="headings", height=5) + position_heads = {"symbol": "Тикер", "side": "Сторона", "size": "Объём", "entry": "Средняя цена", "mark": "Mark price", "upl": "Unrealized P&L", "leverage": "Плечо", "tp": "TP", "sl": "SL"} + for col in position_cols: + self.bybit_positions_table.heading(col, text=position_heads[col]) + self.bybit_positions_table.column(col, width=110, anchor="center") + position_scroll = ttk.Scrollbar(positions_tab, orient="vertical", command=self.bybit_positions_table.yview) + self.bybit_positions_table.configure(yscrollcommand=position_scroll.set) + self.bybit_positions_table.pack(side="left", fill="both", expand=True) + position_scroll.pack(side="right", fill="y") + + def _ensure_symbol(self, symbol: str) -> CurrencyState: + symbol = symbol.strip().upper() + if symbol not in self.symbol_states: + self.symbol_states[symbol] = CurrencyState() + if symbol not in self.currencies: + self.currencies.append(symbol) + return self.symbol_states[symbol] + + def _capture_active_symbol(self) -> None: + if not hasattr(self, "symbol_states"): + return + state = self._ensure_symbol(self.symbol) + state.prices = self.prices + state.candles = self.candles + state.entry_markers = self.entry_markers + state.last_price = self.last_price + state.baseline_close = self.baseline_close + state.last_signal_pct = self.last_signal_pct + state.last_signal_ready = self.last_signal_ready + state.previous_entry_signal_pct = self._previous_entry_signal_pct + state.live_minute_prices = self._live_minute_prices + state.last_ws_message = self.last_ws_message + state.position = self.position + state.live_position = self.live_position + state.live_position_info = self.live_position_info + state.live_order_busy = self.live_order_busy + state.live_transition_pending = self.live_transition_pending + state.live_halted = self.live_halted + + def _activate_symbol_state(self, symbol: str) -> None: + state = self._ensure_symbol(symbol) + self.symbol = symbol + self.prices = state.prices + self.candles = state.candles + self.entry_markers = state.entry_markers + self.last_price = state.last_price + self.baseline_close = state.baseline_close + self.last_signal_pct = state.last_signal_pct + self.last_signal_ready = state.last_signal_ready + self._previous_entry_signal_pct = state.previous_entry_signal_pct + self._live_minute_prices = state.live_minute_prices + self.last_ws_message = state.last_ws_message + self.position = state.position + self.live_position = state.live_position + self.live_position_info = state.live_position_info + self.live_order_busy = state.live_order_busy + self.live_transition_pending = state.live_transition_pending + self.live_halted = state.live_halted + + def _render_currency_tiles(self) -> None: + if not hasattr(self, "tiles_inner"): + return + for child in self.tiles_inner.winfo_children(): + child.destroy() + self.tile_widgets.clear() + self.tile_frames.clear() + self._tile_layout_key = None + for symbol in list(self.currencies): + self._ensure_symbol(symbol) + tile = ttk.Frame(self.tiles_inner, width=TILE_WIDTH, height=TILE_HEIGHT, padding=7, relief="ridge") + # Fixed tile size so the grid stays even regardless of the text inside. + tile.grid_propagate(False) + tile.pack_propagate(False) + self.tile_frames[symbol] = tile + enabled = tk.BooleanVar(value=symbol in self.enabled_symbols) + toggle = ttk.Checkbutton(tile, text="В торгах", variable=enabled, + command=lambda s=symbol, v=enabled: self._toggle_symbol(s, v.get())) + toggle.pack(anchor="w") + title = ttk.Label(tile, text=symbol, font=("Segoe UI", 11, "bold"), cursor="hand2") + title.pack(anchor="w", pady=(3, 2)) + price = ttk.Label(tile, text="Цена: ждём данные", cursor="hand2") + price.pack(anchor="w") + change = ttk.Label(tile, text="24 ч: —", cursor="hand2") + change.pack(anchor="w") + session = ttk.Label(tile, text="Запуск: +0.00 USDT", cursor="hand2") + session.pack(anchor="w", pady=(4, 0)) + account = ttk.Label(tile, text="Аккаунт: +0.00 USDT", cursor="hand2") + account.pack(anchor="w") + status = ttk.Label(tile, text="Ожидание", foreground="#576574", cursor="hand2", + wraplength=TILE_WIDTH - 20) + status.pack(anchor="w", pady=(3, 0)) + for widget in (tile, title, price, change, session, account, status): + widget.bind("", lambda _e, s=symbol: self._open_currency_details(s)) + widget.bind("", lambda _e, s=symbol: self._open_currency_details(s)) + self.tile_widgets[symbol] = {"enabled": enabled, "price": price, "change": change, + "session": session, "account": account, "status": status} + self.tile_add_button = ttk.Button(self.tiles_inner, text="+\nДобавить\nвалюту", + command=self._add_currency_dialog, width=19) + self._refresh_currency_tiles() + self._layout_currency_tiles() + + def _tile_order(self) -> list[str]: + """Enabled pairs first, then the rest; each group by 24 h change, highest first.""" + def change(symbol: str) -> float: + value = self.ticker_24h.get(symbol) + return value if value is not None and math.isfinite(value) else float("-inf") + enabled = sorted((s for s in self.tile_frames if s in self.enabled_symbols), + key=lambda s: (-change(s), s)) + disabled = sorted((s for s in self.tile_frames if s not in self.enabled_symbols), + key=lambda s: (-change(s), s)) + return enabled + disabled + + def _layout_currency_tiles(self) -> None: + if not hasattr(self, "tiles_canvas") or not hasattr(self, "tile_frames"): + return + width = max(int(self.tiles_canvas.winfo_width()), TILE_WIDTH + TILE_GAP) + columns = max(1, width // (TILE_WIDTH + TILE_GAP)) + order = self._tile_order() + key = (columns, tuple(order)) + if key == self._tile_layout_key: + return # nothing moved: avoid re-gridding (and flicker) on every refresh + self._tile_layout_key = key + for index, symbol in enumerate(order): + self.tile_frames[symbol].grid(row=index // columns, column=index % columns, + padx=TILE_GAP // 2, pady=TILE_GAP // 2) + if self.tile_add_button is not None: + index = len(order) + self.tile_add_button.grid(row=index // columns, column=index % columns, + padx=TILE_GAP // 2, pady=TILE_GAP // 2, sticky="nsew") + self.tiles_inner.update_idletasks() + self.tiles_canvas.configure(scrollregion=self.tiles_canvas.bbox("all")) + + def _on_tiles_wheel(self, event: tk.Event) -> None: + # Scroll the tile grid only when the pointer is over it (charts use their own wheel zoom). + widget = event.widget + while widget is not None: + if widget is self.tiles_canvas: + break + widget = getattr(widget, "master", None) + else: + return + if getattr(event, "num", None) == 4 or getattr(event, "delta", 0) > 0: + self.tiles_canvas.yview_scroll(-1, "units") + else: + self.tiles_canvas.yview_scroll(1, "units") + + def _add_currency_dialog(self) -> None: + dialog = tk.Toplevel(self.root) + dialog.title("Добавить валюту") + dialog.transient(self.root) + dialog.resizable(False, False) + body = ttk.Frame(dialog, padding=14) + body.pack(fill="both", expand=True) + ttk.Label(body, text="Тикер USDT perpetual, например ETHUSDT").pack(anchor="w") + value = tk.StringVar() + entry = ttk.Entry(body, textvariable=value, width=24) + entry.pack(fill="x", pady=8) + entry.focus_set() + def add() -> None: + symbol = value.get().strip().upper() + if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol): + messagebox.showerror("Неверный тикер", "Введите тикер контракта, например ETHUSDT.", parent=dialog) + return + self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + self._select_symbol(symbol) + self._save_settings() + self._render_currency_tiles() + if self.running: + self._subscribe_running_symbols() + self._fetch_baseline_async(symbol, self.interval_minutes) + dialog.destroy() + ttk.Button(body, text="Добавить и включить", command=add).pack(anchor="e") + entry.bind("", lambda _event: add()) + + def _toggle_symbol(self, symbol: str, enabled: bool) -> None: + self._ensure_symbol(symbol) + if enabled: + self.enabled_symbols.add(symbol) + self.rotation_pending_disable.discard(symbol) + else: + self.enabled_symbols.discard(symbol) + self.rotation_pending_disable.discard(symbol) + self._save_settings() + if self.running: + if enabled and self.mode_var.get() == "Реальная торговля" and symbol not in self.live_commands_by_symbol and symbol not in self.live_preparing_symbols: + self._begin_live_additional_symbol(symbol) + if enabled and self.symbol_states[symbol].baseline_close is None: + self._fetch_baseline_async(symbol, self.interval_minutes) + self._subscribe_running_symbols() + self._refresh_currency_tiles() + self._refresh_ui() + + def _begin_live_additional_symbol(self, symbol: str) -> None: + client = self.live_client + if client is None: + self.status_var.set("Сначала подключите Bybit API") + return + base = self.applied_settings or self._safe_read_settings() + defaults = self._read_default_strategy(base) + settings = self._strategy_for_symbol(symbol, defaults) + self.live_preparing_symbols.add(symbol) + thread = threading.Thread(target=self._live_additional_symbol_worker, + args=(client, symbol, settings), daemon=True) + thread.start() + + def _live_additional_symbol_worker(self, client: BybitLiveClient, symbol: str, + settings: dict[str, float]) -> None: + try: + spec = client.get_instrument(symbol) + fee_pct = client.get_taker_fee_pct(symbol) + rows = client.get_positions(symbol) + if any(int(row.get("positionIdx", 0)) != 0 for row in rows): + raise BybitAPIError(f"{symbol}: для бота нужен режим позиции One-Way") + position_row = next((row for row in rows if float(row.get("size") or 0) > 0), None) + state = self.symbol_states.get(symbol) + shadow = state.live_position if state else None + if position_row: + if position_row.get("side") != "Buy": + raise BybitAPIError(f"{symbol}: бот сопровождает только LONG-позиции") + avg, qty = float(position_row.get("avgPrice") or 0), float(position_row.get("size") or 0) + leverage = float(position_row.get("leverage") or settings["leverage"]) + settings["leverage"] = leverage + shadow = Position(**vars(shadow)) if shadow else Position( + self._allocate_live_id(), symbol, avg, qty, avg * qty / leverage, + avg * qty * fee_pct / 100, time.time(), avg, settings["max_adds"]) + shadow.entry_price, shadow.qty, shadow.stake = avg, qty, avg * qty / leverage + tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + client.update_position_stops(symbol, + avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0, + avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0, + spec["tick_size"]) + else: + wallet = client.get_wallet() + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + if wallet["available"] < required: + raise BybitAPIError(f"{symbol}: недостаточно свободной маржи для первого входа") + client.set_leverage(symbol, settings["leverage"]) + settings["fee"] = fee_pct + self.events.put(("live_symbol_ready", symbol, settings, spec, fee_pct, position_row, shadow)) + except Exception as exc: + self.events.put(("live_symbol_failed", symbol, str(exc))) + + def _activate_live_symbol(self, symbol: str, settings: dict[str, float], spec: dict[str, str], + fee_pct: float, position_row: dict | None, shadow: Position | None) -> None: + self.auto_enabling_symbols.discard(symbol) + state = self._ensure_symbol(symbol) + state.live_position = shadow + state.live_position_info = position_row + state.live_halted = False + state.live_order_busy = False + state.live_transition_pending = False + if shadow: + self._reserve_live_id(shadow.trade_id) + self.strategy_by_symbol[symbol] = settings.copy() + commands = self.live_commands_by_symbol[symbol] = queue.Queue() + worker = threading.Thread(target=self._live_worker, + args=(self.live_client, symbol, settings.copy(), spec, fee_pct, shadow, commands), daemon=True) + self.live_workers[symbol] = worker + worker.start() + if position_row: + self._replace_cached_position(position_row) + self._fetch_baseline_async(symbol, self.interval_minutes) + self._subscribe_running_symbols() + self._save_account_state() + self._refresh_currency_tiles() + self.status_var.set(f"Параллельное управление включено · {symbol}") + + def _select_symbol(self, symbol: str) -> None: + changed = symbol != self.symbol + if changed: + self._capture_active_symbol() + self._activate_symbol_state(symbol) + self.symbol_var.set(symbol) + self._load_currency_settings(symbol) + if symbol in self.strategy_by_symbol: + self.applied_settings = self.strategy_by_symbol[symbol].copy() + elif self.currency_settings.get(symbol): + self.applied_settings = self._strategy_for_symbol(symbol, self._safe_read_settings()) + if changed: + self.chart_view_end = None + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self._refresh_price_label() + self._refresh_ui() + self._draw_chart() + + def _load_currency_settings(self, symbol: str) -> None: + values = self.currency_settings.get(symbol) or self.default_currency_settings + variable_map = {"stake_pct": self.stake_var, "max_adds": self.max_adds_var, + "leverage": self.leverage_var, "trigger_pct": self.trigger_var, + "add_step_pct": self.add_step_var, "stop_loss_pct": self.stop_loss_var, + "take_profit_pct": self.take_profit_var} + for key, variable in variable_map.items(): + if key in values: + variable.set(str(values[key])) + + def _strategy_for_symbol(self, symbol: str, fallback: dict[str, float]) -> dict[str, float]: + if not self.currency_settings.get(symbol): + return fallback.copy() + variables = (self.stake_var, self.max_adds_var, self.leverage_var, self.trigger_var, + self.add_step_var, self.stop_loss_var, self.take_profit_var) + snapshot = [(variable, variable.get()) for variable in variables] + try: + self._load_currency_settings(symbol) + parsed = self._read_settings() + parsed["initial"] = fallback["initial"] + parsed["deposit_basis"] = fallback.get("deposit_basis", fallback["initial"]) + parsed["stake"] = parsed["deposit_basis"] * parsed["stake_pct"] / 100 + return parsed + except ValueError: + return fallback.copy() + finally: + for variable, value in snapshot: + variable.set(value) + + def _read_default_strategy(self, fallback: dict[str, float]) -> dict[str, float]: + variables = {"stake_pct": self.stake_var, "max_adds": self.max_adds_var, + "leverage": self.leverage_var, "trigger_pct": self.trigger_var, + "add_step_pct": self.add_step_var, "stop_loss_pct": self.stop_loss_var, + "take_profit_pct": self.take_profit_var} + snapshot = [(variable, variable.get()) for variable in variables.values()] + try: + for key, variable in variables.items(): + variable.set(str(self.default_currency_settings.get(key, variable.get()))) + parsed = self._read_settings() + parsed["initial"] = fallback["initial"] + parsed["deposit_basis"] = fallback.get("deposit_basis", fallback["initial"]) + parsed["stake"] = parsed["deposit_basis"] * parsed["stake_pct"] / 100 + return parsed + except ValueError: + return fallback.copy() + finally: + for variable, value in snapshot: + variable.set(value) + + def _open_currency_details(self, symbol: str) -> None: + self._select_symbol(symbol) + window = self.detail_windows.get(symbol) + if window and window.winfo_exists(): + self._load_detail_strategy_fields(symbol, window) + window.deiconify() + window.lift() + return + window = tk.Toplevel(self.root) + window.title(f"{symbol} · стратегия и график") + window.geometry("1100x800") + window.minsize(820, 600) + self.detail_windows[symbol] = window + if len(self.symbol_states[symbol].candles) < 10: + self._fetch_chart_candles_async(symbol, self.interval_minutes) + toolbar = ttk.Frame(window, padding=8) + toolbar.pack(fill="x") + ttk.Label(toolbar, text=symbol, font=("Segoe UI", 13, "bold")).pack(side="left") + metrics = ttk.Label(toolbar, text="") + metrics.pack(side="left", padx=16) + close_button = ttk.Button(toolbar, text="Закрыть сделку", + command=lambda s=symbol: self._close_from_detail(s), state="disabled") + close_button.pack(side="right", padx=(6, 0)) + window._close_button = close_button + strategy_frame = ttk.LabelFrame(window, text=f"Стратегия · {symbol}", padding=8) + strategy_frame.pack(fill="x", padx=8, pady=(0, 6)) + fields = ( + ("stake_pct", "Ставка, % депозита"), ("max_adds", "Количество доливок"), + ("leverage", "Плечо"), ("trigger_pct", "Рост для входа, %"), + ("add_step_pct", "Шаг доливки при снижении, %"), + ("stop_loss_pct", "Стоп от средней цены, %"), + ("take_profit_pct", "TP от средней цены, %"), + ) + window._strategy_vars = {} + for index, (key, label) in enumerate(fields): + row, column = divmod(index, 4) + cell = ttk.Frame(strategy_frame) + cell.grid(row=row, column=column, sticky="w", padx=(0, 12), pady=3) + ttk.Label(cell, text=label).pack(anchor="w") + variable = tk.StringVar() + window._strategy_vars[key] = variable + ttk.Entry(cell, textvariable=variable, width=15).pack(anchor="w") + ttk.Button(strategy_frame, text="Применить для этой валюты", + command=lambda s=symbol, w=window: self._apply_detail_strategy(s, w)).grid( + row=1, column=3, sticky="e", padx=4, pady=4) + ttk.Button(strategy_frame, text="Сделать дефолтными и применить ко всем", + command=lambda s=symbol, w=window: self._apply_detail_strategy(s, w, all_symbols=True)).grid( + row=2, column=3, sticky="e", padx=4, pady=4) + window._strategy_status = tk.StringVar(value="Настройки сохраняются отдельно для этой валюты.") + ttk.Label(strategy_frame, textvariable=window._strategy_status).grid( + row=3, column=0, columnspan=4, sticky="w", pady=(4, 0)) + for index in range(4): + strategy_frame.columnconfigure(index, weight=1) + self._load_detail_strategy_fields(symbol, window) + chart = tk.Canvas(window, background="#101820", highlightthickness=0) + chart.pack(fill="both", expand=True, padx=8, pady=(0, 8)) + window._symbol_chart = chart + window._symbol_metrics = metrics + chart.bind("", lambda _event, s=symbol: self._draw_detail_chart(s)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel_linux, event, 1)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel_linux, event, -1)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_press, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_drag, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_release, event)) + chart.bind("", lambda event, s=symbol: self._detail_chart_action(s, self._reset_chart_view, event)) + window.protocol("WM_DELETE_WINDOW", lambda s=symbol: self._close_detail(s)) + self._draw_detail_chart(symbol) + + def _load_detail_strategy_fields(self, symbol: str, window: tk.Toplevel) -> None: + if not hasattr(window, "_strategy_vars"): + return + values = self.currency_settings.get(symbol) or self.default_currency_settings + for key, variable in window._strategy_vars.items(): + variable.set(str(values.get(key, ""))) + if hasattr(window, "_strategy_status"): + window._strategy_status.set( + f"Индивидуальные настройки классического режима: {symbol}" + if self.strategy_mode == strategy.STRATEGY_CLASSIC else + f"Сейчас выбран режим «{strategy.STRATEGY_TITLES[self.strategy_mode]}»: его параметры общие для всех " + "валют («Настройки режима…»). Поля ниже относятся только к классическому режиму." + ) + + def _apply_detail_strategy(self, symbol: str, window: tk.Toplevel, *, all_symbols: bool = False) -> None: + if not window.winfo_exists(): + return + self._ensure_symbol(symbol) + values = {key: variable.get().strip().replace(",", ".") + for key, variable in window._strategy_vars.items()} + try: + stake_pct = float(values["stake_pct"]) + max_adds = float(values["max_adds"]) + leverage = float(values["leverage"]) + trigger = float(values["trigger_pct"]) + add_step = float(values["add_step_pct"]) + stop_loss = float(values["stop_loss_pct"]) + take_profit = float(values["take_profit_pct"]) + numeric = (stake_pct, max_adds, leverage, trigger, add_step, stop_loss, take_profit) + if any(not math.isfinite(value) for value in numeric): + raise ValueError("Все поля должны содержать конечные числа.") + if stake_pct <= 0 or stake_pct > 100: + raise ValueError("Ставка должна быть больше 0% и не больше 100%.") + if max_adds < 0 or not max_adds.is_integer() or max_adds > 100: + raise ValueError("Количество доливок должно быть целым числом от 0 до 100.") + if leverage < 1 or leverage > 100: + raise ValueError("Плечо должно быть от 1 до 100 (Bybit не принимает плечо меньше 1).") + if trigger <= 0 or add_step < 0 or stop_loss < 0 or take_profit < 0: + raise ValueError("Рост для входа должен быть больше 0; остальные проценты не могут быть отрицательными.") + if stop_loss == 0 and take_profit == 0: + raise ValueError("Укажите TP, стоп-лосс или оба уровня.") + except (KeyError, ValueError) as exc: + messagebox.showerror("Проверьте настройки", str(exc), parent=window) + return + + self._capture_active_symbol() + targets = list(self.currencies) if all_symbols else [symbol] + if symbol not in targets: + targets.append(symbol) + account_settings = self.applied_settings or self._safe_read_settings() + deposit_basis = (self._current_live_deposit_basis() or account_settings.get("deposit_basis", 0) + if self.mode_var.get() == "Реальная торговля" + else account_settings.get("initial", self.initial_balance)) + target_stake = deposit_basis * stake_pct / 100 + if self.mode_var.get() == "Реальная торговля": + incompatible = [target for target in targets + if self._ensure_symbol(target).live_position + and self.strategy_by_symbol.get(target, {}).get("leverage") != leverage] + if incompatible: + messagebox.showerror( + "Открыта реальная позиция", + "Нельзя изменить плечо для валют с открытыми позициями: " + ", ".join(incompatible), + parent=window, + ) + return + elif self.running and target_stake > self.balance: + messagebox.showerror("Проверьте ставку", "Ставка на каждый вход не может превышать свободный баланс.", parent=window) + return + + for target in targets: + self._ensure_symbol(target) + settings = { + **account_settings, + "initial": account_settings.get("initial", self.initial_balance), + "deposit_basis": deposit_basis, + "stake_pct": stake_pct, + "stake": target_stake, + "max_adds": int(max_adds), + "leverage": leverage, + "trigger": trigger, + "add_step": add_step, + "stop_loss": stop_loss, + "take_profit": take_profit, + "fee": self.live_fee_pct if self.mode_var.get() == "Реальная торговля" else TAKER_FEE_PCT, + "interval": float(CANDLE_INTERVAL_MINUTES), + } + self.currency_settings[target] = values.copy() + self.strategy_by_symbol[target] = settings.copy() + if self.symbol == target: + self._load_currency_settings(target) + self.applied_settings = settings.copy() + commands = self.live_commands_by_symbol.get(target) + state = self._ensure_symbol(target) + if commands and not state.live_order_busy: + state.live_order_busy = True + commands.put(("settings", time.time(), state.last_price or 0.0, settings.copy())) + if all_symbols: + self.default_currency_settings = values.copy() + self._save_settings() + self._save_account_state() + self._refresh_currency_tiles(set(targets)) + self._refresh_settings_summary() + if all_symbols: + window._strategy_status.set( + f"Настройки применены к {len(targets)} валютам и сохранены как значения по умолчанию." + ) + self.status_var.set(f"Дефолтная стратегия обновлена и применена к {len(targets)} валютам") + else: + window._strategy_status.set(f"Настройки применены только для {symbol}.") + self.status_var.set(f"Индивидуальная стратегия {symbol} сохранена") + + def _close_detail(self, symbol: str) -> None: + window = self.detail_windows.pop(symbol, None) + if window and window.winfo_exists(): + window.destroy() + + def _close_from_detail(self, symbol: str) -> None: + self._select_symbol(symbol) + self._manual_close_position() + + def _draw_detail_chart(self, symbol: str) -> None: + window = self.detail_windows.get(symbol) + if not window or not window.winfo_exists(): + return + self._capture_active_symbol() + active_symbol = self.symbol + active_canvas = self.canvas + self._activate_symbol_state(symbol) + self.canvas = window._symbol_chart + try: + self._draw_chart() + state = self._ensure_symbol(symbol) + pct = self.ticker_24h.get(symbol) + position = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position + exchange_position = next((row for row in self.live_positions if row.get("symbol") == symbol + and float(row.get("size") or 0) > 0), None) + window._symbol_metrics.configure(text=( + f"Цена {self._fmt_price(state.last_price or self.ticker_prices.get(symbol)) if (state.last_price or self.ticker_prices.get(symbol)) else '—'} · " + f"24 ч {pct:+.2f}%" if pct is not None else "24 ч —" + ) + (f" · позиция {position.entry_price:g}" if position else + f" · Bybit {exchange_position.get('side')} · P&L {float(exchange_position.get('unrealisedPnl') or 0):+.2f}" + if exchange_position else " · без позиции")) + window._close_button.configure(state="normal" if self.running and position else "disabled") + finally: + self.canvas = active_canvas + self._activate_symbol_state(active_symbol) + + def _detail_chart_action(self, symbol: str, callback, *args): + window = self.detail_windows.get(symbol) + if not window or not window.winfo_exists(): + return + active_symbol = self.symbol + active_canvas = self.canvas + self._capture_active_symbol() + self._activate_symbol_state(symbol) + self.canvas = window._symbol_chart + try: + callback(*args) + finally: + self._capture_active_symbol() + self.canvas = active_canvas + self._activate_symbol_state(active_symbol) + self._refresh_currency_tiles() + return "break" + + def _refresh_currency_tiles(self, only_symbols: set[str] | None = None) -> None: + if not hasattr(self, "tile_widgets"): + return + for symbol, widgets in list(self.tile_widgets.items()): + if only_symbols is not None and symbol not in only_symbols: + continue + state = self._ensure_symbol(symbol) + if not widgets["price"].winfo_exists(): + continue + widgets["enabled"].set(symbol in self.enabled_symbols) + current_price = state.last_price or self.ticker_prices.get(symbol) + widgets["price"].configure(text=f"Цена: {self._fmt_price(current_price) if current_price else '—'}") + pct = self.ticker_24h.get(symbol) + widgets["change"].configure(text=f"24 ч: {pct:+.2f}%" if pct is not None else "24 ч: —", + foreground="#13843b" if pct and pct > 0 else "#c62828" if pct and pct < 0 else "") + session_pnl = sum(t.net_pnl for t in self.trades if t.symbol == symbol and t.opened_at >= getattr(self, "session_started_at", 0)) + session_pnl += sum(t.net_pnl for t in self.live_trades if t.symbol == symbol and t.opened_at >= getattr(self, "session_started_at", 0)) + account_pnl = sum(t.net_pnl for t in self.trades if t.symbol == symbol) + local_live_total = sum(t.net_pnl for t in self.live_trades if t.symbol == symbol) + exchange_live_total = sum(float(row.get("closedPnl") or 0) for row in self.live_closed_pnl + if row.get("symbol") == symbol) + account_pnl += max(local_live_total, exchange_live_total) + state_position = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position + exchange_position = next((row for row in self.live_positions if row.get("symbol") == symbol + and float(row.get("size") or 0) > 0), None) + if state_position and state.last_price: + current_unrealized = strategy.unrealized_pnl(state_position.side, state_position.entry_price, + state.last_price, state_position.qty) + if state.live_position: + current_unrealized = float((state.live_position_info or {}).get("unrealisedPnl") or current_unrealized) + session_pnl += current_unrealized + account_pnl += current_unrealized + elif exchange_position: + exchange_unrealized = float(exchange_position.get("unrealisedPnl") or 0) + account_pnl += exchange_unrealized + widgets["session"].configure(text=f"Запуск: {session_pnl:+.2f} USDT") + widgets["account"].configure(text=f"Аккаунт: {account_pnl:+.2f} USDT") + pos = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position + if pos: + status_text = ("Сделка · выключится после закрытия" + if symbol in self.rotation_pending_disable else + f"{pos.side.upper()} · стоп {self._fmt_price(pos.stop_price)}" + if pos.mode != strategy.STRATEGY_CLASSIC else + f"В позиции · {pos.add_count + 1} входов") + elif state.mode_signal and self.running and self.mode_var.get() == "Симуляция": + status_text = f"Сигнал {state.mode_signal['side'].upper()} · ждёт входа" + elif exchange_position: + status_text = ("Сделка · выключится после закрытия" + if symbol in self.rotation_pending_disable else + f"Bybit {exchange_position.get('side')} · P&L {float(exchange_position.get('unrealisedPnl') or 0):+.2f}") + else: + status_text = ("Выключена" if symbol in self.rotation_pending_disable else + "В торгах" if symbol in self.enabled_symbols else "Выключена") + widgets["status"].configure(text=status_text) + if only_symbols is None: + self._layout_currency_tiles() + + def _poll_ticker_24h(self) -> None: + if not self._ticker_poll_busy: + self._ticker_poll_busy = True + def worker() -> None: + try: + snapshot, source, funding = self._fetch_ticker_snapshot() + self.events.put(("ticker_24h", snapshot, source, funding)) + except Exception as exc: + # Keep market-data failures visible: otherwise the scanner appears + # connected via WebSocket while its separate REST feed is empty. + self.events.put(("ticker_24h_error", str(exc))) + finally: + self._ticker_poll_busy = False + threading.Thread(target=worker, daemon=True).start() + if self.root.winfo_exists(): + self.root.after(15000, self._poll_ticker_24h) + + @staticmethod + def _fetch_ticker_snapshot() -> tuple[dict[str, tuple[float, float, float]], str, dict[str, float]]: + """(symbol → (price, 24h change %, 24h turnover), host, symbol → current funding rate %).""" + errors = [] + for host in PUBLIC_MARKET_API_HOSTS: + try: + request = urllib.request.Request( + f"{host}/v5/market/tickers?category=linear", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}, + ) + with urllib.request.urlopen(request, timeout=10) as response: + payload = json.loads(response.read().decode("utf-8")) + if payload.get("retCode") != 0: + raise RuntimeError(f"Bybit retCode {payload.get('retCode')}: {payload.get('retMsg', 'ошибка запроса')}") + snapshot = {} + funding: dict[str, float] = {} + for row in payload.get("result", {}).get("list", []): + symbol = str(row.get("symbol") or "").upper() + if not symbol.endswith("USDT"): + continue + try: + snapshot[symbol] = ( + float(row.get("lastPrice") or 0), + float(row.get("price24hPcnt") or 0) * 100, + float(row.get("turnover24h") or 0), + ) + if row.get("fundingRate") not in (None, ""): + funding[symbol] = float(row["fundingRate"]) * 100 + except (TypeError, ValueError): + continue + if not snapshot: + raise RuntimeError("Bybit вернул пустой список USDT-контрактов") + return snapshot, host, funding + except Exception as exc: + errors.append(f"{host}: {exc}") + raise RuntimeError("Не удалось загрузить тикеры. " + " · ".join(errors)) + + def _symbol_has_open_position(self, symbol: str) -> bool: + state = self.symbol_states.get(symbol) + if state and (state.position is not None or state.live_position is not None): + return True + return any(row.get("symbol") == symbol and float(row.get("size") or 0) > 0 + for row in self.live_positions) + + def _finish_auto_retirement(self, symbol: str) -> bool: + if symbol not in self.rotation_pending_disable or self._symbol_has_open_position(symbol): + return False + self.rotation_pending_disable.discard(symbol) + self.enabled_symbols.discard(symbol) + if self.running: + self._subscribe_running_symbols() + self._save_settings() + self._render_currency_tiles() + return True + + def _auto_enable_symbol(self, symbol: str) -> bool: + if symbol in self.enabled_symbols: + self.rotation_pending_disable.discard(symbol) + return False + if time.monotonic() < self.auto_symbol_retry_after.get(symbol, 0.0): + return False + self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + self.rotation_pending_disable.discard(symbol) + base = self.applied_settings or self._safe_read_settings() + defaults = self._read_default_strategy(base) + settings = self._strategy_for_symbol(symbol, defaults) + self.strategy_by_symbol[symbol] = settings.copy() + if self.running: + if self.mode_var.get() == "Реальная торговля": + if symbol not in self.live_commands_by_symbol and symbol not in self.live_preparing_symbols: + self.auto_enabling_symbols.add(symbol) + self._begin_live_additional_symbol(symbol) + else: + self._fetch_baseline_async(symbol, self.interval_minutes) + return True + + def _maybe_auto_rotate_currencies(self) -> None: + if not self.running or self.mode_var.get() not in ("Симуляция", "Реальная торговля"): + return + now = time.monotonic() + if now < self.next_auto_currency_scan_at: + return + try: + threshold = float(self.auto_currency_growth_var.get().strip().replace(",", ".")) + except (ValueError, tk.TclError): + self.auto_currency_status_var.set("Ошибка: проверьте порог роста за 24 ч") + self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS + return + if not math.isfinite(threshold) or not 0 <= threshold <= 1000: + self.auto_currency_status_var.set("Ошибка: порог должен быть от 0 до 1000%") + self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS + return + if not self.ticker_turnover_24h: + self.auto_currency_status_var.set("Ожидаю котировки Bybit REST…") + self.next_auto_currency_scan_at = now + 30 + return + self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS + ranked = sorted( + ((symbol, turnover) for symbol, turnover in self.ticker_turnover_24h.items() + if re.fullmatch(r"[A-Z0-9]+USDT", symbol) and turnover > 0), + key=lambda item: item[1], reverse=True, + )[:TOP_LIQUID_SYMBOLS] + top_symbols = {symbol for symbol, _turnover in ranked} + eligible = {symbol for symbol in top_symbols + if self.ticker_24h.get(symbol, float("-inf")) > threshold} + for symbol in list(self.auto_symbol_retry_after): + if symbol not in eligible: + self.auto_symbol_retry_after.pop(symbol, None) + observed = set(self.ticker_turnover_24h) + removed = 0 + deferred = 0 + changed = False + for symbol in list(self.enabled_symbols): + # Missing ticker data is treated as a temporary API omission, not as a reason to retire a pair. + if symbol not in observed or symbol in eligible: + if symbol in eligible: + self.rotation_pending_disable.discard(symbol) + continue + if self._symbol_has_open_position(symbol): + self.rotation_pending_disable.add(symbol) + deferred += 1 + else: + self.rotation_pending_disable.discard(symbol) + self.enabled_symbols.discard(symbol) + removed += 1 + changed = True + added = 0 + for symbol in sorted(eligible): + if symbol not in self.enabled_symbols: + if self._auto_enable_symbol(symbol): + added += 1 + changed = True + if changed: + if self.mode_var.get() == "Симуляция": + self._subscribe_running_symbols() + self._save_settings() + self._refresh_currency_tiles() + self.auto_currency_status_var.set( + f"Подходят: {len(eligible)} · новых: {added} · отключено: {removed} · ждут закрытия: {deferred}" + ) + + def _begin_startup_currency_filter(self, mode: str, threshold: float) -> None: + """Fetch fresh Bybit tickers before enabling any strategy entries.""" + if self.startup_currency_filter_busy: + return + self.startup_currency_filter_busy = True + self.start_btn.configure(state="disabled") + self.mode_combo.configure(state="disabled") + self.status_var.set(f"Проверяю рост за 24 ч перед запуском · порог {threshold:g}%…") + + def worker() -> None: + try: + snapshot, source, funding = self._fetch_ticker_snapshot() + self.ticker_funding_pct.update(funding) + self.events.put(("startup_currency_filter_ready", mode, threshold, snapshot, source)) + except Exception as exc: + self.events.put(("startup_currency_filter_failed", mode, str(exc))) + + threading.Thread(target=worker, daemon=True).start() + + def _apply_startup_currency_filter( + self, mode: str, threshold: float, + snapshot: dict[str, tuple[float, float, float]], source: str, + ) -> None: + for symbol, (price, change, turnover) in snapshot.items(): + self.ticker_prices[symbol] = price + self.ticker_24h[symbol] = change + self.ticker_turnover_24h[symbol] = turnover + self.ticker_data_source = source + + ranked = sorted( + ((symbol, row[2]) for symbol, row in snapshot.items() + if re.fullmatch(r"[A-Z0-9]+USDT", symbol) and row[2] > 0), + key=lambda item: item[1], reverse=True, + )[:TOP_LIQUID_SYMBOLS] + top_symbols = {symbol for symbol, _turnover in ranked} + eligible = {symbol for symbol in top_symbols if snapshot[symbol][1] > threshold} + known_symbols = set(self.currencies) | set(self.symbol_states) + known_symbols.update(str(row.get("symbol") or "").upper() for row in self.live_positions) + open_symbols = {symbol for symbol in known_symbols if self._symbol_has_open_position(symbol)} + + # Existing positions remain managed even when their currency misses the entry filter. + selected = eligible | open_symbols + self.rotation_pending_disable = open_symbols - eligible + self.enabled_symbols = set(selected) + for symbol in sorted(eligible): + self._ensure_symbol(symbol) + self._save_settings() + self._render_currency_tiles() + self._refresh_currency_tiles() + self.auto_currency_status_var.set( + f"Предстартовый отбор · топ-{len(top_symbols)} по обороту · порог > {threshold:g}% · подходит {len(eligible)}" + ) + self.startup_currency_filter_approved_for = mode + if not selected: + self.startup_currency_filter_approved_for = None + self.start_btn.configure(state="normal") + self.status_var.set(f"Запуск отменён: в топ-{TOP_LIQUID_SYMBOLS} нет валют с ростом выше {threshold:g}% за 24 ч") + messagebox.showwarning( + "Нет валют для запуска", + f"В топ-{TOP_LIQUID_SYMBOLS} по обороту сейчас нет валют с ростом выше {threshold:g}% за 24 часа.", + ) + return + self.start_btn.configure(state="normal") + self.status_var.set(f"Отбор завершён · подходит {len(eligible)} валют · продолжаю запуск") + self.start() + + @staticmethod + def _ws_send_topics(ws, op: str, symbols: list[str]) -> None: + # Bybit accepts a limited number of args per request; send in chunks of 10. + for index in range(0, len(symbols), 10): + chunk = symbols[index:index + 10] + ws.send(json.dumps({"op": op, "args": [f"publicTrade.{symbol}" for symbol in chunk]})) + + def _subscribe_running_symbols(self) -> None: + symbols = sorted(self.enabled_symbols | {s for s, state in self.symbol_states.items() + if state.position or state.live_position}) + self.ws_symbols = symbols + app = self.ws_app + sock = getattr(app, "sock", None) if app else None + if sock is not None and getattr(sock, "connected", False): + # Change topics on the live socket so trades of other pairs are not lost + # during a reconnect (open positions keep receiving prices). + try: + with self._ws_lock: + wanted = set(symbols) + added = sorted(wanted - self.ws_subscribed) + removed = sorted(self.ws_subscribed - wanted) + if removed: + self._ws_send_topics(app, "unsubscribe", removed) + if added: + self._ws_send_topics(app, "subscribe", added) + self.ws_subscribed = wanted + except Exception: + try: + app.close() # fall back to a reconnect, which resubscribes everything + except Exception: + pass + if self.running and symbols and not (self.ws_thread and self.ws_thread.is_alive()): + self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbols,), daemon=True) + self.ws_thread.start() + + def _build_settings_window(self) -> None: + self.settings_window = tk.Toplevel(self.root) + self.settings_window.title("Настройки стратегии и симуляции") + self.settings_window.geometry("1200x700") + self.settings_window.minsize(1000, 600) + self.settings_window.withdraw() + self.settings_window.protocol("WM_DELETE_WINDOW", self.settings_window.withdraw) + + body = ttk.Frame(self.settings_window, padding=12) + body.pack(fill="both", expand=True) + controls = ttk.LabelFrame(body, text="Параметры", padding=10) + controls.pack(fill="x", pady=(0, 10)) + + self.symbol_var = tk.StringVar(value="BTCUSDT") + symbol_cell = ttk.Frame(controls) + symbol_cell.grid(row=0, column=0, sticky="w", padx=(0, 10), pady=2) + ttk.Label(symbol_cell, text="Тикер Bybit").pack(anchor="w") + ttk.Entry(symbol_cell, textvariable=self.symbol_var, width=14).pack(anchor="w") + self.symbol_var.trace_add("write", self._schedule_settings_save) + + self.initial_var = self._setting(controls, "Начальный капитал, USDT", "5000", 0, 2) + self.stake_var = self._setting(controls, "Ставка на каждый вход, % стартового депозита", "5", 0, 4) + self.max_adds_var = self._setting(controls, "Максимум доливок, шт. (0 = выкл.)", "2", 0, 6) + self.leverage_var = self._setting(controls, "Плечо", "1", 1, 0) + self.trigger_var = self._setting(controls, "Рост от прошлой 1-мин свечи для входа, %", "0.2", 1, 2) + self.add_step_var = self._setting(controls, "Шаг доливки при снижении, %", "1.5", 1, 4) + self.stop_loss_var = self._setting(controls, "Стоп от средней цены, %", "0", 2, 0) + self.take_profit_var = self._setting(controls, "TP от средней цены, %", "10", 2, 2) + self.apply_btn = ttk.Button(controls, text="Применить", command=self.apply_settings) + self.apply_btn.grid(row=2, column=4, sticky="w", padx=(8, 0), pady=2) + ttk.Label(controls, text="Первый вход — по росту от закрытия прошлой минутной свечи. Доливки срабатывают при снижении от последней покупки на заданный шаг, пока не достигнут их лимит. Максимум 0 или шаг 0 отключает доливки. TP и стоп применяются ко всему объёму от средневзвешенной цены. В симуляции ставка считается от начального капитала, в реальной торговле — от первого загруженного USDT-депозита аккаунта.").grid( + row=3, column=0, columnspan=8, sticky="w", pady=(6, 0) + ) + + preview = ttk.LabelFrame(body, text="Как настройки влияют на входы и выходы", padding=6) + preview.pack(fill="both", expand=True) + self.preview_canvas = tk.Canvas(preview, background="#101820", highlightthickness=0, height=390) + self.preview_canvas.pack(fill="both", expand=True) + self.preview_canvas.bind("", lambda _event: self._refresh_strategy_preview()) + for variable in (self.trigger_var, self.add_step_var, self.max_adds_var, self.stop_loss_var, self.take_profit_var, self.stake_var, self.leverage_var): + variable.trace_add("write", lambda *_args: self._refresh_strategy_preview()) + self._refresh_strategy_preview() + + def open_settings(self) -> None: + self.settings_window.deiconify() + self.settings_window.lift() + self.settings_window.focus_force() + self._refresh_strategy_preview() + + def _build_live_settings_window(self) -> None: + self.live_settings_window = tk.Toplevel(self.root) + self.live_settings_window.title("Настройки подключения Bybit") + self.live_settings_window.geometry("700x340") + self.live_settings_window.resizable(False, False) + self.live_settings_window.withdraw() + self.live_settings_window.protocol("WM_DELETE_WINDOW", self.live_settings_window.withdraw) + body = ttk.Frame(self.live_settings_window, padding=14) + body.pack(fill="both", expand=True) + ttk.Label(body, text="API key").grid(row=0, column=0, sticky="w", pady=5) + self.api_key_entry = ttk.Entry(body, textvariable=self.api_key_var, width=58) + self.api_key_entry.grid(row=0, column=1, sticky="ew", pady=5) + ttk.Button(body, text="Вставить", command=lambda: self._paste_into(self.api_key_entry)).grid(row=0, column=2, padx=(6, 0)) + ttk.Label(body, text="API secret").grid(row=1, column=0, sticky="w", pady=5) + self.api_secret_entry = ttk.Entry(body, textvariable=self.api_secret_var, width=58, show="•") + self.api_secret_entry.grid(row=1, column=1, sticky="ew", pady=5) + ttk.Button(body, text="Вставить", command=lambda: self._paste_into(self.api_secret_entry)).grid(row=1, column=2, padx=(6, 0)) + ttk.Checkbutton(body, text="Testnet (тестовая среда, без реальных средств)", variable=self.testnet_var, + command=self._schedule_settings_save).grid(row=2, column=1, sticky="w", pady=(8, 3)) + ttk.Label(body, text="Режим Mainnet отправляет реальные рыночные ордера.", foreground="#a52626").grid( + row=3, column=1, sticky="w", pady=2 + ) + ttk.Label(body, text="Создайте ключ с чтением аккаунта и торговлей контрактами, без права вывода средств.", + wraplength=560).grid(row=4, column=1, sticky="w", pady=2) + ttk.Label(body, text="Сохранённые ключи шифруются Windows DPAPI и доступны только этому пользователю Windows.", + wraplength=560).grid(row=5, column=1, sticky="w", pady=2) + ttk.Label(body, textvariable=self.credentials_status_var, wraplength=560).grid( + row=6, column=1, sticky="w", pady=(8, 2) + ) + actions = ttk.Frame(body) + actions.grid(row=7, column=1, columnspan=2, sticky="e", pady=(8, 0)) + ttk.Button(actions, text="Сохранить ключи", command=self._save_api_credentials).pack(side="left", padx=(0, 6)) + ttk.Button(actions, text="Удалить сохранённые", command=self._delete_api_credentials).pack(side="left", padx=(0, 6)) + ttk.Button(actions, text="Готово", command=self.live_settings_window.withdraw).pack(side="left") + body.columnconfigure(1, weight=1) + + def _load_saved_credentials(self) -> None: + try: + credentials = load_credentials() + except CredentialStoreError as exc: + self.credentials_status_var.set(str(exc)) + return + if credentials: + self.api_key_var.set(credentials["api_key"]) + self.api_secret_var.set(credentials["api_secret"]) + self.credentials_status_var.set("Зашифрованные ключи загружены из хранилища Windows.") + + def _save_api_credentials(self) -> None: + try: + save_credentials(self.api_key_var.get(), self.api_secret_var.get()) + except CredentialStoreError as exc: + self.credentials_status_var.set(str(exc)) + messagebox.showerror("Не удалось сохранить ключи", str(exc), parent=self.live_settings_window) + return + self.credentials_status_var.set("Ключи сохранены в зашифрованном виде для текущего пользователя Windows.") + + def _delete_api_credentials(self) -> None: + try: + delete_credentials() + except CredentialStoreError as exc: + self.credentials_status_var.set(str(exc)) + messagebox.showerror("Не удалось удалить ключи", str(exc), parent=self.live_settings_window) + return + self.api_key_var.set("") + self.api_secret_var.set("") + self.credentials_status_var.set("Сохранённые ключи удалены.") + + @staticmethod + def _paste_into(entry: ttk.Entry) -> None: + entry.focus_set() + entry.event_generate("<>") + + def open_live_settings(self) -> None: + self.live_settings_window.deiconify() + self.live_settings_window.lift() + self.live_settings_window.focus_force() + + # ----- strategy modes (classic / A / B) ------------------------------------------------- + + def _mode_from_title(self, title: str) -> str: + return next((mode for mode, text in strategy.STRATEGY_TITLES.items() if text == title), + strategy.STRATEGY_CLASSIC) + + def _on_strategy_mode_selected(self, _event: tk.Event | None = None) -> None: + selected = self._mode_from_title(self.strategy_mode_var.get()) + if selected == self.strategy_mode: + return + if self.running or self.historical_running or self.live_preflight: + self.strategy_mode_var.set(strategy.STRATEGY_TITLES[self.strategy_mode]) + messagebox.showinfo("Режим стратегии", "Остановите торговлю или прогон, затем смените режим стратегии.") + return + self.strategy_mode = selected + for state in self.symbol_states.values(): + state.mode_signal = None + state.mode_signal_bucket = 0 + self._save_settings() + self._update_strategy_hint() + self._refresh_settings_summary() + if self.strategy_window is not None and self.strategy_window.winfo_exists(): + self._build_strategy_settings_content() + self.status_var.set(f"Режим стратегии: {strategy.STRATEGY_TITLES[selected]}") + + def _update_strategy_hint(self) -> None: + if not hasattr(self, "strategy_hint_var"): + return + if self.strategy_mode == strategy.STRATEGY_CLASSIC: + text = "настройки — в плитке каждой валюты" + else: + try: + params = self._strategy_mode_params(self.strategy_mode) + text = (f"ставка {params['stake_pct']:g}% × плечо {params['leverage']:g} · " + f"свечи {int(params['timeframe_min'])} мин · общие для всех валют") + except ValueError as exc: + text = f"ошибка настроек: {exc}" + if self.mode_var.get() == "Реальная торговля": + text += " · в реальной торговле доступна только классика" + self.strategy_hint_var.set(text) + + def _strategy_mode_params(self, mode: str | None = None) -> dict[str, float]: + mode = mode or self.strategy_mode + return strategy.parse_mode_params(mode, self.mode_settings.get(mode, {})) + + def open_strategy_settings(self) -> None: + window = self.strategy_window + if window is None or not window.winfo_exists(): + window = tk.Toplevel(self.root) + window.title("Настройки режима стратегии") + window.geometry("980x600") + window.minsize(760, 480) + self.strategy_window = window + top = ttk.Frame(window, padding=(12, 10, 12, 4)) + top.pack(fill="x") + ttk.Label(top, text="Режим:").pack(side="left") + combo = ttk.Combobox(top, textvariable=self.strategy_mode_var, state="readonly", width=44, + values=[strategy.STRATEGY_TITLES[mode] for mode in strategy.STRATEGY_MODES]) + combo.pack(side="left", padx=6) + combo.bind("<>", self._on_strategy_mode_selected) + window._content = ttk.Frame(window, padding=(12, 4, 12, 12)) + window._content.pack(fill="both", expand=True) + self._build_strategy_settings_content() + window.deiconify() + window.lift() + window.focus_force() + + def _build_strategy_settings_content(self) -> None: + window = self.strategy_window + if window is None or not window.winfo_exists(): + return + content = window._content + for child in content.winfo_children(): + child.destroy() + mode = self.strategy_mode + ttk.Label(content, text=strategy.STRATEGY_TITLES[mode], font=("Segoe UI", 12, "bold")).pack(anchor="w") + ttk.Label(content, text=strategy.STRATEGY_DESCRIPTIONS[mode], wraplength=930, justify="left").pack( + anchor="w", pady=(4, 10)) + grid = ttk.LabelFrame(content, text="Параметры режима", padding=8) + grid.pack(fill="x") + window._strategy_vars = {} + if mode == strategy.STRATEGY_CLASSIC: + fields = [("stake_pct", "Ставка, % депозита"), ("max_adds", "Количество доливок"), + ("leverage", "Плечо"), ("trigger_pct", "Рост для входа, %"), + ("add_step_pct", "Шаг доливки при снижении, %"), + ("stop_loss_pct", "Стоп от средней цены, %"), ("take_profit_pct", "TP от средней цены, %")] + values = self.default_currency_settings + else: + fields = [(key, label) for key, label, *_rest in strategy.MODE_FIELDS[mode]] + values = self.mode_settings.get(mode, {}) + for index, (key, label) in enumerate(fields): + row, column = divmod(index, 3) + cell = ttk.Frame(grid) + cell.grid(row=row, column=column, sticky="w", padx=(0, 18), pady=3) + ttk.Label(cell, text=label).pack(anchor="w") + variable = tk.StringVar(value=str(values.get(key, ""))) + window._strategy_vars[key] = variable + ttk.Entry(cell, textvariable=variable, width=18).pack(anchor="w") + for column in range(3): + grid.columnconfigure(column, weight=1) + actions = ttk.Frame(content) + actions.pack(fill="x", pady=(10, 0)) + if mode == strategy.STRATEGY_CLASSIC: + ttk.Button(actions, text="Применить ко всем валютам", + command=lambda: self._apply_detail_strategy(self.symbol, window, all_symbols=True)).pack(side="left") + else: + ttk.Button(actions, text="Применить", command=self._apply_strategy_mode_settings).pack(side="left") + ttk.Button(actions, text="Рекомендуемые значения", command=self._reset_strategy_mode_fields).pack(side="left", padx=6) + ttk.Button(actions, text="Закрыть", command=window.withdraw).pack(side="right") + window._strategy_status = tk.StringVar(value=( + "Шаблон классики: применяется ко всем валютам, индивидуальные настройки задаются в плитке валюты." + if mode == strategy.STRATEGY_CLASSIC else + "Параметры общие для всех валют. Стоп и цели открытых позиций рассчитываются при входе; " + "доля частичной фиксации, безубыток, трейлинг и время удержания берутся из текущих настроек." + )) + ttk.Label(content, textvariable=window._strategy_status, wraplength=930, justify="left").pack( + anchor="w", pady=(8, 0)) + if mode != strategy.STRATEGY_CLASSIC: + ttk.Label(content, wraplength=930, justify="left", foreground="#55606b", text=( + "R — расстояние от входа до начального стопа. Funding указывается в процентах за расчётный период " + "(0.01 = 0.01%). Режимы A и B работают в симуляции и историческом прогоне; реальная торговля " + "использует только классический режим. Лимит одновременных позиций и автоподбор валют — общие." + )).pack(anchor="w", pady=(6, 0)) + + def _reset_strategy_mode_fields(self) -> None: + window = self.strategy_window + if window is None or not window.winfo_exists(): + return + defaults = (DEFAULT_CURRENCY_STRATEGY if self.strategy_mode == strategy.STRATEGY_CLASSIC + else {key: f"{value:g}" for key, value in strategy.MODE_DEFAULTS[self.strategy_mode].items()}) + for key, variable in window._strategy_vars.items(): + if key in defaults: + variable.set(str(defaults[key])) + window._strategy_status.set("Подставлены рекомендуемые значения. Нажмите «Применить», чтобы сохранить.") + + def _apply_strategy_mode_settings(self) -> None: + window = self.strategy_window + mode = self.strategy_mode + if window is None or not window.winfo_exists() or mode == strategy.STRATEGY_CLASSIC: + return + raw = {key: variable.get().strip().replace(",", ".") for key, variable in window._strategy_vars.items()} + try: + strategy.parse_mode_params(mode, raw) + except ValueError as exc: + messagebox.showerror("Проверьте настройки режима", str(exc), parent=window) + return + self.mode_settings[mode] = raw + self._save_settings() + self._update_strategy_hint() + self._refresh_settings_summary() + window._strategy_status.set(f"Настройки режима сохранены: {strategy.STRATEGY_TITLES[mode]}.") + self.status_var.set("Настройки режима стратегии применены") + + def _on_mode_change(self, _event: tk.Event | None = None) -> None: + selected = self.mode_var.get() + if self.running or self.historical_running or self.live_preflight: + self.mode_var.set("Реальная торговля" if self.live_client else "Симуляция") + return + if selected == "Реальная торговля" and any(state.position for state in self.symbol_states.values()): + messagebox.showerror("Открыта симуляционная сделка", "Сначала закройте позицию в режиме симуляции.") + self.mode_var.set("Симуляция") + elif selected == "Симуляция" and any(state.live_position for state in self.symbol_states.values()): + messagebox.showerror("Открыта реальная позиция", "Сначала закройте позицию на Bybit в реальном режиме.") + self.mode_var.set("Реальная торговля") + else: + self.start_btn.configure(text="Запустить прогон" if selected == HISTORICAL_MODE else "Старт") + self.applied_settings = self._safe_read_settings() + self._refresh_settings_summary() + self._update_historical_controls() + self._update_auto_currency_controls() + self._update_simulation_controls() + self._update_strategy_hint() + self._refresh_ui() + + def _update_historical_controls(self) -> None: + if self.mode_var.get() == HISTORICAL_MODE: + if not self.historical_controls_frame.winfo_manager(): + self.historical_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame) + else: + self.historical_controls_frame.pack_forget() + + def _update_auto_currency_controls(self) -> None: + if self.mode_var.get() in ("Симуляция", "Реальная торговля"): + if not self.auto_currency_controls_frame.winfo_manager(): + self.auto_currency_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame) + else: + self.auto_currency_controls_frame.pack_forget() + + def _update_simulation_controls(self) -> None: + if self.mode_var.get() == "Симуляция": + if not self.simulation_controls_frame.winfo_manager(): + self.simulation_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame) + else: + self.simulation_controls_frame.pack_forget() + + def _simulation_position_limit(self) -> int: + raw = self.max_active_sim_positions_var.get().strip().replace(",", ".") + try: + value = float(raw) + except (ValueError, tk.TclError) as exc: + raise ValueError("Количество одновременных сделок должно быть целым числом от 1 до 100.") from exc + if not math.isfinite(value) or not value.is_integer() or not 1 <= value <= 100: + raise ValueError("Количество одновременных сделок должно быть целым числом от 1 до 100.") + return int(value) + + def apply_simulation_controls(self) -> None: + try: + deposit = float(self.initial_var.get().strip().replace(",", ".")) + if not math.isfinite(deposit) or deposit <= 0: + raise ValueError + self._simulation_position_limit() + except (ValueError, tk.TclError): + messagebox.showerror( + "Проверьте настройки симуляции", + "Укажите депозит больше нуля и целый лимит сделок от 1 до 100.", + ) + return + + deposit_changed = abs(deposit - self.initial_balance) > 1e-9 + has_open_positions = any(state.position is not None for state in self.symbol_states.values()) + if deposit_changed and (self.running or has_open_positions): + messagebox.showerror( + "Нельзя изменить депозит", + "Остановите симуляцию и закройте открытые сделки, затем примените новый депозит.", + ) + return + if deposit_changed: + # Preserve already-earned simulation P&L when changing the starting capital. + self.balance += deposit - self.initial_balance + self.initial_balance = deposit + self._save_account_state() + self._save_settings() + self._refresh_ui() + self.status_var.set("Настройки симуляции применены") + + def _refresh_strategy_preview(self) -> None: + canvas = getattr(self, "preview_canvas", None) + if canvas is None or not canvas.winfo_exists(): + return + canvas.delete("all") + width = max(canvas.winfo_width(), 900) + height = max(canvas.winfo_height(), 360) + + def value(var: tk.StringVar, fallback: float) -> float: + try: + return max(0.0, float(var.get().strip().replace(",", "."))) + except (ValueError, tk.TclError): + return fallback + + trigger = value(self.trigger_var, .3) + add_step = value(self.add_step_var, .5) + max_adds = int(value(self.max_adds_var, 2)) + stop_loss = value(self.stop_loss_var, .45) + take_profit = value(self.take_profit_var, .5) + stake_pct = value(self.stake_var, 2) + try: + simulation_capital = max(0.0, float(self.initial_var.get().strip().replace(",", "."))) + except (ValueError, tk.TclError): + simulation_capital = 5000.0 + deposit_basis = (self._current_live_deposit_basis() + if self.mode_var.get() == "Реальная торговля" else None) or simulation_capital + stake = deposit_basis * stake_pct / 100 + leverage = value(self.leverage_var, 10) + reference = 100.0 + entry_prices = [reference * (1 + trigger / 100)] + for _ in range(max_adds if add_step > 0 else 0): + entry_prices.append(entry_prices[-1] * (1 - add_step / 100)) + notional_per_entry = stake * leverage + quantities = [notional_per_entry / price for price in entry_prices] + total_qty = sum(quantities) + total_notional = notional_per_entry * len(entry_prices) + average = total_notional / total_qty if total_qty else entry_prices[-1] + effective_tp = max(take_profit, self._fee_cover_pct(TAKER_FEE_PCT)) + tp_price = average * (1 + effective_tp / 100) if take_profit > 0 else None + sl_price = average * (1 - stop_loss / 100) if stop_loss > 0 else None + next_add_price = entry_prices[-1] * (1 - add_step / 100) if add_step > 0 and len(entry_prices) <= max_adds else None + gross = ((tp_price - average) * total_qty) if tp_price is not None else 0.0 + exit_notional = (tp_price * total_qty) if tp_price is not None else 0.0 + fees = (total_notional + exit_notional) * TAKER_FEE_PCT / 100 + net = gross - fees + total_margin = stake * len(entry_prices) + roi = net / total_margin * 100 if total_margin else 0.0 + + canvas.create_text(16, 12, anchor="nw", fill="#e5edf5", font=("Segoe UI", 11, "bold"), text=f"Пример усреднения · условная прошлая цена = 100.00 USDT · максимум доливок: {max_adds} · 1-мин свечи") + left, right = 78, width - 30 + top, bottom = 52, height - 95 + preview_levels = [reference, *entry_prices, sl_price if sl_price else average] + if next_add_price is not None: + preview_levels.append(next_add_price) + if tp_price is not None: + preview_levels.append(tp_price) + low = min(preview_levels) * .998 + high = max(preview_levels) * 1.002 + if high <= low: + high = low + 1 + + def y_for(price: float) -> float: + return bottom - (price - low) / (high - low) * (bottom - top) + + def fmt(price: float) -> str: + return f"{price:.6f}".rstrip("0").rstrip(".") + + def level(price: float, label: str, color: str, dash: tuple[int, ...] = (4, 3)) -> None: + y = y_for(price) + canvas.create_line(left, y, right, y, fill=color, dash=dash, width=1) + canvas.create_text(left + 5, y - 13, anchor="sw", fill=color, font=("Segoe UI", 8), text=f"{label}: {fmt(price)}") + + level(reference, "Закрытие прошлой свечи", "#9fb2c4") + for index, price in enumerate(entry_prices): + title = f"Вход #{index + 1}" if index == 0 else f"Доливка #{index} (−{add_step:g}%)" + level(price, title, "#63a8ff" if index == 0 else "#b49cff") + level(average, "Средняя цена позиции", "#f2c14e", (2, 3)) + if tp_price is not None: + level(tp_price, f"TP +{effective_tp:g}%", "#40d6b0") + if sl_price is not None: + level(sl_price, f"Стоп −{stop_loss:g}%", "#ff6969") + if next_add_price is not None: + level(next_add_price, f"Следующая доливка −{add_step:g}%", "#d28cff") + + # Draw only the entry levels enabled by the add-step setting. + entry_x = [left + (right-left) * (.24 + index * .18) for index in range(len(entry_prices))] + path = [(left + 10, reference), *zip(entry_x, entry_prices), (right - 10, tp_price if tp_price is not None else average)] + coords = [(x, y_for(price)) for x, price in path] + candle_width = min(34, max(16, (right - left) / (len(path) * 2.8))) + for index, ((x1, open_price), (x2, close_price)) in enumerate(zip(path, path[1:])): + wick = max(abs(close_price - open_price) * .2, max(open_price, close_price) * .0005) + center_x = (x1 + x2) / 2 + canvas.create_line(center_x, y_for(max(open_price, close_price) + wick), center_x, y_for(min(open_price, close_price) - wick), fill="#ef5965" if close_price < open_price else "#38d996", width=2) + color = "#38d996" if close_price >= open_price else "#ef5965" + body_top, body_bottom = sorted((y_for(open_price), y_for(close_price))) + if body_bottom - body_top < 3: + body_bottom = body_top + 3 + canvas.create_rectangle(center_x-candle_width/2, body_top, center_x+candle_width/2, body_bottom, fill=color, outline=color) + for index in range(len(entry_prices)): + x, y = coords[index + 1] + label = "ВХОД" if index == 0 else f"ДОЛИВКА {index}" + canvas.create_oval(x-4, y-4, x+4, y+4, fill="#63a8ff" if index == 0 else "#b49cff", outline="white") + canvas.create_text(x, y-8, anchor="s", fill="#c6b4ff" if index else "#8fc2ff", font=("Segoe UI", 8, "bold"), text=label) + if tp_price is not None: + x, y = coords[-1] + canvas.create_oval(x-4, y-4, x+4, y+4, fill="#40d6b0", outline="white") + canvas.create_text(x, y-8, anchor="s", fill="#63e6c2", font=("Segoe UI", 8, "bold"), text="ЗАКРЫТИЕ TP") + + pnl_text = f"При TP после {len(entry_prices)} вход(а/ов): Gross {gross:+.4f} · комиссии {fees:.4f} · Net {net:+.4f} USDT ({roi:+.2f}% на суммарную ставку {total_margin:g})" + entries_text = " → ".join((f"вход {fmt(entry_prices[0])}", *(f"доливка {fmt(price)}" for price in entry_prices[1:]))) + canvas.create_text(16, height-58, anchor="nw", fill="#dce7f0", font=("Segoe UI", 9), text=f"Пример: 100.00 → {entries_text} → средняя {fmt(average)} → TP {fmt(tp_price) if tp_price else 'выкл.'} / стоп {fmt(sl_price) if sl_price else 'выкл.'}") + canvas.create_text(16, height-38, anchor="nw", fill="#dce7f0", font=("Segoe UI", 9), text=pnl_text) + canvas.create_text(16, height-18, anchor="nw", fill="#9fb2c4", font=("Segoe UI", 8), text=f"Ставка {stake_pct:g}% от базы {deposit_basis:g} USDT = {stake:g} USDT × плечо {leverage:g} на каждый вход · taker-комиссия {TAKER_FEE_PCT:g}% за сторону · расчёт примерный, без проскальзывания и funding.") + + def _setting(self, parent: ttk.Widget, label: str, default: str, row: int, col: int) -> tk.StringVar: + cell = ttk.Frame(parent) + cell.grid(row=row, column=col, sticky="w", padx=(0, 10), pady=2) + ttk.Label(cell, text=label).pack(anchor="w") + var = tk.StringVar(value=default) + ttk.Entry(cell, textvariable=var, width=13).pack(anchor="w") + var.trace_add("write", self._schedule_settings_save) + return var + + def _settings_payload(self) -> dict[str, object]: + return { + "symbol": self.symbol_var.get().strip().upper(), + "currencies": self.currencies, + "enabled_symbols": sorted(self.enabled_symbols), + "currency_settings": self.currency_settings, + "default_currency_settings": self.default_currency_settings, + "strategy_defaults_version": STRATEGY_DEFAULTS_VERSION, + "initial_capital": self.initial_var.get(), + "stake_pct": self.stake_var.get(), + "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), + "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), + "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + "historical_days": self.historical_days_var.get(), + "historical_initial_capital": self.historical_initial_capital_var.get(), + "historical_growth_threshold_pct": self.historical_growth_var.get(), + "historical_min_equity_pct": self.historical_min_equity_var.get(), + "historical_universe_mode": bool(self.historical_universe_var.get()), + "historical_include_funding": bool(self.historical_funding_var.get()), + "strategy_mode": self.strategy_mode, + "strategy_mode_settings": self.mode_settings, + "auto_currency_min_growth_24h_pct": self.auto_currency_growth_var.get(), + "max_active_sim_positions": self.max_active_sim_positions_var.get(), + "live_testnet": bool(self.testnet_var.get()), + } + + def _load_saved_settings(self) -> None: + try: + saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError, TypeError): + return + variables = { + "symbol": self.symbol_var, + "initial_capital": self.initial_var, + "max_adds": self.max_adds_var, + "leverage": self.leverage_var, + "trigger_pct": self.trigger_var, + "add_step_pct": self.add_step_var, + "stop_loss_pct": self.stop_loss_var, + "take_profit_pct": self.take_profit_var, + } + if "historical_days" in saved: + self.historical_days_var.set(str(saved["historical_days"])) + if "historical_initial_capital" in saved: + self.historical_initial_capital_var.set(str(saved["historical_initial_capital"])) + elif "initial_capital" in saved: + self.historical_initial_capital_var.set(str(saved["initial_capital"])) + if "historical_growth_threshold_pct" in saved: + self.historical_growth_var.set(str(saved["historical_growth_threshold_pct"])) + if "historical_min_equity_pct" in saved: + self.historical_min_equity_var.set(str(saved["historical_min_equity_pct"])) + if "historical_universe_mode" in saved: + self.historical_universe_var.set(bool(saved["historical_universe_mode"])) + if "historical_include_funding" in saved: + self.historical_funding_var.set(bool(saved["historical_include_funding"])) + saved_modes = saved.get("strategy_mode_settings") + if isinstance(saved_modes, dict): + for mode, values in saved_modes.items(): + if mode in self.mode_settings and isinstance(values, dict): + self.mode_settings[mode].update({str(key): str(value) for key, value in values.items() + if key in strategy.MODE_DEFAULTS[mode]}) + if saved.get("strategy_mode") in strategy.STRATEGY_MODES: + self.strategy_mode = saved["strategy_mode"] + self.strategy_mode_var.set(strategy.STRATEGY_TITLES[self.strategy_mode]) + self._update_strategy_hint() + if "auto_currency_min_growth_24h_pct" in saved: + self.auto_currency_growth_var.set(str(saved["auto_currency_min_growth_24h_pct"])) + if "max_active_sim_positions" in saved: + self.max_active_sim_positions_var.set(str(saved["max_active_sim_positions"])) + for key, variable in variables.items(): + if key in saved: + variable.set(str(saved[key])) + if "stake_pct" in saved: + self.stake_var.set(str(saved["stake_pct"])) + elif "stake" in saved: + # Migrate earlier settings where stake was saved as a fixed USDT amount. + try: + old_capital = float(str(saved.get("initial_capital", self.initial_var.get())).replace(",", ".")) + old_stake = float(str(saved["stake"]).replace(",", ".")) + if old_capital > 0 and old_stake > 0: + self.stake_var.set(f"{old_stake / old_capital * 100:.8g}") + except (ValueError, TypeError): + pass + if "live_testnet" in saved: + self.testnet_var.set(bool(saved["live_testnet"])) + if "add_step_pct" not in saved: + self.add_step_var.set("0.5") + if "max_adds" not in saved: + self.max_adds_var.set("2") + configured = saved.get("currencies", []) + if isinstance(configured, list): + for value in configured: + symbol = str(value).strip().upper() + if re.fullmatch(r"[A-Z0-9]{2,30}", symbol): + self._ensure_symbol(symbol) + active = saved.get("enabled_symbols") + if isinstance(active, list): + self._has_saved_enabled_symbols = True + self.enabled_symbols = {str(value).strip().upper() for value in active + if re.fullmatch(r"[A-Z0-9]{2,30}", str(value).strip().upper())} + else: + self.enabled_symbols = {self.symbol_var.get().strip().upper()} + saved_overrides = saved.get("currency_settings", {}) + if isinstance(saved_overrides, dict): + self.currency_settings = {str(symbol).strip().upper(): dict(values) + for symbol, values in saved_overrides.items() + if isinstance(values, dict)} + if not self.currencies: + self.currencies = [self.symbol_var.get().strip().upper()] + self.default_currency_settings = { + "stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + } + saved_defaults = saved.get("default_currency_settings", {}) + try: + saved_defaults_version = int(saved.get("strategy_defaults_version", 0)) + except (TypeError, ValueError): + saved_defaults_version = 0 + if saved_defaults_version >= STRATEGY_DEFAULTS_VERSION and isinstance(saved_defaults, dict): + self.default_currency_settings.update({str(key): str(value) for key, value in saved_defaults.items() + if key in self.default_currency_settings}) + else: + # Upgrade the old shared template to the requested defaults while + # preserving individual overrides already saved for specific symbols. + self.default_currency_settings = DEFAULT_CURRENCY_STRATEGY.copy() + self._load_currency_settings(self.symbol_var.get().strip().upper()) + self._render_currency_tiles() + self._update_historical_controls() + self._update_auto_currency_controls() + self._update_simulation_controls() + + def _load_saved_state(self) -> None: + """Restore the virtual account and closed-trade history from the prior run.""" + if not STATE_FILE.exists(): + try: + configured_capital = float(self.initial_var.get().strip().replace(",", ".")) + if configured_capital > 0: + self.initial_balance = self.balance = configured_capital + except (ValueError, tk.TclError): + pass + return + try: + state = json.loads(STATE_FILE.read_text(encoding="utf-8")) + initial = float(state["initial_balance"]) + balance = float(state["balance"]) + fees = float(state.get("total_fees", 0.0)) + next_id = int(state.get("next_id", 1)) + if initial <= 0 or balance < 0 or fees < 0 or next_id < 1: + raise ValueError("Некорректные значения счёта") + loaded_trades = [ClosedTrade(**row) for row in state.get("trades", [])] + position_data = state.get("position") + loaded_position = Position(**position_data) if position_data else None + loaded_positions = {str(symbol): Position(**row) for symbol, row in state.get("positions", {}).items()} + loaded_live_trades = [ClosedTrade(**row) for row in state.get("live_trades", [])] + loaded_deposit_bases = {str(key): float(value) for key, value in state.get("live_initial_deposits", {}).items() + if float(value) > 0} + live_position_data = state.get("live_position") + loaded_live_position = Position(**live_position_data) if live_position_data else None + loaded_live_positions = {str(symbol): Position(**row) for symbol, row in state.get("live_positions_managed", {}).items()} + if loaded_position and (loaded_position.qty <= 0 or loaded_position.entry_price <= 0): + raise ValueError("Некорректные данные открытой позиции") + if loaded_live_position and (loaded_live_position.qty <= 0 or loaded_live_position.entry_price <= 0): + raise ValueError("Некорректные данные реальной позиции") + except (OSError, json.JSONDecodeError, TypeError, KeyError, ValueError) as exc: + self.status_var.set(f"Не удалось загрузить счёт из {STATE_FILE.name}: {exc}") + return + + self.initial_balance = initial + self.balance = balance + self.total_fees = fees + self.trades = loaded_trades + self.position = loaded_position + self.live_trades = loaded_live_trades + self.live_initial_deposits = loaded_deposit_bases + self.live_position = loaded_live_position + for symbol, position in loaded_positions.items(): + self._ensure_symbol(symbol).position = position + self.enabled_symbols.add(symbol) + for symbol, position in loaded_live_positions.items(): + self._ensure_symbol(symbol).live_position = position + self.enabled_symbols.add(symbol) + if loaded_position: + self._ensure_symbol(loaded_position.symbol).position = loaded_position + if loaded_live_position: + self._ensure_symbol(loaded_live_position.symbol).live_position = loaded_live_position + max_trade_id = max((trade.trade_id for trade in loaded_trades), default=0) + max_open_id = max((position.trade_id for position in loaded_positions.values()), default=0) + self.next_id = max(next_id, max_trade_id + 1, max_open_id + 1, + loaded_position.trade_id + 1 if loaded_position else 1) + self.next_live_id = max(int(state.get("next_live_id", 1)), max((trade.trade_id for trade in loaded_live_trades), default=0) + 1, + max((position.trade_id for position in loaded_live_positions.values()), default=0) + 1, + loaded_live_position.trade_id + 1 if loaded_live_position else 1) + self.initial_var.set(str(initial)) + if loaded_position or loaded_live_position: + restored_symbol = loaded_position.symbol if loaded_position else loaded_live_position.symbol + self.symbol = restored_symbol + self.symbol_var.set(restored_symbol) + for trade in reversed(loaded_trades): + tag = "profit" if trade.net_pnl > 0 else "loss" if trade.net_pnl < 0 else "" + self.table.insert( + "", "end", + values=(trade.trade_id, trade.symbol, self._fmt_price(trade.entry_price), self._fmt_price(trade.exit_price), + f"{trade.roi_pct:+.2f}", f"{trade.gross_pnl:+.4f}", f"{trade.fees:.4f}", + f"{trade.net_pnl:+.4f}", trade.reason), + tags=(tag,), + ) + for trade in reversed(loaded_live_trades): + tag = "profit" if trade.net_pnl > 0 else "loss" if trade.net_pnl < 0 else "" + self.table.insert( + "", "end", + values=(f"R{trade.trade_id}", trade.symbol, self._fmt_price(trade.entry_price), self._fmt_price(trade.exit_price), + f"{trade.roi_pct:+.2f}", f"{trade.gross_pnl:+.4f}", f"{trade.fees:.4f}", + f"{trade.net_pnl:+.4f}", f"LIVE · {trade.reason}"), + tags=(tag,), + ) + self.status_var.set(f"Загружено сделок: {len(loaded_trades)} · баланс {self.balance:,.2f} USDT") + + def _save_account_state(self) -> None: + self._capture_active_symbol() + state = { + "version": 1, + "initial_balance": self.initial_balance, + "balance": self.balance, + "total_fees": self.total_fees, + "next_id": self.next_id, + "trades": [vars(trade) for trade in self.trades], + "position": vars(self.position) if self.position else None, + "positions": {symbol: vars(state.position) for symbol, state in self.symbol_states.items() if state.position}, + "next_live_id": self.next_live_id, + "live_trades": [vars(trade) for trade in self.live_trades], + "live_position": vars(self.live_position) if self.live_position else None, + "live_positions_managed": {symbol: vars(state.live_position) for symbol, state in self.symbol_states.items() if state.live_position}, + "live_initial_deposits": self.live_initial_deposits, + } + try: + 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: + if hasattr(self, "status_var"): + self.status_var.set(f"Не удалось сохранить историю счёта: {exc}") + + def _schedule_settings_save(self, *_args) -> None: + if not hasattr(self, "root") or not self.root.winfo_exists(): + return + if self._settings_save_job is not None: + try: + self.root.after_cancel(self._settings_save_job) + except tk.TclError: + pass + self._settings_save_job = self.root.after(350, self._save_settings) + + def _save_settings(self) -> None: + self._settings_save_job = None + try: + 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: + self.status_var.set(f"Не удалось сохранить настройки: {exc}") + + @staticmethod + def _num(var: tk.StringVar, label: str, *, minimum: float = 0, allow_zero: bool = False) -> float: + try: + value = float(var.get().strip().replace(",", ".")) + except ValueError as exc: + raise ValueError(f"Проверьте значение «{label}».") from exc + if not math.isfinite(value) or value < minimum or (not allow_zero and value == 0): + raise ValueError(f"«{label}» должно быть {('не меньше' if allow_zero else 'больше')} {minimum}.") + return value + + def _read_settings(self) -> dict[str, float]: + take_profit = self._num(self.take_profit_var, "TP", allow_zero=True) + stop_loss = self._num(self.stop_loss_var, "стоп-лосс", allow_zero=True) + max_adds_value = self._num(self.max_adds_var, "максимум доливок", allow_zero=True) + if not max_adds_value.is_integer() or max_adds_value > 100: + raise ValueError("Максимум доливок должен быть целым числом от 0 до 100.") + if take_profit == 0 and stop_loss == 0: + raise ValueError("Укажите TP, стоп-лосс или оба уровня — нельзя запускать позицию без условий выхода.") + initial = self._num(self.initial_var, "начальный капитал") + stake_pct = self._num(self.stake_var, "ставка от депозита") + if stake_pct > 100: + raise ValueError("Ставка на каждый вход должна быть не больше 100% депозита.") + deposit_basis = self._current_live_deposit_basis() if self.mode_var.get() == "Реальная торговля" else None + stake = (deposit_basis if deposit_basis is not None else initial) * stake_pct / 100 + return { + "initial": initial, + "stake_pct": stake_pct, + "deposit_basis": deposit_basis or initial, + "stake": stake, + "leverage": self._num(self.leverage_var, "плечо", minimum=1, allow_zero=True), + "trigger": self._num(self.trigger_var, "порог роста"), + "add_step": self._num(self.add_step_var, "шаг доливки", allow_zero=True), + "max_adds": int(max_adds_value), + "stop_loss": stop_loss, + "take_profit": take_profit, + "fee": TAKER_FEE_PCT, + "interval": float(CANDLE_INTERVAL_MINUTES), + } + + def _deposit_baseline_key(self, api_key: str | None = None, testnet: bool | None = None) -> str | None: + key = (api_key if api_key is not None else self.api_key_var.get()).strip() + if not key: + return None + network = self.testnet_var.get() if testnet is None else testnet + fingerprint = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16] + return f"{'testnet' if network else 'mainnet'}:{fingerprint}" + + def _current_live_deposit_basis(self) -> float | None: + key = self._deposit_baseline_key() + value = self.live_initial_deposits.get(key) if key else None + return float(value) if value and value > 0 else None + + def _remember_live_deposit(self, api_key: str, testnet: bool, wallet: dict[str, float], baseline: float | None = None) -> float: + key = self._deposit_baseline_key(api_key, testnet) + if not key: + return float(baseline or wallet.get("wallet") or 0) + saved = self.live_initial_deposits.get(key) + if saved and saved > 0: + return float(saved) + value = float(baseline or wallet.get("wallet") or 0) + if value > 0: + self.live_initial_deposits[key] = value + self._save_account_state() + return value + + def connect_bybit(self) -> None: + """Read the account snapshot without starting the trading loop or placing orders.""" + if self.running or self.live_preflight: + self.status_var.set("Остановите торговый цикл перед новым подключением аккаунта") + return + if self.api_connecting: + return + api_key = self.api_key_var.get().strip() + api_secret = self.api_secret_var.get().strip() + if not api_key or not api_secret: + self.open_live_settings() + self.status_var.set("Вставьте API key и secret, затем нажмите «Подключиться»") + return + self.api_connecting = True + self.connect_btn.configure(state="disabled") + self.status_var.set(f"Подключаюсь к Bybit ({'Testnet' if self.testnet_var.get() else 'Mainnet'}) · только чтение…") + threading.Thread(target=self._api_connect_worker, + args=(api_key, api_secret, self.testnet_var.get()), daemon=True).start() + + def _api_connect_worker(self, api_key: str, api_secret: str, testnet: bool) -> None: + try: + client = BybitLiveClient(api_key, api_secret, testnet) + wallet = client.get_wallet() + optional_results = [] + warnings = [] + for label, method in ( + ("позиции", client.get_open_positions), + ("ордера", lambda: client.get_order_history(50)), + ("историю P&L", lambda: client.get_closed_pnl_history(50)), + ): + try: + optional_results.append(method()) + except Exception as exc: + optional_results.append([]) + warnings.append(f"{label}: {exc}") + positions, orders, closed_pnl = optional_results + self.events.put(("api_connected", client, wallet, positions, orders, closed_pnl, + self._deposit_baseline_key(api_key, testnet), warnings)) + except Exception as exc: + self.events.put(("api_connect_failed", str(exc))) + + def _show_api_snapshot(self, client: BybitLiveClient, wallet: dict[str, float], positions: list[dict], + orders: list[dict], closed_pnl: list[dict], baseline_key: str | None, + warnings: list[str] | None = None) -> None: + self.live_client = client + self.live_wallet = wallet + self.live_positions = positions + for row in positions: + symbol = str(row.get("symbol") or "").upper() + if symbol: + self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + self._render_currency_tiles() + self.live_orders = orders + self.live_closed_pnl = closed_pnl + self.testnet_var.set(client.testnet) + if baseline_key: + baseline = self.live_initial_deposits.get(baseline_key) + if not baseline or baseline <= 0: + baseline = float(wallet.get("wallet") or 0) + if baseline > 0: + self.live_initial_deposits[baseline_key] = baseline + else: + baseline = float(wallet.get("wallet") or 0) + if wallet.get("unrealized_pnl") is None: + wallet["unrealized_pnl"] = sum(float(row.get("unrealisedPnl") or 0) for row in positions) + self._render_bybit_orders() + self._render_bybit_positions() + self.mode_var.set("Реальная торговля") + self._update_historical_controls() + self._update_auto_currency_controls() + self._update_simulation_controls() + self.applied_settings = self._safe_read_settings() + if positions: + self.history_tabs.select(2) + else: + self.history_tabs.select(1) + recent_realized = sum(float(row.get("closedPnl") or 0) for row in closed_pnl) + network = "Testnet" if client.testnet else "MAINNET" + self.live_account_var.set( + f"{network} подключён · стартовый депозит {baseline:,.2f} · кошелёк {wallet['wallet']:,.2f} · " + f"equity {wallet['equity']:,.2f} · P&L нереализованный {wallet.get('unrealized_pnl', 0):+,.2f} · " + f"реализованный за загруженную историю {recent_realized:+,.2f} USDT · " + f"ордеров {len(orders)} · открытых позиций {len(positions)}" + ) + if self.live_position is None: + selected = next((row for row in positions if row.get("symbol") == self.symbol_var.get().strip().upper()), None) + if selected: + self.position_var.set( + f"Bybit · {selected.get('symbol')} {selected.get('side')} · объём {selected.get('size')} · " + f"средняя {selected.get('avgPrice')} · P&L {float(selected.get('unrealisedPnl') or 0):+.4f} USDT · " + f"TP {selected.get('takeProfit') or '—'} · SL {selected.get('stopLoss') or '—'} · " + "подключено для просмотра; нажмите «Старт» для сопровождения ботом" + ) + elif positions: + self.position_var.set(f"На аккаунте открыто позиций: {len(positions)} · подробности во вкладке «Открытые позиции»") + else: + self.position_var.set("Bybit · открытых позиций нет") + self._save_account_state() + self._save_settings() + self._refresh_settings_summary() + self._refresh_ui() + status = f"Bybit подключён · торговля не запущена · ордеров: {len(orders)} · позиций: {len(positions)}" + if warnings: + status += " · часть данных не загружена: " + "; ".join(warnings) + self.status_var.set(status) + + def _render_bybit_orders(self) -> None: + if not hasattr(self, "bybit_orders_table"): + return + for item in self.bybit_orders_table.get_children(): + self.bybit_orders_table.delete(item) + for row in self.live_orders: + stamp = int(row.get("updatedTime") or row.get("createdTime") or 0) / 1000 + try: + time_text = datetime.fromtimestamp(stamp).strftime("%Y-%m-%d %H:%M:%S") + except (OverflowError, OSError, ValueError): + time_text = "—" + self.bybit_orders_table.insert("", "end", values=( + time_text, row.get("symbol", ""), row.get("side", ""), row.get("orderType", ""), + row.get("qty", ""), row.get("price", ""), row.get("avgPrice", ""), + row.get("orderStatus", ""), row.get("orderId", ""), + )) + + def _render_bybit_positions(self) -> None: + if not hasattr(self, "bybit_positions_table"): + return + for item in self.bybit_positions_table.get_children(): + self.bybit_positions_table.delete(item) + for row in self.live_positions: + self.bybit_positions_table.insert("", "end", values=( + row.get("symbol", ""), row.get("side", ""), row.get("size", ""), row.get("avgPrice", ""), + row.get("markPrice", ""), row.get("unrealisedPnl", ""), row.get("leverage", ""), + row.get("takeProfit", "") or "—", row.get("stopLoss", "") or "—", + )) + + def apply_settings(self) -> None: + requested_symbol = self.symbol_var.get().strip().upper() + if not re.fullmatch(r"[A-Z0-9]{2,30}", requested_symbol): + messagebox.showerror("Неверный тикер", "Введите тикер USDT-перпетуального контракта, например BTCUSDT.") + return + self._ensure_symbol(requested_symbol) + self.enabled_symbols.add(requested_symbol) + self._capture_active_symbol() + self._activate_symbol_state(requested_symbol) + try: + settings = self._read_settings() + except ValueError as exc: + messagebox.showerror("Проверьте настройки", str(exc)) + return + if self.mode_var.get() == "Реальная торговля" and any(s.live_position for s in self.symbol_states.values()) and self.applied_settings: + if settings["leverage"] != self.applied_settings["leverage"]: + messagebox.showerror("Открыта реальная позиция", "Нельзя менять плечо, пока позиция открыта. Закройте её и примените новое плечо.") + self.leverage_var.set(str(self.applied_settings["leverage"])) + return + if self.mode_var.get() == "Симуляция" and settings["stake"] > self.balance: + messagebox.showerror("Проверьте ставку", "Ставка не может быть больше текущего баланса.") + return + if not self.running and self.mode_var.get() == "Симуляция" and settings["stake"] > settings["initial"]: + messagebox.showerror("Проверьте ставку", "Ставка не может быть больше начального капитала.") + return + if not self.running and self.mode_var.get() == "Симуляция": + self.balance += settings["initial"] - self.initial_balance + self.initial_balance = settings["initial"] + if self.mode_var.get() == "Реальная торговля": + settings["fee"] = self.live_fee_pct + self.currency_settings[requested_symbol] = { + "stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(), + "leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(), + "add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(), + "take_profit_pct": self.take_profit_var.get(), + } + self.strategy_by_symbol[requested_symbol] = settings.copy() + old_interval = self.interval_minutes + self.applied_settings = settings + self.interval_minutes = int(settings["interval"]) + if self.running: + for state in self.symbol_states.values(): + state.baseline_close = None + state.last_signal_ready = False + state.last_signal_pct = None + if old_interval != self.interval_minutes: + state.candles.clear() + if old_interval != self.interval_minutes: + self.chart_view_end = None + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self.chart_price_center = None + self.chart_price_span = None + for symbol in sorted(self.enabled_symbols): + self._fetch_baseline_async(symbol, self.interval_minutes) + if self.mode_var.get() == "Симуляция": + self._subscribe_running_symbols() + self._refresh_price_label() + if self.mode_var.get() == "Реальная торговля": + for symbol, commands in self.live_commands_by_symbol.items(): + state = self._ensure_symbol(symbol) + if not state.live_order_busy: + state.live_order_busy = True + symbol_settings = self.strategy_by_symbol.get(symbol, settings).copy() + commands.put(("settings", time.time(), state.last_price or 0.0, symbol_settings)) + self._save_settings() + self._render_currency_tiles() + self._save_account_state() + self._refresh_settings_summary() + self._refresh_ui() + self.status_var.set("Настройки применены") + + def start(self) -> None: + if self.running: + return + mode = self.mode_var.get() + if mode == HISTORICAL_MODE: + self._start_historical_backtest() + return + if mode == "Реальная торговля" and self.strategy_mode != strategy.STRATEGY_CLASSIC: + messagebox.showerror( + "Режим стратегии", + "Режимы A и B пока работают только в симуляции и историческом прогоне. " + "Для реальной торговли выберите классический режим стратегии.", + ) + return + if self.strategy_mode != strategy.STRATEGY_CLASSIC: + try: + self._strategy_mode_params() + except ValueError as exc: + messagebox.showerror("Проверьте настройки режима", str(exc)) + return + if websocket is None: + messagebox.showerror("Нет зависимости", "Не найден websocket-client. Запустите приложение через run.bat.") + return + if self.startup_currency_filter_busy: + return + if self.startup_currency_filter_approved_for != mode: + try: + threshold = float(self.auto_currency_growth_var.get().strip().replace(",", ".")) + except (ValueError, tk.TclError): + messagebox.showerror("Проверьте порог", "Введите корректный порог роста за 24 часа.") + return + if not math.isfinite(threshold) or not 0 <= threshold <= 1000: + messagebox.showerror("Проверьте порог", "Порог роста за 24 часа должен быть от 0 до 1000%.") + return + self._begin_startup_currency_filter(mode, threshold) + return + self.startup_currency_filter_approved_for = None + self.startup_currency_filter_busy = False + self.mode_combo.configure(state="readonly") + symbols = sorted(self.enabled_symbols) + if not symbols: + messagebox.showerror("Нет активных валют", "Включите переключатель «В торгах» хотя бы у одной валюты.") + return + invalid = next((symbol for symbol in symbols if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol)), None) + if invalid: + messagebox.showerror("Неверный тикер", f"Проверьте тикер {invalid}.") + return + classic = self.strategy_mode == strategy.STRATEGY_CLASSIC + try: + # Modes A/B do not use the classic per-currency settings, so those cannot block a start. + visible_settings = self._read_settings() if classic else self._safe_read_settings() + if self.mode_var.get() == "Симуляция": + self._simulation_position_limit() + except ValueError as exc: + messagebox.showerror("Проверьте настройки", str(exc)) + return + default_settings = self._read_default_strategy(visible_settings) + selected_symbol = self.symbol_var.get().strip().upper() + if selected_symbol not in symbols: + selected_symbol = symbols[0] + per_symbol_settings = {symbol: self._strategy_for_symbol(symbol, default_settings) for symbol in symbols} + settings = per_symbol_settings[selected_symbol] + if classic and self.mode_var.get() == "Симуляция" and any( + item["stake"] > item["initial"] for item in per_symbol_settings.values() + ): + messagebox.showerror("Проверьте ставку", "Ставка не может быть больше начального капитала.") + return + if self.mode_var.get() == "Реальная торговля": + self._begin_live_preflight(symbols[0], settings, per_symbol_settings) + return + self.strategy_by_symbol = per_symbol_settings + self.applied_settings = settings.copy() + self.interval_minutes = int(settings["interval"]) + self._refresh_settings_summary() + self.chart_visible_seconds = self.interval_minutes * 60 * 30 + self._save_settings() + for symbol in symbols: + state = self._ensure_symbol(symbol) + state.mode_signal = None + state.mode_signal_bucket = 0 + state.mode_eval_busy = False + if state.position: + # Keep its restored position and indicators; only refresh market data. + state.baseline_close = None + else: + state.prices.clear() + state.candles.clear() + state.entry_markers.clear() + state.last_price = None + state.baseline_close = None + state.previous_entry_signal_pct = None + state.last_signal_pct = None + state.last_signal_ready = False + state.live_minute_prices.clear() + self._last_signal_refresh_at = 0.0 + selected = selected_symbol + if selected not in symbols: + selected = symbols[0] + self.symbol_var.set(selected) + self._activate_symbol_state(selected) + self.market_price_var.set(f"{selected}: ожидаю данные Bybit…") + self.running = True + self.next_auto_currency_scan_at = 0.0 + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + self.session_started_at = time.time() + self.status_var.set(f"Подключение к Bybit: {', '.join(symbols)} · параллельно") + for symbol in symbols: + self._fetch_baseline_async(symbol, self.interval_minutes) + self._save_account_state() + self.ws_symbols = symbols + self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbols,), daemon=True) + self.ws_thread.start() + + def _start_historical_backtest(self) -> None: + if self.running or self.live_preflight or self.historical_running: + self.status_var.set("Сначала завершите текущий торговый цикл или прогон") + return + universe_mode = bool(self.historical_universe_var.get()) + symbols = sorted(self.enabled_symbols) + if universe_mode: + # Symbols come from the point-in-time selection; strategies are prepared for + # every pair with saved overrides, the rest use the default strategy. + symbols = sorted(set(self.currency_settings) | set(self.enabled_symbols)) + if not symbols and not universe_mode: + messagebox.showerror("Нет активных валют", "Включите валюты, которые нужно проверить исторически.") + return + invalid = next((symbol for symbol in symbols if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol)), None) + if invalid: + messagebox.showerror("Неверный тикер", f"Проверьте тикер {invalid}.") + return + try: + # Modes A/B do not use the classic per-currency settings, so those cannot block a run. + visible = (self._read_settings() if self.strategy_mode == strategy.STRATEGY_CLASSIC + else self._safe_read_settings()) + days = int(self.historical_days_var.get().strip()) + if not 1 <= days <= 365: + raise ValueError("Количество дней для прогона должно быть от 1 до 365.") + historical_capital = float( + self.historical_initial_capital_var.get().strip().replace(",", ".") + ) + if not math.isfinite(historical_capital) or historical_capital <= 0: + raise ValueError("Начальный депозит для прогона должен быть больше 0 USDT.") + growth_threshold = float(self.historical_growth_var.get().strip().replace(",", ".")) + if not math.isfinite(growth_threshold) or not 0 <= growth_threshold <= 1000: + raise ValueError("Порог роста за 24 часа должен быть от 0 до 1000%.") + min_equity_pct = float(self.historical_min_equity_var.get().strip().replace(",", ".")) + if not math.isfinite(min_equity_pct) or not 1 <= min_equity_pct <= 100: + raise ValueError("Порог остановки капитала должен быть от 1 до 100%.") + max_positions = self._simulation_position_limit() + if universe_mode: + growth_threshold = float(self.auto_currency_growth_var.get().strip().replace(",", ".")) + if not math.isfinite(growth_threshold) or not 0 <= growth_threshold <= 1000: + raise ValueError("Порог автоподбора (рост за 24 ч) должен быть от 0 до 1000%.") + # Historical stake percentages must use the historical deposit, not the + # separate paper-account capital currently configured in the main UI. + visible["initial"] = historical_capital + visible["deposit_basis"] = historical_capital + visible["stake"] = historical_capital * visible["stake_pct"] / 100 + defaults = self._read_default_strategy(visible) + settings_by_symbol = { + symbol: self._strategy_for_symbol(symbol, defaults) for symbol in symbols + } + mode_params = (self._strategy_mode_params() if self.strategy_mode != strategy.STRATEGY_CLASSIC + else None) + except ValueError as exc: + messagebox.showerror("Проверьте настройки", str(exc)) + return + self._save_settings() + def compact(settings: dict[str, float]) -> dict[str, float]: + return { + "stake": settings["stake"], "leverage": settings["leverage"], + "trigger": settings["trigger"], "add_step": settings["add_step"], + "max_adds": settings["max_adds"], "stop_loss": settings["stop_loss"], + "take_profit": settings["take_profit"], + } + + strategies = {symbol: compact(settings) for symbol, settings in settings_by_symbol.items()} + default_strategy = compact(defaults) + self._backtest_cancel.clear() + self.historical_running = True + self.mode_combo.configure(state="disabled") + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + self.status_var.set( + f"{strategy.STRATEGY_TITLES[self.strategy_mode]} · " + f"загружаю свечи за {days} дн. · депозит {historical_capital:g} USDT · " + f"{'автоподбор' if universe_mode else 'фильтр роста 24 ч'}: {growth_threshold:g}% · " + f"лимит позиций {max_positions} · стоп капитала: {min_equity_pct:g}%" + + ("" if universe_mode else f": {', '.join(symbols)}") + "…" + ) + thread = threading.Thread( + target=self._historical_backtest_worker, + args=(symbols, strategies, historical_capital, int(visible["interval"]), + days, growth_threshold, min_equity_pct), + kwargs={"max_open_positions": max_positions, "universe_mode": universe_mode, + "default_strategy": default_strategy, + "include_funding": bool(self.historical_funding_var.get()), + "strategy_mode": self.strategy_mode, "mode_params": mode_params}, + daemon=True, + ) + thread.start() + + def _historical_backtest_worker(self, symbols: list[str], strategies: dict[str, dict[str, float]], + initial_capital: float, interval: int, days: int = 30, + growth_threshold: float = 30.0, + min_equity_pct: float = 10.0, + max_open_positions: int | None = None, + universe_mode: bool = False, + default_strategy: dict[str, float] | None = None, + include_funding: bool = True, + strategy_mode: str = strategy.STRATEGY_CLASSIC, + mode_params: dict[str, float] | None = None) -> None: + step_ms = interval * 60_000 + end_ms = (int(time.time() * 1000) // step_ms) * step_ms - 1 + period_ms = days * 24 * 60 * 60 * 1000 + trading_start_ms = ((end_ms - period_ms) // step_ms) * step_ms + start_ms = trading_start_ms - 24 * 60 * 60 * 1000 - step_ms + mode_run = strategy_mode != strategy.STRATEGY_CLASSIC and mode_params is not None + # Modes A/B need closed signal candles before the first decision (24h covers B's growth). + warmup_ms = (max(strategy.required_bars(strategy_mode, mode_params) + 2, + strategy.bars_for_hours(24, mode_params["timeframe_min"]) + 2) + * int(mode_params["timeframe_min"]) * 60_000 if mode_run else 2 * step_ms) + if mode_run: + start_ms = min(start_ms, trading_start_ms - warmup_ms) + + def progress(symbol: str, count: int, total: int, stage: str = "") -> None: + self.events.put(("historical_progress", symbol, count, total, stage)) + + candles_by_symbol: dict[str, list[list[float]]] = {} + try: + windows = None + ranges = {symbol: start_ms for symbol in symbols} + skipped: list[str] = [] + if universe_mode: + windows, skipped = prepare_universe(trading_start_ms, end_ms, growth_threshold, + cancel=self._backtest_cancel.is_set, progress=progress) + if not windows: + raise RuntimeError( + f"За период ни одна валюта из топ-100 по обороту не выросла за 24 ч больше {growth_threshold:g}%" + ) + symbols = sorted(windows) + fallback = default_strategy or next(iter(strategies.values())) + strategies = {symbol: strategies.get(symbol, fallback) for symbol in symbols} + # Minute data is needed from just before a pair first qualifies. + ranges = {symbol: max(start_ms, windows[symbol][0][0] - warmup_ms) for symbol in symbols} + with ThreadPoolExecutor(max_workers=max(1, min(2, len(symbols)))) as pool: + futures = { + pool.submit(fetch_klines, symbol, interval, ranges[symbol], end_ms, + self._backtest_cancel.is_set, progress, with_turnover=mode_run): symbol + for symbol in symbols + } + for future in as_completed(futures): + symbol = futures[future] + try: + candles_by_symbol[symbol] = future.result() + except InterruptedError: + raise + except Exception: + if not universe_mode: + raise + skipped.append(symbol) + if self._backtest_cancel.is_set(): + raise InterruptedError("Исторический прогон отменён") + funding_by_symbol: dict[str, dict[int, float]] | None = None + funding_failed: list[str] = [] + if include_funding: + funding_by_symbol = {} + loaded = sorted(candles_by_symbol) + with ThreadPoolExecutor(max_workers=4) as pool: + futures = {pool.submit(fetch_funding_history, symbol, int(candles_by_symbol[symbol][0][0]), + end_ms, self._backtest_cancel.is_set): symbol for symbol in loaded} + for done, future in enumerate(as_completed(futures), start=1): + symbol = futures[future] + try: + funding_by_symbol[symbol] = future.result() + except InterruptedError: + raise + except Exception: + funding_failed.append(symbol) + progress("Funding", done, len(loaded), f"история funding: {done}/{len(loaded)}") + if mode_run: + btc_hourly = None + if strategy_mode == strategy.STRATEGY_BREAKOUT and mode_params["btc_filter"] >= 1: + hour_ms = 3_600_000 + btc_start = trading_start_ms - (int(mode_params["btc_ema"]) * 3 + 48) * hour_ms + btc_hourly = fetch_klines("BTCUSDT", 60, btc_start, end_ms, self._backtest_cancel.is_set, progress) + result = run_mode_backtest( + candles_by_symbol, strategy_mode, mode_params, initial_capital, TAKER_FEE_PCT, + self._backtest_cancel.is_set, trading_start_ms=trading_start_ms, + min_growth_24h_pct=None if universe_mode else growth_threshold, + min_equity_pct=min_equity_pct, max_open_positions=max_open_positions, + universe_windows=windows, funding_by_symbol=funding_by_symbol, btc_hourly=btc_hourly, + ) + else: + result = run_backtest(candles_by_symbol, strategies, initial_capital, + TAKER_FEE_PCT, self._backtest_cancel.is_set, + trading_start_ms=trading_start_ms, + pause_below_24h_pct=growth_threshold, + resume_above_24h_pct=growth_threshold + 1.0, + min_equity_pct=min_equity_pct, + max_open_positions=max_open_positions, + universe_windows=windows, + funding_by_symbol=funding_by_symbol) + result["summary"]["unavailable_symbols"] = sorted(skipped) + result["summary"]["funding_unavailable_symbols"] = sorted(funding_failed) + csv_path, json_path = save_report(result, BACKTEST_REPORTS_DIR) + self.events.put(("historical_completed", result, str(csv_path), str(json_path))) + except InterruptedError: + self.events.put(("historical_cancelled",)) + except Exception as exc: + self.events.put(("historical_failed", str(exc))) + + def _show_historical_report(self, result: dict, csv_path: str, json_path: str) -> None: + summary = result["summary"] + window = tk.Toplevel(self.root) + window.title("Результат исторического прогона · Bybit") + window.geometry("1100x680") + window.minsize(820, 480) + body = ttk.Frame(window, padding=10) + body.pack(fill="both", expand=True) + net = summary["total_net_including_open_usdt"] + candle_items = list(summary["candles"].items()) + ttk.Label(body, text=( + f"{summary['period_start_utc'][:16]} — {summary['period_end_utc'][:16]} UTC · " + f"валют: {len(summary['symbols'])} · свечей: " + ", ".join( + f"{symbol} {count:,}" for symbol, count in candle_items[:30]) + + (f" … ещё {len(candle_items) - 30}" if len(candle_items) > 30 else "") + ), wraplength=1050).pack(anchor="w", pady=(0, 6)) + funding_text = ( + f" · funding {summary.get('funding_usdt', 0.0):+.4f} USDT ({summary.get('funding_events', 0)} начислений)" + if summary.get("funding_included") else " · funding не учтён" + ) + ttk.Label(body, text=( + f"{summary.get('strategy_title', strategy.STRATEGY_TITLES[strategy.STRATEGY_CLASSIC])} · " + f"Капитал {summary['initial_capital']:.2f} → оценка {summary['ending_equity_estimate']:.2f} USDT · " + f"Net {net:+.2f} USDT ({summary['return_pct']:+.2f}%) · " + f"закрыто {summary['closed_trades']} · прибыльных {summary['wins']} · " + f"процент прибыльных {summary['win_rate_pct']:.1f}% · " + f"комиссии {summary['fees_usdt']:.4f} USDT{funding_text} · открытых позиций {summary['open_positions']}" + ), font=("Segoe UI", 10, "bold"), wraplength=1050).pack(anchor="w", pady=(0, 8)) + if "avg_win_usdt" in summary: + profit_factor = summary.get("profit_factor") + ttk.Label(body, text=( + f"Средняя прибыльная {summary['avg_win_usdt']:+.4f} · средняя убыточная " + f"{summary['avg_loss_usdt']:+.4f} USDT · profit factor " + f"{profit_factor:.2f}" if profit_factor is not None else + f"Средняя прибыльная {summary['avg_win_usdt']:+.4f} · средняя убыточная " + f"{summary['avg_loss_usdt']:+.4f} USDT · profit factor —" + ) + f" · сигналов {summary.get('signals', 0)} · отменено при входе " + f"{summary.get('signals_rejected_at_fill', 0)}", wraplength=1050).pack(anchor="w", pady=(0, 6)) + if summary.get("funding_unavailable_symbols"): + ttk.Label(body, text="Нет истории funding (без funding): " + + ", ".join(summary["funding_unavailable_symbols"][:40]), wraplength=1050).pack(anchor="w") + if "max_drawdown_pct" in summary: + hold_days = summary.get("longest_hold_hours", 0.0) / 24 + risk_text = ( + f"Риск: макс. просадка {summary['max_drawdown_pct']:.2f}% " + f"({summary['max_drawdown_usdt']:.2f} USDT) · минимум капитала {summary['min_equity_usdt']:.2f} USDT · " + f"стопов {summary.get('stops', 0)} · ликвидаций {summary.get('liquidations', 0)} · " + f"открытых в минусе {summary.get('open_losing_positions', 0)} · " + f"самое долгое удержание {hold_days:.1f} дн. · макс. маржа в позициях " + f"{summary.get('max_margin_used_usdt', 0.0):.2f} USDT · одновременно позиций до " + f"{summary.get('max_simultaneous_positions', 0)}" + + (f" (лимит {summary['max_open_positions_limit']}, пропущено сигналов " + f"{summary.get('skipped_entries_position_limit', 0)})" + if summary.get("max_open_positions_limit") else "") + ) + ttk.Label(body, text=risk_text, foreground="#b45309", wraplength=1050).pack(anchor="w", pady=(0, 8)) + if summary.get("unavailable_symbols"): + ttk.Label(body, text="Нет данных Bybit (пропущены): " + ", ".join(summary["unavailable_symbols"][:40]) + + (" …" if len(summary["unavailable_symbols"]) > 40 else ""), + wraplength=1050).pack(anchor="w", pady=(0, 6)) + if summary.get("equity_stop_triggered"): + stop_message = ( + f"Прогон остановлен: капитал достиг {summary['equity_stop_pct']:g}% " + f"от начального ({summary['equity_stop_value_usdt']:.2f} USDT). " + f"Оценка капитала в момент остановки: {summary['equity_at_stop_usdt']:.2f} USDT; " + "открытые позиции показаны по цене срабатывания." + ) + ttk.Label(body, text=stop_message, foreground="#b42318", wraplength=1050).pack( + anchor="w", pady=(0, 8) + ) + else: + ttk.Label(body, text=( + f"Защитный порог капитала: {summary['equity_stop_pct']:g}% от начального " + "(с учётом открытого P&L и оценочной комиссии закрытия); не достигнут." + ), wraplength=1050).pack(anchor="w", pady=(0, 8)) + gate_items = list(summary["entry_allowed_at_end"].items()) + gate_state = " · ".join( + f"{symbol}: входы {'разрешены' if allowed else 'заблокированы'}" + for symbol, allowed in gate_items[:30] + ) + (f" · … ещё {len(gate_items) - 30}" if len(gate_items) > 30 else "") + ttk.Label(body, text=f"{summary['entry_filter']} {gate_state}", wraplength=1050).pack(anchor="w", pady=(0, 6)) + table_frame = ttk.Frame(body) + table_frame.pack(fill="both", expand=True) + columns = ("symbol", "side", "status", "opened", "closed", "entry", "exit", "entries", "gross", "fees", + "funding", "net", "roi", "reason") + tree = ttk.Treeview(table_frame, columns=columns, show="headings") + heads = {"symbol": "Тикер", "side": "Сторона", "status": "Статус", "opened": "Вход UTC", "closed": "Выход UTC", + "entry": "Средняя входа", "exit": "Выход / цена", "entries": "Входов", + "gross": "Gross USDT", "fees": "Комиссии", "funding": "Funding", "net": "Net USDT", + "roi": "ROI %", "reason": "Причина"} + widths = {"symbol": 90, "side": 60, "status": 66, "opened": 135, "closed": 135, "entry": 100, "exit": 100, + "entries": 55, "gross": 88, "fees": 80, "funding": 80, "net": 88, "roi": 70, "reason": 210} + for column in columns: + tree.heading(column, text=heads[column]) + tree.column(column, width=widths[column], anchor="center") + tree.tag_configure("profit", foreground="#13843b") + tree.tag_configure("loss", foreground="#c62828") + tree.pack(side="left", fill="both", expand=True) + scrollbar = ttk.Scrollbar(table_frame, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scrollbar.set) + scrollbar.pack(side="right", fill="y") + for trade in result["trades"]: + tree.insert("", "end", values=( + trade["symbol"], trade.get("side", "LONG"), trade["status"], trade["opened_at"][:19].replace("T", " "), + trade["closed_at"][:19].replace("T", " ") if trade["closed_at"] else "—", + f"{trade['entry']:.10g}", f"{trade['exit']:.10g}", trade["entries"], + f"{trade['gross_usdt']:+.4f}", f"{trade['fees_usdt']:.4f}", f"{trade.get('funding_usdt', 0.0):+.4f}", + f"{trade['net_usdt']:+.4f}", f"{trade['roi_pct']:+.2f}", trade["reason"], + ), tags=("profit" if trade["net_usdt"] > 0 else "loss" if trade["net_usdt"] < 0 else "",)) + ttk.Label(body, text=summary["assumptions"], wraplength=1050, justify="left").pack(anchor="w", pady=8) + ttk.Label(body, text=f"CSV: {csv_path} · Сводка: {json_path}", wraplength=1050).pack(anchor="w") + + def _begin_live_preflight(self, symbol: str, settings: dict[str, float], + per_symbol_settings: dict[str, dict[str, float]] | None = None) -> None: + api_key = self.api_key_var.get().strip() + api_secret = self.api_secret_var.get().strip() + if not api_key or not api_secret: + messagebox.showerror("Нет API-данных", "Откройте «API Bybit…» и вставьте API key и API secret.") + self.open_live_settings() + return + all_settings = list((per_symbol_settings or {}).values()) or [settings] + no_stop = [item for item in all_settings if item.get("stop_loss", 0) <= 0] + if no_stop and not self.testnet_var.get(): + worst_leverage = max(item.get("leverage", 1) for item in no_stop) + if not messagebox.askyesno( + "Стоп-лосс выключен", + "У части валют стоп-лосс равен 0: убыток позиции ничем не ограничен, а доливки " + "увеличивают объём при падении цены" + + (f". При плече {worst_leverage:g}x позицию может ликвидировать биржа" if worst_leverage > 1 else "") + + ".\n\nВсё равно запустить на Mainnet?", + icon="warning", + ): + return + if not self.testnet_var.get() and not messagebox.askyesno( + "Подтвердите реальные ордера", + f"Будут отправляться реальные рыночные ордера по {', '.join(sorted(self.enabled_symbols))} " + f"с плечом {settings['leverage']:g}. " + "Биржевые TP/SL останутся активны, пока позиция открыта. Продолжить на Mainnet?", + icon="warning", + ): + return + self.live_preflight = True + self.mode_combo.configure(state="disabled") + self.start_btn.configure(state="disabled") + network_name = "Testnet" if self.testnet_var.get() else "Mainnet" + self.status_var.set(f"Проверяю API Bybit ({network_name})…") + thread = threading.Thread( + target=self._live_preflight_multi_worker, + args=(api_key, api_secret, self.testnet_var.get(), sorted(self.enabled_symbols), + settings.copy(), per_symbol_settings or {}), + daemon=True, + ) + thread.start() + + def _live_preflight_multi_worker(self, api_key: str, api_secret: str, testnet: bool, + symbols: list[str], base_settings: dict[str, float], + per_symbol_settings: dict[str, dict[str, float]]) -> None: + """Validate and reconcile every enabled symbol before starting parallel live loops.""" + try: + client = BybitLiveClient(api_key, api_secret, testnet) + wallet = client.get_wallet() + baseline_key = self._deposit_baseline_key(api_key, testnet) + baseline = float(self.live_initial_deposits.get(baseline_key, 0) or wallet.get("wallet") or 0) + if baseline <= 0: + raise BybitAPIError("Не удалось определить стартовый депозит аккаунта для расчёта ставки") + prepared = [] + projected_available = float(wallet.get("available") or 0) + for symbol in symbols: + settings = per_symbol_settings.get(symbol, base_settings).copy() + settings["deposit_basis"] = baseline + settings["stake"] = baseline * settings["stake_pct"] / 100 + spec = client.get_instrument(symbol) + fee_pct = client.get_taker_fee_pct(symbol) + rows = client.get_positions(symbol) + if any(int(row.get("positionIdx", 0)) != 0 for row in rows): + raise BybitAPIError(f"{symbol}: для бота нужен режим позиции One-Way (positionIdx=0), а не Hedge") + exchange_position = next((row for row in rows if float(row.get("size") or 0) > 0), None) + saved_position = self.symbol_states.get(symbol, CurrencyState()).live_position + if saved_position is None and self.live_position and self.live_position.symbol == symbol: + saved_position = self.live_position + resume_position = None + if exchange_position: + if exchange_position.get("side") != "Buy": + raise BybitAPIError(f"{symbol}: найдена SHORT-позиция; бот сопровождает только LONG") + actual_leverage = float(exchange_position.get("leverage") or settings["leverage"]) + settings["leverage"] = actual_leverage + avg = float(exchange_position.get("avgPrice") or (saved_position.entry_price if saved_position else 0)) + qty = float(exchange_position.get("size") or 0) + if avg <= 0 or qty <= 0: + raise BybitAPIError(f"{symbol}: у Bybit-позиции нет цены или размера") + if saved_position: + resume_position = Position(**vars(saved_position)) + changed = abs(qty - saved_position.qty) > float(spec["qty_step"]) * 2 + resume_position.entry_price = avg + resume_position.qty = qty + resume_position.stake = avg * qty / actual_leverage + if changed: + resume_position.add_count = settings["max_adds"] + else: + resume_position = Position(self._allocate_live_id(), symbol, avg, qty, + avg * qty / actual_leverage, avg * qty * fee_pct / 100, + time.time(), avg, settings["max_adds"]) + tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + client.update_position_stops(symbol, + avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0, + avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0, + spec["tick_size"]) + else: + if saved_position: + # The saved position was closed on Bybit while the app was off: + # record its realized result instead of silently dropping it. + closed = client.get_latest_closed_pnl(symbol, int(saved_position.opened_at * 1000)) + self.events.put(("live_restored_closed", closed, saved_position)) + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + if projected_available < required: + raise BybitAPIError( + f"{symbol}: для всех включённых валют не хватает свободной маржи; " + f"после предыдущих резервов осталось {projected_available:.2f} USDT, нужно около {required:.2f} USDT" + ) + projected_available -= required + client.set_leverage(symbol, settings["leverage"]) + settings["fee"] = fee_pct + prepared.append((symbol, settings, spec, fee_pct, exchange_position, resume_position)) + self.events.put(("live_ready_multi", client, wallet, prepared, baseline_key, baseline)) + except Exception as exc: + self.events.put(("live_preflight_failed", str(exc))) + + def _activate_live_multi(self, client: BybitLiveClient, wallet: dict[str, float], prepared: list, + baseline_key: str | None, baseline: float) -> None: + self._capture_active_symbol() + self.live_preflight = False + self.mode_combo.configure(state="readonly") + self.live_client = client + self.live_wallet = wallet + if baseline_key: + self.live_initial_deposits[baseline_key] = float(baseline) + self.live_order_lock = threading.Lock() + self.running = True + self.next_auto_currency_scan_at = 0.0 + self.session_started_at = time.time() + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + for symbol, settings, spec, fee_pct, exchange_position, resume_position in prepared: + state = self._ensure_symbol(symbol) + self.enabled_symbols.add(symbol) + state.live_position = resume_position + state.live_position_info = exchange_position + state.live_order_busy = False + state.live_transition_pending = False + state.live_halted = False + self.live_commands_by_symbol[symbol] = queue.Queue() + if resume_position: + self._reserve_live_id(resume_position.trade_id) + if exchange_position: + self._replace_cached_position(exchange_position) + else: + self._replace_cached_position(None, symbol) + self._fetch_baseline_async(symbol, self.interval_minutes) + worker = threading.Thread(target=self._live_worker, + args=(client, symbol, settings.copy(), spec, fee_pct, resume_position, + self.live_commands_by_symbol[symbol]), daemon=True) + self.live_workers[symbol] = worker + worker.start() + selected = self.symbol_var.get().strip().upper() + if selected not in self.enabled_symbols: + selected = prepared[0][0] + self.symbol_var.set(selected) + selected_config = next((item for item in prepared if item[0] == selected), prepared[0]) + self.applied_settings = selected_config[1].copy() + self.live_spec = selected_config[2] + self.live_fee_pct = selected_config[3] + self._activate_symbol_state(selected) + self.ws_symbols = sorted(self.enabled_symbols | {s for s, state in self.symbol_states.items() if state.live_position}) + self.ws_thread = threading.Thread(target=self._ws_worker, args=(self.ws_symbols,), daemon=True) + self.ws_thread.start() + self.status_var.set(f"Реальный бот запущен параллельно · {len(prepared)} валют · {'Testnet' if client.testnet else 'MAINNET'}") + self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · equity {wallet['equity']:.2f} · доступно {wallet['available']:.2f} USDT") + self._refresh_settings_summary() + self._refresh_ui() + self._refresh_currency_tiles() + self._save_account_state() + + def _live_preflight_worker(self, api_key: str, api_secret: str, testnet: bool, symbol: str, + settings: dict[str, float], saved_position: Position | None) -> None: + try: + client = BybitLiveClient(api_key, api_secret, testnet) + wallet = client.get_wallet() + baseline_key = self._deposit_baseline_key(api_key, testnet) + baseline = float(self.live_initial_deposits.get(baseline_key, 0) or wallet.get("wallet") or 0) + if baseline <= 0: + raise BybitAPIError("Не удалось определить стартовый депозит аккаунта для расчёта ставки") + settings["deposit_basis"] = baseline + settings["stake"] = baseline * settings["stake_pct"] / 100 + spec = client.get_instrument(symbol) + fee_pct = client.get_taker_fee_pct(symbol) + rows = client.get_positions(symbol) + if any(int(row.get("positionIdx", 0)) != 0 for row in rows): + raise BybitAPIError("Для этого бота нужен режим позиции One-Way (positionIdx=0), а не Hedge") + exchange_position = next((row for row in rows if float(row.get("size") or 0) > 0), None) + resume_position = None + if exchange_position: + if exchange_position.get("side") != "Buy": + raise BybitAPIError("По тикеру уже открыта SHORT-позиция; бот управляет только LONG") + if saved_position and saved_position.symbol != symbol: + raise BybitAPIError( + f"В истории программы есть позиция {saved_position.symbol}, а на бирже обнаружена {symbol}. " + "Укажите тикер открытой позиции, чтобы продолжить её сопровождение." + ) + actual_leverage = float(exchange_position.get("leverage") or settings["leverage"]) + settings["leverage"] = actual_leverage + avg = float(exchange_position.get("avgPrice") or (saved_position.entry_price if saved_position else 0)) + qty = float(exchange_position.get("size") or 0) + if avg <= 0 or qty <= 0: + raise BybitAPIError("Bybit вернул открытую позицию без цены или размера; сопровождение не запущено") + if saved_position: + # Reconcile local shadow against the authoritative position. + # This also recovers fills that happened just before a shutdown. + resume_position = Position(**vars(saved_position)) + quantity_changed = abs(qty - saved_position.qty) > float(spec["qty_step"]) * 2 + resume_position.entry_price = avg + resume_position.qty = qty + resume_position.stake = avg * qty / actual_leverage + resume_position.last_add_price = resume_position.last_add_price or avg + if quantity_changed: + # The precise number of fills may be unknown after a + # crash; avoid exceeding the configured add limit. + resume_position.add_count = settings["max_adds"] + else: + # Adopt an existing LONG even when the app has no local + # shadow (e.g. the process restarted after a fill). + now = time.time() + resume_position = Position( + self._allocate_live_id(), symbol, avg, qty, avg * qty / actual_leverage, + avg * qty * fee_pct / 100, now, avg, settings["max_adds"], + ) + tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + tp = avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0 + sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + client.update_position_stops(symbol, tp, sl, spec["tick_size"]) + else: + if saved_position: + closed = client.get_latest_closed_pnl(symbol, int(saved_position.opened_at * 1000)) + self.events.put(("live_restored_closed", closed, saved_position)) + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + if wallet["available"] < required: + raise BybitAPIError(f"Доступно {wallet['available']:.2f} USDT, требуется около {required:.2f} USDT на маржу и комиссию") + client.set_leverage(symbol, settings["leverage"]) + self.events.put(("live_ready", client, wallet, spec, fee_pct, settings, symbol, + exchange_position, resume_position, baseline_key, baseline)) + except Exception as exc: + self.events.put(("live_preflight_failed", str(exc))) + + def _activate_live(self, client: BybitLiveClient, wallet: dict[str, float], spec: dict[str, str], + fee_pct: float, settings: dict[str, float], symbol: str, exchange_position: dict | None, + resume_position: Position | None, baseline_key: str | None = None, + baseline: float | None = None) -> None: + self.live_preflight = False + self.mode_combo.configure(state="readonly") + self.live_client = client + self.live_wallet = wallet + if baseline_key: + self.live_initial_deposits[baseline_key] = float(baseline or settings.get("deposit_basis") or wallet.get("wallet") or 0) + self._save_account_state() + self.live_spec = spec + self.live_fee_pct = fee_pct + settings["fee"] = fee_pct + self.applied_settings = settings.copy() + self.symbol = symbol + self.interval_minutes = CANDLE_INTERVAL_MINUTES + self.live_halted = False + self.live_order_busy = False + self.live_transition_pending = False + if exchange_position: + if resume_position is None: + raise RuntimeError("Не удалось восстановить данные открытой позиции Bybit") + self.live_position = resume_position + self._reserve_live_id(resume_position.trade_id) + self.leverage_var.set(str(settings["leverage"])) + self.live_position_info = exchange_position + self._replace_cached_position(exchange_position) + self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · Equity {wallet['equity']:.2f} · доступно {wallet['available']:.2f} USDT") + self._save_account_state() + self.status_var.set( + f"Открытая позиция Bybit восстановлена · {symbol} · средняя {resume_position.entry_price:g} · " + f"объём {resume_position.qty:g}; управление возобновлено" + ) + else: + self.live_position_info = None + self.live_positions = [row for row in self.live_positions if row.get("symbol") != symbol] + self._render_bybit_positions() + self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · стартовый депозит {settings.get('deposit_basis', wallet['wallet']):.2f} · кошелёк {wallet['wallet']:.2f} · доступно {wallet['available']:.2f} USDT") + self.running = True + self.start_btn.configure(state="disabled") + self.stop_btn.configure(state="normal") + restored = " · сопровождение открытой позиции восстановлено" if exchange_position else "" + self.status_var.set(f"Реальный бот запущен · {symbol} · {'Testnet' if client.testnet else 'MAINNET'}{restored}") + self._refresh_settings_summary() + self._refresh_ui() + self._fetch_baseline_async(symbol, self.interval_minutes) + self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbol,), daemon=True) + self.ws_thread.start() + self.live_control_thread = threading.Thread(target=self._live_worker, args=(client, symbol, settings.copy(), spec, fee_pct, self.live_position), daemon=True) + self.live_control_thread.start() + self._save_account_state() + + def _allocate_live_id(self) -> int: + """Return a unique live trade id; safe to call from worker threads.""" + with self._live_id_lock: + trade_id = self.next_live_id + self.next_live_id += 1 + return trade_id + + def _reserve_live_id(self, trade_id: int) -> None: + """Make sure future ids are above an id restored from disk or the exchange.""" + with self._live_id_lock: + self.next_live_id = max(self.next_live_id, trade_id + 1) + + def _replace_cached_position(self, row: dict | None, symbol: str | None = None) -> None: + target = symbol or (row.get("symbol") if row else None) + if target: + self.live_positions = [item for item in self.live_positions if item.get("symbol") != target] + if row and float(row.get("size") or 0) > 0: + self.live_positions.append(row) + self._render_bybit_positions() + + def _live_worker(self, client: BybitLiveClient, symbol: str, settings: dict[str, float], + spec: dict[str, str], fee_pct: float, shadow: Position | None, + command_queue: queue.Queue | None = None) -> None: + command_queue = command_queue or self.live_commands + try: + self._live_worker_loop(client, symbol, settings, spec, fee_pct, shadow, command_queue) + finally: + # Let the UI thread unregister this worker's queue so the symbol can get a + # fresh worker when it is enabled again (manually or by auto-rotation). + self.events.put(("live_worker_exited", symbol, command_queue)) + + def _live_worker_loop(self, client: BybitLiveClient, symbol: str, settings: dict[str, float], + spec: dict[str, str], fee_pct: float, shadow: Position | None, + command_queue: queue.Queue) -> None: + last_wallet_at = 0.0 + last_position_at = 0.0 + while self.running: + if symbol not in self.enabled_symbols and shadow is None: + return + try: + command = command_queue.get(timeout=0.4) + except queue.Empty: + command = None + try: + if command: + action, timestamp, price, *extra = command + if action == "settings": + updated_settings = extra[0] + updated_settings["fee"] = fee_pct + if updated_settings["leverage"] != settings["leverage"]: + client.set_leverage(symbol, updated_settings["leverage"]) + settings = updated_settings + if shadow: + action = "stops" + else: + self.events.put(("live_settings_updated", symbol)) + action = "settings_done" + if action in ("open", "add"): + skip_reason = None + with self.live_order_lock: + wallet_now = client.get_wallet() + required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100) + order_qty = "" + notional = 0.0 + if wallet_now["available"] < required: + skip_reason = (f"недостаточно доступной маржи: {wallet_now['available']:.2f} USDT; " + f"требуется около {required:.2f} USDT с учётом комиссии") + else: + try: + order_qty = client.floor_qty(settings["stake"] * settings["leverage"] / price, spec) + except BybitAPIError as exc: + skip_reason = str(exc) + else: + notional = float(order_qty) * price + minimum = float(spec.get("min_notional") or 0) + if notional < minimum: + skip_reason = (f"размер заявки {notional:.4f} USDT меньше минимума " + f"контракта {minimum:g} USDT") + if skip_reason: + # A skipped signal is not an exchange failure: keep managing the + # symbol. For an add, consume this level (same rule as simulation + # and backtest) so the next add is measured from this price. + if action == "add" and shadow is not None: + shadow.last_add_price = price + self.events.put(("live_order_skipped", symbol, action, skip_reason, price)) + continue + added_qty = float(order_qty) + expected_avg = price if shadow is None else (shadow.entry_price * shadow.qty + price * added_qty) / (shadow.qty + added_qty) + target_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + tp = expected_avg * (1 + target_pct / 100) if settings["take_profit"] > 0 else 0.0 + sl = expected_avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + submitted_at_ms = int(time.time() * 1000) + order_id = client.place_market_buy(symbol, order_qty, tp, sl, spec["tick_size"]) + row = None + order_info = None + closed_row = None + no_fill_status = None + for attempt in range(20): + time.sleep(.5) + row = client.get_open_position(symbol) + if row and row.get("side") == "Buy": + break + if attempt % 4 == 3 and order_id: + order_info = client.get_order(symbol, order_id) + if order_info: + order_status = str(order_info.get("orderStatus") or "") + executed_qty = float(order_info.get("cumExecQty") or 0) + if order_status in {"Cancelled", "Rejected", "Deactivated"} and executed_qty <= 0: + no_fill_status = order_status + break + if order_status == "Filled": + closed_row = client.get_latest_closed_pnl(symbol, submitted_at_ms - 2000) + if (closed_row and int(closed_row.get("updatedTime") or 0) >= submitted_at_ms - 2000 + and float(closed_row.get("closedSize") or 0) > 0): + break + if no_fill_status: + self.events.put(("live_order_no_fill", symbol, action, no_fill_status)) + continue + if not row and not closed_row: + # Keep the execution worker alive and block further + # entries until the exchange can confirm the order. + # Never resend an order whose result is ambiguous. + self.events.put(("live_order_pending", symbol, order_id)) + while self.running and not row and not no_fill_status and not closed_row: + time.sleep(2.0) + try: + row = client.get_open_position(symbol) + if row: + break + order_info = client.get_order(symbol, order_id) if order_id else None + if order_info: + order_status = str(order_info.get("orderStatus") or "") + executed_qty = float(order_info.get("cumExecQty") or 0) + if order_status in {"Cancelled", "Rejected", "Deactivated"} and executed_qty <= 0: + no_fill_status = order_status + break + if order_status == "Filled" or executed_qty > 0: + closed_row = client.get_latest_closed_pnl(symbol, submitted_at_ms - 2000) + if (closed_row and int(closed_row.get("updatedTime") or 0) >= submitted_at_ms - 2000 + and float(closed_row.get("closedSize") or 0) > 0): + break + except Exception: + # Transient API failures do not justify + # duplicating an order with unknown status. + continue + if not self.running: + return + if no_fill_status: + self.events.put(("live_order_no_fill", symbol, action, no_fill_status)) + continue + if not row and closed_row: + # A fast TP/SL can close the position before the + # position endpoint ever observes it. Record the + # exchange's realized result and continue the loop. + closed_avg = float(closed_row.get("avgEntryPrice") or expected_avg) + closed_qty = float(closed_row.get("closedSize") or closed_row.get("qty") or added_qty) + if shadow is None: + recovered_id = self._allocate_live_id() + shadow = Position( + recovered_id, symbol, closed_avg, closed_qty, + closed_avg * closed_qty / settings["leverage"], + float(closed_row.get("openFee") or 0), timestamp, closed_avg, 0, + ) + else: + shadow.entry_price = closed_avg + shadow.qty = closed_qty + shadow.stake = closed_avg * closed_qty / settings["leverage"] + wallet = client.get_wallet() + self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True + self.events.put(("live_closed", shadow, closed_row, wallet, + "TP/стоп Bybit сработал сразу после входа")) + shadow = None + last_position_at = time.time() + last_wallet_at = last_position_at + continue + if not row or row.get("side") != "Buy": + raise BybitAPIError("Bybit подтвердил позицию в неизвестном направлении; автоматическое управление остановлено") + avg = float(row["avgPrice"]) + qty = float(row["size"]) + stake_total = avg * qty / settings["leverage"] + if shadow is None: + shadow = Position(self._allocate_live_id(), symbol, avg, qty, stake_total, + notional * fee_pct / 100, timestamp, price, 0) + else: + shadow.entry_price = avg + shadow.qty = qty + shadow.stake = stake_total + shadow.entry_fee += notional * fee_pct / 100 + shadow.last_add_price = price + shadow.add_count += 1 + # Persist the confirmed fill before any follow-up API call can fail. + self.events.put(("live_order_result", symbol, action, shadow, row, None)) + actual_tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + actual_tp = avg * (1 + actual_tp_pct / 100) if settings["take_profit"] > 0 else 0.0 + actual_sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + client.update_position_stops(symbol, actual_tp, actual_sl, spec["tick_size"]) + wallet = client.get_wallet() + self.events.put(("live_sync", symbol, shadow, row, wallet)) + last_position_at = time.time() + last_wallet_at = last_position_at + elif action == "close" and not shadow: + self.events.put(("live_order_skipped", symbol, action, "нет открытой позиции", price)) + elif action == "close" and shadow: + qty = client.floor_qty(shadow.qty, spec) + client.close_long_market(symbol, qty) + # Poll for the exchange to confirm instead of failing after one short check. + deadline = time.time() + MANUAL_CLOSE_CONFIRM_SECONDS + row = None + while self.running: + time.sleep(0.5) + try: + row = client.get_open_position(symbol) + except BybitAPIError: + row = shadow # unknown state: keep waiting until the deadline + if not row or time.time() >= deadline: + break + if row: + # Still open (or unknown): keep managing the position; the user can retry. + self.events.put(("live_order_skipped", symbol, action, + "Bybit не подтвердил закрытие за " + f"{MANUAL_CLOSE_CONFIRM_SECONDS} с; позиция остаётся под управлением, " + "проверьте её на бирже", price)) + last_position_at = 0.0 + continue + closed_row = client.get_latest_closed_pnl(symbol, int(shadow.opened_at * 1000)) + wallet = client.get_wallet() + self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True + self.events.put(("live_closed", shadow, closed_row, wallet, "Ручное закрытие")) + shadow = None + last_wallet_at = time.time() + elif action == "stops" and shadow: + avg = shadow.entry_price + target_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct)) + tp = avg * (1 + target_pct / 100) if settings["take_profit"] > 0 else 0.0 + sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0 + client.update_position_stops(symbol, tp, sl, spec["tick_size"]) + self.events.put(("live_stops_updated", symbol)) + now = time.time() + if now - last_position_at >= 2.0: + row = client.get_open_position(symbol) + if row is None and shadow is not None: + closed_row = client.get_latest_closed_pnl(symbol, int(shadow.opened_at * 1000)) + wallet = client.get_wallet() + self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True + self.events.put(("live_closed", shadow, closed_row, wallet, "TP/стоп на Bybit")) + shadow = None + last_wallet_at = now + elif row is not None and shadow is None: + raise BybitAPIError("На аккаунте появилась позиция без записи бота. Автоматическая торговля остановлена") + elif row is not None: + shadow.entry_price = float(row.get("avgPrice") or shadow.entry_price) + shadow.qty = float(row.get("size") or shadow.qty) + shadow.stake = shadow.entry_price * shadow.qty / settings["leverage"] + wallet = client.get_wallet() if now - last_wallet_at >= 8.0 else None + self.events.put(("live_sync", symbol, shadow, row, wallet)) + if wallet: + last_wallet_at = now + last_position_at = now + except Exception as exc: + self.events.put(("live_worker_failed", symbol, str(exc))) + break + + def _position_limit_or_none(self) -> int | None: + try: + return self._simulation_position_limit() + except ValueError: + return None + + def _live_slots_in_use(self) -> int: + """Open live positions plus entries already sent and not yet reconciled.""" + self._capture_active_symbol() + return sum(1 for state in self.symbol_states.values() + if state.live_position is not None + or (state.live_order_busy and state.live_position is None)) + + def _on_live_tick(self, timestamp: float, price: float, crossed_entry_threshold: bool) -> None: + if self.live_order_busy or self.live_halted or self.live_transition_pending or not self.live_client: + return + settings = self.strategy_by_symbol.get(self.symbol) or self.applied_settings or self._safe_read_settings() + if self.live_position is None: + if (crossed_entry_threshold and self.symbol in self.enabled_symbols + and self.symbol not in self.rotation_pending_disable): + limit = self._position_limit_or_none() + if limit is not None and self._live_slots_in_use() >= limit: + self.status_var.set(f"Вход {self.symbol} пропущен: лимит одновременных позиций {limit} занят") + return + self.live_order_busy = True + commands = self.live_commands_by_symbol.get(self.symbol, self.live_commands) + commands.put(("open", timestamp, price)) + self.status_var.set(f"Сигнал входа · отправляю рыночный ордер {self.symbol}") + elif (self.symbol in self.enabled_symbols and self.symbol not in self.rotation_pending_disable + and strategy.can_add(self.live_position.add_count, settings["max_adds"], settings["add_step"]) + and price <= strategy.add_level(self.live_position.last_add_price, settings["add_step"])): + # Pairs waiting for retirement only manage their position (same rule as the backtest). + self.live_order_busy = True + commands = self.live_commands_by_symbol.get(self.symbol, self.live_commands) + commands.put(("add", timestamp, price)) + self.status_var.set(f"Уровень доливки · отправляю ордер {self.symbol}") + + def _ws_worker(self, symbols: list[str] | str) -> None: + if isinstance(symbols, str): + symbols = [symbols] + while self.running: + try: + symbols = list(self.ws_symbols) + if not symbols: + time.sleep(1) + continue + def on_open(ws) -> None: + # Subscribe to whatever is current at connect time; later changes are + # applied with subscribe/unsubscribe on this socket (no reconnect). + with self._ws_lock: + selected = sorted(set(self.ws_symbols)) + self._ws_send_topics(ws, "subscribe", selected) + self.ws_subscribed = set(selected) + + app = websocket.WebSocketApp( + WS_URL, + on_open=on_open, + on_message=self._on_message, + on_error=lambda _ws, err: self.events.put(("status", f"Ошибка потока: {err}")), + on_close=lambda _ws, code, _msg: self.events.put(("status", f"Соединение закрыто ({code}); переподключение…")), + ) + self.ws_app = app + app.run_forever(ping_interval=20, ping_timeout=10) + except Exception as exc: + self.events.put(("status", f"Ошибка подключения: {exc}")) + if self.running: + time.sleep(2) + + def _on_message(self, _ws, message: str) -> None: + try: + packet = json.loads(message) + if packet.get("op") == "subscribe": + self.events.put(("status", "Поток Bybit подключён" if packet.get("success") else f"Подписка: {packet}")) + topic = str(packet.get("topic") or "") + symbol = topic.removeprefix("publicTrade.").upper() + if symbol not in self.ws_symbols: + return + for trade in packet.get("data", []): + price = float(trade["p"]) + timestamp = int(trade["T"]) / 1000.0 + self.events.put(("trade", symbol, timestamp, price)) + except (ValueError, KeyError, TypeError, json.JSONDecodeError) as exc: + self.events.put(("status", f"Не удалось разобрать сообщение Bybit: {exc}")) + + def stop(self) -> None: + if self.historical_running: + self._backtest_cancel.set() + self.status_var.set("Останавливаю исторический прогон…") + self.stop_btn.configure(state="disabled") + return + if not self.running: + return + self.running = False + self._save_account_state() + for commands in [self.live_commands, *self.live_commands_by_symbol.values()]: + while True: + try: + commands.get_nowait() + except queue.Empty: + break + if self.ws_app: + try: + self.ws_app.close() + except Exception: + pass + if self.mode_var.get() == "Реальная торговля" and any(s.live_position for s in self.symbol_states.values()): + self.status_var.set("Мониторинг остановлен · биржевые TP/SL продолжают действовать на Bybit") + else: + self.status_var.set("Остановлен") + self.start_btn.configure(state="normal") + self.stop_btn.configure(state="disabled") + self._refresh_ui() + self._draw_chart() + + def _poll_events(self) -> None: + handled = 0 + while handled < MAX_EVENTS_PER_POLL: + try: + event = self.events.get_nowait() + except queue.Empty: + break + handled += 1 + if event[0] == "historical_progress": + _, symbol, count, total, *stage = event + if self.historical_running: + detail = f" · {stage[0]}" if stage and stage[0] else "" + if symbol == "Отбор валют": + self.status_var.set(f"Отбор валют по истории: {count:,} из {total:,} контрактов{detail}") + elif symbol == "Funding": + self.status_var.set(f"Загружаю историю funding: {count:,} из {total:,} валют") + else: + self.status_var.set(f"Загружаю {symbol}: {count:,} из ~{total:,} свечей{detail}") + elif event[0] == "historical_completed": + _, result, csv_path, json_path = event + self.historical_running = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal", text="Запустить прогон") + self.stop_btn.configure(state="disabled") + summary = result["summary"] + self.status_var.set( + (f"Прогон остановлен по лимиту капитала {summary['equity_stop_pct']:g}% · " + if summary.get("equity_stop_triggered") else "Прогон завершён · ") + + f"Net {summary['total_net_including_open_usdt']:+.2f} USDT · отчёт {csv_path}" + ) + self._show_historical_report(result, csv_path, json_path) + elif event[0] == "historical_cancelled": + self.historical_running = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal", text="Запустить прогон") + self.stop_btn.configure(state="disabled") + self.status_var.set("Исторический прогон отменён") + elif event[0] == "historical_failed": + self.historical_running = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal", text="Запустить прогон") + self.stop_btn.configure(state="disabled") + self.status_var.set(f"Исторический прогон не выполнен: {event[1]}") + messagebox.showerror("Исторический прогон не выполнен", event[1]) + elif event[0] == "startup_currency_filter_ready": + _, mode, threshold, snapshot, source = event + self.startup_currency_filter_busy = False + self.mode_combo.configure(state="readonly") + if mode != self.mode_var.get(): + self.start_btn.configure(state="normal") + self.status_var.set("Режим изменён во время проверки. Нажмите «Старт» ещё раз.") + continue + self._apply_startup_currency_filter(mode, threshold, snapshot, source) + elif event[0] == "startup_currency_filter_failed": + _, mode, error = event + self.startup_currency_filter_busy = False + self.startup_currency_filter_approved_for = None + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal") + self.status_var.set(f"Предстартовая проверка не выполнена: {error}") + messagebox.showerror( + "Проверка валют не выполнена", + "Не удалось получить актуальные данные Bybit за 24 часа. Сделки не запущены.\n\n" + error, + ) + elif event[0] == "status": + if self.running: + self.status_var.set(event[1]) + elif event[0] == "api_connected": + self.api_connecting = False + self.connect_btn.configure(state="normal") + self._show_api_snapshot(*event[1:]) + elif event[0] == "api_connect_failed": + self.api_connecting = False + self.connect_btn.configure(state="normal") + self.status_var.set(f"Не удалось подключиться к Bybit: {event[1]}") + messagebox.showerror("Подключение Bybit не выполнено", event[1]) + elif event[0] == "baseline": + if self.running and int(event[2]) == self.interval_minutes: + self._capture_active_symbol() + state = self._ensure_symbol(event[1]) + state.baseline_close = float(event[3]) + state.previous_entry_signal_pct = None + if event[1] == self.symbol: + self._activate_symbol_state(event[1]) + self.status_var.set(f"База сигнала {event[1]} загружена: закрытие {self.interval_minutes}-мин свечи") + self._refresh_rolling_change(reschedule=False) + elif event[0] == "trade" and self.running: + if len(event) >= 4: + self._on_trade(event[1], event[2], event[3]) + else: + self._on_trade(self.symbol, event[1], event[2]) + elif event[0] == "ticker_24h": + for symbol, (price, change, turnover) in event[1].items(): + self.ticker_prices[symbol] = price + self.ticker_24h[symbol] = change + self.ticker_turnover_24h[symbol] = turnover + self.ticker_data_source = event[2] if len(event) > 2 else "Bybit" + if len(event) > 3: + self.ticker_funding_pct.update(event[3]) + if self.auto_currency_status_var.get().startswith("Ошибка"): + self.auto_currency_status_var.set(f"Данные восстановлены · пар: {len(event[1])}") + self._refresh_currency_tiles() + for symbol in list(self.detail_windows): + self._draw_detail_chart(symbol) + self._maybe_auto_rotate_currencies() + elif event[0] == "mode_signal": + _, symbol, mode, bucket, tf_ms, signal, error = event + state = self._ensure_symbol(symbol) + state.mode_eval_busy = False + if mode != self.strategy_mode or not self.running: + continue + if error: + # Retry on the next poll unless the candle is long gone (e.g. a delisted pair). + if time.time() * 1000 - (bucket + tf_ms) > 60_000: + state.mode_signal_bucket = bucket + self.status_var.set(f"Сигнал {symbol}: {error}") + continue + state.mode_signal_bucket = bucket + self._capture_active_symbol() + if signal is not None and state.position is None: + signal["valid_until"] = (bucket + 2 * tf_ms) / 1000 + signal["mode"] = mode + state.mode_signal = signal + side = "SHORT" if signal["side"] == "short" else "LONG" + self.status_var.set( + f"Сигнал {side} {symbol} · закрытие {self._fmt_price(signal['close'])} · " + f"ATR {self._fmt_price(signal['atr'])} · вход на следующей сделке" + ) + self._request_redraw(symbol) + else: + state.mode_signal = None + elif event[0] == "ticker_24h_error": + self.auto_currency_status_var.set(f"Ошибка котировок: {event[1][:150]}") + elif event[0] == "chart_candles": + _, symbol, interval, candles, baseline = event + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + if interval == self.interval_minutes: + merged = {int(row[0]): row for row in candles} + merged.update({int(row[0]): row for row in state.candles}) + state.candles = deque([merged[key] for key in sorted(merged)[-300:]]) + state.baseline_close = baseline + if symbol == self.symbol: + self._activate_symbol_state(symbol) + self._draw_chart() + self._draw_detail_chart(symbol) + elif event[0] == "live_ready": + self._activate_live(*event[1:]) + elif event[0] == "live_ready_multi": + self._activate_live_multi(*event[1:]) + elif event[0] == "live_symbol_ready": + _, symbol, settings, spec, fee_pct, row, shadow = event + self.live_preparing_symbols.discard(symbol) + self._activate_live_symbol(symbol, settings, spec, fee_pct, row, shadow) + elif event[0] == "live_symbol_failed": + _, symbol, error = event + self.live_preparing_symbols.discard(symbol) + was_auto_added = symbol in self.auto_enabling_symbols + self.auto_enabling_symbols.discard(symbol) + if was_auto_added: + self.auto_symbol_retry_after[symbol] = time.monotonic() + AUTO_CURRENCY_SCAN_SECONDS + self.enabled_symbols.discard(symbol) + self._save_settings() + self._render_currency_tiles() + self.status_var.set(f"Не удалось включить {symbol}: {error}") + if not was_auto_added: + messagebox.showerror("Не удалось включить валюту", f"{symbol}: {error}") + elif event[0] == "live_preflight_failed": + self.live_preflight = False + self.mode_combo.configure(state="readonly") + self.start_btn.configure(state="normal") + self.status_var.set(f"Реальный режим не запущен: {event[1]}") + messagebox.showerror("Проверка Bybit не пройдена", event[1]) + elif event[0] == "live_restored_closed": + self._record_live_close(event[2], event[1], None, "Закрыта на Bybit во время перерыва") + elif event[0] == "live_order_result": + if len(event) == 6: + _kind, symbol, action, position, row, wallet = event + else: + _kind, action, position, row, wallet = event + symbol = position.symbol + selected = self.symbol + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_position = position + state.live_position_info = row + state.live_order_busy = False + state.entry_markers.append((time.time(), position.last_add_price, position.trade_id)) + if wallet: + self.live_wallet = wallet + self._replace_cached_position(row) + self._activate_symbol_state(selected) + self._save_account_state() + self.status_var.set(("Открыта реальная позиция" if action == "open" else "Доливка реальной позиции") + + f" #{position.trade_id} · {position.qty:.8g} {position.symbol}") + self._refresh_ui() + self._draw_chart() + elif event[0] == "live_order_no_fill": + _kind, symbol, action, order_status = event + self._capture_active_symbol() + self._ensure_symbol(symbol).live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set( + f"Bybit не исполнил ордер ({order_status or 'без исполнения'}); бот продолжает работу" + ) + self._refresh_ui() + elif event[0] == "live_order_pending": + _kind, symbol, order_id = event + self.status_var.set( + f"Жду подтверждения ордера Bybit {symbol} {order_id or ''}; повторный ордер заблокирован до сверки" + ) + elif event[0] == "live_sync": + if len(event) == 5: + _kind, symbol, position, row, wallet = event + else: + _kind, position, row, wallet = event + symbol = position.symbol if position else str((row or {}).get("symbol") or self.symbol) + selected = self.symbol + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_position = position + state.live_position_info = row + self._replace_cached_position(row, position.symbol if position else None) + if wallet: + self.live_wallet = wallet + self._activate_symbol_state(selected) + self._save_account_state() + self._refresh_ui() + self._draw_chart() + elif event[0] == "live_closed": + _kind, position, row, wallet, reason = event + self._record_live_close(position, row, wallet, reason) + elif event[0] == "live_worker_failed": + symbol, error = event[1], event[2] + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_halted = True + state.live_transition_pending = False + state.live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set(f"Реальная торговля {symbol} приостановлена: {error}") + messagebox.showerror("Реальная торговля приостановлена", f"{symbol}: {error}\nПроверьте позицию и TP/SL на Bybit.") + self._refresh_ui() + elif event[0] == "live_stops_updated": + self._capture_active_symbol() + self._ensure_symbol(event[1]).live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set(f"Биржевые TP/SL обновлены · {event[1]}") + self._refresh_ui() + elif event[0] == "live_settings_updated": + self._capture_active_symbol() + self._ensure_symbol(event[1]).live_order_busy = False + self._activate_symbol_state(self.symbol) + self.status_var.set("Настройки реальной стратегии применены") + self._refresh_ui() + elif event[0] == "live_order_skipped": + _kind, symbol, action, reason, price = event + self._capture_active_symbol() + state = self._ensure_symbol(symbol) + state.live_order_busy = False + if action == "add" and state.live_position is not None: + state.live_position.last_add_price = min(state.live_position.last_add_price, price) + self._activate_symbol_state(self.symbol) + labels = {"open": "Вход", "add": "Доливка", "close": "Закрытие"} + self.status_var.set(f"{labels.get(action, action)} {symbol} пропущен(а): {reason}") + self._request_redraw(symbol, main=True) + elif event[0] == "live_worker_exited": + _kind, symbol, command_queue = event + if self.live_commands_by_symbol.get(symbol) is command_queue: + self.live_commands_by_symbol.pop(symbol, None) + self.live_workers.pop(symbol, None) + if self.running and symbol in self.enabled_symbols: + state = self._ensure_symbol(symbol) + if not state.live_halted and self.mode_var.get() == "Реальная торговля" \ + and symbol not in self.live_preparing_symbols: + # The worker ended although the pair is enabled (e.g. it was + # re-enabled right as the old worker retired): start a new one. + self._begin_live_additional_symbol(symbol) + # Drain bursts without starving Tk: continue immediately if events remain. + self.root.after(1 if handled >= MAX_EVENTS_PER_POLL else 100, self._poll_events) + + # ----- strategy modes A/B in the simulation ------------------------------------------ + + def _poll_mode_signals(self) -> None: + """Evaluate mode A/B signals once per closed signal candle for every enabled pair.""" + try: + if (self.running and self.mode_var.get() == "Симуляция" + and self.strategy_mode != strategy.STRATEGY_CLASSIC): + params = self._strategy_mode_params() + tf_ms = int(params["timeframe_min"]) * 60_000 + now_ms = int(time.time() * 1000) + last_closed = (now_ms // tf_ms) * tf_ms - tf_ms + # Give Bybit a few seconds to publish the closed candle. + if now_ms - (last_closed + tf_ms) >= 3000: + self._capture_active_symbol() + for symbol in sorted(self.enabled_symbols): + if symbol in self.rotation_pending_disable: + continue + state = self._ensure_symbol(symbol) + if state.mode_eval_busy or state.mode_signal_bucket == last_closed: + continue + if state.position is not None: + state.mode_signal = None + state.mode_signal_bucket = last_closed + continue + state.mode_eval_busy = True + self._signal_pool.submit(self._mode_signal_worker, symbol, self.strategy_mode, + dict(params), last_closed) + except ValueError as exc: + self.status_var.set(f"Настройки режима стратегии: {exc}") + finally: + if self.root.winfo_exists(): + self.root.after(5000, self._poll_mode_signals) + + @staticmethod + def _fetch_recent_klines(symbol: str, interval: int, limit: int) -> list[list[float]]: + """Closed candles [start_ms, o, h, l, c, turnover], oldest first.""" + query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, "interval": str(interval), + "limit": str(max(2, min(1000, limit)))}) + request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + with urllib.request.urlopen(request, timeout=10) as response: + payload = json.loads(response.read().decode("utf-8")) + if payload.get("retCode") != 0: + raise RuntimeError(f"Bybit {payload.get('retCode')}: {payload.get('retMsg', 'ошибка свечей')}") + now_ms = int(time.time() * 1000) + interval_ms = interval * 60_000 + rows = [[int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]), + float(row[6]) if len(row) > 6 and row[6] not in (None, "") else 0.0] + for row in payload.get("result", {}).get("list", []) + if int(row[0]) + interval_ms <= now_ms] + rows.sort(key=lambda row: row[0]) + return rows + + def _btc_regime(self, ema_period: int) -> bool | None: + """BTC closed-hour close above its EMA, refreshed once per hour.""" + hour = int(time.time() // 3600) + with self._btc_regime_lock: + cached_hour, cached_period, value = self._btc_regime_cache + if cached_hour == hour and cached_period == ema_period and value is not None: + return value + rows = self._fetch_recent_klines("BTCUSDT", 60, ema_period * 3 + 5) + value = strategy.btc_regime_ok([row[4] for row in rows], ema_period) + self._btc_regime_cache = (hour, ema_period, value) + return value + + def _mode_signal_worker(self, symbol: str, mode: str, params: dict[str, float], bucket: int) -> None: + tf = int(params["timeframe_min"]) + try: + rows = self._fetch_recent_klines(symbol, tf, strategy.required_bars(mode, params) + 5) + rows = [row for row in rows if row[0] <= bucket] + if not rows or rows[-1][0] != bucket: + raise RuntimeError("Bybit ещё не опубликовал закрытую свечу") + btc_ok: bool | None = True + if mode == strategy.STRATEGY_BREAKOUT and params["btc_filter"] >= 1: + btc_ok = self._btc_regime(int(params["btc_ema"])) + signal = strategy.evaluate_signal(mode, rows, params, self.ticker_funding_pct.get(symbol), btc_ok) + self.events.put(("mode_signal", symbol, mode, bucket, tf * 60_000, signal, None)) + except Exception as exc: + self.events.put(("mode_signal", symbol, mode, bucket, tf * 60_000, None, str(exc)[:160])) + + def _maybe_enter_mode_position(self, price: float, timestamp: float) -> None: + state = self.symbol_states.get(self.symbol) + signal = state.mode_signal if state else None + if not signal: + return + if timestamp > signal["valid_until"] or signal.get("mode") != self.strategy_mode: + state.mode_signal = None + return + if self.symbol not in self.enabled_symbols or self.symbol in self.rotation_pending_disable: + return + try: + params = self._strategy_mode_params(signal["mode"]) + position_limit = self._simulation_position_limit() + except ValueError as exc: + self.status_var.set(str(exc)) + return + active_positions = sum(item.position is not None for item in self.symbol_states.values()) + stake = self.initial_balance * params["stake_pct"] / 100 + if active_positions >= position_limit or stake > max(0.0, self._sim_free_margin()): + if not signal.get("skip_noted"): + signal["skip_noted"] = True + self.status_var.set( + f"Сигнал {self.symbol} ждёт: " + ("лимит одновременных сделок занят" + if active_positions >= position_limit + else "свободного баланса меньше ставки") + ) + return + plan = strategy.entry_plan(signal, price, params) + state.mode_signal = None + if plan is None: + self.status_var.set(f"Сигнал {self.symbol} отменён: цена ушла за уровень сигнала или стоп слишком далеко") + return + notional = stake * params["leverage"] + qty = notional / price + entry_fee = notional * TAKER_FEE_PCT / 100 + self.balance -= entry_fee + self.total_fees += entry_fee + self.position = Position( + self.next_id, self.symbol, price, qty, stake, entry_fee, timestamp, price, + side=plan["side"], mode=signal["mode"], leverage=params["leverage"], + stop_price=plan["stop"], initial_stop=plan["stop"], atr=plan["atr"], extreme=price, + partial_target=plan["partial_target"] or 0.0, final_target=plan["final_target"] or 0.0, + opened_stake=stake, + ) + state.position = self.position + self.entry_markers.append((timestamp, price, self.position.trade_id)) + self.next_id += 1 + self._save_account_state() + self.status_var.set( + f"Открыта {plan['side'].upper()} #{self.position.trade_id} · {self.symbol} · {price:g} · " + f"стоп {self._fmt_price(plan['stop'])}" + ) + + def _partial_close_position(self, price: float, params: dict[str, float]) -> None: + pos = self.position + if pos is None: + return + fraction = min(1.0, params["partial_pct"] / 100) + qty = pos.qty * fraction + gross = strategy.unrealized_pnl(pos.side, pos.entry_price, price, qty) + exit_fee = price * qty * TAKER_FEE_PCT / 100 + self.balance += gross - exit_fee + self.total_fees += exit_fee + pos.realized_gross += gross + pos.realized_fees += exit_fee + pos.qty -= qty + pos.stake *= 1 - fraction + pos.partial_done = True + if params["breakeven"] >= 1: + pos.stop_price = strategy.tighten_stop(pos.side, pos.stop_price, + strategy.breakeven_price(pos.side, pos.entry_price, TAKER_FEE_PCT)) + self._save_account_state() + self.status_var.set( + f"Частичная фиксация {params['partial_pct']:g}% #{pos.trade_id} · {pos.symbol} · {price:g} · " + f"gross {gross:+.4f} · стоп {self._fmt_price(pos.stop_price)}" + ) + + def _manage_mode_position(self, price: float, timestamp: float) -> None: + pos = self.position + if pos is None: + return + try: + params = self._strategy_mode_params(pos.mode) + except ValueError: + params = strategy.parse_mode_params(pos.mode, {}) + side = pos.side + liquidation = strategy.liquidation_price(pos.entry_price, pos.leverage, side=side) + if liquidation is not None and strategy.stop_hit(side, price, liquidation): + self._close_position(price, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True) + return + if strategy.stop_hit(side, price, pos.stop_price): + moved = abs(pos.stop_price - pos.initial_stop) > 1e-12 + self._close_position(price, "Стоп (трейлинг/безубыток)" if moved else "Стоп") + return + if params["max_hold_hours"] > 0 and timestamp - pos.opened_at >= params["max_hold_hours"] * 3600: + self._close_position(price, f"Время удержания {params['max_hold_hours']:g} ч") + return + if (not pos.partial_done and pos.partial_target > 0 + and strategy.target_hit(side, price, pos.partial_target)): + if params["partial_pct"] >= 100: + self._close_position(pos.partial_target, f"TP на {params['partial_r']:g}R") + return + self._partial_close_position(pos.partial_target, params) + if pos.final_target > 0 and strategy.target_hit(side, price, pos.final_target): + self._close_position(pos.final_target, f"TP на {params['take_profit_r']:g}R") + return + pos.extreme = max(pos.extreme, price) if side == "long" else min(pos.extreme, price) + if strategy.trailing_active(pos.partial_done, params): + pos.stop_price = strategy.trailing_stop(side, pos.stop_price, pos.extreme, pos.atr, params["trail_atr"]) + + def _on_trade(self, symbol: str, timestamp: float, price: float) -> None: + display_symbol = self.symbol + balance_before = self.balance + self._display_symbol_during_tick = display_symbol + self._capture_active_symbol() + self._activate_symbol_state(symbol) + try: + self._process_active_trade(timestamp, price) + finally: + self._capture_active_symbol() + self._activate_symbol_state(display_symbol) + self._display_symbol_during_tick = None + self._request_redraw(symbol, main=symbol == display_symbol or self.balance != balance_before) + + def _request_redraw(self, symbol: str | None = None, main: bool = False) -> None: + """Coalesce UI updates: at most one redraw every UI_REDRAW_INTERVAL_MS. + + Redrawing the whole chart on every public trade starves the Tk thread when many + pairs are subscribed, so prices would be processed late. + """ + if symbol: + self._dirty_symbols.add(symbol) + self._dirty_main = self._dirty_main or main + if self._redraw_job is None and self.root.winfo_exists(): + self._redraw_job = self.root.after(UI_REDRAW_INTERVAL_MS, self._flush_redraw) + + def _flush_redraw(self) -> None: + self._redraw_job = None + symbols, self._dirty_symbols = self._dirty_symbols, set() + main, self._dirty_main = self._dirty_main, False + if symbols: + self._refresh_currency_tiles(symbols) + if main or self.symbol in symbols: + self._refresh_price_label() + self._refresh_ui() + self._draw_chart() + for symbol in symbols: + if symbol in self.detail_windows: + self._draw_detail_chart(symbol) + + def _process_active_trade(self, timestamp: float, price: float) -> None: + self.last_ws_message = time.time() + self.last_price = price + self._live_minute_prices.append((timestamp, price)) + while self._live_minute_prices and self._live_minute_prices[0][0] < timestamp - 2 * WINDOW_MS / 1000: + self._live_minute_prices.popleft() + self.prices.append((timestamp, price)) + cutoff = timestamp - WINDOW_MS / 1000 + while self.prices and self.prices[0][0] < cutoff - 2: + self.prices.popleft() + candle_start = int(timestamp // (self.interval_minutes * 60)) * (self.interval_minutes * 60) + new_candle = not self.candles or self.candles[-1][0] != candle_start + if new_candle: + self._previous_entry_signal_pct = None + self._update_candle(timestamp, price) + keep_seconds = max(CHART_SECONDS, self.interval_minutes * 60 * 30) + while self.candles and self.candles[0][0] < timestamp - keep_seconds: + expired = self.candles.popleft() + while self.entry_markers and self.entry_markers[0][0] < expired[0]: + self.entry_markers.popleft() + + settings = self.strategy_by_symbol.get(self.symbol) or self.applied_settings or self._safe_read_settings() + + signal_pct =((price / self.baseline_close) - 1) * 100 if self.baseline_close and self.baseline_close > 0 else None + crossed_entry_threshold = ( + signal_pct is not None + and signal_pct >= settings["trigger"] + and (self._previous_entry_signal_pct is None or self._previous_entry_signal_pct < settings["trigger"]) + ) + if self.mode_var.get() == "Реальная торговля": + self._on_live_tick(timestamp, price, crossed_entry_threshold) + self._previous_entry_signal_pct = signal_pct + return + self._previous_entry_signal_pct = signal_pct + if self.position and self.position.mode != strategy.STRATEGY_CLASSIC: + self._manage_mode_position(price, timestamp) + return + if self.position is None and self.strategy_mode != strategy.STRATEGY_CLASSIC: + self._maybe_enter_mode_position(price, timestamp) + return + if self.position: + stop_price = strategy.stop_loss_price(self.position.entry_price, settings["stop_loss"]) + effective_tp_pct = strategy.effective_take_profit_pct(settings["take_profit"], settings["fee"]) + take_profit_price = strategy.take_profit_price(self.position.entry_price, settings["take_profit"], settings["fee"]) + liquidation_price = strategy.liquidation_price(self.position.entry_price, settings["leverage"]) + add_price = strategy.add_level(self.position.last_add_price, settings["add_step"]) + if liquidation_price is not None and price <= liquidation_price: + self._close_position(price, f"Ликвидация (плечо {settings['leverage']:g}x)", liquidation=True) + elif stop_price is not None and price <= stop_price: + stop_pct = (self.position.entry_price - price) / self.position.entry_price * 100 + self._close_position(price, f"Стоп от средней цены {stop_pct:.2f}%") + elif take_profit_price is not None and price >= take_profit_price: + # Exchange TP is a trigger at the level; do not credit the overshoot of a jump. + self._close_position(take_profit_price, f"TP от средней цены +{effective_tp_pct:.3f}%") + elif (self.symbol in self.enabled_symbols and self.symbol not in self.rotation_pending_disable + and strategy.can_add(self.position.add_count, settings["max_adds"], settings["add_step"]) + and add_price is not None and price <= add_price): + self._add_position(price, timestamp, settings) + elif (crossed_entry_threshold and self.symbol in self.enabled_symbols + and self.symbol not in self.rotation_pending_disable): + self._open_position(price, timestamp, settings) + + def _refresh_rolling_change(self, reschedule: bool = True, now: float | None = None) -> None: + if now is None: + now = time.time() + self._last_signal_refresh_at = now + current = self.last_price + self.last_signal_pct = ((current / self.baseline_close) - 1) * 100 if current and self.baseline_close and self.baseline_close > 0 else None + self.last_signal_ready = self.last_signal_pct is not None + if hasattr(self, "market_price_var"): + self._refresh_price_label() + if hasattr(self, "root") and self.root.winfo_exists(): + self._refresh_ui() + if reschedule: + self.root.after(5000, self._refresh_rolling_change) + + def _refresh_price_label(self) -> None: + current = self.last_price + if not current: + self.market_price_var.set(f"{self.symbol}: ожидаю цену Bybit…") + elif self.last_signal_ready and self.last_signal_pct is not None: + self.market_price_var.set( + f"{self.symbol}: {self._fmt_price(current)} USDT " + f"Изменение от закрытия прошлой {self.interval_minutes}-мин свечи: {self.last_signal_pct:+.2f}%" + ) + else: + self.market_price_var.set( + f"{self.symbol}: {self._fmt_price(current)} USDT " + f"Изменение от закрытия прошлой {self.interval_minutes}-мин свечи: ждём базу…" + ) + + def _sim_free_margin(self) -> float: + """Money available for new simulated entries/adds. + + Like Bybit's available balance: cash minus margin locked in open positions, plus + their current unrealized P&L after the estimated closing fee. Losing positions + therefore reduce what can still be invested; the same figure is shown on screen. + """ + self._capture_active_symbol() + free = self.balance + for state in self.symbol_states.values(): + pos = state.position + if pos is None: + continue + settings = self.strategy_by_symbol.get(pos.symbol) or self.applied_settings or {} + fee_pct = settings.get("fee", TAKER_FEE_PCT) if pos.mode == strategy.STRATEGY_CLASSIC else TAKER_FEE_PCT + mark = state.last_price or pos.entry_price + free += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) + - mark * pos.qty * fee_pct / 100 - pos.stake) + return free + + def _open_position(self, price: float, timestamp: float, settings: dict[str, float]) -> None: + try: + position_limit = self._simulation_position_limit() + except ValueError as exc: + self.status_var.set(str(exc)) + return + active_positions = sum(state.position is not None for state in self.symbol_states.values()) + if active_positions >= position_limit: + self.status_var.set( + f"Вход пропущен: лимит одновременных сделок {position_limit} уже занят" + ) + return + if settings["stake"] > max(0.0, self._sim_free_margin()): + self.status_var.set("Вход пропущен: свободного баланса меньше ставки") + return + notional = settings["stake"] * settings["leverage"] + qty = notional / price + entry_fee = notional * settings["fee"] / 100 + self.balance -= entry_fee + self.total_fees += entry_fee + self.position = Position(self.next_id, self.symbol, price, qty, settings["stake"], entry_fee, timestamp, price) + self.entry_markers.append((timestamp, price, self.position.trade_id)) + self.next_id += 1 + self._save_account_state() + self.status_var.set(f"Открыта LONG #{self.position.trade_id} · {self.symbol} · {price:g}") + + def _add_position(self, price: float, timestamp: float, settings: dict[str, float]) -> None: + pos = self.position + if pos is None: + return + free_margin = self._sim_free_margin() + if free_margin < settings["stake"]: + # Same rule as live and backtest: the level is consumed, the next add is measured from here. + pos.last_add_price = price + self.status_var.set("Доливка пропущена: недостаточно свободного капитала") + return + notional = settings["stake"] * settings["leverage"] + added_qty = notional / price + added_fee = notional * settings["fee"] / 100 + total_qty = pos.qty + added_qty + pos.entry_price = (pos.entry_price * pos.qty + price * added_qty) / total_qty + pos.qty = total_qty + pos.stake += settings["stake"] + pos.entry_fee += added_fee + pos.last_add_price = price + pos.add_count += 1 + self.balance -= added_fee + self.total_fees += added_fee + self.entry_markers.append((timestamp, price, pos.trade_id)) + self._save_account_state() + self.status_var.set(f"Доливка #{pos.add_count} в сделку #{pos.trade_id} · {price:g} · средняя {pos.entry_price:g}") + + def _mark_position(self, price: float, settings: dict[str, float]) -> tuple[float, float, float]: + assert self.position is not None + p = self.position + gross = strategy.unrealized_pnl(p.side, p.entry_price, price, p.qty) + exit_fee = price * p.qty * settings["fee"] / 100 + fees = p.entry_fee + exit_fee + return gross - fees, fees, gross + + def _close_position(self, price: float, reason: str, liquidation: bool = False) -> None: + if not self.position: + return + pos = self.position + if pos.mode != strategy.STRATEGY_CLASSIC: + settings = {"fee": TAKER_FEE_PCT} # modes A/B never read the classic currency settings + else: + settings = (self.strategy_by_symbol.get(pos.symbol) or self.applied_settings + or self._safe_read_settings()) + if liquidation: + # Isolated-margin liquidation forfeits the position margin (as in the backtest). + gross, exit_fee = -pos.stake, 0.0 + else: + _net, fees, gross = self._mark_position(price, settings) + exit_fee = max(0, fees - pos.entry_fee) + self.balance += gross - exit_fee + self.total_fees += exit_fee + # A partial take-profit (modes A/B) was already credited; report the whole trade. + gross += pos.realized_gross + fees = pos.entry_fee + pos.realized_fees + exit_fee + net = gross - fees + roi = net / (pos.opened_stake or pos.stake) * 100 + if pos.mode != strategy.STRATEGY_CLASSIC: + reason = f"{pos.side.upper()} · {reason}" + closed = ClosedTrade(pos.trade_id, pos.symbol, pos.entry_price, price, pos.qty, gross, fees, net, roi, pos.opened_at, time.time(), reason) + self.trades.append(closed) + self.table.insert("", 0, values=(closed.trade_id, closed.symbol, self._fmt_price(closed.entry_price), self._fmt_price(closed.exit_price), f"{closed.roi_pct:+.2f}", f"{closed.gross_pnl:+.4f}", f"{closed.fees:.4f}", f"{closed.net_pnl:+.4f}", closed.reason), tags=("profit" if closed.net_pnl > 0 else "loss" if closed.net_pnl < 0 else "",)) + self.position = None + state = self._ensure_symbol(pos.symbol) + state.position = None + self._save_account_state() + self.status_var.set(f"Закрыта сделка #{closed.trade_id}: {closed.reason} · net {closed.net_pnl:+.4f} USDT") + self._finish_auto_retirement(pos.symbol) + + def _manual_close_position(self) -> None: + if self.mode_var.get() == "Реальная торговля": + if not self.live_position: + self.status_var.set("Нет открытой реальной позиции") + return + if not self.running or self.live_order_busy or self.live_halted: + self.status_var.set("Для ручного закрытия запустите реальный бот; дождитесь завершения текущего ордера") + return + if not messagebox.askyesno("Закрыть позицию Bybit", f"Отправить рыночный ордер на закрытие LONG {self.live_position.symbol}?"): + return + self.live_order_busy = True + commands = self.live_commands_by_symbol.get(self.live_position.symbol, self.live_commands) + commands.put(("close", time.time(), self.last_price or self.live_position.entry_price)) + self.status_var.set("Отправляю reduce-only ордер на закрытие…") + self._refresh_ui() + return + if not self.position: + self.status_var.set("Нет открытой сделки для закрытия") + return + if not self.running or not self.last_price or self.last_price <= 0: + self.status_var.set("Для ручного закрытия запустите поток цен Bybit") + return + self._close_position(self.last_price, "Закрыта вручную") + self._refresh_ui() + self._draw_chart() + + def _record_live_close(self, position: Position, row: dict | None, + wallet: dict[str, float] | None, reason: str) -> None: + if row: + state = self._ensure_symbol(position.symbol) + exit_price = float(row.get("avgExitPrice") or row.get("avgEntryPrice") or state.last_price or position.entry_price) + entry_price = float(row.get("avgEntryPrice") or position.entry_price) + qty = float(row.get("closedSize") or row.get("qty") or position.qty) + # Bybit's closedPnl is the authoritative net result. Gross is derived from the + # fill prices so it never depends on how funding is reported in the record; + # any difference between gross − fees and net is funding/other charges. + net = float(row.get("closedPnl") or 0.0) + fees = float(row.get("openFee") or 0.0) + float(row.get("closeFee") or 0.0) + gross = (exit_price - entry_price) * qty + close_time = float(row.get("updatedTime") or int(time.time() * 1000)) / 1000 + else: + exit_price = self._ensure_symbol(position.symbol).last_price or position.entry_price + qty = position.qty + fees = position.entry_fee + exit_price * qty * self.live_fee_pct / 100 + gross = (exit_price - position.entry_price) * qty + net = gross - fees + close_time = time.time() + reason += " · PnL не подтверждён API" + roi = net / position.stake * 100 if position.stake else 0.0 + closed = ClosedTrade(position.trade_id, position.symbol, position.entry_price, exit_price, + qty, gross, fees, net, roi, position.opened_at, close_time, reason) + # Replayed close events can occur when an app closes while Bybit already closed the position. + if not any(existing.trade_id == closed.trade_id for existing in self.live_trades): + self.live_trades.append(closed) + tag = "profit" if net > 0 else "loss" if net < 0 else "" + self.table.insert("", 0, values=(f"R{closed.trade_id}", closed.symbol, + self._fmt_price(closed.entry_price), self._fmt_price(closed.exit_price), + f"{closed.roi_pct:+.2f}", f"{closed.gross_pnl:+.4f}", f"{closed.fees:.4f}", + f"{closed.net_pnl:+.4f}", f"LIVE · {closed.reason}"), tags=(tag,)) + state = self._ensure_symbol(position.symbol) + if state.live_position and state.live_position.trade_id == position.trade_id: + state.live_position = None + state.live_position_info = None + state.live_order_busy = False + state.live_transition_pending = False + if self.live_position and self.live_position.trade_id == position.trade_id: + self.live_position = None + self._replace_cached_position(None, position.symbol) + self._finish_auto_retirement(position.symbol) + if self.symbol == position.symbol: + self.live_order_busy = False + self.live_transition_pending = False + if wallet: + self.live_wallet = wallet + self._save_account_state() + self.status_var.set(f"Реальная сделка #{closed.trade_id} закрыта · net {closed.net_pnl:+.4f} USDT · {reason}") + self._refresh_ui() + self._draw_chart() + + @staticmethod + def _fmt_price(price: float) -> str: + return f"{price:.10g}" + + @staticmethod + def _fee_cover_pct(fee_pct: float) -> float: + """Minimum gross price rise that offsets taker fees on entry and exit fills.""" + return strategy.fee_cover_pct(fee_pct) + + def _safe_read_settings(self) -> dict[str, float]: + try: + return self._read_settings() + except ValueError: + return {"initial": self.initial_balance, "stake_pct": 2, "deposit_basis": self.initial_balance, + "stake": 0, "leverage": 1, "trigger": 5, "add_step": .5, "max_adds": 2, + "stop_loss": 1, "take_profit": 1, "fee": TAKER_FEE_PCT, + "interval": float(CANDLE_INTERVAL_MINUTES)} + + def _refresh_settings_summary(self) -> None: + """Show the active strategy thresholds in the main window.""" + settings = self.applied_settings or self._safe_read_settings() + stop_loss = "выключен" if settings["stop_loss"] == 0 else f"−{settings['stop_loss']:g}%" + take_profit = ( + "выключен" + if settings["take_profit"] == 0 + else f"+{settings['take_profit']:g}% (уровень с учётом комиссий не ниже {self._fee_cover_pct(settings['fee']):.3f}%)" + ) + add_text = (f"доливка через −{settings['add_step']:g}% от последнего входа, максимум {settings['max_adds']}" + if settings["add_step"] > 0 and settings["max_adds"] > 0 else "доливки выключены") + self.strategy_summary_var.set( + f"Параметры: 1-мин свеча · первый вход при росте +{settings['trigger']:g}% от предыдущего закрытия · " + f"{add_text} · ставка {settings.get('stake_pct', 0):g}% от стартового депозита " + f"({settings.get('deposit_basis', settings['initial']):g} USDT = {settings['stake']:g} USDT на вход) × плечо {settings['leverage']:g} · " + f"TP {take_profit} / стоп {stop_loss} от средней цены · " + f"комиссия taker {settings['fee']:g}% за сторону" + ) + + def _refresh_ui(self) -> None: + current = self.last_price or 0.0 + self._refresh_price_label() + settings = self.applied_settings or self._safe_read_settings() + if self.mode_var.get() == HISTORICAL_MODE: + self.main_metrics_frame.pack_forget() + elif not self.main_metrics_frame.winfo_manager(): + self.main_metrics_frame.pack(fill="x", pady=(6, 0), before=self.currencies_frame) + if self.mode_var.get() == "Реальная торговля": + wallet = self.live_wallet or {"wallet": 0.0, "equity": 0.0, "available": 0.0, "unrealized_pnl": 0.0} + if self.live_client: + network = "Testnet" if self.live_client.testnet else "MAINNET" + baseline = self._current_live_deposit_basis() or wallet["wallet"] + realized = sum(float(row.get("closedPnl") or 0) for row in self.live_closed_pnl) + self.live_account_var.set( + f"{network} · стартовый депозит {baseline:,.2f} · кошелёк {wallet['wallet']:,.2f} · " + f"equity {wallet['equity']:,.2f} · нереализованный P&L {wallet.get('unrealized_pnl', 0):+,.2f} · " + f"реализованный P&L (последние {len(self.live_closed_pnl)}) {realized:+,.2f} USDT · " + f"ордеров {len(self.live_orders)} · позиций {len(self.live_positions)}" + ) + position = self.live_position + unrealized = float((self.live_position_info or {}).get("unrealisedPnl") or 0.0) + if position: + mark_price = current or float((self.live_position_info or {}).get("markPrice") or position.entry_price) + unrealized = float((self.live_position_info or {}).get("unrealisedPnl") or ((mark_price - position.entry_price) * position.qty)) + margin = position.stake + pnl_pct = unrealized / margin * 100 if margin else 0.0 + self.position_var.set( + f"LIVE LONG #{position.trade_id} · {position.symbol} · средняя {self._fmt_price(position.entry_price)} · " + f"входов {position.add_count + 1} · текущая {self._fmt_price(mark_price)} · размер {position.qty:.8g} · " + f"unrealized PnL {unrealized:+.4f} USDT ({pnl_pct:+.2f}%)" + ) + else: + selected = next((row for row in self.live_positions if row.get("symbol") == self.symbol_var.get().strip().upper()), None) + if selected: + self.position_var.set( + f"Bybit · {selected.get('symbol')} {selected.get('side')} · объём {selected.get('size')} · " + f"средняя {selected.get('avgPrice')} · P&L {float(selected.get('unrealisedPnl') or 0):+.4f} USDT · " + f"TP {selected.get('takeProfit') or '—'} · SL {selected.get('stopLoss') or '—'} · " + "нажмите «Старт» для сопровождения ботом" + ) + elif self.live_positions: + self.position_var.set(f"На аккаунте открыто позиций: {len(self.live_positions)} · подробности во вкладке «Открытые позиции»") + else: + self.position_var.set("LIVE · открытых позиций нет; ждём сигнал") + self.close_trade_btn.configure(state="normal" if self.running and position and not self.live_order_busy else "disabled") + for key, title in (("balance", "Bybit кошелёк"), ("equity", "Equity"), + ("pnl", "Нереализованный PnL"), ("free", "Доступно"), + ("fees", "Комиссии сделки · оценка")): + self.metric_title_vars[key].set(title) + self.metric_boxes[key].configure(text=title) + values = { + "balance": f"{wallet['wallet']:,.2f} USDT", + "equity": f"{wallet['equity']:,.2f} USDT", + "free": f"{wallet['available']:,.2f} USDT", + "pnl": f"{float(wallet.get('unrealized_pnl', unrealized)):+,.2f} USDT", + "fees": (f"{position.entry_fee + position.entry_price * position.qty * self.live_fee_pct / 100:,.4f} USDT" + if position else "см. историю Bybit"), + } + for key, value in values.items(): + self.metric_vars[key].set(value) + live_open = sum(1 for state in self.symbol_states.values() if state.live_position is not None) + self._set_main_metrics( + wallet["wallet"], float(wallet.get("unrealized_pnl", unrealized)), wallet["equity"], + "Баланс Bybit", "Нереализованный P&L", "Общий баланс с P&L", + free=float(wallet.get("available") or 0.0), open_positions=live_open, + free_title="Свободно на Bybit для новых сделок", + ) + return + for key, title in (("balance", "Баланс"), ("equity", "Бюджет всего"), ("pnl", "Без стартового"), + ("free", "Свободно"), ("fees", "Комиссии")): + self.metric_title_vars[key].set(title) + self.metric_boxes[key].configure(text=title) + open_positions = [(symbol, state.position, state.last_price or state.position.entry_price) + for symbol, state in self.symbol_states.items() if state.position] + unrealized_gross = 0.0 + estimated_exit_fees = 0.0 + used_margin = 0.0 + position_lines = [] + for symbol, pos, mark in open_positions: + assert pos is not None + gross = strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty) + exit_fee = mark * pos.qty * settings["fee"] / 100 + unrealized_gross += gross + estimated_exit_fees += exit_fee + used_margin += pos.stake + net = gross - exit_fee - pos.entry_fee + pos.realized_gross - pos.realized_fees + side = f"{pos.side.upper()} " if pos.mode != strategy.STRATEGY_CLASSIC else "" + position_lines.append( + f"{symbol}: {side}#{pos.trade_id} · {self._fmt_price(pos.entry_price)} → {self._fmt_price(mark)} · " + + (f"стоп {self._fmt_price(pos.stop_price)}" if pos.mode != strategy.STRATEGY_CLASSIC + else f"{pos.add_count + 1} вход(ов)") + + f" · net {net:+.3f} USDT" + ) + equity = self.balance + unrealized_gross - estimated_exit_fees + free = max(0.0, self._sim_free_margin()) + pnl = equity - self.initial_balance + if position_lines: + self.position_var.set("Открытые позиции · " + " | ".join(position_lines)) + selected_position = self.position is not None and self.last_price is not None + self.close_trade_btn.configure(state="normal" if self.running and selected_position else "disabled") + else: + self.position_var.set("Нет открытых сделок") + self.close_trade_btn.configure(state="disabled") + values = { + "balance": f"{self.balance:,.2f} USDT", + "equity": f"{equity:,.2f} USDT", + "free": f"{free:,.2f} USDT", + "pnl": f"{pnl:+,.2f} USDT", + "fees": f"{self.total_fees:,.4f} USDT", + } + for key, value in values.items(): + self.metric_vars[key].set(value) + self._set_main_metrics( + self.balance, pnl, equity, "Баланс симуляции", "P&L с запуска", "Общий баланс с P&L", + free=free, open_positions=len(open_positions), + free_title="Свободно для новых сделок", + ) + + def _set_main_metrics(self, balance: float, pnl: float, equity: float, + balance_title: str, pnl_title: str, equity_title: str, *, + free: float | None = None, open_positions: int = 0, + free_title: str = "Свободно для новых сделок") -> None: + titles = {"balance": balance_title, "pnl": pnl_title, "equity": equity_title, "free": free_title} + values = { + "balance": f"{balance:,.2f} USDT", + "pnl": f"{pnl:+,.2f} USDT", + "equity": f"{equity:,.2f} USDT", + "free": "—" if free is None else f"{free:,.2f} USDT" + self._entries_left_text(free, open_positions), + } + for key in ("balance", "pnl", "equity", "free"): + self.main_metric_titles[key].configure(text=titles[key]) + self.main_metric_vars[key].set(values[key]) + + def _entries_left_text(self, free: float, open_positions: int) -> str: + """How many more default-size entries fit into free money and the position limit.""" + settings = self._safe_read_settings() + if self.strategy_mode != strategy.STRATEGY_CLASSIC and self.mode_var.get() == "Симуляция": + # Modes A/B size entries from their own settings, not the classic currency template. + try: + params = self._strategy_mode_params() + settings = {"stake": self.initial_balance * params["stake_pct"] / 100, + "leverage": params["leverage"]} + except ValueError: + return "" + stake = float(settings.get("stake") or 0.0) if settings else 0.0 + if stake <= 0: + return "" + by_money = max(0, int(free // (stake * (1 + float(settings.get("leverage", 1)) * TAKER_FEE_PCT / 100)))) + limit = self._position_limit_or_none() + if limit is not None: + by_limit = max(0, limit - open_positions) + return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}" + return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}" + + def _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 + if self.chart_view_end is None: + self.chart_view_end = candle_start + interval_seconds + elif self.chart_view_end >= candle_start - interval_seconds: + # Keep the live candle on screen when the view is following the market. + self.chart_view_end = candle_start + interval_seconds + if not self.candles or self.candles[-1][0] != candle_start: + if self.candles: + self.baseline_close = self.candles[-1][4] + self.candles.append([candle_start, price, price, price, price]) + else: + candle = self.candles[-1] + candle[2] = max(candle[2], price) + candle[3] = min(candle[3], price) + candle[4] = price + + def reset_statistics(self) -> None: + if self.mode_var.get() == "Реальная торговля": + messagebox.showinfo("Сброс статистики", "Реальная история загружается с Bybit и не может быть сброшена из симулятора. Сброс доступен только для виртуального счёта.") + return + if any(state.position for state in self.symbol_states.values()): + messagebox.showerror("Сброс статистики", "Сначала дождитесь закрытия открытой позиции по TP или стопу.") + return + if not messagebox.askyesno( + "Сброс статистики", + "Очистить историю, комиссии и результат симуляции?", + ): + return + self.trades.clear() + self.total_fees = 0.0 + self.balance = self.initial_balance + self.next_id = 1 + self.entry_markers.clear() + for state in self.symbol_states.values(): + state.entry_markers.clear() + for item in self.table.get_children(): + self.table.delete(item) + self._save_account_state() + self._refresh_ui() + self._draw_chart() + self.status_var.set("Статистика сброшена; симуляция продолжает работу" if self.running else "Статистика сброшена") + + def _fetch_baseline_async(self, symbol: str, interval: int) -> None: + threading.Thread(target=self._fetch_baseline, args=(symbol, interval), daemon=True).start() + + def _fetch_chart_candles_async(self, symbol: str, interval: int) -> None: + def worker() -> None: + query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, + "interval": str(interval), "limit": "50"}) + request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}", + headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + try: + with urllib.request.urlopen(request, timeout=8) as response: + result = json.loads(response.read().decode("utf-8")) + if result.get("retCode") != 0: + return + interval_seconds = interval * 60 + now = time.time() + candles = [[int(row[0]) / 1000, float(row[1]), float(row[2]), float(row[3]), float(row[4])] + for row in result.get("result", {}).get("list", []) + if int(row[0]) / 1000 + interval_seconds <= now] + candles.sort(key=lambda row: row[0]) + if candles: + self.events.put(("chart_candles", symbol, interval, candles, candles[-1][4])) + except Exception: + return + threading.Thread(target=worker, daemon=True).start() + + def _fetch_baseline(self, symbol: str, interval: int) -> None: + query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, "interval": str(interval), "limit": "3"}) + request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}", headers={"User-Agent": "RealtimePaperSimulator/1.0"}) + try: + with urllib.request.urlopen(request, timeout=8) as response: + result = json.loads(response.read().decode("utf-8")) + if result.get("retCode") != 0: + raise RuntimeError(result.get("retMsg", "Bybit kline request failed")) + interval_ms = interval * 60_000 + now_ms = int(time.time() * 1000) + closed = [row for row in result.get("result", {}).get("list", []) if int(row[0]) + interval_ms <= now_ms] + if not closed: + raise RuntimeError("Bybit не вернул закрытую свечу") + latest = max(closed, key=lambda row: int(row[0])) + self.events.put(("baseline", symbol, interval, float(latest[4]))) + except Exception as exc: + self.events.put(("status", f"Не удалось загрузить закрытие свечи: {exc}")) + + @staticmethod + def _draw_level(canvas: tk.Canvas, price: float, low: float, high: float, left: int, right: int, top: int, bottom: int, label: str, color: str) -> None: + if not low <= price <= high: + return + y = bottom - (price - low) / (high - low) * (bottom - top) + canvas.create_line(left, y, right, y, fill=color, dash=(5, 3)) + canvas.create_text(left + 4, y - 3, anchor="sw", fill=color, text=f"{label}: {PaperSimulator._fmt_price(price)}") + + def _on_close(self) -> None: + if self.running: + self.stop() + self._save_settings() + self._save_account_state() + self._signal_pool.shutdown(wait=False, cancel_futures=True) + self.root.destroy() + + +def main() -> None: + root = tk.Tk() + PaperSimulator(root) + root.mainloop() + + +if __name__ == "__main__": + main() diff --git a/meme_matcher/README.md b/meme_matcher/README.md new file mode 100644 index 0000000..e10f103 --- /dev/null +++ b/meme_matcher/README.md @@ -0,0 +1,105 @@ +# Meme Matcher + +Finds the same memecoins on **CEX perpetual futures** and on **DEX spot**, and compares their prices. + +``` +py -3 meme_matcher.py # window +py -3 meme_matcher.py --once # console table + meme_matches.csv +``` + +Python 3.10+ standard library only; all APIs are public (no keys). + +## Sources + +| What | Where | +|---|---| +| USDT perpetuals: price, 24h volume, funding | Bybit, Binance, OKX, Gate, MEXC, Bitget, BingX | +| Which coins are memecoins, market cap, contract addresses | CoinGecko, category `meme-token` (top 1000 by default, 4 pages × 250) | +| DEX pools: price, liquidity, 24h volume | DexScreener (Solana, Ethereum, BSC, Base, Arbitrum, TON, …) | +| DEX spot order book | HyperLiquid spot (USDC pairs) | + +The CoinGecko contract list (~4 MB) is cached in `cache/` for 24 h. + +## How a coin is identified + +A ticker alone is not enough: CoinGecko lists 21 different "PEPE" tokens, and one exchange can list `CAT` and +`1000CAT` as two different coins. So: + +1. Contract size prefixes and suffixes are removed and the price is converted to one coin (`1000PEPE`, `1MBABYDOGE`, + `SHIB1000`). +2. Each CEX contract is tied to the CoinGecko meme token with the same symbol **whose price agrees** with it (within + ±50%); contracts that agree with no meme token are skipped (not a memecoin, or an unknown one). +3. For that token's contract addresses every DexScreener pool is fetched; the token must be the pool's base asset. + The chosen pool is the deepest one whose price is within ±25% of the CEX price; HyperLiquid spot is added by + token name with the same price check. +4. Status by the DEX − CEX price gap: **совпадает** ≤ 5%, **проверить** ≤ 25%, **разные монеты?** above that (only + pools at a very different price exist — usually a copycat token on another chain), **нет на DEX**. + +## Window + +Exchange checkboxes, minimum DEX liquidity and CEX volume, number of CoinGecko pages, "only on DEX" and +"only matching" filters. Columns sort on click; a double click opens the pool on DexScreener / HyperLiquid; +"Сохранить CSV" saves what is shown. `(+N)` after the DEX means the coin also trades on N more chains at the same +price. Funding is the largest absolute funding rate over the listed exchanges. + +## Lead-lag: does the DEX move before the futures? + +``` +py -3 leadlag.py --minutes 30 --coins 12 # scan, record, analyse +py -3 leadlag.py --analyze recordings\leadlag_….jsonl.gz +``` + +Also the «Опережение DEX…» button in the window. Coins: status «совпадает», a pool on **Solana, BSC or Base** +(blocks ≤ 2 s; a 12 s Ethereum block cannot show a 1 s lead) with at least 120 swaps an hour (the most active pool +is used), and a perpetual on Binance, Bybit, Gate or MEXC (in that order of preference). + +Recorded at the same time: +* futures trades over WebSockets with exchange timestamps in ms (Binance `fstream…/market/stream` aggTrade, Bybit + publicTrade, Gate futures.trades, MEXC push.deal); +* DEX swaps from GeckoTerminal (`/pools/{pool}/trades`, last 300 swaps, polled every 30 s, ≤ 26 requests a minute) + with **on-chain block timestamps** — so the lead is measured on chain time, not on when the API showed the swap. + +Recordings go to `recordings/`, verdicts to `leadlag_results.csv`. + +Analysis on a 1-second grid (DEX: volume-weighted price of the block second; futures: last trade of the second): +* correlation of 1-s returns at lags −10…+10 s (+ = futures after the DEX); +* events — seconds where the DEX moved ≥ 0.15%: the futures move in the same direction in that second, and **from + t+1 to t+3/5/10** — i.e. after the DEX second and the next one, so a sub-second reaction that merely lands in the + next second does not count as a lead. Block times are whole seconds, so a lead under ~1 s cannot be told apart + from "simultaneous". +* verdicts: **DEX опережает ≥1 с** (t+1→t+5 move the DEX way, t ≥ 2, hit rate ≥ 60%, ≥ 10 events), **фьючерс + опережает** (best correlation at a negative lag), **после DEX фьючерс откатывает**, **одновременно / нет + опережения**, **мало движений DEX / мало данных**. + +**Live use:** GeckoTerminal publishes swaps 1–2 minutes late (column «Задержка данных DEX»). The tool can find +which coins lead; acting on a lead needs a direct chain feed (Solana RPC WebSocket on the pool), not this API. + +## Autonomous search (autoscan) + +``` +py -3 autoscan.py --minutes 15 --coins 12 # or autoscan.bat, or «Автопоиск…» → «Запустить» in the window +``` + +Runs on its own in a loop: scan → up to 12 coins (earlier leaders are re-checked first, the rest rotate through all +candidates) → 15 min recording → lead analysis → next cycle (one cycle ≈ 20 min). Every result is appended to +`autoscan_history.csv`, the log to `autoscan.log`. A coin with «DEX опережает ≥1 с» whose pool is on Solana and of a +type the simulator reads live (Raydium AMM v4 / CPMM, PumpSwap, Meteora DLMM — checked through the pool account's +owner program) and whose futures are on Binance, Bybit or MEXC is added to the simulator's `../lead_connections.json` +(never removed; the simulator's active connection is not changed; the simulator picks the new entry up within 30 s). +Only one autoscan runs at a time (`autoscan.lock`); the manual «Опережение DEX…» recording shares GeckoTerminal's +rate limit with it. «Автопоиск…» in the window shows the history (leaders highlighted, what was added) and starts or +stops the background process, which keeps running when the windows are closed. + +## Limits + +* The meme universe is CoinGecko's `meme-token` category: memecoins that CoinGecko has not tagged, or that are + outside the scanned pages, are not found. +* The CoinGecko free API allows a few requests per minute; the scanner waits between pages and retries on HTTP 429. +* Prices come from different moments (each API is polled once); small gaps are timing, not arbitrage. DEX prices + do not include swap fees, slippage or gas. + +## Tests + +``` +py -3 -m unittest discover -s tests +``` diff --git a/meme_matcher/autoscan.bat b/meme_matcher/autoscan.bat new file mode 100644 index 0000000..3d78c7b --- /dev/null +++ b/meme_matcher/autoscan.bat @@ -0,0 +1,5 @@ +@echo off +rem Autonomous DEX -> futures lead search; leaders are added to the simulator's connection list. +cd /d "%~dp0" +py -3 autoscan.py --minutes 15 --coins 12 +pause diff --git a/meme_matcher/autoscan.py b/meme_matcher/autoscan.py new file mode 100644 index 0000000..3097d21 --- /dev/null +++ b/meme_matcher/autoscan.py @@ -0,0 +1,406 @@ +"""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 +CONNECTIONS_FILE = SIM_DIR / "lead_connections.json" +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 +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((SIM_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: + """One autoscan at a time (they would share GeckoTerminal's rate limit).""" + 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: + 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 = ROOT / "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) + + +def stop_background() -> None: + pid = running_pid() + if pid: + import subprocess + subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True) + try: + LOCK_FILE.unlink() + except OSError: + pass + log("остановлено из окна") + + +def open_window(parent) -> None: + """History of the autonomous search + start/stop, refreshed every 15 s.""" + import tkinter as tk + from tkinter import ttk + + win = tk.Toplevel(parent) + win.title("Автопоиск: DEX опережает фьючерсы") + win.geometry("1250x620") + top = ttk.Frame(win, padding=6) + top.pack(fill="x") + minutes, coins = tk.StringVar(value="15"), tk.StringVar(value="12") + ttk.Label(top, text="Минут на цикл").pack(side="left") + ttk.Entry(top, textvariable=minutes, width=5).pack(side="left", padx=(4, 10)) + ttk.Label(top, text="Монет за цикл (до 13)").pack(side="left") + ttk.Entry(top, textvariable=coins, width=5).pack(side="left", padx=(4, 10)) + start_btn = ttk.Button(top, text="▶ Запустить автопоиск") + start_btn.pack(side="left", padx=4) + stop_btn = ttk.Button(top, text="■ Остановить") + stop_btn.pack(side="left") + state_var = tk.StringVar() + ttk.Label(top, textvariable=state_var, padding=(10, 0)).pack(side="left") + only_leaders = tk.BooleanVar(value=False) + ttk.Checkbutton(top, text="Только «DEX опережает»", variable=only_leaders, command=lambda: fill()).pack(side="left") + cols = {"time": ("Время", 110), "cycle": ("Цикл", 45), "symbol": ("Монета", 80), "verdict": ("Вывод", 200), + "futures": ("Фьючерс", 70), "dex_pool": ("Пул DEX", 130), "dex_moves": ("Движений", 70), + "best_lag_s": ("Лаг, с", 50), "follow_t1_t5_pct": ("t+1→t+5", 70), "hit_t5": ("Попад.", 55), + "t_stat": ("t", 50), "added_to_simulator": ("В симулятор", 230)} + tree = ttk.Treeview(win, columns=list(cols), show="headings", height=18) + for key, (title, width) in cols.items(): + tree.heading(key, text=title) + tree.column(key, width=width, anchor="w") + tree.tag_configure("lead", background="#e8f7e8") + tree.pack(fill="both", expand=True, padx=6) + log_var = tk.StringVar() + ttk.Label(win, textvariable=log_var, padding=6, wraplength=1200, justify="left", foreground="#444").pack(fill="x") + + def fill() -> None: + tree.delete(*tree.get_children()) + try: + rows = list(csv.DictReader(HISTORY_CSV.open(encoding="utf-8-sig"), delimiter=";")) + except OSError: + rows = [] + for r in reversed(rows[-500:]): + if only_leaders.get() and r["verdict"] != LEAD_VERDICT: + continue + tree.insert("", "end", values=[r.get(k, "") for k in cols], + tags=("lead",) if r["verdict"] == LEAD_VERDICT else ()) + + def refresh() -> None: + pid = running_pid() + state_var.set(f"автопоиск работает (процесс {pid})" if pid else "автопоиск остановлен") + start_btn.configure(state="disabled" if pid else "normal") + stop_btn.configure(state="normal" if pid else "disabled") + fill() + try: + lines = LOG_FILE.read_text(encoding="utf-8").splitlines()[-4:] + except OSError: + lines = [] + log_var.set("\n".join(lines)) + if win.winfo_exists(): + win.after(15000, refresh) + + def start() -> None: + try: + m, n = float(minutes.get()), max(1, min(13, int(coins.get()))) + except ValueError: + state_var.set("проверьте числа") + return + start_background(m, n) + win.after(1500, refresh) + + start_btn.configure(command=start) + stop_btn.configure(command=lambda: (stop_background(), win.after(500, refresh))) + refresh() + + +def main() -> None: + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + parser = argparse.ArgumentParser(description="autonomous DEX → futures lead search") + parser.add_argument("--minutes", type=float, default=15, help="recording per cycle") + parser.add_argument("--coins", type=int, default=12, help="coins per cycle (GeckoTerminal allows ~13)") + parser.add_argument("--min-txns", type=int, default=120, help="min swaps per hour in the DEX pool") + parser.add_argument("--threshold", type=float, default=0.15, help="DEX move in one second, %%") + args = parser.parse_args() + if not take_lock(): + print("Автопоиск уже запущен (autoscan.lock) — второй экземпляр не нужен") + return + try: + run(args.minutes, min(13, args.coins), args.min_txns, args.threshold) + except KeyboardInterrupt: + log("остановлено") + finally: + try: + LOCK_FILE.unlink() + except OSError: + pass + + +if __name__ == "__main__": + main() diff --git a/meme_matcher/leadlag.py b/meme_matcher/leadlag.py new file mode 100644 index 0000000..c7938be --- /dev/null +++ b/meme_matcher/leadlag.py @@ -0,0 +1,591 @@ +"""Lead-lag: does the DEX spot price move BEFORE the CEX perpetual (by at least a second)? + +For memecoins found by meme_matcher (same coin, price agrees, a pool on a fast chain) it records at the same time +* CEX perpetual trades from a WebSocket (Binance, Bybit, Gate or MEXC) with exchange timestamps in milliseconds; +* DEX swaps of the most active pool from GeckoTerminal with ON-CHAIN block timestamps (1 s resolution). + +Then, on a 1-second grid, it checks whether a DEX move in second t is followed by the futures moving the same way +AFTER second t+1 - i.e. later than any same-second reaction could explain. That is the part one could trade. + +Note: GeckoTerminal publishes swaps ~40-60 s after the block (it caches for 30 s), so this tool MEASURES the lead +on chain time; using a lead live needs a direct chain feed (e.g. a Solana RPC WebSocket). The DEX data delay is +reported per coin. + +Run: py -3 leadlag.py --minutes 20 --coins 10 (scan, record, analyse) + py -3 leadlag.py --analyze recordings\\leadlag_....jsonl.gz +""" + +from __future__ import annotations + +import argparse +import csv +import gzip +import json +import math +import threading +import time +from collections import deque +from dataclasses import asdict, dataclass, field +from datetime import datetime +from pathlib import Path + +import numpy as np + +import meme_matcher as mm + +ROOT = Path(__file__).resolve().parent +REC_DIR = ROOT / "recordings" +RESULTS_CSV = ROOT / "leadlag_results.csv" + +# DexScreener chain -> GeckoTerminal network. Only chains with blocks of ~2 s or faster: a 12 s Ethereum block +# cannot show a 1 s lead. +FAST_CHAINS = {"solana": "solana", "bsc": "bsc", "base": "base"} +CEX_PRIORITY = ["Binance", "Bybit", "Gate", "MEXC"] +GECKO_CALLS_PER_MIN = 26 # free tier: 30 a minute +MIN_POLL_S = 30 # GeckoTerminal caches responses for 30 s +TAIL_S = 180 # extra DEX polling after the CEX recording ends (swaps are published late) + + +@dataclass +class Target: + symbol: str + cg_id: str + cex: str + cex_symbol: str + multiplier: float + chain: str + network: str + pool: str + token: str + dex: str + txns_h1: int + + +def pick_targets(matches: list[mm.Match], max_coins: int = 10, min_txns_h1: int = 120) -> list[Target]: + out = [] + for m in matches: + if m.status != "совпадает": + continue + pools = [p for p in m.pools if p.source == "DexScreener" and p.chain in FAST_CHAINS and p.pair_address] + if not pools: + continue + pool = max(pools, key=lambda p: p.txns_h1) + if pool.txns_h1 < min_txns_h1: + continue + by_exchange = {l.exchange: l for l in m.cex} + listing = next((by_exchange[e] for e in CEX_PRIORITY if e in by_exchange), None) + if listing is None: + continue + out.append(Target(m.symbol, m.cg_id, listing.exchange, listing.symbol, listing.multiplier, pool.chain, + FAST_CHAINS[pool.chain], pool.pair_address, pool.contract, pool.dex, pool.txns_h1)) + out.sort(key=lambda t: -t.txns_h1) + return out[:max_coins] + + +# -------------------------------------------------------------------------------------------- +# Recording +# -------------------------------------------------------------------------------------------- + +class Recorder: + def __init__(self, targets: list[Target]) -> None: + self.targets = targets + self.lock = threading.Lock() + self.cex: dict[str, list[tuple[float, float]]] = {t.symbol: [] for t in targets} + self.dex: dict[str, list[tuple[float, float, float, str, float]]] = {t.symbol: [] for t in targets} + self.seen: set[str] = set() + self.gaps: dict[str, int] = {t.symbol: 0 for t in targets} + self.errors: deque[str] = deque(maxlen=20) + self.started = time.time() + + def add_cex(self, symbol: str, ts: float, price: float) -> None: + with self.lock: + self.cex[symbol].append((ts, price)) + + def add_dex(self, symbol: str, trade_id: str, ts: float, price: float, volume: float, kind: str) -> bool: + with self.lock: + if trade_id in self.seen: + return False + self.seen.add(trade_id) + self.dex[symbol].append((ts, price, volume, kind, time.time())) + return True + + def counts(self) -> dict[str, tuple[int, int]]: + with self.lock: + return {s: (len(self.cex[s]), len(self.dex[s])) for s in self.cex} + + def save(self, path: Path | None = None) -> Path: + REC_DIR.mkdir(exist_ok=True) + path = path or REC_DIR / f"leadlag_{datetime.now():%Y%m%d_%H%M%S}.jsonl.gz" + with self.lock, gzip.open(path, "wt", encoding="utf-8") as f: + f.write(json.dumps({"meta": {"started": self.started, "saved": time.time(), "gaps": self.gaps, + "targets": [asdict(t) for t in self.targets]}}) + "\n") + for s, rows in self.cex.items(): + for ts, price in rows: + f.write(json.dumps(["C", s, ts, price]) + "\n") + for s, rows in self.dex.items(): + for row in rows: + f.write(json.dumps(["D", s, *row]) + "\n") + return path + + +def load(path: Path) -> tuple[list[Target], dict, dict, dict]: + cex: dict[str, list] = {} + dex: dict[str, list] = {} + meta = {} + with gzip.open(path, "rt", encoding="utf-8") as f: + for line in f: + row = json.loads(line) + if isinstance(row, dict): + meta = row["meta"] + elif row[0] == "C": + cex.setdefault(row[1], []).append((row[2], row[3])) + else: + dex.setdefault(row[1], []).append(tuple(row[2:])) + targets = [Target(**t) for t in meta.get("targets", [])] + return targets, cex, dex, meta + + +class CexFeed(threading.Thread): + """Trades of one exchange's perpetuals over a WebSocket; reconnects on errors.""" + + def __init__(self, exchange: str, targets: list[Target], rec: Recorder, stop: threading.Event) -> None: + super().__init__(daemon=True) + self.exchange, self.rec, self.stop_event = exchange, rec, stop + self.by_symbol = {t.cex_symbol: t for t in targets} + + def _url(self) -> str: + if self.exchange == "Binance": + streams = "/".join(f"{s.lower()}@aggTrade" for s in self.by_symbol) + return f"wss://fstream.binance.com/market/stream?streams={streams}" + return {"Bybit": "wss://stream.bybit.com/v5/public/linear", "Gate": "wss://fx-ws.gateio.ws/v4/ws/usdt", + "MEXC": "wss://contract.mexc.com/edge"}[self.exchange] + + def _subscribe(self, ws) -> None: + symbols = list(self.by_symbol) + if self.exchange == "Bybit": + for i in range(0, len(symbols), 10): + ws.send(json.dumps({"op": "subscribe", "args": [f"publicTrade.{s}" for s in symbols[i:i + 10]]})) + elif self.exchange == "Gate": + ws.send(json.dumps({"time": int(time.time()), "channel": "futures.trades", "event": "subscribe", + "payload": symbols})) + elif self.exchange == "MEXC": + for s in symbols: + ws.send(json.dumps({"method": "sub.deal", "param": {"symbol": s}})) + + def _ping(self, ws) -> None: + if self.exchange == "Bybit": + ws.send(json.dumps({"op": "ping"})) + elif self.exchange == "Gate": + ws.send(json.dumps({"time": int(time.time()), "channel": "futures.ping"})) + elif self.exchange == "MEXC": + ws.send(json.dumps({"method": "ping"})) + + def _emit(self, symbol: str, ts_ms, price) -> None: + target = self.by_symbol.get(symbol) + if target is not None: + self.rec.add_cex(target.symbol, float(ts_ms) / 1000, float(price) / target.multiplier) + + def handle(self, msg: dict) -> None: + if self.exchange == "Binance": + d = msg.get("data") or {} + if d.get("e") == "aggTrade": + self._emit(d["s"], d["T"], d["p"]) + elif self.exchange == "Bybit": + if str(msg.get("topic", "")).startswith("publicTrade."): + for d in msg.get("data", []): + self._emit(d["s"], d["T"], d["p"]) + elif self.exchange == "Gate": + if msg.get("channel") == "futures.trades" and msg.get("event") == "update": + for d in msg.get("result", []): + self._emit(d["contract"], d["create_time_ms"], d["price"]) + elif self.exchange == "MEXC": + if msg.get("channel") == "push.deal": + data = msg.get("data") + for d in data if isinstance(data, list) else [data]: + self._emit(msg.get("symbol", ""), d["t"], d["p"]) + + def run(self) -> None: + import websocket + + while not self.stop_event.is_set(): + try: + ws = websocket.create_connection(self._url(), timeout=5) + self._subscribe(ws) + last_ping = time.time() + while not self.stop_event.is_set(): + if time.time() - last_ping > 15: + self._ping(ws) + last_ping = time.time() + try: + raw = ws.recv() + except websocket.WebSocketTimeoutException: + continue + if raw: + self.handle(json.loads(raw)) + ws.close() + except Exception as exc: + self.rec.errors.append(f"{self.exchange}: {exc}") + self.stop_event.wait(3) + + +def parse_gecko_trades(data: dict, token: str) -> list[tuple[str, float, float, float, str]]: + """GeckoTerminal /trades -> (id, block time, price of OUR token in USD, volume USD, buy/sell).""" + token = token.lower() + out = [] + for item in data.get("data") or []: + a = item.get("attributes") or {} + try: + ts = datetime.fromisoformat(a["block_timestamp"].replace("Z", "+00:00")).timestamp() + except (KeyError, ValueError): + continue + if str(a.get("from_token_address", "")).lower() == token: + price = mm._f(a.get("price_from_in_usd")) + elif str(a.get("to_token_address", "")).lower() == token: + price = mm._f(a.get("price_to_in_usd")) + else: + continue + if price > 0: + out.append((item.get("id") or a.get("tx_hash", ""), ts, price, mm._f(a.get("volume_in_usd")), + a.get("kind", ""))) + return out + + +class DexPoller(threading.Thread): + def __init__(self, targets: list[Target], rec: Recorder, stop: threading.Event) -> None: + super().__init__(daemon=True) + self.targets, self.rec, self.stop_event = targets, rec, stop + + def run(self) -> None: + gap = 60.0 / GECKO_CALLS_PER_MIN + first = {t.symbol: True for t in self.targets} + while not self.stop_event.is_set(): + cycle_start = time.time() + for t in self.targets: + if self.stop_event.is_set(): + return + try: + data = mm.http_json(f"https://api.geckoterminal.com/api/v2/networks/{t.network}/pools/{t.pool}" + "/trades", retries=2) + trades = parse_gecko_trades(data or {}, t.token) + new = sum(self.rec.add_dex(t.symbol, *tr) for tr in trades) + if not first[t.symbol] and trades and new == len(trades) and len(trades) >= 300: + self.rec.gaps[t.symbol] += 1 # all 300 were new: some swaps were missed + first[t.symbol] = False + except Exception as exc: + self.rec.errors.append(f"GeckoTerminal {t.symbol}: {exc}") + self.stop_event.wait(gap) + rest = MIN_POLL_S - (time.time() - cycle_start) + if rest > 0: + self.stop_event.wait(rest) + + +def record(targets: list[Target], minutes: float, log=print, stop: threading.Event | None = None) -> Recorder: + rec = Recorder(targets) + stop = stop or threading.Event() + threads = [DexPoller(targets, rec, stop)] + for exchange in CEX_PRIORITY: + mine = [t for t in targets if t.cex == exchange] + if mine: + threads.append(CexFeed(exchange, mine, rec, stop)) + for th in threads: + th.start() + end = time.time() + minutes * 60 + while time.time() < end and not stop.is_set(): + stop.wait(10) + counts = rec.counts() + left = max(0, end - time.time()) / 60 + log(f"Запись: осталось {left:.1f} мин · " + ", ".join(f"{s} {c}/{d}" for s, (c, d) in counts.items()) + + " (сделок фьючерс/DEX)") + # GeckoTerminal shows swaps 1-2 min late: keep polling the DEX so the last minutes of CEX data are covered + if not stop.is_set(): + log(f"Дозаписываю последние сделки DEX (они появляются с задержкой 1–2 мин), {TAIL_S // 60} мин…") + stop.wait(TAIL_S) + stop.set() + for th in threads: + th.join(timeout=10) + return rec + + +# -------------------------------------------------------------------------------------------- +# Analysis +# -------------------------------------------------------------------------------------------- + +@dataclass +class LeadResult: + symbol: str + cex: str + pool: str + seconds: int + cex_trades: int + dex_trades: int + events: int # seconds with a DEX move of at least the threshold + corr: dict[int, float] # lag (s, + = futures after DEX) -> correlation of 1-s returns + best_lag: int + same_second: float # mean futures move in the DEX move's direction, same second, % + follow: dict[int, float] # mean futures move from t+1 to t+k in the DEX direction, % + hit: dict[int, float] # share of events where that move went the DEX way (of those that moved) + t_stat: float # of the follow move t+1 -> t+5 + dex_delay_s: float # how late GeckoTerminal published the swaps (median) + gaps: int + verdict: str + notes: list[str] = field(default_factory=list) + + +def second_series(trades: list[tuple], t0: int, t1: int, vwap: bool) -> np.ndarray: + """Price per second on [t0, t1], forward-filled. DEX: volume-weighted within the block second.""" + n = t1 - t0 + 1 + px = np.full(n, np.nan) + if vwap: + num, den = np.zeros(n), np.zeros(n) + for ts, price, vol, *_ in trades: + i = int(ts) - t0 + if 0 <= i < n: + w = max(vol, 1e-9) + num[i] += price * w + den[i] += w + mask = den > 0 + px[mask] = num[mask] / den[mask] + else: + for ts, price in sorted(trades): + i = int(math.floor(ts)) - t0 + if 0 <= i < n: + px[i] = price # last trade of the second + # forward fill + last = np.nan + for i in range(n): + if np.isnan(px[i]): + px[i] = last + else: + last = px[i] + return px + + +def analyze_coin(target: Target, cex: list, dex: list, gaps: int = 0, threshold_pct: float = 0.15, + max_lag: int = 10) -> LeadResult: + notes = [] + empty = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", 0, len(cex), len(dex), 0, {}, 0, + 0.0, {}, {}, 0.0, 0.0, gaps, "мало данных", notes) + if len(cex) < 20 or len(dex) < 20: + return empty + t0 = int(max(min(t for t, _ in cex), min(r[0] for r in dex))) + t1 = int(min(max(t for t, _ in cex), max(r[0] for r in dex))) + if t1 - t0 < 120: + return empty + c = second_series(cex, t0, t1, vwap=False) + d = second_series(dex, t0, t1, vwap=True) + ok = ~(np.isnan(c) | np.isnan(d)) + start = int(np.argmax(ok)) + c, d = np.log(c[start:]), np.log(d[start:]) + rc, rd = np.diff(c), np.diff(d) + n = len(rc) + corr = {} + for k in range(-max_lag, max_lag + 1): + a = rd[max(0, -k): n - max(0, k)] + b = rc[max(0, k): n - max(0, -k)] + corr[k] = float(np.corrcoef(a, b)[0, 1]) if len(a) > 30 and a.std() > 0 and b.std() > 0 else 0.0 + best_lag = max(corr, key=lambda k: corr[k]) + # events: DEX moved at least the threshold within one second (rd[i] = second i+1 vs i) + thr = threshold_pct / 100 + horizons = (2, 3, 5, 10) + same, follow, hit = [], {k: [] for k in horizons}, {k: [] for k in horizons} + for i in np.nonzero(np.abs(rd) >= thr)[0]: + t = i + 1 # index of the second where the DEX move landed + if t + max(horizons) >= len(c) or t < 1: + continue + sign = 1.0 if rd[i] > 0 else -1.0 + same.append(sign * (c[t] - c[t - 1])) + for k in horizons: + move = sign * (c[t + k] - c[t + 1]) # strictly after the DEX second and the next one + follow[k].append(move) + if abs(move) > 1e-12: + hit[k].append(move > 0) + events = len(same) + f5 = np.array(follow[5]) if follow[5] else np.array([0.0]) + t_stat = float(f5.mean() / (f5.std(ddof=1) / math.sqrt(len(f5)))) if len(f5) > 2 and f5.std() > 0 else 0.0 + # publication delay only for swaps made during the recording (the first poll returns old history) + first_cex = min(t for t, _ in cex) + delays = [r[4] - r[0] for r in dex if len(r) > 4 and r[0] >= first_cex] + res = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", n, len(cex), len(dex), events, corr, + best_lag, float(np.mean(same) * 100) if same else 0.0, + {k: float(np.mean(v) * 100) if v else 0.0 for k, v in follow.items()}, + {k: float(np.mean(v)) if v else 0.0 for k, v in hit.items()}, t_stat, + float(np.median(delays)) if delays else 0.0, gaps, "", notes) + if gaps: + notes.append(f"пропуски DEX: {gaps} раз пришло 300 новых сделок подряд") + if events < 10: + res.verdict = "мало движений DEX" + elif t_stat >= 2 and res.hit[5] >= 0.6 and res.follow[5] > 0: + res.verdict = "DEX опережает ≥1 с" + elif best_lag < 0 and corr[best_lag] > corr.get(0, 0) and corr[best_lag] > 3 / math.sqrt(n): + res.verdict = "фьючерс опережает" + elif t_stat <= -2: + res.verdict = "после DEX фьючерс откатывает" + else: + res.verdict = "одновременно / нет опережения" + return res + + +def analyze(targets: list[Target], cex: dict, dex: dict, gaps: dict | None = None, + threshold_pct: float = 0.15) -> list[LeadResult]: + out = [analyze_coin(t, cex.get(t.symbol, []), dex.get(t.symbol, []), (gaps or {}).get(t.symbol, 0), + threshold_pct) for t in targets] + order = {"DEX опережает ≥1 с": 0, "одновременно / нет опережения": 1, "фьючерс опережает": 2, + "после DEX фьючерс откатывает": 3, "мало движений DEX": 4, "мало данных": 5} + out.sort(key=lambda r: (order.get(r.verdict, 9), -r.t_stat)) + return out + + +RESULT_COLUMNS = ["symbol", "verdict", "cex", "dex_pool", "minutes", "cex_trades", "dex_trades", "dex_moves", + "best_lag_s", "corr_lag0", "corr_lag1", "corr_lag2", "corr_lag-1", "same_second_pct", + "follow_t1_t3_pct", "follow_t1_t5_pct", "follow_t1_t10_pct", "hit_t5", "t_stat", + "dex_publish_delay_s", "notes"] + + +def result_row(r: LeadResult) -> list: + return [r.symbol, r.verdict, r.cex, r.pool, f"{r.seconds / 60:.1f}", r.cex_trades, r.dex_trades, r.events, + r.best_lag, f"{r.corr.get(0, 0):.3f}", f"{r.corr.get(1, 0):.3f}", f"{r.corr.get(2, 0):.3f}", + f"{r.corr.get(-1, 0):.3f}", f"{r.same_second:+.3f}", f"{r.follow.get(3, 0):+.3f}", + f"{r.follow.get(5, 0):+.3f}", f"{r.follow.get(10, 0):+.3f}", f"{r.hit.get(5, 0):.2f}", + f"{r.t_stat:+.2f}", f"{r.dex_delay_s:.0f}", "; ".join(r.notes)] + + +def save_results(results: list[LeadResult], path: Path = RESULTS_CSV) -> None: + with path.open("w", newline="", encoding="utf-8-sig") as f: + w = csv.writer(f, delimiter=";") + w.writerow(RESULT_COLUMNS) + w.writerows(result_row(r) for r in results) + + +def print_results(results: list[LeadResult]) -> None: + print(f"\n{'Монета':10s} {'Вывод':30s} {'Фьючерс':8s} {'DEX':18s} {'Движ.':>5s} {'Лаг':>4s} " + f"{'Та же с':>8s} {'t+1→t+5':>8s} {'Попад.':>6s} {'t':>6s} {'Задержка':>8s}") + for r in results: + print(f"{r.symbol:10s} {r.verdict:30s} {r.cex:8s} {r.pool[:18]:18s} {r.events:5d} {r.best_lag:+4d} " + f"{r.same_second:+7.3f}% {r.follow.get(5, 0):+7.3f}% {r.hit.get(5, 0) * 100:5.0f}% {r.t_stat:+6.2f} " + f"{r.dex_delay_s:7.0f}с") + + +def open_window(parent, get_matches) -> None: + """'Опережение DEX' dialog for the Meme Matcher window: pick coins, record N minutes, show the verdicts.""" + import tkinter as tk + from tkinter import ttk + + win = tk.Toplevel(parent) + win.title("Опережение DEX → фьючерсы") + win.geometry("1200x560") + form = ttk.Frame(win, padding=6) + form.pack(fill="x") + minutes, coins, min_txns, thr = (tk.StringVar(value=v) for v in ("20", "10", "120", "0.15")) + for label, var in (("Минут записи", minutes), ("Монет (до 13)", coins), ("Мин. сделок в пуле за час", min_txns), + ("Движение DEX за 1 с, %", thr)): + ttk.Label(form, text=label).pack(side="left", padx=(0, 4)) + ttk.Entry(form, textvariable=var, width=7).pack(side="left", padx=(0, 10)) + start_btn = ttk.Button(form, text="Записать и проверить") + start_btn.pack(side="left", padx=4) + stop_btn = ttk.Button(form, text="Остановить", state="disabled") + stop_btn.pack(side="left") + columns = {"symbol": ("Монета", 80), "verdict": ("Вывод", 210), "cex": ("Фьючерс", 70), "pool": ("Пул DEX", 140), + "events": ("Движений DEX", 90), "lag": ("Лучший лаг, с", 85), "same": ("Та же секунда", 90), + "follow": ("После t+1 → t+5", 105), "hit": ("Попадание", 75), "t": ("t-стат.", 60), + "delay": ("Задержка данных DEX", 125)} + tree = ttk.Treeview(win, columns=list(columns), show="headings", height=14) + for key, (title, width) in columns.items(): + tree.heading(key, text=title) + tree.column(key, width=width, anchor="w") + tree.tag_configure("lead", background="#e8f7e8") + tree.pack(fill="both", expand=True, padx=6) + status = tk.StringVar(value="Берутся монеты со статусом «совпадает», пулом на Solana/BSC/Base и фьючерсом на " + "Binance/Bybit/Gate/MEXC. «После t+1 → t+5» — движение фьючерса в сторону DEX, " + "начиная со следующей секунды после движения на DEX.") + ttk.Label(win, textvariable=status, padding=6, wraplength=1150).pack(fill="x") + stop_event = threading.Event() + + def show(results): + tree.delete(*tree.get_children()) + for r in results: + tree.insert("", "end", tags=("lead",) if r.verdict.startswith("DEX опережает") else (), values=( + r.symbol, r.verdict, r.cex, r.pool, r.events, f"{r.best_lag:+d}", f"{r.same_second:+.3f}%", + f"{r.follow.get(5, 0):+.3f}%", f"{r.hit.get(5, 0) * 100:.0f}%", f"{r.t_stat:+.2f}", + f"{r.dex_delay_s:.0f} с")) + + def log(text): + win.after(0, status.set, text) + + def start(): + matches = get_matches() + if not matches: + status.set("Сначала дождитесь сканирования в главном окне") + return + try: + n_min, n_coins = float(minutes.get()), max(1, min(13, int(coins.get()))) + n_txns, threshold = int(min_txns.get()), float(thr.get()) + except ValueError: + status.set("Проверьте числа в полях") + return + targets = pick_targets(matches, n_coins, n_txns) + if not targets: + status.set("Нет подходящих монет — уменьшите «Мин. сделок в пуле за час»") + return + stop_event.clear() + start_btn.configure(state="disabled") + stop_btn.configure(state="normal") + + def work(): + rec = record(targets, n_min, log, stop_event) + path = rec.save() + results = analyze(targets, rec.cex, rec.dex, rec.gaps, threshold) + save_results(results) + win.after(0, finish, results, path) + + threading.Thread(target=work, daemon=True).start() + + def finish(results, path): + start_btn.configure(state="normal") + stop_btn.configure(state="disabled") + show(results) + leaders = [r.symbol for r in results if r.verdict.startswith("DEX опережает")] + status.set(f"Запись: {path.name} · результаты: {RESULTS_CSV.name} · DEX опережает: " + f"{', '.join(leaders) if leaders else 'не найдено'}") + + start_btn.configure(command=start) + stop_btn.configure(command=lambda: (stop_event.set(), status.set("Останавливаю и считаю…"))) + + +def main() -> None: + import sys + + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + parser = argparse.ArgumentParser(description="DEX → CEX futures lead-lag for memecoins") + parser.add_argument("--minutes", type=float, default=20) + parser.add_argument("--coins", type=int, default=10) + parser.add_argument("--min-txns", type=int, default=120, help="min swaps per hour in the DEX pool") + parser.add_argument("--threshold", type=float, default=0.15, help="DEX move in one second, %%") + parser.add_argument("--analyze", type=Path, help="analyse an existing recording instead of recording") + args = parser.parse_args() + if args.analyze: + targets, cex, dex, meta = load(args.analyze) + results = analyze(targets, cex, dex, meta.get("gaps"), args.threshold) + else: + matches = mm.scan() + targets = pick_targets(matches, args.coins, args.min_txns) + if not targets: + print("Нет подходящих монет (совпадение цены, пул на Solana/BSC/Base, достаточно сделок в час)") + return + print("Монеты для записи:") + for t in targets: + print(f" {t.symbol:10s} {t.cex:8s} {t.cex_symbol:16s} {t.chain}/{t.dex} пул {t.pool[:10]}… " + f"сделок в час {t.txns_h1}") + rec = record(targets, args.minutes) + path = rec.save() + print(f"Запись: {path}") + for e in rec.errors: + print(" ошибка:", e) + results = analyze(targets, rec.cex, rec.dex, rec.gaps, args.threshold) + save_results(results) + print_results(results) + print(f"\nCSV: {RESULTS_CSV}") + + +if __name__ == "__main__": + main() diff --git a/meme_matcher/meme_matcher.py b/meme_matcher/meme_matcher.py new file mode 100644 index 0000000..f49d47e --- /dev/null +++ b/meme_matcher/meme_matcher.py @@ -0,0 +1,718 @@ +"""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), + "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), +} + + +def fetch_cex(exchanges: list[str], log=print) -> list[Listing]: + def one(name): + url, parser = CEX_SOURCES[name] + try: + items = parser(http_json(url)) + log(f"{name}: {len(items)} фьючерсов") + return items + except Exception as exc: # one exchange down must not stop the rest + log(f"{name}: ошибка {exc}") + return [] + + with ThreadPoolExecutor(max_workers=len(exchanges) or 1) as pool: + return [x for chunk in pool.map(one, exchanges) for x in chunk] + + +# -------------------------------------------------------------------------------------------- +# CoinGecko: which coins are memes, and their contracts +# -------------------------------------------------------------------------------------------- + +@dataclass +class MemeCoin: + cg_id: str + symbol: str # upper case + name: str + price: float + market_cap: float + platforms: dict[str, str] = field(default_factory=dict) # CoinGecko platform -> contract + + +def fetch_memes(pages: int, log=print) -> list[dict]: + rows = [] + for page in range(1, pages + 1): + chunk = http_json("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=meme-token" + f"&order=market_cap_desc&per_page=250&page={page}") or [] + rows += chunk + log(f"CoinGecko: мемкойнов {len(rows)}") + if len(chunk) < 250: + break + time.sleep(2.5) # free tier: a few requests per minute + return rows + + +def fetch_platforms(max_age_hours: float = 24, log=print) -> dict[str, dict[str, str]]: + """CoinGecko id -> {platform: contract}; the 4 MB list is cached for a day.""" + CACHE_DIR.mkdir(exist_ok=True) + path = CACHE_DIR / "coingecko_platforms.json" + if path.exists() and time.time() - path.stat().st_mtime < max_age_hours * 3600: + return json.loads(path.read_text(encoding="utf-8")) + data = http_json("https://api.coingecko.com/api/v3/coins/list?include_platform=true") or [] + platforms = {c["id"]: {k: v for k, v in (c.get("platforms") or {}).items() if k and v} for c in data} + path.write_text(json.dumps(platforms), encoding="utf-8") + log(f"CoinGecko: адреса контрактов {len(platforms)} монет") + return platforms + + +def build_memes(markets: list[dict], platforms: dict[str, dict[str, str]]) -> list[MemeCoin]: + out = [] + for m in markets: + price = _f(m.get("current_price")) + if not m.get("symbol") or price <= 0: + continue + out.append(MemeCoin(m["id"], m["symbol"].upper(), m.get("name") or m["id"], price, _f(m.get("market_cap")), + platforms.get(m["id"], {}))) + return out + + +def pick_coin(base: str, cex_price: float, memes_by_symbol: dict[str, list[MemeCoin]]) -> MemeCoin | None: + """The meme token behind a CEX ticker: same symbol, price closest to the CEX price (and not wildly off).""" + best, best_gap = None, None + for coin in memes_by_symbol.get(base.upper(), []): + gap = abs(math.log(coin.price / cex_price)) + if best_gap is None or gap < best_gap: + best, best_gap = coin, gap + if best is None or best_gap > math.log(1 + SYMBOL_PRICE_TOL) + 1e-12: + return None + return best + + +# -------------------------------------------------------------------------------------------- +# DEX +# -------------------------------------------------------------------------------------------- + +@dataclass +class DexPair: + source: str # DexScreener / HyperLiquid + chain: str + dex: str + pair: str # e.g. PEPE/WETH + price: float + liquidity_usd: float + volume_usd: float + contract: str + url: str + pair_address: str = "" + txns_h1: int = 0 # swaps in the last hour (DexScreener) + + +def best_pairs(pairs: list[dict]) -> dict[tuple[str, str], DexPair]: + """(chain, lower-case token address) -> its most liquid pair where the token is the BASE asset.""" + out: dict[tuple[str, str], DexPair] = {} + for p in pairs: + base = p.get("baseToken") or {} + price = _f(p.get("priceUsd")) + if not base.get("address") or price <= 0: + continue + key = (p.get("chainId", ""), base["address"].lower()) + liq = _f((p.get("liquidity") or {}).get("usd")) + if key in out and out[key].liquidity_usd >= liq: + continue + h1 = (p.get("txns") or {}).get("h1") or {} + out[key] = DexPair("DexScreener", p.get("chainId", ""), p.get("dexId", ""), + f"{base.get('symbol', '')}/{(p.get('quoteToken') or {}).get('symbol', '')}", price, liq, + _f((p.get("volume") or {}).get("h24")), base["address"], p.get("url", ""), + p.get("pairAddress", ""), int(_f(h1.get("buys")) + _f(h1.get("sells")))) + return out + + +def fetch_dexscreener(contracts: dict[str, set[str]], log=print) -> dict[tuple[str, str], list[DexPair]]: + """contracts: DexScreener chain -> addresses. One request per contract returns all its pools (DexScreener + allows ~300 requests a minute); the batch endpoint returns only one pool per token, often not the deepest.""" + jobs = [(chain, address) for chain, addresses in contracts.items() for address in sorted(addresses)] + + def one(job): + chain, address = job + try: + return http_json(f"https://api.dexscreener.com/token-pairs/v1/{chain}/{address}") or [] + except Exception as exc: + log(f"DexScreener {chain} {address[:10]}…: ошибка {exc}") + return [] + + with ThreadPoolExecutor(max_workers=4) as pool: + pairs = [p for chunk in pool.map(one, jobs) for p in chunk] + log(f"DexScreener: {len(pairs)} пар по {len(jobs)} контрактам") + return all_pairs(pairs) + + +def all_pairs(pairs: list[dict]) -> dict[tuple[str, str], list[DexPair]]: + """(chain, lower-case token address) -> every pool where the token is the BASE asset, deepest first.""" + out: dict[tuple[str, str], list[DexPair]] = {} + seen = set() + for p in pairs: + if p.get("pairAddress") in seen: + continue + seen.add(p.get("pairAddress")) + best = best_pairs([p]) + for key, pair in best.items(): + out.setdefault(key, []).append(pair) + for items in out.values(): + items.sort(key=lambda d: (-d.liquidity_usd, -d.volume_usd)) + return out + + +def parse_hyperliquid_spot(data) -> dict[str, DexPair]: + """Upper-case token name -> its USDC spot pair on HyperLiquid.""" + meta, ctxs = data + tokens = {t["index"]: t for t in meta["tokens"]} + out = {} + for market in meta["universe"]: + base_i, quote_i = market["tokens"] + if tokens.get(quote_i, {}).get("name") != "USDC" or market["index"] >= len(ctxs): + continue + ctx = ctxs[market["index"]] + price = _f(ctx.get("midPx")) or _f(ctx.get("markPx")) + name = tokens.get(base_i, {}).get("name", "").upper() + if not name or price <= 0: + continue + pair = DexPair("HyperLiquid", "hyperliquid", "hyperliquid", f"{name}/USDC", price, 0.0, + _f(ctx.get("dayNtlVlm")), tokens[base_i].get("tokenId", ""), + f"https://app.hyperliquid.xyz/trade/{market['name']}") + if name not in out or pair.volume_usd > out[name].volume_usd: + out[name] = pair + return out + + +def fetch_hyperliquid(log=print) -> dict[str, DexPair]: + try: + out = parse_hyperliquid_spot(http_json("https://api.hyperliquid.xyz/info", {"type": "spotMetaAndAssetCtxs"})) + log(f"HyperLiquid: спот-пар {len(out)}") + return out + except Exception as exc: + log(f"HyperLiquid: ошибка {exc}") + return {} + + +# -------------------------------------------------------------------------------------------- +# Matching +# -------------------------------------------------------------------------------------------- + +@dataclass +class Match: + symbol: str + name: str + cg_id: str + market_cap: float + cex: list[Listing] + cex_price: float # median price of one coin over the CEX listings + cex_volume_usd: float + dex: DexPair | None + dex_count: int # how many chains the token has a DEX pair on + diff_pct: float | None # (DEX - CEX) / CEX + status: str + pools: list[DexPair] = field(default_factory=list) # every DEX pool whose price agrees with the CEX + + @property + def exchanges(self) -> str: + return ", ".join(sorted(f"{l.exchange}" + (f"×{l.multiplier:g}" if l.multiplier != 1 else "") + for l in self.cex)) + + @property + def funding(self) -> float | None: + values = [l.funding for l in self.cex if l.funding is not None] + return max(values, key=abs) if values else None + + +def status_of(diff_pct: float | None) -> str: + if diff_pct is None: + return "нет на DEX" + if abs(diff_pct) <= MATCH_PCT: + return "совпадает" + if abs(diff_pct) <= CHECK_PCT: + return "проверить" + return "разные монеты?" + + +def contracts_for(coins: list[MemeCoin]) -> dict[str, set[str]]: + out: dict[str, set[str]] = {} + for coin in coins: + for platform, address in coin.platforms.items(): + chain = CHAINS.get(platform) + if chain: + out.setdefault(chain, set()).add(address.lower() if chain in EVM_CHAINS else address) + return out + + +def _agrees(price: float, ref: float, pct: float = CHECK_PCT) -> bool: + return price > 0 and ref > 0 and abs(math.log(price / ref)) <= math.log(1 + pct / 100) + + +def match(listings: list[Listing], memes: list[MemeCoin], dex_pairs: dict[tuple[str, str], list[DexPair]], + hl_pairs: dict[str, DexPair]) -> list[Match]: + by_symbol: dict[str, list[MemeCoin]] = {} + for coin in memes: + by_symbol.setdefault(coin.symbol, []).append(coin) + # Each CEX contract is tied to a coin by its own price: CAT and 1000CAT on one exchange can be two coins. + groups: dict[str, tuple[MemeCoin, list[Listing]]] = {} + for l in listings: + coin = pick_coin(l.base, l.price, by_symbol) + if coin is not None: + groups.setdefault(coin.cg_id, (coin, []))[1].append(l) + out = [] + for coin, items in groups.values(): + cex_price = statistics.median(l.price for l in items) + pools = [] + for platform, address in coin.platforms.items(): + chain = CHAINS.get(platform) + if chain: + pools += dex_pairs.get((chain, address.lower()), []) + hl = hl_pairs.get(coin.symbol) + if hl and _agrees(hl.price, cex_price): + pools.append(hl) + # The deepest pool whose price agrees with the CEX; a lone disagreeing pool is still shown, flagged. + agreeing = [p for p in pools if _agrees(p.price, cex_price)] + candidates = agreeing or pools + dex = max(candidates, key=lambda p: (p.liquidity_usd, p.volume_usd)) if candidates else None + diff = (dex.price / cex_price - 1) * 100 if dex else None + chains = len({p.chain for p in agreeing}) + out.append(Match(coin.symbol, coin.name, coin.cg_id, coin.market_cap, items, cex_price, + sum(l.volume_usd for l in items), dex, chains, diff, status_of(diff), agreeing)) + out.sort(key=lambda m: -m.cex_volume_usd) + return out + + +def scan(exchanges: list[str] | None = None, meme_pages: int = 4, log=print) -> list[Match]: + exchanges = exchanges or list(CEX_SOURCES) + listings = fetch_cex(exchanges, log) + memes = build_memes(fetch_memes(meme_pages, log), fetch_platforms(log=log)) + bases = {l.base for l in listings} + wanted = [c for c in memes if c.symbol in bases] + log(f"Мемкойнов с фьючерсами на CEX (по тикеру): {len(wanted)}") + dex_pairs = fetch_dexscreener(contracts_for(wanted), log) + hl_pairs = fetch_hyperliquid(log) + result = match(listings, wanted, dex_pairs, hl_pairs) + log(f"Готово: совпадений {len(result)}, из них на DEX {sum(m.dex is not None for m in result)}") + return result + + +# -------------------------------------------------------------------------------------------- +# Output +# -------------------------------------------------------------------------------------------- + +CSV_COLUMNS = ["symbol", "name", "coingecko_id", "market_cap_usd", "cex_exchanges", "cex_price", "cex_volume_24h_usd", + "max_funding", "dex_source", "dex_chain", "dex", "dex_pair", "dex_price", "dex_liquidity_usd", + "dex_volume_24h_usd", "dex_chains", "diff_pct", "status", "contract", "url"] + + +def to_row(m: Match) -> list: + d = m.dex + return [m.symbol, m.name, m.cg_id, f"{m.market_cap:.0f}", m.exchanges, f"{m.cex_price:.10g}", + f"{m.cex_volume_usd:.0f}", "" if m.funding is None else f"{m.funding:.6f}", + d.source if d else "", d.chain if d else "", d.dex if d else "", d.pair if d else "", + f"{d.price:.10g}" if d else "", f"{d.liquidity_usd:.0f}" if d else "", f"{d.volume_usd:.0f}" if d else "", + m.dex_count, "" if m.diff_pct is None else f"{m.diff_pct:+.2f}", m.status, d.contract if d else "", + d.url if d else ""] + + +def save_csv(matches: list[Match], path: Path = OUT_CSV) -> None: + with path.open("w", newline="", encoding="utf-8-sig") as f: + writer = csv.writer(f, delimiter=";") + writer.writerow(CSV_COLUMNS) + writer.writerows(to_row(m) for m in matches) + + +def human(value: float) -> str: + for unit, size in (("B", 1e9), ("M", 1e6), ("K", 1e3)): + if abs(value) >= size: + return f"{value / size:.1f}{unit}" + return f"{value:.0f}" + + +def print_table(matches: list[Match]) -> None: + print(f"{'Монета':12s} {'CEX фьючерсы':38s} {'Объём CEX':>9s} {'DEX':24s} {'Ликв.':>7s} {'Разница':>8s} Статус") + for m in matches: + d = m.dex + dex = f"{d.chain}/{d.dex}" if d else "—" + print(f"{m.symbol:12s} {m.exchanges[:38]:38s} {human(m.cex_volume_usd):>9s} {dex[:24]:24s} " + f"{human(d.liquidity_usd) if d else '':>7s} {'' if m.diff_pct is None else f'{m.diff_pct:+.2f}%':>8s} " + f"{m.status}") + + +# -------------------------------------------------------------------------------------------- +# Window +# -------------------------------------------------------------------------------------------- + +def run_window() -> None: + import tkinter as tk + from tkinter import messagebox, ttk + + root = tk.Tk() + root.title("Meme Matcher — мемкойны: фьючерсы CEX ↔ спот DEX") + root.geometry("1280x720") + state: dict = {"matches": [], "sort": ("cex_volume", True)} + + top = ttk.Frame(root, padding=6) + top.pack(fill="x") + ex_vars = {name: tk.BooleanVar(value=True) for name in CEX_SOURCES} + ttk.Label(top, text="Биржи:").pack(side="left") + for name, var in ex_vars.items(): + ttk.Checkbutton(top, text=name, variable=var).pack(side="left") + filters = ttk.Frame(root, padding=(6, 0)) + filters.pack(fill="x") + min_liq = tk.StringVar(value="10000") + min_vol = tk.StringVar(value="0") + pages = tk.StringVar(value="4") + only_dex = tk.BooleanVar(value=True) + only_match = tk.BooleanVar(value=False) + for label, var, width in (("Мин. ликвидность DEX, $", min_liq, 10), ("Мин. объём CEX за 24 ч, $", min_vol, 12), + ("Страниц мемов CoinGecko (×250)", pages, 4)): + ttk.Label(filters, text=label).pack(side="left", padx=(0, 4)) + ttk.Entry(filters, textvariable=var, width=width).pack(side="left", padx=(0, 12)) + ttk.Checkbutton(filters, text="Только есть на DEX", variable=only_dex, command=lambda: fill()).pack(side="left") + ttk.Checkbutton(filters, text="Только «совпадает»", variable=only_match, command=lambda: fill()).pack(side="left") + scan_btn = ttk.Button(filters, text="Обновить", command=lambda: start()) + scan_btn.pack(side="left", padx=8) + ttk.Button(filters, text="Сохранить CSV", command=lambda: export()).pack(side="left") + ttk.Button(filters, text="Опережение DEX…", command=lambda: open_leadlag()).pack(side="left", padx=8) + ttk.Button(filters, text="Автопоиск…", command=lambda: __import__("autoscan").open_window(root)).pack(side="left") + + def open_leadlag(): + import leadlag + leadlag.open_window(root, lambda: state["matches"]) + + columns = {"symbol": ("Монета", 90), "name": ("Название", 140), "cex": ("Фьючерсы CEX", 250), + "cex_volume": ("Объём CEX 24 ч", 100), "funding": ("Funding", 70), "dex": ("DEX", 150), + "pair": ("Пара", 110), "liquidity": ("Ликвидность", 90), "dex_volume": ("Объём DEX", 90), + "diff": ("Разница", 70), "status": ("Статус", 110), "mcap": ("Капитализация", 100)} + frame = ttk.Frame(root, padding=6) + frame.pack(fill="both", expand=True) + tree = ttk.Treeview(frame, columns=list(columns), show="headings") + for key, (title, width) in columns.items(): + tree.heading(key, text=title, command=lambda k=key: sort_by(k)) + tree.column(key, width=width, anchor="w") + tree.tag_configure("совпадает", background="#e8f7e8") + tree.tag_configure("проверить", background="#fff6d8") + tree.tag_configure("разные монеты?", background="#fde3e3") + scroll = ttk.Scrollbar(frame, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scroll.set) + tree.pack(side="left", fill="both", expand=True) + scroll.pack(side="right", fill="y") + status = tk.StringVar(value="Нажмите «Обновить». Двойной щелчок по строке открывает пару на DEX.") + ttk.Label(root, textvariable=status, padding=6).pack(fill="x") + + def keyf(m: Match, key: str): + d = m.dex + return {"symbol": m.symbol, "name": m.name, "cex": m.exchanges, "cex_volume": m.cex_volume_usd, + "funding": abs(m.funding or 0), "dex": f"{d.chain}/{d.dex}" if d else "", "pair": d.pair if d else "", + "liquidity": d.liquidity_usd if d else -1, "dex_volume": d.volume_usd if d else -1, + "diff": abs(m.diff_pct) if m.diff_pct is not None else 1e9, "status": m.status, + "mcap": m.market_cap}[key] + + def sort_by(key): + prev, desc = state["sort"] + state["sort"] = (key, not desc if prev == key else key in ("cex_volume", "liquidity", "dex_volume", "mcap")) + fill() + + def visible() -> list[Match]: + try: + liq, vol = float(min_liq.get() or 0), float(min_vol.get() or 0) + except ValueError: + liq = vol = 0.0 + out = [] + for m in state["matches"]: + if only_dex.get() and m.dex is None: + continue + if only_match.get() and m.status != "совпадает": + continue + if m.dex is not None and m.dex.source == "DexScreener" and m.dex.liquidity_usd < liq: + continue + if m.cex_volume_usd < vol: + continue + out.append(m) + key, desc = state["sort"] + return sorted(out, key=lambda m: keyf(m, key), reverse=desc) + + def fill(): + tree.delete(*tree.get_children()) + rows = visible() + for i, m in enumerate(rows): + d = m.dex + tree.insert("", "end", iid=str(i), tags=(m.status,), values=( + m.symbol, m.name, m.exchanges, human(m.cex_volume_usd), + "" if m.funding is None else f"{m.funding * 100:+.3f}%", + f"{d.chain}/{d.dex}" + (f" (+{m.dex_count - 1})" if m.dex_count > 1 else "") if d else "—", + d.pair if d else "", human(d.liquidity_usd) if d and d.liquidity_usd else ("" if not d else "—"), + human(d.volume_usd) if d else "", "" if m.diff_pct is None else f"{m.diff_pct:+.2f}%", m.status, + human(m.market_cap))) + state["rows"] = rows + total = len(state["matches"]) + on_dex = sum(m.dex is not None for m in state["matches"]) + same = sum(m.status == "совпадает" for m in state["matches"]) + if total: + status.set(f"Мемкойнов с фьючерсами: {total} · есть на DEX: {on_dex} · цена совпадает: {same} · " + f"показано: {len(rows)}") + + def open_row(_event=None): + sel = tree.selection() + if sel: + m = state["rows"][int(sel[0])] + if m.dex and m.dex.url: + webbrowser.open(m.dex.url) + + tree.bind("", open_row) + + def log(text): + root.after(0, status.set, text) + + def start(): + chosen = [n for n, v in ex_vars.items() if v.get()] + if not chosen: + messagebox.showwarning("Meme Matcher", "Выберите хотя бы одну биржу", parent=root) + return + try: + n_pages = max(1, min(20, int(pages.get()))) + except ValueError: + n_pages = 4 + scan_btn.configure(state="disabled") + + def work(): + try: + result = scan(chosen, n_pages, log) + save_csv(result) + root.after(0, done, result, "") + except Exception as exc: + root.after(0, done, None, str(exc)) + + threading.Thread(target=work, daemon=True).start() + + def done(result, error): + scan_btn.configure(state="normal") + if error: + status.set(f"Ошибка: {error}") + return + state["matches"] = result + fill() + + def export(): + save_csv(visible()) + status.set(f"Сохранено: {OUT_CSV}") + + root.after(200, start) + root.mainloop() + + +def main() -> None: + import sys + + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--once", action="store_true", help="print the table and save meme_matches.csv") + parser.add_argument("--pages", type=int, default=4, help="CoinGecko meme pages of 250 coins") + parser.add_argument("--exchanges", default=",".join(CEX_SOURCES), help="comma-separated CEX list") + args = parser.parse_args() + if args.once: + matches = scan([e for e in args.exchanges.split(",") if e in CEX_SOURCES], args.pages) + save_csv(matches) + print_table([m for m in matches if m.dex is not None]) + print(f"\nCSV: {OUT_CSV}") + else: + run_window() + + +if __name__ == "__main__": + main() diff --git a/meme_matcher/tests/test_autoscan.py b/meme_matcher/tests/test_autoscan.py new file mode 100644 index 0000000..549a0ea --- /dev/null +++ b/meme_matcher/tests/test_autoscan.py @@ -0,0 +1,94 @@ +"""Autonomous search: coin rotation, leaders first, simulator connections, history.""" + +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import autoscan as au # noqa: E402 +import leadlag as ll # noqa: E402 + + +def target(symbol, cex="MEXC", chain="solana", cex_symbol=None): + return ll.Target(symbol, symbol.lower(), cex, cex_symbol or f"{symbol}_USDT", 1.0, chain, chain, f"POOL{symbol}", + "TOKEN", "pumpswap", 500) + + +def result(symbol, verdict=au.LEAD_VERDICT): + return ll.LeadResult(symbol, "MEXC", "solana/pumpswap", 900, 100, 100, 30, {0: 0.1}, 2, 0.0, {5: 0.1}, + {5: 0.6}, 2.5, 70.0, 0, verdict) + + +class AutoscanTests(unittest.TestCase): + def test_rotation_covers_everyone_and_leaders_come_first(self): + cands = [target(s) for s in "ABCDEFG"] + first, off = au.choose_targets(cands, [], 0, 3) + second, off = au.choose_targets(cands, [], off, 3) + third, off = au.choose_targets(cands, [], off, 3) + seen = [t.symbol for t in first + second + third] + self.assertEqual(set(seen), set("ABCDEFG")) + with_leader, _ = au.choose_targets(cands, ["F"], 0, 3) + self.assertEqual(with_leader[0].symbol, "F") + self.assertEqual(len({t.symbol for t in with_leader}), 3) + + def test_simulator_connection_mapping(self): + conn = au.simulator_connection(target("CLAUDIA")) + self.assertEqual(conn, {"lead_market": "raydium", "lead_ticker": "CLAUDIAUSDTM", "lead_pool": "POOLCLAUDIA", + "follow_exchange": "mexc", "follow_ticker": "CLAUDIA_USDT"}) + self.assertEqual(au.simulator_connection(target("X", cex="Binance", cex_symbol="1000XUSDT"))["follow_ticker"], + "1000XUSDT") + self.assertIsNone(au.simulator_connection(target("X", cex="Gate"))) + self.assertIsNone(au.simulator_connection(target("X", chain="bsc"))) + + def test_add_connection_keeps_existing_and_skips_duplicates(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "lead_connections.json" + old = {"lead_market": "futures", "lead_ticker": "MARSCOINUSDTM", "lead_pool": "", "follow_exchange": "bybit", + "follow_ticker": "MARSCOINUSDT"} + path.write_text(json.dumps([old]), encoding="utf-8") + conn = au.simulator_connection(target("SI")) + self.assertTrue(au.add_connection(conn, path)) + self.assertFalse(au.add_connection(conn, path)) + saved = json.loads(path.read_text(encoding="utf-8")) + self.assertEqual(saved, [old, conn]) + + def test_loop_survives_the_recording_and_errors(self): + """record() sets the stop event it is given; the loop must keep running for the next cycle.""" + import threading + from unittest import mock + calls = {"n": 0} + loop_stop = threading.Event() + + def fake_cycle(st, *args): + calls["n"] += 1 + given = threading.Event() + given.set() # what record() does with its own event + if calls["n"] == 2: + raise RuntimeError("boom") # an error in a cycle is logged, not fatal + if calls["n"] >= 3: + loop_stop.set() + + with tempfile.TemporaryDirectory() as folder, \ + mock.patch.object(au, "_cycle", fake_cycle), mock.patch.object(au, "LOG_FILE", Path(folder) / "l.log"), \ + mock.patch.object(loop_stop, "wait", lambda s: None): + au.run(1, 1, 1, 0.15, stop=loop_stop) + self.assertEqual(calls["n"], 3) + + def test_history_and_leaders(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "h.csv" + targets = {s: target(s) for s in ("A", "B", "C")} + au.append_history(1, [result("A"), result("B", "одновременно / нет опережения")], targets, {"A": "да"}, path) + au.append_history(2, [result("C")], targets, {}, path) + self.assertEqual(set(au.read_leaders(path)), {"A", "C"}) + self.assertEqual(au.last_cycle(path), 2) + self.assertIn("да", path.read_text(encoding="utf-8-sig")) + + +if __name__ == "__main__": + unittest.main() diff --git a/meme_matcher/tests/test_leadlag.py b/meme_matcher/tests/test_leadlag.py new file mode 100644 index 0000000..be2e1be --- /dev/null +++ b/meme_matcher/tests/test_leadlag.py @@ -0,0 +1,137 @@ +"""Offline tests for the DEX → CEX lead-lag recorder and analysis on synthetic prices.""" + +from __future__ import annotations + +import sys +import tempfile +import threading +import unittest +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import leadlag as ll # noqa: E402 +import meme_matcher as mm # noqa: E402 + +T0 = 1_800_000_000 + + +def target(symbol="WIF", cex="Binance", cex_symbol="WIFUSDT", multiplier=1.0): + return ll.Target(symbol, "dogwifcoin", cex, cex_symbol, multiplier, "solana", "solana", "POOL", "TOKEN", + "raydium", 600) + + +def walk(seconds=1500, step=0.004, seed=1): + rng = np.random.default_rng(seed) + return 1.0 * np.exp(np.cumsum(rng.choice([-step, 0.0, step], size=seconds, p=[0.3, 0.4, 0.3]))) + + +def trades(path, delay_s, offset=0.3): + """One trade per second at the path's price, `delay_s` seconds late.""" + return [(T0 + i + delay_s + offset, float(p)) for i, p in enumerate(path)] + + +def dex_rows(path, delay_s=0, publish_delay=45): + return [(T0 + i + delay_s + 0.5, float(p), 100.0, "buy", T0 + i + delay_s + publish_delay) + for i, p in enumerate(path)] + + +class AnalysisTests(unittest.TestCase): + def test_dex_leading_by_three_seconds_is_found(self): + path = walk() + r = ll.analyze_coin(target(), trades(path, 3), dex_rows(path, 0)) + self.assertEqual(r.verdict, "DEX опережает ≥1 с", r) + self.assertEqual(r.best_lag, 3) + self.assertGreater(r.follow[5], 0) + self.assertGreater(r.hit[5], 0.7) # later random steps add noise on top of the copied move + self.assertAlmostEqual(r.dex_delay_s, 45, delta=1) + + def test_futures_leading_is_not_called_a_dex_lead(self): + path = walk(seed=2) + r = ll.analyze_coin(target(), trades(path, 0), dex_rows(path, 3)) + self.assertEqual(r.verdict, "фьючерс опережает") + self.assertEqual(r.best_lag, -3) + + def test_simultaneous_moves_are_no_lead(self): + path = walk(seed=3) + r = ll.analyze_coin(target(), trades(path, 0, offset=0.6), dex_rows(path, 0)) + self.assertEqual(r.verdict, "одновременно / нет опережения") + self.assertIn(r.best_lag, (0, 1)) # a sub-second reaction may land in the next second + + def test_too_little_data(self): + r = ll.analyze_coin(target(), [(T0, 1.0)], []) + self.assertEqual(r.verdict, "мало данных") + + def test_results_csv(self): + path = walk(seed=4) + res = ll.analyze([target()], {"WIF": trades(path, 2)}, {"WIF": dex_rows(path)}) + with tempfile.TemporaryDirectory() as folder: + out = Path(folder) / "r.csv" + ll.save_results(res, out) + self.assertIn("WIF;DEX опережает", out.read_text(encoding="utf-8-sig")) + + +class DataTests(unittest.TestCase): + def test_gecko_trades_take_our_token_price(self): + data = {"data": [ + {"id": "a", "attributes": {"block_timestamp": "2026-10-16T16:53:05Z", "from_token_address": "TOKEN", + "to_token_address": "SOL", "price_from_in_usd": "0.15", + "price_to_in_usd": "104", "volume_in_usd": "10", "kind": "sell"}}, + {"id": "b", "attributes": {"block_timestamp": "2026-10-16T16:53:06Z", "from_token_address": "SOL", + "to_token_address": "token", "price_from_in_usd": "104", + "price_to_in_usd": "0.16", "volume_in_usd": "20", "kind": "buy"}}, + {"id": "c", "attributes": {"block_timestamp": "2026-10-16T16:53:07Z", "from_token_address": "X", + "to_token_address": "Y", "price_from_in_usd": "1", "price_to_in_usd": "1"}}]} + rows = ll.parse_gecko_trades(data, "TOKEN") + self.assertEqual([(r[0], r[2], r[4]) for r in rows], [("a", 0.15, "sell"), ("b", 0.16, "buy")]) + + def test_exchange_messages_are_parsed_per_coin(self): + stop = threading.Event() + for exchange, symbol, msg in ( + ("Binance", "1000PEPEUSDT", {"data": {"e": "aggTrade", "s": "1000PEPEUSDT", "T": 1000, "p": "0.004"}}), + ("Bybit", "1000PEPEUSDT", {"topic": "publicTrade.1000PEPEUSDT", + "data": [{"s": "1000PEPEUSDT", "T": 1000, "p": "0.004"}]}), + ("Gate", "PEPE_USDT", {"channel": "futures.trades", "event": "update", + "result": [{"contract": "PEPE_USDT", "create_time_ms": 1000, + "price": "0.000004"}]}), + ("MEXC", "PEPE_USDT", {"channel": "push.deal", "symbol": "PEPE_USDT", + "data": [{"p": 0.000004, "t": 1000}]})): + mult = 1000.0 if symbol.startswith("1000") else 1.0 + t = target("PEPE", exchange, symbol, mult) + rec = ll.Recorder([t]) + ll.CexFeed(exchange, [t], rec, stop).handle(msg) + self.assertEqual(len(rec.cex["PEPE"]), 1, exchange) + ts, price = rec.cex["PEPE"][0] + self.assertEqual(ts, 1.0) + self.assertAlmostEqual(price, 0.000004) + + def test_dedupe_save_and_load(self): + t = target() + rec = ll.Recorder([t]) + self.assertTrue(rec.add_dex("WIF", "id1", T0, 1.0, 5.0, "buy")) + self.assertFalse(rec.add_dex("WIF", "id1", T0, 1.0, 5.0, "buy")) + rec.add_cex("WIF", T0 + 0.1, 1.01) + with tempfile.TemporaryDirectory() as folder: + path = rec.save(Path(folder) / "r.jsonl.gz") + targets, cex, dex, meta = ll.load(path) + self.assertEqual(targets[0].symbol, "WIF") + self.assertEqual(len(cex["WIF"]), 1) + self.assertEqual(dex["WIF"][0][1], 1.0) + + def test_pick_targets_needs_fast_chain_activity_and_supported_cex(self): + def match(symbol, chain, txns, exchange="Binance", status="совпадает"): + pool = mm.DexPair("DexScreener", chain, "raydium", f"{symbol}/SOL", 1.0, 1e6, 1e6, "TOKEN", "", + "POOL", txns) + listing = mm.Listing(exchange, f"{symbol}USDT", symbol, 1, 1.0, 1e6) + return mm.Match(symbol, symbol, symbol.lower(), 1e6, [listing], 1.0, 1e6, pool, 1, 0.0, status, [pool]) + + picked = ll.pick_targets([match("A", "solana", 500), match("B", "ethereum", 900), match("C", "solana", 50), + match("D", "bsc", 300, exchange="BingX"), match("E", "base", 800), + match("F", "solana", 900, status="проверить")]) + self.assertEqual([t.symbol for t in picked], ["E", "A"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/meme_matcher/tests/test_meme_matcher.py b/meme_matcher/tests/test_meme_matcher.py new file mode 100644 index 0000000..75ed6e4 --- /dev/null +++ b/meme_matcher/tests/test_meme_matcher.py @@ -0,0 +1,117 @@ +"""Offline tests: symbol parsing, coin identification by price, DEX pool choice, statuses, CSV.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import meme_matcher as mm # noqa: E402 + + +def coin(cg_id, symbol, price, platforms=None, mcap=1e6): + return mm.MemeCoin(cg_id, symbol, cg_id, price, mcap, platforms or {}) + + +def ds_pair(chain, address, price, liquidity, symbol="X", pair_address=None, dex="uniswap"): + return {"chainId": chain, "dexId": dex, "pairAddress": pair_address or f"{address}-{liquidity}", + "priceUsd": str(price), "liquidity": {"usd": liquidity}, "volume": {"h24": liquidity / 10}, + "baseToken": {"address": address, "symbol": symbol}, "quoteToken": {"symbol": "WETH"}, + "url": f"https://dexscreener.com/{chain}/{address}"} + + +class SymbolTests(unittest.TestCase): + def test_size_prefixes_and_suffixes(self): + self.assertEqual(mm.split_base("1000PEPE"), ("PEPE", 1000.0)) + self.assertEqual(mm.split_base("1000000BABYDOGE"), ("BABYDOGE", 1_000_000.0)) + self.assertEqual(mm.split_base("1MBABYDOGE"), ("BABYDOGE", 1_000_000.0)) + self.assertEqual(mm.split_base("SHIB1000"), ("SHIB", 1000.0)) + self.assertEqual(mm.split_base("1INCH"), ("1INCH", 1.0)) + self.assertEqual(mm.split_base("WIF"), ("WIF", 1.0)) + + def test_exchange_parsers_give_price_per_coin(self): + bybit = mm.parse_bybit({"result": {"list": [ + {"symbol": "1000PEPEUSDT", "lastPrice": "0.004", "turnover24h": "100", "fundingRate": "0.0001"}, + {"symbol": "BTCPERP", "lastPrice": "1", "turnover24h": "1"}]}}) + self.assertEqual(len(bybit), 1) + self.assertAlmostEqual(bybit[0].price, 0.000004) + self.assertEqual((bybit[0].base, bybit[0].funding), ("PEPE", 0.0001)) + okx = mm.parse_okx({"data": [{"instId": "WIF-USDT-SWAP", "last": "2", "volCcy24h": "50"}]}) + self.assertEqual((okx[0].base, okx[0].volume_usd), ("WIF", 100.0)) + gate = mm.parse_gate([{"contract": "BONK_USDT", "last": "0.00002", "volume_24h_quote": "7"}]) + self.assertEqual(gate[0].base, "BONK") + binance = mm.parse_binance([{"symbol": "BTCUSDT_261225", "lastPrice": "1", "quoteVolume": "1"}, + {"symbol": "DOGEUSDT", "lastPrice": "0.1", "quoteVolume": "5"}]) + self.assertEqual([l.base for l in binance], ["DOGE"]) + + +class MatchTests(unittest.TestCase): + def test_coin_is_picked_by_price_among_same_tickers(self): + by_symbol = {"PEPE": [coin("baby-pepe", "PEPE", 0.5), coin("pepe", "PEPE", 0.000004)]} + self.assertEqual(mm.pick_coin("PEPE", 0.0000041, by_symbol).cg_id, "pepe") + self.assertIsNone(mm.pick_coin("PEPE", 0.01, by_symbol)) # no coin at that price + self.assertIsNone(mm.pick_coin("DOGE", 0.1, by_symbol)) # not a meme coin + + def test_two_contracts_with_one_ticker_are_two_coins(self): + listings = [mm.Listing("Binance", "CATUSDT", "CAT", 1, 0.02, 10), + mm.Listing("Binance", "1000CATUSDT", "CAT", 1000, 0.000005, 20)] + memes = [coin("cat-a", "CAT", 0.02), coin("simons-cat", "CAT", 0.000005)] + result = {m.cg_id: m for m in mm.match(listings, memes, {}, {})} + self.assertEqual(set(result), {"cat-a", "simons-cat"}) + self.assertEqual(len(result["simons-cat"].cex), 1) + + def test_deepest_agreeing_pool_wins_and_fakes_are_flagged(self): + address = "0xAbC" + memes = [coin("pepe", "PEPE", 0.000004, {"ethereum": address, "solana": "SoLpEpE"})] + pools = mm.all_pairs([ + ds_pair("ethereum", address, 0.000004, 1_000_000), + ds_pair("ethereum", address, 0.0000041, 5_000_000), + ds_pair("solana", "SoLpEpE", 0.9, 50_000_000), # a fake: price way off, ignored + ]) + listing = mm.Listing("Bybit", "1000PEPEUSDT", "PEPE", 1000, 0.000004, 100) + m = mm.match([listing], memes, pools, {})[0] + self.assertEqual(m.dex.liquidity_usd, 5_000_000) + self.assertEqual(m.status, "совпадает") + self.assertEqual(m.dex_count, 1) + # only a fake pool: still shown, but flagged + fake_only = mm.all_pairs([ds_pair("solana", "SoLpEpE", 0.9, 1_000)]) + m = mm.match([listing], memes, fake_only, {})[0] + self.assertEqual(m.status, "разные монеты?") + + def test_pool_where_token_is_quote_is_ignored(self): + pair = ds_pair("ethereum", "0xother", 1.0, 1e6) + pair["quoteToken"] = {"address": "0xabc", "symbol": "PEPE"} + self.assertNotIn(("ethereum", "0xabc"), mm.all_pairs([pair])) + + def test_hyperliquid_spot_and_status(self): + data = ({"tokens": [{"index": 0, "name": "USDC"}, {"index": 1, "name": "WIF", "tokenId": "0x1"}], + "universe": [{"tokens": [1, 0], "name": "@7", "index": 0}]}, + [{"midPx": "1.01", "dayNtlVlm": "5000"}]) + hl = mm.parse_hyperliquid_spot(data) + listing = mm.Listing("OKX", "WIF-USDT-SWAP", "WIF", 1, 1.0, 50) + m = mm.match([listing], [coin("dogwifcoin", "WIF", 1.0)], {}, hl)[0] + self.assertEqual((m.dex.source, m.status), ("HyperLiquid", "совпадает")) + self.assertEqual(mm.status_of(None), "нет на DEX") + self.assertEqual(mm.status_of(10.0), "проверить") + self.assertEqual(mm.status_of(-40.0), "разные монеты?") + + def test_contracts_keep_case_for_solana_only(self): + out = mm.contracts_for([coin("x", "X", 1, {"ethereum": "0xAbC", "solana": "AbC", "unknown-chain": "q"})]) + self.assertEqual(out, {"ethereum": {"0xabc"}, "solana": {"AbC"}}) + + def test_csv(self): + listing = mm.Listing("Bybit", "WIFUSDT", "WIF", 1, 1.0, 50, 0.0001) + m = mm.match([listing], [coin("dogwifcoin", "WIF", 1.0)], {}, {})[0] + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "m.csv" + mm.save_csv([m], path) + text = path.read_text(encoding="utf-8-sig") + self.assertIn("WIF;dogwifcoin", text) + self.assertIn("нет на DEX", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/minorder.py b/minorder.py new file mode 100644 index 0000000..cf7ce3a --- /dev/null +++ b/minorder.py @@ -0,0 +1,224 @@ +"""The smallest orders the five exchanges accept, spot and USDT perpetual, and from them the smallest trade amount a +spot–futures trade can be entered with: the spot buy must reach the spot minimum (USDT and coins) and the coins +bought must make at least the perp's minimum lot (and its minimum notional) — both legs, or the trade is not made. + +The rules come from the exchanges' public instrument lists (no keys), loaded in the background and renewed hourly. +Paper and real trading check the same figure, so the paper trades are only those a real account could make. +""" + +from __future__ import annotations + +import math +import threading +import time + +import arb + +REFRESH_S = 3600.0 +RETRY_S = 300.0 +MARGIN = 1.02 # prices move between the check and the order, and the lot is rounded down +AUTOLOAD = False # the program turns it on; tests fill the rules themselves (no network) + + +def _f(v, default: float = 0.0) -> float: + try: + return float(v) + except (TypeError, ValueError): + return default + + +def _units(symbol_base: str) -> float: + return arb.split_base(symbol_base)[1] + + +# --- loaders: {key: rule}; spot keyed by base coin, perp by the symbol the price lists use -------------------------- +# spot rule: {"usd": smallest order in USDT, "coins": smallest quantity}; perp rule: {"coins": smallest order in +# coins (lot × contract size), "usd": smallest notional} +def _bybit(category: str) -> dict: + out, cursor = {}, "" + while True: + res = arb._get(f"https://api.bybit.com/v5/market/instruments-info?category={category}&limit=1000" + + (f"&cursor={cursor}" if cursor else ""))["result"] + for x in res["list"]: + if x.get("quoteCoin") != "USDT" or x.get("status") != "Trading": + continue + lot = x.get("lotSizeFilter") or {} + if category == "spot": + out[x["baseCoin"]] = {"usd": _f(lot.get("minOrderAmt")), "coins": _f(lot.get("minOrderQty"))} + else: + out[x["symbol"]] = {"coins": max(_f(lot.get("minOrderQty")), _f(lot.get("qtyStep"))) + * _units(x["symbol"][:-4]), "usd": _f(lot.get("minNotionalValue"))} + cursor = res.get("nextPageCursor") or "" + if not cursor or not res["list"]: + return out + + +def _binance_spot() -> dict: + out = {} + for s in arb._get("https://api.binance.com/api/v3/exchangeInfo?symbolStatus=TRADING")["symbols"]: + if s.get("quoteAsset") != "USDT": + continue + f = {x["filterType"]: x for x in s.get("filters", [])} + notional = f.get("NOTIONAL") or f.get("MIN_NOTIONAL") or {} + out[s["baseAsset"]] = {"usd": _f(notional.get("minNotional")), "coins": _f((f.get("LOT_SIZE") or {}).get("minQty"))} + return out + + +def _binance_fut() -> dict: + out = {} + for s in arb._get("https://fapi.binance.com/fapi/v1/exchangeInfo")["symbols"]: + if s.get("quoteAsset") != "USDT" or s.get("status") != "TRADING": + continue + f = {x["filterType"]: x for x in s.get("filters", [])} + lot = f.get("MARKET_LOT_SIZE") if _f((f.get("MARKET_LOT_SIZE") or {}).get("stepSize")) > 0 else f.get("LOT_SIZE", {}) + out[s["symbol"]] = {"coins": max(_f(lot.get("minQty")), _f(lot.get("stepSize"))) * _units(s["symbol"][:-4]), + "usd": _f((f.get("MIN_NOTIONAL") or {}).get("notional"))} + return out + + +def _mexc_spot() -> dict: + out = {} + for s in arb._get("https://api.mexc.com/api/v3/exchangeInfo")["symbols"]: + if s.get("quoteAsset") != "USDT": + continue + out[s["baseAsset"]] = {"usd": _f(s.get("quoteAmountPrecisionMarket") or s.get("quoteAmountPrecision")), + "coins": _f(s.get("baseSizePrecision"))} + return out + + +def _mexc_fut() -> dict: + out = {} + for c in arb._get("https://contract.mexc.com/api/v1/contract/detail")["data"]: + if c.get("quoteCoin") != "USDT": + continue + out[c["symbol"]] = {"coins": _f(c.get("contractSize"), 1) * _units(c["symbol"][:-5]) * max(1.0, _f(c.get("minVol"), 1)), + "usd": 0.0} + return out + + +def _htx_spot() -> dict: + out = {} + for s in arb._get("https://api.huobi.pro/v1/settings/common/market-symbols")["data"]: + if s.get("qc") != "usdt" or s.get("state") != "online": + continue + # market buy: «minov» USDT; the market sale later: «smminoa» coins + out[s["bc"].upper()] = {"usd": _f(s.get("minov")), "coins": _f(s.get("smminoa") or s.get("minoa"))} + return out + + +def _htx_fut() -> dict: + out = {} + for c in arb._get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]: + if not c["contract_code"].endswith("-USDT"): + continue + out[c["contract_code"]] = {"coins": _f(c.get("contract_size"), 1) * _units(c["contract_code"][:-5]), "usd": 0.0} + return out + + +def _gate_spot() -> dict: + out = {} + for s in arb._get("https://api.gateio.ws/api/v4/spot/currency_pairs"): + if s.get("quote") != "USDT" or s.get("trade_status") not in (None, "tradable"): + continue + out[s["base"]] = {"usd": _f(s.get("min_quote_amount")), "coins": _f(s.get("min_base_amount"))} + return out + + +def _gate_fut() -> dict: + out = {} + for c in arb._get("https://api.gateio.ws/api/v4/futures/usdt/contracts"): + out[c["name"]] = {"coins": _f(c.get("quanto_multiplier"), 1) * _units(c["name"][:-5]) + * max(1.0, _f(c.get("order_size_min"), 1)), "usd": 0.0} + return out + + +LOADERS = {("Bybit", "spot"): lambda: _bybit("spot"), ("Bybit", "fut"): lambda: _bybit("linear"), + ("Binance", "spot"): _binance_spot, ("Binance", "fut"): _binance_fut, + ("MEXC", "spot"): _mexc_spot, ("MEXC", "fut"): _mexc_fut, + ("HTX", "spot"): _htx_spot, ("HTX", "fut"): _htx_fut, + ("Gate", "spot"): _gate_spot, ("Gate", "fut"): _gate_fut} + + +class Rules: + def __init__(self) -> None: + self.data: dict[tuple[str, str], dict] = {} + self.loaded: dict[tuple[str, str], float] = {} # when loaded (or when the last try failed) + self.loading: set = set() + self.lock = threading.Lock() + + def set(self, exchange: str, market: str, rules: dict) -> None: + with self.lock: + self.data[(exchange, market)] = rules + self.loaded[(exchange, market)] = time.time() + + def _get(self, exchange: str, market: str) -> dict: + key = (exchange, market) + if AUTOLOAD and key in LOADERS: + with self.lock: + stale = time.time() - self.loaded.get(key, 0.0) > (REFRESH_S if key in self.data else RETRY_S) + start = stale and key not in self.loading + if start: + self.loading.add(key) + if start: + threading.Thread(target=self._load, args=(key,), daemon=True).start() + return self.data.get(key) or {} + + def _load(self, key) -> None: + try: + rules = LOADERS[key]() + if rules: + self.set(*key, rules) + except Exception: + with self.lock: + self.loaded[key] = time.time() # tried: again in RETRY_S + finally: + with self.lock: + self.loading.discard(key) + + def spot(self, exchange: str, base: str) -> dict | None: + return self._get(exchange, "spot").get(base) + + def fut(self, exchange: str, symbol: str) -> dict | None: + return self._get(exchange, "fut").get(symbol) + + def min_entry(self, spot_ex: str, base: str, spot_ask: float, fut_ex: str, fut_symbol: str, fut_bid: float, + spot_fee_pct: float) -> dict | None: + """The smallest trade amount, $, both legs accept: {"usd": total, "spot": $ the spot leg needs (None: + unknown), "fut": $ the perp leg needs}; None when neither exchange's rules are known yet.""" + sr, fr = self.spot(spot_ex, base), self.fut(fut_ex, fut_symbol) + if sr is None and fr is None or spot_ask <= 0 or fut_bid <= 0: + return None + keep = 1 - spot_fee_pct / 100 # the buy fee is taken in coins + spot_usd = None if sr is None else max(sr["usd"], sr["coins"] * spot_ask / keep) + fut_usd = None + if fr is not None: # the coins bought must make the perp's smallest order + coins = max(fr["coins"], fr["usd"] / fut_bid if fr["usd"] else 0.0) + fut_usd = coins * spot_ask / keep + need = max(v for v in (spot_usd, fut_usd) if v is not None) * MARGIN + return {"usd": math.ceil(need * 100) / 100, "spot": spot_usd, "fut": fut_usd} + + + def min_entry_ss(self, spot_ex: str, base: str, spot_ask: float, sell_ex: str, sell_bid: float, + spot_fee_pct: float) -> dict | None: + """Spot–spot: the buy on A's spot and the sale of the same coins on B's spot must both pass their spot + minimums ("fut" = what B's sale needs).""" + ra, rb = self.spot(spot_ex, base), self.spot(sell_ex, base) + if ra is None and rb is None or spot_ask <= 0 or sell_bid <= 0: + return None + keep = 1 - spot_fee_pct / 100 + buy_usd = None if ra is None else max(ra["usd"], ra["coins"] * spot_ask / keep) + sell_usd = None if rb is None else max(rb["coins"], rb["usd"] / sell_bid if rb["usd"] else 0.0) * spot_ask / keep + need = max(v for v in (buy_usd, sell_usd) if v is not None) * MARGIN + return {"usd": math.ceil(need * 100) / 100, "spot": buy_usd, "fut": sell_usd} + + +RULES = Rules() + + +def too_small(amount: float, m: dict | None, spot_ex: str, fut_ex: str, b_leg: str = "фьюч") -> str: + """Why `amount` cannot enter the trade ("" when it can, or when the rules are not known).""" + if m is None or amount >= m["usd"]: + return "" + parts = ([f"спот {spot_ex} ≥ {m['spot']:.2f} $"] if m["spot"] is not None else []) + \ + ([f"{b_leg} {fut_ex} ≥ {m['fut']:.2f} $"] if m["fut"] is not None else []) + return f"сумма {amount:g} $ меньше мин. входа {m['usd']:.2f} $ ({', '.join(parts)})" diff --git a/real_mirror.py b/real_mirror.py new file mode 100644 index 0000000..5898583 --- /dev/null +++ b/real_mirror.py @@ -0,0 +1,574 @@ +"""Real trading for the «Симулятор» tab: a paper position the simulator opens on a coin's futures exchange is repeated +with a real market order of the same size and closed with a real reduce-only order when the paper one closes. + +Strictly one real trade per coin at a time: while real mode is on, the simulator opens nothing new on the coin until +the previous real trade is closed AND the exchange shows no position left on the symbol (`gate`). A paper position +whose real order did not go through is closed at once, so paper and real trades stay one to one. + +Results (prices, fees) are the exchange's own fills; `exact` is False where the exchange did not report a figure. +- the tab-wide switch is in web_sim_data/real_simulator.json; it gates new trades only — an open real trade is + always closed with its paper twin; +- real positions are saved (web_sim_data/real_positions_.json); paper positions do not survive a restart, so + a saved real position is closed right after a restart («осиротевшая»); +- every order and every error goes to web_sim_data/real_orders.jsonl (journal on the page). +""" + +from __future__ import annotations + +import json +import queue +import threading +import time +from pathlib import Path + +import live + +ROOT = Path(__file__).resolve().parent +DATA_DIR = ROOT / "web_sim_data" +SETTINGS_FILE = DATA_DIR / "real_simulator.json" +JOURNAL = DATA_DIR / "real_orders.jsonl" +_journal_lock = threading.Lock() +RECENT: list[dict] = [] # last events of both tabs, newest last + + +def journal(tab: str, exchange: str, coin: str, action: str, ok: bool, text: str, **extra) -> dict: + event = {"time": time.time(), "tab": tab, "exchange": exchange, "coin": coin, "action": action, "ok": ok, + "text": text, **extra} + with _journal_lock: + RECENT.append(event) + del RECENT[:-300] + try: + DATA_DIR.mkdir(exist_ok=True) + with JOURNAL.open("a", encoding="utf-8") as f: + f.write(json.dumps(event, ensure_ascii=False) + "\n") + except OSError: + pass + return event + + +def load_recent(limit: int = 300) -> None: + try: + lines = JOURNAL.read_text(encoding="utf-8").splitlines()[-limit:] + except OSError: + return + with _journal_lock: + RECENT[:] = [json.loads(x) for x in lines if x.strip()] + + +DEFAULT_SL_PCT = 1.5 # stop-loss of a real position on the exchange, % from the entry +DEFAULT_MAX_PING_MS = 400.0 # no new entry while the round trip to the exchange is above this (0 = no check) +FEES: dict[str, float] = {} # exchange → real taker rate %, measured from the exchange's own fills +FEE_LISTENERS: list = [] # fn(exchange, pct): called when a new real rate is measured + + +def load_settings() -> dict: + """{"coins": {coin_key: {"on": bool, "since": t}}, "exchange_tpsl": bool} — real mode is per coin; + `since` = from when the coin's real statistics are taken from the exchange (first switch-on or a reset).""" + s = {"coins": {}, "exchange_tpsl": True, "auto_transfer": True, "sl_pct": DEFAULT_SL_PCT, + "max_ping_ms": DEFAULT_MAX_PING_MS, "fees": {}} + try: + s.update(json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))) + except (OSError, ValueError): + pass + s.pop("enabled", None) # the old tab-wide switch: real mode is per coin now + return s + + +def save_settings(values: dict) -> str: + s = load_settings() + for key in ("exchange_tpsl", "auto_transfer"): + if key in values: + s[key] = values[key] in (True, "true", 1, "1") + if "sl_pct" in values: + try: + v = float(values["sl_pct"]) + except (TypeError, ValueError): + return "неверный стоп-лосс" + if not 0 <= v <= 50: + return "стоп-лосс должен быть от 0 до 50 %" + s["sl_pct"] = v + if "max_ping_ms" in values: + try: + v = float(values["max_ping_ms"]) + except (TypeError, ValueError): + return "неверный порог пинга" + if not 0 <= v <= 10000: + return "порог пинга должен быть от 0 до 10000 мс" + s["max_ping_ms"] = v + for ex, pct in (values.get("fee") or {}).items(): + s.setdefault("fees", {})[ex] = round(float(pct), 5) + coin = values.get("coin") + if coin: + c = s["coins"].setdefault(str(coin), {"on": False, "since": 0.0}) + if "enabled" in values: + c["on"] = values["enabled"] in (True, "true", 1, "1") + if c["on"] and not c.get("since"): + c["since"] = time.time() + if values.get("reset_stats"): + c["since"] = time.time() + DATA_DIR.mkdir(exist_ok=True) + SETTINGS_FILE.write_text(json.dumps(s), encoding="utf-8") + 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.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 (OSError, ValueError): + 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.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 + + # --- 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: + 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 time.time() < self.paused_until: + return # real mode off, or a real trade still runs (gate was bypassed) + self.state = "opening" + units = symbol_units(self.symbol) + self.position = {"uid": pos.uid, "side": pos.side, "coins": pos.qty * units, + "paper_entry": pos.entry / units, "opened": time.time(), + # the paper take-profit as a distance from the entry: the real TP is placed at + # the same distance from the REAL fill price, not at the paper price + "tp_pct": (pos.target / pos.entry - 1) * 100 if getattr(pos, "target", None) else None, + "ping": self.ping()} + self.jobs.put(("open", None)) + elif event == "close" and self.position and self.position.get("uid") == pos.uid: + self.jobs.put(("close", "закрыта в симуляторе")) + + # --- 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 == "watch": + self._watch() + except Exception as exc: # never let the worker die + with self.lock: + self.problem = f"сбой: {exc}" + 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.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 + 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) and c is not None: + # accepted, fill not confirmed: the exchange's position decides + try: + held = abs(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 + else: + self._top_up_futures(c, str(exc), pos["coins"] * pos["paper_entry"]) + self._failed_open(str(exc)) + return + # the exchange's real fee rate (it decides how far the TP has to be, and the paper model uses it too) + fee_pct = fill.fee_usd / (fill.coins * fill.price) * 100 if fill.exact and fill.coins and fill.price else None + if fee_pct: + self._record_fee(fee_pct) + notes = [] + sl_set = bool(sl) and getattr(fill, "tpsl", "") == "на бирже" + if sl: + notes.append(f"SL {sl:.10g} (−{sl_pct:g}%) на бирже" if sl_set else f"SL НЕ выставлен: {fill.tpsl or 'нет ответа'}") + tp_id = "" + if use_tpsl and pos.get("tp_pct") is not None: + # TP: a reduce-only LIMIT order at the paper distance from the REAL entry (never closer than two fees + # plus a margin) — it fills at the TP price or better, not through the spread like a triggered market order + need = 2 * (fee_pct or FEES.get(self.exchange) or 0.1) + self.TP_MARGIN_PCT + dist = max(abs(pos["tp_pct"]), need) + tp = fill.price * (1 + sign * dist / 100) + try: + tp_id = c.fut_take_profit(self.symbol, "sell" if side == "buy" else "buy", fill.coins, tp) + notes.append(f"TP лимит {tp:.10g} ({'+' if sign > 0 else '−'}{dist:.3f}% от реального входа" + + (f", бумажный {abs(pos['tp_pct']):.3f}% меньше двух комиссий — отодвинут" if dist > abs(pos['tp_pct']) else "") + + ")") + except (live.LiveError, AttributeError) as exc: + notes.append(f"TP НЕ выставлен: {exc}") + with self.lock: + pos.update(coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd, exact=fill.exact, order_in=fill.order_id, + tp_order=tp_id, tpsl_on=sl_set or bool(tp_id)) + closing_requested = self.state == "closing" + self.state, self.problem = ("closing" if closing_requested else "open"), "" + self._save() + journal("simulator", self.exchange, self.coin, "open", True, + f"{'лонг' if side == 'buy' else 'шорт'} {fill.coins:g} по {fill.price:.10g} (сигнал " + f"{pos['paper_entry']:.10g}, {(fill.price / pos['paper_entry'] - 1) * 100 * sign:+.3f}% проскальзывание" + + (f", пинг {pos['ping']:.0f} мс" if pos.get("ping") is not None else "") + "), " + f"комиссия {fill.fee_usd:.4f} $" + (f"; {'; '.join(notes)}" if notes else ""), side=pos["side"], + coins=fill.coins, price=fill.price, order=fill.order_id, ping=pos.get("ping"), + slip=(fill.price / pos["paper_entry"] - 1) * 100 * sign) + + def _top_up_futures(self, c, error: str, notional: float) -> None: + """The exchange refused for lack of money: move USDT from the spot account so the NEXT signal can trade + (this one is gone: no extra requests before an entry, they would delay every order).""" + if c is None or not self.settings().get("auto_transfer", True): + return + if not any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно")): + return + try: + moved = live.ensure_usdt(c, 0.0, notional * 1.03) + if moved: + journal("simulator", self.exchange, self.coin, "transfer", True, moved + " — для следующей сделки") + except (live.LiveError, AttributeError) as exc: + journal("simulator", self.exchange, self.coin, "transfer", False, f"перевод не удался: {exc}") + + def _record_fee(self, pct: float) -> None: + """Remember the exchange's real taker rate; listeners (the paper model) use it from now on.""" + FEES[self.exchange] = pct + if self.settings is load_settings: # (tests pass their own settings and must not write the file) + save_settings({"fee": {self.exchange: pct}}) + for fn in FEE_LISTENERS: + fn(self.exchange, pct) + + def _blocked(self, problem: str, text: str, pos: dict) -> None: + """The close is not confirmed yet: keep the coin blocked; journal only when the reason changes.""" + with self.lock: + changed = problem != self.problem + self.state, self.problem = "closing", problem + self._save() + if changed: + journal("simulator", self.exchange, self.coin, "close", False, text, side=pos["side"]) + + PAUSE_S = 30.0 # after the exchange refused an entry: no new trade on the coin for this long + BLOCKED_PAUSE_S = 900.0 # …and this long when the account itself is restricted (MEXC 6002) or rate-limited + + def _failed_open(self, why: str) -> None: + account = any(k in why for k in ("6002", "restricted", "510", "too frequent", "10006", "Too many")) + pause = self.BLOCKED_PAUSE_S if account else self.PAUSE_S + with self.lock: + uid = self.position["uid"] if self.position else None + side = self.position["side"] if self.position else "" + self.position, self.state, self.problem = None, "", "" + self.last_error, self.paused_until = why, time.time() + pause + self._save() + hint = (" — биржа ограничила аккаунт или частоту запросов: проверьте почту и уведомления биржи" if account else "") + journal("simulator", self.exchange, self.coin, "open", False, + f"{why}{hint}; бумажная позиция тоже закрыта, новые входы по монете на паузе {pause / 60:.0f} мин" + if pause >= 60 else f"{why}; бумажная позиция тоже закрыта, пауза {pause:.0f} с", side=side) + if uid is not None and self.on_failed_open: + self.on_failed_open(uid) + + def _close(self, reason: str) -> None: + with self.lock: + pos = self.position + if pos is None or self.state == "": + return + self.state = "closing" + c = self.client_for(self.exchange) + side = "sell" if pos["side"] == "LONG" else "buy" + fills = pos.setdefault("exit_fills", []) + try: + if pos.get("tp_order") and not pos.get("tp_cancelled"): + try: # the TP limit must not fill on top of our close + c.fut_cancel_all(self.symbol) + pos["tp_cancelled"] = True + except (live.LiveError, AttributeError): + pass # reduce-only orders cannot overshoot anyway + held = c.fut_position(self.symbol) # what is really open: TP/SL may have closed it already + if abs(held) > self.VERIFY_TOLERANCE: + try: + fill = c.fut_order(self.symbol, side, abs(held), reduce_only=True) + fills.append({"coins": fill.coins, "price": fill.price, "fee": fill.fee_usd, "exact": fill.exact, + "order": fill.order_id}) + except live.LiveError as exc: + if not getattr(exc, "sent", False): + raise + # accepted, not confirmed: the position check below decides + with self.lock: + self.state = "check" + self._save() + held = c.fut_position(self.symbol) + except live.LiveError as exc: + self._blocked(str(exc), f"не закрыта: {exc} — повторяю через {self.RETRY_S:g} с и дальше", pos) + self._retry_close(reason) + return + left = abs(held) + if left > self.VERIFY_TOLERANCE: + with self.lock: + pos["left"] = left + self._blocked(f"на бирже ещё {held:+g} {self.coin}", f"на бирже осталась позиция {held:+g} — докрываю", pos) + self._retry_close(reason) + return + # confirmed: no position on the symbol any more + done_ours = sum(f["coins"] for f in fills) + if done_ours < pos["coins"] * 0.999: + # (part of) it was closed by the exchange (TP / SL): its own closing fills give the result + try: + theirs = c.fut_closes(self.symbol, side, pos["opened"] - 2) + ours = {f.get("order") for f in fills} + for f in theirs: + if f.order_id not in ours and done_ours < pos["coins"] * 0.999: + fills.append({"coins": f.coins, "price": f.price, "fee": f.fee_usd, "exact": f.exact, + "order": f.order_id}) + done_ours += f.coins + if theirs and "биржей" not in reason: + reason = f"закрыта биржей по TP/SL ({reason})" + except (live.LiveError, AttributeError): + pass + if pos.get("tpsl_on") and not pos.get("tp_cancelled"): + try: # (already done before our own close: not twice) + c.fut_cancel_all(self.symbol) # TP / SL orders left after the exchange's close + except (live.LiveError, AttributeError): + pass + done = sum(f["coins"] for f in fills) + exit_price = sum(f["coins"] * f["price"] for f in fills) / done if done else pos.get("entry", 0.0) + sign = 1 if pos["side"] == "LONG" else -1 + coins = min(done, pos["coins"]) if done else pos["coins"] + gross = sign * (exit_price - pos.get("entry", exit_price)) * coins + fees = pos.get("fee_in", 0.0) + sum(f["fee"] for f in fills) + trade = {"side": pos["side"], "coins": coins, "entry": pos.get("entry", 0.0), "exit": exit_price, + "opened": pos["opened"], "closed": time.time(), "gross": gross, "fees": fees, "net": gross - fees, + "pct": sign * (exit_price / pos["entry"] - 1) * 100 if pos.get("entry") else 0.0, + "reason": reason, "exact": pos.get("exact", True) and all(f["exact"] for f in fills) and bool(fills)} + with self.lock: + self.trades.append(trade) + self.position, self.state, self.problem = None, "", "" + self._save() + self.last_sync = 0.0 # pull the exchange's own figures for this trade soon + journal("simulator", self.exchange, self.coin, "close", True, + f"закрыта по {exit_price:.10g}, биржа подтвердила: позиции нет; итог {trade['net']:+.4f} $ " + f"(комиссии {fees:.4f} $, {reason})", side=pos["side"], coins=coins, price=exit_price, net=trade["net"]) + + # --- view ------------------------------------------------------------------------------------------------------ + def view(self) -> dict: + with self.lock: + # the exchange's history when synced; until then the program's own record of its orders + trades = self.exchange_trades if self.exchange_trades is not None else [ + t for t in self.trades if t.get("closed", 0) >= (self.coin_settings().get("since") or 0)] + stats = trade_stats(trades) + pos = dict(self.position) if self.position and self.state else None + return {"open": 1 if pos else 0, "state": self.state, "problem": self.problem, "position": pos, + **stats, "positions": [pos] if pos else [], "enabled": self.enabled(), + "source": "биржа" if self.exchange_trades is not None else "программа", + "synced": self.synced, "sync_error": self.sync_error, "since": self.coin_settings().get("since"), + "last_error": self.last_error, "paused_s": max(0.0, self.paused_until - time.time()), + "trade_list": list(reversed(trades[-200:]))} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7b39e8e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +websocket-client>=1.8,<2 +numpy>=1.26 diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..3bbee35 --- /dev/null +++ b/run.bat @@ -0,0 +1,11 @@ +@echo off +setlocal +cd /d "%~dp0" +py -3 -c "import websocket" >nul 2>nul +if errorlevel 1 ( + echo Installing required websocket-client package... + py -3 -m pip install -r requirements.txt + if errorlevel 1 pause & exit /b 1 +) +py -3 main.py +if errorlevel 1 pause diff --git a/run_hint.bat b/run_hint.bat new file mode 100644 index 0000000..aad1b79 --- /dev/null +++ b/run_hint.bat @@ -0,0 +1,11 @@ +@echo off +setlocal +cd /d "%~dp0" +py -3 -c "import websocket" >nul 2>nul +if errorlevel 1 ( + echo Installing required websocket-client package... + py -3 -m pip install -r requirements.txt + if errorlevel 1 pause & exit /b 1 +) +py -3 scalp_hint.py +if errorlevel 1 pause diff --git a/run_web_sim.bat b/run_web_sim.bat new file mode 100644 index 0000000..562c2cb --- /dev/null +++ b/run_web_sim.bat @@ -0,0 +1,9 @@ +@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) +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 diff --git a/scalp_hint.py b/scalp_hint.py new file mode 100644 index 0000000..ed90e07 --- /dev/null +++ b/scalp_hint.py @@ -0,0 +1,1710 @@ +"""Scalping hint from the MetaScalp order book and tape: which side, where to enter, stop and target. + +Read-only: connects to the local MetaScalp API (127.0.0.1:17845-17855), follows the order book that +is open in the terminal and never sends orders. The rules mirror a manual read of the book: + +* book imbalance - resting size near the price on the bid side versus the ask side; +* tape delta and momentum - who hits the market and where the price moved recently; +* absorption - heavy market selling that does not push the price down (or the mirror case); +* plan - enter next to the density on the chosen side, keep the stop BEHIND that density, + aim just before the opposite density and skip moves that do not cover the trading costs. + +Every hint that becomes actionable is also checked against the following trades (would the limit +fill, then stop or target first) and appended to a CSV journal, so the hints build their own statistics. +""" + +from __future__ import annotations + +import csv +import json +import math +import queue +import statistics +import threading +import time +import urllib.request +from collections import deque +from dataclasses import dataclass, field, fields +from datetime import datetime, timezone +from pathlib import Path + +API_HOST = "127.0.0.1" +API_PORTS = range(17845, 17856) +JOURNAL_FILE = Path(__file__).with_name("scalp_hint_journal.csv") +MAKER_FEE_PCT = 0.02 +TAKER_FEE_PCT = 0.055 +# Weights of the score components; the adaptive paper policy re-weights them from its own results. +DEFAULT_WEIGHTS = {"book_imb": 0.35, "near_imb": 0.15, "tape_delta": 0.3, "momentum": 0.2, "absorption": 0.15} + + +@dataclass +class HintSettings: + weights: dict = field(default_factory=lambda: dict(DEFAULT_WEIGHTS)) + window_pct: float = 0.3 # depth window around the mid price for imbalance and densities + near_levels: int = 5 # levels per side for the "near the price" imbalance + density_mult: float = 4.0 # a density is a level >= mult x median level size in the window + tape_seconds: float = 60.0 # tape window for delta, momentum and absorption + entry_offset_ticks: int = 1 # enter this many ticks in front of the density + stop_buffer_ticks: int = 2 # stop this many ticks behind the density / recent extreme + min_target_pct: float = 0.15 # the move must at least cover fees and slippage + min_rr: float = 1.5 # minimum reward / risk + max_entry_distance_pct: float = 0.3 + score_threshold: float = 0.25 # below this |score| the hint is "wait" + min_trades: int = 5 # fewer tape trades than this: the tape is ignored + min_risk_pct: float = 0.1 # stop at least this far, and at least half the recent tape range + smooth_seconds: float = 8.0 # time constant of the score smoothing (removes flicker) + fill_minutes: float = 2.0 # how long a hinted limit order may wait for a fill + hold_minutes: float = 5.0 # time stop once filled + + +class OrderBook: + """Absolute-size price levels; an update with size 0 removes the level.""" + + def __init__(self) -> None: + self.asks: dict[float, float] = {} + self.bids: dict[float, float] = {} + + def clear(self) -> None: + self.asks.clear() + self.bids.clear() + + def apply_snapshot(self, data: dict) -> None: + self.clear() + for level in data.get("asks", []): + self._set(self.asks, level) + for level in data.get("bids", []): + self._set(self.bids, level) + marks = [level for level in (data.get("bestAsk"), data.get("bestBid")) if isinstance(level, dict)] + if marks: + self.apply_updates(marks) + + def apply_updates(self, updates: list[dict]) -> None: + best_ask_mark = best_bid_mark = None + for level in updates: + kind = str(level.get("type", "")) + if kind in ("Ask", "BestAsk"): + self._set(self.asks, level) + elif kind in ("Bid", "BestBid"): + self._set(self.bids, level) + try: + if kind == "BestAsk" and float(level["size"]) > 0: + best_ask_mark = float(level["price"]) + elif kind == "BestBid" and float(level["size"]) > 0: + best_bid_mark = float(level["price"]) + except (KeyError, TypeError, ValueError): + pass + # MetaScalp marks the current best prices; levels in front of them are stale (consumed or + # cancelled without an explicit removal), so they are dropped. + if best_ask_mark is not None: + for price in [p for p in self.asks if p < best_ask_mark]: + del self.asks[price] + if best_bid_mark is not None: + for price in [p for p in self.bids if p > best_bid_mark]: + del self.bids[price] + if self.asks and self.bids: + best_ask, best_bid = min(self.asks), max(self.bids) + if best_bid >= best_ask: + # Still crossed without best-price marks: drop the crossing bids until the next update. + for price in [p for p in self.bids if p >= best_ask]: + del self.bids[price] + + @staticmethod + def _set(side: dict[float, float], level: dict) -> None: + try: + price, size = float(level["price"]), float(level["size"]) + except (KeyError, TypeError, ValueError): + return + if size <= 0: + side.pop(price, None) + else: + side[price] = size + + def best(self) -> tuple[float | None, float | None]: + return (max(self.bids) if self.bids else None, min(self.asks) if self.asks else None) + + +@dataclass +class Trade: + ts: float + price: float + size: float + side: str # "Buy" or "Sell" (aggressor) + + +class Tape: + def __init__(self, keep_seconds: float = 900.0) -> None: + self.trades: deque[Trade] = deque() + self.keep = keep_seconds + + def add(self, trade: Trade) -> None: + self.trades.append(trade) + while self.trades and self.trades[0].ts < trade.ts - self.keep: + self.trades.popleft() + + def window(self, seconds: float, now: float) -> list[Trade]: + return [t for t in self.trades if t.ts >= now - seconds] + + def clear(self) -> None: + self.trades.clear() + + +@dataclass +class Hint: + side: str # "LONG", "SHORT" or "WAIT" + confidence: str + score: float + entry: float | None = None + stop: float | None = None + target: float | None = None + rr: float | None = None + reasons: list[str] = field(default_factory=list) + metrics: dict = field(default_factory=dict) + + +def _clip(value: float) -> float: + return max(-1.0, min(1.0, value)) + + +def _to_tick(price: float, tick: float, up: bool | None = None) -> float: + steps = price / tick + steps = math.ceil(steps - 1e-9) if up else math.floor(steps + 1e-9) if up is False else round(steps) + decimals = max(0, -int(math.floor(math.log10(tick)))) if tick < 1 else 0 + return round(steps * tick, decimals + 2) + + +def _imbalance(bid: float, ask: float) -> float: + total = bid + ask + return (bid - ask) / total if total > 0 else 0.0 + + +def significant_imbalance(book: OrderBook, depth_pct: float = 0.3, low_pct: float = 20.0, + high_pct: float = 90.0) -> dict | None: + """Imbalance of the 'significant' resting orders near the price. + + Levels within ±depth_pct of the mid are pooled (both sides); levels below the low percentile of their + sizes (noise) and above the high percentile (outsized walls, often pulled before the price arrives) + are dropped, and the remaining sizes are summed per side. Returns None without a usable book. + """ + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return None + mid = (best_bid + best_ask) / 2 + window = mid * depth_pct / 100 + levels = sorted([(s, "ask") for p, s in book.asks.items() if p <= mid + window] + + [(s, "bid") for p, s in book.bids.items() if p >= mid - window]) + if len(levels) < 4: + return None + # Cut by count, not by value: many identical sizes at a percentile would otherwise all be + # kept or all be dropped. The smallest low_pct% and the largest (100 - high_pct)% of levels go. + n = len(levels) + drop_low = int(n * low_pct / 100) + drop_high = int(n * (100 - high_pct) / 100) + kept = levels[drop_low:n - drop_high] or levels + bid_sum = sum(s for s, side in kept if side == "bid") + ask_sum = sum(s for s, side in kept if side == "ask") + return {"mid": mid, "bid_sum": bid_sum, "ask_sum": ask_sum, "imbalance": _imbalance(bid_sum, ask_sum), + "low": kept[0][0], "high": kept[-1][0], "used": len(kept), "levels": n} + + +class HintEngine: + """Smooths the score over time so the hint does not flip on every book update.""" + + def __init__(self, settings: HintSettings) -> None: + self.settings = settings + self.score: float | None = None + self.at = 0.0 + + def reset(self) -> None: + self.score = None + + def __call__(self, book: OrderBook, tape: Tape, tick: float, now: float) -> Hint: + raw = evaluate(book, tape, tick, self.settings, now) + if not raw.metrics: + return raw + if self.score is None: + self.score = raw.score + else: + alpha = 1 - math.exp(-max(0.0, now - self.at) / self.settings.smooth_seconds) + self.score += alpha * (raw.score - self.score) + self.at = now + return evaluate(book, tape, tick, self.settings, now, score_override=self.score) + + +def evaluate(book: OrderBook, tape: Tape, tick: float, settings: HintSettings, now: float, + score_override: float | None = None) -> Hint: + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None or tick <= 0: + return Hint("WAIT", "—", 0.0, reasons=["Нет стакана — жду данные MetaScalp"]) + mid = (best_bid + best_ask) / 2 + spread_pct = (best_ask - best_bid) / mid * 100 + window = mid * settings.window_pct / 100 + asks = sorted((p, s) for p, s in book.asks.items() if p <= mid + window) + bids = sorted(((p, s) for p, s in book.bids.items() if p >= mid - window), reverse=True) + if not asks or not bids: + return Hint("WAIT", "—", 0.0, reasons=["Стакан слишком тонкий в окне ±{:g}%".format(settings.window_pct)]) + + # Book imbalance, levels closer to the price weigh more. + def weighted(levels): + return sum(s * (1 - abs(p - mid) / window) for p, s in levels) + + book_imb = _imbalance(weighted(bids), weighted(asks)) + near_imb = _imbalance(sum(s for _, s in bids[:settings.near_levels]), + sum(s for _, s in asks[:settings.near_levels])) + + # Safety: the book must agree with the tape, otherwise it is out of sync and nothing is hinted. + if tape.trades: + last_price = tape.trades[-1].price + if abs(last_price - mid) / mid * 100 > 0.3: + return Hint("WAIT", "—", 0.0, reasons=[ + f"Стакан расходится с лентой ({mid:.10g} против последней сделки {last_price:.10g}) — " + "жду обновления данных"]) + + # Tape delta, momentum and absorption. + recent = tape.window(settings.tape_seconds, now) + buy = sum(t.size for t in recent if t.side == "Buy") + sell = sum(t.size for t in recent if t.side == "Sell") + enough = len(recent) >= settings.min_trades + tape_delta = _imbalance(buy, sell) if enough else 0.0 + if enough: + momentum = _clip((recent[-1].price - recent[0].price) / mid / (settings.window_pct / 100)) + tape_high = max(t.price for t in recent) + tape_low = min(t.price for t in recent) + else: + momentum, tape_high, tape_low = 0.0, best_ask, best_bid + absorption = 0.0 + if enough and buy + sell > 0: + if tape_delta < -0.3 and momentum >= 0: + absorption = 1.0 # sellers hit hard, price does not fall: buyers absorb + elif tape_delta > 0.3 and momentum <= 0: + absorption = -1.0 # buyers hit hard, price does not rise: sellers absorb + + w = settings.weights + raw_score = (w["book_imb"] * book_imb + w["near_imb"] * near_imb + w["tape_delta"] * tape_delta + + w["momentum"] * momentum + w["absorption"] * absorption) + score = raw_score if score_override is None else score_override + min_risk = max(mid * settings.min_risk_pct / 100, (tape_high - tape_low) / 2, 2 * tick) + sizes = [s for _, s in asks] + [s for _, s in bids] + median = statistics.median(sizes) if sizes else 0.0 + threshold = median * settings.density_mult + resistance = next(((p, s) for p, s in asks if s >= threshold and p > best_ask - tick / 2), None) + support = next(((p, s) for p, s in bids if s >= threshold and p < best_bid + tick / 2), None) + + metrics = {"mid": mid, "spread_pct": spread_pct, "book_imb": book_imb, "near_imb": near_imb, + "tape_delta": tape_delta, "momentum": momentum, "absorption": absorption, + "trades": len(recent), "resistance": resistance, "support": support, + "ask_volume": sum(s for _, s in asks), "bid_volume": sum(s for _, s in bids)} + reasons = [ + f"Стакан ±{settings.window_pct:g}%: покупатели {metrics['bid_volume']:,.0f} / продавцы " + f"{metrics['ask_volume']:,.0f} (перекос {book_imb:+.2f}, у цены {near_imb:+.2f})", + (f"Лента {settings.tape_seconds:.0f} с: покупки {buy:,.0f} / продажи {sell:,.0f} " + f"(перевес {tape_delta:+.2f}), импульс {momentum:+.2f}, сделок {len(recent)}") + if enough else f"Лента: мало сделок за {settings.tape_seconds:.0f} с ({len(recent)}) — не учитывается", + ] + if absorption > 0: + reasons.append("Поглощение: продают по рынку, но цена не падает — снизу держат") + elif absorption < 0: + reasons.append("Поглощение: покупают по рынку, но цена не растёт — сверху держат") + if resistance: + reasons.append(f"Плотность продавцов {resistance[1]:,.0f} на {resistance[0]:.10g}") + if support: + reasons.append(f"Плотность покупателей {support[1]:,.0f} на {support[0]:.10g}") + reasons.append(f"Спред {spread_pct:.3f}%") + thin = min(metrics["ask_volume"], metrics["bid_volume"]) / max(metrics["ask_volume"], metrics["bid_volume"]) + if thin < 0.08: + reasons.append("Внимание: одна сторона стакана почти пустая — так бывает при резком движении; " + "сверьтесь со стаканом в терминале") + + strength = abs(score) + if strength < settings.score_threshold: + reasons.insert(0, "Перевеса нет — боковик, вход не нужен") + return Hint("WAIT", "—", score, reasons=reasons, metrics=metrics) + confidence = "высокая" if strength >= 0.65 else "средняя" if strength >= 0.45 else "низкая" + side = "LONG" if score > 0 else "SHORT" + offset = settings.entry_offset_ticks * tick + buffer = settings.stop_buffer_ticks * tick + if side == "SHORT": + if resistance and resistance[0] - offset >= best_ask: + entry = resistance[0] - offset + stop = resistance[0] + buffer + else: + entry = best_ask + stop = max(entry, tape_high) + buffer + stop = max(stop, entry + min_risk) + risk = stop - entry + target = support[0] + offset if support and support[0] + offset < entry - risk else entry - 2 * risk + reward = entry - target + else: + if support and support[0] + offset <= best_bid: + entry = support[0] + offset + stop = support[0] - buffer + else: + entry = best_bid + stop = min(entry, tape_low) - buffer + stop = min(stop, entry - min_risk) + risk = entry - stop + target = resistance[0] - offset if resistance and resistance[0] - offset > entry + risk else entry + 2 * risk + reward = target - entry + # Orders sit on the price grid: the stop rounds away from the entry, the target towards it. + if side == "SHORT": + entry, stop, target = _to_tick(entry, tick), _to_tick(stop, tick, up=True), _to_tick(target, tick, up=True) + risk, reward = stop - entry, entry - target + else: + entry, stop, target = _to_tick(entry, tick), _to_tick(stop, tick, up=False), _to_tick(target, tick, up=False) + risk, reward = entry - stop, target - entry + rr = reward / risk if risk > 0 else 0.0 + reward_pct = reward / entry * 100 + entry_distance = abs(entry - mid) / mid * 100 + hint = Hint(side, confidence, score, entry, stop, target, rr, reasons, metrics) + problems = [] + if reward_pct < settings.min_target_pct: + problems.append(f"ход до цели {reward_pct:.2f}% меньше издержек ({settings.min_target_pct:g}%)") + if rr < settings.min_rr: + problems.append(f"риск/прибыль 1:{rr:.1f} хуже 1:{settings.min_rr:g}") + if entry_distance > settings.max_entry_distance_pct: + problems.append(f"вход далеко от цены ({entry_distance:.2f}%)") + if problems: + hint.reasons.insert(0, f"Перевес в {side}, но сделка невыгодна: " + "; ".join(problems)) + hint.side = "WAIT" + return hint + + +@dataclass +class Tracked: + ticker: str + side: str + entry: float + stop: float + target: float + created: float + confidence: str + score: float + filled_at: float | None = None + result: str = "" + pnl_pct: float = 0.0 + + +class Journal: + """Checks each actionable hint against later trades: fill, then stop or target first.""" + + def __init__(self, settings: HintSettings, path: Path = JOURNAL_FILE) -> None: + self.settings = settings + self.path = path + self.active: Tracked | None = None + self.done: list[Tracked] = [] + self._load() + + def _load(self) -> None: + try: + with self.path.open(encoding="utf-8-sig") as file: + for row in csv.DictReader(file): + self.done.append(Tracked(row["ticker"], row["side"], float(row["entry"]), float(row["stop"]), + float(row["target"]), 0.0, row["confidence"], float(row["score"]), + result=row["result"], pnl_pct=float(row["pnl_pct"] or 0))) + except (OSError, KeyError, ValueError): + pass + + def offer(self, ticker: str, hint: Hint, now: float) -> None: + if self.active is not None or hint.side == "WAIT" or hint.entry is None: + return + self.active = Tracked(ticker, hint.side, hint.entry, hint.stop, hint.target, now, hint.confidence, hint.score) + + def cancel(self, reason: str) -> None: + if self.active and self.active.filled_at is None: + self._finish(reason, 0.0) + elif self.active: + self._finish(reason, self.active.pnl_pct) + + def on_trade(self, trade: Trade) -> None: + tr = self.active + if tr is None: + return + long = tr.side == "LONG" + if tr.filled_at is None: + # A resting limit fills only when the market trades through it (queue is unknown). + through = trade.price < tr.entry if long else trade.price > tr.entry + if through: + tr.filled_at = trade.ts + elif trade.ts - tr.created > self.settings.fill_minutes * 60: + self._finish("не исполнился", 0.0) + return + stop_hit = trade.price <= tr.stop if long else trade.price >= tr.stop + target_hit = trade.price >= tr.target if long else trade.price <= tr.target + sign = 1 if long else -1 + if stop_hit: + self._finish("стоп", sign * (tr.stop - tr.entry) / tr.entry * 100 - MAKER_FEE_PCT - TAKER_FEE_PCT) + elif target_hit: + self._finish("цель", sign * (tr.target - tr.entry) / tr.entry * 100 - 2 * MAKER_FEE_PCT) + elif trade.ts - tr.filled_at > self.settings.hold_minutes * 60: + self._finish("время", sign * (trade.price - tr.entry) / tr.entry * 100 - MAKER_FEE_PCT - TAKER_FEE_PCT) + + def _finish(self, result: str, pnl: float) -> None: + tr = self.active + self.active = None + if tr is None: + return + tr.result, tr.pnl_pct = result, pnl + self.done.append(tr) + new_file = not self.path.exists() + try: + with self.path.open("a", encoding="utf-8-sig", newline="") as file: + writer = csv.writer(file) + if new_file: + writer.writerow(["time_utc", "ticker", "side", "confidence", "score", "entry", "stop", "target", + "result", "pnl_pct"]) + writer.writerow([datetime.now(timezone.utc).isoformat(timespec="seconds"), tr.ticker, tr.side, + tr.confidence, f"{tr.score:.3f}", f"{tr.entry:.10g}", f"{tr.stop:.10g}", + f"{tr.target:.10g}", result, f"{pnl:.4f}"]) + except OSError: + pass + + def stats(self) -> str: + filled = [t for t in self.done if t.result in ("стоп", "цель", "время")] + if not filled: + unfilled = sum(t.result == "не исполнился" for t in self.done) + return f"Проверено подсказок: 0 исполненных · не исполнилось {unfilled}" + wins = sum(t.pnl_pct > 0 for t in filled) + avg = sum(t.pnl_pct for t in filled) / len(filled) + return (f"Исполнено {len(filled)} · в плюс {wins} ({wins / len(filled) * 100:.0f}%) · " + f"средний итог {avg:+.3f}% после комиссий · не исполнилось " + f"{sum(t.result == 'не исполнился' for t in self.done)}") + + +# -------------------------------------------------------------------------------------------- +# MetaScalp connection +# -------------------------------------------------------------------------------------------- + +def discover_port() -> int | None: + for port in API_PORTS: + try: + with urllib.request.urlopen(f"http://{API_HOST}:{port}/ping", timeout=1) as response: + if json.loads(response.read().decode("utf-8")).get("app") == "MetaScalp": + return port + except Exception: + continue + return None + + +def active_order_book(port: int) -> dict | None: + """The order book document of the selected tab: connection id, ticker and price step.""" + with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/ui/state", timeout=3) as response: + state = json.loads(response.read().decode("utf-8")) + for window in state.get("windows", []): + tabs = window.get("tabs", []) + for tab in sorted(tabs, key=lambda t: not t.get("isSelected")): + for doc in tab.get("documents", []): + if doc.get("kind") == "orderBook" and doc.get("orderBook"): + return {"connectionId": doc["connectionId"], "ticker": doc["ticker"], + "tick": float(doc["orderBook"].get("priceIncrement") or 0)} + return None + + +def connection_name(port: int, connection_id: int) -> str: + try: + with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/connections/{connection_id}", timeout=3) as r: + data = json.loads(r.read().decode("utf-8")) + return str(data.get("Name") or data.get("name") or connection_id) + except Exception: + return str(connection_id) + + +def connection_info(port: int, connection_id: int) -> dict: + try: + with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/connections/{connection_id}", timeout=3) as r: + return json.loads(r.read().decode("utf-8")) + except Exception: + return {} + + +BYBIT_WS = "wss://stream.bybit.com/v5/public/linear" + + +class ClockSync: + """Exchange-minus-local clock offset, re-measured every `period` seconds (the PC clock drifts and Windows + steps it now and then, which would otherwise show up as a sudden jump in measured latency).""" + + def __init__(self, period: float = 60.0) -> None: + self.period = period + self.offset: float | None = None + self.measured = -1e9 + + def get(self) -> float | None: + if time.monotonic() - self.measured > self.period: + self.measured = time.monotonic() + value = bybit_clock_offset() + if value is not None: + self.offset = value + return self.offset + + +def bybit_clock_offset() -> float | None: + """Exchange clock minus local clock, seconds (round-trip corrected); None when Bybit is unreachable.""" + try: + t0 = time.time() + with urllib.request.urlopen("https://api.bybit.com/v5/market/time", timeout=5) as response: + payload = json.loads(response.read().decode("utf-8")) + t1 = time.time() + server = int(payload["result"]["timeNano"]) / 1e9 + return server - (t0 + t1) / 2 + except Exception: + return None + + +def parse_time(value: str) -> float: + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() + except (ValueError, AttributeError): + return time.time() + + +class Feed(threading.Thread): + """WebSocket reader: pushes ("book_snapshot"|"book_update"|"trades", data) into a queue.""" + + def __init__(self, port: int, connection_id: int, ticker: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.port, self.connection_id, self.ticker, self.out = port, connection_id, ticker, out + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + self.ws = websocket.create_connection(f"ws://{API_HOST}:{self.port}/", timeout=30) + base = {"connectionId": self.connection_id, "ticker": self.ticker} + self.ws.send(json.dumps({"Type": "orderbook_subscribe", + "Data": {**base, "zoomIndex": 0, "depthLevels": 100, "depthPercent": 1.0}})) + self.ws.send(json.dumps({"Type": "trade_subscribe", "Data": {**base, "zoomIndex": 1}})) + self.out.put(("status", f"Подключено: {self.ticker}")) + while not self.stopped.is_set(): + message = json.loads(self.ws.recv()) + kind = message.get("Type") + data = message.get("Data") or {} + if data.get("ticker") not in (None, self.ticker): + continue + if kind == "orderbook_snapshot": + self.out.put(("book_snapshot", data)) + elif kind == "orderbook_update": + self.out.put(("book_update", data.get("updates", []))) + elif kind == "trade_update": + trades = data.get("trades", []) + self.out.put(("trades", trades)) + offset = clock.get() + if offset is not None and trades: + exchange_time = parse_time(trades[-1].get("time")) + self.out.put(("latency", (time.time() + offset - exchange_time) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с MetaScalp: {exc}; переподключение…")) + time.sleep(2) + + +class BybitFeed(threading.Thread): + """Direct Bybit public WebSocket (orderbook.50 every ~20 ms + public trades), converted to the same events + as the MetaScalp feed. Sizes are converted from coins to USDT so both sources look alike.""" + + def __init__(self, ticker: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.ticker, self.out = ticker, out + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + @staticmethod + def _levels(rows, kind: str) -> list[dict]: + out = [] + for price, size in rows: + p, s = float(price), float(size) + out.append({"price": p, "size": s * p, "type": kind}) + return out + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + self.ws = websocket.create_connection(BYBIT_WS, timeout=10) + self.ws.send(json.dumps({"op": "subscribe", + "args": [f"orderbook.50.{self.ticker}", f"publicTrade.{self.ticker}"]})) + self.out.put(("status", f"Bybit напрямую: {self.ticker}")) + last_ping = time.time() + self.ws.settimeout(5) + while not self.stopped.is_set(): + if time.time() - last_ping > 20: + self.ws.send(json.dumps({"op": "ping"})) + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + topic = str(message.get("topic", "")) + data = message.get("data") + if topic.startswith("orderbook.") and isinstance(data, dict): + if message.get("type") == "snapshot": + self.out.put(("book_snapshot", {"asks": self._levels(data.get("a", []), "Ask"), + "bids": self._levels(data.get("b", []), "Bid")})) + else: + self.out.put(("book_update", self._levels(data.get("a", []), "Ask") + + self._levels(data.get("b", []), "Bid"))) + elif topic.startswith("publicTrade.") and isinstance(data, list): + trades = [] + for row in data: + try: + p = float(row["p"]) + trades.append({"price": p, "size": float(row["v"]) * p, "side": row.get("S"), + "time": datetime.fromtimestamp(int(row["T"]) / 1000, + timezone.utc).isoformat()}) + except (KeyError, TypeError, ValueError): + continue + if trades: + self.out.put(("trades", trades)) + offset = clock.get() + if offset is not None: + self.out.put(("latency", (time.time() + offset - int(data[-1]["T"]) / 1000) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с Bybit: {exc}; переподключение…")) + time.sleep(2) + + +KUCOIN_BULLET = "https://api-futures.kucoin.com/api/v1/bullet-public" +KUCOIN_SPOT_BULLET = "https://api.kucoin.com/api/v1/bullet-public" + + +class KucoinFeed(threading.Thread): + """KuCoin public WebSocket: best bid/ask of one futures contract (tickerV2, e.g. MARSCOINUSDTM) or one spot pair + (/market/ticker, e.g. MARSCOIN-USDT), pushed as ("leader", (bid, ask)) plus ("leader_latency", ms) measured + against Bybit's clock.""" + + def __init__(self, ticker: str, out: queue.Queue, spot: bool = False) -> None: + super().__init__(daemon=True) + self.ticker, self.out, self.spot = ticker, out, spot + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def parse(self, message: dict) -> tuple[float, float, float] | None: + """(bid, ask, exchange time in s) from a futures tickerV2 or a spot /market/ticker message.""" + data = message.get("data") or {} + try: + if self.spot and message.get("subject") == "trade.ticker": + return float(data["bestBid"]), float(data["bestAsk"]), float(data.get("time") or 0) / 1e3 + if not self.spot and message.get("subject") == "tickerV2": + return float(data["bestBidPrice"]), float(data["bestAskPrice"]), float(data.get("ts") or 0) / 1e9 + except (KeyError, TypeError, ValueError): + return None + return None + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + req = urllib.request.Request(KUCOIN_SPOT_BULLET if self.spot else KUCOIN_BULLET, data=b"", + method="POST", headers={"User-Agent": "Mozilla/5.0"}) + with urllib.request.urlopen(req, timeout=10) as resp: + bullet = json.loads(resp.read())["data"] + server = bullet["instanceServers"][0] + self.ws = websocket.create_connection(f"{server['endpoint']}?token={bullet['token']}", timeout=5) + topic = f"/market/ticker:{self.ticker}" if self.spot else f"/contractMarket/tickerV2:{self.ticker}" + self.ws.send(json.dumps({"id": "1", "type": "subscribe", "response": True, "topic": topic})) + self.out.put(("leader_status", f"KuCoin {'спот' if self.spot else 'фьючерс'}: {self.ticker}")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 15: + self.ws.send(json.dumps({"id": "ping", "type": "ping"})) + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + bid_ask = self.parse(message) + if bid_ask is None: + continue + bid, ask, exchange_time = bid_ask + self.out.put(("leader", (bid, ask))) + offset = clock.get() + if offset is not None and exchange_time: + self.out.put(("leader_latency", (time.time() + offset - exchange_time) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("leader_status", f"Нет связи с KuCoin: {exc}; переподключение…")) + time.sleep(2) + + +BINANCE_PUBLIC_WS = "wss://fstream.binance.com/public/stream?streams=" # bookTicker +BINANCE_MARKET_WS = "wss://fstream.binance.com/market/stream?streams=" # aggTrade + + +class BinanceFeed(threading.Thread): + """Binance USDⓈ-M futures: best bid/ask (bookTicker, every change) as a one-level book plus aggregated trades, + as the same events as the Bybit feed (sizes in USDT).""" + + def __init__(self, ticker: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.ticker, self.out = ticker, out + self.stopped = threading.Event() + self.sockets: list = [] + + def stop(self) -> None: + self.stopped.set() + for ws in self.sockets: + try: + ws.close() + except Exception: + pass + + def book_event(self, data: dict) -> tuple | None: + try: + bid, ask = float(data["b"]), float(data["a"]) + return ("book_snapshot", {"bids": [{"price": bid, "size": float(data["B"]) * bid, "type": "Bid"}], + "asks": [{"price": ask, "size": float(data["A"]) * ask, "type": "Ask"}]}) + except (KeyError, TypeError, ValueError): + return None + + @staticmethod + def trade_event(data: dict) -> tuple | None: + try: + p = float(data["p"]) + return ("trades", [{"price": p, "size": float(data["q"]) * p, "side": "Sell" if data.get("m") else "Buy", + "time": datetime.fromtimestamp(int(data["T"]) / 1000, timezone.utc).isoformat()}]) + except (KeyError, TypeError, ValueError): + return None + + def _loop(self, url: str, kind: str) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + ws = websocket.create_connection(url, timeout=5) + self.sockets.append(ws) + self.out.put(("status", f"Binance фьючерс напрямую: {self.ticker}")) + while not self.stopped.is_set(): + try: + message = json.loads(ws.recv()) + except websocket.WebSocketTimeoutException: + continue + data = message.get("data") or {} + event = self.book_event(data) if kind == "book" else self.trade_event(data) + if event: + self.out.put(event) + offset = clock.get() + if kind == "trades" and offset is not None and data.get("T"): + self.out.put(("latency", (time.time() + offset - int(data["T"]) / 1000) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с Binance: {exc}; переподключение…")) + time.sleep(2) + + def run(self) -> None: + s = self.ticker.lower() + threading.Thread(target=self._loop, args=(f"{BINANCE_MARKET_WS}{s}@aggTrade", "trades"), daemon=True).start() + self._loop(f"{BINANCE_PUBLIC_WS}{s}@bookTicker", "book") + + +MEXC_WS = "wss://contract.mexc.com/edge" + + +def mexc_contract(ticker: str) -> tuple[float, float]: + """(price step, coins per contract) of a MEXC USDT perpetual such as SI_USDT.""" + try: + with urllib.request.urlopen(f"https://contract.mexc.com/api/v1/contract/detail?symbol={ticker}", + timeout=15) as resp: + data = json.loads(resp.read())["data"] + return float(data["priceUnit"]), float(data["contractSize"]) + except (OSError, ValueError, KeyError, TypeError): + return 0.0, 1.0 + + +class MexcFeed(threading.Thread): + """MEXC USDT perpetual (e.g. SI_USDT): the top 5 levels of the book (push.depth.full) and trades (push.deal), + as the same events as the Bybit feed (sizes in USDT, from contracts × contract size).""" + + def __init__(self, ticker: str, out: queue.Queue, contract_size: float = 1.0) -> None: + super().__init__(daemon=True) + self.ticker, self.out, self.contract_size = ticker, out, contract_size + self.stopped = threading.Event() + self.ws = None + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def parse(self, message: dict) -> list[tuple]: + channel, data = message.get("channel"), message.get("data") + events = [] + try: + if channel == "push.depth.full" and isinstance(data, dict): + def levels(rows, kind): + return [{"price": float(p), "size": float(v) * self.contract_size * float(p), "type": kind} + for p, v, *_ in rows] + events.append(("book_snapshot", {"asks": levels(data.get("asks", []), "Ask"), + "bids": levels(data.get("bids", []), "Bid")})) + elif channel == "push.deal": + rows = data if isinstance(data, list) else [data] + trades = [{"price": float(d["p"]), "size": float(d["v"]) * self.contract_size * float(d["p"]), + "side": "Buy" if int(d.get("T", 1)) == 1 else "Sell", + "time": datetime.fromtimestamp(int(d["t"]) / 1000, timezone.utc).isoformat()} + for d in rows] + if trades: + events.append(("trades", trades)) + except (KeyError, TypeError, ValueError): + return [] + return events + + def run(self) -> None: + import websocket + clock = ClockSync() + while not self.stopped.is_set(): + try: + self.ws = websocket.create_connection(MEXC_WS, timeout=5) + self.ws.send(json.dumps({"method": "sub.depth.full", "param": {"symbol": self.ticker, "limit": 5}})) + self.ws.send(json.dumps({"method": "sub.deal", "param": {"symbol": self.ticker}})) + self.out.put(("status", f"MEXC фьючерс напрямую: {self.ticker}")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 15: + self.ws.send(json.dumps({"method": "ping"})) + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + for event in self.parse(message): + self.out.put(event) + offset = clock.get() + if event[0] == "trades" and offset is not None and message.get("ts"): + self.out.put(("latency", (time.time() + offset - int(message["ts"]) / 1000) * 1000)) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("status", f"Нет связи с MEXC: {exc}; переподключение…")) + time.sleep(2) + + +def binance_tick(ticker: str) -> float: + """Price step of a Binance USDⓈ-M perpetual (public REST).""" + try: + with urllib.request.urlopen("https://fapi.binance.com/fapi/v1/exchangeInfo", timeout=15) as resp: + symbols = json.loads(resp.read())["symbols"] + for s in symbols: + if s["symbol"] == ticker.upper(): + return float(next(f["tickSize"] for f in s["filters"] if f["filterType"] == "PRICE_FILTER")) + except (OSError, ValueError, KeyError, StopIteration): + pass + return 0.0 + + +SOLANA_RPC = "https://api.mainnet-beta.solana.com" +SOLANA_WS = "wss://api.mainnet-beta.solana.com" +RAYDIUM_AMM_V4 = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" +RAYDIUM_CPMM = "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C" +PUMPSWAP = "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA" +WSOL = "So11111111111111111111111111111111111111112" +STABLES = {"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"} +_B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + +def b58encode(raw: bytes) -> str: + n = int.from_bytes(raw, "big") + out = "" + while n: + n, r = divmod(n, 58) + out = _B58[r] + out + return "1" * (len(raw) - len(raw.lstrip(b"\0"))) + out + + +def solana_rpc(method: str, params: list): + body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode() + req = urllib.request.Request(SOLANA_RPC, data=body, headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=20) as resp: + return json.loads(resp.read())["result"] + + +def raydium_pool(owner: str, data: bytes) -> dict: + """Vaults and mints of a Raydium constant-product pool (AMM v4 or CPMM) from its account data.""" + import struct + if owner == RAYDIUM_AMM_V4: + return {"vault0": b58encode(data[336:368]), "vault1": b58encode(data[368:400]), + "mint0": b58encode(data[400:432]), "mint1": b58encode(data[432:464])} + if owner == RAYDIUM_CPMM: + return {"vault0": b58encode(data[72:104]), "vault1": b58encode(data[104:136]), + "mint0": b58encode(data[168:200]), "mint1": b58encode(data[200:232])} + if owner == PUMPSWAP: + # pool_bump u8, index u16, creator, base_mint, quote_mint, lp_mint, base vault, quote vault + return {"vault0": b58encode(data[139:171]), "vault1": b58encode(data[171:203]), + "mint0": b58encode(data[43:75]), "mint1": b58encode(data[75:107])} + raise ValueError("тип пула не поддерживается: нужен Raydium AMM v4 / CPMM / CLMM, PumpSwap, Meteora DLMM, " + "Orca Whirlpool или PancakeSwap CLMM") + + +METEORA_DLMM = "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo" + + +def dlmm_state(data: bytes) -> tuple[int, int, str, str]: + """(active bin id, bin step in bps, token X mint, token Y mint) of a Meteora DLMM LbPair account.""" + import struct + active_id, bin_step = struct.unpack_from(" float: + """Price of X in Y of the active bin: (1 + bin_step/10000) ** active_id, scaled by the decimals.""" + return (1 + bin_step / 10000) ** active_id * 10 ** (decimals_x - decimals_y) + + +ORCA_WHIRLPOOL = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" +RAYDIUM_CLMM = "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK" +PANCAKE_CLMM = "HpNfyc2Saw7RKkQd8nEL4khUcuPhQ7WwY1B2qjx8jxFq" # a Raydium CLMM fork, same pool layout +CLMM_KINDS = {ORCA_WHIRLPOOL: "Orca Whirlpool", RAYDIUM_CLMM: "Raydium CLMM", PANCAKE_CLMM: "PancakeSwap CLMM"} + + +def clmm_state(owner: str, data: bytes) -> tuple[int, str, str]: + """(sqrt price Q64.64, mint of token 0/A, mint of token 1/B) of a concentrated-liquidity pool account.""" + if owner == ORCA_WHIRLPOOL: + # discriminator, config, bump, tick spacing, seed, fee, protocol fee, liquidity u128, sqrt_price u128 @65 + return int.from_bytes(data[65:81], "little"), b58encode(data[101:133]), b58encode(data[181:213]) + # Raydium CLMM PoolState: discriminator, bump, amm config, owner, mint0 @73, mint1 @105, …, sqrt_price_x64 @253 + return int.from_bytes(data[253:269], "little"), b58encode(data[73:105]), b58encode(data[105:137]) + + +def clmm_price(sqrt_price_x64: int, decimals_0: int, decimals_1: int) -> float: + """Price of token 0 in token 1: (sqrt_price / 2**64) ** 2, scaled by the decimals.""" + return (sqrt_price_x64 / 2 ** 64) ** 2 * 10 ** (decimals_0 - decimals_1) + + +def mint_decimals(mint: str) -> int: + return int(solana_rpc("getAccountInfo", [mint, {"encoding": "jsonParsed"}])["value"]["data"]["parsed"]["info"] + ["decimals"]) + + +def pool_price_usd(amounts: dict, token_vault: str, quote_vault: str, quote_usd: float) -> float | None: + token, quote = amounts.get(token_vault), amounts.get(quote_vault) + if not token or not quote or quote_usd <= 0: + return None + return quote / token * quote_usd + + +class RaydiumFeed(threading.Thread): + """A Raydium pool on Solana in real time: the two vault balances over the public Solana RPC WebSocket + (accountSubscribe, 'processed' commitment); price = quote vault / token vault, in USD through Binance's SOL price + when the pool is quoted in SOL. Pushed as ("leader", (price, price)) on every swap (never on SOL moves alone).""" + + def __init__(self, pool: str, out: queue.Queue) -> None: + super().__init__(daemon=True) + self.pool, self.out = pool, out + self.stopped = threading.Event() + self.ws = None + self.sol_usd = 0.0 + + def stop(self) -> None: + self.stopped.set() + try: + if self.ws: + self.ws.close() + except Exception: + pass + + def _start_sol_price(self) -> None: + if not getattr(self, "_sol_thread", None): + self._sol_thread = threading.Thread(target=self._sol_price, daemon=True) + self._sol_thread.start() + + def _run_dlmm(self, owner: str = METEORA_DLMM) -> None: + """Pools whose price lives in the pool account itself — the pool account is watched, so every swap + refreshes the price. Meteora DLMM: the active bin's (1 + bin step) ** active id; Orca Whirlpool and + Raydium/PancakeSwap CLMM: (sqrt price) ** 2.""" + import base64 + import websocket + data = base64.b64decode(solana_rpc("getAccountInfo", [self.pool, {"encoding": "base64"}])["value"]["data"][0]) + if owner == METEORA_DLMM: + _, _, mint_x, mint_y = dlmm_state(data) + kind = "Meteora DLMM" + else: + _, mint_x, mint_y = clmm_state(owner, data) + kind = CLMM_KINDS[owner] + dec_x, dec_y = mint_decimals(mint_x), mint_decimals(mint_y) + token_is_x = mint_y in (WSOL, *STABLES) or mint_x not in (WSOL, *STABLES) + quote_mint = mint_y if token_is_x else mint_x + if quote_mint == WSOL: + self._start_sol_price() + self.ws = websocket.create_connection(SOLANA_WS, timeout=30) + self.ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "accountSubscribe", + "params": [self.pool, {"encoding": "base64", "commitment": "processed"}]})) + self.out.put(("leader_status", f"{kind} пул {self.pool[:6]}… (Solana, в реальном времени)")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 30: + self.ws.ping() + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + try: + raw = base64.b64decode(message["params"]["result"]["value"]["data"][0]) + except (KeyError, TypeError, IndexError): + continue + if owner == METEORA_DLMM: + active_id, bin_step, _, _ = dlmm_state(raw) + price_y_per_x = dlmm_price(active_id, bin_step, dec_x, dec_y) + else: + price_y_per_x = clmm_price(clmm_state(owner, raw)[0], dec_x, dec_y) + if price_y_per_x <= 0: + continue + in_quote = price_y_per_x if token_is_x else 1 / price_y_per_x + quote_usd = self.sol_usd if quote_mint == WSOL else 1.0 + if quote_usd > 0: + price = in_quote * quote_usd + self.out.put(("leader", (price, price))) + + def _sol_price(self) -> None: + import websocket + while not self.stopped.is_set(): + try: + ws = websocket.create_connection(f"{BINANCE_PUBLIC_WS}solusdt@bookTicker", timeout=5) + while not self.stopped.is_set(): + try: + d = json.loads(ws.recv()).get("data") or {} + except websocket.WebSocketTimeoutException: + continue + if d.get("b") and d.get("a"): + self.sol_usd = (float(d["b"]) + float(d["a"])) / 2 + except Exception: + time.sleep(2) + + def run(self) -> None: + import base64 + import websocket + while not self.stopped.is_set(): + try: + info = solana_rpc("getAccountInfo", [self.pool, {"encoding": "base64"}])["value"] + if info["owner"] == METEORA_DLMM or info["owner"] in CLMM_KINDS: + self._run_dlmm(info["owner"]) + continue + pool = raydium_pool(info["owner"], base64.b64decode(info["data"][0])) + if pool["mint0"] in (WSOL, *STABLES) and pool["mint1"] not in (WSOL, *STABLES): + token_vault, quote_vault, quote_mint = pool["vault1"], pool["vault0"], pool["mint0"] + else: + token_vault, quote_vault, quote_mint = pool["vault0"], pool["vault1"], pool["mint1"] + quote_is_sol = quote_mint == WSOL + if quote_is_sol: + self._start_sol_price() + accounts = solana_rpc("getMultipleAccounts", [[token_vault, quote_vault], + {"encoding": "jsonParsed", "commitment": "processed"}]) + amounts = {acc: v["data"]["parsed"]["info"]["tokenAmount"]["uiAmount"] + for acc, v in zip((token_vault, quote_vault), accounts["value"])} + self.ws = websocket.create_connection(SOLANA_WS, timeout=30) + ids = {} + for i, acc in enumerate((token_vault, quote_vault), start=1): + ids[i] = acc + self.ws.send(json.dumps({"jsonrpc": "2.0", "id": i, "method": "accountSubscribe", + "params": [acc, {"encoding": "jsonParsed", "commitment": "processed"}]})) + subs, slots = {}, {} + kind = "PumpSwap" if info["owner"] == PUMPSWAP else "Raydium" + self.out.put(("leader_status", f"{kind} пул {self.pool[:6]}… (Solana, в реальном времени)")) + last_ping = time.time() + while not self.stopped.is_set(): + if time.time() - last_ping > 30: + self.ws.ping() + last_ping = time.time() + try: + message = json.loads(self.ws.recv()) + except websocket.WebSocketTimeoutException: + continue + if "id" in message and "result" in message: + subs[message["result"]] = ids.get(message["id"]) + continue + params = message.get("params") or {} + acc = subs.get(params.get("subscription")) + if acc is None: + continue + try: + amounts[acc] = params["result"]["value"]["data"]["parsed"]["info"]["tokenAmount"]["uiAmount"] + slots[acc] = params["result"]["context"]["slot"] + except (KeyError, TypeError): + continue + # a swap changes both vaults in one slot: price only when both are from the same slot + if slots.get(token_vault) != slots.get(quote_vault): + continue + price = pool_price_usd(amounts, token_vault, quote_vault, self.sol_usd if quote_is_sol else 1.0) + if price: + self.out.put(("leader", (price, price))) + except Exception as exc: + if self.stopped.is_set(): + return + self.out.put(("leader_status", f"Нет связи с Solana: {exc}; переподключение…")) + time.sleep(3) + + +def bybit_tick(ticker: str) -> float: + """Price step of a Bybit USDT perpetual (public REST).""" + try: + with urllib.request.urlopen(f"https://api.bybit.com/v5/market/instruments-info?category=linear&symbol={ticker}", + timeout=10) as resp: + items = json.loads(resp.read())["result"]["list"] + return float(items[0]["priceFilter"]["tickSize"]) if items else 0.0 + except (OSError, ValueError, KeyError, IndexError): + return 0.0 + + +# -------------------------------------------------------------------------------------------- +# Window +# -------------------------------------------------------------------------------------------- + +def run_legacy_window() -> None: + """The previous window with every strategy (simple, adaptive, pulse, sums, Algo Hunter): py -3 scalp_hint.py --legacy""" + import tkinter as tk + from tkinter import messagebox, ttk + + import scalp_paper as sp + + settings = HintSettings() + root = tk.Tk() + root.title("Подсказка скальпера · MetaScalp") + root.geometry("940x960") + root.attributes("-topmost", True) + events: queue.Queue = queue.Queue() + book, tape, journal = OrderBook(), Tape(), Journal(settings) + paper = sp.PaperTrader(sp.PaperSettings(), settings) + engine = HintEngine(settings) + state = {"port": None, "doc": None, "feed": None, "name": "", "last_side": "WAIT", "recorder": None} + + header = tk.StringVar(value="Ищу MetaScalp…") + side_var = tk.StringVar(value="—") + plan_var = tk.StringVar(value="") + reasons_var = tk.StringVar(value="") + stats_var = tk.StringVar(value=journal.stats()) + follow = tk.BooleanVar(value=True) + + body = ttk.Frame(root, padding=10) + body.pack(fill="both", expand=True) + ttk.Label(body, textvariable=header, font=("Segoe UI", 10, "bold"), wraplength=860).pack(anchor="w") + top_row = ttk.Frame(body) + top_row.pack(fill="x") + ttk.Checkbutton(top_row, text="Следовать за стаканом, открытым в MetaScalp", variable=follow).pack(side="left") + sources = {"metascalp": "MetaScalp (стакан ~раз в 220 мс)", "bybit": "Bybit напрямую (стакан ~раз в 20 мс)"} + ttk.Label(top_row, text=" Источник стакана:").pack(side="left") + source_var = tk.StringVar(value=sources.get(paper.settings.data_source, sources["metascalp"])) + source_combo = ttk.Combobox(top_row, textvariable=source_var, values=list(sources.values()), state="readonly", + width=36) + source_combo.pack(side="left", padx=4) + latency_var = tk.StringVar(value="") + ttk.Label(top_row, textvariable=latency_var, foreground="#555").pack(side="left", padx=8) + latencies: deque[float] = deque(maxlen=300) + + def on_source_change(_event=None) -> None: + paper.settings.data_source = next(k for k, v in sources.items() if v == source_var.get()) + paper.ledger.save() + if state["doc"] is not None: + switch(state["doc"]) # reconnect with the new source + + source_combo.bind("<>", on_source_change) + side_label = tk.Label(body, textvariable=side_var, font=("Segoe UI", 22, "bold"), anchor="w") + side_label.pack(fill="x", pady=(8, 2)) + tk.Label(body, textvariable=plan_var, font=("Consolas", 11), justify="left", anchor="w").pack(fill="x") + bars = {} + for key, title in (("book_imb", "Стакан"), ("tape_delta", "Лента"), ("momentum", "Импульс")): + row = ttk.Frame(body) + row.pack(fill="x", pady=1) + ttk.Label(row, text=f"{title:8s}", width=9).pack(side="left") + canvas = tk.Canvas(row, height=14, width=300, highlightthickness=0, background="#e8e8e8") + canvas.pack(side="left") + value = ttk.Label(row, width=7) + value.pack(side="left", padx=4) + bars[key] = (canvas, value) + ttk.Label(body, textvariable=reasons_var, wraplength=860, justify="left").pack(anchor="w", pady=(8, 4)) + ttk.Label(body, textvariable=stats_var, wraplength=860, foreground="#334").pack(anchor="w") + + # --- paper trading ------------------------------------------------------------------- + paper_box = ttk.LabelFrame(body, text="Тестовые сделки (виртуальный счёт, ордера на биржу не уходят)", padding=6) + paper_box.pack(fill="both", expand=True, pady=(8, 0)) + ps = paper.settings + mode_row = ttk.Frame(paper_box) + mode_row.pack(fill="x", pady=(0, 4)) + ttk.Label(mode_row, text="Схема решений:").pack(side="left") + mode_var = tk.StringVar(value=sp.MODES.get(ps.mode, sp.MODES["adaptive"])) + mode_combo = ttk.Combobox(mode_row, textvariable=mode_var, values=list(sp.MODES.values()), state="readonly", + width=42) + mode_combo.pack(side="left", padx=6) + mode_combo.bind("<>", lambda _e: (show_mode_fields(), apply_paper())) + record_var = tk.BooleanVar(value=True) + ttk.Checkbutton(mode_row, text=f"Записывать поток в {sp.RECORD_DIR.name}\\ (для сравнения схем)", + variable=record_var).pack(side="left", padx=10) + # Common settings in the first row; the second row shows only the fields of the selected scheme. + common_fields = (("budget", "Бюджет, $"), ("stake", "Ставка, $"), ("leverage", "Плечо"), + ("min_target_pct", "Цель не меньше, %"), ("max_hold_minutes", "Макс. удержание, мин")) + mode_fields = { + "simple": (("adverse_ticks", "Закрыть при откате, шагов цены"),), + "adaptive": (("noise_mult", "Стоп × шум"), ("min_rr", "Прибыль / риск после комиссий")), + "pulse": (("pulse_offset_pct", "Лимитка от цены, %"),), + "sums": (("sums_depth_pct", "Глубина стакана, ±%"), ("sums_low_pct", "Без мелких: ниже перцентиля"), + ("sums_high_pct", "Без крупных: выше перцентиля"), ("sums_threshold", "Перевес для входа (0–1)")), + # Algo Hunter keeps its own config (algo_hunter_config.json); the key prefix "ah." marks those fields. + "algo_hunter": (("ah.min_confidence", "Мин. уверенность (0–1)"), ("ah.tp_ticks", "TP, шагов цены"), + ("ah.sl_ticks", "SL, шагов цены"), ("ah.max_hold_ms", "Удержание, мс"), + ("ah.min_entry_spread_ticks", "Мин. спред для входа,\nшагов цены (0 = выкл)")), + } + import algo_hunter as ah + ah_cfg = paper.algo_config or ah.AlgoHunterConfig.load() + paper.algo_config = ah_cfg + if ps.mode == "algo_hunter" and getattr(paper.policy, "cfg", None) is not ah_cfg: + paper.policy = paper._make_policy() + paper_vars: dict[str, tk.StringVar] = {} + mode_cells: dict[str, list] = {} + form = ttk.Frame(paper_box) + form.pack(fill="x") + + def add_field(key: str, label: str, row: int, column: int): + cell = ttk.Frame(form) + cell.grid(row=row, column=column, sticky="w", padx=(0, 8), pady=(0, 2)) + ttk.Label(cell, text=label).pack(anchor="w") + source = ah_cfg if key.startswith("ah.") else ps + var = tk.StringVar(value=f"{getattr(source, key.removeprefix('ah.')):g}") + ttk.Entry(cell, textvariable=var, width=12).pack(anchor="w") + paper_vars[key] = var + return cell + + for index, (key, label) in enumerate(common_fields): + add_field(key, label, 0, index) + mode_title = ttk.Label(form, text="", foreground="#1d4f91") + mode_title.grid(row=1, column=0, sticky="sw", pady=(4, 0)) + for mode, items in mode_fields.items(): + mode_cells[mode] = [add_field(key, label, 1, index + 1) for index, (key, label) in enumerate(items)] + invert_var = tk.BooleanVar(value=ps.sums_invert) + invert_cell = ttk.Checkbutton(form, text="Торговать против перевеса\n(LONG ↔ SHORT)", variable=invert_var, + command=lambda: apply_paper()) + invert_cell.grid(row=1, column=len(mode_fields["sums"]) + 1, sticky="sw", padx=(4, 0)) + mode_cells["sums"].append(invert_cell) + dry_run_var = tk.BooleanVar(value=ah_cfg.dry_run) + dry_run_cell = ttk.Checkbutton(form, text="Только проверка (dry-run):\nдетект и лог, без сделок", + variable=dry_run_var, command=lambda: apply_paper()) + dry_run_cell.grid(row=1, column=len(mode_fields["algo_hunter"]) + 1, sticky="sw", padx=(4, 0)) + mode_cells["algo_hunter"].append(dry_run_cell) + quick_exit_var = tk.BooleanVar(value=ah_cfg.quick_exit) + requote_var = tk.BooleanVar(value=ah_cfg.requote) + quick_cell = ttk.Frame(form) + quick_cell.grid(row=1, column=len(mode_fields["algo_hunter"]) + 2, sticky="sw", padx=(4, 0)) + ttk.Checkbutton(quick_cell, text="Закрывать на следующем тике\n(без TP/SL/времени)", variable=quick_exit_var, + command=lambda: apply_paper()).pack(anchor="w") + ttk.Checkbutton(quick_cell, text="Переставлять заявку за стаканом", variable=requote_var, + command=lambda: apply_paper()).pack(anchor="w") + fallback_var = tk.BooleanVar(value=ah_cfg.fallback) + ttk.Checkbutton(quick_cell, text="Без алгоса: микроцена + сдвиги спреда\n(заявка всегда стоит)", + variable=fallback_var, command=lambda: apply_paper()).pack(anchor="w") + mode_cells["algo_hunter"].append(quick_cell) + + def show_mode_fields(*_args) -> None: + mode = next((k for k, v in sp.MODES.items() if v == mode_var.get()), "adaptive") + mode_title.configure(text="Настройки схемы:") + for name, cells in mode_cells.items(): + for cell in cells: + if name == mode: + cell.grid() + else: + cell.grid_remove() + + show_mode_fields() + enabled_var = tk.BooleanVar(value=ps.enabled) + actions = ttk.Frame(paper_box) + actions.pack(fill="x", pady=(4, 2)) + ttk.Checkbutton(actions, text="Открывать тестовые сделки по сигналам", variable=enabled_var, + command=lambda: apply_paper()).pack(side="left") + ttk.Button(actions, text="Применить", command=lambda: apply_paper()).pack(side="left", padx=6) + ttk.Button(actions, text="Закрыть позицию", command=lambda: paper.close_now(book, time.time(), "вручную")).pack( + side="left") + ttk.Button(actions, text="Сбросить счёт", command=lambda: reset_paper()).pack(side="left", padx=6) + paper_summary = tk.StringVar(value=paper.summary()) + paper_position = tk.StringVar(value="") + paper_message = tk.StringVar(value="") + paper_status = tk.StringVar(value="") + ttk.Label(paper_box, textvariable=paper_summary, font=("Segoe UI", 10, "bold")).pack(anchor="w") + ttk.Label(paper_box, textvariable=paper_status, foreground="#1d4f91", wraplength=880).pack(anchor="w") + ttk.Label(paper_box, textvariable=paper_position, wraplength=880).pack(anchor="w") + ttk.Label(paper_box, textvariable=paper_message, foreground="#555", wraplength=860).pack(anchor="w") + columns = ("time", "ticker", "side", "qty", "usd", "entry", "exit", "pct", "net", "fee", "reason", "hold") + heads = {"time": "Закрыта (UTC)", "ticker": "Тикер", "side": "Напр.", "qty": "Объём", "usd": "Объём в $", + "entry": "Цена откр.", "exit": "Цена закр.", "pct": "Процент", "net": "Чистая, $", + "fee": "Комиссия, $", "reason": "Причина", "hold": "Сек."} + widths = {"time": 120, "ticker": 90, "side": 50, "qty": 70, "usd": 70, "entry": 80, "exit": 80, "pct": 65, + "net": 75, "fee": 75, "reason": 150, "hold": 45} + table_frame = ttk.Frame(paper_box) + table_frame.pack(fill="both", expand=True, pady=(4, 0)) + tree = ttk.Treeview(table_frame, columns=columns, show="headings", height=8) + for col in columns: + tree.heading(col, text=heads[col]) + tree.column(col, width=widths[col], anchor="center") + tree.tag_configure("win", foreground="#13843b") + tree.tag_configure("loss", foreground="#c62828") + scroll = ttk.Scrollbar(table_frame, orient="vertical", command=tree.yview) + tree.configure(yscrollcommand=scroll.set) + tree.pack(side="left", fill="both", expand=True) + scroll.pack(side="right", fill="y") + shown = {"count": -1} + + def apply_paper() -> None: + try: + values = {key: float(var.get().replace(",", ".")) for key, var in paper_vars.items()} + if values["stake"] <= 0 or values["budget"] <= 0 or not 1 <= values["leverage"] <= 100: + raise ValueError("ставка и бюджет больше 0, плечо от 1 до 100") + if values["min_target_pct"] < 0 or values["adverse_ticks"] < 1 or values["max_hold_minutes"] <= 0: + raise ValueError("цель ≥ 0, откат ≥ 1 шага, удержание > 0") + if values["noise_mult"] <= 0 or values["min_rr"] <= 0: + raise ValueError("множитель шума и прибыль/риск больше 0") + if values["pulse_offset_pct"] < 0: + raise ValueError("отступ лимитки не может быть отрицательным") + if not (values["sums_depth_pct"] > 0 and 0 <= values["sums_low_pct"] < values["sums_high_pct"] <= 100 + and 0 < values["sums_threshold"] < 1): + raise ValueError("глубина > 0, перцентили 0 ≤ мелкие < крупные ≤ 100, перевес от 0 до 1") + if not (0 < values["ah.min_confidence"] <= 1 and values["ah.tp_ticks"] >= 1 and values["ah.sl_ticks"] >= 1 + and values["ah.max_hold_ms"] > 0 and values["ah.min_entry_spread_ticks"] >= 0): + raise ValueError("Algo Hunter: уверенность от 0 до 1, TP и SL ≥ 1 шага (SL обязателен), удержание > 0, " + "мин. спред ≥ 0") + except ValueError as exc: + paper_message.set(f"Проверьте настройки: {exc}") + return + budget_changed = values["budget"] != ps.budget + # Settings that live only in algo_hunter_config.json may have been edited by hand: take them from the file. + on_disk = ah.AlgoHunterConfig.load() + for f in fields(ah.AlgoHunterConfig): + if f"ah.{f.name}" not in values and f.name not in ("dry_run", "quick_exit", "requote", "fallback"): + setattr(ah_cfg, f.name, getattr(on_disk, f.name)) + for key, value in values.items(): + if key.startswith("ah."): + name = key.removeprefix("ah.") + setattr(ah_cfg, name, type(getattr(ah_cfg, name))(value)) + else: + setattr(ps, key, int(value) if key == "adverse_ticks" else value) + ah_cfg.dry_run = bool(dry_run_var.get()) + ah_cfg.quick_exit = bool(quick_exit_var.get()) + ah_cfg.requote = bool(requote_var.get()) + ah_cfg.fallback = bool(fallback_var.get()) + ah_cfg.save() + if hasattr(paper.policy, "rearm"): + paper.policy.rearm() # «Применить» switches Algo Hunter back on after an adaptation shutdown + ps.enabled = bool(enabled_var.get()) + ps.sums_invert = bool(invert_var.get()) + mode = next((k for k, v in sp.MODES.items() if v == mode_var.get()), "adaptive") + if mode != ps.mode: + paper.close_now(book, time.time(), "смена схемы") + paper.set_mode(mode) + if budget_changed and not paper.trades and paper.position is None: + paper.ledger.balance = ps.budget + paper.ledger.save() + paper_message.set("Настройки тестовых сделок применены" + + (" · новый бюджет начнёт действовать после «Сбросить счёт»" + if budget_changed and (paper.trades or paper.position) else "")) + + def reset_paper() -> None: + apply_paper() + paper.reset() + shown["count"] = -1 + paper_message.set(f"Счёт сброшен: {ps.budget:g}$") + + ttk.Label(body, text="Это подсказка по текущему стакану, не гарантия. Ордера не отправляются. " + f"Журналы: {JOURNAL_FILE.name}, {sp.TRADES_FILE.name}; записи потока: " + f"{sp.RECORD_DIR.name}\\ (сравнение: py -3 scalp_paper.py compare)", wraplength=880, + foreground="#777").pack(anchor="w", side="bottom") + + def draw_bar(key: str, value: float) -> None: + canvas, label = bars[key] + canvas.delete("all") + width, mid = 300, 150 + x = mid + value * mid + canvas.create_line(mid, 0, mid, 14, fill="#999") + canvas.create_rectangle(min(mid, x), 2, max(mid, x), 12, fill="#2e9d57" if value >= 0 else "#d04a4a", + outline="") + label.configure(text=f"{value:+.2f}") + + def switch(doc: dict) -> None: + if state["feed"]: + state["feed"].stop() + journal.cancel("смена тикера") + paper.close_now(book, time.time(), "смена тикера") + book.clear() + tape.clear() + engine.reset() + state["last_side"] = "WAIT" + state["doc"] = doc + state["name"] = connection_name(state["port"], doc["connectionId"]) + if state["recorder"]: + state["recorder"].close() + state["recorder"] = None + if record_var.get(): + try: + state["recorder"] = sp.Recorder(doc["ticker"], doc["connectionId"], doc["tick"]) + except OSError as exc: + paper_message.set(f"Запись потока недоступна: {exc}") + latencies.clear() + paper.data_latency_ms = None + feed = None + if paper.settings.data_source == "bybit": + info = connection_info(state["port"], doc["connectionId"]) + if info.get("Exchange") == "Bybit" and "USDT" in str(info.get("Market", "")) \ + and "Perpetual" in str(info.get("Market", "")): + feed = BybitFeed(doc["ticker"], events) + else: + paper_message.set(f"Bybit напрямую доступен только для фьючерсов Bybit USDT; {doc['ticker']} " + f"({info.get('Name', '?')}) читается через MetaScalp") + if feed is None: + feed = Feed(state["port"], doc["connectionId"], doc["ticker"], events) + state["feed"] = feed + state["source_name"] = "Bybit напрямую" if isinstance(feed, BybitFeed) else "MetaScalp" + feed.start() + + def poll_ui() -> None: + try: + if state["port"] is None: + state["port"] = discover_port() + if state["port"] is None: + header.set("MetaScalp не найден на 127.0.0.1:17845–17855 — запустите терминал") + if state["port"] is not None and follow.get(): + doc = active_order_book(state["port"]) + if doc and (state["doc"] is None or (doc["connectionId"], doc["ticker"]) != + (state["doc"]["connectionId"], state["doc"]["ticker"])): + switch(doc) + elif doc is None and state["doc"] is None: + header.set("Откройте стакан в MetaScalp") + except Exception as exc: + header.set(f"Ошибка API MetaScalp: {exc}") + state["port"] = None + root.after(2000, poll_ui) + + def pump() -> None: + if record_var.get() and state["recorder"] is None and state["doc"] is not None: + try: + doc = state["doc"] + state["recorder"] = sp.Recorder(doc["ticker"], doc["connectionId"], doc["tick"]) + except OSError: + pass + recorder = state["recorder"] if record_var.get() else None + for _ in range(5000): + try: + kind, data = events.get_nowait() + except queue.Empty: + break + # Receive time is used everywhere (tape, paper trades, recording) so a replay of the + # recording sees exactly the same sequence as the window. + now = time.time() + if kind == "book_snapshot": + book.apply_snapshot(data) + if recorder: + recorder.write("S", {"asks": data.get("asks", []), "bids": data.get("bids", []), + "bestAsk": data.get("bestAsk"), "bestBid": data.get("bestBid")}, now) + if state["doc"]: + paper.on_book(now, book, state["doc"]["tick"]) + elif kind == "book_update": + book.apply_updates(data) + if recorder: + recorder.write("U", data, now) + if state["doc"]: + paper.on_book(now, book, state["doc"]["tick"]) + elif kind == "latency": + latencies.append(float(data)) + if len(latencies) >= 5: + paper.data_latency_ms = statistics.median(latencies) + elif kind == "trades": + if recorder: + recorder.write("T", data, now) + for raw in data: + try: + trade = Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) + except (KeyError, TypeError, ValueError): + continue + tape.add(trade) + journal.on_trade(trade) + paper.on_trade(trade) + elif kind == "status": + header.set(data) + root.after(100, pump) + + def refresh() -> None: + doc = state["doc"] + if doc: + hint = engine(book, tape, doc["tick"], time.time()) + m = hint.metrics + header.set(f"{doc['ticker']} · {state['name']} · данные: {state.get('source_name', '')}" + + (f" · цена {m['mid']:.10g} · спред {m['spread_pct']:.3f}%" if m else "")) + if paper.data_latency_ms is not None: + latency_var.set(f"задержка данных ~{paper.data_latency_ms:.0f} мс (по часам Bybit)") + if (paper.settings.mode == "algo_hunter" and not state.get("latency_warned") + and paper.data_latency_ms > ah_cfg.max_data_latency_ms): + state["latency_warned"] = True + messagebox.showwarning( + "Algo Hunter: задержка слишком большая", + f"Данные приходят с задержкой ~{paper.data_latency_ms:.0f} мс (порог " + f"{ah_cfg.max_data_latency_ms:g} мс). Реальную гонку за место в очереди перед алгосом " + "с такой задержкой не выиграть: режим полезен только как проверка (dry-run) и для " + "виртуальной статистики, а RiskGuard не пустит виртуальные входы при задержке выше " + f"{ah_cfg.max_order_latency_ms:g} мс.", parent=root) + colors = {"LONG": "#1f8a4c", "SHORT": "#c23b3b", "WAIT": "#666"} + side_label.configure(fg=colors[hint.side]) + if hint.side == "WAIT": + side_var.set("ЖДАТЬ") + plan_var.set("") + else: + mid = m["mid"] + side_var.set(f"{hint.side} · уверенность {hint.confidence}") + plan_var.set( + f"Вход лимиткой {hint.entry:.10g} ({(hint.entry / mid - 1) * 100:+.2f}%)\n" + f"Стоп {hint.stop:.10g} ({(hint.stop / mid - 1) * 100:+.2f}%)\n" + f"Цель {hint.target:.10g} ({(hint.target / mid - 1) * 100:+.2f}%)\n" + f"Риск/прибыль 1:{hint.rr:.1f} стоп по времени {settings.hold_minutes:g} мин") + if state["last_side"] != hint.side: + journal.offer(doc["ticker"], hint, time.time()) + state["last_side"] = hint.side + for key in bars: + draw_bar(key, m.get(key, 0.0) if m else 0.0) + reasons_var.set("\n".join("• " + r for r in hint.reasons)) + active = journal.active + stats_var.set("Проверка подсказок лимиткой: " + journal.stats() + ( + f"\nПроверяется: {active.side} от {active.entry:.10g} — " + + ("ждём исполнения" if active.filled_at is None else "в позиции") if active else "")) + if book.asks and book.bids: + paper.on_tick(time.time(), doc["ticker"], hint, book, doc["tick"]) + pos = paper.position + order = paper.pending_order() + if pos: + pnl = paper.unrealized(book) + if paper.settings.mode == "pulse": + plan = "закрытие по рынку на следующем тике" + elif paper.settings.mode == "sums": + plan = (f"цель {pos.target:.10g} · выход при развороте перевеса или через " + f"{paper.settings.max_hold_minutes:g} мин") + else: + plan = (f"цель {pos.target:.10g} · " + (f"стоп {pos.stop:.10g}" if pos.stop is not None else + f"закрытие при откате на {paper.settings.adverse_ticks} шаг(а)")) + paper_position.set( + f"Позиция: {pos.side} {pos.ticker} {pos.qty:.6g} по {pos.entry:.10g} ({pos.entry * pos.qty:.2f}$) · " + f"{plan}{' · ' + pos.regime if pos.regime else ''} · сейчас {pnl:+.4f}$") + elif order and paper.settings.mode == "algo_hunter": + ahead = f"{order.ahead:,.0f}$" if order.ahead is not None else "ещё не на бирже" + paper_position.set(f"Лимитка {order.side} {order.price:.10g} ({order.scenario}) · в очереди перед нами " + f"{ahead} · впереди алгоса: {'да' if order.front_run else 'пока нет'}") + elif order and paper.settings.mode == "sums": + paper_position.set(f"Лимитка {order.side} {order.price:.10g} по лучшей цене — держится, пока есть перевес · " + f"цель {order.target:.10g}") + elif order and paper.settings.mode == "pulse": + paper_position.set(f"Лимитка {order.side} {order.price:.10g} — снимется и переставится на следующем тике, " + "если не исполнится") + elif order: + paper_position.set(f"Ждёт исполнения: лимитка {order.side} {order.price:.10g} ({order.regime}) · стоп " + f"{order.stop:.10g} · цель {order.target:.10g} · {time.time() - order.created:.0f} с") + else: + paper_position.set("Позиции нет" + ("" if paper.settings.enabled else " · тестовые сделки выключены")) + status = paper.policy.status + if paper.settings.mode == "pulse": + status = "Импульс + стакан: " + status + elif paper.settings.mode == "sums": + status = "Суммы: " + status + elif paper.settings.mode == "algo_hunter": + status = "Algo Hunter: " + status + elif paper.settings.mode == "adaptive": + weights = ", ".join(f"{k} {v:.2f}" for k, v in settings.weights.items()) + status = f"Адаптивная: {status}\nВеса признаков: {weights}" + paper_status.set(status) + paper_summary.set(paper.summary()) + if paper.message: + paper_message.set(paper.message) + if shown["count"] != len(paper.trades): + shown["count"] = len(paper.trades) + tree.delete(*tree.get_children()) + for t in reversed(paper.trades[-300:]): + tree.insert("", "end", values=( + t.closed_utc[:19].replace("T", " "), t.ticker, t.side, f"{t.qty:.6g}", f"{t.notional_usd:.2f}", + f"{t.entry:.10g}", f"{t.exit:.10g}", f"{t.pct:+.3f}%", f"{t.net_usd:+.4f}", f"{t.fee_usd:.4f}", + t.reason, f"{t.hold_seconds:.0f}"), tags=("win" if t.net_usd > 0 else "loss",)) + root.after(500, refresh) + + def on_close() -> None: + if state["recorder"]: + state["recorder"].close() + if state["feed"]: + state["feed"].stop() + root.destroy() + + root.protocol("WM_DELETE_WINDOW", on_close) + poll_ui() + pump() + refresh() + root.mainloop() + + +def run_console(seconds: float) -> None: + """Headless check: print a hint every few seconds (used for testing the connection).""" + settings = HintSettings() + port = discover_port() + if port is None: + raise SystemExit("MetaScalp не найден") + doc = active_order_book(port) + if not doc: + raise SystemExit("В MetaScalp не открыт стакан") + events: queue.Queue = queue.Queue() + book, tape = OrderBook(), Tape() + engine = HintEngine(settings) + feed = Feed(port, doc["connectionId"], doc["ticker"], events) + feed.start() + end = time.time() + seconds + next_print = time.time() + 5 + while time.time() < end: + try: + kind, data = events.get(timeout=0.2) + if kind == "book_snapshot": + book.apply_snapshot(data) + elif kind == "book_update": + book.apply_updates(data) + elif kind == "trades": + for raw in data: + tape.add(Trade(parse_time(raw.get("time")), float(raw["price"]), float(raw["size"]), raw["side"])) + except queue.Empty: + pass + hint = engine(book, tape, doc["tick"], time.time()) if book.asks else None + if hint and time.time() >= next_print: + next_print = time.time() + 5 + plan = (f" вход {hint.entry:.10g} стоп {hint.stop:.10g} цель {hint.target:.10g} 1:{hint.rr:.1f}" + if hint.side != "WAIT" else "") + print(f"{doc['ticker']} {hint.side} ({hint.confidence}, score {hint.score:+.2f}){plan}") + for reason in hint.reasons: + print(" ", reason) + feed.stop() + + +if __name__ == "__main__": + import sys + if len(sys.argv) > 2 and sys.argv[1] == "--console": + run_console(float(sys.argv[2])) + elif len(sys.argv) > 1 and sys.argv[1] == "--legacy": + run_legacy_window() + else: + import lead_window + lead_window.run() diff --git a/scalp_paper.py b/scalp_paper.py new file mode 100644 index 0000000..64a158e --- /dev/null +++ b/scalp_paper.py @@ -0,0 +1,1394 @@ +"""Paper trading for the scalping hint: a virtual ledger, two decision policies, a stream recorder +and an offline replay that runs any policy over a recorded MetaScalp stream. + +Policies +* simple - market entry whenever the hint is actionable and its target is at least min_target_pct away; + exit at the target (limit), as soon as the mid price moves `adverse_ticks` against the entry, + or on the time stop. +* adaptive - decides from the market state: + - noise: the typical 30-second price swing; the stop sits beyond it (never one tick); + - regime: trend when the last minutes moved efficiently in one direction, otherwise range; + trend -> join the move with a passive limit; range -> fade only at the edge of the range + (near a density), never in the middle; + - costs: the target after fees must be at least min_rr x the stop after fees and slippage; + - self-tuning: component weights move towards what worked, and a losing streak raises the + entry threshold and pauses trading for a while. +No order is ever sent to an exchange. +""" + +from __future__ import annotations + +import csv +import gzip +import json +import math +import statistics +import sys +import time +from collections import deque +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path + +import scalp_hint as sh + +ROOT = Path(__file__).resolve().parent +STATE_FILE = ROOT / "scalp_paper_state.json" +TRADES_FILE = ROOT / "scalp_paper_trades.csv" +RECORD_DIR = ROOT / "scalp_recordings" +MAKER = sh.MAKER_FEE_PCT +TAKER = sh.TAKER_FEE_PCT +# (taker, maker) fees in % of the USDT perpetuals the lead/vector modes trade on (public base rates) +FOLLOW_FEES = {"bybit": (0.055, 0.02), "binance": (0.05, 0.02), "mexc": (0.02, 0.0)} +COLUMNS = ["closed_utc", "ticker", "mode", "side", "qty", "notional_usd", "entry", "exit", "pct", "net_usd", + "fee_usd", "reason", "hold_seconds", "regime"] +MODES = {"simple": "Простая (вход по рынку, выход при откате)", "adaptive": "Адаптивная", + "pulse": "Импульс + стакан (лимитка, выход на следующем тике)", + "sums": "Суммы значимых заявок (перевес стакана без мелких и крупных)", + "algo_hunter": "Algo Hunter (охота на маркет-мейкерские алгоритмы)", + "lead": "Ведущая биржа: KuCoin → ставки на Bybit", + "vector": "Вектор KuCoin → ставка на Bybit (+цель %)", + "basis": "Разрыв цен ведущей и фьючерса → ставка на схождение"} + + +@dataclass +class PaperSettings: + enabled: bool = True + mode: str = "adaptive" + data_source: str = "metascalp" # "metascalp" or "bybit" (direct public WebSocket, Bybit pairs only) + budget: float = 300.0 + stake: float = 5.0 + leverage: float = 1.0 + min_target_pct: float = 0.2 + max_hold_minutes: float = 5.0 + cooldown_seconds: float = 15.0 + cooldown_ms: float = 0.0 # lead / vector / basis modes: pause after a trade, milliseconds + # simple policy + adverse_ticks: int = 1 + # adaptive policy + noise_mult: float = 1.5 # stop beyond this many typical 30-second swings + min_rr: float = 1.5 # net reward / net risk after fees + limit_timeout_seconds: float = 60.0 + regime_minutes: float = 5.0 + trend_efficiency: float = 0.35 # net move / path length above which the market trends + edge_share: float = 0.25 # range edge = outer quarter of the recent range + reversal_threshold: float = 0.15 # book-based confirmation needed to fade a range edge + loss_streak: int = 3 # losses in a row that trigger a pause + pause_minutes: float = 3.0 + learning: bool = True + learn_rate: float = 0.1 + # pulse policy + pulse_offset_pct: float = 0.15 # limit order at least this far from the current price + # significant-orders policy + sums_depth_pct: float = 0.3 # book window around the mid price + sums_low_pct: float = 20.0 # drop levels smaller than this percentile of sizes (noise) + sums_high_pct: float = 90.0 # drop levels larger than this percentile (outsized walls) + sums_threshold: float = 0.2 # |imbalance| needed to enter; the opposite imbalance closes + sums_invert: bool = False # trade against the imbalance (SHORT on buyer dominance and vice versa) + # lead-exchange policy: a leader exchange's move predicts the follower (where the paper trades are made) + lead_market: str = "futures" # leader: KuCoin "futures", KuCoin "spot" or a "raydium" pool on Solana + lead_pool: str = "" # Raydium pool address (AMM v4 / CPMM) when lead_market == "raydium" + follow_exchange: str = "bybit" # where the paper trades are made: "bybit", "binance" or "mexc" perpetuals + lead_ticker: str = "MARSCOINUSDTM" # KuCoin futures contract (MARSCOINUSDTM) or spot pair (MARSCOIN-USDT) + follow_ticker: str = "MARSCOINUSDT" # Bybit USDT perpetual + lead_threshold_pct: float = 0.05 # leader moved this much more than the follower within the window + lead_window_ms: float = 500.0 + stop_loss_pct: float = 0.3 + max_hold_seconds: float = 30.0 + max_data_age_ms: float = 2000.0 # no entry when either feed has been silent longer than this + min_confidence: float = 0.0 # lead/vector: enter only when the signal's confidence (0-1) is this high + # automatic take-profit: forecast of the follower's move from how far it lags behind the leader + auto_tp: bool = False + auto_tp_share_pct: float = 100.0 # share of the lag the follower is expected to catch up (when not learnt) + auto_tp_learn: bool = True # learn that share from what actually happened after past signals + auto_tp_horizon_seconds: float = 10.0 # ...measured this long after each signal + max_positions: int = 1 # parallel positions (each one stake) in the lead/vector modes + entry_gap_seconds: float = 1.0 # at least this long between two entries + one_per_tick: bool = True # at most one open position per price step (and side) of Bybit's book + cut_loss: bool = False # close at once when Bybit's mid goes against the entry, then go on + cut_loss_ticks: int = 1 # ...by this many price steps (mid vs mid at entry, so the spread + # paid on entry alone does not trigger it); no pause after such a close + # live leader check (all lead modes): who actually moves first right now, from the last minutes of prices + require_leader: bool = True # no entries while the follower, not the leader, moves first + leader_min_edge: float = 0.1 # leader→follower correlation must beat follower→leader by this much + auto_stop_pct: float = 20.0 # web simulator: stop a pair when the futures lead the leader by this + # share, % of (follower→leader − leader→follower) / both; 0 = off + # basis policy: the price gap leader − follower vs its usual level; bet on the gap closing + basis_window_seconds: float = 60.0 # usual gap = exponential average over about this long + basis_entry_z: float = 2.0 # enter when the gap is this many standard deviations from usual + basis_exit_z: float = 0.5 # close when it is back within this many + basis_min_gap_pct: float = 0.15 # ...and only when the extra gap is at least this large (fees) + # vector policy: KuCoin's direction over a longer window, bet on Bybit moving the same way + vector_window_seconds: float = 5.0 + vector_min_move_pct: float = 0.1 + + +@dataclass +class Position: + ticker: str + side: str + qty: float + entry: float + target: float + stop: float | None + opened: float + fee_in: float + entry_mid: float + regime: str = "" + features: dict = field(default_factory=dict) + uid: int = 0 # unique per ledger, so one of several open positions can be closed by hand + + +@dataclass +class Order: + ticker: str + side: str + price: float + target: float + stop: float + created: float + regime: str + features: dict + + +@dataclass +class PaperTrade: + closed_utc: str + ticker: str + mode: str + side: str + qty: float + notional_usd: float + entry: float + exit: float + pct: float + net_usd: float + fee_usd: float + reason: str + hold_seconds: float + regime: str = "" + + +class Ledger: + def __init__(self, settings: PaperSettings, state_path: Path | None = None, + trades_path: Path | None = None) -> None: + self.settings = settings + self.state_path = state_path + self.trades_path = trades_path + self.balance = settings.budget + self.positions: list[Position] = [] + self.trades: list[PaperTrade] = [] + self.hooks: list = [] # hook(event, pos): "open" / "close" — real trading mirrors the paper positions + self._load() + + def _load(self) -> None: + 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)) + 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): + pass + if self.trades_path: + header: list[str] = [] + try: + with self.trades_path.open(encoding="utf-8-sig") as file: + reader = csv.DictReader(file) + header = list(reader.fieldnames or []) + for row in reader: + self.trades.append(PaperTrade( + row["closed_utc"], row["ticker"], row.get("mode") or "simple", row["side"], + float(row["qty"]), float(row["notional_usd"]), float(row["entry"]), float(row["exit"]), + float(row["pct"]), float(row["net_usd"]), float(row["fee_usd"]), row["reason"], + float(row["hold_seconds"]), row.get("regime") or "")) + except (OSError, KeyError, ValueError): + pass + if header and header != COLUMNS: + self._rewrite() # an older journal without the mode/regime columns + + def _rewrite(self) -> None: + try: + with self.trades_path.open("w", encoding="utf-8-sig", newline="") as file: + writer = csv.writer(file) + writer.writerow(COLUMNS) + for t in self.trades: + writer.writerow([t.closed_utc, t.ticker, t.mode, t.side, f"{t.qty:.8g}", f"{t.notional_usd:.4f}", + f"{t.entry:.10g}", f"{t.exit:.10g}", f"{t.pct:.4f}", f"{t.net_usd:.6f}", + f"{t.fee_usd:.6f}", t.reason, f"{t.hold_seconds:.1f}", t.regime]) + except OSError: + pass + + def 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 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) + self.balance = self.settings.budget + self.position = None + self.trades = [] + if self.trades_path: + try: + self.trades_path.unlink() + except OSError: + pass + self.save() + + 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 + qty = notional / price + fee = notional * fee_pct / 100 + 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) + self.positions.append(pos) + self.save() + for hook in self.hooks: + hook("open", pos) + return pos + + @property + def position(self) -> Position | None: + """The first open position (the single position of every mode except parallel lead/vector trading).""" + return self.positions[0] if self.positions else None + + @position.setter + def position(self, value: Position | None) -> None: + self.positions = [] if value is None else [value] + + def close(self, price: float, now: float, reason: str, fee_pct: float, utc: str | None = None, + pos: Position | None = None) -> PaperTrade: + pos = pos or self.position + assert pos is not None + self.positions.remove(pos) + for hook in self.hooks: + hook("close", pos) + sign = 1 if pos.side == "LONG" else -1 + gross = sign * (price - pos.entry) * pos.qty + fee_out = price * pos.qty * fee_pct / 100 + self.balance += gross - fee_out + trade = PaperTrade(utc or datetime.now(timezone.utc).isoformat(timespec="seconds"), pos.ticker, + self.settings.mode, pos.side, pos.qty, pos.entry * pos.qty, pos.entry, price, + sign * (price / pos.entry - 1) * 100, gross - pos.fee_in - fee_out, pos.fee_in + fee_out, + reason, max(0.0, now - pos.opened), pos.regime) + self.trades.append(trade) + if self.trades_path: + new_file = not self.trades_path.exists() + try: + with self.trades_path.open("a", encoding="utf-8-sig", newline="") as file: + writer = csv.writer(file) + if new_file: + writer.writerow(COLUMNS) + writer.writerow([trade.closed_utc, trade.ticker, trade.mode, trade.side, f"{trade.qty:.8g}", + f"{trade.notional_usd:.4f}", f"{trade.entry:.10g}", f"{trade.exit:.10g}", + f"{trade.pct:.4f}", f"{trade.net_usd:.6f}", f"{trade.fee_usd:.6f}", + trade.reason, f"{trade.hold_seconds:.1f}", trade.regime]) + except OSError: + pass + self.save() + return trade + + +def _round(price: float, tick: float, up: bool | None) -> float: + return sh._to_tick(price, tick, up) + + +class SimplePolicy: + name = "simple" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.status = "" + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + led = trader.ledger + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return + mid = (best_bid + best_ask) / 2 + pos = led.position + if pos is not None: + long = pos.side == "LONG" + exit_price = best_bid if long else best_ask + against = (pos.entry_mid - mid) if long else (mid - pos.entry_mid) + if against >= self.s.adverse_ticks * tick - tick * 1e-6: + trader.close(exit_price, now, "курс против — закрыто", TAKER) + elif now - pos.opened >= self.s.max_hold_minutes * 60: + trader.close(exit_price, now, "время", TAKER) + return + if not self.s.enabled or hint.side == "WAIT" or hint.target is None: + return + if now - trader.last_close < self.s.cooldown_seconds: + return + long = hint.side == "LONG" + entry = best_ask if long else best_bid + target_pct = (hint.target - entry) / entry * 100 * (1 if long else -1) + if target_pct < self.s.min_target_pct: + trader.message = (f"Сигнал {hint.side}, но до цели {target_pct:.2f}% < {self.s.min_target_pct:g}% — " + "сделка не открыта") + return + if led.balance < self.s.stake: + trader.message = "Баланс меньше ставки — сделки остановлены" + return + led.open(ticker, hint.side, entry, now, TAKER, hint.target, None, mid) + trader.message = f"Открыта {hint.side} {ticker} по {entry:.10g}, цель {hint.target:.10g} (+{target_pct:.2f}%)" + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + pos = trader.ledger.position + if pos is not None: + hit = trade.price > pos.target if pos.side == "LONG" else trade.price < pos.target + if hit: + trader.close(pos.target, trade.ts, "цель", MAKER) + + +class AdaptivePolicy: + name = "adaptive" + + def __init__(self, settings: PaperSettings, hint_settings: sh.HintSettings) -> None: + self.s = settings + self.hs = hint_settings + self.samples: deque[tuple[float, float]] = deque() + self.order: Order | None = None + self.losses = 0 + self.bump = 0.0 + self.pause_until = 0.0 + self.status = "Накапливаю статистику рынка…" + self.base_weights = dict(sh.DEFAULT_WEIGHTS) + + # --- market state ------------------------------------------------------------------ + def market(self, now: float) -> dict | None: + horizon = self.s.regime_minutes * 60 + recent = [(t, m) for t, m in self.samples if t >= now - horizon] + if len(recent) < 20 or recent[-1][0] - recent[0][0] < 0.6 * horizon: + return None + buckets: dict[int, list[float]] = {} + for t, m in self.samples: + if t >= now - 600: + lo_hi = buckets.setdefault(int(t // 30), [m, m]) + lo_hi[0], lo_hi[1] = min(lo_hi[0], m), max(lo_hi[1], m) + noise = statistics.median(hi - lo for lo, hi in buckets.values()) if buckets else 0.0 + points: dict[int, float] = {} + for t, m in recent: + points[int(t // 5)] = m + series = [points[k] for k in sorted(points)] + path = sum(abs(b - a) for a, b in zip(series, series[1:])) + move = series[-1] - series[0] + mids = [m for _, m in recent] + return {"noise": noise, "efficiency": abs(move) / path if path > 0 else 0.0, "move": move, + "high": max(mids), "low": min(mids)} + + # --- main loop --------------------------------------------------------------------- + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return + mid = (best_bid + best_ask) / 2 + self.samples.append((now, mid)) + while self.samples and self.samples[0][0] < now - 900: + self.samples.popleft() + led = trader.ledger + pos = led.position + if pos is not None: + if now - pos.opened >= self.s.max_hold_minutes * 60: + trader.close(best_bid if pos.side == "LONG" else best_ask, now, "время", TAKER) + return + state = self.market(now) + if state is None: + self.status = f"Накапливаю статистику рынка ({self.s.regime_minutes:g} мин)…" + return + trend = state["efficiency"] >= self.s.trend_efficiency and abs(state["move"]) >= 2 * state["noise"] + regime_text = (f"{'тренд ' + ('вверх' if state['move'] > 0 else 'вниз') if trend else 'боковик'} " + f"{state['low']:.10g}–{state['high']:.10g} · шум 30 с {state['noise'] / mid * 100:.3f}% · " + f"направленность {state['efficiency']:.2f}") + threshold = self.hs.score_threshold + self.bump + self.status = regime_text + f" · порог {threshold:.2f}" + ( + f" · пауза ещё {self.pause_until - now:.0f} с" if now < self.pause_until else "") + if self.order is not None: + order = self.order + direction = 1 if order.side == "LONG" else -1 + if now - order.created > self.s.limit_timeout_seconds: + self.order = None + trader.message = f"Лимитка {order.side} {order.price:.10g} снята: не исполнилась за " \ + f"{self.s.limit_timeout_seconds:.0f} с" + elif hint.score * direction < -threshold: + self.order = None + trader.message = f"Лимитка {order.side} снята: перевес сменился" + return + if (not self.s.enabled or now < self.pause_until or now - trader.last_close < self.s.cooldown_seconds + or not hint.metrics or led.balance < self.s.stake): + return + spread = best_ask - best_bid + min_risk = max(self.s.noise_mult * state["noise"], 2 * spread, mid * 0.001, 2 * tick) + score = hint.score + metrics = hint.metrics + if trend: + direction = 1 if state["move"] > 0 else -1 + if score * direction < 0.6 * threshold: + return + side = "LONG" if direction > 0 else "SHORT" + entry = best_bid if direction > 0 else best_ask + stop = entry - direction * min_risk + target = entry + direction * max(mid * self.s.min_target_pct / 100, 2 * min_risk) + regime = "тренд" + else: + width = state["high"] - state["low"] + if width < 2 * state["noise"] or width <= 0: + self.status += " · узкий боковик (меньше двух шумов) — не торгую" + return + where = (mid - state["low"]) / width + # At a range edge the tape and momentum point INTO the edge by construction (price just got + # there), so a reversal is confirmed by the book: imbalance near the price and absorption. + reversal = (0.5 * metrics.get("book_imb", 0.0) + 0.25 * metrics.get("near_imb", 0.0) + + 0.25 * metrics.get("absorption", 0.0)) + edge_threshold = self.s.reversal_threshold + self.bump + self.status += f" · разворот {reversal:+.2f} (нужно ±{edge_threshold:.2f})" + if where <= self.s.edge_share and reversal >= edge_threshold: + direction = 1 + anchor = state["low"] + if metrics.get("support"): + anchor = min(anchor, metrics["support"][0]) + entry = best_bid + stop = min(anchor - max(0.5 * state["noise"], 2 * tick), entry - min_risk) + target = state["high"] - tick + regime = "боковик: нижний край" + elif where >= 1 - self.s.edge_share and reversal <= -edge_threshold: + direction = -1 + anchor = state["high"] + if metrics.get("resistance"): + anchor = max(anchor, metrics["resistance"][0]) + entry = best_ask + stop = max(anchor + max(0.5 * state["noise"], 2 * tick), entry + min_risk) + target = state["low"] + tick + regime = "боковик: верхний край" + else: + self.status += (" · середина диапазона — жду края" if self.s.edge_share < where < 1 - self.s.edge_share + else " · у края, но перевеса стакана/ленты нет") + return + side = "LONG" if direction > 0 else "SHORT" + long = direction > 0 + entry = _round(entry, tick, None) + stop = _round(stop, tick, up=not long) + target = _round(target, tick, up=not long) + risk_pct = abs(entry - stop) / entry * 100 + reward_pct = (target - entry) / entry * 100 * direction + if reward_pct < self.s.min_target_pct: + trader.message = f"{side} ({regime}): до цели {reward_pct:.2f}% < {self.s.min_target_pct:g}% — пропуск" + return + net_reward = reward_pct - 2 * MAKER + net_risk = risk_pct + MAKER + TAKER + tick / entry * 100 + if net_reward < self.s.min_rr * net_risk: + trader.message = (f"{side} ({regime}): прибыль {net_reward:.2f}% против риска {net_risk:.2f}% " + f"после комиссий — хуже 1:{self.s.min_rr:g}, пропуск") + return + features = {k: float(metrics.get(k, 0.0)) for k in sh.DEFAULT_WEIGHTS} + self.order = Order(ticker, side, entry, target, stop, now, regime, features) + trader.message = (f"Лимитка {side} {entry:.10g} ({regime}) · стоп {stop:.10g} (−{risk_pct:.2f}%) · " + f"цель {target:.10g} (+{reward_pct:.2f}%)") + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + led = trader.ledger + if self.order is not None: + order = self.order + through = trade.price < order.price if order.side == "LONG" else trade.price > order.price + if through: + self.order = None + led.open(order.ticker, order.side, order.price, trade.ts, MAKER, order.target, order.stop, + order.price, order.regime, order.features) + trader.message = f"Лимитка {order.side} исполнена по {order.price:.10g} ({order.regime})" + pos = led.position + if pos is None: + return + long = pos.side == "LONG" + if pos.stop is not None and (trade.price <= pos.stop if long else trade.price >= pos.stop): + # A stop-market fills at the stop or worse: one tick of slippage beyond the stop. + slip = abs(pos.entry) * 0.0002 + trader.close(pos.stop - slip if long else pos.stop + slip, trade.ts, "стоп", TAKER) + elif trade.price > pos.target if long else trade.price < pos.target: + trader.close(pos.target, trade.ts, "цель", MAKER) + + def on_close(self, trade: PaperTrade, features: dict, now: float) -> None: + if trade.net_usd < 0: + self.losses += 1 + if self.losses >= self.s.loss_streak: + self.pause_until = now + self.s.pause_minutes * 60 + self.bump = min(0.2, self.bump + 0.1) + self.losses = 0 + else: + self.losses = 0 + self.bump = max(0.0, self.bump - 0.05) + if self.s.learning and features: + outcome = 1.0 if trade.net_usd > 0 else -1.0 + direction = 1.0 if trade.side == "LONG" else -1.0 + weights = self.hs.weights + for key, base in self.base_weights.items(): + factor = math.exp(self.s.learn_rate * outcome * direction * features.get(key, 0.0)) + weights[key] = min(2 * base, max(0.5 * base, weights[key] * factor)) + scale = sum(self.base_weights.values()) / sum(weights.values()) + for key in weights: + weights[key] *= scale + + +class PulsePolicy: + """Impulse + book: a limit order `pulse_offset_pct` away from the price in the direction where the price + impulse and the book imbalance agree. A tick is the next trade at a different price: an unfilled order is + then cancelled and re-placed from the new price, and a filled position is closed at market. No time limits.""" + + name = "pulse" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.order: Order | None = None + self.hint: sh.Hint | None = None + self.book: sh.OrderBook | None = None + self.tick = 0.0 + self.ticker = "" + self.last_price: float | None = None + self.status = "Жду импульс и перекос стакана в одну сторону…" + + def direction(self) -> int: + """+1 / -1 when impulse and book agree, 0 otherwise.""" + m = self.hint.metrics if self.hint else {} + momentum, book_imb = m.get("momentum", 0.0), m.get("book_imb", 0.0) + if momentum > 0 and book_imb > 0: + return 1 + if momentum < 0 and book_imb < 0: + return -1 + return 0 + + def place(self, trader: "PaperTrader", now: float) -> None: + self.order = None + if not self.s.enabled or self.book is None or self.hint is None or trader.ledger.position is not None: + return + if trader.ledger.balance < self.s.stake: + self.status = "Баланс меньше ставки — сделки остановлены" + return + best_bid, best_ask = self.book.best() + if best_bid is None or best_ask is None or self.tick <= 0: + return + m = self.hint.metrics + direction = self.direction() + if direction == 0: + self.status = (f"Импульс {m.get('momentum', 0.0):+.2f} и стакан {m.get('book_imb', 0.0):+.2f} " + "смотрят в разные стороны — заявки нет") + return + mid = (best_bid + best_ask) / 2 + offset = self.s.pulse_offset_pct / 100 + long = direction > 0 + price = _round(mid * (1 - offset), self.tick, up=False) if long else _round(mid * (1 + offset), self.tick, up=True) + side = "LONG" if long else "SHORT" + self.order = Order(self.ticker, side, price, price, price, now, "импульс + стакан", {}) + self.status = (f"Импульс {m.get('momentum', 0.0):+.2f}, стакан {m.get('book_imb', 0.0):+.2f} → {side}: " + f"лимитка {price:.10g} ({'−' if long else '+'}{self.s.pulse_offset_pct:g}% от {mid:.10g})") + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + self.hint, self.book, self.tick, self.ticker = hint, book, tick, ticker + if self.order is None and trader.ledger.position is None: + self.place(trader, now) + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + new_tick = self.last_price is not None and trade.price != self.last_price + led = trader.ledger + pos = led.position + if pos is not None and new_tick: + best_bid, best_ask = self.book.best() if self.book else (None, None) + exit_price = (best_bid if pos.side == "LONG" else best_ask) or trade.price + trader.close(exit_price, trade.ts, "следующий тик", TAKER) + self.place(trader, trade.ts) + elif self.order is not None: + order = self.order + through = trade.price < order.price if order.side == "LONG" else trade.price > order.price + if through: + self.order = None + led.open(order.ticker, order.side, order.price, trade.ts, MAKER, order.price, None, order.price, + order.regime) + trader.message = f"Лимитка {order.side} исполнена по {order.price:.10g}" + elif new_tick: + self.place(trader, trade.ts) # not filled by the next tick: cancel and re-place from the new price + self.last_price = trade.price + + +class SumsPolicy: + """Direction from the imbalance of significant resting orders (small and outsized levels dropped). + + Entry: a passive limit at the best bid (LONG) / best ask (SHORT) while |imbalance| >= threshold; it is + cancelled when the imbalance weakens or flips. Exit: take-profit limit at min_target_pct, at market when + the imbalance flips beyond the threshold, or on the time stop.""" + + name = "sums" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.order: Order | None = None + self.last: dict | None = None + self.status = "Жду стакан…" + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, + tick: float) -> None: + s = self.s + info = sh.significant_imbalance(book, s.sums_depth_pct, s.sums_low_pct, s.sums_high_pct) + if info is None: + return + self.last = info + imb = info["imbalance"] + signal = 1 if imb >= s.sums_threshold else -1 if imb <= -s.sums_threshold else 0 + if s.sums_invert: + signal = -signal + self.status = (f"значимые заявки {info['low']:,.0f}–{info['high']:,.0f}$ ({info['used']} из {info['levels']} " + f"уровней ±{s.sums_depth_pct:g}%): покупатели {info['bid_sum']:,.0f}$ / продавцы " + f"{info['ask_sum']:,.0f}$ · перевес {imb:+.2f} → " + + ({1: "LONG", -1: "SHORT", 0: f"нет (нужно ±{s.sums_threshold:g})"}[signal]) + + (" (против перевеса)" if s.sums_invert and signal else "")) + best_bid, best_ask = book.best() + led = trader.ledger + pos = led.position + if pos is not None: + direction = 1 if pos.side == "LONG" else -1 + exit_price = best_bid if direction > 0 else best_ask + if signal == -direction: + trader.close(exit_price, now, "перевес развернулся", TAKER) + elif now - pos.opened >= s.max_hold_minutes * 60: + trader.close(exit_price, now, "время", TAKER) + return + if self.order is not None: + direction = 1 if self.order.side == "LONG" else -1 + touch = best_bid if direction > 0 else best_ask + if signal != direction: + self.order = None + trader.message = "Лимитка снята: перевес ослаб или развернулся" + elif touch != self.order.price: + self.order = Order(ticker, self.order.side, touch, self._target(touch, direction, tick), 0.0, now, + "суммы", {}) # follow the best price + return + if not s.enabled or signal == 0 or led.balance < s.stake or now - trader.last_close < s.cooldown_seconds: + return + price = best_bid if signal > 0 else best_ask + self.order = Order(ticker, "LONG" if signal > 0 else "SHORT", price, self._target(price, signal, tick), 0.0, + now, "суммы", {}) + trader.message = f"Лимитка {self.order.side} {price:.10g} по перевесу {imb:+.2f}" + + def _target(self, price: float, direction: int, tick: float) -> float: + return _round(price * (1 + direction * self.s.min_target_pct / 100), tick, up=direction > 0) + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + led = trader.ledger + if self.order is not None: + order = self.order + if trade.price < order.price if order.side == "LONG" else trade.price > order.price: + self.order = None + led.open(order.ticker, order.side, order.price, trade.ts, MAKER, order.target, None, order.price, + "суммы") + trader.message = f"Лимитка {order.side} исполнена по {order.price:.10g}, цель {order.target:.10g}" + pos = led.position + if pos is not None and (trade.price > pos.target if pos.side == "LONG" else trade.price < pos.target): + trader.close(pos.target, trade.ts, "цель", MAKER) + + +class LeadPolicy: + """Leader exchange → paper trades on the follower. + + The leader (KuCoin futures) and the follower (Bybit perpetual) are watched at the same time. When the leader's + mid price moved over the last `lead_window_ms` by at least `lead_threshold_pct` MORE than the follower's mid, + the follower is expected to catch up: a market order is opened on the follower in the leader's direction. + Exits: take-profit `min_target_pct` (limit, filled when the follower trades through it), stop-loss + `stop_loss_pct` (market, on the follower's best price), time `max_hold_seconds` (market).""" + + name = "lead" + + def __init__(self, settings: PaperSettings) -> None: + self.s = settings + self.leader: deque[tuple[float, float]] = deque() # (local time, mid) + self.follower: deque[tuple[float, float]] = deque() + self.leader_quote: tuple[float, float] | None = None + self.book: sh.OrderBook | None = None + self.tick = 0.0 + self.ticker = settings.follow_ticker + self.signal = 0.0 # leader move − follower move over the window, % + self.moves = (0.0, 0.0) # (leader, follower) moves over the window, % + self.skip_pause = False # set after a cut-loss close: the next signal does not wait for the pause + self.last_entry = 0.0 + self.last_entry_price: dict[str, float] = {} # side -> price of the last entry (one per price step) + # 0.5 s price grid of both exchanges for the live leader check (and the basis mode) + self.grid: deque[tuple[float, float, float]] = deque(maxlen=2400) # (time, leader mid, follower mid) + self.next_grid = 0.0 + self.next_check = 0.0 + self.leadership: dict = {"lead": 0.0, "follow": 0.0, "edge": None, "pct": None, "minutes": 0.0, + "since": None, "at": None} + self.suitable_since: float | None = None + self.samples: deque[tuple[float, int, float, float]] = deque() # (time, direction, lag %, follower mid) + self.ratios: deque[float] = deque(maxlen=200) # follower's later move / lag at the signal + self.last_sample = 0.0 + self.forecast = 0.0 # forecast follower move for the current signal, % + self.conf = 0.0 # confidence of the current signal, 0-1 + self.status = f"Жду данные {self.L} и {self.F}…" + + @property + def L(self) -> str: + """Name of the leader for the texts.""" + return {"futures": "KuCoin", "spot": "KuCoin спот", "raydium": "DEX"}.get(self.s.lead_market, "KuCoin") + + @property + def F(self) -> str: + """Name of the follower (where the paper trades are made).""" + return {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC"}.get(self.s.follow_exchange, "Bybit") + + @property + def taker(self) -> float: + """Market-order fee of the follower exchange, %.""" + return FOLLOW_FEES.get(self.s.follow_exchange, (TAKER, MAKER))[0] + + @property + def maker(self) -> float: + """Limit-order fee of the follower exchange, %.""" + return FOLLOW_FEES.get(self.s.follow_exchange, (TAKER, MAKER))[1] + + # --- data ------------------------------------------------------------------------------ + def _trim(self, series: deque, now: float) -> None: + keep = max(self.s.lead_window_ms / 1000 * 3, 5.0) + while len(series) > 2 and series[1][0] < now - keep: + series.popleft() + + @staticmethod + def _move(series: deque, now: float, window: float) -> float | None: + """% change of the mid over the last `window` seconds (from the last value at or before now − window).""" + if not series: + return None + start = None + for t, mid in series: + if t <= now - window: + start = mid + else: + break + if start is None: + return None + return (series[-1][1] / start - 1) * 100 + + @staticmethod + def _efficiency(series: deque, now: float, window: float) -> float: + """Net move / path length of the mid over the window: 1 = a clean one-way move, ~0 = back-and-forth.""" + points = [mid for t, mid in series if t >= now - window] + before = [mid for t, mid in series if t < now - window] + if before: + points.insert(0, before[-1]) + if len(points) < 2: + return 0.0 + path = sum(abs(b - a) for a, b in zip(points, points[1:])) + return abs(points[-1] - points[0]) / path if path > 0 else 0.0 + + def confidence(self, move: float, threshold: float, window: float, follow_move: float | None) -> float: + """0-1: average of the KuCoin move's strength (1 at twice the threshold), how one-way it was, and (when + `follow_move` is given) how much Bybit already confirms the direction (1 when it moved as much).""" + parts = [min(1.0, abs(move) / (2 * threshold)) if threshold > 0 else 1.0, + self._efficiency(self.leader, self.leader[-1][0], window)] + if follow_move is not None and move: + parts.append(max(0.0, min(1.0, follow_move / move))) + return sum(parts) / len(parts) + + # --- live leader check ------------------------------------------------------------------ + GRID_STEP = 0.5 + LAGS = 10 # ± 5 s on the 0.5 s grid + + def _sample(self, now: float) -> None: + if now < self.next_grid or not self.leader or not self.follower: + return + self.next_grid = now + self.GRID_STEP + self.grid.append((now, self.leader[-1][1], self.follower[-1][1])) + self._on_grid(now) + if now >= self.next_check and len(self.grid) >= 240: # at least 2 minutes of prices + self.next_check = now + 10 + self.leadership = self.measure_leadership() + # since when the leader has been really leading (suitable for trades), for the indicator + if self.leadership["edge"] >= self.s.leader_min_edge: + self.leadership["since"] = self.suitable_since = self.suitable_since or now + else: + self.suitable_since = None + self.leadership["since"] = None + + def _on_grid(self, now: float) -> None: + """Hook for policies that work on the 0.5 s grid.""" + + def measure_leadership(self) -> dict: + """Sum of positive correlations of grid returns with the follower AFTER the leader (lead) and BEFORE + it (follow), lags up to 5 s; edge = lead − follow (> 0: the leader really moves first).""" + pts = list(self.grid) + rl = [math.log(b[1] / a[1]) for a, b in zip(pts, pts[1:])] + rf = [math.log(b[2] / a[2]) for a, b in zip(pts, pts[1:])] + + def corr(a: list, b: list) -> float: + n = len(a) + if n < 30: + return 0.0 + ma, mb = sum(a) / n, sum(b) / n + va = sum((x - ma) ** 2 for x in a) + vb = sum((y - mb) ** 2 for y in b) + if va <= 0 or vb <= 0: + return 0.0 + return sum((x - ma) * (y - mb) for x, y in zip(a, b)) / math.sqrt(va * vb) + + n = len(rl) + lead = sum(max(0.0, corr(rl[:n - k], rf[k:])) for k in range(1, self.LAGS + 1)) + follow = sum(max(0.0, corr(rl[k:], rf[:n - k])) for k in range(1, self.LAGS + 1)) + # the same as a percentage: +100 = only the leader moves first, −100 = only the follower does + pct = (lead - follow) / (lead + follow) * 100 if lead + follow > 0 else 0.0 + return {"lead": lead, "follow": follow, "edge": lead - follow, "pct": pct, + "minutes": (pts[-1][0] - pts[0][0]) / 60, "at": pts[-1][0]} + + def leader_block(self) -> str: + """Why the live leader check blocks entries now ('' = it does not).""" + if not self.s.require_leader: + return "" + edge = self.leadership.get("edge") + if edge is None: + return f"проверяю, кто ведёт: копится {len(self.grid) * self.GRID_STEP / 60:.1f} из 2 мин цен" + if edge < self.s.leader_min_edge: + who = self.F if edge < 0 else "никто явно" + return (f"сейчас ведёт {who}, а не {self.L} ({self.L}→{self.F} {self.leadership['lead']:.2f} / " + f"{self.F}→{self.L} {self.leadership['follow']:.2f})") + return "" + + def on_leader(self, trader: "PaperTrader", now: float, bid: float, ask: float) -> None: + if bid <= 0 or ask <= 0 or bid > ask: # bid == ask: a DEX pool price (no book) + return + self.leader_quote = (bid, ask) + self.leader.append((now, (bid + ask) / 2)) + self._trim(self.leader, now) + self._sample(now) + self._evaluate(trader, now) + + def on_book(self, trader: "PaperTrader", now: float, book: sh.OrderBook, tick: float) -> None: + self.book = book + if tick > 0: + self.tick = tick + best_bid, best_ask = book.best() + if best_bid is None or best_ask is None: + return + self.follower.append((now, (best_bid + best_ask) / 2)) + self._trim(self.follower, now) + self._sample(now) + mid = (best_bid + best_ask) / 2 + for pos in list(trader.ledger.positions): + long = pos.side == "LONG" + exit_price = best_bid if long else best_ask + against = (pos.entry_mid - mid if long else mid - pos.entry_mid) / self.tick if self.tick > 0 else 0.0 + if pos.stop is not None and (exit_price <= pos.stop if long else exit_price >= pos.stop): + trader.close(exit_price, now, "стоп", self.taker, pos=pos) + elif now - pos.opened >= self.s.max_hold_seconds: + trader.close(exit_price, now, "время", self.taker, pos=pos) + elif self.s.cut_loss and against >= self.s.cut_loss_ticks - 1e-9: + trader.close(exit_price, now, "минус — закрыта сразу", self.taker, pos=pos) + self.skip_pause = True # the next signal is taken at once + self._extra_exits(trader, now, best_bid, best_ask) + self._resolve_samples(now, mid) + self._evaluate(trader, now) + + def _extra_exits(self, trader: "PaperTrader", now: float, best_bid: float, best_ask: float) -> None: + """Hook for policy-specific exits (the basis mode closes when the gap is gone).""" + + # --- forecast for the automatic take-profit ---------------------------------------------- + def _resolve_samples(self, now: float, mid: float) -> None: + """How much of the lag did the follower actually catch up `auto_tp_horizon_seconds` after each signal.""" + while self.samples and self.samples[0][0] <= now - self.s.auto_tp_horizon_seconds: + _, d, lag, mid0 = self.samples.popleft() + if lag > 0 and mid0 > 0: + self.ratios.append(d * (mid / mid0 - 1) * 100 / lag) + + def share(self) -> tuple[float, str]: + """(share of the lag expected to be caught up, where it comes from).""" + if self.s.auto_tp_learn and len(self.ratios) >= 10: + return max(0.0, min(3.0, statistics.median(self.ratios))), f"выучено по {len(self.ratios)} сигналам" + note = f"копится история {len(self.ratios)}/10" if self.s.auto_tp_learn else "задано вручную" + return self.s.auto_tp_share_pct / 100, note + + def _record_sample(self, now: float, direction: int) -> None: + if direction == 0 or now - self.last_sample < 1.0 or not self.follower: + return + lead_move, follow_move = self.moves + lag = direction * (lead_move - follow_move) + if lag > 0: + self.samples.append((now, direction, lag, self.follower[-1][1])) + self.last_sample = now + + def on_trade(self, trader: "PaperTrader", trade: sh.Trade) -> None: + for pos in list(trader.ledger.positions): + long = pos.side == "LONG" + if (trade.price > pos.target) if long else (trade.price < pos.target): + trader.close(pos.target, trade.ts, "цель", self.maker, pos=pos) + + def on_tick(self, trader: "PaperTrader", now: float, ticker: str, hint, book: sh.OrderBook, tick: float) -> None: + self.ticker = ticker or self.s.follow_ticker + self.book = book + if tick > 0: + self.tick = tick + + # --- decision -------------------------------------------------------------------------- + def _signal(self, now: float) -> tuple[int, str, str, str] | None: + """(direction +1/−1/0, status text, why not entering, why entered) or None while data is gathering.""" + window = self.s.lead_window_ms / 1000 + lead_move = self._move(self.leader, now, window) + follow_move = self._move(self.follower, now, window) + if lead_move is None or follow_move is None: + return None + self.moves = (lead_move, follow_move) + self.signal = lead_move - follow_move + # Bybit lagging is the signal here, so its own move does not add confidence + self.conf = self.confidence(lead_move, self.s.lead_threshold_pct, window, None) + base = (f"{self.L} {lead_move:+.3f}% · {self.F} {follow_move:+.3f}% за {self.s.lead_window_ms:g} мс · " + f"отставание {self.F} {self.signal:+.3f}% (порог ±{self.s.lead_threshold_pct:g}%) · " + f"уверенность {self.conf:.2f}") + # only KuCoin's own move is a signal; Bybit moving first is not traded + if (abs(lead_move) < self.s.lead_threshold_pct or abs(self.signal) < self.s.lead_threshold_pct + or lead_move * self.signal <= 0): + return 0, base, f"ждём, когда {self.L} уйдёт вперёд", "" + return ((1 if self.signal > 0 else -1), base, "", + f"{self.L} {lead_move:+.3f}% / {self.F} {follow_move:+.3f}% · уверенность {self.conf:.2f}") + + def _evaluate(self, trader: "PaperTrader", now: float) -> None: + sig = self._signal(now) + if sig is None: + self.status = "Копятся данные обеих бирж…" + return + direction, base, wait, why = sig + self._record_sample(now, direction) + if self.s.auto_tp and direction: + share, note = self.share() + lead_move, follow_move = self.moves + self.forecast = max(0.0, share * direction * (lead_move - follow_move)) + base += f" · прогноз {self.F} {direction * self.forecast:+.3f}% (доля {share * 100:.0f}%, {note})" + stale = max(now - self.leader[-1][0], now - self.follower[-1][0]) * 1000 + open_n = len(trader.ledger.positions) + if open_n: + base += f" · открыто позиций {open_n} из {max(1, int(self.s.max_positions))}" + reason = "" + if open_n >= max(1, int(self.s.max_positions)): + reason = "открыто максимум позиций" + elif open_n and now - self.last_entry < self.s.entry_gap_seconds: + reason = f"следующая позиция не раньше чем через {self.s.entry_gap_seconds - (now - self.last_entry):.1f} с" + elif not self.s.enabled: + reason = "тестовые сделки выключены" + elif trader.gate is not None and trader.gate(): + reason = trader.gate() # real trading: the previous real trade is not closed yet + elif stale > self.s.max_data_age_ms: + reason = f"данные устарели ({stale:.0f} мс)" + elif (now - trader.last_close) * 1000 < self.s.cooldown_ms and not self.skip_pause: + reason = f"пауза после сделки ещё {self.s.cooldown_ms - (now - trader.last_close) * 1000:.0f} мс" + elif trader.ledger.balance < self.s.stake * (open_n + 1): + reason = "баланса не хватает ещё на одну ставку" + elif direction == 0: + reason = wait + elif self.leader_block(): + reason = self.leader_block() + elif self.conf < self.s.min_confidence: + reason = f"уверенность {self.conf:.2f} ниже порога {self.s.min_confidence:g}" + self.status = base + (f" · {reason}" if reason else "") + if reason or self.book is None: + return + best_bid, best_ask = self.book.best() + if best_bid is None or best_ask is None: + return + long = direction > 0 + price = best_ask if long else best_bid # market order on the follower + side = "LONG" if long else "SHORT" + half = (self.tick or price * 1e-9) / 2 + # forget the last entry price once Bybit's price for that side has moved to another step + for s_, p_ in list(self.last_entry_price.items()): + current = best_ask if s_ == "LONG" else best_bid + if abs(current - p_) >= half: + del self.last_entry_price[s_] + if self.s.one_per_tick: + if any(p.side == side and abs(p.entry - price) < half for p in trader.ledger.positions): + self.status = base + f" · на цене {price:.10g} уже есть позиция {side} (одна на шаг цены)" + return + if side in self.last_entry_price: + # one entry per price step even if the previous one is already closed: the next one only after + # Bybit's price moves to another step + self.status = base + f" · на цене {price:.10g} уже был вход {side} — жду другой шаг цены" + return + spread_pct = (best_ask - best_bid) / ((best_ask + best_bid) / 2) * 100 + if spread_pct >= self.s.stop_loss_pct: + self.status = (base + f" · спред {self.F} {spread_pct:.3f}% не меньше стоп-лосса {self.s.stop_loss_pct:g}% — " + "сделка закрылась бы по стопу сразу") + return + sign = 1 if long else -1 + if self.s.auto_tp: + # take-profit where the forecast puts Bybit's mid; skip when that does not pay spread and fees + target = (best_bid + best_ask) / 2 * (1 + sign * self.forecast / 100) + expected = sign * (target / price - 1) * 100 - (self.taker + self.maker) + if expected <= 0: + self.status = (base + f" · прогноз {sign * self.forecast:+.3f}% не покрывает спред и комиссию " + f"({self.taker + self.maker:.3f}%)") + return + why += f" · прогноз {sign * self.forecast:+.3f}%" + else: + target = price * (1 + sign * self.s.min_target_pct / 100) + stop = price * (1 - sign * self.s.stop_loss_pct / 100) + if self.tick > 0: + target = _round(target, self.tick, up=long) + stop = _round(stop, self.tick, up=not long) + self.skip_pause = False + self.last_entry = now + self.last_entry_price[side] = price + trader.ledger.open(self.ticker, side, price, now, self.taker, target, stop, (best_bid + best_ask) / 2, why) + trader.message = f"Открыта {side} {self.ticker} по {price:.10g} · {why} · цель {target:.10g}" + + +class VectorPolicy(LeadPolicy): + """Direction (vector) of KuCoin over the last `vector_window_seconds` → the same direction on Bybit. + + Rising on KuCoin → LONG on Bybit, falling → SHORT, once the KuCoin move over the window is at least + `vector_min_move_pct`. Unlike the lead mode, Bybit having moved too does not matter. Same exits: take-profit + `min_target_pct` (e.g. +0.2%), stop-loss, holding time.""" + + name = "vector" + + def _trim(self, series: deque, now: float) -> None: + keep = max(self.s.vector_window_seconds * 2, 5.0) + while len(series) > 2 and series[1][0] < now - keep: + series.popleft() + + def _signal(self, now: float) -> tuple[int, str, str, str] | None: + move = self._move(self.leader, now, self.s.vector_window_seconds) + follow_move = self._move(self.follower, now, self.s.vector_window_seconds) + if move is None or follow_move is None: + return None + self.moves = (move, follow_move) + self.signal = move + self.conf = self.confidence(move, self.s.vector_min_move_pct, self.s.vector_window_seconds, follow_move) + base = (f"Вектор {self.L} за {self.s.vector_window_seconds:g} с: {move:+.3f}% ({self.F} {follow_move:+.3f}%) · " + f"порог ±{self.s.vector_min_move_pct:g}% · уверенность {self.conf:.2f}") + if abs(move) < self.s.vector_min_move_pct: + return 0, base, "направления нет", "" + word = "растёт" if move > 0 else "падает" + return ((1 if move > 0 else -1), base, "", + f"{self.L} {word} {move:+.3f}% за {self.s.vector_window_seconds:g} с · уверенность {self.conf:.2f}") + + +class BasisPolicy(LeadPolicy): + """The price gap between the leader and the follower (ln leader − ln follower, %) against its usual level. + + The usual gap and its spread are exponential averages over `basis_window_seconds` on the 0.5 s grid. When the + gap is `basis_entry_z` standard deviations (and at least `basis_min_gap_pct`) away from usual — typically a DEX + jump the futures have not followed yet — the follower is bought (gap above usual) or sold (below) for the gap to + close. The position is closed when the gap is back within `basis_exit_z` deviations («разрыв закрылся»), or by + take-profit / stop-loss / holding time. With the automatic take-profit the forecast is share × extra gap.""" + + name = "basis" + + def __init__(self, settings: PaperSettings) -> None: + super().__init__(settings) + self.b_mean: float | None = None + self.b_var = 0.0 + self.b_count = 0 + self.dev = 0.0 + self.z = 0.0 + + def _basis(self) -> float | None: + if not self.leader or not self.follower: + return None + return (math.log(self.leader[-1][1]) - math.log(self.follower[-1][1])) * 100 + + def _on_grid(self, now: float) -> None: + b = self._basis() + if b is None: + return + alpha = min(1.0, self.GRID_STEP / max(self.s.basis_window_seconds, self.GRID_STEP)) + if self.b_mean is None: + self.b_mean, self.b_var = b, 0.0 + else: + diff = b - self.b_mean + self.b_mean += alpha * diff + self.b_var = (1 - alpha) * (self.b_var + alpha * diff * diff) + self.b_count += 1 + + def _sd(self) -> float: + return max(math.sqrt(self.b_var), 0.01) # at least 0.01 %: a flat gap is not "many sigmas" off + + def _signal(self, now: float) -> tuple[int, str, str, str] | None: + b = self._basis() + warm = int(self.s.basis_window_seconds / self.GRID_STEP / 2) + if b is None or self.b_mean is None or self.b_count < warm: + return None + self.dev = b - self.b_mean + self.z = self.dev / self._sd() + self.moves = (self.dev, 0.0) # the extra gap is what the follower should catch up + self.signal = self.dev + self.conf = min(1.0, abs(self.z) / (2 * self.s.basis_entry_z)) + base = (f"разрыв {self.L}−{self.F} {b:+.3f}% · обычный {self.b_mean:+.3f}% ±{self._sd():.3f}% · " + f"отклонение {self.dev:+.3f}% ({self.z:+.1f}σ, вход от {self.s.basis_entry_z:g}σ и " + f"{self.s.basis_min_gap_pct:g}%)") + if abs(self.z) < self.s.basis_entry_z or abs(self.dev) < self.s.basis_min_gap_pct: + return 0, base, "разрыв в обычных пределах", "" + side = "выше" if self.dev > 0 else "ниже" + return ((1 if self.dev > 0 else -1), base, "", + f"{self.L} {side} {self.F} на {abs(self.dev):.3f}% сверх обычного ({self.z:+.1f}σ)") + + def _extra_exits(self, trader: "PaperTrader", now: float, best_bid: float, best_ask: float) -> None: + b = self._basis() + if b is None or self.b_mean is None: + return + dev = b - self.b_mean + for pos in list(trader.ledger.positions): + sign = 1 if pos.side == "LONG" else -1 + if sign * dev <= self.s.basis_exit_z * self._sd(): + trader.close(best_bid if sign > 0 else best_ask, now, "разрыв закрылся", self.taker, pos=pos) + + +class PaperTrader: + """Ledger + the selected policy; used by the window and by the replay.""" + + def __init__(self, settings: PaperSettings, hint_settings: sh.HintSettings, + state_path: Path | None = STATE_FILE, trades_path: Path | None = TRADES_FILE) -> None: + self.settings = settings + self.hint_settings = hint_settings + self.ledger = Ledger(settings, state_path, trades_path) + self.message = "" + self.last_close = 0.0 + self.gate = None # callable → "" or why no new position may open (real trading: previous not closed) + self.data_latency_ms: float | None = None # measured delay of market data, set by the window + self.algo_config = None # AlgoHunterConfig, loaded lazily for the algo_hunter mode + if settings.mode == "algo_hunter": + import algo_hunter + self.algo_config = algo_hunter.AlgoHunterConfig.load() if state_path else algo_hunter.AlgoHunterConfig() + self.policy = self._make_policy() + + def _make_policy(self): + if self.settings.mode == "adaptive": + return AdaptivePolicy(self.settings, self.hint_settings) + if self.settings.mode == "pulse": + return PulsePolicy(self.settings) + if self.settings.mode == "sums": + return SumsPolicy(self.settings) + if self.settings.mode == "lead": + return LeadPolicy(self.settings) + if self.settings.mode == "vector": + return VectorPolicy(self.settings) + if self.settings.mode == "basis": + return BasisPolicy(self.settings) + if self.settings.mode == "algo_hunter": + import algo_hunter # isolated module, loaded only when the mode is selected + return algo_hunter.AlgoHunterPolicy(self.settings, self.algo_config, + algo_hunter.TRADES_FILE if self.ledger.trades_path else None) + return SimplePolicy(self.settings) + + def set_mode(self, mode: str) -> None: + if mode != self.settings.mode: + self.settings.mode = mode + if mode == "algo_hunter" and self.algo_config is None: + import algo_hunter + self.algo_config = algo_hunter.AlgoHunterConfig.load() + self.policy = self._make_policy() + self.ledger.save() + + def on_book(self, now: float, book: sh.OrderBook, tick: float) -> None: + """Every order-book update (only policies that watch the book itself use it).""" + handler = getattr(self.policy, "on_book", None) + if handler is not None: + handler(self, now, book, tick) + + def on_leader(self, now: float, bid: float, ask: float) -> None: + """Best quotes of the leader exchange (lead mode only).""" + handler = getattr(self.policy, "on_leader", None) + if handler is not None: + handler(self, now, bid, ask) + + @property + def position(self) -> Position | None: + return self.ledger.position + + @property + def trades(self) -> list[PaperTrade]: + return self.ledger.trades + + @property + def balance(self) -> float: + return self.ledger.balance + + def pending_order(self) -> Order | None: + return getattr(self.policy, "order", None) + + def on_tick(self, now: float, ticker: str, hint: sh.Hint, book: sh.OrderBook, tick: float) -> None: + self.policy.on_tick(self, now, ticker, hint, book, tick) + + def on_trade(self, trade: sh.Trade) -> None: + self.policy.on_trade(self, trade) + + 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) + 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) + + def close_now(self, book: sh.OrderBook, now: float, reason: str) -> None: + if hasattr(self.policy, "order"): + self.policy.order = None + best_bid, best_ask = book.best() + for pos in list(self.ledger.positions): + price = (best_bid if pos.side == "LONG" else best_ask) or pos.entry + self.close(price, now, reason, TAKER, pos=pos) + + def reset(self) -> None: + self.ledger.reset() + self.policy = self._make_policy() + self.hint_settings.weights = dict(sh.DEFAULT_WEIGHTS) + + def unrealized(self, book: sh.OrderBook) -> float: + best_bid, best_ask = book.best() + total = 0.0 + for pos in self.ledger.positions: + price = best_bid if pos.side == "LONG" else best_ask + if price is not None: + total += (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty + return total + + def summary(self) -> str: + trades = self.ledger.trades + n = len(trades) + wins = sum(t.net_usd > 0 for t in trades) + net = sum(t.net_usd for t in trades) + fees = sum(t.fee_usd for t in trades) + return (f"Баланс {self.ledger.balance:.2f}$ (старт {self.settings.budget:g}$) · сделок {n} · в плюс {wins}" + f"{f' ({wins / n * 100:.0f}%)' if n else ''} · чистая прибыль {net:+.4f}$ · комиссии {fees:.4f}$") + + +# -------------------------------------------------------------------------------------------- +# Recording and replay +# -------------------------------------------------------------------------------------------- + +class Recorder: + """Appends the raw MetaScalp stream to a gzip JSON-lines file: [receive_time, kind, data].""" + + def __init__(self, ticker: str, connection_id: int, tick: float, folder: Path = RECORD_DIR) -> None: + folder.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + self.path = folder / f"{ticker}_{connection_id}_{stamp}.jsonl.gz" + self.file = gzip.open(self.path, "at", encoding="utf-8") + self.lines = 0 + self.write("meta", {"ticker": ticker, "connectionId": connection_id, "tick": tick}) + + def write(self, kind: str, data, now: float | None = None) -> None: + if self.file is None: + return + self.file.write(json.dumps([round(now if now is not None else time.time(), 3), kind, data], + separators=(",", ":")) + "\n") + self.lines += 1 + if self.lines % 500 == 0: + self.file.flush() + + def close(self) -> None: + if self.file is not None: + self.file.close() + self.file = None + + +def read_recording(path: Path): + """Rows of a recording; a file still being written (or cut off) is read up to its last flushed line.""" + try: + with gzip.open(path, "rt", encoding="utf-8") as file: + for line in file: + try: + yield json.loads(line) + except json.JSONDecodeError: + return + except (EOFError, OSError): + return + + +def replay(paths: list[Path], settings: PaperSettings, step: float = 0.5, algo_config=None) -> PaperTrader: + """Run a policy over recordings exactly as the window would: book/tape updates, a decision every step.""" + hint_settings = sh.HintSettings() + trader = PaperTrader(settings, hint_settings, state_path=None, trades_path=None) + if algo_config is not None: + trader.algo_config = algo_config + trader.policy = trader._make_policy() + for path in paths: + book, tape = sh.OrderBook(), sh.Tape() + engine = sh.HintEngine(hint_settings) + meta = {"ticker": "?", "tick": 0.0} + next_tick = None + last_t = None + for t, kind, data in read_recording(path): + if kind == "meta": + meta = data + continue + while next_tick is not None and next_tick <= t: + if book.asks and book.bids: + hint = engine(book, tape, meta["tick"], next_tick) + trader.on_tick(next_tick, meta["ticker"], hint, book, meta["tick"]) + next_tick += step + if kind == "S": + book.apply_snapshot(data) + trader.on_book(t, book, meta["tick"]) + elif kind == "U": + book.apply_updates(data) + trader.on_book(t, book, meta["tick"]) + elif kind == "L": + trader.on_leader(t, float(data[0]), float(data[1])) + elif kind == "T": + for raw in data: + try: + trade = sh.Trade(t, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) + except (KeyError, TypeError, ValueError): + continue + tape.add(trade) + trader.on_trade(trade) + if next_tick is None: + next_tick = t + step + last_t = t + if trader.position is not None and last_t is not None: + trader.close_now(book, last_t, "конец записи") + if hasattr(trader.policy, "order"): + trader.policy.order = None + return trader + + +def compare(paths: list[Path]) -> None: + variants = [(f"простая, откат {n} шаг.", PaperSettings(mode="simple", adverse_ticks=n)) for n in (1, 3, 5, 10)] + variants += [("адаптивная", PaperSettings(mode="adaptive")), + ("адаптивная без самонастройки", PaperSettings(mode="adaptive", learning=False))] + variants += [(f"импульс + стакан, лимитка {p:g}%", PaperSettings(mode="pulse", pulse_offset_pct=p)) + for p in (0.05, 0.1, 0.15, 0.25)] + variants += [(f"суммы ±{d:g}%, перевес {th:g}, цель {tp:g}%", + PaperSettings(mode="sums", sums_depth_pct=d, sums_threshold=th, min_target_pct=tp)) + for d, th, tp in ((0.3, 0.2, 0.2), (0.3, 0.4, 0.2), (0.6, 0.2, 0.2), (0.6, 0.4, 0.3))] + minutes = 0.0 + for path in paths: + times = [row[0] for row in read_recording(path) if row[1] != "meta"] + if times: + minutes += (times[-1] - times[0]) / 60 + print(f"Записей: {len(paths)}, всего {minutes:.0f} мин потока\n") + print(f"{'вариант':34s} {'сделок':>6s} {'в плюс':>7s} {'итог $':>9s} {'на сделку':>10s} {'комиссии':>9s} причины") + for name, settings in variants: + trader = replay(paths, settings) + trades = trader.trades + n = len(trades) + net = sum(t.net_usd for t in trades) + wins = sum(t.net_usd > 0 for t in trades) + reasons: dict[str, int] = {} + for t in trades: + reasons[t.reason] = reasons.get(t.reason, 0) + 1 + print(f"{name:34s} {n:6d} {(wins / n * 100 if n else 0):6.0f}% {net:+9.4f} " + f"{(net / n if n else 0):+10.5f} {sum(t.fee_usd for t in trades):9.4f} {reasons}") + + +if __name__ == "__main__": + if len(sys.argv) >= 2 and sys.argv[1] == "compare": + files = [Path(p) for p in sys.argv[2:]] or sorted(RECORD_DIR.glob("*.jsonl.gz")) + if not files: + raise SystemExit(f"Нет записей в {RECORD_DIR}") + compare(files) + else: + print("usage: py -3 scalp_paper.py compare [files...]") diff --git a/server_control.ps1 b/server_control.ps1 new file mode 100644 index 0000000..86dc0d8 --- /dev/null +++ b/server_control.ps1 @@ -0,0 +1,86 @@ +# Запуск и остановка сервера симулятора (вызывается из ЗАПУСТИТЬ_СЕРВЕР.bat и ОСТАНОВИТЬ_СЕРВЕР.bat). +# start — сервер в фоне без окон (страница + движок с автоперезапуском), затем открывается страница +# stop — останавливает страницу, движок и его цикл перезапуска +# Если в Планировщике есть задача «RealtimePaperSimulator watchdog» (поднимает сервер раз в 5 минут), +# stop её выключает, а start включает обратно — иначе она запустила бы сервер снова. +param([Parameter(Position = 0)] [string] $Action = "start") +$ErrorActionPreference = "Continue" +$Dir = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $Dir +$Url = "http://127.0.0.1:8765" +$Task = "RealtimePaperSimulator watchdog" +$Parts = 'web_sim_service\.bat|web_sim\.py|web_proxy\.py' + +function Server-Processes { + Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -match $Parts -and + $_.ProcessId -ne $PID -and $_.Name -notmatch 'powershell' } +} + +function Answers { + try { Invoke-RestMethod "$Url/api/state" -TimeoutSec 3 | Out-Null; return $true } catch { return $false } +} + +function Set-Watchdog([bool] $On) { + $t = Get-ScheduledTask -TaskName $Task -ErrorAction SilentlyContinue + if (-not $t) { return } + if ($On) { Enable-ScheduledTask -TaskName $Task | Out-Null; Write-Host "Сторож в Планировщике включён (поднимает сервер, если тот упадёт)." } + else { Disable-ScheduledTask -TaskName $Task | Out-Null; Write-Host "Сторож в Планировщике выключен, чтобы не запустил сервер снова." } +} + +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 }) + if ($closing.Count) { + Write-Host ("Сейчас закрывается реальная сделка: " + (($closing | ForEach-Object { $_.base }) -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 ", ") + + " — пока сервер остановлен, за ними никто не следит; после запуска программа продолжит их вести.") -ForegroundColor Yellow + } + } catch {} + Set-Watchdog $false + # сначала цикл перезапуска (иначе он поднимет движок), потом движок и страница + foreach ($round in 1..3) { + $procs = @(Server-Processes) + if (-not $procs.Count) { break } + $procs | Sort-Object { if ($_.CommandLine -match 'web_sim_service') { 0 } else { 1 } } | + ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } + Start-Sleep -Seconds 2 + } + if (Server-Processes) { Write-Host "Не все части сервера остановились — запустите файл ещё раз." -ForegroundColor Red; exit 1 } + Write-Host "Сервер остановлен." -ForegroundColor Green + exit 0 +} + +# --- start --------------------------------------------------------------------------------------------------- +if ((Server-Processes) -and (Answers)) { + Write-Host "Сервер уже работает: $Url" -ForegroundColor Green + Set-Watchdog $true + 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 и библиотеки ещё не установлены — устанавливаю..." + & 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 +Set-Watchdog $true +foreach ($i in 1..45) { + if (Answers) { + Write-Host "Сервер работает: $Url" -ForegroundColor Green + Start-Process $Url + exit 0 + } + Start-Sleep -Seconds 1 +} +Write-Host "Сервер не ответил за 45 секунд. Журнал движка: web_sim_data\backend.log" -ForegroundColor Red +exit 1 diff --git a/setup.ps1 b/setup.ps1 new file mode 100644 index 0000000..877198c --- /dev/null +++ b/setup.ps1 @@ -0,0 +1,73 @@ +# Установка и запуск симулятора (вызывается из УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat). +# 1) Python 3.10+: если нет — ставится через winget, только для текущего пользователя +# 2) библиотеки программы — в папку .venv рядом, в систему ничего не ставится +# 3) запуск: страница http://127.0.0.1:8765 открывается в браузере +# Параметр /install-only — только установить. +param([Parameter(ValueFromRemainingArguments = $true)] $Rest) +$ErrorActionPreference = "Stop" +$InstallOnly = $Rest -contains "/install-only" +$Dir = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $Dir +$Host.UI.RawUI.WindowTitle = "Симулятор" +$VenvPy = Join-Path $Dir ".venv\Scripts\python.exe" +$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() } + } catch {} + } + foreach ($d in "Python313", "Python312", "Python311", "Python310") { + $p = Join-Path $env:LOCALAPPDATA "Programs\Python\$d\python.exe" + 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() } + } catch {} + return $null +} + +function Fail($text) { + Write-Host "" + Write-Host $text -ForegroundColor Red + exit 1 +} + +if (-not (Test-Path $VenvPy)) { + $py = Find-Python + if (-not $py) { + Write-Host "Python не найден. Ставлю Python 3.12 через winget..." -ForegroundColor Yellow + if (-not (Get-Command winget -ErrorAction SilentlyContinue)) { + Fail ("Не найден winget. Установите Python 3.12 вручную: https://www.python.org/downloads/`n" + + "(при установке отметьте «Add python.exe to PATH») и запустите файл ещё раз.") + } + & winget install -e --id Python.Python.3.12 --scope user --accept-package-agreements --accept-source-agreements + $py = Find-Python + if (-not $py) { Fail "Python установлен, но ещё не виден. Закройте окно и запустите файл ещё раз." } + } + Write-Host "Python: $py" + Write-Host "Создаю окружение программы (.venv)..." + & $py -m venv (Join-Path $Dir ".venv") + if ($LASTEXITCODE -ne 0 -or -not (Test-Path $VenvPy)) { Fail "Не удалось создать .venv" } +} + +Write-Host "Проверяю библиотеки..." +& $VenvPy -m pip install --disable-pip-version-check -q -r (Join-Path $Dir "requirements.txt") +if ($LASTEXITCODE -ne 0) { + Fail "Не удалось установить библиотеки. Проверьте интернет (и VPN, если сайты у вас заблокированы) и запустите ещё раз." +} +& $VenvPy -c "import websocket, numpy" +if ($LASTEXITCODE -ne 0) { Fail "Библиотеки не загружаются — запустите файл ещё раз." } +Write-Host "Установка готова." -ForegroundColor Green +if ($InstallOnly) { exit 0 } + +Write-Host "" +Write-Host "Запускаю симулятор. Страница: http://127.0.0.1:8765" -ForegroundColor Green +Write-Host "Это окно — движок программы: не закрывайте его, пока пользуетесь симулятором." +Write-Host "" +Start-Process -FilePath $VenvPyw -ArgumentList "web_proxy.py" -WorkingDirectory $Dir +Start-Process "http://127.0.0.1:8765" +& $VenvPy web_sim.py --backend diff --git a/strategy.py b/strategy.py new file mode 100644 index 0000000..c0cef37 --- /dev/null +++ b/strategy.py @@ -0,0 +1,396 @@ +"""Shared strategy formulas used by simulation, live trading and the historical backtest. + +Keeping these rules in one place prevents the three modes from drifting apart. +""" + +from __future__ import annotations + +import math + +# Approximate maintenance-margin rate for Bybit USDT perpetuals at the lowest risk tier. +MAINTENANCE_MARGIN_RATE_PCT = 0.5 + + +def fee_cover_pct(fee_pct: float) -> float: + """Minimum gross price rise that offsets taker fees on entry and exit fills.""" + fee = max(0.0, fee_pct) / 100 + return ((1 + fee) / (1 - fee) - 1) * 100 if fee < 1 else math.inf + + +def effective_take_profit_pct(take_profit_pct: float, fee_pct: float) -> float: + """TP percentage raised to cover round-trip fees; 0 keeps TP disabled.""" + if take_profit_pct <= 0: + return 0.0 + return max(take_profit_pct, fee_cover_pct(fee_pct)) + + +def take_profit_price(avg_entry: float, take_profit_pct: float, fee_pct: float) -> float | None: + pct = effective_take_profit_pct(take_profit_pct, fee_pct) + return avg_entry * (1 + pct / 100) if pct > 0 else None + + +def stop_loss_price(avg_entry: float, stop_loss_pct: float) -> float | None: + return avg_entry * (1 - stop_loss_pct / 100) if stop_loss_pct > 0 else None + + +def entry_level(baseline_close: float, trigger_pct: float) -> float: + return baseline_close * (1 + trigger_pct / 100) + + +def add_level(last_add_price: float, add_step_pct: float) -> float | None: + return last_add_price * (1 - add_step_pct / 100) if add_step_pct > 0 else None + + +def can_add(add_count: int, max_adds: int, add_step_pct: float, averaging_frozen: bool = False) -> bool: + return add_step_pct > 0 and add_count < max_adds and not averaging_frozen + + +def liquidation_price(avg_entry: float, leverage: float, + mmr_pct: float = MAINTENANCE_MARGIN_RATE_PCT, side: str = "long") -> float | None: + """Approximate isolated-margin liquidation price; None when leverage <= 1 for a LONG. + + With leverage 1 a LONG cannot lose more than its margin before price reaches 0, + so liquidation is not modelled. For higher leverage the LONG price is + entry * (1 - 1/leverage + MMR) and the SHORT price is entry * (1 + 1/leverage - MMR). + A 1x SHORT is liquidated near a doubling of the price. + """ + if side == "short": + return avg_entry * (1 + 1 / max(leverage, 1.0) - mmr_pct / 100) + if leverage <= 1: + return None + return max(0.0, avg_entry * (1 - 1 / leverage + mmr_pct / 100)) + + +# --------------------------------------------------------------------------- +# Strategy modes. +# +# "classic" — the original rule: entry on a rise above the previous 1-minute close, +# averaging down, TP/stop from the average price (settings per currency). +# "breakout" — mode A: LONG on a close above the N-hour high with a volume spike, +# ATR stop, partial take-profit, breakeven and ATR trailing stop. +# "fade" — mode B: SHORT after a pump stalls (24h growth, high funding, close back +# under the turnover-weighted average price and below the recent high). +# Modes A and B share one exit engine and one parameter set for all currencies. +# --------------------------------------------------------------------------- + +STRATEGY_CLASSIC = "classic" +STRATEGY_BREAKOUT = "breakout" +STRATEGY_FADE = "fade" +STRATEGY_MODES = (STRATEGY_CLASSIC, STRATEGY_BREAKOUT, STRATEGY_FADE) +STRATEGY_TITLES = { + STRATEGY_CLASSIC: "Классика: пробой 1-мин свечи + усреднение", + STRATEGY_BREAKOUT: "A: пробой N-часового максимума (ATR)", + STRATEGY_FADE: "B: шорт затухающего пампа", +} +STRATEGY_DESCRIPTIONS = { + STRATEGY_CLASSIC: ( + "LONG при росте от закрытия прошлой минутной свечи, доливки при снижении, TP и стоп от средней " + "цены. Настройки задаются для каждой валюты отдельно; здесь — шаблон, который применяется ко всем." + ), + STRATEGY_BREAKOUT: ( + "LONG, когда закрытие свечи таймфрейма выше максимума за N часов и оборот свечи в K раз выше " + "среднего. Стоп = вход − ATR × множитель, без усреднения. Часть позиции фиксируется на заданном R " + "(R — расстояние до стопа), стоп переносится в безубыток, остаток ведётся трейлинг-стопом по ATR. " + "Фильтры: BTC выше EMA на часовом графике и funding не выше порога." + ), + STRATEGY_FADE: ( + "SHORT монеты после пампа: рост за 24 ч выше порога, funding не ниже порога, максимум за " + "последние часы уже позади, закрытие ниже него на заданный процент и ниже средней цены по " + "обороту (VWAP). Стоп — над максимумом + ATR × буфер; сделка пропускается, если стоп дальше " + "заданного процента. Выход: частичная фиксация на R, безубыток, трейлинг по ATR. " + "Funding при положительной ставке получают шорты." + ), +} + +# (key, label, minimum, maximum, integer?) — minimum 0 usually means "0 = выключено". +_COMMON_RISK_FIELDS = ( + ("stake_pct", "Ставка, % депозита", 0.01, 100.0, False), + ("leverage", "Плечо", 1.0, 100.0, False), + ("timeframe_min", "Таймфрейм сигнала, мин (5/15/30/60)", 5.0, 60.0, True), + ("atr_period", "Период ATR, свечей", 2.0, 200.0, True), +) +_COMMON_EXIT_FIELDS = ( + ("partial_r", "Частичная фиксация на R (0 = выкл.)", 0.0, 50.0, False), + ("partial_pct", "Доля частичной фиксации, %", 0.0, 100.0, False), + ("breakeven", "Безубыток после частичной (1/0)", 0.0, 1.0, True), + ("trail_atr", "Трейлинг-стоп, ATR (0 = выкл.)", 0.0, 50.0, False), + ("take_profit_r", "Финальный TP на R (0 = выкл.)", 0.0, 100.0, False), + ("max_hold_hours", "Макс. удержание, ч (0 = выкл.)", 0.0, 10000.0, False), +) +MODE_FIELDS: dict[str, tuple[tuple[str, str, float, float, bool], ...]] = { + STRATEGY_BREAKOUT: _COMMON_RISK_FIELDS + ( + ("breakout_hours", "Пробой максимума за, ч", 0.25, 168.0, False), + ("volume_mult", "Оборот свечи × среднего (0 = выкл.)", 0.0, 100.0, False), + ("stop_atr", "Стоп, ATR от входа", 0.1, 50.0, False), + ("btc_filter", "Фильтр BTC выше EMA 1ч (1/0)", 0.0, 1.0, True), + ("btc_ema", "Период EMA BTC, часов", 2.0, 900.0, True), + ("max_funding_pct", "Не входить при funding выше, % (0 = выкл.)", 0.0, 10.0, False), + ) + _COMMON_EXIT_FIELDS, + STRATEGY_FADE: _COMMON_RISK_FIELDS + ( + ("min_growth_24h", "Рост за 24 ч, не меньше %", 0.0, 10000.0, False), + ("min_funding_pct", "Funding не ниже, % (0 = выкл.)", 0.0, 10.0, False), + ("high_lookback_hours", "Максимум пампа за последние, ч", 0.5, 72.0, False), + ("pullback_pct", "Закрытие ниже максимума на, %", 0.0, 90.0, False), + ("vwap_hours", "VWAP по обороту за, ч", 0.5, 72.0, False), + ("stop_buffer_atr", "Стоп над максимумом, ATR", 0.0, 20.0, False), + ("max_stop_pct", "Макс. расстояние до стопа, %", 0.1, 100.0, False), + ) + _COMMON_EXIT_FIELDS, +} +MODE_DEFAULTS: dict[str, dict[str, float]] = { + STRATEGY_BREAKOUT: { + "stake_pct": 5.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0, + "breakout_hours": 4.0, "volume_mult": 2.0, "stop_atr": 2.0, + "btc_filter": 1.0, "btc_ema": 200.0, "max_funding_pct": 0.05, + "partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0, + "take_profit_r": 0.0, "max_hold_hours": 48.0, + }, + STRATEGY_FADE: { + "stake_pct": 3.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0, + "min_growth_24h": 30.0, "min_funding_pct": 0.03, "high_lookback_hours": 6.0, + "pullback_pct": 3.0, "vwap_hours": 6.0, "stop_buffer_atr": 0.5, "max_stop_pct": 15.0, + "partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0, + "take_profit_r": 0.0, "max_hold_hours": 24.0, + }, +} +ALLOWED_TIMEFRAMES = (5, 15, 30, 60) + + +def parse_mode_params(mode: str, raw: dict[str, object]) -> dict[str, float]: + """Validate the text values of a mode's settings; raises ValueError with a readable message.""" + params: dict[str, float] = {} + for key, label, minimum, maximum, integer in MODE_FIELDS[mode]: + value = raw.get(key, MODE_DEFAULTS[mode][key]) + try: + number = float(str(value).strip().replace(",", ".")) + except ValueError as exc: + raise ValueError(f"Проверьте значение «{label}».") from exc + if not math.isfinite(number) or not minimum <= number <= maximum: + raise ValueError(f"«{label}» должно быть от {minimum:g} до {maximum:g}.") + if integer and not number.is_integer(): + raise ValueError(f"«{label}» должно быть целым числом.") + params[key] = number + if int(params["timeframe_min"]) not in ALLOWED_TIMEFRAMES: + raise ValueError("Таймфрейм сигнала: 5, 15, 30 или 60 минут.") + if params["partial_pct"] > 0 and params["partial_r"] <= 0: + raise ValueError("Для частичной фиксации укажите R больше 0 или долю 0%.") + if (params["trail_atr"] <= 0 and params["take_profit_r"] <= 0 + and not (params["partial_r"] > 0 and params["partial_pct"] >= 100) + and params["max_hold_hours"] <= 0): + raise ValueError("Задайте выход по прибыли: трейлинг, финальный TP, 100% частичную фиксацию " + "или максимальное удержание.") + return params + + +def side_sign(side: str) -> float: + return -1.0 if side == "short" else 1.0 + + +def unrealized_pnl(side: str, entry: float, mark: float, qty: float) -> float: + return side_sign(side) * (mark - entry) * qty + + +def bars_for_hours(hours: float, timeframe_min: float) -> int: + return max(1, int(round(hours * 60 / timeframe_min))) + + +def aggregate_candles(rows: list[list[float]], timeframe_min: int) -> list[list[float]]: + """Group minute rows [start_ms, o, h, l, c, (turnover)] into timeframe candles.""" + step = int(timeframe_min) * 60_000 + output: list[list[float]] = [] + for row in rows: + bucket = (int(row[0]) // step) * step + turnover = float(row[5]) if len(row) > 5 and row[5] is not None else 0.0 + if output and output[-1][0] == bucket: + candle = output[-1] + candle[2] = max(candle[2], float(row[2])) + candle[3] = min(candle[3], float(row[3])) + candle[4] = float(row[4]) + candle[5] += turnover + else: + output.append([bucket, float(row[1]), float(row[2]), float(row[3]), float(row[4]), turnover]) + return output + + +def average_true_range(candles: list[list[float]], period: int) -> float | None: + """Simple average of the true range over the last ``period`` candles.""" + period = int(period) + if period < 1 or len(candles) < period + 1: + return None + ranges = [] + for previous, current in zip(candles[-period - 1:-1], candles[-period:]): + high, low, prev_close = float(current[2]), float(current[3]), float(previous[4]) + ranges.append(max(high - low, abs(high - prev_close), abs(low - prev_close))) + value = sum(ranges) / len(ranges) + return value if value > 0 else None + + +def turnover_vwap(candles: list[list[float]]) -> float | None: + """Average typical price weighted by turnover (falls back to an equal-weight mean).""" + if not candles: + return None + typical = [(float(c[2]) + float(c[3]) + float(c[4])) / 3 for c in candles] + weights = [float(c[5]) if len(c) > 5 and c[5] else 0.0 for c in candles] + total = sum(weights) + if total > 0: + return sum(price * weight for price, weight in zip(typical, weights)) / total + return sum(typical) / len(typical) + + +def ema(values: list[float], period: int) -> float | None: + period = int(period) + if period < 1 or len(values) < period: + return None + alpha = 2 / (period + 1) + value = sum(values[:period]) / period + for item in values[period:]: + value = alpha * item + (1 - alpha) * value + return value + + +def btc_regime_ok(hourly_closes: list[float], ema_period: int) -> bool | None: + """True when the last closed BTC hour is above its EMA; None without enough data.""" + average = ema(hourly_closes, ema_period) + if average is None: + return None + return hourly_closes[-1] > average + + +def required_bars(mode: str, params: dict[str, float]) -> int: + """Closed timeframe candles the signal needs (oldest to the just-closed one).""" + tf = params["timeframe_min"] + atr_bars = int(params["atr_period"]) + 1 + if mode == STRATEGY_BREAKOUT: + return max(bars_for_hours(params["breakout_hours"], tf) + 1, atr_bars) + return max(bars_for_hours(24, tf) + 1, bars_for_hours(params["high_lookback_hours"], tf), + bars_for_hours(params["vwap_hours"], tf), atr_bars) + + +def evaluate_breakout(candles: list[list[float]], params: dict[str, float], + funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None: + """Mode A signal on closed candles [start, o, h, l, c, turnover]; the last one has just closed.""" + if len(candles) < required_bars(STRATEGY_BREAKOUT, params): + return None + lookback = bars_for_hours(params["breakout_hours"], params["timeframe_min"]) + last = candles[-1] + prior = candles[-lookback - 1:-1] + level = max(float(c[2]) for c in prior) + close = float(last[4]) + if close <= level: + return None + if params["volume_mult"] > 0: + average = sum(float(c[5]) if len(c) > 5 else 0.0 for c in prior) / len(prior) + turnover = float(last[5]) if len(last) > 5 else 0.0 + if average > 0 and turnover < params["volume_mult"] * average: + return None + if params["btc_filter"] >= 1 and btc_ok is not True: + return None + if (params["max_funding_pct"] > 0 and funding_rate_pct is not None + and funding_rate_pct > params["max_funding_pct"]): + return None + atr = average_true_range(candles, int(params["atr_period"])) + if atr is None: + return None + return {"side": "long", "atr": atr, "level": level, "close": close, "candle_start": int(last[0])} + + +def evaluate_fade(candles: list[list[float]], params: dict[str, float], + funding_rate_pct: float | None = None) -> dict | None: + """Mode B signal on closed candles; returns the planned SHORT stop above the pump high.""" + if len(candles) < required_bars(STRATEGY_FADE, params): + return None + tf = params["timeframe_min"] + last = candles[-1] + close = float(last[4]) + day_ago = float(candles[-bars_for_hours(24, tf) - 1][4]) + if day_ago <= 0: + return None + growth = (close / day_ago - 1) * 100 + if growth < params["min_growth_24h"]: + return None + if params["min_funding_pct"] > 0 and (funding_rate_pct is None + or funding_rate_pct < params["min_funding_pct"]): + return None + window = candles[-bars_for_hours(params["high_lookback_hours"], tf):] + high_index = max(range(len(window)), key=lambda index: float(window[index][2])) + high = float(window[high_index][2]) + if high_index == len(window) - 1: + return None # the pump is still printing new highs + if close > high * (1 - params["pullback_pct"] / 100): + return None + vwap = turnover_vwap(candles[-bars_for_hours(params["vwap_hours"], tf):]) + if vwap is None or close >= vwap: + return None + atr = average_true_range(candles, int(params["atr_period"])) + if atr is None: + return None + return {"side": "short", "atr": atr, "high": high, "stop": high + params["stop_buffer_atr"] * atr, + "vwap": vwap, "growth": growth, "close": close, "candle_start": int(last[0])} + + +def evaluate_signal(mode: str, candles: list[list[float]], params: dict[str, float], + funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None: + if mode == STRATEGY_BREAKOUT: + return evaluate_breakout(candles, params, funding_rate_pct, btc_ok) + if mode == STRATEGY_FADE: + return evaluate_fade(candles, params, funding_rate_pct) + return None + + +def entry_plan(signal: dict, entry_price: float, params: dict[str, float]) -> dict | None: + """Stop and targets for an entry at ``entry_price``; None when the signal is no longer valid.""" + side = signal["side"] + if entry_price <= 0: + return None + if side == "long": + if entry_price <= signal["level"]: + return None # price fell back under the breakout level before the fill + stop = entry_price - params["stop_atr"] * signal["atr"] + if stop <= 0: + return None + else: + stop = signal["stop"] + if entry_price >= stop or (stop / entry_price - 1) * 100 > params["max_stop_pct"]: + return None + risk = abs(entry_price - stop) + sign = side_sign(side) + partial = (entry_price + sign * params["partial_r"] * risk + if params["partial_r"] > 0 and params["partial_pct"] > 0 else None) + final = entry_price + sign * params["take_profit_r"] * risk if params["take_profit_r"] > 0 else None + if final is not None and final <= 0: + final = None + if partial is not None and partial <= 0: + partial = None + return {"side": side, "stop": stop, "risk": risk, "atr": signal["atr"], + "partial_target": partial, "final_target": final} + + +def breakeven_price(side: str, entry: float, fee_pct: float) -> float: + cover = fee_cover_pct(fee_pct) / 100 + return entry * (1 + cover) if side == "long" else entry * (1 - cover) + + +def tighten_stop(side: str, stop: float, candidate: float) -> float: + """Stops only move in the trade's favour.""" + return max(stop, candidate) if side == "long" else min(stop, candidate) + + +def trailing_stop(side: str, stop: float, extreme: float, atr: float, trail_atr: float) -> float: + if trail_atr <= 0 or atr <= 0: + return stop + candidate = extreme - trail_atr * atr if side == "long" else extreme + trail_atr * atr + return tighten_stop(side, stop, candidate) + + +def trailing_active(partial_done: bool, params: dict[str, float]) -> bool: + """Trail from the start without a partial exit, otherwise only after it.""" + return params["trail_atr"] > 0 and (partial_done or params["partial_r"] <= 0 or params["partial_pct"] <= 0) + + +def stop_hit(side: str, price: float, stop: float) -> bool: + return price <= stop if side == "long" else price >= stop + + +def target_hit(side: str, price: float, target: float | None) -> bool: + if target is None or target <= 0: + return False + return price >= target if side == "long" else price <= target diff --git a/tests/test_algo_hunter.py b/tests/test_algo_hunter.py new file mode 100644 index 0000000..92beb40 --- /dev/null +++ b/tests/test_algo_hunter.py @@ -0,0 +1,334 @@ +"""Algo Hunter tests on synthetic order books: detector, tracker, executor (queue model, exits) and risk guard.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import algo_hunter as ah # noqa: E402 +import scalp_hint as sh # noqa: E402 +import scalp_paper as sp # noqa: E402 + +ah._logger().disabled = True # tests must not write into the live algo_hunter.log + +TICK = 0.0001 +MID = 0.1370 + + +def make_book(bids: dict[float, float], asks: dict[float, float]) -> sh.OrderBook: + book = sh.OrderBook() + book.apply_snapshot({"asks": [{"price": p, "size": s, "type": "Ask"} for p, s in asks.items()], + "bids": [{"price": p, "size": s, "type": "Bid"} for p, s in bids.items()]}) + return book + + +def background(algo_bid: float | None = None, algo_ask: float | None = None, algo_size: float = 500.0): + """Random-looking crowd; an algo order of `algo_size` sits ON TOP of the crowd at the given prices.""" + bids = {round(MID - (i + 1) * TICK, 4): 60.0 + 37 * ((i * 7) % 5) for i in range(10)} + asks = {round(MID + i * TICK, 4): 55.0 + 41 * ((i * 3) % 4) for i in range(10)} + if algo_bid is not None: + bids[round(algo_bid, 4)] += algo_size + if algo_ask is not None: + asks[round(algo_ask, 4)] += algo_size + return bids, asks + + +def algo_books(seconds: float = 3.0, dt: float = 0.05, period: float = 0.2, symmetric: bool = True): + """Book updates every `dt`; an MM re-quotes 500$ every `period` seconds, alternating between 1 and 2 ticks + behind the touch on both sides (a cancel + an add each time).""" + t, books = 0.0, [] + while t <= seconds + 1e-9: + offset = 1 + int(round(t / period)) % 2 + bids, asks = background(MID - (offset + 1) * TICK, MID + offset * TICK if symmetric else None) + books.append((round(t, 3), make_book(bids, asks))) + t += dt + return books + + +def run_algo(detector: ah.AlgoDetector, **kwargs): + sig = None + for t, book in algo_books(**kwargs): + sig, _ = detector.on_book(t, book, TICK) + return sig + + +class DetectorTests(unittest.TestCase): + def test_quiet_book_is_not_an_algo(self): + det = ah.AlgoDetector(ah.AlgoHunterConfig()) + sig = None + for i in range(20): + bids, asks = background() + sig, _ = det.on_book(i * 0.2, make_book(bids, asks), TICK) + self.assertTrue(sig is None or sig.confidence < 0.7) + + def test_periodic_symmetric_quoter_is_detected(self): + det = ah.AlgoDetector(ah.AlgoHunterConfig()) + sig = run_algo(det) + self.assertIsNotNone(sig) + self.assertGreaterEqual(sig.confidence, 0.7, sig.signals) + self.assertIn("периодичность", sig.signals) + self.assertIn("симметрия bid/ask", sig.signals) + self.assertEqual(sig.side, "both") + self.assertAlmostEqual(sig.size, 500.0, delta=1) + self.assertTrue(sig.price_levels) + + def test_cluster_of_equal_levels(self): + det = ah.AlgoDetector(ah.AlgoHunterConfig(min_levels_cluster=2)) + bids, asks = background() + bids[round(MID - TICK, 4)] = 300.0 + bids[round(MID - 2 * TICK, 4)] = 300.0 + det.on_book(0.0, make_book(bids, asks), TICK) # the first book is the baseline + sig, _ = det.on_book(0.2, make_book(bids, asks), TICK) + self.assertIn("кластер уровней", sig.signals) + self.assertEqual(sig.side, "bid") + + def test_batch_cancel_on_one_side(self): + det = ah.AlgoDetector(ah.AlgoHunterConfig(batch_size_threshold=3)) + crowd, asks = background() + quoted = dict(crowd) + for k in (1, 2, 3): + quoted[round(MID - k * TICK, 4)] += 500.0 + # The algo quotes three bid levels, pulls and re-quotes them a few times, then pulls all at once. + t = 0.0 + for i in range(8): + det.on_book(t, make_book(quoted if i % 2 == 0 else crowd, asks), TICK) + t += 0.2 + det.on_book(t, make_book(quoted, asks), TICK) + sig, events = det.on_book(t + 0.2, make_book(crowd, asks), TICK) + self.assertGreaterEqual(sum(e.action == "cancel" and e.side == "bid" for e in events), 3) + self.assertEqual(sig.batch_cancel_side, "bid") + + def test_size_tolerance_groups_near_sizes(self): + bids, asks = background() + bids[round(MID - TICK, 4)] = 200.0 + bids[round(MID - 2 * TICK, 4)] = 214.0 # 160 vs 170 coins: ~7% apart + strict = ah.AlgoDetector(ah.AlgoHunterConfig()) + loose = ah.AlgoDetector(ah.AlgoHunterConfig(size_tolerance=0.1)) + for det in (strict, loose): + det.on_book(0.0, make_book(bids, asks), TICK) + sig_strict, _ = strict.on_book(0.2, make_book(bids, asks), TICK) + sig_loose, _ = loose.on_book(0.2, make_book(bids, asks), TICK) + self.assertTrue(sig_strict is None or "кластер уровней" not in sig_strict.signals) + self.assertIn("кластер уровней", sig_loose.signals) + + def test_fills_are_not_counted_as_cancels(self): + det = ah.AlgoDetector(ah.AlgoHunterConfig()) + bids, asks = background() + det.on_book(0.0, make_book(bids, asks), TICK) + price = round(MID - TICK, 4) + det.on_trade(sh.Trade(0.1, price, bids[price], "Sell")) + reduced = dict(bids) + reduced[price] = 1.0 + _, events = det.on_book(0.2, make_book(reduced, asks), TICK) + self.assertEqual([e.action for e in events if e.price == price], ["fill"]) + + +class TrackerTests(unittest.TestCase): + def test_metrics_and_prediction(self): + cfg = ah.AlgoHunterConfig() + det, tracker = ah.AlgoDetector(cfg), ah.AlgoTracker(cfg) + for t, book in algo_books(seconds=4.0): + sig, events = det.on_book(t, book, TICK) + tracker.update(t, sig, events) + self.assertGreater(tracker.avg_lifetime_ms, 0) + self.assertGreater(tracker.replace_frequency(t), 0) + self.assertIn(tracker.typical_offset_ticks("bid"), (1, 2)) + price, share = tracker.prediction("bid", book, TICK) + self.assertGreater(price, 0) + self.assertGreaterEqual(share, 0.4) + + def test_adaptation_flag(self): + cfg = ah.AlgoHunterConfig() + tracker = ah.AlgoTracker(cfg) + strong = ah.AlgoSignature("bid", [], [], 0.85, 0.0, ["a", "b", "c", "d"], 500.0) + tracker.update(0.0, strong, []) + self.assertFalse(tracker.adapted) + tracker.update(1.0, None, []) + tracker.update(2.0, strong, []) # a brief dip does not count + tracker.update(3.0, None, []) + self.assertFalse(tracker.adapted) + tracker.update(7.5, None, []) # below the threshold for 4.5 s in a row + self.assertTrue(tracker.adapted) + + +class RiskGuardTests(unittest.TestCase): + def test_limits(self): + cfg = ah.AlgoHunterConfig(max_trades_per_minute=2, max_consecutive_losses=2, max_daily_loss_usd=1.0, + cooldown_after_exit_ms=0) + guard = ah.RiskGuard(cfg) + self.assertFalse(guard.allow(0.0, 15.0, 250.0)[0]) # latency 250 ms > 100 ms + self.assertFalse(guard.allow(0.0, 500.0, 10.0)[0]) # position above the limit + guard.on_entry(0.0) + guard.on_entry(1.0) + self.assertFalse(guard.allow(2.0, 15.0, 10.0)[0]) # 2 trades in the last minute + guard.on_close(100.0, -0.1) + guard.on_close(101.0, -0.1) + self.assertIn("пауза", guard.allow(102.0, 15.0, 10.0)[1]) # losing streak pause + guard.on_close(1000.0, -1.0) + self.assertIn("дневной убыток", guard.allow(2000.0, 15.0, 10.0)[1]) + + +class ExecutorTests(unittest.TestCase): + def trader(self, **cfg_overrides) -> sp.PaperTrader: + settings = sp.PaperSettings(mode="simple", stake=15.0, cooldown_seconds=0) + trader = sp.PaperTrader(settings, sh.HintSettings(), state_path=None, trades_path=None) + cfg_overrides.setdefault("dry_run", False) + cfg = ah.AlgoHunterConfig(**cfg_overrides) + trader.algo_config = cfg + trader.settings.mode = "algo_hunter" + with tempfile.TemporaryDirectory() as folder: + trader.policy = ah.AlgoHunterPolicy(settings, cfg, Path(folder) / "t.csv") + trader.data_latency_ms = 10.0 + return trader + + def warm(self, trader, seconds=3.0): + book, t = None, 0.0 + for t, book in algo_books(seconds=seconds): + trader.on_trade(sh.Trade(t, MID, 20.0, "Buy")) # market buys keep coming: pressure up + trader.on_book(t, book, TICK) + trader.on_tick(t, "X", sh.Hint("WAIT", "—", 0.0), book, TICK) + return t, book + + def test_dry_run_never_trades(self): + trader = self.trader(dry_run=True) + trader.policy.cfg.dry_run = True + self.warm(trader) + self.assertIsNone(trader.policy.order) + self.assertEqual(trader.trades, []) + self.assertIn("ПРОВЕРОЧНЫЙ", trader.policy.status) + + def test_entry_fill_and_take_profit(self): + trader = self.trader(tp_ticks=2, sl_ticks=3) + t, book = self.warm(trader) + order = trader.policy.order + self.assertIsNotNone(order, trader.policy.status) + self.assertEqual(order.side, "LONG") # pressure up + algo on the bid + # The market sells through our price -> filled, then buys through the target -> take profit. + trader.on_trade(sh.Trade(t + 1, round(order.price - TICK, 4), 50.0, "Sell")) + self.assertIsNotNone(trader.position) + trader.on_trade(sh.Trade(t + 1.2, round(order.price + 3 * TICK, 4), 50.0, "Buy")) + self.assertIsNone(trader.position) + self.assertEqual(trader.trades[-1].reason, "цель") + + def test_stop_and_time_exit(self): + trader = self.trader(tp_ticks=5, sl_ticks=2, max_hold_ms=500) + t, book = self.warm(trader) + order = trader.policy.order + trader.on_trade(sh.Trade(t + 1, round(order.price - TICK, 4), 50.0, "Sell")) + trader.on_book(t + 2, book, TICK) # 1 s later > 500 ms + self.assertEqual(trader.trades[-1].reason, "время") + + def test_blockers_are_all_listed_and_rearm_works(self): + trader = self.trader() + policy = trader.policy + policy.guard.disabled_reason = "алгос адаптировался (уверенность ниже порога) — режим выключен" + trader.data_latency_ms = 300.0 + wide = make_book({round(MID - 10 * TICK, 4): 100.0}, {round(MID + 10 * TICK, 4): 100.0}) + policy.tick = TICK + blockers = policy.entry_blockers(trader, 0.0, wide) + text = " | ".join(blockers) + for part in ("адаптировался", "не подтверждён", "спред", "задержка"): + self.assertIn(part, text) + policy.rearm() + self.assertEqual(policy.guard.disabled_reason, "") + self.assertFalse(policy.tracker.adapted) + + def test_quick_exit_closes_on_next_tick_either_way(self): + for move, word in ((+1, "вверх"), (-1, "вниз")): + trader = self.trader(quick_exit=True, tp_ticks=50, sl_ticks=50) + t, book = self.warm(trader) + order = trader.policy.order + self.assertIsNotNone(order, trader.policy.status) + trader.on_trade(sh.Trade(t + 1, round(order.price - TICK, 4), 50.0, "Sell")) # filled + self.assertIsNotNone(trader.position) + trader.on_trade(sh.Trade(t + 1.1, order.price, 5.0, "Buy")) # same price: still open + self.assertIsNotNone(trader.position) + trader.on_trade(sh.Trade(t + 1.2, round(order.price + move * TICK, 4), 5.0, "Buy")) + self.assertIsNone(trader.position) + self.assertIn(word, trader.trades[-1].reason) + trader.on_book(t + 60, book, TICK) # no time exit involved + + def test_requote_follows_the_book(self): + trader = self.trader(requote=True) + trader.data_latency_ms = 0.0 + self.warm(trader) # the algo alternates between 1 and 2 ticks behind the touch + policy = trader.policy + self.assertIsNotNone(policy.order) + self.assertGreater(policy.stats["requotes"], 0) + self.assertEqual(policy.stats["orders"], policy.stats["requotes"] + 1) # one order, moved, never dropped + + def test_fallback_places_orders_without_an_algo(self): + for bid_size, ask_size, side in ((900.0, 100.0, "LONG"), (100.0, 900.0, "SHORT")): + trader = self.trader(fallback=True, max_entry_spread_ticks=20) + trader.data_latency_ms = 0.0 + policy = trader.policy + bids = {round(MID - (i + 1) * TICK, 4): 100.0 for i in range(10)} + asks = {round(MID + (i + 4) * TICK, 4): 100.0 for i in range(10)} # a 4-tick spread + bids[round(MID - TICK, 4)] = bid_size + asks[round(MID + 4 * TICK, 4)] = ask_size + book = make_book(bids, asks) + for i in range(5): # quiet book: no algo + trader.on_book(100 + i * 0.2, book, TICK) + order = policy.order + self.assertIsNotNone(order, policy.status_reason) + self.assertEqual(order.side, side) + self.assertEqual(order.scenario, "микроцена + спред") + inside = round(MID, 4) if side == "LONG" else round(MID + 3 * TICK, 4) # one tick inside the spread + self.assertAlmostEqual(order.price, inside) + + def test_fallback_follows_spread_moves(self): + trader = self.trader(fallback=True, max_entry_spread_ticks=20) + trader.data_latency_ms = 0.0 + bids = {round(MID - (i + 1) * TICK, 4): 100.0 for i in range(10)} + asks = {round(MID + (i + 4) * TICK, 4): 100.0 for i in range(10)} + trader.on_book(100.0, make_book(bids, asks), TICK) # equal queues: tilt 0 + for k in (1, 2): # bids step into the spread + bids[round(MID - TICK + k * TICK, 4)] = 100.0 + trader.on_book(100 + 0.1 * k, make_book(bids, asks), TICK) + self.assertEqual(trader.policy.order.side, "LONG") + + def test_min_spread_blocks_entries(self): + trader = self.trader(min_entry_spread_ticks=5) # the synthetic book has a 1-tick spread + self.warm(trader) + self.assertIsNone(trader.policy.order) + self.assertIn("спред 1 шаг. < 5", trader.policy.status) + + def test_auto_rearm_after_confirmation(self): + trader = self.trader(rearm_after_ms=500) + policy = trader.policy + policy.guard.disabled_reason = "алгос адаптировался (уверенность ниже порога) — режим выключен" + policy.tracker.adapted = True + self.warm(trader, seconds=2.0) + self.assertEqual(policy.guard.disabled_reason, "") + + def test_no_auto_rearm_by_default(self): + trader = self.trader() + policy = trader.policy + policy.guard.disabled_reason = "алгос адаптировался (уверенность ниже порога) — режим выключен" + self.warm(trader, seconds=2.0) + self.assertTrue(policy.guard.disabled_reason.startswith("алгос адаптировался")) + + def test_latency_blocks_entries(self): + trader = self.trader() + trader.data_latency_ms = 300.0 + self.warm(trader) + self.assertIsNone(trader.policy.order) + self.assertIn("задержка", trader.policy.status) + + +class ConfigTests(unittest.TestCase): + def test_roundtrip(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "c.json" + cfg = ah.AlgoHunterConfig(tp_ticks=7, dry_run=False) + cfg.save(path) + again = ah.AlgoHunterConfig.load(path) + self.assertEqual((again.tp_ticks, again.dry_run), (7, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_arb.py b/tests/test_arb.py new file mode 100644 index 0000000..9950db2 --- /dev/null +++ b/tests/test_arb.py @@ -0,0 +1,148 @@ +"""Cross-exchange arbitrage scanner: best pair, costs, usual spread, funding, exchange parsing.""" + +from __future__ import annotations + +import sys +import threading +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import arb # noqa: E402 + + +def q(exchange, base, bid, ask, funding=None, interval=8, volume=1e6, depth=1000.0, mult=1.0): + return arb.Quote(exchange, f"{base}USDT", base, mult, bid, ask, depth, depth, funding, interval, volume) + + +class ArbTests(unittest.TestCase): + def test_best_pair_costs_and_funding(self): + quotes = [q("Bybit", "PEPE", 1.000, 1.001, funding=0.0001), q("MEXC", "PEPE", 1.010, 1.011, funding=0.0003), + q("Binance", "PEPE", 1.004, 1.005), q("Gate", "SOLO", 5, 5.01)] + rows = arb.best_pairs(quotes, {}) + self.assertEqual([r["coin"] for r in rows], ["PEPE"]) # SOLO is only on one exchange + r = rows[0] + self.assertEqual((r["buy"], r["sell"]), ("Bybit", "MEXC")) # buy the cheapest ask, sell the richest bid + self.assertAlmostEqual(r["gross"], (1.010 / 1.001 - 1) * 100) + self.assertAlmostEqual(r["round_cost"], 2 * (0.055 + 0.02)) + self.assertAlmostEqual(r["net_now"], r["gross"] - r["round_cost"]) + self.assertAlmostEqual(r["carry_8h"], 0.03 - 0.01) # short MEXC receives, long Bybit pays + self.assertIsNone(r["usual"]) + self.assertFalse(r["suspect"]) + self.assertEqual(set(r["prices"]), {"Bybit", "MEXC", "Binance"}) + + def test_pause_is_remembered_per_market(self): + import tempfile + with tempfile.TemporaryDirectory() as folder, \ + mock.patch.object(arb, "PAUSED_FILE", Path(folder) / "paused.json"): + s = arb.ArbScanner("spot") + self.assertFalse(s.paused) + s.set_paused(True) + self.assertTrue(arb.ArbScanner("spot").paused) + self.assertFalse(arb.ArbScanner("futures").paused) + with mock.patch.object(s, "scan_once") as scan, mock.patch.object(arb.time, "sleep", + side_effect=[None, StopIteration]): + with self.assertRaises(StopIteration): + s._loop() + scan.assert_not_called() # paused: no requests to the exchanges + + def test_spot_pair_costs_once_and_skips_leveraged(self): + quotes = [q("Bybit", "PEPE", 1.000, 1.001), q("MEXC", "PEPE", 1.010, 1.011), + q("Gate", "BTC3L", 1, 1.001), q("HTX", "BTC3L", 2, 2.001)] + rows = arb.best_pairs(quotes, {}, market="spot") + self.assertEqual([r["coin"] for r in rows], ["PEPE"]) # leveraged tokens are not the same asset + r = rows[0] + self.assertAlmostEqual(r["round_cost"], 0.1 + 0.05) # two spot trades, no round trip + self.assertIsNone(r["carry_8h"]) + self.assertIn("/trade/spot/PEPE/USDT", r["buy_url"]) + self.assertIsNotNone(r["transfer"]) + + def test_transfer_info_status_networks_fee(self): + wallet = {"HTX": {"X": {"chains": { + "ETH": {"withdraw": True, "deposit": True, "fee": 2.0, "addr": "0xabc", "name": "ERC20"}, + "BSC": {"withdraw": True, "deposit": True, "fee": 0.5, "addr": "0xdef", "name": "BEP20"}, + "TRX": {"withdraw": True, "deposit": True, "fee": 1e9, "addr": "", "name": "TRC20"}}}}, + "Gate": {"X": {"chains": { + "ETH": {"withdraw": True, "deposit": True, "fee": None, "addr": "0xabc", "name": "ETH"}, + "BSC": {"withdraw": True, "deposit": False, "fee": None, "addr": "0xdef", "name": "BSC"}}}}} + t = arb.transfer_info(wallet, "X", "HTX", "Gate", 1.0) + self.assertTrue(t["withdraw"]) + self.assertTrue(t["deposit"]) + self.assertEqual(t["networks"], ["ETH"]) # BSC deposit closed on Gate + self.assertEqual((t["fee_usd"], t["fee_net"]), (2.0, "ETH")) + self.assertFalse(t["different_token"]) + wallet["Gate"]["X"]["chains"]["ETH"]["addr"] = "0x999" + self.assertTrue(arb.transfer_info(wallet, "X", "HTX", "Gate", 1.0)["different_token"]) + unknown = arb.transfer_info(wallet, "X", "Binance", "Bybit", 1.0) + self.assertIsNone(unknown["withdraw"]) + self.assertIsNone(unknown["fee_usd"]) + + def test_norm_chain(self): + self.assertEqual(arb.norm_chain("ERC20"), "ETH") + self.assertEqual(arb.norm_chain("BEP20"), "BSC") + self.assertEqual(arb.norm_chain("TRC20"), "TRX") + + def test_usual_spread_and_expected(self): + quotes = [q("Bybit", "X", 1.0, 1.001), q("Gate", "X", 1.01, 1.011)] + r = arb.best_pairs(quotes, {"X|Bybit|Gate": 0.5})[0] + self.assertAlmostEqual(r["expected"], r["gross"] - 0.5 - r["round_cost"]) + + def test_suspect_and_funding_interval(self): + r = arb.best_pairs([q("Bybit", "Y", 1.0, 1.01), q("HTX", "Y", 1.5, 1.51)], {})[0] + self.assertTrue(r["suspect"]) + self.assertAlmostEqual(arb.funding_8h(q("Bybit", "Z", 1, 1.01, funding=0.0001, interval=1)), 0.08) + self.assertEqual(arb.split_base("1000PEPE"), ("PEPE", 1000.0)) + + def test_spread_must_survive_the_transfer(self): + s = arb.ArbScanner() + t0 = 1_800_000_000.0 + key = "X|Bybit|Gate" + # 20 minutes: the spread is 1 % except one dip to 0.1 % at minute 15 + for m in range(20): + for k in range(6): # every 10 s + t = t0 + m * 60 + k * 10 + gross = 0.1 if (m == 15 and k == 3) else 1.0 + s.record(key, gross, gross > 0.2, t, int(t // 60)) + now = t0 + 19 * 60 + 55 + low, have = s.window_min(key, 3, now) # last 3 minutes: no dip + self.assertEqual((low, have), (1.0, 20.0)) + low, _ = s.window_min(key, 10, now) # last 10 minutes include the dip + self.assertEqual(low, 0.1) + held = (now - s.profitable_since[key]) / 60 # profitable again since the dip + self.assertAlmostEqual(held, 4 + 25 / 60, delta=0.2) + s.rows = [{"key": key, "coin": "X"}] + s.thread = threading.Thread(target=lambda: None) # no real background polling in a test + with mock.patch.object(arb.time, "time", return_value=now): + v = s.view(transfer_min=10) + self.assertIsNotNone(v["rows"][0]["held_min"]) + self.assertEqual(v["rows"][0]["window_low"], 0.1) + + def test_parsers_htx_and_gate_convert_contracts(self): + f = arb.Fetchers() + f.ref = {"htx_size": {"PEPE-USDT": 1000.0}, "htx_interval": {"PEPE-USDT": 4}, "gate_interval": {}} + htx_ticks = {"ticks": [{"contract_code": "PEPE-USDT", "bid": [0.00001, 50], "ask": [0.0000101, 60], + "trade_turnover": "12345"}]} + + def fake(url, timeout=20): + if "funding" in url: + return {"data": [{"contract_code": "PEPE-USDT", "funding_rate": "0.0002"}]} + if "batch_merged" in url: + return htx_ticks + return [{"contract": "1000PEPE_USDT", "highest_bid": "0.01", "lowest_ask": "0.0101", "highest_size": "3", + "lowest_size": "4", "quanto_multiplier": "10", "funding_rate": "-0.0001", + "volume_24h_quote": "999"}] + + with mock.patch.object(arb, "_get", fake): + (h,) = f.htx() + (g,) = f.gate() + self.assertAlmostEqual(h.bid_usd, 0.00001 * 50 * 1000) + self.assertEqual((h.interval_h, h.funding), (4, 0.0002)) + self.assertEqual((g.base, g.mult), ("PEPE", 1000.0)) + self.assertAlmostEqual(g.bid, 0.00001) # per coin + self.assertAlmostEqual(g.bid_usd, 3 * 10 * 0.01) # 30 units of «1000PEPE» at 0.01 $ + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_backtest.py b/tests/test_backtest.py new file mode 100644 index 0000000..4a5e61a --- /dev/null +++ b/tests/test_backtest.py @@ -0,0 +1,314 @@ +"""Unit tests for the shared strategy rules and the historical backtest engine. + +Run from the project folder: py -3 -m unittest discover -s tests +""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import historical_backtest as hb # noqa: E402 +import strategy # noqa: E402 + +MIN = 60_000 + + +def flat(start: int, price: float, count: int) -> list[list[float]]: + return [[start + i * MIN, price, price, price, price] for i in range(count)] + + +def cfg(**overrides) -> dict[str, float]: + base = {"stake": 10.0, "leverage": 1.0, "trigger": 1.0, "add_step": 5.0, + "max_adds": 1, "stop_loss": 0.0, "take_profit": 10.0} + base.update(overrides) + return base + + +def run(candles, strategies, **kwargs): + # Entries are always allowed unless a test passes its own selection windows. + kwargs.setdefault("universe_windows", {symbol: [(0, 10**15)] for symbol in candles}) + kwargs.setdefault("min_equity_pct", 0.0) + return hb.run_backtest(candles, strategies, 100.0, fee_pct=0.0, **kwargs) + + +class StrategyFormulaTests(unittest.TestCase): + def test_fee_cover(self): + self.assertAlmostEqual(strategy.fee_cover_pct(0.0), 0.0) + self.assertGreater(strategy.fee_cover_pct(0.055), 0.11) + + def test_take_profit_is_raised_to_cover_fees(self): + self.assertAlmostEqual(strategy.effective_take_profit_pct(0.01, 0.055), strategy.fee_cover_pct(0.055)) + self.assertEqual(strategy.effective_take_profit_pct(0, 0.055), 0.0) + + def test_liquidation_only_with_leverage(self): + self.assertIsNone(strategy.liquidation_price(100, 1)) + self.assertAlmostEqual(strategy.liquidation_price(100, 10, 0.5), 90.5) + + +class MissingRangesTests(unittest.TestCase): + def test_gaps(self): + gaps = hb._missing_ranges(0, 10 * MIN, [(2 * MIN, 4 * MIN), (7 * MIN, 8 * MIN)], MIN) + self.assertEqual(gaps, [(0, MIN), (5 * MIN, 6 * MIN), (9 * MIN, 10 * MIN)]) + + def test_fully_covered(self): + self.assertEqual(hb._missing_ranges(0, 5 * MIN, [(0, 5 * MIN)], MIN), []) + + +class BacktestTests(unittest.TestCase): + def entry_then(self, *candles): + """Baseline candle at 100, then an entry candle that rises to 101.5 (trigger 1%).""" + rows = [[0, 100, 100, 100, 100], [MIN, 100, 101.5, 100, 101.5]] + for i, c in enumerate(candles, start=2): + rows.append([i * MIN, *c]) + return {"AAA": rows} + + def test_entry_and_take_profit(self): + candles = self.entry_then((101.5, 112, 101.5, 111)) + result = run(candles, {"AAA": cfg()}) + trades = [t for t in result["trades"] if t["status"] == "CLOSED"] + self.assertEqual(len(trades), 1) + self.assertAlmostEqual(trades[0]["exit"], 101.0 * 1.10) + self.assertGreater(trades[0]["net_usdt"], 0) + + def test_average_down_then_open_loss_and_drawdown(self): + candles = self.entry_then((101, 101, 90, 90)) + result = run(candles, {"AAA": cfg()}) + summary = result["summary"] + open_rows = [t for t in result["trades"] if t["status"] == "OPEN"] + self.assertEqual(len(open_rows), 1) + self.assertEqual(open_rows[0]["entries"], 2) + self.assertGreater(summary["max_drawdown_pct"], 0) + self.assertEqual(summary["open_losing_positions"], 1) + + def test_gap_down_triggers_stop_at_open(self): + candles = self.entry_then((80, 80, 79, 79)) + result = run(candles, {"AAA": cfg(stop_loss=5.0, add_step=0.0, max_adds=0)}) + closed = [t for t in result["trades"] if t["status"] == "CLOSED"] + self.assertEqual(len(closed), 1) + self.assertEqual(closed[0]["exit"], 80) + self.assertIn("разрыв", closed[0]["reason"]) + + def test_liquidation_with_leverage(self): + candles = self.entry_then((101, 101, 85, 85)) + result = run(candles, {"AAA": cfg(leverage=10.0, add_step=0.0, max_adds=0)}) + closed = [t for t in result["trades"] if t["status"] == "CLOSED"] + self.assertEqual(len(closed), 1) + self.assertTrue(closed[0]["reason"].startswith("Ликвидация")) + self.assertAlmostEqual(closed[0]["net_usdt"], -10.0) + self.assertEqual(result["summary"]["liquidations"], 1) + + def test_position_limit(self): + rows = [[0, 100, 100, 100, 100], [MIN, 100, 101.5, 100, 101.5]] + candles = {"AAA": rows, "BBB": [list(r) for r in rows]} + result = run(candles, {"AAA": cfg(), "BBB": cfg()}, max_open_positions=1) + self.assertEqual(result["summary"]["open_positions"], 1) + self.assertEqual(result["summary"]["skipped_entries_position_limit"], 1) + + def test_universe_windows_gate_entries(self): + candles = self.entry_then((101.5, 101.5, 101.5, 101.5)) + blocked = run(candles, {"AAA": cfg()}, universe_windows={"AAA": [(10 * MIN, 20 * MIN)]}) + allowed = run(candles, {"AAA": cfg()}, universe_windows={"AAA": [(0, 20 * MIN)]}) + self.assertEqual(blocked["summary"]["open_positions"], 0) + self.assertEqual(allowed["summary"]["open_positions"], 1) + + def test_equity_stop(self): + candles = self.entry_then((101, 101, 5, 5)) + result = hb.run_backtest(candles, {"AAA": cfg(stake=90.0, add_step=0.0, max_adds=0)}, 100.0, + fee_pct=0.0, universe_windows={"AAA": [(0, 10**15)]}, + min_equity_pct=50.0) + self.assertTrue(result["summary"]["equity_stop_triggered"]) + + +class FundingTests(unittest.TestCase): + def test_long_pays_positive_funding(self): + rows = [[0, 100, 100, 100, 100], [MIN, 100, 101.5, 100, 101.5], + [2 * MIN, 101, 101, 101, 101], [3 * MIN, 101, 101, 101, 101]] + result = run({"AAA": rows}, {"AAA": cfg(add_step=0.0, max_adds=0)}, + funding_by_symbol={"AAA": {2 * MIN: 0.01}}) + open_row = [t for t in result["trades"] if t["status"] == "OPEN"][0] + # qty = 10 / 101 at entry 101; payment = qty × 101 × 1% = 0.1 USDT. + self.assertAlmostEqual(open_row["funding_usdt"], -0.1) + self.assertAlmostEqual(result["summary"]["funding_usdt"], -0.1) + without = run({"AAA": rows}, {"AAA": cfg(add_step=0.0, max_adds=0)}) + self.assertAlmostEqual(result["summary"]["total_net_including_open_usdt"], + without["summary"]["total_net_including_open_usdt"] - 0.1) + + def test_funding_cache_roundtrip(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "cache.sqlite3" + connection = hb._open_candle_cache(path) + hb._cache_funding_page(connection, "AAA", 0, 10 * MIN, [(0, 0.0001), (8 * MIN, -0.0002)]) + connection.close() + # Fully covered: no network request is needed. + rates = hb.fetch_funding_history("AAA", 0, 10 * MIN, cache_path=path) + self.assertEqual(rates, {0: 0.0001, 8 * MIN: -0.0002}) + + +def mode_params(mode: str, **overrides) -> dict[str, float]: + raw = {key: f"{value:g}" for key, value in strategy.MODE_DEFAULTS[mode].items()} + raw.update({key: str(value) for key, value in overrides.items()}) + return strategy.parse_mode_params(mode, raw) + + +class ModeSignalTests(unittest.TestCase): + def test_parse_rejects_bad_timeframe(self): + with self.assertRaises(ValueError): + mode_params(strategy.STRATEGY_BREAKOUT, timeframe_min=7) + + def test_breakout_signal(self): + params = mode_params(strategy.STRATEGY_BREAKOUT, timeframe_min=15, breakout_hours=1, atr_period=3, + volume_mult=2, btc_filter=0) + candles = [[i * 15 * MIN, 100, 101, 99, 100, 10.0] for i in range(6)] + candles.append([6 * 15 * MIN, 100, 103, 100, 102.5, 30.0]) + signal = strategy.evaluate_breakout(candles, params) + self.assertIsNotNone(signal) + self.assertEqual(signal["level"], 101) + candles[-1][5] = 15.0 # volume spike too small + self.assertIsNone(strategy.evaluate_breakout(candles, params)) + + def test_breakout_btc_filter(self): + params = mode_params(strategy.STRATEGY_BREAKOUT, breakout_hours=1, atr_period=3, volume_mult=0) + candles = [[i * 15 * MIN, 100, 101, 99, 100, 10.0] for i in range(6)] + candles.append([6 * 15 * MIN, 100, 103, 100, 102.5, 30.0]) + self.assertIsNone(strategy.evaluate_breakout(candles, params, btc_ok=False)) + self.assertIsNotNone(strategy.evaluate_breakout(candles, params, btc_ok=True)) + + def test_fade_signal_and_plan(self): + params = mode_params(strategy.STRATEGY_FADE, timeframe_min=60, min_growth_24h=30, min_funding_pct=0.05, + high_lookback_hours=6, pullback_pct=3, vwap_hours=6, atr_period=3, + stop_buffer_atr=0.5, max_stop_pct=30) + candles = [[h * 60 * MIN, 100, 101, 99, 100, 1.0] for h in range(20)] + for h, price in zip(range(20, 25), (110, 125, 140, 150, 146)): + candles.append([h * 60 * MIN, price - 2, price + 2, price - 4, price, 5.0]) + candles.append([25 * 60 * MIN, 146, 147, 128, 130, 5.0]) + self.assertIsNone(strategy.evaluate_fade(candles, params, funding_rate_pct=0.01)) + signal = strategy.evaluate_fade(candles, params, funding_rate_pct=0.1) + self.assertIsNotNone(signal) + self.assertEqual(signal["side"], "short") + self.assertGreater(signal["stop"], signal["high"]) + plan = strategy.entry_plan(signal, 130, params) + self.assertLess(plan["partial_target"], 130) + self.assertIsNone(strategy.entry_plan(signal, signal["stop"] + 1, params)) + + def test_trailing_only_tightens(self): + self.assertEqual(strategy.trailing_stop("long", 95, 100, 2, 3), 95) + self.assertEqual(strategy.trailing_stop("long", 95, 110, 2, 3), 104) + self.assertEqual(strategy.trailing_stop("short", 105, 90, 2, 3), 96) + self.assertEqual(strategy.trailing_stop("short", 105, 104, 2, 3), 105) + + def test_short_liquidation(self): + self.assertAlmostEqual(strategy.liquidation_price(100, 10, 0.5, side="short"), 109.5) + + +def minute_rows(prices_by_bucket: list[tuple[float, float, float, float, float]], tf_min: int = 15, + start: int = 0) -> list[list[float]]: + """One minute row per signal candle (enough for aggregation tests).""" + return [[start + i * tf_min * MIN, *candle] for i, candle in enumerate(prices_by_bucket)] + + +class ModeBacktestTests(unittest.TestCase): + def breakout_rows(self, after: list[tuple[float, float, float, float, float]]): + rows = [(100, 101, 99, 100, 10.0)] * 6 + [(100, 103, 100, 102.5, 40.0)] + after + return {"AAA": minute_rows(rows)} + + def params(self, **overrides): + base = dict(timeframe_min=15, breakout_hours=1, atr_period=3, volume_mult=2, btc_filter=0, + stop_atr=1, partial_r=1, partial_pct=50, breakeven=1, trail_atr=0, take_profit_r=3, + max_hold_hours=0, max_funding_pct=0) + base.update(overrides) + return mode_params(strategy.STRATEGY_BREAKOUT, **base) + + def run_mode(self, candles, params, **kwargs): + kwargs.setdefault("min_equity_pct", 0.0) + return hb.run_mode_backtest(candles, strategy.STRATEGY_BREAKOUT, params, 100.0, fee_pct=0.0, **kwargs) + + def test_breakout_enters_next_candle_and_hits_stop(self): + candles = self.breakout_rows([(102.5, 102.6, 90, 91, 10.0)]) + result = self.run_mode(candles, self.params()) + closed = [t for t in result["trades"] if t["status"] == "CLOSED"] + self.assertEqual(len(closed), 1) + self.assertEqual(closed[0]["side"], "LONG") + self.assertTrue(closed[0]["reason"].startswith("Стоп")) + self.assertLess(closed[0]["net_usdt"], 0) + self.assertEqual(result["summary"]["signals"], 1) + + def test_partial_breakeven_then_target(self): + # ATR of the last 3 candles is 2.67; risk = 2.67, partial at +1R, final at +3R. + candles = self.breakout_rows([(102.5, 106, 102.4, 105.5, 10.0), (105.5, 112, 105, 111, 10.0)]) + result = self.run_mode(candles, self.params()) + closed = [t for t in result["trades"] if t["status"] == "CLOSED"] + self.assertEqual(len(closed), 1) + self.assertTrue(closed[0]["reason"].startswith("TP")) + self.assertGreater(closed[0]["net_usdt"], 0) + + def test_breakeven_stop_after_partial(self): + candles = self.breakout_rows([(102.5, 106, 102.4, 105.5, 10.0), (105.5, 105.5, 95, 96, 10.0)]) + result = self.run_mode(candles, self.params()) + closed = [t for t in result["trades"] if t["status"] == "CLOSED"] + self.assertEqual(len(closed), 1) + self.assertIn("безубыток", closed[0]["reason"]) + self.assertGreater(closed[0]["net_usdt"], 0) # half closed at +1R, the rest at breakeven + + def test_short_receives_positive_funding(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) + rows = [(100, 101, 99, 100, 1.0)] * 20 + rows += [(price - 2, price + 2, price - 4, price, 5.0) for price in (110, 125, 140, 150, 146)] + rows += [(146, 147, 128, 130, 5.0), (130, 131, 129, 130, 5.0), (130, 131, 129, 130, 5.0)] + candles = {"AAA": minute_rows(rows, tf_min=60)} + funding_stamp = 27 * 60 * MIN + result = hb.run_mode_backtest(candles, strategy.STRATEGY_FADE, params, 100.0, fee_pct=0.0, + min_equity_pct=0.0, funding_by_symbol={"AAA": {funding_stamp: 0.01}}) + rows_out = result["trades"] + self.assertEqual(len(rows_out), 1) + self.assertEqual(rows_out[0]["side"], "SHORT") + self.assertGreater(rows_out[0]["funding_usdt"], 0) + + def test_universe_window_blocks_entry(self): + candles = self.breakout_rows([(102.5, 102.6, 102, 102.5, 10.0)]) + result = self.run_mode(candles, self.params(), universe_windows={"AAA": []}) + self.assertEqual(result["trades"], []) + + +class UniverseTests(unittest.TestCase): + def test_build_universe_windows(self): + hour = 3_600_000 + start = 48 * hour + # PUMP doubles after the first day; FLAT never moves. Both are liquid. + pump = [[t * hour, 1, 1, 1, 1.0 if t < 24 else 2.0, 1000.0] for t in range(0, 72)] + flat_rows = [[t * hour, 1, 1, 1, 1.0, 500.0] for t in range(0, 72)] + windows = hb.build_universe_windows({"PUMP": pump, "FLAT": flat_rows}, start, 70 * hour, 20.0) + self.assertIn("PUMP", windows) + self.assertNotIn("FLAT", windows) + self.assertEqual(windows["PUMP"][0][0], start) + + def test_top_n_limits_selection(self): + hour = 3_600_000 + rich = [[t * hour, 1, 1, 1, 1.0 if t < 24 else 2.0, 1000.0] for t in range(60)] + poor = [[t * hour, 1, 1, 1, 1.0 if t < 24 else 2.0, 1.0] for t in range(60)] + windows = hb.build_universe_windows({"RICH": rich, "POOR": poor}, 48 * hour, 58 * hour, 20.0, top_n=1) + self.assertEqual(set(windows), {"RICH"}) + + +class CacheTests(unittest.TestCase): + def test_turnover_migration_and_roundtrip(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "cache.sqlite3" + connection = hb._open_candle_cache(path) + hb._cache_page(connection, "AAA", 60, 0, 3_600_000, + [[0, 1, 2, 0.5, 1.5, 123.0], [3_600_000, 1.5, 2, 1, 1.8, 50.0]], 3_600_000) + connection.close() + rows = hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path, with_turnover=True) + self.assertEqual(rows[0][5], 123.0) + self.assertEqual(len(hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path)[0]), 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_basis.py b/tests/test_basis.py new file mode 100644 index 0000000..1979f7b --- /dev/null +++ b/tests/test_basis.py @@ -0,0 +1,124 @@ +"""Spot–futures basis trades: gaps, entry rules, exit at convergence, result with fees and funding, settings.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import basis # noqa: E402 + + +def pair(base="NEW", spot=(1.000, 1.001), fut=(1.010, 1.011), depth=10_000.0, age=5.0, innovation=False, meme=False, + funding=0.0001, next_funding=0.0, turnover=1e6): + return basis.Pair(base, f"{base}USDT", f"{base}USDT", 1.0, spot[0], spot[1], fut[0], fut[1], depth, depth, depth, + depth, funding, next_funding, 8.0, turnover, turnover, age, innovation, meme) + + +class BasisTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.e = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + self.e.settings.running = True + + def tearDown(self): + self.dir.cleanup() + + def test_gaps(self): + p = pair() + self.assertAlmostEqual(p.entry_gap, (1.010 / 1.001 - 1) * 100) + self.assertAlmostEqual(p.exit_gap, (1.011 / 1.000 - 1) * 100) + + def test_universe(self): + s = basis.BasisSettings() + self.assertTrue(basis.in_universe(pair(age=10), s)) + self.assertFalse(basis.in_universe(pair(age=400), s)) + self.assertTrue(basis.in_universe(pair(age=400, meme=True), s)) + self.assertTrue(basis.in_universe(pair(age=None, innovation=True), s)) + s.use_memes = False + self.assertFalse(basis.in_universe(pair(age=400, meme=True), s)) + s.all_coins = True + self.assertTrue(basis.in_universe(pair(age=400), s)) + + def test_entry_limits(self): + e = self.e + e.pairs = {"SMALL": pair("SMALL", fut=(1.003, 1.004)), # +0.2% < min 0.6% + "HUGE": pair("HUGE", fut=(1.2, 1.21)), # +19.9% > max 10% + "THIN": pair("THIN", depth=50.0), # less than the 100 $ amount at the best price + "OK": pair("OK")} + e.step(1000.0) + self.assertEqual([p.base for p in e.positions], ["OK"]) + e.step(1001.0) + self.assertEqual(len(e.positions), 1) # one position per coin + + def test_unknown_depth_is_not_checked(self): + p = pair("MX") + p.fut_bid_usd = None # MEXC futures / Gate: size at the best price unknown + self.assertIsNone(basis.entry_depth(p)) + self.assertTrue(basis.depth_ok(p, self.e.settings)) + p.spot_ask_usd = 10.0 # a known leg that is too thin still blocks + self.assertFalse(basis.depth_ok(p, self.e.settings)) + + def test_all_exchanges_registered(self): + self.assertEqual(set(basis.VENUES), {"bybit", "binance", "mexc", "htx", "gate"}) + for key in ("binance", "mexc", "htx", "gate"): + v = basis.VENUES[key]() + self.assertGreater(v.spot_fee, 0) + self.assertIn(v.name.lower()[:3], v.fut_url(pair("ABC")).lower() + v.name.lower()) + + def test_stopped_opens_nothing(self): + self.e.settings.running = False + self.e.pairs = {"OK": pair("OK")} + self.e.step(1000.0) + self.assertEqual(self.e.positions, []) + + def test_exit_on_convergence_with_fees_and_funding(self): + e = self.e + e.pairs = {"OK": pair("OK", next_funding=1500.0)} + e.step(1000.0) + pos = e.positions[0] + qty = 100 / 1.001 + self.assertAlmostEqual(pos.qty, qty) + # funding settles while open: the short receives 0.01% of the position + e.pairs = {"OK": pair("OK", spot=(1.050, 1.051), fut=(1.050, 1.0505), next_funding=30000.0)} + e.step(1600.0) # exit gap 1.0505 / 1.050 − 1 = 0.048% ≤ 0.05% + self.assertEqual(e.positions, []) + t = e.trades[0] + self.assertAlmostEqual(t.funding, qty * 1.05025 * 0.0001) # settled before the exit in the same step + s = e.settings + spot_pnl = qty * (1.050 - 1.001) + fut_pnl = qty * (1.010 - 1.0505) + fees = qty * 1.001 * s.spot_fee / 100 + qty * 1.010 * s.fut_fee / 100 + qty * 1.050 * s.spot_fee / 100 \ + + qty * 1.0505 * s.fut_fee / 100 + self.assertAlmostEqual(t.spot_pnl, spot_pnl) + self.assertAlmostEqual(t.fut_pnl, fut_pnl) + self.assertAlmostEqual(t.fees, fees) + self.assertAlmostEqual(t.net, spot_pnl + fut_pnl - fees + t.funding) + self.assertGreater(t.funding, 0) + self.assertEqual(t.reason, "разница сошлась") + e.step(1610.0) # cooldown: no re-entry right away + self.assertEqual(e.positions, []) + + def test_settings_saved_and_checked(self): + self.assertEqual(self.e.set_settings({"min_gap_pct": "0.8", "use_memes": False, "max_positions": "3"}), "") + again = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + self.assertEqual((again.settings.min_gap_pct, again.settings.use_memes, again.settings.max_positions), + (0.8, False, 3)) + self.assertTrue(self.e.set_settings({"min_gap_pct": "0.01", "exit_gap_pct": "0.05"})) + + def test_manual_close_and_view(self): + e = self.e + e.pairs = {"OK": pair("OK")} + e.step(1000.0) + v = e.view() + self.assertEqual(v["stats"]["open"], 1) + self.assertTrue(v["rows"][0]["fits"] is False or v["rows"][0]["base"] == "OK") + self.assertIn("закрыто позиций: 1", e.close(None)) + self.assertEqual(e.view()["stats"]["trades"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_connections_remove.py b/tests/test_connections_remove.py new file mode 100644 index 0000000..5361d6c --- /dev/null +++ b/tests/test_connections_remove.py @@ -0,0 +1,74 @@ +"""Deleting a pair: out of the list, defaults don't come back, adding it again by hand undoes the delete.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import lead_window as lw # noqa: E402 + + +class RemoveConnectionTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.conns = Path(self.dir.name) / "c.json" + self.removed = Path(self.dir.name) / "r.json" + self.extra = {"lead_market": "raydium", "lead_ticker": "", "lead_pool": "POOL1", + "follow_exchange": "binance", "follow_ticker": "TRUMPUSDT"} + lw._write_list(self.conns, [self.extra]) + + def tearDown(self): + self.dir.cleanup() + + def load(self): + return lw.load_connections(self.conns, self.removed) + + def test_remove_saved_and_default(self): + self.assertTrue(any(lw.same_connection(self.extra, c) for c in self.load())) + lw.remove_connection(self.extra, self.conns, self.removed) + default = lw.DEFAULT_CONNECTIONS[0] + lw.remove_connection(default, self.conns, self.removed) + left = self.load() + self.assertFalse(any(lw.same_connection(self.extra, c) for c in left)) + self.assertFalse(any(lw.same_connection(default, c) for c in left)) # built-in one stays deleted + self.assertEqual(len(left), len(lw.DEFAULT_CONNECTIONS) - 1) + self.assertTrue(lw.is_removed(self.extra, self.removed)) + + def test_add_again_by_hand(self): + lw.remove_connection(self.extra, self.conns, self.removed) + lw.unremove_connection(self.extra, self.removed) + lw._write_list(self.conns, [self.extra]) + self.assertTrue(any(lw.same_connection(self.extra, c) for c in self.load())) + self.assertFalse(lw.is_removed(self.extra, self.removed)) + + +class SimulatorRemoveTests(unittest.TestCase): + def test_remove_stops_feeds_and_closes(self): + import threading + from unittest import mock + import web_sim as ws + + calls = [] + 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)) + engine.shutdown.side_effect = lambda: calls.append("shutdown") + sim = ws.Simulator.__new__(ws.Simulator) + sim.engines, sim.lock = {"k": engine}, threading.Lock() + 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) + self.assertIn("закрыто позиций: 2", message) + self.assertEqual(sim.remove("k"), "нет такой монеты") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cross.py b/tests/test_cross.py new file mode 100644 index 0000000..7a5a5f8 --- /dev/null +++ b/tests/test_cross.py @@ -0,0 +1,175 @@ +"""Spot–futures between exchanges (paper): links A→B, the usual gap, entry above it, exit back to it.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import arb # noqa: E402 +import cross # noqa: E402 + + +def q(ex, base, bid, ask, vol=1e6, depth=1e4, funding=0.0001): + return arb.Quote(ex, f"{base}USDT", base, 1.0, bid, ask, depth, depth, funding, 8.0, vol) + + +class CrossTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.e = cross.CrossEngine(Path(self.dir.name), start=False) + self.e.settings.running = True + self.e.settings.exit_hold_s = 0.0 + + def tearDown(self): + self.dir.cleanup() + + def feed(self, now, spot_ask, fut_bid, spot_ex="Gate", fut_ex="Binance"): + spots = [q(spot_ex, "XYZ", spot_ask - 0.001, spot_ask)] + futs = [q(fut_ex, "XYZ", fut_bid, fut_bid + 0.001), q(spot_ex, "XYZ", 99, 100)] # same exchange: ignored + self.e.links = cross.build_links(spots, futs, set(arb.EXCHANGES)) + self.e.learn(now) + self.e.step(now) + + def test_links_only_between_different_exchanges(self): + spots = [q("Gate", "XYZ", 0.99, 1.0), q("MEXC", "XYZ", 0.995, 1.005), q("Gate", "BTC3L", 1, 1.01)] + futs = [q("Binance", "XYZ", 1.02, 1.021), q("Gate", "XYZ", 1.03, 1.031)] + links = cross.build_links(spots, futs, set(arb.EXCHANGES), kinds=("sf",)) + self.assertEqual(set(links), {"XYZ|Gate|Binance", "XYZ|MEXC|Binance", "XYZ|MEXC|Gate"}) + self.assertAlmostEqual(links["XYZ|Gate|Binance"].entry_gap, (1.02 / 1.0 - 1) * 100) + # all three kinds: inside one exchange (Gate spot → Gate perp) and spot → spot both ways + links = cross.build_links(spots, futs, set(arb.EXCHANGES)) + self.assertEqual({k for k, l in links.items() if l.kind == "in"}, {"XYZ|Gate|Gate"}) + self.assertEqual({k for k, l in links.items() if l.kind == "ss"}, {"XYZ|Gate|MEXC|ss", "XYZ|MEXC|Gate|ss"}) + ss = links["XYZ|Gate|MEXC|ss"] + self.assertEqual((ss.fut_bid, ss.fut_ask), (0.995, 1.005)) # MEXC's SPOT prices + self.assertAlmostEqual(cross.round_trip_fee_pct("Gate", "MEXC", ss=True), + 2 * (cross.SPOT_FEE["Gate"] + cross.SPOT_FEE["MEXC"])) + + def test_persistent_offset_is_not_traded(self): + # the perp on Binance always 3 % above Gate's spot: that is its usual gap, nothing to capture + for i in range(400): # 20 minutes of history + self.feed(1000.0 + i * 3, 1.0, 1.03) + self.assertGreater(self.e.history_min("XYZ|Gate|Binance", 1000.0 + 399 * 3), 15) + self.assertAlmostEqual(self.e.usual["XYZ|Gate|Binance"], (1.0305 / 0.9995 - 1) * 100, delta=0.01) + self.assertEqual(self.e.positions, []) + + def test_enter_above_usual_exit_when_back(self): + t = 1000.0 + for i in range(400): + self.feed(t + i * 3, 1.0, 1.01) # usual ≈ +1.1 % (mid to mid) + t += 400 * 3 + self.feed(t, 1.0, 1.02) # +2 %: about 0.9 % above the usual + self.assertEqual(len(self.e.positions), 1) + pos = self.e.positions[0] + self.assertEqual((pos.spot_ex, pos.fut_ex), ("Gate", "Binance")) + self.assertAlmostEqual(pos.usual, 1.1, delta=0.05) + self.feed(t + 30, 1.0, 1.0145) # exit gap 1.65 % > usual + 0.05 → held + self.assertEqual(len(self.e.positions), 1) + self.feed(t + 60, 1.0, 1.008) # exit gap 1.0 %: back to the usual → closed + self.assertEqual(self.e.positions, []) + tr = self.e.trades[0] + self.assertIn("обычной", tr.reason) + fees = tr.qty * (1.0 * 0.1 + 1.02 * cross.fut_fee("Binance") + 0.999 * 0.1 + 1.009 * cross.fut_fee("Binance")) / 100 + self.assertAlmostEqual(tr.fees, fees, places=6) + self.assertAlmostEqual(tr.net, tr.spot_pnl + tr.fut_pnl - tr.fees + tr.funding) + + def test_not_before_enough_history(self): + for i in range(60): # 3 minutes only + self.feed(1000.0 + i * 3, 1.0, 1.01) + self.feed(1000.0 + 180, 1.0, 1.03) + self.assertEqual(self.e.positions, []) + + def test_stop_when_gap_widens(self): + t = 1000.0 + for i in range(400): + self.feed(t + i * 3, 1.0, 1.01) + t += 400 * 3 + self.feed(t, 1.0, 1.02) + self.assertEqual(len(self.e.positions), 1) + self.feed(t + 30, 1.0, 1.045) # widened by > 2 % + self.assertIn("стоп", self.e.trades[0].reason) + + def test_exchange_switched_off(self): + self.e.settings.use_gate = False + t = 1000.0 + for i in range(400): + self.feed(t + i * 3, 1.0, 1.01) + self.feed(t + 1200, 1.0, 1.03) + self.assertEqual(self.e.positions, []) + self.assertEqual(self.e.view()["rows"], []) + + def test_fast_watch_closes_on_fresh_prices(self): + import threading + import time + from unittest import mock + t = 1000.0 + for i in range(400): + self.feed(t + i * 3, 1.0, 1.01) + self.feed(t + 1200, 1.0, 1.02) + self.assertEqual(len(self.e.positions), 1) + seen = [] + with mock.patch("fastquote.spot_top", lambda ex, s: seen.append(("spot", ex)) or (0.999, 1.0, None, None)), \ + mock.patch("fastquote.fut_top", lambda ex, s: seen.append(("fut", ex)) or (1.008, 1.009, None, None)): + threading.Thread(target=self.e._fast_loop, daemon=True).start() + end = time.time() + 3 + while self.e.positions and time.time() < end: + time.sleep(0.02) + self.assertEqual(self.e.positions, []) + self.assertIn(("spot", "Gate"), seen) # spot from A, perp from B + self.assertIn(("fut", "Binance"), seen) + self.assertIn("обычной", self.e.trades[0].reason) + + def test_usual_survives_restart(self): + for i in range(400): + self.feed(1000.0 + i * 3, 1.0, 1.01) + self.e._save_usual(cross.time.time()) + again = cross.CrossEngine(Path(self.dir.name), start=False) + self.assertAlmostEqual(again.usual["XYZ|Gate|Binance"], self.e.usual["XYZ|Gate|Binance"]) + self.assertEqual(again.seen_since["XYZ|Gate|Binance"], 1000.0) + + def test_settings_saved(self): + self.assertEqual(self.e.set_settings({"min_net_pct": "0.7", "use_mexc": False}), "") + again = cross.CrossEngine(Path(self.dir.name), start=False) + self.assertEqual((again.settings.min_net_pct, again.settings.use_mexc), (0.7, False)) + + def test_entry_decided_by_net_profit(self): + t = 1000.0 + for i in range(400): + self.feed(t + i * 3, 1.0, 1.01) # usual ≈ 1.1 % + t += 400 * 3 + self.e.settings.running = False + self.feed(t, 1.0, 1.0155) # +0.45 % over usual: net ≈ 0.45 − 0.05 − 0.3 + row = self.e.view()["rows"][0] + fees = cross.round_trip_fee_pct("Gate", "Binance") + self.assertAlmostEqual(row["net_pct"], row["excess"] - 0.05 - fees, places=9) + self.assertLess(row["net_pct"], 0.2) + self.assertFalse(row["fits"]) + self.assertEqual(row["why"], "чистая прибыль ниже порога") + self.e.settings.min_net_pct = 0.05 # the same link above a lower threshold + self.e.settings.running = True + self.e.settings.exit_hold_s = 0.0 + self.e.step(t) + self.assertEqual(len(self.e.positions), 1) + + def test_best_net_link_wins(self): + # the same coin on two perp exchanges: the link with the higher net profit is taken + t = 1000.0 + for i in range(400): + spots = [q("Gate", "XYZ", 0.999, 1.0)] + futs = [q("Binance", "XYZ", 1.01, 1.011), q("Bybit", "XYZ", 1.01, 1.011)] + self.e.links = cross.build_links(spots, futs, set(arb.EXCHANGES)) + self.e.learn(t + i * 3) + t += 1200 + spots = [q("Gate", "XYZ", 0.999, 1.0)] + futs = [q("Binance", "XYZ", 1.02, 1.021), q("Bybit", "XYZ", 1.03, 1.031)] + self.e.links = cross.build_links(spots, futs, set(arb.EXCHANGES)) + self.e.step(t) + self.assertEqual(self.e.positions[0].fut_ex, "Bybit") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cross_limits.py b/tests/test_cross_limits.py new file mode 100644 index 0000000..f3c1f22 --- /dev/null +++ b/tests/test_cross_limits.py @@ -0,0 +1,86 @@ +"""«Between exchanges»: the limit of open trades is per exchange. A trade counts on both of its exchanges (spot on +A, short on B); a new one waits while either of its exchanges is full, and the next-best link with free exchanges +is taken instead.""" + +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import cross # noqa: E402 + + +def link(base, spot_ex, fut_ex, fut_bid=1.02): + return cross.Link(base, spot_ex, fut_ex, f"{base}USDT", f"{base}USDT", 0.999, 1.0, fut_bid, fut_bid + 0.001, + 1e5, 1e5, 1e7, 1e7, 0.0001, 8.0) + + +class CrossLimitTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.e = cross.CrossEngine(Path(self.dir.name), start=False) + self.e.settings.running, self.e.settings.history_min = True, 0.0 + self.e.settings.exit_hold_s = 0.0 + + def tearDown(self): + self.dir.cleanup() + + def feed(self, *links): + self.e.links = {l.key: l for l in links} + self.e.usual = {l.key: 0.5 for l in links} + self.e.seen_since = {l.key: 0.0 for l in links} + + def test_trade_counts_on_both_exchanges(self): + self.e.limits.update(HTX=2) + self.feed(link("A1", "HTX", "MEXC"), link("A2", "HTX", "Gate"), link("A3", "HTX", "Bybit"), + link("B1", "Gate", "Bybit")) + self.e.step(1000.0) + held = sorted(p.base for p in self.e.positions) + self.assertEqual(len([b for b in held if b.startswith("A")]), 2) # HTX full after two + self.assertIn("B1", held) # other exchanges still trade + self.assertEqual(len(self.e.open_on("HTX")), 2) + row = {r["base"]: r for r in self.e.view()["rows"]} + waiting = next(r for b, r in row.items() if b.startswith("A") and b not in held) + self.assertIn("на HTX открыто сделок 2 из 2", waiting["why"]) + bal = {r["exchange"]: r for r in self.e.view()["balances"]["rows"]} + self.assertEqual((bal["HTX"]["open_count"], bal["HTX"]["limit"]), (2, 2)) + + def test_next_best_link_when_exchange_full(self): + self.e.limits.update(MEXC=0) # MEXC: no new trades + self.feed(link("XYZ", "Gate", "MEXC", fut_bid=1.03), link("XYZ", "Gate", "Binance", fut_bid=1.02)) + self.e.step(1000.0) + self.assertEqual([(p.base, p.fut_ex) for p in self.e.positions], [("XYZ", "Binance")]) + + def test_limits_saved_and_old_single_limit_carried_over(self): + self.assertEqual(self.e.set_settings({"limits": {"Gate": "1", "MEXC": 4}}), "") + again = cross.CrossEngine(Path(self.dir.name), start=False) + self.assertEqual((again.limits["Gate"], again.limits["MEXC"], again.limits["HTX"]), (1, 4, cross.DEFAULT_LIMIT)) + self.assertIn("от 0 до 100", self.e.set_settings({"limits": {"Gate": "-1"}})) + # a settings file of the older version: one «max_positions» for everything → every exchange gets it + f = Path(self.dir.name) / "basis_cross.json" + d = json.loads(f.read_text("utf-8")) + d.pop("limits") + d["settings"]["max_positions"] = 7 + f.write_text(json.dumps(d), "utf-8") + old = cross.CrossEngine(Path(self.dir.name), start=False) + self.assertEqual(set(old.limits.values()), {7}) + + def test_real_mode_counts_real_trades_only(self): + self.e.limits.update(Gate=1) + self.feed(link("P", "Gate", "Bybit")) + self.e.step(1000.0) # a paper trade on Gate + self.assertEqual(len(self.e.open_on("Gate")), 1) + self.e.settings.real = True + self.assertEqual(self.e.open_on("Gate"), []) # real mode: only real trades count + self.e.pending["Q"] = {"key": "Q|Gate|MEXC"} # a real entry in progress counts + self.assertEqual(self.e.open_on("Gate"), ["Q"]) + self.assertIn("на Gate открыто сделок 1 из 1", self.e.full(link("Z", "Gate", "HTX"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cross_real.py b/tests/test_cross_real.py new file mode 100644 index 0000000..b8b3915 --- /dev/null +++ b/tests/test_cross_real.py @@ -0,0 +1,523 @@ +"""Real trades between exchanges: short on B first, then spot on A; the close buys B back and sells A; the fee rates +follow what the exchanges charged; balances and their change since the start. No request reaches an exchange.""" + +from __future__ import annotations + +import json +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import cross # noqa: E402 +import live # noqa: E402 +import real_mirror # noqa: E402 +from test_real import FakeClient # noqa: E402 + +KEY = "XYZ|Gate|Binance" + + +def link(spot_bid=0.999, spot_ask=1.0, fut_bid=1.02, fut_ask=1.021): + return cross.Link("XYZ", "Gate", "Binance", "XYZUSDT", "XYZUSDT", spot_bid, spot_ask, fut_bid, fut_ask, + 1e5, 1e5, 1e7, 1e7, 0.0001, 8.0) + + +class CrossRealTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.journal = mock.patch.object(real_mirror, "JOURNAL", Path(self.dir.name) / "j.jsonl") + self.journal.start() + self.e = cross.CrossEngine(Path(self.dir.name), start=False, real=True) # the «real trading» tab + self.a, self.b = FakeClient(price=1.0), FakeClient(price=1.02) # A: spot (Gate), B: perp (Binance) + self.e.client_for = lambda ex: {"Gate": self.a, "Binance": self.b}[ex] + self.e.balances = {"gate": {"values": {"Спот USDT": 100.0, "Фьючерсы USDT": 0.0}, "time": 1.0}, + "binance": {"values": {"Спот USDT": 0.0, "Фьючерсы USDT": 100.0}, "time": 1.0}} + s = self.e.settings + s.running = s.real = True + s.entry_limit = s.entry_ioc = False + s.amount, s.history_min = 100.0, 0.0 + s.exit_hold_s = 0.0 # these tests close at once + self.e.links = {KEY: link()} + self.e.usual = {KEY: 0.5} + self.e.seen_since = {KEY: 0.0} + + def tearDown(self): + self.journal.stop() + self.dir.cleanup() + + def run_jobs(self): + while not self.e.jobs.empty(): + self.e.do_job(self.e.jobs.get()) + + def test_short_on_b_then_spot_on_a_and_close(self): + self.e.fees["Gate"]["spot"], self.e.fees["Binance"]["fut"] = 0.2, 0.08 # typed in, a bit off + self.e.step(1000.0) + self.assertEqual(self.e.opening, {"XYZ"}) + self.e.step(1000.5) # no second entry while opening + self.assertEqual(self.e.jobs.qsize(), 1) + self.run_jobs() + pos = self.e.positions[0] + self.assertTrue(pos.real) + self.assertEqual((pos.spot_ex, pos.fut_ex), ("Gate", "Binance")) + self.assertEqual(pos.qty, 99.0) # B's lot + self.assertEqual(self.b.position, -99.0) + self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell")]) + self.assertEqual([o[:2] for o in self.a.orders], [("spot", "buy")]) + self.assertAlmostEqual(pos.usual, 0.5) + self.assertEqual(self.e.opening, set()) + self.assertEqual(self.e.pending, {}) + # back to the usual gap → B bought back first, then A sold + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) + self.e.step(1010.0) + self.e.step(1010.5) + self.assertEqual(self.e.jobs.qsize(), 1) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual(self.b.position, 0.0) + self.assertEqual([o[:3] for o in self.b.orders[1:]], [("fut", "buy", 99.0)]) + self.assertEqual([o[:2] for o in self.a.orders[1:]], [("spot", "sell")]) + t = self.e.trades[0] + self.assertTrue(t.real) + self.assertIn("реально", t.reason) + self.assertAlmostEqual(t.net, t.spot_pnl + t.fut_pnl - t.fees + t.funding) + # the rates the exchanges charged (fake: spot 0.1 %, perp 0.05 %) are the table's rates now + self.assertAlmostEqual(self.e.fees["Gate"]["spot"], 0.1, places=4) + self.assertAlmostEqual(self.e.fees["Binance"]["fut"], 0.05, places=4) + self.assertIn("по сделке XYZ", self.e.fees["Gate"]["spot_src"]) + self.assertEqual(self.e.fees["MEXC"]["spot_src"], "") # not traded: untouched + row = self.e.view()["rows"][0] + self.assertAlmostEqual(row["fees_pct"], 2 * (0.1 + 0.05), places=4) + + def test_fees_not_learned_when_off(self): + self.e.settings.fees_auto = False + self.e.fees["Gate"]["spot"] = 0.2 + self.e.step(1000.0) + self.run_jobs() + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) + self.e.step(1010.0) + self.run_jobs() + self.assertEqual(self.e.fees["Gate"]["spot"], 0.2) + + def test_no_keys_no_entry(self): + del self.e.balances["binance"] + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) + self.assertIn("нет API-ключей Binance", self.e.view()["rows"][0]["why"]) + + def test_spot_buy_fails_short_bought_back(self): + def refuse(base, usdt): + raise live.LiveError("отказ биржи") + self.a.spot_buy = refuse + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell"), ("fut", "buy")]) + self.assertEqual(self.b.position, 0.0) + self.e.step(1001.0) # pause before the coin again + self.assertTrue(self.e.jobs.empty()) + + def test_limit_short_not_filled_nothing_bought(self): + self.e.settings.entry_limit, self.e.settings.limit_hold_s = True, 0.0 + self.b.limit_fill = 0.0 + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual(self.a.orders, []) + self.assertIn(("fut_cancel", "L1"), self.b.orders) + + def test_different_instruments_never_ordered(self): + self.e.links[KEY] = link(spot_bid=0.339, spot_ask=0.3393, fut_bid=104.84, fut_ask=104.9) + self.e.usual[KEY] = 0.0 + self.e.settings.max_gap_pct = 1e6 + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) + # even a request that slipped through stops before the exchange + self.e.opening.add("XYZ") + self.e.do_job(("open", self.e.links[KEY], 0.0, 100.0)) + self.assertEqual(self.a.orders + self.b.orders, []) + + def test_close_retried_until_spot_sold(self): + self.e.step(1000.0) + self.run_jobs() + self.a.fail_spot_sell = True + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) + self.e.step(1010.0) + self.run_jobs() + pos = self.e.positions[0] + self.assertEqual(pos.closing, "fut_done") # B already bought back + self.assertIn("продажа спота", pos.error) + self.e.step(1010.0 + 1) # before retry_at: nothing + self.assertTrue(self.e.jobs.empty()) + self.a.fail_spot_sell = False + pos.retry_at = 0.0 + self.e.step(1030.0) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell"), ("fut", "buy")]) # bought back once + + def test_restart_mid_entry_recovered(self): + # the program stopped after the short on B and the buy on A, before the position was written + self.e.pending["XYZ"] = {"time": 1.0, "key": KEY, "coins": 99.0, "usual": 0.5, "amount": 100.0} + self.e.save() + self.b.position = -99.0 + self.a.spot_balance = 99.2 + again = cross.CrossEngine(Path(self.dir.name), start=False, real=True) + again.client_for = self.e.client_for + again.balances = self.e.balances + again.links, again.usual, again.seen_since = self.e.links, self.e.usual, self.e.seen_since + again.step(1000.0) + self.assertEqual(again.opening, {"XYZ"}) + while not again.jobs.empty(): + again.do_job(again.jobs.get()) + pos = again.positions[0] + self.assertEqual((pos.qty, round(pos.spot_qty, 6)), (99.0, 99.2)) + self.assertFalse(pos.exact) + self.assertEqual(again.pending, {}) + + def test_balances_and_change_since_start(self): + self.e.settings.running = False + self.assertEqual(self.e.set_settings({"running": True}), "") + start = self.e.baseline["time"] + bal = self.e.view()["balances"] + self.assertIsNone(bal["start_total"]) # read before the start: not the reference + self.e.balances["gate"]["time"] = self.e.balances["binance"]["time"] = start + 1 + bal = self.e.view()["balances"] + self.assertAlmostEqual(bal["total"], 200.0) + self.assertAlmostEqual(bal["start_total"], 200.0) + self.e.balances["binance"] = {"values": {"Спот USDT": 0.0, "Фьючерсы USDT": 103.0}, "time": start + 20} + bal = self.e.view()["balances"] + self.assertAlmostEqual(bal["change_pct"], 1.5) + row = {r["exchange"]: r for r in bal["rows"]} + self.assertAlmostEqual(row["Binance"]["change_pct"], 3.0) + self.assertFalse(row["MEXC"]["keys"]) + self.assertIsNone(row["MEXC"]["total"]) + + def test_coins_of_open_position_count_in_balance(self): + self.e.step(1000.0) + self.run_jobs() + bal = {r["exchange"]: r for r in self.e.view()["balances"]["rows"]} + self.assertAlmostEqual(bal["Gate"]["coins"], self.e.positions[0].spot_qty * 0.999, places=6) + self.assertAlmostEqual(bal["Gate"]["total"], 100.0 + bal["Gate"]["coins"]) + + def money(self, ex, spot, fut, unified=False): + self.e.balances[ex.lower()]["free"] = {"spot": spot, "futures": fut} + self.e.balances[ex.lower()]["unified"] = unified + + def test_exchange_without_money_is_out_until_topped_up(self): + self.money("Gate", 120.0, 0.0) + self.money("Binance", 2.0, 1.0) # 3 $ for a 100 $ trade + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) + view = self.e.view() + self.assertEqual(view["rows"], []) # its links are not searched + row = {r["exchange"]: r for r in view["balances"]["rows"]} + self.assertIn("мало средств", row["Binance"]["low_funds"]) + self.assertEqual(row["Gate"]["low_funds"], "") + self.assertTrue(self.e.settings.use_binance) # the user's own switch is not touched + self.money("Binance", 0.0, 150.0) # money arrived + self.e.step(1001.0) + self.assertEqual(self.e.jobs.qsize(), 1) + self.assertEqual(self.e.view()["balances"]["rows"][1]["low_funds"], "") + texts = [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] + self.assertTrue(any("Binance: мало средств" in t for t in texts)) + self.assertTrue(any("Binance: средств достаточно" in t for t in texts)) + + def test_money_for_each_leg_without_transfer(self): + self.e.settings.auto_transfer = False + self.money("Gate", 0.0, 150.0) # A has it on futures, the coin is bought on spot + self.money("Binance", 0.0, 150.0) + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) + self.assertIn("мало средств на споте Gate", self.e.view()["rows"][0]["why"]) + self.e.settings.auto_transfer = True # moved inside Gate: enough + self.e.step(1001.0) + self.assertEqual(self.e.jobs.qsize(), 1) + + def test_paper_mode_ignores_money(self): + self.e.settings.real = False + self.money("Gate", 0.0, 0.0) + self.money("Binance", 0.0, 0.0) + self.e.step(1000.0) + self.assertEqual(len(self.e.positions), 1) + self.assertEqual(self.e.view()["balances"]["rows"][1]["low_funds"], "") + + # --- the signal is checked on fresh prices; no close at a loss «at the usual gap» --------------------------- + def test_stale_signal_not_entered(self): + # the cycle's list says +2 % (usual 0.5); right before the orders the market is at −0.9 % (the DNA case) + self.e.quote_now = lambda l, usd: (0.2229, 0.223, 0.221, 0.2211, 0.04, 0.05) + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.a.orders + self.b.orders, []) + texts = [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] + self.assertTrue(any("по стакану разница -0.897%" in t and "ордеров не было" in t for t in texts)) + self.e.step(1001.0) # the coin's pause: not tried again at once + self.assertTrue(self.e.jobs.empty()) + + # --- confirmation on the order books, the spread filter, the IOC first leg --------------------------------- + def journal_texts(self): + return [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] + + def test_signal_must_hold_on_both_book_checks(self): + self.e.settings.confirm_ms = 0 + answers = iter([(0.999, 1.0, 1.021, 1.022, 0.1, 0.1), (0.999, 1.0, 1.003, 1.004, 0.1, 0.1)]) + self.e.quote_now = lambda l, usd: next(answers) # good, then gone 0.4 s later + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.a.orders + self.b.orders, []) + self.assertTrue(any("проверка 2 из 2" in t and "ордеров не было" in t for t in self.journal_texts())) + + def test_thin_book_or_wide_spread_at_the_check(self): + self.e.settings.confirm_ms = 0 + + def thin(l, usd): + raise cross.ThinBook("на фьючерсе Binance в стакане меньше 100 $") + self.e.quote_now = thin + self.e.step(1000.0) + self.run_jobs() + self.e.step(1001.0) + self.assertTrue(self.e.jobs.empty()) # waits after the failed check + self.assertIn("реально нельзя: по стакану", self.e.view()["rows"][0]["why"]) + self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.9, 0.1) # spot spread 0.9 % > 0.5 + self.e.real_block.clear() + self.e.last_close.clear() + self.e.step(1002.0) + self.run_jobs() + self.assertEqual(self.a.orders + self.b.orders, []) + texts = self.journal_texts() + self.assertTrue(any("в стакане меньше 100 $" in t for t in texts)) + self.assertTrue(any("широкий спред: Gate 0.90%" in t for t in texts)) + + def test_wide_spread_link_not_searched(self): + self.e.links[KEY] = link(spot_bid=0.98, spot_ask=1.0, fut_bid=1.02, fut_ask=1.021) # spot spread 2 % + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) + self.assertIn("широкий спред: Gate 2.04%", self.e.view()["rows"][0]["why"]) + + def test_ioc_first_leg_at_the_confirmed_price(self): + self.e.settings.entry_ioc, self.e.settings.confirm_ms = True, 0 + self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.1, 0.1) + self.b.limit_fill = 0.0 # the price has gone: nothing fills + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.a.orders, []) # nothing bought on A + self.assertEqual([o[0] for o in self.b.orders], ["fut_limit", "fut_cancel"]) # placed, cancelled at once + self.assertEqual(self.b.limits["L1"]["price"], 1.021) # at the confirmed average sale price + self.assertTrue(any("IOC-шорт на Binance по 1.021 не исполнился" in t for t in self.journal_texts())) + self.b.limit_fill = 1.0 # next time it fills: the hedge follows + self.e.last_close.clear() + self.e.step(1010.0) + self.run_jobs() + self.assertEqual(len(self.e.positions), 1) + self.assertEqual([o[:2] for o in self.a.orders], [("spot", "buy")]) + + def test_back_to_usual_must_hold_before_the_close(self): + self.e.settings.exit_hold_s = 3.0 + self.e.step(1000.0) + self.run_jobs() + pos = self.e.positions[0] + closes = lambda: [j for j in list(self.e.jobs.queue) if j[0] == "close"] + at_usual = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) + away = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.019, fut_ask=1.02) + # a spike: at the usual gap for 1.5 s, then away again — not closed, the count starts anew + self.e.links[KEY] = at_usual + self.e.step(1010.0) + self.e.step(1011.5) + self.assertEqual(closes(), []) + self.assertIn("exit_held", self.e.view()["positions"][0]) # the page shows the count + self.e.links[KEY] = away + self.e.step(1012.0) + self.assertEqual(pos.exit_since, 0.0) + # back again and held 3 s without a break → closed, with how long it held + self.e.links[KEY] = at_usual + self.e.step(1020.0) + self.e.step(1022.9) + self.assertEqual(closes(), []) + self.e.step(1023.0) + self.assertEqual(len(closes()), 1) + self.assertIn("держалась 3.0 с", closes()[0][2]) + + def test_exit_follows_a_usual_gap_that_moved_up(self): + # entered at +2 % over a usual of +0.5 %; since then the usual itself has risen to +1.8 % (the overnight + # case: POD, NXPC… targets −6 % while the market sat at −1 %): closed when the gap is back to +1.8 % + self.e.step(1000.0) + self.run_jobs() + pos = self.e.positions[0] + closes = lambda: [j for j in list(self.e.jobs.queue) if j[0] == "close"] + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.0189, fut_ask=1.019) # gap 1.9 % + self.e.step(1010.0) + self.assertEqual(closes(), []) # the entry's usual (0.5): not yet + self.e.usual[KEY] = 1.88 # the usual has moved up (+0.05 margin) + self.e.step(1011.0) + self.assertEqual(len(closes()), 1) + self.assertIn("сместилась: при входе +0.50%, сейчас +1.88%", closes()[0][2]) + view = self.e.view()["positions"][0] + self.assertAlmostEqual(view["exit_level"], 1.88) + + def test_exit_not_harder_when_the_usual_moved_down(self): + self.e.step(1000.0) + self.run_jobs() + self.e.usual[KEY] = -3.0 # dropped: the entry's 0.5 % stays the target + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.0049, fut_ask=1.005) # gap 0.5 % + self.e.step(1010.0) + self.assertEqual(len([j for j in list(self.e.jobs.queue) if j[0] == "close"]), 1) + + def test_stop_is_not_delayed(self): + self.e.settings.exit_hold_s, self.e.settings.stop_widen_pct = 30.0, 1.0 + self.e.step(1000.0) + self.run_jobs() + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.034, fut_ask=1.035) # +3.5 %: stop + self.e.step(1010.0) + self.assertEqual([j[2] for j in list(self.e.jobs.queue) if j[0] == "close"], ["стоп: разница расширилась"]) + + def test_symbol_closed_to_api_blocked_for_a_day(self): + # PTB on 2026-10-22: MEXC refused the spot buy 7 times, the short was opened and closed each time (fees) + def refuse(base, usdt): + raise live.LiveError('HTTP 400: {"code":10007,"msg":"symbol not support api"}') + self.a.spot_buy = refuse + self.e.step(1000.0) + self.run_jobs() + self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell"), ("fut", "buy")]) # once, closed back + self.e.last_close.clear() + self.e.step(cross.time.time()) + self.assertTrue(self.e.jobs.empty()) # not tried again + self.assertIn("не даёт торговать XYZ через API", self.e.real_block["XYZ"][0]) + + def test_negative_gap_beyond_limit_not_traded(self): + self.e.links[KEY] = link(spot_bid=0.0343, spot_ask=0.0344, fut_bid=0.0227, fut_ask=0.02272) # −34 % (SIREN) + self.e.usual[KEY] = -36.0 + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) + self.assertIn("больше ±20%", self.e.view()["rows"][0]["why"]) + + def test_decision_prices_kept_and_compared_with_fills(self): + self.e.settings.confirm_ms = 0 + self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.1, 0.1) + self.e.step(1000.0) + self.run_jobs() + pos = self.e.positions[0] + self.assertEqual(pos.entry_signal[1:3], [1.0, 1.021]) # A ask, B bid confirmed for the entry + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) + self.b.price = 1.0101 # the buy-back fills worse than decided + self.e.step(1010.0) + self.assertEqual(pos.exit_signal[1:3], [1.0, 1.005]) # A bid, B ask of the close decision + self.run_jobs() + t = self.e.trades[0] + self.assertEqual((t.entry_signal[1], t.exit_signal[2]), (1.0, 1.005)) + text = next(x for x in self.journal_texts() if "выкуплен" in x) + self.assertIn("вход: решение при разнице +2.100%", text) + self.assertIn("выкуп B 1.005 → 1.0101 (-0.51%)", text) + + def test_fresh_prices_used_when_still_good(self): + self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.1, 0.1) + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(len(self.e.positions), 1) + self.assertEqual(self.e.links[KEY].fut_bid, 1.021) + + def test_closed_at_usual_gap_even_at_a_loss(self): + # the exit rule is the gap, not the result: an entry worse than the signal is closed at the usual gap too + self.e.step(1000.0) + self.run_jobs() + pos = self.e.positions[0] + pos.usual = 2.5 + self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.0249, fut_ask=1.025) # gap 2.5 = usual + self.e.step(1010.0) + self.assertEqual([j[0] for j in list(self.e.jobs.queue) if j[0] == "close"], ["close"]) + + def test_non_latin_ticker_not_traded(self): + q = lambda ex, base: cross.arb.Quote(ex, f"{base}USDT", base, 1.0, 1.0, 1.001, 1e4, 1e4, 0.0001, 8.0, 1e6) + links = cross.build_links([q("Gate", "龙虾"), q("Gate", "XYZ")], [q("Binance", "龙虾"), q("Binance", "XYZ")], + set(cross.arb.EXCHANGES)) + self.assertEqual({l.base for l in links.values()}, {"XYZ"}) + + def test_gate_fee_read_from_fills(self): + g = live.Gate("k", "s") + g._call = lambda m, path, params=None, body=None: [ + {"order_id": "7", "fee": "0.003315"}, {"order_id": "7", "fee": "0.0000252"}, {"order_id": "8", "fee": "1"}] + fee, exact = g._order_fee("DNA_USDT", "7") + self.assertTrue(exact) + self.assertAlmostEqual(fee, 0.0033402) + + # --- liquidation of the short on B ------------------------------------------------------------------------- + def test_liquidation_formula(self): + self.assertAlmostEqual(cross.liq_distance(100.0, 100.0), 0.99 / 1.01 * 100) # 1× money: ≈ +98 % + self.assertAlmostEqual(cross.equity_for(50.0, 100.0), 51.5) + self.assertAlmostEqual(cross.liq_distance(cross.equity_for(50.0, 100.0), 100.0), 50.0) + + def test_short_refused_when_liquidation_too_close(self): + self.e.settings.auto_transfer = False + self.b.usdt = {"spot": 0.0, "futures": 30.0} # 30 $ behind a ≈101 $ short: ≈ +28 % + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual(self.a.orders + self.b.orders, []) # nothing sent + why = self.e.real_block["XYZ"][0] + self.assertIn("ликвидация шорта на Binance была бы всего на 28%", why) + self.assertIn("нужно 52.0", why) + + def test_transfer_covers_liquidation_margin_and_estimate_kept(self): + self.b.usdt = {"spot": 200.0, "futures": 30.0} + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.b.orders[0][:2], ("transfer", "futures")) # moved inside Binance first + pos = self.e.positions[0] + self.assertEqual(pos.liq_src, "расчёт") # the fake reports no liquidation price + to_liq = (pos.liq_calc / pos.fut_entry - 1) * 100 + self.assertGreater(to_liq, 95) + self.assertAlmostEqual(self.e.view()["positions"][0]["liq_pct"], (pos.liq_price / 1.021 - 1) * 100) + + def test_exchange_liquidation_price_replaces_estimate(self): + self.b.fut_liq_price = lambda symbol: 1.9 + self.e.step(1000.0) + self.run_jobs() + pos = self.e.positions[0] + self.assertEqual((pos.liq_price, pos.liq_src), (1.9, "биржа")) + self.assertGreater(pos.liq_calc, 1.9) # the estimate kept for the comparison + texts = [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] + self.assertTrue(any("ликвидация шорта на Binance: биржа 1.9" in t for t in texts)) + # read again every 30 s (cross margin: it moves with the whole account) + self.b.fut_liq_price = lambda symbol: 1.8 + self.e.step(time.time() + 31) + self.run_jobs() + self.assertEqual(pos.liq_price, 1.8) + + def test_both_legs_closed_near_liquidation(self): + self.e.step(1000.0) + self.run_jobs() + pos = self.e.positions[0] + pos.liq_price = 1.15 # the account has shrunk: liquidation close + self.e.links[KEY] = link(spot_bid=1.05, spot_ask=1.051, fut_bid=1.0715, fut_ask=1.0716) # gap as at entry + self.e.step(1010.0) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertIn("до ликвидации шорта 7.3% < 20%", self.e.trades[0].reason) + self.assertEqual([o[:2] for o in self.b.orders[1:]], [("fut", "buy")]) + self.assertEqual([o[:2] for o in self.a.orders[1:]], [("spot", "sell")]) + + def test_paper_position_has_estimated_liquidation(self): + self.e.settings.real = False + self.e.step(1000.0) + pos = self.e.positions[0] + self.assertAlmostEqual(pos.liq_price, 1.02 * (1 + cross.liq_distance(1.03, 1.0) / 100)) + self.assertEqual(pos.liq_src, "расчёт") + + def test_fees_typed_and_exchange_switched_off(self): + msg = self.e.set_settings({"fees": {"Gate": {"spot": "0.08", "fut": "0.04"}}, "use_binance": False}) + self.assertEqual(msg, "") + self.assertEqual((self.e.fees["Gate"]["spot"], self.e.fees["Gate"]["fut"]), (0.08, 0.04)) + self.assertEqual(self.e.fees["Gate"]["spot_src"], "вручную") + self.e.step(1000.0) # Binance off: neither searched nor traded + self.assertTrue(self.e.jobs.empty()) + self.assertEqual(self.e.view()["rows"], []) + again = cross.CrossEngine(Path(self.dir.name), start=False, real=True) # kept over a restart + self.assertEqual(again.fees["Gate"]["spot"], 0.08) + self.assertIn("от 0 до", self.e.set_settings({"fees": {"Gate": {"spot": "5"}}})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_htx_v5.py b/tests/test_htx_v5.py new file mode 100644 index 0000000..163138d --- /dev/null +++ b/tests/test_htx_v5.py @@ -0,0 +1,120 @@ +"""HTX in the Multi-Assets Collateral mode: v1 answers 6023, so orders, positions and the account go through V5. +No request reaches the exchange: the signed call is replaced by a fake.""" + +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import live # noqa: E402 + + +class FakeHtx(live.Htx): + def __init__(self, mode=2): + super().__init__("k", "s") + self.mode, self.calls = mode, [] + self.rules["fut:DOGE-USDT"] = {"size": 100.0} + + def _call(self, method, host, path, params=None, body=None): + self.calls.append((method, path, params, body)) + if path == "/v5/account/asset_mode": + return {"asset_mode": self.mode} + if path == "/v5/trade/order" and method == "POST": + return {"order_id": "77", "client_order_id": "77"} + if path == "/v5/trade/order": + return {"order_id": "77", "state": "filled", "trade_volume": "3", "trade_avg_price": "0.2", "fee": "-0.03"} + if path == "/v5/trade/cancel_order": + return {"order_id": body["order_id"]} + if path == "/v5/trade/position/opens": + return [{"contract_code": "DOGE-USDT", "position_side": "both", "direction": "sell", "volume": "3"}] + if path == "/v5/account/balance": + return {"equity": "12.5", "available_margin": "10.25", "details": []} + if path == "/linear-swap-api/v1/swap_cross_order": + return {"order_id_str": "v1"} + if path.startswith("/v1/account/accounts"): + return {"list": [{"currency": "usdt", "type": "trade", "balance": "4"}]} if "balance" in path \ + else [{"type": "spot", "id": 1}] + raise AssertionError(path) + + +class HtxV5Tests(unittest.TestCase): + def test_market_short_through_v5(self): + c = FakeHtx() + fill = c.fut_order("DOGE-USDT", "sell", 350, reduce_only=False) + method, path, _, body = c.calls[1] + self.assertEqual((method, path), ("POST", "/v5/trade/order")) + self.assertEqual(body, {"contract_code": "DOGE-USDT", "margin_mode": "cross", "side": "sell", "volume": 3, + "type": "market"}) + self.assertEqual((fill.coins, fill.price, fill.fee_usd, fill.order_id), (300.0, 0.2, 0.03, "77")) + self.assertFalse(any("/linear-swap-api/" in p for _, p, _, _ in c.calls)) + + def test_reduce_only_limit_status_cancel_position(self): + c = FakeHtx() + self.assertEqual(c.fut_limit("DOGE-USDT", "buy", 300, 0.19, reduce_only=True), "77") + body = c.calls[1][3] + self.assertEqual((body["type"], body["price"], body["reduce_only"], body["time_in_force"]), ("limit", 0.19, 1, "gtc")) + st = c.fut_order_status("DOGE-USDT", "77") + self.assertEqual((st["coins"], st["final"]), (300.0, True)) + c.fut_cancel("DOGE-USDT", "77") + self.assertEqual(c.calls[-1][1], "/v5/trade/cancel_order") + self.assertEqual(c.fut_position("DOGE-USDT"), -300.0) # one-way: the side from direction + + def test_account_through_v5(self): + c = FakeHtx() + self.assertEqual(c.balances(), {"Спот USDT": 4.0, "Фьючерсы USDT": 12.5}) + self.assertEqual(c.usdt_free(), {"spot": 4.0, "futures": 10.25}) + + def test_liquidation_price_from_position(self): + c = FakeHtx() + orig = c._call + + def call(method, host, path, params=None, body=None): + if path == "/v5/trade/position/opens": + return [{"contract_code": "DOGE-USDT", "volume": "3", "direction": "sell", "liquidation_price": "0.41"}] + return orig(method, host, path, params, body) + c._call = call + self.assertEqual(c.fut_liq_price("DOGE-USDT"), 0.41) + self.assertIsNone(live._liq([{"volume": "0", "liquidation_price": "1"}], "liquidation_price", 1.0, + lambda r: float(r["volume"]))) # no position + self.assertIsNone(live._liq([{"size": "5", "liqPrice": ""}], "liqPrice", 1.0, + lambda r: float(r["size"]))) # not reported + self.assertEqual(live._liq([{"size": "5", "liqPrice": "2000"}], "liqPrice", 1000.0, + lambda r: float(r["size"])), 2.0) # 1000PEPE: per coin + + def test_market_sale_refused_by_circuit_breaker_goes_as_ioc_limit(self): + # AEVO on HTX, 2026-10-22: bid 0.0222 / ask 0.0257 — every sell-market cancelled (410), the close stuck + from unittest import mock + c = live.Htx("k", "s") + c.account_id = "1" + c.rules["spot:AEVO"] = {"step": 0.0001, "tick": 0.0001} + placed = [] + + def call(method, host, path, params=None, body=None): + if path == "/v1/order/orders/place": + placed.append(body) + return str(len(placed)) + o = placed[int(path.rsplit("/", 1)[1]) - 1] + if o["type"] == "sell-market": + return {"state": "canceled", "field-amount": "0", "canceled-source": None} # as the detail answers + return {"state": "filled", "field-amount": o["amount"], "field-cash-amount": str(float(o["amount"]) * 0.0222), + "field-fees": "0.0171"} + c._call = call + book = ([(0.0222, 1335.0), (0.0221, 3044.0)], [(0.0257, 3891.0)]) + with mock.patch("fastquote.book", lambda ex, market, symbol: book): + fill = c.spot_sell("AEVO", 383.0621) + self.assertEqual([p["type"] for p in placed], ["sell-market", "sell-ioc"]) + self.assertEqual((placed[1]["amount"], placed[1]["price"]), ("383.0621", "0.0222")) + self.assertAlmostEqual(fill.price, 0.0222) + self.assertEqual(fill.coins, 383.0621) + + def test_single_asset_mode_keeps_v1(self): + c = FakeHtx(mode=1) + self.assertEqual(c.fut_limit("DOGE-USDT", "sell", 300, 0.21), "v1") + self.assertEqual(c.calls[-1][1], "/linear-swap-api/v1/swap_cross_order") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_innovation_fee.py b/tests/test_innovation_fee.py new file mode 100644 index 0000000..8e4be3a --- /dev/null +++ b/tests/test_innovation_fee.py @@ -0,0 +1,131 @@ +"""Bybit's Innovation Zone perps have their own taker rate (0.11 % for a regular user, bybit.com/fee): the Bybit tab +and «between exchanges» count those coins with it; other exchanges' «new» labels are no fee group.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import basis # noqa: E402 +import cross # noqa: E402 +import real_mirror # noqa: E402 +from test_basis import pair # noqa: E402 +from test_real import FakeClient # noqa: E402 + + +class BasisInnovationFeeTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.dir.cleanup() + + def test_bybit_innovation_coin_pays_its_rate(self): + e = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + self.assertEqual((e.settings.fut_fee, e.settings.fut_fee_innovation), (0.055, 0.11)) + e.settings.running, e.settings.all_coins = True, True + e.pairs = {"INNO": pair("INNO", innovation=True), "STD": pair("STD", fut=(1.0105, 1.0115))} + rows = {r["base"]: r for r in e.view()["rows"]} + self.assertEqual(rows["INNO"]["fut_fee_pct"], 0.11) + self.assertEqual(rows["STD"]["fut_fee_pct"], 0.055) + self.assertAlmostEqual(rows["INNO"]["net_if_closed_pct"], + rows["INNO"]["entry_gap"] - e.settings.exit_gap_pct - 2 * (0.1 + 0.11)) + e.step(1000.0) + pos = {p.base: p for p in e.positions} + self.assertTrue(pos["INNO"].innovation) + self.assertFalse(pos["STD"].innovation) + inno = pos["INNO"] + self.assertAlmostEqual(inno.fees, inno.qty * 1.001 * 0.1 / 100 + inno.qty * 1.010 * 0.11 / 100) + _, _, fees, _ = basis.close_result(inno, 1.0, 1.011, e.settings) + self.assertAlmostEqual(fees, inno.fees + inno.qty * 1.0 * 0.1 / 100 + inno.qty * 1.011 * 0.11 / 100) + + def test_other_exchange_new_label_is_no_fee_group(self): + e = basis.BasisEngine("mexc", Path(self.dir.name), start=False) + self.assertEqual(e.settings.fut_fee_innovation, 0.0) + e.settings.all_coins = True + e.pairs = {"NEW": pair("NEW", innovation=True)} + self.assertEqual(e.view()["rows"][0]["fut_fee_pct"], e.settings.fut_fee) + + def test_rate_saved_from_settings(self): + e = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + self.assertEqual(e.set_settings({"fut_fee_innovation": "0.09"}), "") + again = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + self.assertEqual(again.settings.fut_fee_innovation, 0.09) + + +KEY = "XYZ|Gate|Bybit" + + +def link(innovation=True): + return cross.Link("XYZ", "Gate", "Bybit", "XYZUSDT", "XYZUSDT", 0.999, 1.0, 1.02, 1.021, 1e5, 1e5, 1e7, 1e7, + 0.0001, 8.0, 1.0, innovation) + + +class CrossInnovationFeeTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.journal = mock.patch.object(real_mirror, "JOURNAL", Path(self.dir.name) / "j.jsonl") + self.journal.start() + self.e = cross.CrossEngine(Path(self.dir.name), start=False) + self.e.settings.running, self.e.settings.history_min = True, 0.0 + self.e.settings.exit_hold_s = 0.0 + self.e.links = {KEY: link()} + self.e.usual, self.e.seen_since = {KEY: 0.5}, {KEY: 0.0} + + def tearDown(self): + self.journal.stop() + self.dir.cleanup() + + def test_links_marked_from_bybit_list(self): + q = lambda ex, sym: cross.arb.Quote(ex, sym, "XYZ", 1.0, 1.0, 1.001, 1e4, 1e4, 0.0001, 8.0, 1e6) + links = cross.build_links([q("Gate", "XYZUSDT")], [q("Bybit", "XYZUSDT"), q("Binance", "XYZUSDT")], + set(cross.arb.EXCHANGES), {"Bybit|XYZUSDT"}) + self.assertTrue(links["XYZ|Gate|Bybit"].innovation) + self.assertFalse(links["XYZ|Gate|Binance"].innovation) + + def test_table_and_paper_trade_use_the_innovation_rate(self): + self.assertEqual(self.e.fees["Bybit"]["fut_innovation"], 0.11) + row = self.e.view()["rows"][0] + self.assertTrue(row["innovation"]) + self.assertAlmostEqual(row["fees_pct"], 2 * (0.1 + 0.11)) + self.e.links[KEY] = link(innovation=False) + self.assertAlmostEqual(self.e.view()["rows"][0]["fees_pct"], 2 * (0.1 + 0.055)) + self.e.links[KEY] = link() + self.e.step(1000.0) + pos = self.e.positions[0] + self.assertTrue(pos.innovation) + self.assertAlmostEqual(pos.fees, pos.qty * 1.0 * 0.1 / 100 + pos.qty * 1.02 * 0.11 / 100) + + def test_real_trade_learns_the_innovation_rate_only(self): + a, b = FakeClient(price=1.0), FakeClient(price=1.02) + self.e.client_for = lambda ex: {"Gate": a, "Bybit": b}[ex] + self.e.balances = {"gate": {"values": {}, "time": 1.0}, "bybit": {"values": {}, "time": 1.0}} + self.e.settings.real, self.e.settings.entry_limit, self.e.settings.entry_ioc = True, False, False + self.e.step(1000.0) + while not self.e.jobs.empty(): + self.e.do_job(self.e.jobs.get()) + self.e.links[KEY] = cross.Link("XYZ", "Gate", "Bybit", "XYZUSDT", "XYZUSDT", 1.0, 1.001, 1.004, 1.005, + 1e5, 1e5, 1e7, 1e7, 0.0001, 8.0, 1.0, True) + self.e.step(1010.0) + while not self.e.jobs.empty(): + self.e.do_job(self.e.jobs.get()) + self.assertEqual(self.e.positions, []) + self.assertAlmostEqual(self.e.fees["Bybit"]["fut_innovation"], 0.05, places=4) # what the fake charged + self.assertEqual(self.e.fees["Bybit"]["fut"], 0.055) # the standard rate kept + + def test_innovation_rate_typed_and_kept(self): + self.assertEqual(self.e.set_settings({"fees": {"Bybit": {"fut_innovation": "0.1"}}}), "") + again = cross.CrossEngine(Path(self.dir.name), start=False) + self.assertEqual((again.fees["Bybit"]["fut_innovation"], again.fees["Bybit"]["fut_innovation_src"]), + (0.1, "вручную")) + self.assertNotIn("fut_innovation", again.fees["Gate"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_keepalive.py b/tests/test_keepalive.py new file mode 100644 index 0000000..0ca4845 --- /dev/null +++ b/tests/test_keepalive.py @@ -0,0 +1,64 @@ +"""Persistent connections in live._http: requests to one host reuse a single TCP connection.""" + +from __future__ import annotations + +import json +import sys +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import live # noqa: E402 + + +class _Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" # keep-alive + connections: set = set() + + def log_message(self, *args): + pass + + def do_GET(self): + _Handler.connections.add(self.client_address) + body = json.dumps({"ok": True}).encode() + self.send_response(500 if self.path == "/fail" else 200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class KeepAliveTests(unittest.TestCase): + def setUp(self): + _Handler.connections = set() + self.server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.base = f"http://127.0.0.1:{self.server.server_address[1]}" + + def tearDown(self): + self.server.shutdown() + self.server.server_close() + + def test_connection_is_reused(self): + for _ in range(5): + self.assertEqual(live._http("GET", self.base + "/x"), {"ok": True}) + self.assertEqual(len(_Handler.connections), 1) # one TCP connection for five requests + + def test_idle_connection_is_replaced(self): + live._http("GET", self.base + "/x") + with mock.patch.object(live, "IDLE_S", -1): # everything counts as too old + live._http("GET", self.base + "/x") + self.assertEqual(len(_Handler.connections), 2) + + def test_http_error_keeps_message(self): + with self.assertRaises(live.LiveError) as err: + live._http("GET", self.base + "/fail") + self.assertIn("HTTP 500", str(err.exception)) + self.assertFalse(err.exception.sent) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_lead.py b/tests/test_lead.py new file mode 100644 index 0000000..591cf62 --- /dev/null +++ b/tests/test_lead.py @@ -0,0 +1,523 @@ +"""Lead-exchange mode: KuCoin (leader) moves first, paper trades are made on Bybit (follower).""" + +from __future__ import annotations + +import gzip +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import lead_window # noqa: E402 +import scalp_hint as sh # noqa: E402 +import scalp_paper as sp # noqa: E402 + +TICK = 0.00001 +T0 = 1_000.0 + + +def follower_book(mid: float, half_spread: float = 2 * TICK) -> sh.OrderBook: + book = sh.OrderBook() + book.apply_snapshot({"asks": [{"price": round(mid + half_spread, 5), "size": 500.0, "type": "Ask"}], + "bids": [{"price": round(mid - half_spread, 5), "size": 500.0, "type": "Bid"}]}) + return book + + +def trader(**overrides) -> sp.PaperTrader: + settings = sp.PaperSettings(mode="lead", stake=100.0, budget=1000.0, cooldown_seconds=0, lead_threshold_pct=0.05, + lead_window_ms=500, min_target_pct=0.1, stop_loss_pct=0.2, max_hold_seconds=30, + require_leader=False) + for k, v in overrides.items(): + setattr(settings, k, v) + return sp.PaperTrader(settings, sh.HintSettings(), state_path=None, trades_path=None) + + +def feed_quiet(tr: sp.PaperTrader, seconds: float = 1.0, lead_mid: float = 0.08, follow_mid: float = 0.08): + t = T0 + while t <= T0 + seconds: + tr.on_leader(t, lead_mid - 5 * TICK, lead_mid + 5 * TICK) + tr.on_book(t, follower_book(follow_mid), TICK) + t = round(t + 0.1, 3) + return t + + +class LeadPolicyTests(unittest.TestCase): + def test_leader_jump_opens_long_on_follower_and_take_profit_closes(self): + tr = trader() + t = feed_quiet(tr) + self.assertIsNone(tr.position) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) # KuCoin +0.1 %, Bybit still flat + pos = tr.position + self.assertIsNotNone(pos, tr.policy.status) + self.assertEqual(pos.side, "LONG") + self.assertAlmostEqual(pos.entry, 0.08002) # market buy at Bybit's best ask + self.assertGreater(pos.target, pos.entry) + self.assertLess(pos.stop, pos.entry) + tr.on_trade(sh.Trade(t + 1, pos.target + TICK, 50.0, "Buy")) + self.assertIsNone(tr.position) + self.assertEqual(tr.trades[-1].reason, "цель") + self.assertIn("KuCoin", tr.trades[-1].regime) + + def test_leader_drop_opens_short_and_stop_loss_closes(self): + tr = trader() + t = feed_quiet(tr) + tr.on_leader(t, 0.07992 - 5 * TICK, 0.07992 + 5 * TICK) + self.assertEqual(tr.position.side, "SHORT") + stop = tr.position.stop + tr.on_book(t + 0.5, follower_book(stop + 3 * TICK), TICK) # ask above the stop + self.assertIsNone(tr.position) + self.assertEqual(tr.trades[-1].reason, "стоп") + self.assertLess(tr.trades[-1].net_usd, 0) + + def test_time_exit(self): + tr = trader(max_hold_seconds=2) + t = feed_quiet(tr) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + tr.on_book(t + 3, follower_book(0.08), TICK) + self.assertEqual(tr.trades[-1].reason, "время") + + def test_no_entry_when_follower_moved_too_or_below_threshold(self): + tr = trader() + t = feed_quiet(tr) + tr.on_book(t, follower_book(0.08008), TICK) # Bybit moved first + tr.on_leader(t + 0.01, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + self.assertIsNone(tr.position) + tr2 = trader() + t = feed_quiet(tr2) + tr2.on_leader(t, 0.08002 - 5 * TICK, 0.08002 + 5 * TICK) # +0.025 % < 0.05 % + self.assertIsNone(tr2.position) + self.assertIn("ждём", tr2.policy.status) + + def test_stale_follower_blocks_entry(self): + tr = trader() + t = feed_quiet(tr) + tr.on_leader(t + 5, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) # Bybit silent for 5 s + self.assertIsNone(tr.position) + self.assertIn("устарели", tr.policy.status) + + def test_disabled_and_cooldown(self): + tr = trader(enabled=False) + t = feed_quiet(tr) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + self.assertIsNone(tr.position) + tr = trader(cooldown_ms=60000) + tr.last_close = T0 + 0.5 + t = feed_quiet(tr) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + self.assertIsNone(tr.position) + self.assertIn("пауза", tr.policy.status) + + def test_replay_reads_leader_rows(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "MARS.jsonl.gz" + with gzip.open(path, "wt", encoding="utf-8") as f: + f.write(json.dumps([0, "meta", {"ticker": "MARSCOINUSDT", "tick": TICK}]) + "\n") + t = T0 + while t <= T0 + 1: + f.write(json.dumps([t, "L", [0.08 - 5 * TICK, 0.08 + 5 * TICK]]) + "\n") + book = {"asks": [{"price": 0.08002, "size": 500.0, "type": "Ask"}], + "bids": [{"price": 0.07998, "size": 500.0, "type": "Bid"}]} + f.write(json.dumps([t, "S", book]) + "\n") + t = round(t + 0.1, 3) + f.write(json.dumps([t, "L", [0.08008 - 5 * TICK, 0.08008 + 5 * TICK]]) + "\n") + settings = sp.PaperSettings(mode="lead", stake=100.0, cooldown_seconds=0, require_leader=False) + tr = sp.replay([path], settings) + self.assertEqual(len(tr.trades), 1) # opened, closed at the end of the file + self.assertEqual(tr.trades[0].side, "LONG") + + def test_vector_follows_kucoin_direction_even_if_bybit_moved_too(self): + tr = trader(mode="vector", vector_window_seconds=3, vector_min_move_pct=0.05, min_target_pct=0.2) + self.assertIsInstance(tr.policy, sp.VectorPolicy) + t, mid = T0, 0.08 + while t <= T0 + 4: # both rise ~0.1 % over 4 s + tr.on_leader(t, mid - 5 * TICK, mid + 5 * TICK) + tr.on_book(t, follower_book(mid), TICK) + if tr.position: + break + mid = round(mid + TICK, 5) if int((t - T0) * 10) % 4 == 0 else mid + t = round(t + 0.1, 3) + pos = tr.position + self.assertIsNotNone(pos, tr.policy.status) + self.assertEqual(pos.side, "LONG") + self.assertGreaterEqual(pos.target, pos.entry * 1.002 - 1e-12) # at least +0.2 %, rounded up to a tick + self.assertLess(pos.target, pos.entry * 1.002 + TICK) + self.assertIn("растёт", pos.regime) + + def test_vector_short_and_no_direction(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05) + t = feed_quiet(tr, seconds=3) + self.assertIsNone(tr.position) + self.assertIn("направления нет", tr.policy.status) + tr.on_leader(t, 0.07992 - 5 * TICK, 0.07992 + 5 * TICK) # KuCoin −0.1 % + self.assertEqual(tr.position.side, "SHORT") + + def test_cut_loss_closes_at_once_and_takes_the_next_signal(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, cut_loss=True, + cut_loss_ticks=1, cooldown_ms=60000) + t = feed_quiet(tr, seconds=3) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) # KuCoin +0.1 % → LONG on Bybit + first = tr.position + self.assertEqual(first.side, "LONG") + tr.on_book(t + 0.1, follower_book(0.08), TICK) # spread only: mid unchanged, keep it + self.assertIs(tr.position, first) + tr.on_book(t + 0.2, follower_book(0.07999), TICK) # Bybit mid 1 step against us + self.assertEqual(tr.trades[-1].reason, "минус — закрыта сразу") + self.assertIsNotNone(tr.position) # KuCoin still up: re-entered, no pause + self.assertIsNot(tr.position, first) + + def test_cut_loss_off_keeps_the_position(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05) + t = feed_quiet(tr, seconds=3) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + tr.on_book(t + 0.2, follower_book(0.07999), TICK) + self.assertEqual(tr.trades, []) + + def test_parallel_positions_up_to_the_limit_with_a_gap(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, max_positions=3, + entry_gap_seconds=1.0) + t = feed_quiet(tr, seconds=3) + up = (0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + tr.on_leader(t, *up) + self.assertEqual(len(tr.ledger.positions), 1) + tr.on_leader(t + 0.5, *up) # too soon for the next one + self.assertEqual(len(tr.ledger.positions), 1) + self.assertIn("не раньше", tr.policy.status) + for k in (1, 2, 3, 4): # one more per second, at most 3 + tr.on_book(t + k, follower_book(0.08 + k * TICK), TICK) + tr.on_leader(t + k + 0.01, 0.08008 + k * 3 * TICK - 5 * TICK, 0.08008 + k * 3 * TICK + 5 * TICK) + self.assertEqual(len(tr.ledger.positions), 3) + self.assertIn("максимум", tr.policy.status) + # take-profit closes each position on its own + top = max(p.target for p in tr.ledger.positions) + tr.on_trade(sh.Trade(t + 5, top + TICK, 50.0, "Buy")) + self.assertEqual(len(tr.ledger.positions), 0) + self.assertEqual([x.reason for x in tr.trades], ["цель"] * 3) + + def test_one_position_per_price_tick(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, max_positions=150, + entry_gap_seconds=0) + t = feed_quiet(tr, seconds=3) + up = (0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + for k in range(10): # many updates, Bybit price unchanged + tr.on_leader(t + k * 0.01, *up) + tr.on_book(t + k * 0.01, follower_book(0.08), TICK) + self.assertEqual(len(tr.ledger.positions), 1) + self.assertIn("одна на шаг цены", tr.policy.status) + tr.on_book(t + 0.2, follower_book(0.08 + TICK), TICK) # Bybit ask moved one step: a new one + tr.on_leader(t + 0.21, 0.08011 - 5 * TICK, 0.08011 + 5 * TICK) + self.assertEqual(len(tr.ledger.positions), 2) + self.assertEqual(len({p.entry for p in tr.ledger.positions}), 2) + off = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, max_positions=150, + entry_gap_seconds=0, one_per_tick=False) + t = feed_quiet(off, seconds=3) + for k in range(5): + off.on_leader(t + k * 0.01, *up) + self.assertEqual(len(off.ledger.positions), 5) + + def test_no_reentry_at_the_same_price_after_a_close(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, max_positions=150, + entry_gap_seconds=0) + t = feed_quiet(tr, seconds=3) + up = (0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + tr.on_leader(t, *up) + pos = tr.position + tr.close(0.07998, t + 0.01, "стоп", sp.TAKER, pos=pos) # closed at once, price unchanged + for k in range(10): # many updates on the same price step + tr.on_leader(t + 0.02 + k * 0.01, *up) + tr.on_book(t + 0.02 + k * 0.01, follower_book(0.08), TICK) + self.assertEqual(len(tr.ledger.positions), 0) + self.assertIn("уже был вход", tr.policy.status) + tr.on_book(t + 0.5, follower_book(0.08 + TICK), TICK) # Bybit moved one step: entry allowed + self.assertEqual(len(tr.ledger.positions), 1) + self.assertAlmostEqual(tr.position.entry, 0.08003) + + def test_stop_inside_the_spread_is_not_entered(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, stop_loss_pct=0.04) + t = feed_quiet(tr, seconds=3) # spread 4 steps = 0.05 % + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + self.assertIsNone(tr.position) + self.assertIn("не меньше стоп-лосса", tr.policy.status) + + def test_manual_close_closes_all(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, max_positions=2, + entry_gap_seconds=0, one_per_tick=False) + t = feed_quiet(tr, seconds=3) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + tr.on_book(t + 0.1, follower_book(0.08), TICK) + self.assertEqual(len(tr.ledger.positions), 2) + tr.close_now(follower_book(0.08), t + 1, "вручную") + self.assertEqual(len(tr.ledger.positions), 0) + self.assertEqual(len(tr.trades), 2) + + def test_confidence_threshold(self): + # A clean one-way KuCoin jump twice the threshold, Bybit flat: strength 1, efficiency 1, agreement 0 → 0.67 + for min_conf, opens in ((0.6, True), (0.8, False)): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, min_confidence=min_conf) + t = feed_quiet(tr, seconds=3) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + self.assertAlmostEqual(tr.policy.conf, 2 / 3, places=2) + self.assertEqual(tr.position is not None, opens, tr.policy.status) + if not opens: + self.assertIn("ниже порога", tr.policy.status) + + def test_choppy_move_has_lower_confidence(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, min_confidence=0.9) + t = feed_quiet(tr, seconds=3) + for k, mid in enumerate((0.08010, 0.07996, 0.08012, 0.07998, 0.08008)): # up and down, ends +0.1 % + tr.on_leader(t + k * 0.1, mid - 5 * TICK, mid + 5 * TICK) + self.assertLess(tr.policy.conf, 0.6) + self.assertIsNone(tr.position) + + def test_kucoin_spot_and_futures_tickers_and_messages(self): + self.assertEqual(lead_window.kucoin_ticker("MARSCOINUSDTM", "spot"), "MARSCOIN-USDT") + self.assertEqual(lead_window.kucoin_ticker("marscoin-usdt", "futures"), "MARSCOINUSDTM") + self.assertEqual(lead_window.kucoin_ticker("MARSCOIN-USDT", "spot"), "MARSCOIN-USDT") + import queue as q + spot = sh.KucoinFeed("MARSCOIN-USDT", q.Queue(), spot=True) + fut = sh.KucoinFeed("MARSCOINUSDTM", q.Queue()) + spot_msg = {"subject": "trade.ticker", "data": {"bestBid": "0.0797", "bestAsk": "0.0798", "time": 1700000000000}} + fut_msg = {"subject": "tickerV2", "data": {"bestBidPrice": "0.07918", "bestAskPrice": "0.07928", + "ts": 1700000000000000000}} + self.assertEqual(spot.parse(spot_msg), (0.0797, 0.0798, 1700000000.0)) + self.assertEqual(fut.parse(fut_msg), (0.07918, 0.07928, 1700000000.0)) + self.assertIsNone(spot.parse(fut_msg)) # each feed reads only its own market + self.assertIsNone(fut.parse(spot_msg)) + + def test_raydium_pool_layout_and_price(self): + data = bytearray(752) + keys = [bytes([i]) * 32 for i in (1, 2, 3, 4)] + for offset, key in zip((336, 368, 400, 432), keys): + data[offset:offset + 32] = key + pool = sh.raydium_pool(sh.RAYDIUM_AMM_V4, bytes(data)) + self.assertEqual(pool["vault0"], sh.b58encode(keys[0])) + self.assertEqual(pool["mint1"], sh.b58encode(keys[3])) + with self.assertRaises(ValueError): + sh.raydium_pool("SomeOtherProgram", bytes(data)) + self.assertEqual(sh.b58encode(b"\0\0\x01"), "112") + # 1 000 000 tokens against 330 SOL at 104 $ → 0.03432 $ per token + price = sh.pool_price_usd({"T": 1_000_000.0, "Q": 330.0}, "T", "Q", 104.0) + self.assertAlmostEqual(price, 0.03432) + self.assertIsNone(sh.pool_price_usd({"T": 1.0}, "T", "Q", 104.0)) + + def test_binance_messages(self): + import queue as q + feed = sh.BinanceFeed("ZEREBROUSDT", q.Queue()) + kind, book = feed.book_event({"b": "0.0338580", "B": "1203", "a": "0.0338670", "A": "1006"}) + self.assertEqual(kind, "book_snapshot") + ob = sh.OrderBook() + ob.apply_snapshot(book) + self.assertEqual(ob.best(), (0.033858, 0.033867)) + kind, trades = feed.trade_event({"p": "0.033866", "q": "2041", "m": True, "T": 1792180517370}) + self.assertEqual((kind, trades[0]["side"]), ("trades", "Sell")) + self.assertAlmostEqual(trades[0]["size"], 0.033866 * 2041) + + def test_dex_price_without_spread_is_a_valid_leader(self): + tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, lead_market="raydium", + follow_exchange="binance") + self.assertEqual((tr.policy.L, tr.policy.F), ("DEX", "Binance")) + t = T0 + while t <= T0 + 3: + tr.on_leader(t, 0.08, 0.08) # pool price: bid == ask + tr.on_book(t, follower_book(0.08), TICK) + t = round(t + 0.1, 3) + tr.on_leader(t, 0.08008, 0.08008) + self.assertEqual(tr.position.side, "LONG") + self.assertIn("DEX", tr.position.regime) + + def test_auto_take_profit_from_the_lag(self): + # KuCoin +0.3 %, Bybit flat: lag 0.3 %; share 100 % → target = Bybit mid × 1.003 + tr = trader(mode="lead", lead_threshold_pct=0.05, auto_tp=True, auto_tp_learn=False, auto_tp_share_pct=100) + t = feed_quiet(tr) + tr.on_leader(t, 0.08024 - 5 * TICK, 0.08024 + 5 * TICK) + pos = tr.position + self.assertIsNotNone(pos, tr.policy.status) + self.assertAlmostEqual(pos.target, 0.08 * 1.003, places=5) + self.assertIn("прогноз +0.300%", pos.regime) + # share 50 % → half the lag + tr = trader(mode="lead", lead_threshold_pct=0.05, auto_tp=True, auto_tp_learn=False, auto_tp_share_pct=50) + t = feed_quiet(tr) + tr.on_leader(t, 0.08024 - 5 * TICK, 0.08024 + 5 * TICK) + self.assertAlmostEqual(tr.position.target, 0.08 * 1.0015, places=5) + + def test_auto_take_profit_skips_when_forecast_does_not_pay(self): + # lag 0.1 % × share 50 % = 0.05 % < spread + fees → no entry + tr = trader(mode="lead", lead_threshold_pct=0.05, auto_tp=True, auto_tp_learn=False, auto_tp_share_pct=50) + t = feed_quiet(tr) + tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK) + self.assertIsNone(tr.position) + self.assertIn("не покрывает", tr.policy.status) + + def test_share_is_learnt_from_history(self): + tr = trader(mode="lead", lead_threshold_pct=0.05, auto_tp=True, auto_tp_learn=True, auto_tp_share_pct=100, + auto_tp_horizon_seconds=2, enabled=False) + pol = tr.policy + t = feed_quiet(tr) + mid, lead = 0.08, 0.08 + # 12 signals: KuCoin steps +0.1 %, Bybit catches up only a quarter of that lag (0.025 %) a bit later + for k in range(12): + lead *= 1.001 + tr.on_leader(t, lead - 5 * TICK, lead + 5 * TICK) + tr.on_book(t + 0.01, follower_book(mid), TICK) + mid *= 1.00025 + tr.on_book(t + 2.5, follower_book(mid), TICK) + t += 5 + tr.on_book(t, follower_book(mid), TICK) + tr.on_leader(t, lead - 5 * TICK, lead + 5 * TICK) + share, note = pol.share() + self.assertGreaterEqual(len(pol.ratios), 10) + self.assertAlmostEqual(share, 0.25, delta=0.1) + self.assertIn("выучено", note) + + def test_pumpswap_pool_layout(self): + data = bytearray(301) + keys = {43: bytes([1]) * 32, 75: bytes([2]) * 32, 139: bytes([3]) * 32, 171: bytes([4]) * 32} + for offset, key in keys.items(): + data[offset:offset + 32] = key + pool = sh.raydium_pool(sh.PUMPSWAP, bytes(data)) + self.assertEqual((pool["mint0"], pool["mint1"]), (sh.b58encode(keys[43]), sh.b58encode(keys[75]))) + self.assertEqual((pool["vault0"], pool["vault1"]), (sh.b58encode(keys[139]), sh.b58encode(keys[171]))) + names = [lead_window.connection_name(c) for c in lead_window.DEFAULT_CONNECTIONS] + self.assertTrue(any(n.startswith("CLAUDIA: DEX пул Fe7bpD") and "MEXC CLAUDIA_USDT" in n for n in names)) + + def test_meteora_dlmm_price(self): + import struct + data = bytearray(904) + struct.pack_into(" 0)) + self.assertLessEqual(m.view()["paused_s"], m.PAUSE_S) + + def test_no_entry_while_ping_is_high(self): + self.settings["max_ping_ms"] = 400 + m = self.mirror() + m.ping = lambda: 650.0 + self.assertIn("пинг до биржи 650 мс", m.gate()) + m.ping = lambda: 200.0 + self.assertEqual(m.gate(), "") + m.ping = lambda: None # no fresh measurement: not blocked + self.assertEqual(m.gate(), "") + self.settings["max_ping_ms"] = 0 # check switched off + m.ping = lambda: 5000.0 + self.assertEqual(m.gate(), "") + + def test_ping_and_slippage_go_to_the_journal(self): + m = self.mirror() + m.ping = lambda: 230.0 + m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5)) + self.assertTrue(wait(lambda: m.state == "open")) + event = next(e for e in reversed(real_mirror.RECENT) if e["action"] == "open" and e["ok"]) + self.assertEqual(event["ping"], 230.0) + self.assertIn("пинг 230 мс", event["text"]) + + def test_fee_rate_learned_from_history_sync(self): + fills = [{"time": 1, "side": "buy", "coins": 100.0, "price": 1.0, "fee": 0.08, "pnl": None, "order": "1"}, + {"time": 2, "side": "sell", "coins": 100.0, "price": 1.0, "fee": 0.08, "pnl": 0.0, "order": "2"}] + self.client.fut_fills = lambda symbol, since: fills + m = self.mirror() + m.sync() + self.assertAlmostEqual(real_mirror.FEES["bybit"], 0.08) + + def test_close_retry_backs_off(self): + m = self.mirror() + m.RETRY_S, m.RETRY_MAX_S = 10.0, 30.0 # only the delays are looked at + m.position = {"side": "LONG"} + delays = [] + with mock.patch.object(real_mirror.threading, "Timer", lambda d, fn: delays.append(d) or mock.Mock()): + for _ in range(5): + m._retry_close("x") + self.assertEqual(delays, [10.0, 15.0, 22.5, 30.0, 30.0]) + + def test_real_mode_is_per_coin(self): + other = real_mirror.FuturesMirror("other", "Y", "bybit", "YUSDT", Path(self.dir.name), + client_for=lambda ex: self.client, settings=lambda: self.settings) + other.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5)) + time.sleep(0.1) + self.assertEqual(self.client.orders, []) # not switched on for this coin + self.assertFalse(other.view()["enabled"]) + self.assertTrue(self.mirror().view()["enabled"]) + + def test_statistics_come_from_exchange_history(self): + fills = [{"time": time.time() - 30, "side": "buy", "coins": 700.0, "price": 0.007371, "fee": 0.00412776, + "pnl": None, "order": "1"}, + {"time": time.time() - 28, "side": "sell", "coins": 700.0, "price": 0.00738, "fee": 0.0041328, + "pnl": 0.0063, "order": "2"}] + self.client.fut_fills = lambda symbol, since: fills + m = self.mirror() + m.sync() + v = m.view() + self.assertEqual(v["source"], "биржа") + self.assertEqual(v["trades"], 1) + self.assertAlmostEqual(v["gross"], 0.0063) + self.assertAlmostEqual(v["fees"], 0.00412776 + 0.0041328) + self.assertAlmostEqual(v["net"], 0.0063 - 0.00412776 - 0.0041328) + + def test_orphan_closed_after_restart(self): + m = self.mirror() + m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5)) + self.assertTrue(wait(lambda: m.state == "open" and m.file.exists())) + self.client.orders.clear() + again = self.mirror() # paper positions are gone after a restart + self.assertTrue(wait(lambda: len(again.trades) == 1)) + self.assertEqual(self.client.orders, [("fut", "sell", 10.0, True)]) + self.assertEqual(again.view()["open"], 0) + + +class BasisRealTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.journal = mock.patch.object(real_mirror, "JOURNAL", Path(self.dir.name) / "j.jsonl") + self.journal.start() + self.e = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + self.client = FakeClient(price=1.0) + self.e.client_for = lambda ex: self.client + self.e.settings.running = self.e.settings.real = True + # the market entry (spot first) unless a test switches the limit entry / exchange TP on + self.e.settings.entry_limit = self.e.settings.exchange_tp = False + self.e.pairs = {"OK": basis.Pair("OK", "OKUSDT", "OKUSDT", 1.0, 1.0, 1.001, 1.010, 1.011, 1e4, 1e4, 1e4, 1e4, + 0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False)} + + def tearDown(self): + self.journal.stop() + self.dir.cleanup() + + def run_jobs(self): + while not self.e.jobs.empty(): + kind, *args = self.e.jobs.get() + getattr(self.e, "_real_open" if kind == "open" else "_real_close")(*args) + if kind == "close": + self.e.busy.discard(args[0]) + + def test_open_hedged_then_close(self): + self.e.step(1000.0) + self.assertEqual(self.e.opening, {"OK"}) + self.e.step(1000.5) # no second entry while opening + self.assertEqual(self.e.jobs.qsize(), 1) + self.run_jobs() + pos = self.e.positions[0] + self.assertTrue(pos.real) + self.assertEqual(pos.qty, 99.0) # perp rounded down to the lot + self.assertAlmostEqual(pos.spot_qty, 99.9) # coins really held after the buy fee + self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("fut", "sell")]) + # gap closes → perp bought back first, then the spot sold + self.e.pairs["OK"] = basis.Pair("OK", "OKUSDT", "OKUSDT", 1.0, 1.0, 1.001, 1.0, 1.0002, 1e4, 1e4, 1e4, 1e4, + 0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False) + self.e.step(1010.0) + self.e.step(1010.5) # close already in progress + self.assertEqual(self.e.jobs.qsize(), 1) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual([o[:2] for o in self.client.orders[2:]], [("fut", "buy"), ("spot", "sell")]) + self.assertIn("реально", self.e.trades[0].reason) + + def test_failed_short_sells_spot_back(self): + self.client.fail_fut = True + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("fut", "sell"), ("spot", "sell")]) + self.assertEqual(self.e.opening, set()) + self.e.step(1001.0) # pause before trying the coin again + self.assertTrue(self.e.jobs.empty()) + + def test_spot_sale_retried_after_perp_bought_back(self): + self.e.step(1000.0) + self.run_jobs() + uid = self.e.positions[0].uid + self.client.fail_spot_sell = True + self.assertIn("реальных отправлено на закрытие: 1", self.e.close(uid)) + self.run_jobs() + pos = self.e.positions[0] + self.assertEqual(pos.closing, "fut_done") + self.assertTrue(pos.error) + self.client.fail_spot_sell = False + self.e.step(pos.retry_at + 1) # retried: only the spot sale is left + self.run_jobs() + self.assertEqual(self.e.positions, []) + self.assertEqual(sum(1 for o in self.client.orders if o[:2] == ("fut", "buy")), 1) # perp not bought twice + + def test_unconfirmed_short_keeps_position(self): + self.client.unconfirmed = 1 + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(len(self.e.positions), 1) # not sold back: the short may be open + self.assertIn("не подтверждён", self.e.positions[0].error) + self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("fut", "sell")]) + + def test_lot_too_big_no_spot_bought(self): + # the incident: CATE, 5.2 $ ≈ 70 coins, the perp's minimum lot is bigger — spot was bought and sold back + self.client.fut_min_coins = lambda symbol: 1000.0 + self.e.step(1000.0) + self.run_jobs() + self.assertEqual(self.client.orders, []) # nothing bought at all + self.assertIn("меньше минимального лота", self.e.real_block["OK"][0]) + self.e.step(1100.0) # not tried again on every step + self.assertTrue(self.e.jobs.empty()) + self.assertIn("лота", self.e.view()["rows"][0]["real_block"]) # the reason is shown in the table + self.assertEqual(self.e.set_settings({"amount": "2000"}), "") # a bigger amount saved: checked anew + self.assertEqual(self.e.real_block, {}) + self.assertEqual(self.e.view()["rows"][0]["real_block"], "") + + def test_balance_insufficient_pauses_the_exchange(self): + self.client.fut_order = mock.Mock(side_effect=live.LiveError("MEXC фьючерсы 2005: Balance insufficient")) + self.e.step(1000.0) + self.run_jobs() + self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("spot", "sell")]) # sold back + self.assertIn("не хватает баланса", self.e.view()["real_pause"]) + self.e.step(time.time() + 10) + self.assertTrue(self.e.jobs.empty()) # no new tries during the pause + + def run_all(self): + while not self.e.jobs.empty(): + kind, *args = self.e.jobs.get() + {"open": self.e._real_open, "close": self.e._real_close, "short": self.e._real_short, + "adopt": self.e.adopt, "watch": self.e._watch_tp, "untp": self.e._remove_tp, + "tp": lambda uid: self.e._place_tp(self.client, next(x for x in self.e.positions if x.uid == uid)) + }[kind](*args) + if kind in ("close", "short", "watch", "tp", "untp"): + self.e.busy.discard(args[0]) + if kind == "adopt": + self.e.opening.discard(args[0]) + + def test_adopt_spot_then_short_then_normal_close(self): + # the incident: 346.2 SI on the spot account, unknown to the program + self.client.spot_balance = 346.2 + self.e.settings.running = False + msg = self.e.adopt("ok", price=1.0, fee_usd=0.0042) + self.assertIn("подхвачено", msg) + pos = self.e.positions[0] + self.assertTrue(pos.short_pending) + self.assertEqual((pos.spot_qty, pos.qty), (346.2, 0.0)) + self.e.step(1000.0) # the short is opened next + self.run_all() + self.assertFalse(pos.short_pending) + self.assertEqual(pos.qty, 346.0) # rounded down to the lot + self.assertEqual(self.client.orders, [("fut", "sell", 346.0, False)]) + self.assertIn("уже ведётся", self.e.adopt("OK")) + + def test_short_refused_retried_later_spot_can_be_sold(self): + self.client.spot_balance = 346.2 + self.e.settings.running = False + self.client.fut_order = mock.Mock(side_effect=live.LiveError("MEXC фьючерсы 2005: Balance insufficient")) + self.e.adopt("OK", price=1.0) + self.e.step(1000.0) + self.run_all() + pos = self.e.positions[0] + self.assertTrue(pos.short_pending) + self.assertIn("шорт не открыт", pos.error) + self.e.step(1001.0) # not retried right away + self.assertTrue(self.e.jobs.empty()) + self.assertIn("отправлено на закрытие", self.e.close(pos.uid)) # «×»: sell the spot, no perp involved + self.run_all() + self.assertEqual(self.e.positions, []) + self.assertEqual(self.client.orders, [("spot", "sell", 346.2)]) + + def test_no_spot_bought_while_another_real_position_exists(self): + # the race of 10:25:31: an entry queued just before a coin was adopted must not buy anything + self.e.step(1000.0) # entry queued (nothing held yet) + self.client.spot_balance = 346.2 + self.e.adopt("OK", price=1.0) # meanwhile: coins taken over + self.run_all() + self.assertNotIn(("spot", "buy"), [o[:2] for o in self.client.orders]) + + def test_entry_cut_by_restart_is_recovered(self): + self.e.pending["OK"] = {"time": 1.0, "amount": 100} + self.e.save() + self.client.spot_balance = 99.9 # bought, then the program stopped + again = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + again.client_for = lambda ex: self.client + again.pairs = self.e.pairs + self.assertEqual(again.recover, {"OK"}) + again.step(1000.0) + kind, base = again.jobs.get() + self.assertEqual((kind, base), ("adopt", "OK")) + again.adopt(base) + self.assertTrue(again.positions[0].short_pending) + self.assertAlmostEqual(again.positions[0].spot_qty, 99.9) + + def test_spot_usdt_moved_to_futures_before_entry(self): + self.client.usdt = {"spot": 300.0, "futures": 20.0} # the short's margin is missing + self.e.step(1000.0) + self.run_all() + first = self.client.orders[0] + self.assertEqual(first[:2], ("transfer", "futures")) # moved BEFORE anything was bought + self.assertAlmostEqual(first[2], 100 * 1.03 - 20 + 0.01, places=2) + self.assertEqual([o[:2] for o in self.client.orders[1:3]], [("spot", "buy"), ("fut", "sell")]) + + def test_not_enough_in_total_nothing_bought(self): + self.client.usdt = {"spot": 60.0, "futures": 40.0} # 100 in total, 204 needed + self.e.step(1000.0) + self.run_all() + self.assertEqual(self.client.orders, []) + self.assertIn("не хватает", self.e.view()["real_pause"]) + + def test_transfer_switched_off(self): + self.e.settings.auto_transfer = False + self.client.usdt = {"spot": 300.0, "futures": 0.0} + self.e.step(1000.0) + self.run_all() + self.assertNotIn("transfer", [o[0] for o in self.client.orders]) + + def test_short_for_adopted_coins_gets_margin_from_spot(self): + self.client.spot_balance = 346.2 + self.client.usdt = {"spot": 6.37, "futures": 0.0} + self.e.settings.running = False + self.client.price = 0.015 + self.e.pairs["OK"] = basis.Pair("OK", "OKUSDT", "OKUSDT", 1.0, 0.015, 0.01502, 0.015, 0.01502, 1e4, 1e4, 1e4, + 1e4, 0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False) + self.e.adopt("OK", price=0.01502) + self.e.step(1000.0) + self.run_all() + self.assertEqual([o[:2] for o in self.client.orders], [("transfer", "futures"), ("fut", "sell")]) + self.assertFalse(self.e.positions[0].short_pending) + + def limit_mode(self, hold=0.0): + self.e.settings.entry_limit = self.e.settings.exchange_tp = True + self.e.settings.limit_hold_s = hold + + def test_limit_entry_short_first_then_spot_then_tp(self): + self.limit_mode() + self.e.step(1000.0) + self.run_all() + kinds = [o[:2] for o in self.client.orders] + self.assertEqual(kinds, [("fut_limit", "sell"), ("spot", "buy")]) # short first, then the hedge + pos = self.e.positions[0] + self.assertAlmostEqual(pos.fut_entry, 1.010) # at the signal's perp bid + self.assertTrue(pos.tp_order) + side, coins, tp = self.client.take_profits[0] + self.assertEqual((side, coins), ("buy", pos.qty)) + self.assertAlmostEqual(tp, pos.spot_entry * (1 + self.e.settings.exit_gap_pct / 100)) + + def test_limit_not_filled_nothing_bought(self): + self.limit_mode() + self.client.limit_fill = 0.0 + self.e.step(1000.0) + self.run_all() + self.assertEqual([o[0] for o in self.client.orders], ["fut_limit", "fut_cancel"]) + self.assertEqual(self.e.positions, []) + self.assertEqual(self.e.opening, set()) + + def test_limit_partly_filled_spot_for_that_part(self): + self.limit_mode() + self.client.limit_fill = 0.5 + self.e.step(1000.0) + self.run_all() + pos = self.e.positions[0] + self.assertAlmostEqual(pos.qty, 49.5) # half of 99 coins + buy = next(o for o in self.client.orders if o[:2] == ("spot", "buy")) + self.assertAlmostEqual(buy[2], 49.5 * 1.001 * 1.001 * 1.003 / 1.0, places=3) + + def test_exchange_tp_filled_then_spot_sold(self): + self.limit_mode() + self.e.step(1000.0) + self.run_all() + pos = self.e.positions[0] + self.client.fill_take_profit(pos.tp_order) # the TP fills on the exchange + self.e.step(1010.0) # the watch notices it + self.run_all() + self.assertEqual(self.e.positions, []) + after = [o[:2] for o in self.client.orders[2:]] + self.assertNotIn(("fut", "buy"), after) # no market buy-back: the TP did it + self.assertIn(("spot", "sell"), after) + t = self.e.trades[-1] + self.assertAlmostEqual(t.fut_exit, pos.tp_price) + + def test_program_close_cancels_tp_first(self): + self.limit_mode() + self.e.step(1000.0) + self.run_all() + uid = self.e.positions[0].uid + self.e.close(uid) + self.run_all() + kinds = [o[0] for o in self.client.orders[2:]] + self.assertEqual(kinds[:2], ["fut_cancel", "fut"]) # TP removed, then the market buy-back + self.assertEqual(self.e.positions, []) + + def test_old_exchange_tp_is_removed(self): + self.limit_mode() + self.e.step(1000.0) + self.run_all() + pos = self.e.positions[0] + self.assertTrue(pos.tp_order) + self.e.settings.exchange_tp = False # the program watches by itself now + self.e.step(1001.0) + kind, uid = self.e.jobs.get() + self.assertEqual((kind, uid), ("untp", pos.uid)) + self.e._remove_tp(uid) + self.assertEqual(pos.tp_order, "") + self.assertEqual(self.client.orders[-1][0], "fut_cancel") + self.assertEqual(len(self.e.positions), 1) # the position itself stays + + def test_exchange_tp_never_set_from_saved_settings(self): + self.e.settings.exchange_tp = True + self.e.save() + again = basis.BasisEngine("bybit", Path(self.dir.name), start=False) + self.assertFalse(again.settings.exchange_tp) + + def test_fast_watch_closes_on_fresh_prices(self): + # paper position; the market list is not refreshed, only the fast per-symbol prices are + self.e.settings.real = False + self.e.step(1000.0) + self.assertEqual(len(self.e.positions), 1) + quotes = {"spot": (1.0, 1.001, None, None), "fut": (1.0, 1.0002, None, None)} # the gap has closed + with mock.patch("fastquote.spot_top", lambda ex, s: quotes["spot"]), \ + mock.patch("fastquote.fut_top", lambda ex, s: quotes["fut"]): + threading.Thread(target=self.e._fast_loop, daemon=True).start() + self.assertTrue(wait(lambda: not self.e.positions)) + self.assertEqual(self.e.trades[-1].reason, "разница сошлась") + self.assertIn("OK", self.e.fast_seen) + + def test_several_real_positions_when_allowed(self): + second = basis.Pair("TWO", "TWOUSDT", "TWOUSDT", 1.0, 1.0, 1.001, 1.012, 1.013, 1e4, 1e4, 1e4, 1e4, + 0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False) + self.e.pairs["TWO"] = second + self.e.step(1000.0) # one entry at a time… + self.assertEqual(self.e.jobs.qsize(), 1) + self.run_all() + self.assertEqual(len(self.e.positions), 1) + self.e.step(1100.0) # limit 1: the second waits + self.assertTrue(self.e.jobs.empty()) + self.assertIn("ждёт закрытия", next(r["why"] for r in self.e.view()["rows"] if not r["base"] in + {p.base for p in self.e.positions})) + self.e.settings.max_real_positions = 2 # two at the same time allowed + self.e.step(1200.0) + self.run_all() + self.assertEqual(sorted(p.base for p in self.e.positions), ["OK", "TWO"]) + self.e.step(1300.0) # and not a third + self.assertTrue(self.e.jobs.empty()) + + def test_coin_in_a_trade_elsewhere_is_not_opened(self): + other = basis.BasisEngine("gate", Path(self.dir.name), start=False) + other.positions.append(basis.Position(1, "OK", 0.0, 10.0, 1.0, 1.01, 1.0, 0.0, 0.0)) + basis.ENGINES.append(other) + try: + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) # OK is in a trade on Gate + self.assertIn("уже в сделке: Gate", self.e.view()["rows"][0]["why"]) + other.positions.clear() + self.e.step(1001.0) + self.assertEqual(self.e.jobs.qsize(), 1) # free again + finally: + basis.ENGINES.remove(other) + + def test_different_instruments_never_traded(self): + # the incident: MEXC EWT — spot 0.339 $, perp 104.84 $: +30 797 %, a perp leg of ~1 570 $ for a 5 $ trade + ewt = basis.Pair("EWT", "EWTUSDT", "EWT_USDT", 1.0, 0.3388, 0.3393, 104.84, 104.9, 1e4, 1e4, 1e4, 1e4, + 0.0, 0.0, 8.0, 1e6, 1e6, 100.0, False, True) + self.e.pairs = {"EWT": ewt} + self.e.settings.max_gap_pct = 300000.0 # whatever is typed in the settings… + self.e.settings.all_coins = True + self.e.step(1000.0) + self.assertTrue(self.e.jobs.empty()) # …it is not entered + row = self.e.view()["rows"][0] + self.assertFalse(row["fits"]) + self.assertIn("разные инструменты", row["why"]) + msg = self.e.set_settings({"max_gap_pct": "300000"}) + self.assertIn("не может быть больше", msg) + self.assertEqual(self.e.settings.max_gap_pct, basis.HARD_MAX_GAP_PCT) + # even an order request that slipped through stops right before the exchange + self.limit_mode() + self.e._open_limit_first(self.client, ewt, 5.1) + self.assertEqual(self.client.orders, []) + self.assertIn("разные инструменты", self.e.real_block["EWT"][0]) + + def test_reset_refused_with_real_positions(self): + self.e.step(1000.0) + self.run_jobs() + self.assertIn("реальные позиции", self.e.reset()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_scalp_hint.py b/tests/test_scalp_hint.py new file mode 100644 index 0000000..4a1aea6 --- /dev/null +++ b/tests/test_scalp_hint.py @@ -0,0 +1,133 @@ +"""Tests for the MetaScalp scalping hint (order book, signal, plan and journal).""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import scalp_hint as sh # noqa: E402 + +TICK = 0.00001 + + +def book_from(asks: dict[float, float], bids: dict[float, float]) -> sh.OrderBook: + book = sh.OrderBook() + book.apply_snapshot({"asks": [{"price": p, "size": s, "type": "Ask"} for p, s in asks.items()], + "bids": [{"price": p, "size": s, "type": "Bid"} for p, s in bids.items()]}) + return book + + +def tape_from(trades: list[tuple[float, float, str]], now: float) -> sh.Tape: + tape = sh.Tape() + for i, (price, size, side) in enumerate(trades): + tape.add(sh.Trade(now - len(trades) + i, price, size, side)) + return tape + + +def levels(start: float, count: int, step: float, size: float) -> dict[float, float]: + return {round(start + i * step, 5): size for i in range(count)} + + +class OrderBookTests(unittest.TestCase): + def test_updates_are_absolute_and_zero_removes(self): + book = book_from({0.04905: 10.0}, {0.049: 5.0}) + book.apply_updates([{"price": 0.04905, "size": 0.0, "type": "Ask"}, + {"price": 0.04906, "size": 7.0, "type": "BestAsk"}, + {"price": 0.049, "size": 9.0, "type": "BestBid"}]) + self.assertEqual(book.best(), (0.049, 0.04906)) + self.assertEqual(book.bids[0.049], 9.0) + + def test_best_price_marks_remove_stale_levels(self): + book = book_from({0.04849: 50.0, 0.04891: 20.0, 0.04895: 30.0}, {0.04845: 10.0}) + book.apply_updates([{"price": 0.04891, "size": 20.0, "type": "BestAsk"}, + {"price": 0.04889, "size": 15.0, "type": "BestBid"}]) + self.assertNotIn(0.04849, book.asks) # consumed ask without an explicit removal + self.assertEqual(book.best(), (0.04889, 0.04891)) + + def test_book_out_of_sync_with_tape_waits(self): + book = book_from(levels(0.04849, 10, TICK, 100.0), levels(0.04845, 10, -TICK, 100.0)) + tape = tape_from([(0.0490, 10.0, "Buy") for _ in range(6)], 1_000.0) + hint = sh.evaluate(book, tape, TICK, sh.HintSettings(), 1_000.0) + self.assertEqual(hint.side, "WAIT") + self.assertIn("расходится", hint.reasons[0]) + + def test_crossed_bids_are_dropped(self): + book = book_from({0.04905: 10.0}, {0.049: 5.0}) + book.apply_updates([{"price": 0.04906, "size": 3.0, "type": "Bid"}]) + self.assertEqual(book.best()[0], 0.049) + + +class EvaluateTests(unittest.TestCase): + settings = sh.HintSettings(min_target_pct=0.05) + + def test_heavy_sellers_give_short_with_stop_behind_density(self): + asks = levels(0.04905, 12, TICK, 300.0) + asks[0.04910] = 5000.0 # resistance density + bids = levels(0.04900, 12, -TICK, 60.0) + bids[0.04870] = 3000.0 # support density further away + now = 1_000.0 + tape = tape_from([(0.04906 - i * 0.000005, 200.0, "Sell") for i in range(8)], now) + hint = sh.evaluate(book_from(asks, bids), tape, TICK, self.settings, now) + self.assertEqual(hint.side, "SHORT") + self.assertAlmostEqual(hint.entry, 0.04909) + self.assertGreater(hint.stop, 0.04910) # behind the density, not in front of it + self.assertGreater(hint.target, 0.04870) # exits before the opposite density + self.assertGreaterEqual(hint.rr, self.settings.min_rr) + + def test_balanced_book_waits(self): + asks = levels(0.04905, 12, TICK, 100.0) + bids = levels(0.04900, 12, -TICK, 100.0) + now = 1_000.0 + tape = tape_from([(0.04903, 50.0, "Buy" if i % 2 else "Sell") for i in range(10)], now) + hint = sh.evaluate(book_from(asks, bids), tape, TICK, self.settings, now) + self.assertEqual(hint.side, "WAIT") + + def test_few_trades_are_ignored(self): + asks = levels(0.04905, 12, TICK, 100.0) + bids = levels(0.04900, 12, -TICK, 100.0) + now = 1_000.0 + tape = tape_from([(0.04905, 5000.0, "Buy")], now) + hint = sh.evaluate(book_from(asks, bids), tape, TICK, self.settings, now) + self.assertEqual(hint.metrics["tape_delta"], 0.0) + self.assertEqual(hint.side, "WAIT") + + def test_small_move_is_rejected(self): + asks = levels(0.04905, 12, TICK, 300.0) + bids = levels(0.04900, 12, -TICK, 60.0) + now = 1_000.0 + tape = tape_from([(0.04903, 200.0, "Sell") for _ in range(8)], now) + strict = sh.HintSettings(min_target_pct=5.0) + hint = sh.evaluate(book_from(asks, bids), tape, TICK, strict, now) + self.assertEqual(hint.side, "WAIT") + self.assertIn("невыгодна", hint.reasons[0]) + + +class JournalTests(unittest.TestCase): + def test_fill_then_target(self): + with tempfile.TemporaryDirectory() as folder: + journal = sh.Journal(sh.HintSettings(), Path(folder) / "j.csv") + hint = sh.Hint("SHORT", "средняя", -0.5, entry=0.04910, stop=0.04915, target=0.04890, rr=4.0) + journal.offer("PUFFERUSDT", hint, 0.0) + journal.on_trade(sh.Trade(1.0, 0.04911, 10, "Buy")) # trades through the limit -> filled + journal.on_trade(sh.Trade(2.0, 0.04889, 10, "Sell")) # target + self.assertIsNone(journal.active) + self.assertEqual(journal.done[-1].result, "цель") + self.assertGreater(journal.done[-1].pnl_pct, 0) + self.assertTrue((Path(folder) / "j.csv").exists()) + + def test_unfilled_expires(self): + with tempfile.TemporaryDirectory() as folder: + journal = sh.Journal(sh.HintSettings(fill_minutes=1), Path(folder) / "j.csv") + hint = sh.Hint("LONG", "низкая", 0.3, entry=0.049, stop=0.0489, target=0.0492, rr=2.0) + journal.offer("X", hint, 0.0) + journal.on_trade(sh.Trade(30.0, 0.04905, 1, "Buy")) + journal.on_trade(sh.Trade(61.0, 0.04905, 1, "Buy")) + self.assertEqual(journal.done[-1].result, "не исполнился") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_scalp_paper.py b/tests/test_scalp_paper.py new file mode 100644 index 0000000..03db6a7 --- /dev/null +++ b/tests/test_scalp_paper.py @@ -0,0 +1,219 @@ +"""Tests for the paper trader: simple and adaptive policies, recording and replay.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import scalp_hint as sh # noqa: E402 +import scalp_paper as sp # noqa: E402 + +TICK = 0.00001 + + +def book(bid: float, ask: float, depth: int = 10, bid_size: float = 100.0, ask_size: float = 100.0) -> sh.OrderBook: + b = sh.OrderBook() + b.apply_snapshot({"asks": [{"price": round(ask + i * TICK, 5), "size": ask_size, "type": "Ask"} for i in range(depth)], + "bids": [{"price": round(bid - i * TICK, 5), "size": bid_size, "type": "Bid"} for i in range(depth)]}) + return b + + +def trader(folder: str | None = None, **overrides) -> sp.PaperTrader: + settings = sp.PaperSettings(cooldown_seconds=0, **overrides) + paths = (Path(folder) / "state.json", Path(folder) / "trades.csv") if folder else (None, None) + return sp.PaperTrader(settings, sh.HintSettings(), *paths) + + +def hint(side: str, target: float, score: float = 0.5, metrics: dict | None = None) -> sh.Hint: + return sh.Hint(side, "средняя", score, entry=0.049, stop=0.0489, target=target, rr=2.0, + metrics=metrics if metrics is not None else {"mid": 0.049}) + + +class SimplePolicyTests(unittest.TestCase): + def test_market_entry_stake_and_target(self): + with tempfile.TemporaryDirectory() as folder: + t = trader(folder, mode="simple") + t.on_tick(0.0, "X", hint("LONG", 0.04915), book(0.04900, 0.04901), TICK) + pos = t.position + self.assertAlmostEqual(pos.entry, 0.04901) # market buy at the ask + self.assertAlmostEqual(pos.entry * pos.qty, 5.0) # 5$ x leverage 1 + t.on_trade(sh.Trade(1.0, 0.04916, 1.0, "Buy")) + self.assertEqual(t.trades[-1].reason, "цель") + self.assertGreater(t.trades[-1].net_usd, 0) + self.assertAlmostEqual(t.balance, 300.0 + t.trades[-1].net_usd) + again = trader(folder, mode="simple") # persisted + self.assertEqual(len(again.trades), 1) + self.assertAlmostEqual(again.balance, t.balance) + + def test_adverse_tick_and_minimum_target(self): + t = trader(mode="simple", adverse_ticks=1) + t.on_tick(0.0, "X", hint("LONG", 0.04905), book(0.04900, 0.04901), TICK) # +0.08% only + self.assertIsNone(t.position) + t.on_tick(1.0, "X", hint("LONG", 0.04915), book(0.04900, 0.04901), TICK) + t.on_tick(2.0, "X", hint("LONG", 0.04915), book(0.04899, 0.04900), TICK) # mid one tick lower + self.assertEqual(t.trades[-1].reason, "курс против — закрыто") + + +class AdaptivePolicyTests(unittest.TestCase): + def warm(self, t: sp.PaperTrader, mids: list[float], start: float = 0.0, step: float = 1.0) -> float: + now = start + for mid in mids: + bid = round(mid - TICK / 2, 6) + t.on_tick(now, "X", hint("WAIT", 0.0, score=0.0, metrics={}), book(bid, round(bid + TICK, 6)), TICK) + now += step + return now + + def test_waits_until_market_statistics_exist(self): + t = trader(mode="adaptive") + t.on_tick(0.0, "X", hint("LONG", 0.0495, score=0.9), book(0.049, 0.04901), TICK) + self.assertIsNone(t.pending_order()) + self.assertIn("Накапливаю", t.policy.status) + + def test_range_edge_places_limit_with_stop_beyond_noise(self): + t = trader(mode="adaptive") + # A sideways market slowly swinging between 0.04880 and 0.04920 (100 s up, 100 s down). + mids = [0.0490 + 0.0002 * (1 - abs((i % 200) - 100) / 50) for i in range(320)] + now = self.warm(t, mids) + policy = t.policy + state = policy.market(now) + self.assertIsNotNone(state) + self.assertLess(state["efficiency"], 0.35) # range, not trend + low = state["low"] + # At the lower edge the book confirms the reversal (bids outweigh asks), whatever the tape says. + t.on_tick(now, "X", hint("LONG", 0.0, score=-0.2, metrics={"mid": low, "support": None, "book_imb": 0.6, + "near_imb": 0.4}), + book(round(low, 5), round(low + TICK, 5)), TICK) + order = t.pending_order() + self.assertIsNotNone(order) + self.assertEqual(order.side, "LONG") + self.assertLess(order.stop, low) # stop below the range low + self.assertGreater((order.target - order.price) / order.price * 100, 0.2) + # Limit fills only when the market trades through it, then the stop closes it. + t.on_trade(sh.Trade(now + 1, order.price - TICK, 1, "Sell")) + self.assertIsNotNone(t.position) + t.on_trade(sh.Trade(now + 2, order.stop - TICK, 1, "Sell")) + self.assertEqual(t.trades[-1].reason, "стоп") + + def test_middle_of_range_is_skipped(self): + t = trader(mode="adaptive") + mids = [0.0490 + 0.0002 * (1 - abs((i % 200) - 100) / 50) for i in range(320)] + now = self.warm(t, mids) + t.on_tick(now, "X", hint("LONG", 0.0, score=0.9, metrics={"mid": 0.0490, "book_imb": 0.9, "near_imb": 0.9}), + book(0.04900, 0.04901), TICK) + self.assertIsNone(t.pending_order()) + self.assertIn("середина", t.policy.status) + + def test_losing_streak_pauses_and_raises_threshold(self): + t = trader(mode="adaptive", loss_streak=2) + policy = t.policy + loss = sp.PaperTrade("", "X", "adaptive", "LONG", 1, 5, 1, 0.99, -1, -0.05, 0.01, "стоп", 3) + policy.on_close(loss, {"book_imb": 0.8}, now=100.0) + policy.on_close(loss, {"book_imb": 0.8}, now=101.0) + self.assertGreater(policy.pause_until, 101.0) + self.assertGreater(policy.bump, 0) + self.assertLess(t.hint_settings.weights["book_imb"], sh.DEFAULT_WEIGHTS["book_imb"]) # learned + + +class PulsePolicyTests(unittest.TestCase): + up = {"mid": 0.049, "momentum": 0.5, "book_imb": 0.4} + + def test_no_order_when_impulse_and_book_disagree(self): + t = trader(mode="pulse") + t.on_tick(0.0, "X", hint("WAIT", 0.0, metrics={"momentum": 0.5, "book_imb": -0.3}), + book(0.04900, 0.04901), TICK) + self.assertIsNone(t.pending_order()) + self.assertIn("разные стороны", t.policy.status) + + def test_limit_offset_requote_fill_and_close_on_next_tick(self): + t = trader(mode="pulse", pulse_offset_pct=0.15) + b = book(0.04900, 0.04901) + t.on_tick(0.0, "X", hint("WAIT", 0.0, metrics=self.up), b, TICK) + order = t.pending_order() + self.assertEqual(order.side, "LONG") + self.assertAlmostEqual(order.price, 0.04893) # mid 0.049005 - 0.15%, rounded down + t.on_trade(sh.Trade(1.0, 0.04901, 1, "Buy")) # first trade sets the reference price + t.on_trade(sh.Trade(2.0, 0.04902, 1, "Buy")) # next tick, not filled -> re-placed + self.assertIsNotNone(t.pending_order()) + self.assertIsNone(t.position) + price = t.pending_order().price + t.on_trade(sh.Trade(3.0, round(price - TICK, 5), 1, "Sell")) # trades through -> filled + self.assertIsNotNone(t.position) + self.assertAlmostEqual(t.position.entry, price) + t.on_trade(sh.Trade(4.0, round(price - TICK, 5), 1, "Sell")) # same price: not a new tick + self.assertIsNotNone(t.position) + t.on_trade(sh.Trade(5.0, price, 1, "Buy")) # next tick -> closed at market + self.assertIsNone(t.position) + self.assertEqual(t.trades[-1].reason, "следующий тик") + self.assertIsNotNone(t.pending_order()) # and a new order is placed at once + + +def custom_book(asks: list[float], bids: list[float], ask0: float = 0.04901, bid0: float = 0.04900) -> sh.OrderBook: + b = sh.OrderBook() + b.apply_snapshot({"asks": [{"price": round(ask0 + i * TICK, 5), "size": s, "type": "Ask"} for i, s in enumerate(asks)], + "bids": [{"price": round(bid0 - i * TICK, 5), "size": s, "type": "Bid"} for i, s in enumerate(bids)]}) + return b + + +class SignificantImbalanceTests(unittest.TestCase): + def test_small_and_outsized_levels_are_ignored(self): + # Asks hold one huge wall; bids hold more mid-sized orders. Plain sums favour sellers, + # significant sums favour buyers. + asks = [100, 100, 100, 100, 50_000, 1, 1, 1] + bids = [300, 300, 300, 300, 300, 1, 1, 1] + info = sh.significant_imbalance(custom_book(asks, bids), 0.3, 20, 90) + self.assertGreater(info["imbalance"], 0.3) + self.assertLess(info["high"], 50_000) # the wall is above the upper cut + self.assertEqual(info["used"], 16 - 3 - 1) # 20% smallest and 10% largest levels dropped + plain = sh.significant_imbalance(custom_book(asks, bids), 0.3, 0, 100) + self.assertLess(plain["imbalance"], 0) + + def test_sums_policy_enters_follows_and_exits(self): + t = trader(mode="sums", sums_threshold=0.2, min_target_pct=0.2) + bullish = custom_book([100] * 8, [400] * 8) + t.on_tick(0.0, "X", hint("WAIT", 0.0, metrics={}), bullish, TICK) + order = t.pending_order() + self.assertEqual((order.side, order.price), ("LONG", 0.049)) # passive limit at the best bid + moved = custom_book([100] * 8, [400] * 8, ask0=0.04903, bid0=0.04902) + t.on_tick(1.0, "X", hint("WAIT", 0.0, metrics={}), moved, TICK) + self.assertEqual(t.pending_order().price, 0.04902) # follows the best bid + t.on_trade(sh.Trade(2.0, 0.04901, 1, "Sell")) # trades through -> filled + self.assertIsNotNone(t.position) + bearish = custom_book([400] * 8, [100] * 8, ask0=0.04903, bid0=0.04902) + t.on_tick(3.0, "X", hint("WAIT", 0.0, metrics={}), bearish, TICK) + self.assertEqual(t.trades[-1].reason, "перевес развернулся") + + +class SumsInvertTests(unittest.TestCase): + def test_invert_swaps_the_side(self): + t = trader(mode="sums", sums_threshold=0.2, sums_invert=True) + t.on_tick(0.0, "X", hint("WAIT", 0.0, metrics={}), custom_book([100] * 8, [400] * 8), TICK) + order = t.pending_order() + self.assertEqual((order.side, order.price), ("SHORT", 0.04901)) # buyers dominate -> SHORT at the ask + self.assertIn("против перевеса", t.policy.status) + + +class RecordingTests(unittest.TestCase): + def test_record_and_replay(self): + with tempfile.TemporaryDirectory() as folder: + rec = sp.Recorder("X", 1, TICK, Path(folder)) + t0 = 1_000.0 + asks = [{"price": round(0.04901 + i * TICK, 5), "size": 100.0, "type": "Ask"} for i in range(10)] + bids = [{"price": round(0.04900 - i * TICK, 5), "size": 300.0, "type": "Bid"} for i in range(10)] + rec.write("S", {"asks": asks, "bids": bids}, t0) + for i in range(30): + rec.write("T", [{"price": 0.04901, "size": 50.0, "side": "Buy"}], t0 + i) + rec.write("T", [{"price": 0.04930, "size": 50.0, "side": "Buy"}], t0 + 40) + rec.close() + rows = list(sp.read_recording(rec.path)) + self.assertEqual(rows[0][1], "meta") + self.assertEqual(len(rows), 33) + result = sp.replay([rec.path], sp.PaperSettings(mode="simple", cooldown_seconds=0)) + self.assertIsInstance(result.trades, list) # runs end to end + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_unified.py b/tests/test_unified.py new file mode 100644 index 0000000..1b6c6f9 --- /dev/null +++ b/tests/test_unified.py @@ -0,0 +1,219 @@ +"""«Арбитраж»: one mode for every link — spot → perp between exchanges, spot → perp inside one exchange, spot → spot +(from the coin's stock on the selling exchange); the simulation and real trading are two engines, each started and +stopped by itself; the single-exchange tabs' positions moved in. No request reaches an exchange.""" + +from __future__ import annotations + +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])) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import cross # noqa: E402 +import real_mirror # noqa: E402 +from test_real import FakeClient # noqa: E402 + + +def link(base, a, b, buy=1.0, sell=1.02, ss=False): + return cross.Link(base, a, b, f"{base}USDT", f"{base}USDT", buy - 0.001, buy, sell, sell + 0.001, + 1e5, 1e5, 1e7, 1e7, 0.0 if ss else 0.0001, 8.0, 1.0, False, ss=ss) + + +class UnifiedTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.journal = mock.patch.object(real_mirror, "JOURNAL", Path(self.dir.name) / "j.jsonl") + self.journal.start() + + def tearDown(self): + self.journal.stop() + self.dir.cleanup() + + def engine(self, real=False, leader=None): + e = cross.CrossEngine(Path(self.dir.name), start=False, real=real, leader=leader) + e.settings.running, e.settings.history_min = True, 0.0 + e.settings.exit_hold_s = 0.0 + return e + + def feed(self, e, *links): + e.links = {l.key: l for l in links} + for l in links: + e.usual[l.key], e.seen_since[l.key] = 0.5, 0.0 + + # --- kinds --------------------------------------------------------------------------------------------------- + def test_inside_one_exchange_and_spot_spot_on_paper(self): + e = self.engine() + self.feed(e, link("AAA", "MEXC", "MEXC"), link("BBB", "Gate", "MEXC", ss=True)) + e.step(1000.0) + pos = {p.base: p for p in e.positions} + self.assertEqual(pos["AAA"].kind, "in") + self.assertEqual(pos["BBB"].kind, "ss") + self.assertEqual(pos["BBB"].liq_price, 0.0) # a spot sale is never liquidated + fees_ss = pos["BBB"].qty * (1.0 * cross.SPOT_FEE["Gate"] + 1.02 * cross.SPOT_FEE["MEXC"]) / 100 + self.assertAlmostEqual(pos["BBB"].fees, fees_ss) + rows = {r["base"]: r for r in e.view()["rows"]} + self.assertEqual(rows["BBB"]["kind_name"], "спот → спот") + # inside one exchange: one trade, counted once on that exchange + self.assertEqual(e.open_on("MEXC").count("AAA"), 1) + e.links["BBB|Gate|MEXC|ss"] = link("BBB", "Gate", "MEXC", buy=1.0, sell=1.0, ss=True) # back to usual + e.step(1010.0) + self.assertEqual([t.kind for t in e.trades], ["ss"]) + + def test_search_switches(self): + e = self.engine() + e.settings.search_ss = e.settings.search_in = False + self.feed(e, link("AAA", "MEXC", "MEXC"), link("BBB", "Gate", "MEXC", ss=True), link("CCC", "Gate", "MEXC")) + e.step(1000.0) + self.assertEqual([p.base for p in e.positions], ["CCC"]) + self.assertEqual({r["kind"] for r in e.view()["rows"]}, {"sf"}) + + # --- real spot–spot ---------------------------------------------------------------------------------------- + def test_real_spot_spot_needs_stock_then_sells_b_buys_a(self): + e = self.engine(real=True) + a, b = FakeClient(price=1.0), FakeClient(price=1.02) + e.client_for = lambda ex: {"Gate": a, "MEXC": b}[ex] + e.balances = {"gate": {"values": {}, "time": 1.0}, "mexc": {"values": {}, "time": 1.0, "coins": {"BBB": 10.0}}} + e.settings.amount = 100.0 + self.feed(e, link("BBB", "Gate", "MEXC", ss=True)) + e.step(1000.0) + self.assertTrue(e.jobs.empty()) # 10 coins on MEXC, ~100 needed + self.assertIn("мало запаса BBB на MEXC", e.view()["rows"][0]["why"]) + e.balances["mexc"]["coins"] = {"BBB": 500.0} + b.spot_balance = 500.0 + e.step(1001.0) + while not e.jobs.empty(): + e.do_job(e.jobs.get()) + self.assertEqual([o[:2] for o in b.orders], [("spot", "sell")]) # B's stock sold first + self.assertEqual([o[:2] for o in a.orders], [("spot", "buy")]) + pos = e.positions[0] + self.assertTrue(pos.real and pos.ss) + self.assertAlmostEqual(pos.entry_gap, 2.0) + # back to usual → the stock bought back on B, the coins sold on A + e.links[pos.key] = link("BBB", "Gate", "MEXC", buy=1.0, sell=1.0, ss=True) + b.price = 1.0 # B's market has come down with the quote + e.step(1010.0) + while not e.jobs.empty(): + e.do_job(e.jobs.get()) + self.assertEqual(e.positions, []) + self.assertEqual([o[:2] for o in b.orders[1:]], [("spot", "buy")]) + self.assertEqual([o[:2] for o in a.orders[1:]], [("spot", "sell")]) + self.assertGreaterEqual(b.spot_balance, 500.0 - 1e-9) # the stock is back + self.assertEqual(e.trades[0].kind, "ss") + + def test_real_inside_one_exchange_one_transfer(self): + e = self.engine(real=True) + c = FakeClient(price=1.0) + c.usdt = {"spot": 300.0, "futures": 0.0} + e.client_for = lambda ex: c + e.balances = {"mexc": {"values": {}, "time": 1.0}} + e.settings.entry_limit = e.settings.entry_ioc = False + self.feed(e, link("AAA", "MEXC", "MEXC", buy=1.0, sell=1.02)) + e.step(1000.0) + while not e.jobs.empty(): + e.do_job(e.jobs.get()) + transfers = [o for o in c.orders if o[0] == "transfer"] + self.assertEqual(len(transfers), 1) # once, leaving enough for both legs + self.assertGreaterEqual(c.usdt["spot"], 100.0) + self.assertEqual(e.positions[0].kind, "in") + + # --- two engines --------------------------------------------------------------------------------------------- + def test_simulation_and_real_are_independent(self): + paper = self.engine() + real = self.engine(real=True, leader=paper) + self.assertIs(real.usual, paper.usual) # one set of learnt gaps + l = link("CCC", "Gate", "MEXC") + paper.links = {l.key: l} + paper.usual[l.key], paper.seen_since[l.key] = 0.5, 0.0 + paper.step(1000.0) + self.assertEqual(len(paper.positions), 1) + self.assertEqual(real.elsewhere("CCC"), "") # a paper trade never blocks a real one + real.settings.running = False + real.take_prices(paper.links, paper) + self.assertIn(l.key, real.links) + self.assertTrue(real.jobs.empty()) # stopped: nothing + self.assertEqual(real.set_settings({"real": False}), "") + self.assertTrue(real.settings.real) # the tab decides, not a setting + + def test_real_engine_starts_from_simulation_settings(self): + paper = self.engine() + paper.set_settings({"amount": "7", "limits": {"Gate": 2}}) + real = cross.CrossEngine(Path(self.dir.name), start=False, real=True, leader=paper) + self.assertEqual((real.settings.amount, real.limits["Gate"]), (7.0, 2)) + self.assertFalse(real.settings.running) + self.assertTrue(real.settings.real) + + # --- hot watch: links in profit priced every 0.5 s ------------------------------------------------------------ + def test_hot_links_are_those_in_profit_of_running_engines(self): + paper = self.engine() + real = self.engine(real=True, leader=paper) + paper.settings.min_net_pct = 5.0 # in profit, but not entered (threshold) + good, poor, held = link("GOOD", "Gate", "MEXC", sell=1.03), link("POOR", "Gate", "MEXC", sell=1.004), \ + link("HELD", "Gate", "MEXC", sell=1.03) + self.feed(paper, good, poor, held) + paper.positions.append(cross.CrossPosition(99, "HELD", "Gate", "MEXC", "", "", 1.0, 1.0, 1.0, 1.03, 3.0, 0.5, + 0.0, 0.0)) + paper.step(1000.0) + self.assertEqual(paper.pick_hot([paper, real]), [good.key]) # not POOR (net < 0), not HELD (in a trade) + real.settings.running = False + paper.settings.running = False + self.assertEqual(paper.pick_hot([paper, real]), []) # nothing runs: no extra requests + + def test_hot_step_enters_on_fresh_prices(self): + e = self.engine() + l = link("HOT", "Gate", "MEXC", sell=1.004) # +0.4 %: below the threshold now + self.feed(e, l) + e.step(1000.0) + self.assertEqual(e.positions, []) + e.links[l.key] = link("HOT", "Gate", "MEXC", sell=1.02) # the hot watch's fresh prices: +2 % + e.hot_step([l.key], 1000.5) + self.assertEqual([p.base for p in e.positions], ["HOT"]) + self.assertGreater(e.cand[l.key]["net"], 0.5) # the table shows the fresh figure + + def test_page_uses_the_cycle_result(self): + e = self.engine() + self.feed(e, link("AAA", "Gate", "MEXC", sell=1.004)) + e.step(1000.0) + calls = [] + orig = e.candidates + e.candidates = lambda now, keys=None: calls.append(keys) or orig(now, keys) + e.cand_time = cross.time.time() + e.view() + self.assertEqual(calls, []) # no recount of every link per page update + + # --- the single-exchange tabs moved in ------------------------------------------------------------------- + def test_positions_of_single_exchange_tabs_move_in(self): + old = {"settings": {"exit_gap_pct": 0.05}, + "positions": [{"uid": 1, "base": "CATE", "opened": 1.0, "qty": 100.0, "spot_entry": 0.0754, + "fut_entry": 0.0786, "entry_gap": 4.29, "fees": 0.012, "next_funding": 0.0, + "real": True, "spot_qty": 100.4, "fut_symbol": "CATE_USDT"}, + {"uid": 2, "base": "PAP", "opened": 1.0, "qty": 10.0, "spot_entry": 1.0, + "fut_entry": 1.01, "entry_gap": 1.0, "fees": 0.002, "next_funding": 0.0}], + "trades": [{"uid": 3, "base": "OLD", "opened": 1.0, "closed": 2.0, "qty": 1.0, "spot_entry": 1.0, + "spot_exit": 1.0, "fut_entry": 1.0, "fut_exit": 1.0, "entry_gap": 1.0, "exit_gap": 0.0, + "spot_pnl": 0.0, "fut_pnl": 0.01, "fees": 0.001, "funding": 0.0, "net": 0.009, + "reason": "разница сошлась (реально)", "amount": 1.0, "real": True}]} + (Path(self.dir.name) / "basis_mexc.json").write_text(json.dumps(old), "utf-8") + paper = self.engine() + real = self.engine(real=True, leader=paper) + self.assertEqual([p.base for p in paper.positions], ["PAP"]) # paper → the simulation + cate = real.positions[0] # real → real trading, still managed + self.assertEqual((cate.base, cate.kind, cate.real, cate.fut_symbol, cate.spot_qty), + ("CATE", "in", True, "CATE_USDT", 100.4)) + self.assertAlmostEqual(cate.usual + real.settings.exit_over_usual_pct, 0.05) # the old exit level + self.assertEqual([t.base for t in real.trades], ["OLD"]) + self.assertEqual(paper.trades, []) + again = cross.CrossEngine(Path(self.dir.name), start=False, real=True) + self.assertEqual(len(again.positions), 1) # taken over once, not again + # it closes like any position: gap back to the old exit level + real.links = {cate.key: link("CATE", "MEXC", "MEXC", buy=0.0790, sell=0.07902)} + real.step(1000.0) + self.assertEqual(real.jobs.qsize(), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web_proxy.py b/tests/test_web_proxy.py new file mode 100644 index 0000000..891ae7b --- /dev/null +++ b/tests/test_web_proxy.py @@ -0,0 +1,77 @@ +"""The public proxy forwards GET and POST (with body) to the engine and reports a missing engine.""" + +from __future__ import annotations + +import json +import sys +import threading +import unittest +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import web_proxy as wp # noqa: E402 + + +class Echo(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _reply(self, payload): + data = json.dumps(payload).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + self._reply({"method": "GET", "path": self.path}) + + def do_POST(self): + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + self._reply({"method": "POST", "path": self.path, "body": json.loads(body or b"{}")}) + + +def serve(handler): + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + +class ProxyTests(unittest.TestCase): + def test_forwards_get_and_post(self): + engine = serve(Echo) + with mock.patch.object(wp, "ENGINE", f"http://127.0.0.1:{engine.server_address[1]}"): + proxy = serve(wp.Proxy) + base = f"http://127.0.0.1:{proxy.server_address[1]}" + try: + 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"}) + got = json.loads(urllib.request.urlopen(req).read()) + self.assertEqual(got["body"], {"a": 1}) + finally: + for s in (proxy, engine): + s.shutdown() + s.server_close() + + def test_missing_engine_is_502(self): + with mock.patch.object(wp, "ENGINE", "http://127.0.0.1:9"): + proxy = serve(wp.Proxy) + try: + with self.assertRaises(urllib.error.HTTPError) as ctx: + urllib.request.urlopen(f"http://127.0.0.1:{proxy.server_address[1]}/") + self.assertEqual(ctx.exception.code, 502) + finally: + proxy.shutdown() + proxy.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web_sim.py b/tests/test_web_sim.py new file mode 100644 index 0000000..1d81665 --- /dev/null +++ b/tests/test_web_sim.py @@ -0,0 +1,272 @@ +"""Web simulator: engines per coin, settings, closing one position by id, HTTP API (no network feeds).""" + +from __future__ import annotations + +import json +import sys +import tempfile +import threading +import unittest +import urllib.request +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import scalp_hint as sh # noqa: E402 +import scalp_paper as sp # noqa: E402 +import web_sim as ws # noqa: E402 + +TICK = 0.00001 +CONN = {"lead_market": "raydium", "lead_ticker": "SIUSDTM", "lead_pool": "8uwFMFCUDi61rgT1e6bUuDEfaUcN6roSoL7qHkp2NtHk", + "follow_exchange": "mexc", "follow_ticker": "SI_USDT"} + + +class _NoReal: + """Stands in for real_mirror.FuturesMirror: tests must never send real orders, even with real mode on.""" + def __init__(self, *args, **kwargs): + self.trades = [] + self.on_failed_open = None + + def hook(self, *args): + pass + + def gate(self): + return "" + + 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": []} + + +_no_real = mock.patch.object(ws.real_mirror, "FuturesMirror", _NoReal) + + +def setUpModule(): + _no_real.start() + + +def tearDownModule(): + _no_real.stop() + + +def book(mid, half=2 * TICK): + b = sh.OrderBook() + b.apply_snapshot({"asks": [{"price": round(mid + half, 5), "size": 500.0, "type": "Ask"}], + "bids": [{"price": round(mid - half, 5), "size": 500.0, "type": "Bid"}]}) + return b + + +class WebSimTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.patches = [mock.patch.object(ws, "DATA_DIR", Path(self.tmp.name)), + mock.patch.object(ws, "SETTINGS_FILE", Path(self.tmp.name) / "settings.json")] + for p in self.patches: + p.start() + + def tearDown(self): + for p in self.patches: + p.stop() + self.tmp.cleanup() + + def engine(self, **common): + base = dict(ws.load_common(), mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, + max_positions=5, entry_gap_seconds=0, cooldown_ms=0, stake=100.0, budget=1000.0, + stop_loss_pct=0.3, min_confidence=0.0, auto_tp=False, one_per_tick=False, require_leader=False) + base.update(common) + e = ws.Engine(CONN, base) + e.tick = TICK + return e + + def feed(self, e, t0=1000.0): + t = t0 + while t <= t0 + 3: + e.paper.on_leader(t, 0.08, 0.08) + e.book = book(0.08) + e.paper.on_book(t, e.book, TICK) + t = round(t + 0.1, 3) + return t + + def test_new_coin_is_stopped_with_the_common_budget(self): + e = self.engine() + self.assertFalse(e.paper.settings.enabled) + self.assertEqual(e.paper.ledger.balance, 1000.0) + self.assertEqual((e.paper.settings.follow_exchange, e.paper.settings.lead_pool), ("mexc", CONN["lead_pool"])) + self.assertEqual(e.symbol, "SI") + + def test_start_trade_and_close_one_position_by_id(self): + e = self.engine() + e.set_trading(True) + t = self.feed(e) + e.paper.on_leader(t, 0.08008, 0.08008) + e.paper.on_leader(t + 0.05, 0.08016, 0.08016) + self.assertEqual(len(e.paper.ledger.positions), 2) + uid = e.paper.ledger.positions[0].uid + self.assertIn("1", e.close(uid)) + self.assertEqual([p.uid for p in e.paper.ledger.positions], [uid + 1]) + self.assertEqual(e.paper.ledger.trades[-1].reason, "вручную") + d = e.detail() + self.assertEqual(len(d["positions"]), 1) + self.assertEqual(len(d["closed"]), 1) + e.close(None) + self.assertEqual(e.paper.ledger.positions, []) + + def test_reset_clears_only_this_coins_statistics(self): + e = self.engine() + e.set_trading(True) + t = self.feed(e) + e.paper.on_leader(t, 0.08008, 0.08008) + e.close(None) + 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)) + e.reset() + self.assertEqual((e.paper.trades, e.paper.ledger.positions), ([], [])) + self.assertEqual(e.paper.ledger.balance, 1000.0) + self.assertTrue(e.paper.settings.enabled) # Start/Stop survives the reset + self.assertFalse((ws.DATA_DIR / f"{e.key}.csv").exists()) + + def test_auto_stop_when_cex_leads(self): + e = self.engine(auto_stop_pct=20.0) + e.set_trading(True) + pol = e.paper.policy + pol.leadership = {"lead": 0.3, "follow": 0.4, "edge": -0.1, "pct": -14.3, "at": 1.0} + e._auto_stop(1000.0) + self.assertTrue(e.paper.settings.enabled) # CEX ahead by 14 % < 20 %: keep going + pol.leadership = {"lead": 0.2, "follow": 0.6, "edge": -0.4, "pct": -50.0, "at": 2.0} + e._auto_stop(1010.0) + self.assertFalse(e.paper.settings.enabled) + self.assertIn("опережает DEX на 50%", e.auto_stop) + self.assertEqual(e.summary()["auto_stop"], e.auto_stop) + e.set_trading(True) # Start clears the note + self.assertEqual(e.auto_stop, "") + e._auto_stop(1020.0) # same measurement: not applied twice + self.assertTrue(e.paper.settings.enabled) + e.paper.settings.auto_stop_pct = 0.0 # 0 = off + pol.leadership = dict(pol.leadership, at=3.0) + e._auto_stop(1030.0) + self.assertTrue(e.paper.settings.enabled) + + def test_exchange_links(self): + links = {l["label"]: l["url"] for l in ws.exchange_links(CONN)} + self.assertEqual(links["DEX пул · DexScreener"], f"https://dexscreener.com/solana/{CONN['lead_pool']}") + self.assertEqual(links["MEXC фьючерс SI_USDT"], "https://futures.mexc.com/exchange/SI_USDT") + kucoin = {"lead_market": "spot", "lead_ticker": "MARSCOIN-USDT", "lead_pool": "", "follow_exchange": "bybit", + "follow_ticker": "MARSCOINUSDT"} + urls = [l["url"] for l in ws.exchange_links(kucoin)] + self.assertEqual(urls, ["https://www.kucoin.com/trade/MARSCOIN-USDT", + "https://www.bybit.com/trade/usdt/MARSCOINUSDT"]) + self.assertIn("https://www.binance.com/en/futures/ZEREBROUSDT", + [l["url"] for l in ws.exchange_links(dict(CONN, follow_exchange="binance", + follow_ticker="ZEREBROUSDT"))]) + self.assertTrue(ws.Engine(CONN, ws.load_common()).detail()["links"]) + + def test_trading_pairs_are_listed_first(self): + sim = ws.Simulator.__new__(ws.Simulator) + 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) + sim.engines = {a.key: a, z.key: z} + self.assertEqual([c["symbol"] for c in sim.state()["coins"]], ["AAA", "ZZZ"]) + z.set_trading(True) + self.assertEqual([c["symbol"] for c in sim.state()["coins"]], ["ZZZ", "AAA"]) + + def test_stop_keeps_prices_but_blocks_entries(self): + e = self.engine() + t = self.feed(e) + e.paper.on_leader(t, 0.08008, 0.08008) + self.assertEqual(e.paper.ledger.positions, []) + self.assertIn("выключены", e.paper.policy.status) + + def test_settings_validation_and_apply(self): + sim = ws.Simulator.__new__(ws.Simulator) + sim.common = ws.load_common() + sim.engines = {"x": self.engine()} + sim.lock = threading.Lock() + self.assertIn("стоп", sim.save_common({"stop_loss_pct": "0"})) + self.assertEqual(sim.save_common({"stake": "250", "auto_tp": True, "mode": "lead"}), "") + ps = sim.engines["x"].paper.settings + self.assertEqual((ps.stake, ps.auto_tp, ps.mode), (250.0, True, "lead")) + self.assertEqual(json.loads(ws.SETTINGS_FILE.read_text(encoding="utf-8"))["stake"], 250.0) + + def test_scanner_view_and_add(self): + au = ws.autoscan_module() + tmp = Path(self.tmp.name) + history = tmp / "h.csv" + conns = tmp / "lead_connections.json" + conns.write_text("[]", encoding="utf-8") + import leadlag as ll + targets = {"NEWC": ll.Target("NEWC", "newc", "MEXC", "NEWC_USDT", 1.0, "solana", "solana", "PoolNew", "T", + "pumpswap", 500), + "OLDC": ll.Target("OLDC", "oldc", "Gate", "OLDC_USDT", 1.0, "solana", "solana", "PoolOld", "T", + "raydium", 500)} + + def res(symbol, verdict): + return ll.LeadResult(symbol, targets[symbol].cex, "solana/pumpswap", 900, 10, 10, 30, {}, 2, 0.0, + {5: 0.2}, {5: 0.7}, 2.6, 60.0, 0, verdict) + + with mock.patch.object(au, "HISTORY_CSV", history), mock.patch.object(ws.lw, "CONNECTIONS_FILE", conns), \ + mock.patch.object(au, "pool_owner", return_value="pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"): + targets["ANSEM"] = ll.Target("ANSEM", "ansem", "MEXC", "ANSEM_USDT", 1.0, "solana", "solana", "PoolAnsem", + "T", "pumpswap", 500) + au.append_history(1, [res("NEWC", au.LEAD_VERDICT), res("OLDC", au.LEAD_VERDICT), + res("ANSEM", "мало движений DEX")], targets, + {"NEWC": "можно добавить (PumpSwap)", "OLDC": "нет: solana/Gate не поддерживается"}, + history) + ansem = {c["symbol"]: c for c in ws.scanner_view([])["coins"]}["ANSEM"] + self.assertTrue(ansem["addable"]) # supported pool + MEXC: addable for a test + self.assertEqual(ansem["leads"], 0) + conn, _ = ws.scanner_add("ANSEM", []) + self.assertEqual(conn["follow_ticker"], "ANSEM_USDT") + conns.write_text("[]", encoding="utf-8") + view = ws.scanner_view([]) + rows = {c["symbol"]: c for c in view["coins"]} + self.assertTrue(rows["NEWC"]["addable"]) + self.assertFalse(rows["OLDC"]["addable"]) + conn, msg = ws.scanner_add("NEWC", []) + self.assertEqual(conn["follow_ticker"], "NEWC_USDT") + self.assertEqual(conn["lead_pool"], "PoolNew") + saved = json.loads(conns.read_text(encoding="utf-8")) + self.assertEqual(saved, [conn]) + self.assertTrue(ws.scanner_view(saved)["coins"][0]["in_list"]) + self.assertIsNone(ws.scanner_add("NEWC", saved)[0]) # already in the list + self.assertIsNone(ws.scanner_add("OLDC", saved)[0]) # Gate futures cannot be traded + + def test_http_api(self): + sim = ws.Simulator.__new__(ws.Simulator) + sim.common = ws.load_common() + e = self.engine() + sim.engines = {e.key: e} + sim.lock = threading.Lock() + ws.SIM = sim + server = ws.ThreadingHTTPServer(("127.0.0.1", 0), ws.Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{server.server_address[1]}" + try: + state = json.loads(urllib.request.urlopen(base + "/api/state").read()) + self.assertEqual(state["coins"][0]["symbol"], "SI") + # a command without the page's header (another site, a script) is refused + req = urllib.request.Request(f"{base}/api/coin/{e.key}/start", data=b"{}", method="POST") + with self.assertRaises(urllib.error.HTTPError) as refused: + urllib.request.urlopen(req) + self.assertEqual(refused.exception.code, 403) + self.assertFalse(e.paper.settings.enabled) + req = urllib.request.Request(f"{base}/api/coin/{e.key}/start", data=b"{}", method="POST", + headers={"X-Sim": "1"}) + self.assertTrue(json.loads(urllib.request.urlopen(req).read())["ok"]) + self.assertTrue(e.paper.settings.enabled) + detail = json.loads(urllib.request.urlopen(f"{base}/api/coin/{e.key}").read()) + self.assertTrue(detail["running"]) + page = urllib.request.urlopen(base + "/").read().decode("utf-8") + self.assertIn("Монеты на проверке", page) + finally: + server.shutdown() + server.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/web_proxy.py b/web_proxy.py new file mode 100644 index 0000000..0f7d5df --- /dev/null +++ b/web_proxy.py @@ -0,0 +1,67 @@ +"""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 urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +LISTEN = ("127.0.0.1", 8765) # local only: real trading and API keys are behind this page +ENGINE = "http://127.0.0.1:8766" +HOP_HEADERS = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-authorization", + "proxy-authenticate", "host", "content-length"} + + +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": + 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} + 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, Proxy) + if sys.stdout: + print(f"Прокси страницы: {LISTEN[0]}:{LISTEN[1]} → {ENGINE}", flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/web_sim.html b/web_sim.html new file mode 100644 index 0000000..439acec --- /dev/null +++ b/web_sim.html @@ -0,0 +1,1453 @@ + + + + + +Симулятор опережения + + + + + + + +
+
+
+

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

+ виртуальные сделки, ордера на биржи не отправляются +
+
+ Реальная торговля + включается для каждой монеты отдельно — кнопкой на странице монеты; её позиции повторяются настоящими рыночными ордерами (сумма = «Ставка» × плечо) + + +
+
+ + · по каждой монете одна реальная сделка за раз: следующая — только когда биржа подтвердила, что прошлая закрыта + +
+
+
+
+ + + +
+
+
+ +
Выберите монету слева
+
+
+ + + diff --git a/web_sim.py b/web_sim.py new file mode 100644 index 0000000..8fa9a07 --- /dev/null +++ b/web_sim.py @@ -0,0 +1,849 @@ +"""Web interface of the lead/vector paper simulator: every coin of the connection list runs at the same time. + + py -3 web_sim.py → http://127.0.0.1:8765 (opens the browser) + +* Common trade settings at the top apply to every coin (web_sim_data/settings.json). +* Each coin (a connection from lead_connections.json: leader = KuCoin futures/spot or a Solana DEX pool, follower = + Bybit/Binance/MEXC futures) has its own feeds, its own paper account and journal (web_sim_data/.json/.csv) + and its own Start/Stop. Stop only forbids new entries: prices, the comparison and the forecast learning go on. +* Coins added later to lead_connections.json (e.g. by meme_matcher/autoscan.py) appear within 30 s. +Nothing is ever sent to an exchange. +""" + +from __future__ import annotations + +import json +import queue +import re +import statistics +import threading +import time +import webbrowser +from collections import deque +from dataclasses import fields +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +import keystore +import lead_window as lw +import live +import real_mirror +import scalp_hint as sh +import scalp_paper as sp + +ROOT = Path(__file__).resolve().parent +MEME_DIR = ROOT / "meme_matcher" + + +def autoscan_module(): + """meme_matcher/autoscan.py (imported on first use: it pulls numpy and the matcher).""" + import sys + if str(MEME_DIR) not in sys.path: + sys.path.insert(0, str(MEME_DIR)) + import autoscan + return autoscan + + +def scanner_view(connections: list[dict]) -> dict: + """Autoscan state and its findings, one row per coin (latest check first), with what can be added.""" + au = autoscan_module() + import csv + try: + with au.HISTORY_CSV.open(encoding="utf-8-sig") as f: + rows = list(csv.DictReader(f, delimiter=";")) + except OSError: + rows = [] + coins: dict[str, dict] = {} + for r in rows: + c = coins.setdefault(r["symbol"], {"symbol": r["symbol"], "checks": 0, "leads": 0}) + c["checks"] += 1 + lead = r["verdict"] == au.LEAD_VERDICT + c["leads"] += lead + c["last_time"], c["verdict"] = r["time"], r["verdict"] # latest check + if lead or "last_lead" not in c: + # the figures shown: of the latest check where the DEX led (or of the latest check at all) + c.update(futures=r["futures"], futures_symbol=r["futures_symbol"], dex_pool=r["dex_pool"], + pool=r["pool_address"], follow=r["follow_t1_t5_pct"], hit=r["hit_t5"], t_stat=r["t_stat"], + lag=r["best_lag_s"], note=r["added_to_simulator"]) + # pool types learned later (Orca, PancakeSwap CLMM…): the old verdict is re-checked on «Добавить» + if "тип пула не читается" in c["note"]: + c["note"] = "" + if lead: + c["last_lead"] = r["time"] + out = [] + for c in coins.values(): + target_like = type("T", (), {"chain": c["dex_pool"].split("/")[0], "cex": c["futures"], "symbol": c["symbol"], + "pool": c["pool"], "cex_symbol": c["futures_symbol"]}) + conn = au.simulator_connection(target_like) + c["in_list"] = bool(conn and any(au.same_connection(conn, x) for x in connections)) + # any coin the simulator can read and trade may be added for a test, not only where the DEX led + c["addable"] = bool(conn) and not c["in_list"] and not c["note"].startswith("нет:") + c["unsupported"] = c["note"] if c["note"].startswith("нет:") else ("" if conn else + "фьючерс или сеть не поддерживаются") + out.append(c) + out.sort(key=lambda c: (-c["leads"], c.get("last_lead", "") == "", c["symbol"])) + try: + log_lines = au.LOG_FILE.read_text(encoding="utf-8").splitlines()[-6:] + except OSError: + log_lines = [] + pid = au.running_pid() + return {"running": bool(pid), "pid": pid, "auto_add": au.load_config()["auto_add"], "coins": out, + "log": log_lines, "cycles": max((int(r["cycle"]) for r in rows), default=0)} + + +def scanner_add(symbol: str, connections: list[dict]) -> tuple[dict | None, str]: + """Connection for a coin the autoscan found leading; added to lead_connections.json.""" + au = autoscan_module() + row = next((c for c in scanner_view(connections)["coins"] if c["symbol"] == symbol), None) + if row is None: + return None, "монета не найдена в истории сканера" + if not row["addable"]: + return None, "уже в списке" if row["in_list"] else (row["unsupported"] or "нельзя добавить") + owner = au.pool_owner(row["pool"]) + if owner not in au.SUPPORTED_OWNERS: + return None, "тип пула не читается симулятором вживую" + target_like = type("T", (), {"chain": "solana", "cex": row["futures"], "symbol": symbol, "pool": row["pool"], + "cex_symbol": row["futures_symbol"]}) + conn = au.simulator_connection(target_like) + lw.unremove_connection(conn) # deleted earlier and now added again by hand + au.add_connection(conn, lw.CONNECTIONS_FILE) + return conn, f"{symbol} добавлена ({au.SUPPORTED_OWNERS[owner]}) — монета остановлена, нажмите «Старт»" +DATA_DIR = ROOT / "web_sim_data" +SETTINGS_FILE = DATA_DIR / "settings.json" +PAGE = ROOT / "web_sim.html" +PORT = 8765 +CONNECTION_FIELDS = set(lw.CONNECTION_KEYS) +COMMON_FIELDS = [f.name for f in fields(sp.PaperSettings) + if f.name in {"mode", "budget", "stake", "leverage", "min_target_pct", "stop_loss_pct", + "max_hold_seconds", "cooldown_ms", "max_positions", "entry_gap_seconds", + "min_confidence", "lead_threshold_pct", "lead_window_ms", "vector_window_seconds", + "vector_min_move_pct", "auto_tp", "auto_tp_share_pct", "auto_tp_learn", + "auto_tp_horizon_seconds", "one_per_tick", "cut_loss", "cut_loss_ticks", + "max_data_age_ms", "require_leader", "leader_min_edge", "auto_stop_pct", + "basis_window_seconds", + "basis_entry_z", "basis_exit_z", "basis_min_gap_pct"}] +SERIES_STEP = 0.5 # chart sampling, s +SERIES_KEEP = 1200 # 10 minutes + + +def coin_key(conn: dict) -> str: + lead = conn["lead_pool"][:8] if conn["lead_market"] == "raydium" else conn["lead_ticker"] + raw = f"{conn['follow_exchange']}_{conn['follow_ticker']}_{conn['lead_market']}_{lead}" + return re.sub(r"[^A-Za-z0-9_]", "", raw) + + +def exchange_links(conn: dict) -> list[dict]: + """Pages of this pair on the exchanges the data comes from: the leader (DEX pool / KuCoin) and the futures.""" + links = [] + if conn["lead_market"] == "raydium": + pool = conn["lead_pool"] + links.append({"label": "DEX пул · DexScreener", "url": f"https://dexscreener.com/solana/{pool}"}) + links.append({"label": "пул · Solscan", "url": f"https://solscan.io/account/{pool}"}) + elif conn["lead_market"] == "spot": + links.append({"label": f"KuCoin спот {conn['lead_ticker']}", + "url": f"https://www.kucoin.com/trade/{conn['lead_ticker']}"}) + else: + links.append({"label": f"KuCoin фьючерс {conn['lead_ticker']}", + "url": f"https://www.kucoin.com/futures/trade/{conn['lead_ticker']}"}) + ticker, exchange = conn["follow_ticker"], conn["follow_exchange"] + url = {"bybit": f"https://www.bybit.com/trade/usdt/{ticker}", + "binance": f"https://www.binance.com/en/futures/{ticker}", + "mexc": f"https://futures.mexc.com/exchange/{ticker}"}.get(exchange) + if url: + name = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC"}[exchange] + links.append({"label": f"{name} фьючерс {ticker}", "url": url}) + return links + + +def coin_symbol(conn: dict) -> str: + return conn["follow_ticker"].replace("_USDT", "").removesuffix("USDT") + + +def load_common() -> dict: + defaults = {k: getattr(sp.PaperSettings(), k) for k in COMMON_FIELDS} + defaults["mode"] = "lead" + try: + saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) + except (OSError, ValueError): + # first start: take the Tk window's settings + try: + saved = json.loads(lw.STATE_FILE.read_text(encoding="utf-8")).get("settings", {}) + except (OSError, ValueError): + saved = {} + if "cooldown_ms" not in saved and "cooldown_seconds" in saved: + saved["cooldown_ms"] = float(saved["cooldown_seconds"]) * 1000 # the pause used to be in seconds + for k in COMMON_FIELDS: + if k in saved: + try: + defaults[k] = type(defaults[k])(saved[k]) + except (TypeError, ValueError): + pass + if defaults["mode"] not in lw.MODES: + defaults["mode"] = "lead" + return defaults + + +def check_common(values: dict) -> tuple[dict, str]: + """Cast and validate settings coming from the page.""" + out = {} + defaults = sp.PaperSettings() + for k in COMMON_FIELDS: + if k not in values: + continue + kind = type(getattr(defaults, k)) + try: + if kind is bool: + out[k] = bool(values[k]) + elif kind is str: + out[k] = str(values[k]) + else: + out[k] = kind(float(str(values[k]).replace(",", "."))) + except (TypeError, ValueError): + return {}, f"поле {k}: нужно число" + merged = dict(load_common(), **out) + numbers = {k: float(v) for k, v in merged.items() if not isinstance(v, (bool, str))} + numbers.setdefault("min_confidence", 0.0) + problem = lw.validate(numbers) + if not problem and merged.get("mode") not in lw.MODES: + problem = "неизвестный режим" + if not problem and int(merged.get("cut_loss_ticks", 1)) < 1: + problem = "минус для закрытия — не меньше 1 шага" + if not problem and not 0 <= float(merged.get("auto_stop_pct", 20)) <= 100: + problem = "автостоп — от 0 до 100% (0 — выключен)" + return (out, "") if not problem else ({}, problem) + + +class Engine: + """One coin: leader + follower feeds, a paper trader and a price history for the chart.""" + + def __init__(self, conn: dict, common: dict) -> None: + self.conn = dict(conn) + self.key = coin_key(conn) + self.symbol = coin_symbol(conn) + self.name = lw.connection_name(conn) + DATA_DIR.mkdir(exist_ok=True) + settings = sp.PaperSettings(mode=common.get("mode", "lead"), enabled=False) + state_file = DATA_DIR / f"{self.key}.json" + new_account = not state_file.exists() + self.paper = sp.PaperTrader(settings, sh.HintSettings(), state_file, DATA_DIR / f"{self.key}.csv") + enabled = self.paper.settings.enabled # the coin's own Start/Stop survives restarts + self.apply(common, initial=True) + self.paper.settings.enabled = enabled + if new_account: + self.paper.ledger.balance = self.paper.settings.budget + for k in CONNECTION_FIELDS: + setattr(self.paper.settings, k, conn[k]) + self.paper.policy = self.paper._make_policy() + # real trading: the same orders on the coin's futures exchange while the tab's real mode is on + ps = self.paper.settings + self.mirror = real_mirror.FuturesMirror(self.key, self.symbol, ps.follow_exchange, ps.follow_ticker) + self.paper.ledger.hooks.append(self.mirror.hook) + self.paper.gate = self.mirror.gate # one real trade at a time, confirmed closed + self.mirror.on_failed_open = lambda uid: self.close(uid, "реальный ордер не прошёл") + self.mirror.ping = lambda ex=ps.follow_exchange: ping_for(ex) # no entry while the ping is above the limit + self.lock = threading.RLock() + self.events: queue.Queue = queue.Queue() + self.book = sh.OrderBook() + self.tick = 0.0 + self.leader: tuple[float, float] | None = None + self.last_leader = self.last_follower = 0.0 + self.lead_series: deque[tuple[float, float]] = deque(maxlen=SERIES_KEEP) + self.follow_series: deque[tuple[float, float]] = deque(maxlen=SERIES_KEEP) + self.lat_lead: deque[float] = deque(maxlen=200) + self.lat_follow: deque[float] = deque(maxlen=200) + self.lead_status = "подключаюсь…" + self.follow_status = "подключаюсь…" + self.message = "" + self.auto_stop = "" # why the pair was stopped automatically (cleared by Start) + self.checked_at = None # time of the last leader measurement looked at + self.feeds: list = [] + self.stopped = threading.Event() + self.thread = threading.Thread(target=self._pump, daemon=True) + + # --- lifecycle --------------------------------------------------------------------------- + def start(self) -> None: + ps = self.paper.settings + if ps.follow_exchange == "mexc": + self.tick, size = sh.mexc_contract(ps.follow_ticker) + follower = sh.MexcFeed(ps.follow_ticker, self.events, size) + elif ps.follow_exchange == "binance": + self.tick = sh.binance_tick(ps.follow_ticker) + follower = sh.BinanceFeed(ps.follow_ticker, self.events) + else: + self.tick = sh.bybit_tick(ps.follow_ticker) + follower = sh.BybitFeed(ps.follow_ticker, self.events) + if ps.lead_market == "raydium": + leader = sh.RaydiumFeed(ps.lead_pool, self.events) + else: + leader = sh.KucoinFeed(ps.lead_ticker, self.events, spot=ps.lead_market == "spot") + self.feeds = [follower, leader] + for feed in self.feeds: + feed.start() + self.thread.start() + + def shutdown(self) -> None: + self.stopped.set() + for feed in self.feeds: + feed.stop() + with self.lock: + self.paper.ledger.save() + + def apply(self, common: dict, initial: bool = False) -> None: + ps = self.paper.settings + lock = self.lock if not initial else threading.RLock() + with lock: + mode = common.get("mode", ps.mode) + for k, v in common.items(): + if k != "mode": + setattr(ps, k, v) + if mode != ps.mode: + if not initial: + self.paper.close_now(self.book, time.time(), "смена режима") + self.paper.set_mode(mode) + self.paper.ledger.save() + + def set_trading(self, on: bool) -> None: + with self.lock: + self.paper.settings.enabled = on + self.paper.ledger.save() + if on: + self.auto_stop = "" + self.message = ("Старт: новые сделки открываются" if on else + "Стоп: новые сделки не открываются; открытые закроются по тейку, стопу или времени") + + def reset(self) -> str: + """Clear this coin's statistics: open positions dropped, journal emptied, balance back to the budget. + Start/Stop, prices, the leader check and the forecast learning are kept.""" + with self.lock: + enabled = self.paper.settings.enabled + self.paper.ledger.reset() # positions, trades, CSV; balance = budget + self.mirror.reset_stats() # real figures start again from now too + self.paper.settings.enabled = enabled + self.paper.ledger.save() + self.paper.message = "" + self.message = "Статистика сброшена" + return self.message + + def close(self, uid: int | None, reason: str = "вручную") -> str: + """Close one position (uid) or all of them at the follower's current best price.""" + with self.lock: + best_bid, best_ask = self.book.best() + closed = 0 + for pos in list(self.paper.ledger.positions): + if uid is not None and pos.uid != uid: + continue + price = (best_bid if pos.side == "LONG" else best_ask) or pos.entry + self.paper.close(price, time.time(), reason, self.paper.policy.taker, pos=pos) + closed += 1 + return f"закрыто позиций: {closed}" + + def _auto_stop(self, now: float) -> None: + """On every new leader measurement: stop the pair when the futures (CEX) lead the leader by + `auto_stop_pct` % or more. Prices, the comparison and open positions' exits go on.""" + pol, ps = self.paper.policy, self.paper.settings + lead = getattr(pol, "leadership", {}) + at = lead.get("at") + if at is None or at == self.checked_at: + return + self.checked_at = at + pct = lead.get("pct") + if not ps.enabled or ps.auto_stop_pct <= 0 or pct is None or -pct < ps.auto_stop_pct: + return + ps.enabled = False + self.paper.ledger.save() + self.auto_stop = (f"автостоп в {time.strftime('%H:%M:%S', time.gmtime(now + 3 * 3600))} МСК: " + f"{pol.F} опережает {pol.L} на {-pct:.0f}% (порог {ps.auto_stop_pct:g}%)") + self.message = self.auto_stop + " — новые сделки остановлены, открытые закроются сами" + + # --- data -------------------------------------------------------------------------------- + def _pump(self) -> None: + next_sample = 0.0 + while not self.stopped.is_set(): + try: + kind, data = self.events.get(timeout=0.1) + except queue.Empty: + kind, data = None, None + now = time.time() + with self.lock: + if kind == "book_snapshot": + self.book.apply_snapshot(data) + self.last_follower = now + self.paper.on_book(now, self.book, self.tick) + elif kind == "book_update": + self.book.apply_updates(data) + self.last_follower = now + self.paper.on_book(now, self.book, self.tick) + elif kind == "trades": + for raw in data: + try: + trade = sh.Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side"))) + except (KeyError, TypeError, ValueError): + continue + self.paper.on_trade(trade) + elif kind == "leader": + self.leader = data + self.last_leader = now + self.paper.on_leader(now, data[0], data[1]) + elif kind == "latency": + self.lat_follow.append(float(data)) + elif kind == "leader_latency": + self.lat_lead.append(float(data)) + elif kind == "status": + self.follow_status = data + elif kind == "leader_status": + self.lead_status = data + self._auto_stop(now) + if now >= next_sample: + next_sample = now + SERIES_STEP + bid, ask = self.book.best() + if bid and ask: + self.follow_series.append((round(now, 2), (bid + ask) / 2)) + if self.leader: + self.lead_series.append((round(now, 2), (self.leader[0] + self.leader[1]) / 2)) + + # --- views ------------------------------------------------------------------------------- + def summary(self) -> dict: + with self.lock: + led = self.paper.ledger + trades = led.trades + wins = sum(t.net_usd > 0 for t in trades) + bid, ask = self.book.best() + pol = self.paper.policy + now = time.time() + return { + "key": self.key, "symbol": self.symbol, "name": self.name, + "leader": pol.L, "follower": pol.F, "follow_ticker": self.conn["follow_ticker"], + "running": self.paper.settings.enabled, + "price": (bid + ask) / 2 if bid and ask else None, + "lead_price": sum(self.leader) / 2 if self.leader else None, + "signal": getattr(pol, "signal", 0.0), "confidence": getattr(pol, "conf", 0.0), + "open": len(led.positions), "trades": len(trades), "wins": wins, + "net": sum(t.net_usd for t in trades), "fees": sum(t.fee_usd for t in trades), + "unrealized": self.paper.unrealized(self.book), "balance": led.balance, + "leadership": getattr(pol, "leadership", {}), "leader_block": pol.leader_block() + if hasattr(pol, "leader_block") else "", "min_edge": self.paper.settings.leader_min_edge, + "now": now, "auto_stop": self.auto_stop, + "grid_minutes": len(getattr(pol, "grid", ())) * 0.5 / 60, + "live": (now - self.last_follower) < 5 and (now - self.last_leader) < 120, + "real": {k: v for k, v in self.mirror.view().items() if k != "trade_list"}, + "exchange": self.paper.settings.follow_exchange, + } + + def detail(self, since: float = 0.0) -> dict: + with self.lock: + d = self.summary() + pol = self.paper.policy + bid, ask = self.book.best() + now = time.time() + positions = [] + for pos in reversed(self.paper.ledger.positions): + price = bid if pos.side == "LONG" else ask + pnl = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty if price else 0.0 + positions.append({"uid": pos.uid, "side": pos.side, "qty": pos.qty, "usd": pos.entry * pos.qty, + "entry": pos.entry, "target": pos.target, "stop": pos.stop, + "age": now - pos.opened, "pnl": pnl, "pct": pnl / (pos.entry * pos.qty) * 100, + "why": pos.regime, "opened": pos.opened}) + trades = [{"closed": t.closed_utc, "side": t.side, "usd": t.notional_usd, "entry": t.entry, + "exit": t.exit, "pct": t.pct, "net": t.net_usd, "fee": t.fee_usd, "reason": t.reason, + "hold": t.hold_seconds, "why": t.regime} for t in reversed(self.paper.ledger.trades[-300:])] + real_uids = {p["uid"] for p in d["real"]["positions"]} + for p in positions: + p["real"] = p["uid"] in real_uids + d.update({ + "real_trades": self.mirror.view()["trade_list"], + "status": pol.status, "message": self.paper.message or self.message, + "lead_status": self.lead_status, "follow_status": self.follow_status, + "lead_latency": statistics.median(self.lat_lead) if len(self.lat_lead) >= 5 else None, + "follow_latency": statistics.median(self.lat_follow) if len(self.lat_follow) >= 5 else None, + "bid": bid, "ask": ask, "forecast": getattr(pol, "forecast", 0.0), + "lead_series": [p for p in self.lead_series if p[0] > since], + "follow_series": [p for p in self.follow_series if p[0] > since], + "positions": positions, "closed": trades, "now": now, "links": exchange_links(self.conn), + }) + return d + + +class Simulator: + def __init__(self) -> None: + self.common = load_common() + self.engines: dict[str, Engine] = {} + self.lock = threading.Lock() + self.sync_connections() + threading.Thread(target=self._watch, daemon=True).start() + + def sync_connections(self) -> None: + """Start an engine for every connection in the list (new ones appear; removal is only via remove()).""" + for conn in lw.load_connections(): + key = coin_key(conn) + with self.lock: + if key in self.engines: + continue + engine = Engine(conn, self.common) + self.engines[key] = engine + engine.start() + + def remove(self, key: str) -> str: + """Delete a pair: close its open positions, stop all its data feeds and forget the connection.""" + with self.lock: + engine = self.engines.get(key) + if engine is None: + return "нет такой монеты" + lw.remove_connection(engine.conn) + del self.engines[key] + with engine.lock: + engine.paper.settings.enabled = False + closed = len(engine.paper.ledger.positions) + engine.close(None) # open positions at the current price + engine.shutdown() # feeds (exchange + DEX/KuCoin) and the pump thread stop + return f"{engine.name} удалена, сбор данных остановлен" + (f", закрыто позиций: {closed}" if closed else "") + + def _watch(self) -> None: + while True: + time.sleep(30) + try: + self.sync_connections() + except Exception: + pass + + def save_common(self, values: dict) -> str: + clean, problem = check_common(values) + if problem: + return problem + self.common.update(clean) + DATA_DIR.mkdir(exist_ok=True) + SETTINGS_FILE.write_text(json.dumps(self.common, ensure_ascii=False, indent=2), encoding="utf-8") + for engine in list(self.engines.values()): + engine.apply(clean) + return "" + + def state(self) -> dict: + return {"settings": self.common, "modes": lw.MODES, + # pairs enabled for trades first, then by name + "coins": sorted((e.summary() for e in self.engines.values()), + key=lambda c: (not c["running"], c["symbol"], c["name"]))} + + +SIM: Simulator | None = None +ARB: dict = {} # market ("spot" / "futures") → arb.ArbScanner, started on the first request for it + + +def arb_view(transfer_min: float | None = None, market: str = "spot") -> dict: + market = market if market in ("spot", "futures") else "spot" + if market not in ARB: + import arb + ARB[market] = arb.ArbScanner(market) + return ARB[market].view(transfer_min) + + +BALANCES: dict = {} # exchange → {"values": {...}, "time": t} or {"error": ..., "time": t}: from the account itself + + +LATENCY: dict = {} # API host → last round trip, ms (warm-up pings) + + +def apply_real_fee(exchange: str, pct: float) -> None: + """The exchange's measured taker rate replaces the paper one (entry and exit) for all its coins.""" + if exchange in sp.FOLLOW_FEES and pct > 0: + sp.FOLLOW_FEES[exchange] = (round(pct, 5), round(pct, 5)) + + +PING_SAMPLES: dict = {} # host → deque of (time, ms) +FUTURES_HOST = {"bybit": "api.bybit.com", "binance": "fapi.binance.com", "mexc": "contract.mexc.com", + "htx": "api.hbdm.com", "gate": "api.gateio.ws"} + + +def ping_for(exchange: str) -> float | None: + """Current round trip to the exchange's futures API: median of the last three pings, None when stale.""" + samples = PING_SAMPLES.get(FUTURES_HOST.get(exchange, "")) + if not samples or time.time() - samples[-1][0] > 10: + return None + return statistics.median(ms for _, ms in samples) + + +def warm_loop() -> None: + """Keeps a ready HTTPS connection to every exchange with keys (a real order skips the handshake) and measures + the ping every 2 s — the entry check uses it.""" + while True: + try: + for host, ms in live.warm_up([ex for ex in keystore.EXCHANGES if keystore.get(ex) is not None]).items(): + PING_SAMPLES.setdefault(host, deque(maxlen=3)).append((time.time(), ms)) + LATENCY[host] = statistics.median(v for _, v in PING_SAMPLES[host]) + except Exception: + pass + time.sleep(2) + + +def balances_loop() -> None: + """Account balances of every exchange with saved keys, every 10 s (shown next to the real trading figures); + a failed read keeps the last good figures and says how old they are.""" + while True: + for ex in keystore.EXCHANGES: + if keystore.get(ex) is None: + BALANCES.pop(ex, None) + continue + try: + c = live.client(ex) + values = c.balances() + try: # what is free for a new trade (the spot–futures tabs check the trade amount against it) + free = c.usdt_free() + except Exception: + free = (BALANCES.get(ex) or {}).get("free") + try: # the coins on spot: the stock a spot–spot trade sells from + coins = c.spot_coins() + except Exception: + coins = (BALANCES.get(ex) or {}).get("coins") + BALANCES[ex] = {"values": values, "free": free, "coins": coins, + "unified": bool(getattr(c, "unified", False)), "time": time.time()} + except Exception as exc: + old = BALANCES.get(ex) or {} + BALANCES[ex] = {**({"values": old["values"], "time": old["time"]} if "values" in old else {"time": 0}), + "free": old.get("free"), "coins": old.get("coins"), + "unified": old.get("unified", False), "error": str(exc)} + time.sleep(10) + + +BASIS: dict = {} # venue ("bybit") → basis.BasisEngine (spot–futures), started on the first request for it +BASIS_LOCK = threading.Lock() + + +def basis_engine(venue: str): + """«Арбитраж»: "cross" — the simulation, "cross_real" — real trading; both search every link (between the + exchanges, inside one exchange, spot–spot), each is started and stopped by itself. The real one takes the + simulation's prices. (The single-exchange spot–futures engines are gone: their positions moved here.)""" + if venue not in ("cross", "cross_real"): + return None + with BASIS_LOCK: + if "cross" not in BASIS: + import cross + BASIS["cross"] = cross.CrossEngine() + BASIS["cross"].balances = BALANCES # the accounts of every exchange with keys (read every 10 s) + if venue == "cross_real" and "cross_real" not in BASIS: + import cross + BASIS["cross_real"] = cross.CrossEngine(real=True, leader=BASIS["cross"]) + BASIS["cross_real"].balances = BALANCES + return BASIS[venue] + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args) -> None: # quiet + pass + + def _send(self, code: int, body: bytes, kind: str = "application/json") -> None: + self.send_response(code) + self.send_header("Content-Type", f"{kind}; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _json(self, data, code: int = 200) -> None: + self._send(code, json.dumps(data, ensure_ascii=False).encode("utf-8")) + + def do_GET(self) -> None: + path, _, query = self.path.partition("?") + if path in ("/", "/index.html"): + self._send(200, PAGE.read_bytes(), "text/html") + elif path == "/api/state": + self._json(SIM.state()) + elif path == "/api/arb": + m = re.search(r"transfer=([0-9.]+)", query) + mk = re.search(r"market=(spot|futures)", query) + self._json(arb_view(float(m.group(1)) if m else None, mk.group(1) if mk else "spot")) + elif path == "/api/real": + basis_real = {k: getattr(e.settings, "real", False) for k, e in BASIS.items()} + self._json({"keys": keystore.summary(), "simulator": real_mirror.load_settings(), "basis": basis_real, + "balances": BALANCES, "latency": LATENCY, + "journal": list(reversed(real_mirror.RECENT[-150:]))}) + elif path == "/api/basis": + m = re.search(r"ex=([a-z_]+)", query) + engine = basis_engine(m.group(1) if m else "cross") + if engine is None: + self._json({"error": "эта биржа пока не подключена"}, 404) + else: + self._json(engine.view()) + elif path == "/api/scanner": + try: + self._json(scanner_view(lw.load_connections())) + except Exception as exc: + self._json({"error": f"сканер недоступен: {exc}"}, 500) + elif path.startswith("/api/coin/"): + engine = SIM.engines.get(path.split("/")[3]) + if engine is None: + self._json({"error": "нет такой монеты"}, 404) + return + since = 0.0 + m = re.search(r"since=([0-9.]+)", query) + if m: + since = float(m.group(1)) + self._json(engine.detail(since)) + else: + self._json({"error": "not found"}, 404) + + def do_POST(self) -> None: + if not local_request(self): + self._json({"error": "команды принимаются только со страницы симулятора на этом компьютере"}, 403) + return + length = int(self.headers.get("Content-Length") or 0) + try: + body = json.loads(self.rfile.read(length) or b"{}") + except ValueError: + body = {} + parts = self.path.strip("/").split("/") + if parts == ["api", "settings"]: + problem = SIM.save_common(body) + self._json({"ok": not problem, "error": problem}) + return + if parts[:3] == ["api", "real", "simulator"]: + problem = real_mirror.save_settings(body) + self._json({"ok": not problem, "error": problem}) + return + if parts[:3] == ["api", "real", "keys"] and len(parts) >= 4: + ex = parts[3] + if ex not in keystore.EXCHANGES: + self._json({"ok": False, "error": "неизвестная биржа"}, 404) + elif len(parts) == 4: + problem = keystore.set_keys(ex, str(body.get("api_key", "")), str(body.get("api_secret", ""))) + self._json({"ok": not problem, "error": problem}) + elif parts[4] == "delete": + keystore.delete_keys(ex) + self._json({"ok": True}) + elif parts[4] == "check": + try: + self._json({"ok": True, "balances": live.client(ex).balances()}) + except live.LiveError as exc: + self._json({"ok": False, "error": str(exc)}) + else: + self._json({"error": "unknown action"}, 404) + return + if parts[:2] == ["api", "arb"] and len(parts) == 4 and parts[3] in ("start", "stop"): + market = parts[2] if parts[2] in ("spot", "futures") else "spot" + arb_view(None, market) # make sure the scanner exists + ARB[market].set_paused(parts[3] == "stop") + self._json({"ok": True, "paused": ARB[market].paused}) + return + if parts[:2] == ["api", "basis"] and len(parts) >= 4: + engine = basis_engine(parts[2]) + if engine is None: + self._json({"error": "эта биржа пока не подключена"}, 404) + elif parts[3] == "settings": + problem = engine.set_settings(body) + self._json({"ok": not problem, "error": problem}) + elif parts[3] == "close": + uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None + self._json({"ok": True, "message": engine.close(uid)}) + elif parts[3] == "reset": + self._json({"ok": True, "message": engine.reset()}) + elif parts[3] == "adopt": + try: + price = float(body["price"]) if body.get("price") not in (None, "") else None + fee = float(body["fee"]) if body.get("fee") not in (None, "") else None + except (TypeError, ValueError): + self._json({"ok": False, "error": "неверная цена или комиссия"}) + return + if not hasattr(engine, "adopt"): + self._json({"ok": False, "message": "в этом режиме нельзя"}) + return + message = engine.adopt(str(body.get("base", "")), price, fee) + self._json({"ok": "подхвачено" in message, "message": message}) + else: + self._json({"error": "unknown action"}, 404) + return + if parts[:2] == ["api", "scanner"] and len(parts) == 3: + au = autoscan_module() + action = parts[2] + if action == "start": + if not au.running_pid(): + au.start_background(float(body.get("minutes", 15)), int(body.get("coins", 12))) + self._json({"ok": True}) + elif action == "stop": + au.stop_background() + self._json({"ok": True}) + elif action == "config": + cfg = au.load_config() + cfg["auto_add"] = bool(body.get("auto_add", cfg["auto_add"])) + au.save_config(cfg) + self._json({"ok": True}) + elif action == "add": + conn, message = scanner_add(str(body.get("symbol", "")), lw.load_connections()) + if conn: + SIM.sync_connections() + self._json({"ok": True, "message": message, "key": coin_key(conn)}) + else: + self._json({"ok": False, "error": message}) + else: + self._json({"error": "unknown action"}, 404) + return + if len(parts) >= 4 and parts[:2] == ["api", "coin"]: + engine = SIM.engines.get(parts[2]) + if engine is None: + self._json({"error": "нет такой монеты"}, 404) + return + action = parts[3] + if action == "start": + engine.set_trading(True) + self._json({"ok": True}) + elif action == "stop": + engine.set_trading(False) + self._json({"ok": True}) + elif action == "reset": + self._json({"ok": True, "message": engine.reset()}) + elif action == "remove": + self._json({"ok": True, "message": SIM.remove(parts[2])}) + elif action == "close": + uid = int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else None + self._json({"ok": True, "message": engine.close(uid)}) + else: + self._json({"error": "unknown action"}, 404) + return + self._json({"error": "not found"}, 404) + + +HOST = "127.0.0.1" # this PC only: the page switches real trading and holds exchange API keys +BACKEND_PORT = 8766 # --backend: engine on 127.0.0.1:8766 behind web_proxy.py (127.0.0.1:8765, VPN-excluded) +LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"} + + +def local_request(handler) -> bool: + """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" + + +def main() -> None: + import sys + global SIM + # --backend: only for this PC on BACKEND_PORT, the public page is served by web_proxy.py (outside the VPN) + if "--backend" in sys.argv: + host, port = "127.0.0.1", BACKEND_PORT + else: + host, port = ("127.0.0.1" if "--local" in sys.argv else HOST), PORT + real_mirror.load_recent() + import minorder + minorder.AUTOLOAD = True # the exchanges' smallest orders (spot and perp), loaded and renewed hourly + # the paper model pays what the exchange really charges (measured from the real fills), not the textbook rate + real_mirror.FEE_LISTENERS.append(apply_real_fee) + for ex, pct in (real_mirror.load_settings().get("fees") or {}).items(): + apply_real_fee(ex, pct) + threading.Thread(target=balances_loop, daemon=True).start() + threading.Thread(target=warm_loop, daemon=True).start() + SIM = Simulator() + # «Арбитраж»: the simulation and the real engine run from the start (open real positions are watched at once) + basis_engine("cross") + basis_engine("cross_real") + server = ThreadingHTTPServer((host, port), Handler) + url = f"http://127.0.0.1:{PORT}" + print(f"Симулятор: {url} (движок слушает {host}:{port}, монет: {len(SIM.engines)})", flush=True) + threading.Timer(1.0, lambda: webbrowser.open(url)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + for engine in SIM.engines.values(): + engine.shutdown() + + +if __name__ == "__main__": + main() diff --git a/web_sim_autostart.vbs b/web_sim_autostart.vbs new file mode 100644 index 0000000..f602024 --- /dev/null +++ b/web_sim_autostart.vbs @@ -0,0 +1,26 @@ +' Starts the web simulator without windows (Windows autostart: shortcut in the Startup folder). +' page - pythonw.exe web_proxy.py (0.0.0.0:8765, public; pythonw.exe excluded from the VPN) +' engine - python.exe web_sim.py --backend via web_sim_service.bat (127.0.0.1:8766, restarted if it stops) +' A part that is already running is not started twice. +Set sh = CreateObject("WScript.Shell") +Set fso = CreateObject("Scripting.FileSystemObject") +dir = fso.GetParentFolderName(WScript.ScriptFullName) +sh.CurrentDirectory = dir + +Function Running(pattern) + Running = False + Set procs = GetObject("winmgmts:").ExecQuery("SELECT CommandLine FROM Win32_Process") + For Each p In procs + If Not IsNull(p.CommandLine) Then + If InStr(1, p.CommandLine, pattern, vbTextCompare) > 0 Then Running = True + End If + Next +End Function + +' the program's own environment (.venv, made by УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat) when there is one +pyw = "pyw -3" +If fso.FileExists(dir & "\.venv\Scripts\pythonw.exe") Then pyw = """" & dir & "\.venv\Scripts\pythonw.exe""" +If Not Running("web_proxy.py") Then sh.Run pyw & " """ & dir & "\web_proxy.py""", 0, False +If Not Running("web_sim_service.bat") And Not Running("web_sim.py") Then + sh.Run "cmd /c """ & dir & "\web_sim_service.bat""", 0, False +End If diff --git a/web_sim_service.bat b/web_sim_service.bat new file mode 100644 index 0000000..c1b713e --- /dev/null +++ b/web_sim_service.bat @@ -0,0 +1,16 @@ +@echo off +rem Engine of the web simulator, restarted automatically if it stops (crash, network loss at boot, manual kill). +rem Started hidden by web_sim_autostart.vbs; output goes to web_sim_data\backend.log. +cd /d "%~dp0" +set PYTHONIOENCODING=utf-8 +if not exist web_sim_data mkdir web_sim_data +:loop +echo [%date% %time%] start >> web_sim_data\backend.log +if exist ".venv\Scripts\python.exe" ( + ".venv\Scripts\python.exe" web_sim.py --backend >> web_sim_data\backend.log 2>&1 +) else ( + py -3 web_sim.py --backend >> web_sim_data\backend.log 2>&1 +) +echo [%date% %time%] stopped, restart in 5 s >> web_sim_data\backend.log +timeout /t 5 /nobreak >nul +goto loop diff --git a/ЗАПУСТИТЬ_СЕРВЕР.bat b/ЗАПУСТИТЬ_СЕРВЕР.bat new file mode 100644 index 0000000..c38d464 --- /dev/null +++ b/ЗАПУСТИТЬ_СЕРВЕР.bat @@ -0,0 +1,6 @@ +@echo off +rem Starts the simulator server in the background (no windows) and opens the page http://127.0.0.1:8765 +rem Installs Python and the libraries first if they are missing. See server_control.ps1. +cd /d "%~dp0" +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0server_control.ps1" start +if errorlevel 1 (pause) else (timeout /t 4 >nul) \ No newline at end of file diff --git a/ОСТАНОВИТЬ_СЕРВЕР.bat b/ОСТАНОВИТЬ_СЕРВЕР.bat new file mode 100644 index 0000000..5c9b886 --- /dev/null +++ b/ОСТАНОВИТЬ_СЕРВЕР.bat @@ -0,0 +1,5 @@ +@echo off +rem Stops the simulator server: the page, the engine and its restart loop. See server_control.ps1. +cd /d "%~dp0" +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0server_control.ps1" stop +pause \ No newline at end of file diff --git a/ПРОЧТИ_МЕНЯ.txt b/ПРОЧТИ_МЕНЯ.txt new file mode 100644 index 0000000..68983b0 --- /dev/null +++ b/ПРОЧТИ_МЕНЯ.txt @@ -0,0 +1,52 @@ +СИМУЛЯТОР ОПЕРЕЖЕНИЯ / АРБИТРАЖ +================================ + +Что нужно: Windows 10 или 11 и интернет. + +ПЕРВЫЙ ЗАПУСК +1. Распакуйте архив в любую папку (лучше без кириллицы и пробелов в пути, например C:\Simulator). +2. Дважды щёлкните «ЗАПУСТИТЬ_СЕРВЕР.bat». + - Если Python не установлен, файл поставит Python 3.12 сам (через winget, только для вашего пользователя). + Если появится сообщение «закройте окно и запустите ещё раз» — так и сделайте. + - Нужные библиотеки ставятся в папку .venv внутри программы, в систему ничего не ставится. +3. Сервер запускается в фоне, без окон, и открывается страница http://127.0.0.1:8765 . + Если движок программы упадёт, он сам перезапустится через 5 секунд. + +ЗАПУСК И ОСТАНОВКА +- «ЗАПУСТИТЬ_СЕРВЕР.bat» — запустить сервер (если уже работает — просто откроет страницу). +- «ОСТАНОВИТЬ_СЕРВЕР.bat» — остановить сервер полностью. Если в этот момент закрывается реальная сделка, + файл спросит, точно ли останавливать. +- «УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat» — запуск с чёрным окном движка (видно, что происходит); закрыли окно — + движок остановлен. + +ВКЛАДКИ +- «Симулятор» — опережение: ведущая биржа → ставки на фьючерсах. +- «Арбитраж» — поиск расхождений цен между биржами и внутри бирж: спот → фьючерс между биржами, + спот → фьючерс на одной бирже, спот → спот между биржами. Внутри две вкладки: + «Симуляция» (бумажные сделки) и «Реальная торговля» — у каждой своя кнопка «Старт / Стоп». + В карточке «Биржи» — балансы, комиссии, лимит сделок и включение каждой биржи. +- «Реальная торговля · API-ключи» — ключи бирж и журнал реальных ордеров. +- Кнопка «Калькулятор бюджета» справа вверху — сколько денег держать на биржах. + +ВАЖНО +- Из России биржи (Bybit, Binance, MEXC…) без VPN часто не отвечают — тогда на странице не будет цен. + Включите VPN для программы. +- Сайт открывается только на этом компьютере (127.0.0.1), снаружи он недоступен — так задумано. +- Реальные ордера отправляются ТОЛЬКО если вы сами сохраните API-ключи во вкладке + «Реальная торговля · API-ключи» и нажмёте «Старт» во вкладке «Арбитраж → Реальная торговля» + (или включите реальный режим монеты во вкладке «Симулятор»). + Ключи создавайте только с правами на торговлю, без права вывода средств. Ключи шифруются средствами + Windows и читаются только вашей учётной записью на этом компьютере. +- Спот → спот в реальном режиме продаёт монету из запаса, который лежит на бирже продажи: без запаса + такие сделки не открываются. Деньги и монеты между биржами программа не переводит. +- Реальная торговля — на ваш риск: начинайте с минимальных сумм. + +АВТОЗАПУСК ВМЕСТЕ С WINDOWS (по желанию) +Положите ярлык на файл «web_sim_autostart.vbs» в папку автозагрузки +(Win+R → shell:startup → Enter). Программа будет запускаться без окон. + +ЕСЛИ ЧТО-ТО НЕ РАБОТАЕТ +- Страница не открывается — посмотрите журнал движка web_sim_data\backend.log + (или запустите «УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat», чтобы видеть окно движка). +- Нет цен — проверьте VPN. +- Удалить программу — остановите сервер и удалите папку (и ярлык из автозагрузки, если ставили). diff --git a/УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat b/УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat new file mode 100644 index 0000000..f8cc395 --- /dev/null +++ b/УСТАНОВИТЬ_И_ЗАПУСТИТЬ.bat @@ -0,0 +1,6 @@ +@echo off +rem Installs what the simulator needs and starts it: see setup.ps1 (this file only calls it). +rem /install-only - install, do not start. +cd /d "%~dp0" +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0setup.ps1" %* +if errorlevel 1 pause