This commit is contained in:
listik committed 2026-10-22 20:19:52 +03:00
commit 5c6b0dc54a
62 files changed
+28141

No files matched your search

+240
View File
@@ -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/<coin>.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.
+945
View File
@@ -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
+42
View File
@@ -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
}
}
+576
View File
@@ -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}
+1334
View File
File diff suppressed because it is too large. Load diff
+260
View File
@@ -0,0 +1,260 @@
"""Small signed Bybit V5 client used by the optional live-trading mode.
API credentials are held only in memory and are never written to disk or logs.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from decimal import Decimal, ROUND_DOWN, ROUND_UP
class BybitAPIError(RuntimeError):
pass
class BybitLiveClient:
def __init__(self, api_key: str, api_secret: str, testnet: bool = True) -> None:
if not api_key.strip() or not api_secret.strip():
raise ValueError("Введите API key и API secret")
self.api_key = api_key.strip()
self._secret = api_secret.strip().encode("utf-8")
self.testnet = testnet
self.base_url = "https://api-testnet.bybit.com" if testnet else "https://api.bybit.com"
self.recv_window = "5000"
def _request(self, method: str, path: str, params: dict | None = None) -> dict:
params = params or {}
timestamp = str(int(time.time() * 1000))
if method == "GET":
query = urllib.parse.urlencode(sorted((key, str(value)) for key, value in params.items()))
body = ""
payload = None
else:
query = ""
body = json.dumps(params, separators=(",", ":"), ensure_ascii=False)
payload = body.encode("utf-8")
signature_input = f"{timestamp}{self.api_key}{self.recv_window}{query or body}"
signature = hmac.new(self._secret, signature_input.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
"X-BAPI-API-KEY": self.api_key,
"X-BAPI-SIGN": signature,
"X-BAPI-TIMESTAMP": timestamp,
"X-BAPI-RECV-WINDOW": self.recv_window,
"Content-Type": "application/json",
"User-Agent": "RealtimePaperSimulator/1.0",
}
url = f"{self.base_url}{path}" + (f"?{query}" if query else "")
request = urllib.request.Request(url, data=payload, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=10) as response:
result = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
raw_details = exc.read()
try:
details = json.loads(raw_details.decode("utf-8"))
except Exception:
details = {}
# Keep the useful Bybit error code and request context, but never
# include request headers, signatures, API keys, or secrets.
ret_code = details.get("retCode") if isinstance(details, dict) else None
ret_msg = details.get("retMsg") if isinstance(details, dict) else None
endpoint = "тестовой сети" if self.testnet else "основной сети"
context = f"{method} {path} ({endpoint})"
if ret_code is not None:
message = f"Bybit API HTTP {exc.code}, retCode {ret_code}: {ret_msg or 'ошибка запроса'}"
hints = {
10002: "Проверьте синхронизацию часов Windows.",
10003: "Ключ не подходит к выбранному домену: сверьте Testnet/Mainnet с сетью, где создан API-ключ.",
10004: "Bybit отклонил подпись. Проверьте API Secret и отсутствие лишних пробелов при вставке.",
10005: "Проверьте права API-ключа для чтения аккаунта и торговли контрактами.",
10009: "Bybit ограничил доступ к API для региона аккаунта или подключения.",
10010: "IP компьютера не совпадает с IP, разрешённым в настройках API-ключа.",
}
if ret_code in hints:
message += f" {hints[ret_code]}"
elif exc.code == 401:
message = (
f"Bybit вернул HTTP 401 для {context}: запрос авторизации отклонён. "
"Проверьте, что API-ключ создан в выбранной сети (Testnet/Mainnet), "
"ключ и секрет скопированы полностью без пробелов, а IP компьютера "
"разрешён в настройках ключа. Секрет приложения не выводит."
)
else:
message = f"Bybit API HTTP {exc.code} для {context}"
raise BybitAPIError(message) from None
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
raise BybitAPIError(f"Не удалось связаться с Bybit: {exc}") from None
if result.get("retCode") != 0:
raise BybitAPIError(f"Bybit API {result.get('retCode')}: {result.get('retMsg', 'ошибка запроса')}")
return result.get("result", {})
def get_wallet(self) -> dict[str, float]:
result = self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"})
rows = result.get("list", [])
if not rows:
raise BybitAPIError("Bybit не вернул Unified USDT-баланс; проверьте тип аккаунта и права API")
row = rows[0]
available_raw = row.get("totalAvailableBalance")
if available_raw in (None, ""):
equity = float(row.get("totalEquity") or 0)
initial_margin = float(row.get("totalInitialMargin") or 0)
available = max(0.0, equity - initial_margin)
else:
available = float(available_raw)
return {
"wallet": float(row.get("totalWalletBalance") or 0),
"equity": float(row.get("totalEquity") or 0),
"available": available,
"unrealized_pnl": float(row.get("totalPerpUPL") or 0),
}
def get_instrument(self, symbol: str) -> dict[str, str]:
result = self._request("GET", "/v5/market/instruments-info", {"category": "linear", "symbol": symbol})
rows = result.get("list", [])
if not rows:
raise BybitAPIError(f"Контракт {symbol} не найден на Bybit linear")
row = rows[0]
lot = row.get("lotSizeFilter", {})
if row.get("status") != "Trading":
raise BybitAPIError(f"Контракт {symbol} сейчас не торгуется")
return {
"qty_step": lot.get("qtyStep", "0"),
"min_qty": lot.get("minOrderQty", "0"),
"min_notional": lot.get("minNotionalValue", "0"),
"max_market_qty": lot.get("maxMktOrderQty", lot.get("maxMarketOrderQty", "0")),
"tick_size": row.get("priceFilter", {}).get("tickSize", "0"),
}
def get_taker_fee_pct(self, symbol: str) -> float:
result = self._request("GET", "/v5/account/fee-rate", {"category": "linear", "symbol": symbol})
rows = result.get("list", [])
if not rows:
raise BybitAPIError(f"Bybit не вернул комиссию для {symbol}")
return float(rows[0]["takerFeeRate"]) * 100
def get_positions(self, symbol: str) -> list[dict]:
result = self._request("GET", "/v5/position/list", {"category": "linear", "symbol": symbol})
return result.get("list", [])
def get_open_positions(self) -> list[dict]:
"""Return all open USDT-settled linear positions for account overview."""
result = self._request("GET", "/v5/position/list", {
"category": "linear", "settleCoin": "USDT", "limit": 200,
})
return [row for row in result.get("list", []) if float(row.get("size") or 0) > 0]
def get_order_history(self, limit: int = 50) -> list[dict]:
"""Return recent linear-contract order records (read-only)."""
result = self._request("GET", "/v5/order/history", {
"category": "linear", "settleCoin": "USDT", "limit": max(1, min(int(limit), 50)),
})
return result.get("list", [])
def get_closed_pnl_history(self, limit: int = 50) -> list[dict]:
"""Return recent realized PnL records for linear contracts."""
result = self._request("GET", "/v5/position/closed-pnl", {
"category": "linear", "limit": max(1, min(int(limit), 100)),
})
return result.get("list", [])
def get_open_position(self, symbol: str) -> dict | None:
for row in self.get_positions(symbol):
if float(row.get("size") or 0) > 0:
return row
return None
def get_order(self, symbol: str, order_id: str) -> dict | None:
"""Read the exchange state of an accepted order for safe reconciliation."""
params = {"category": "linear", "symbol": symbol, "orderId": order_id}
for path in ("/v5/order/realtime", "/v5/order/history"):
result = self._request("GET", path, params)
rows = result.get("list", [])
if rows:
return rows[0]
return None
def get_latest_closed_pnl(self, symbol: str, opened_at_ms: int) -> dict | None:
result = self._request("GET", "/v5/position/closed-pnl", {
"category": "linear", "symbol": symbol, "startTime": opened_at_ms, "limit": 50,
})
rows = result.get("list", [])
return max(rows, key=lambda row: int(row.get("updatedTime", 0))) if rows else None
def set_leverage(self, symbol: str, leverage: float) -> None:
try:
self._request("POST", "/v5/position/set-leverage", {
"category": "linear", "symbol": symbol,
"buyLeverage": str(leverage), "sellLeverage": str(leverage),
})
except BybitAPIError as exc:
# Bybit returns 110043 if the requested leverage is already active.
if "110043" not in str(exc):
raise
@staticmethod
def floor_qty(raw_qty: float, spec: dict[str, str]) -> str:
step = Decimal(spec["qty_step"])
if step <= 0:
raise BybitAPIError("Bybit вернул некорректный шаг количества")
qty = (Decimal(str(raw_qty)) / step).to_integral_value(rounding=ROUND_DOWN) * step
if qty < Decimal(spec["min_qty"]):
raise BybitAPIError(f"Размер заявки меньше минимального: {spec['min_qty']}")
maximum = Decimal(spec.get("max_market_qty") or "0")
if maximum > 0 and qty > maximum:
raise BybitAPIError(f"Рыночная заявка превышает максимум {maximum}; уменьшите ставку или плечо")
return format(qty, "f")
@staticmethod
def format_price(raw_price: float, tick_size: str) -> str:
tick = Decimal(tick_size)
if tick <= 0:
return format(Decimal(str(raw_price)), "f")
price = (Decimal(str(raw_price)) / tick).to_integral_value(rounding=ROUND_UP) * tick
return format(price, "f")
def place_market_buy(self, symbol: str, qty: str, take_profit: float, stop_loss: float,
tick_size: str, order_id: str | None = None) -> str:
body = {
"category": "linear", "symbol": symbol, "side": "Buy", "orderType": "Market",
"qty": qty, "positionIdx": 0, "timeInForce": "IOC",
"tpslMode": "Full", "tpOrderType": "Market", "slOrderType": "Market",
"takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0",
"stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0",
"tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice",
"orderLinkId": order_id or f"rps-{uuid.uuid4().hex[:28]}",
}
result = self._request("POST", "/v5/order/create", body)
return result.get("orderId", "")
def update_position_stops(self, symbol: str, take_profit: float, stop_loss: float,
tick_size: str) -> None:
try:
self._request("POST", "/v5/position/trading-stop", {
"category": "linear", "symbol": symbol, "tpslMode": "Full", "positionIdx": 0,
"takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0",
"stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0",
"tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice",
"tpOrderType": "Market", "slOrderType": "Market",
})
except BybitAPIError as exc:
# Bybit's 34040 is an idempotent response: the requested TP/SL is
# already active (or no value changed), so there is nothing to do.
if "34040" not in str(exc):
raise
def close_long_market(self, symbol: str, qty: str) -> str:
result = self._request("POST", "/v5/order/create", {
"category": "linear", "symbol": symbol, "side": "Sell", "orderType": "Market",
"qty": qty, "positionIdx": 0, "timeInForce": "IOC", "reduceOnly": True,
"closeOnTrigger": True, "orderLinkId": f"rps-close-{uuid.uuid4().hex[:24]}",
})
return result.get("orderId", "")
+119
View File
@@ -0,0 +1,119 @@
"""Store Bybit credentials encrypted for the current Windows user with DPAPI."""
from __future__ import annotations
import base64
import ctypes
import json
import os
from ctypes import wintypes
from pathlib import Path
class CredentialStoreError(RuntimeError):
"""Raised when credentials cannot be safely stored or loaded."""
class _DataBlob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_byte))]
def _default_path() -> Path:
local_app_data = os.environ.get("LOCALAPPDATA")
if not local_app_data:
raise CredentialStoreError("Не удалось определить папку профиля Windows для защищённого хранения")
return Path(local_app_data) / "RealtimePaperSimulator" / "bybit_credentials.dpapi"
def _protect(data: bytes) -> bytes:
if os.name != "nt":
raise CredentialStoreError("Защищённое хранение ключей доступно только в Windows")
crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
source_buffer = ctypes.create_string_buffer(data)
source = _DataBlob(len(data), ctypes.cast(source_buffer, ctypes.POINTER(ctypes.c_byte)))
encrypted = _DataBlob()
crypt32.CryptProtectData.argtypes = [
ctypes.POINTER(_DataBlob), wintypes.LPCWSTR, ctypes.POINTER(_DataBlob),
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob),
]
crypt32.CryptProtectData.restype = wintypes.BOOL
kernel32.LocalFree.argtypes = [ctypes.c_void_p]
kernel32.LocalFree.restype = ctypes.c_void_p
if not crypt32.CryptProtectData(ctypes.byref(source), "Bybit API credentials", None, None, None, 1,
ctypes.byref(encrypted)):
raise ctypes.WinError(ctypes.get_last_error())
try:
return ctypes.string_at(encrypted.pbData, encrypted.cbData)
finally:
kernel32.LocalFree(encrypted.pbData)
def _unprotect(data: bytes) -> bytes:
if os.name != "nt":
raise CredentialStoreError("Защищённое хранение ключей доступно только в Windows")
crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
source_buffer = ctypes.create_string_buffer(data)
source = _DataBlob(len(data), ctypes.cast(source_buffer, ctypes.POINTER(ctypes.c_byte)))
decrypted = _DataBlob()
crypt32.CryptUnprotectData.argtypes = [
ctypes.POINTER(_DataBlob), ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(_DataBlob),
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob),
]
crypt32.CryptUnprotectData.restype = wintypes.BOOL
kernel32.LocalFree.argtypes = [ctypes.c_void_p]
kernel32.LocalFree.restype = ctypes.c_void_p
if not crypt32.CryptUnprotectData(ctypes.byref(source), None, None, None, None, 1,
ctypes.byref(decrypted)):
raise ctypes.WinError(ctypes.get_last_error())
try:
return ctypes.string_at(decrypted.pbData, decrypted.cbData)
finally:
kernel32.LocalFree(decrypted.pbData)
def save_credentials(api_key: str, api_secret: str, path: Path | None = None) -> None:
api_key, api_secret = api_key.strip(), api_secret.strip()
if not api_key or not api_secret:
raise CredentialStoreError("Введите API key и API secret перед сохранением")
target = path or _default_path()
try:
encrypted = _protect(json.dumps(
{"api_key": api_key, "api_secret": api_secret}, separators=(",", ":")
).encode("utf-8"))
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(base64.b64encode(encrypted).decode("ascii"), encoding="ascii")
except CredentialStoreError:
raise
except (OSError, ValueError, TypeError) as exc:
raise CredentialStoreError(f"Не удалось сохранить API-ключи: {exc}") from None
def load_credentials(path: Path | None = None) -> dict[str, str] | None:
target = path or _default_path()
if not target.exists():
return None
try:
encrypted = base64.b64decode(target.read_text(encoding="ascii"), validate=True)
payload = json.loads(_unprotect(encrypted).decode("utf-8"))
api_key = str(payload["api_key"])
api_secret = str(payload["api_secret"])
if not api_key or not api_secret:
raise ValueError("пустые ключи")
return {"api_key": api_key, "api_secret": api_secret}
except CredentialStoreError:
raise
except Exception:
raise CredentialStoreError(
"Не удалось расшифровать сохранённые ключи текущим пользователем Windows. "
"Сохраните ключи заново в окне API Bybit."
) from None
def delete_credentials(path: Path | None = None) -> None:
target = path or _default_path()
try:
target.unlink(missing_ok=True)
except OSError as exc:
raise CredentialStoreError(f"Не удалось удалить сохранённые ключи: {exc}") from None
+1950
View File
File diff suppressed because it is too large. Load diff
+159
View File
@@ -0,0 +1,159 @@
"""Best bid / ask of ONE symbol, fast (public REST, kept-alive connections): used to watch open positions several
times a second, instead of the whole-market lists that take 1–20 s per cycle.
spot_top(exchange, symbol) -> (bid, ask, bid $ size or None, ask $ size or None)
fut_top(exchange, symbol) -> the same for the USDT perpetual, prices per the symbol's unit (1000PEPE…)
`exchange` is "Bybit" / "Binance" / "MEXC" / "HTX" / "Gate"; symbols are the exchange's own (as the scanners have them).
"""
from __future__ import annotations
import urllib.parse
from live import LiveError, _http
def _f(v) -> float:
try:
return float(v)
except (TypeError, ValueError):
return 0.0
def _q(s: str) -> str:
return urllib.parse.quote(s, safe="")
def spot_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]:
if exchange == "Bybit":
t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=spot&symbol={_q(symbol)}")["result"]["list"][0]
b, a = _f(t["bid1Price"]), _f(t["ask1Price"])
return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size"))
if exchange in ("Binance", "MEXC"):
host = "https://api.binance.com" if exchange == "Binance" else "https://api.mexc.com"
t = _http("GET", f"{host}/api/v3/ticker/bookTicker?symbol={_q(symbol)}")
b, a = _f(t["bidPrice"]), _f(t["askPrice"])
return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty"))
if exchange == "HTX":
t = _http("GET", f"https://api.huobi.pro/market/detail/merged?symbol={_q(symbol.lower())}")["tick"]
return _f(t["bid"][0]), _f(t["ask"][0]), _f(t["bid"][0]) * _f(t["bid"][1]), _f(t["ask"][0]) * _f(t["ask"][1])
if exchange == "Gate":
t = _http("GET", f"https://api.gateio.ws/api/v4/spot/tickers?currency_pair={_q(symbol)}")[0]
return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None
raise LiveError(f"нет быстрых цен для {exchange}")
def fut_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]:
if exchange == "Bybit":
t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=linear&symbol={_q(symbol)}")["result"]["list"][0]
b, a = _f(t["bid1Price"]), _f(t["ask1Price"])
return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size"))
if exchange == "Binance":
t = _http("GET", f"https://fapi.binance.com/fapi/v1/ticker/bookTicker?symbol={_q(symbol)}")
b, a = _f(t["bidPrice"]), _f(t["askPrice"])
return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty"))
if exchange == "MEXC":
t = _http("GET", f"https://contract.mexc.com/api/v1/contract/ticker?symbol={_q(symbol)}")["data"]
return _f(t["bid1"]), _f(t["ask1"]), None, None
if exchange == "HTX":
t = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/detail/merged?contract_code={_q(symbol)}")["tick"]
return _f(t["bid"][0]), _f(t["ask"][0]), None, None
if exchange == "Gate":
t = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/tickers?contract={_q(symbol)}")[0]
return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None
raise LiveError(f"нет быстрых цен для {exchange}")
# --- order books: what an order of N $ would really get --------------------------------------------------------------
# The tickers above can lag the book by a second or two on a fast move (seen on Gate: a «gap» that was gone when the
# orders arrived). Before a real entry the program reads the books themselves and prices the whole trade amount.
_SIZES: dict[tuple[str, str], float] = {} # (exchange, perp symbol) → coins (of the symbol's unit) per contract
def _contract_size(exchange: str, symbol: str) -> float:
key = (exchange, symbol)
if key not in _SIZES:
if exchange == "MEXC":
d = _http("GET", f"https://contract.mexc.com/api/v1/contract/detail?symbol={_q(symbol)}")["data"]
_SIZES[key] = _f(d.get("contractSize")) or 1.0
elif exchange == "HTX":
d = _http("GET", f"https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?contract_code={_q(symbol)}")["data"]
_SIZES[key] = _f(d[0].get("contract_size")) or 1.0
elif exchange == "Gate":
d = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/contracts/{_q(symbol)}")
_SIZES[key] = _f(d.get("quanto_multiplier")) or 1.0
else:
_SIZES[key] = 1.0
return _SIZES[key]
def book(exchange: str, market: str, symbol: str) -> tuple[list, list]:
"""(bids, asks) of the order book, best first, as [(price per symbol unit, quantity in symbol units)];
market "spot" or "fut"."""
fut = market == "fut"
if exchange == "Bybit":
r = _http("GET", f"https://api.bybit.com/v5/market/orderbook?category={'linear' if fut else 'spot'}"
f"&symbol={_q(symbol)}&limit=50")["result"]
bids, asks = r["b"], r["a"]
elif exchange == "Binance":
host = "https://fapi.binance.com/fapi/v1" if fut else "https://api.binance.com/api/v3"
r = _http("GET", f"{host}/depth?symbol={_q(symbol)}&limit=20")
bids, asks = r["bids"], r["asks"]
elif exchange == "MEXC":
if fut:
r = _http("GET", f"https://contract.mexc.com/api/v1/contract/depth/{_q(symbol)}?limit=20")["data"]
size = _contract_size(exchange, symbol)
bids = [(b[0], _f(b[1]) * size) for b in r["bids"]]
asks = [(a[0], _f(a[1]) * size) for a in r["asks"]]
else:
r = _http("GET", f"https://api.mexc.com/api/v3/depth?symbol={_q(symbol)}&limit=20")
bids, asks = r["bids"], r["asks"]
elif exchange == "HTX":
if fut:
r = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/depth?contract_code={_q(symbol)}&type=step0")["tick"]
size = _contract_size(exchange, symbol)
bids = [(b[0], _f(b[1]) * size) for b in r["bids"]]
asks = [(a[0], _f(a[1]) * size) for a in r["asks"]]
else:
r = _http("GET", f"https://api.huobi.pro/market/depth?symbol={_q(symbol.lower())}&depth=20&type=step0")["tick"]
bids, asks = r["bids"], r["asks"]
elif exchange == "Gate":
if fut:
r = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/order_book?contract={_q(symbol)}&limit=20")
size = _contract_size(exchange, symbol)
bids = [(b["p"], abs(_f(b["s"])) * size) for b in r["bids"]]
asks = [(a["p"], abs(_f(a["s"])) * size) for a in r["asks"]]
else:
r = _http("GET", f"https://api.gateio.ws/api/v4/spot/order_book?currency_pair={_q(symbol)}&limit=20")
bids, asks = r["bids"], r["asks"]
else:
raise LiveError(f"нет стакана для {exchange}")
return [(_f(p), _f(q)) for p, q in bids[:50]], [(_f(p), _f(q)) for p, q in asks[:50]]
def fill_price(levels: list, usd: float) -> float | None:
"""Average price of an order for `usd` $ walking the book from the best level; None when the book (as read)
holds less than that."""
left, cost, qty = usd, 0.0, 0.0
for price, q in levels:
if price <= 0 or q <= 0:
continue
take = min(left, price * q)
cost += take
qty += take / price
left -= take
if left <= 1e-9:
return cost / qty
return None
def execution(exchange: str, market: str, symbol: str, usd: float) -> dict:
"""What an order of `usd` $ gets now: {"bid": average sale price, "ask": average purchase price (None: not
enough in the book), "best_bid", "best_ask", "spread_pct"} — prices per symbol unit."""
bids, asks = book(exchange, market, symbol)
if not bids or not asks:
raise LiveError(f"{exchange}: пустой стакан {symbol}")
bb, ba = bids[0][0], asks[0][0]
return {"bid": fill_price(bids, usd), "ask": fill_price(asks, usd), "best_bid": bb, "best_ask": ba,
"spread_pct": (ba / bb - 1) * 100 if bb > 0 else 100.0}
File diff suppressed because it is too large. Load diff
+108
View File
@@ -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()}
+696
View File
@@ -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("<<ComboboxSelected>>", on_connection)
mode_row = ttk.Frame(box)
mode_row.pack(fill="x", pady=(0, 4))
ttk.Label(mode_row, text="Режим:").pack(side="left")
mode_var = tk.StringVar(value=MODES[ps.mode])
mode_combo = ttk.Combobox(mode_row, textvariable=mode_var, values=list(MODES.values()), state="readonly",
width=58)
mode_combo.pack(side="left", padx=6)
ttk.Label(mode_row, text=" Ведущая:").pack(side="left")
market_var = tk.StringVar(value=LEAD_MARKETS.get(ps.lead_market, LEAD_MARKETS["futures"]))
market_combo = ttk.Combobox(mode_row, textvariable=market_var, values=list(LEAD_MARKETS.values()),
state="readonly", width=16)
market_combo.pack(side="left", padx=6)
ttk.Label(mode_row, text=" Ставки на:").pack(side="left")
follow_ex_var = tk.StringVar(value=FOLLOW_EXCHANGES.get(ps.follow_exchange, FOLLOW_EXCHANGES["bybit"]))
follow_combo = ttk.Combobox(mode_row, textvariable=follow_ex_var, values=list(FOLLOW_EXCHANGES.values()),
state="readonly", width=16)
follow_combo.pack(side="left", padx=6)
def on_market(_event=None) -> None:
market = next(k for k, v in LEAD_MARKETS.items() if v == market_var.get())
if market in ("futures", "spot"):
vars_["lead_ticker"].set(kucoin_ticker(vars_["lead_ticker"].get(), market))
apply()
market_combo.bind("<<ComboboxSelected>>", on_market)
follow_combo.bind("<<ComboboxSelected>>", lambda _e: apply())
form = ttk.Frame(box)
form.pack(fill="x")
vars_: dict[str, tk.StringVar] = {}
mode_cells: dict[str, list] = {m: [] for m in MODES}
def add_field(key: str, label: str, row: int, column: int):
cell = ttk.Frame(form)
cell.grid(row=row, column=column, sticky="w", padx=(0, 8), pady=(0, 4))
ttk.Label(cell, text=label).pack(anchor="w")
value = getattr(ps, key)
var = tk.StringVar(value=value if isinstance(value, str) else f"{value:g}")
ttk.Entry(cell, textvariable=var, width=16 if isinstance(value, str) else 12).pack(anchor="w")
vars_[key] = var
return cell
for i, (key, label) in enumerate(COMMON_FIELDS):
add_field(key, label, i // 6, i % 6)
mode_row_index = (len(COMMON_FIELDS) + 5) // 6
for mode, items in MODE_FIELDS.items():
for i, (key, label) in enumerate(items):
mode_cells[mode].append(add_field(key, label, mode_row_index, i))
for i, (key, label) in enumerate(TEXT_FIELDS):
add_field(key, label, mode_row_index, 2 + i)
auto_var = tk.BooleanVar(value=ps.auto_tp)
learn_var = tk.BooleanVar(value=ps.auto_tp_learn)
auto_cell = ttk.Frame(form)
auto_cell.grid(row=mode_row_index + 1, column=0, columnspan=2, sticky="w", pady=(0, 4))
ttk.Checkbutton(auto_cell, text="Авто тейк-профит по прогнозу:\nтейк = доля × отставание фьючерса от ведущей",
variable=auto_var, command=lambda: apply()).pack(anchor="w")
for i, (key, label) in enumerate(AUTO_FIELDS):
add_field(key, label, mode_row_index + 1, 2 + i)
learn_cell = ttk.Frame(form)
learn_cell.grid(row=mode_row_index + 1, column=4, columnspan=2, sticky="w", pady=(0, 4))
ttk.Checkbutton(learn_cell, text="Учить долю на истории сигналов\n(после 10 сигналов — вместо ручной)",
variable=learn_var, command=lambda: apply()).pack(anchor="w")
def current_mode() -> str:
return next(k for k, v in MODES.items() if v == mode_var.get())
def show_mode_fields() -> None:
for mode, cells in mode_cells.items():
for cell in cells:
cell.grid() if mode == current_mode() else cell.grid_remove()
def on_mode(_event=None) -> None:
show_mode_fields()
apply()
mode_combo.bind("<<ComboboxSelected>>", on_mode)
show_mode_fields()
actions = ttk.Frame(box)
actions.pack(fill="x", pady=(2, 2))
enabled_var = tk.BooleanVar(value=ps.enabled)
start_btn = tk.Button(actions, text="▶ Старт", width=9, command=lambda: set_trading(True))
start_btn.pack(side="left")
stop_btn = tk.Button(actions, text="■ Стоп", width=9, command=lambda: set_trading(False))
stop_btn.pack(side="left", padx=(4, 0))
trading_label = tk.Label(actions, text="", font=("Segoe UI", 9, "bold"))
trading_label.pack(side="left", padx=8)
def show_trading() -> None:
on = ps.enabled
start_btn.configure(state="disabled" if on else "normal", bg="#d8f0dc" if on else "SystemButtonFace")
stop_btn.configure(state="normal" if on else "disabled", bg="SystemButtonFace" if on else "#f6d6d6")
trading_label.configure(text="Сделки открываются" if on else
"Новые сделки остановлены · цены, сравнение и прогноз продолжают работать",
fg="#1f8a4c" if on else "#c23b3b")
def set_trading(on: bool) -> None:
"""Start/stop opening new paper positions only; the feeds, the comparison, the forecast learning and the
exits of positions already open keep running."""
enabled_var.set(on)
ps.enabled = on
paper.ledger.save()
show_trading()
message.set("Старт: новые сделки открываются" if on else
"Стоп: новые сделки не открываются; открытые позиции закроются по тейку, стопу или времени")
ttk.Button(actions, text="Применить", command=lambda: apply()).pack(side="left", padx=6)
ttk.Button(actions, text="Закрыть позицию", command=lambda: paper.close_now(book, time.time(), "вручную")).pack(
side="left")
ttk.Button(actions, text="Сбросить счёт", command=lambda: reset()).pack(side="left", padx=6)
cut_row = ttk.Frame(box)
cut_row.pack(fill="x", pady=(0, 2))
cut_var = tk.BooleanVar(value=ps.cut_loss)
ttk.Checkbutton(cut_row, text="Сразу закрывать, если ушло в минус на", variable=cut_var,
command=lambda: apply()).pack(side="left")
cut_ticks_var = tk.StringVar(value=str(ps.cut_loss_ticks))
ttk.Entry(cut_row, textvariable=cut_ticks_var, width=4).pack(side="left", padx=4)
ttk.Label(cut_row, text="шаг(а) цены (середина Bybit против цены при входе) — и сразу брать следующий сигнал "
"без паузы").pack(side="left")
tick_row = ttk.Frame(box)
tick_row.pack(fill="x", pady=(0, 2))
one_tick_var = tk.BooleanVar(value=ps.one_per_tick)
ttk.Checkbutton(tick_row, text="Не больше одной позиции на один шаг цены Bybit (в каждую сторону); всего "
"параллельно — до «Позиций одновременно»", variable=one_tick_var,
command=lambda: apply()).pack(side="left")
record_var = tk.BooleanVar(value=True)
ttk.Checkbutton(actions, text=f"Записывать поток в {sp.RECORD_DIR.name}\\", variable=record_var).pack(
side="left", padx=10)
summary, status, position, message = (tk.StringVar() for _ in range(4))
ttk.Label(box, textvariable=summary, font=("Segoe UI", 10, "bold")).pack(anchor="w")
ttk.Label(box, textvariable=status, foreground="#1d4f91", wraplength=940).pack(anchor="w")
ttk.Label(box, textvariable=position, wraplength=940).pack(anchor="w")
ttk.Label(box, textvariable=message, foreground="#555", wraplength=940).pack(anchor="w")
columns = ("time", "ticker", "side", "qty", "usd", "entry", "exit", "pct", "net", "fee", "reason", "hold", "why")
heads = {"time": "Закрыта (UTC)", "ticker": "Тикер", "side": "Напр.", "qty": "Объём", "usd": "Объём в $",
"entry": "Цена откр.", "exit": "Цена закр.", "pct": "Процент", "net": "Чистая, $", "fee": "Комиссия, $",
"reason": "Причина", "hold": "Сек.", "why": "Почему вошли"}
widths = {"time": 115, "ticker": 95, "side": 45, "qty": 65, "usd": 60, "entry": 75, "exit": 75, "pct": 60,
"net": 70, "fee": 65, "reason": 60, "hold": 40, "why": 200}
table = ttk.Frame(box)
table.pack(fill="both", expand=True, pady=(4, 0))
tree = ttk.Treeview(table, columns=columns, show="headings", height=10)
for col in columns:
tree.heading(col, text=heads[col])
tree.column(col, width=widths[col], anchor="center")
tree.tag_configure("win", foreground="#13843b")
tree.tag_configure("loss", foreground="#c62828")
scroll = ttk.Scrollbar(table, orient="vertical", command=tree.yview)
tree.configure(yscrollcommand=scroll.set)
tree.pack(side="left", fill="both", expand=True)
scroll.pack(side="right", fill="y")
shown = {"count": -1}
def start_feeds() -> None:
for key in ("leader_feed", "follower_feed"):
if state[key]:
state[key].stop()
if state["recorder"]:
state["recorder"].close()
state["recorder"] = None
book.clear()
lat_follow.clear()
lat_lead.clear()
state["leader"] = None
paper.policy = paper._make_policy()
if ps.follow_exchange == "mexc":
state["tick"], size = sh.mexc_contract(ps.follow_ticker)
state["follower_feed"] = sh.MexcFeed(ps.follow_ticker, events, size)
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()
+1448
View File
File diff suppressed because it is too large. Load diff
+4821
View File
File diff suppressed because it is too large. Load diff
+105
View File
@@ -0,0 +1,105 @@
# Meme Matcher
Finds the same memecoins on **CEX perpetual futures** and on **DEX spot**, and compares their prices.
```
py -3 meme_matcher.py # window
py -3 meme_matcher.py --once # console table + meme_matches.csv
```
Python 3.10+ standard library only; all APIs are public (no keys).
## Sources
| What | Where |
|---|---|
| USDT perpetuals: price, 24h volume, funding | Bybit, Binance, OKX, Gate, MEXC, Bitget, BingX |
| Which coins are memecoins, market cap, contract addresses | CoinGecko, category `meme-token` (top 1000 by default, 4 pages × 250) |
| DEX pools: price, liquidity, 24h volume | DexScreener (Solana, Ethereum, BSC, Base, Arbitrum, TON, …) |
| DEX spot order book | HyperLiquid spot (USDC pairs) |
The CoinGecko contract list (~4 MB) is cached in `cache/` for 24 h.
## How a coin is identified
A ticker alone is not enough: CoinGecko lists 21 different "PEPE" tokens, and one exchange can list `CAT` and
`1000CAT` as two different coins. So:
1. Contract size prefixes and suffixes are removed and the price is converted to one coin (`1000PEPE`, `1MBABYDOGE`,
`SHIB1000`).
2. Each CEX contract is tied to the CoinGecko meme token with the same symbol **whose price agrees** with it (within
±50%); contracts that agree with no meme token are skipped (not a memecoin, or an unknown one).
3. For that token's contract addresses every DexScreener pool is fetched; the token must be the pool's base asset.
The chosen pool is the deepest one whose price is within ±25% of the CEX price; HyperLiquid spot is added by
token name with the same price check.
4. Status by the DEX − CEX price gap: **совпадает** ≤ 5%, **проверить** ≤ 25%, **разные монеты?** above that (only
pools at a very different price exist — usually a copycat token on another chain), **нет на DEX**.
## Window
Exchange checkboxes, minimum DEX liquidity and CEX volume, number of CoinGecko pages, "only on DEX" and
"only matching" filters. Columns sort on click; a double click opens the pool on DexScreener / HyperLiquid;
"Сохранить CSV" saves what is shown. `(+N)` after the DEX means the coin also trades on N more chains at the same
price. Funding is the largest absolute funding rate over the listed exchanges.
## Lead-lag: does the DEX move before the futures?
```
py -3 leadlag.py --minutes 30 --coins 12 # scan, record, analyse
py -3 leadlag.py --analyze recordings\leadlag_….jsonl.gz
```
Also the «Опережение DEX…» button in the window. Coins: status «совпадает», a pool on **Solana, BSC or Base**
(blocks ≤ 2 s; a 12 s Ethereum block cannot show a 1 s lead) with at least 120 swaps an hour (the most active pool
is used), and a perpetual on Binance, Bybit, Gate or MEXC (in that order of preference).
Recorded at the same time:
* futures trades over WebSockets with exchange timestamps in ms (Binance `fstream…/market/stream` aggTrade, Bybit
publicTrade, Gate futures.trades, MEXC push.deal);
* DEX swaps from GeckoTerminal (`/pools/{pool}/trades`, last 300 swaps, polled every 30 s, ≤ 26 requests a minute)
with **on-chain block timestamps** — so the lead is measured on chain time, not on when the API showed the swap.
Recordings go to `recordings/`, verdicts to `leadlag_results.csv`.
Analysis on a 1-second grid (DEX: volume-weighted price of the block second; futures: last trade of the second):
* correlation of 1-s returns at lags −10…+10 s (+ = futures after the DEX);
* events — seconds where the DEX moved ≥ 0.15%: the futures move in the same direction in that second, and **from
t+1 to t+3/5/10** — i.e. after the DEX second and the next one, so a sub-second reaction that merely lands in the
next second does not count as a lead. Block times are whole seconds, so a lead under ~1 s cannot be told apart
from "simultaneous".
* verdicts: **DEX опережает ≥1 с** (t+1→t+5 move the DEX way, t ≥ 2, hit rate ≥ 60%, ≥ 10 events), **фьючерс
опережает** (best correlation at a negative lag), **после DEX фьючерс откатывает**, **одновременно / нет
опережения**, **мало движений DEX / мало данных**.
**Live use:** GeckoTerminal publishes swaps 1–2 minutes late (column «Задержка данных DEX»). The tool can find
which coins lead; acting on a lead needs a direct chain feed (Solana RPC WebSocket on the pool), not this API.
## Autonomous search (autoscan)
```
py -3 autoscan.py --minutes 15 --coins 12 # or autoscan.bat, or «Автопоиск…» → «Запустить» in the window
```
Runs on its own in a loop: scan → up to 12 coins (earlier leaders are re-checked first, the rest rotate through all
candidates) → 15 min recording → lead analysis → next cycle (one cycle ≈ 20 min). Every result is appended to
`autoscan_history.csv`, the log to `autoscan.log`. A coin with «DEX опережает ≥1 с» whose pool is on Solana and of a
type the simulator reads live (Raydium AMM v4 / CPMM, PumpSwap, Meteora DLMM — checked through the pool account's
owner program) and whose futures are on Binance, Bybit or MEXC is added to the simulator's `../lead_connections.json`
(never removed; the simulator's active connection is not changed; the simulator picks the new entry up within 30 s).
Only one autoscan runs at a time (`autoscan.lock`); the manual «Опережение DEX…» recording shares GeckoTerminal's
rate limit with it. «Автопоиск…» in the window shows the history (leaders highlighted, what was added) and starts or
stops the background process, which keeps running when the windows are closed.
## Limits
* The meme universe is CoinGecko's `meme-token` category: memecoins that CoinGecko has not tagged, or that are
outside the scanned pages, are not found.
* The CoinGecko free API allows a few requests per minute; the scanner waits between pages and retries on HTTP 429.
* Prices come from different moments (each API is polled once); small gaps are timing, not arbitrage. DEX prices
do not include swap fees, slippage or gas.
## Tests
```
py -3 -m unittest discover -s tests
```
+5
View File
@@ -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
+406
View File
@@ -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()
+591
View File
@@ -0,0 +1,591 @@
"""Lead-lag: does the DEX spot price move BEFORE the CEX perpetual (by at least a second)?
For memecoins found by meme_matcher (same coin, price agrees, a pool on a fast chain) it records at the same time
* CEX perpetual trades from a WebSocket (Binance, Bybit, Gate or MEXC) with exchange timestamps in milliseconds;
* DEX swaps of the most active pool from GeckoTerminal with ON-CHAIN block timestamps (1 s resolution).
Then, on a 1-second grid, it checks whether a DEX move in second t is followed by the futures moving the same way
AFTER second t+1 - i.e. later than any same-second reaction could explain. That is the part one could trade.
Note: GeckoTerminal publishes swaps ~40-60 s after the block (it caches for 30 s), so this tool MEASURES the lead
on chain time; using a lead live needs a direct chain feed (e.g. a Solana RPC WebSocket). The DEX data delay is
reported per coin.
Run: py -3 leadlag.py --minutes 20 --coins 10 (scan, record, analyse)
py -3 leadlag.py --analyze recordings\\leadlag_....jsonl.gz
"""
from __future__ import annotations
import argparse
import csv
import gzip
import json
import math
import threading
import time
from collections import deque
from dataclasses import asdict, dataclass, field
from datetime import datetime
from pathlib import Path
import numpy as np
import meme_matcher as mm
ROOT = Path(__file__).resolve().parent
REC_DIR = ROOT / "recordings"
RESULTS_CSV = ROOT / "leadlag_results.csv"
# DexScreener chain -> GeckoTerminal network. Only chains with blocks of ~2 s or faster: a 12 s Ethereum block
# cannot show a 1 s lead.
FAST_CHAINS = {"solana": "solana", "bsc": "bsc", "base": "base"}
CEX_PRIORITY = ["Binance", "Bybit", "Gate", "MEXC"]
GECKO_CALLS_PER_MIN = 26 # free tier: 30 a minute
MIN_POLL_S = 30 # GeckoTerminal caches responses for 30 s
TAIL_S = 180 # extra DEX polling after the CEX recording ends (swaps are published late)
@dataclass
class Target:
symbol: str
cg_id: str
cex: str
cex_symbol: str
multiplier: float
chain: str
network: str
pool: str
token: str
dex: str
txns_h1: int
def pick_targets(matches: list[mm.Match], max_coins: int = 10, min_txns_h1: int = 120) -> list[Target]:
out = []
for m in matches:
if m.status != "совпадает":
continue
pools = [p for p in m.pools if p.source == "DexScreener" and p.chain in FAST_CHAINS and p.pair_address]
if not pools:
continue
pool = max(pools, key=lambda p: p.txns_h1)
if pool.txns_h1 < min_txns_h1:
continue
by_exchange = {l.exchange: l for l in m.cex}
listing = next((by_exchange[e] for e in CEX_PRIORITY if e in by_exchange), None)
if listing is None:
continue
out.append(Target(m.symbol, m.cg_id, listing.exchange, listing.symbol, listing.multiplier, pool.chain,
FAST_CHAINS[pool.chain], pool.pair_address, pool.contract, pool.dex, pool.txns_h1))
out.sort(key=lambda t: -t.txns_h1)
return out[:max_coins]
# --------------------------------------------------------------------------------------------
# Recording
# --------------------------------------------------------------------------------------------
class Recorder:
def __init__(self, targets: list[Target]) -> None:
self.targets = targets
self.lock = threading.Lock()
self.cex: dict[str, list[tuple[float, float]]] = {t.symbol: [] for t in targets}
self.dex: dict[str, list[tuple[float, float, float, str, float]]] = {t.symbol: [] for t in targets}
self.seen: set[str] = set()
self.gaps: dict[str, int] = {t.symbol: 0 for t in targets}
self.errors: deque[str] = deque(maxlen=20)
self.started = time.time()
def add_cex(self, symbol: str, ts: float, price: float) -> None:
with self.lock:
self.cex[symbol].append((ts, price))
def add_dex(self, symbol: str, trade_id: str, ts: float, price: float, volume: float, kind: str) -> bool:
with self.lock:
if trade_id in self.seen:
return False
self.seen.add(trade_id)
self.dex[symbol].append((ts, price, volume, kind, time.time()))
return True
def counts(self) -> dict[str, tuple[int, int]]:
with self.lock:
return {s: (len(self.cex[s]), len(self.dex[s])) for s in self.cex}
def save(self, path: Path | None = None) -> Path:
REC_DIR.mkdir(exist_ok=True)
path = path or REC_DIR / f"leadlag_{datetime.now():%Y%m%d_%H%M%S}.jsonl.gz"
with self.lock, gzip.open(path, "wt", encoding="utf-8") as f:
f.write(json.dumps({"meta": {"started": self.started, "saved": time.time(), "gaps": self.gaps,
"targets": [asdict(t) for t in self.targets]}}) + "\n")
for s, rows in self.cex.items():
for ts, price in rows:
f.write(json.dumps(["C", s, ts, price]) + "\n")
for s, rows in self.dex.items():
for row in rows:
f.write(json.dumps(["D", s, *row]) + "\n")
return path
def load(path: Path) -> tuple[list[Target], dict, dict, dict]:
cex: dict[str, list] = {}
dex: dict[str, list] = {}
meta = {}
with gzip.open(path, "rt", encoding="utf-8") as f:
for line in f:
row = json.loads(line)
if isinstance(row, dict):
meta = row["meta"]
elif row[0] == "C":
cex.setdefault(row[1], []).append((row[2], row[3]))
else:
dex.setdefault(row[1], []).append(tuple(row[2:]))
targets = [Target(**t) for t in meta.get("targets", [])]
return targets, cex, dex, meta
class CexFeed(threading.Thread):
"""Trades of one exchange's perpetuals over a WebSocket; reconnects on errors."""
def __init__(self, exchange: str, targets: list[Target], rec: Recorder, stop: threading.Event) -> None:
super().__init__(daemon=True)
self.exchange, self.rec, self.stop_event = exchange, rec, stop
self.by_symbol = {t.cex_symbol: t for t in targets}
def _url(self) -> str:
if self.exchange == "Binance":
streams = "/".join(f"{s.lower()}@aggTrade" for s in self.by_symbol)
return f"wss://fstream.binance.com/market/stream?streams={streams}"
return {"Bybit": "wss://stream.bybit.com/v5/public/linear", "Gate": "wss://fx-ws.gateio.ws/v4/ws/usdt",
"MEXC": "wss://contract.mexc.com/edge"}[self.exchange]
def _subscribe(self, ws) -> None:
symbols = list(self.by_symbol)
if self.exchange == "Bybit":
for i in range(0, len(symbols), 10):
ws.send(json.dumps({"op": "subscribe", "args": [f"publicTrade.{s}" for s in symbols[i:i + 10]]}))
elif self.exchange == "Gate":
ws.send(json.dumps({"time": int(time.time()), "channel": "futures.trades", "event": "subscribe",
"payload": symbols}))
elif self.exchange == "MEXC":
for s in symbols:
ws.send(json.dumps({"method": "sub.deal", "param": {"symbol": s}}))
def _ping(self, ws) -> None:
if self.exchange == "Bybit":
ws.send(json.dumps({"op": "ping"}))
elif self.exchange == "Gate":
ws.send(json.dumps({"time": int(time.time()), "channel": "futures.ping"}))
elif self.exchange == "MEXC":
ws.send(json.dumps({"method": "ping"}))
def _emit(self, symbol: str, ts_ms, price) -> None:
target = self.by_symbol.get(symbol)
if target is not None:
self.rec.add_cex(target.symbol, float(ts_ms) / 1000, float(price) / target.multiplier)
def handle(self, msg: dict) -> None:
if self.exchange == "Binance":
d = msg.get("data") or {}
if d.get("e") == "aggTrade":
self._emit(d["s"], d["T"], d["p"])
elif self.exchange == "Bybit":
if str(msg.get("topic", "")).startswith("publicTrade."):
for d in msg.get("data", []):
self._emit(d["s"], d["T"], d["p"])
elif self.exchange == "Gate":
if msg.get("channel") == "futures.trades" and msg.get("event") == "update":
for d in msg.get("result", []):
self._emit(d["contract"], d["create_time_ms"], d["price"])
elif self.exchange == "MEXC":
if msg.get("channel") == "push.deal":
data = msg.get("data")
for d in data if isinstance(data, list) else [data]:
self._emit(msg.get("symbol", ""), d["t"], d["p"])
def run(self) -> None:
import websocket
while not self.stop_event.is_set():
try:
ws = websocket.create_connection(self._url(), timeout=5)
self._subscribe(ws)
last_ping = time.time()
while not self.stop_event.is_set():
if time.time() - last_ping > 15:
self._ping(ws)
last_ping = time.time()
try:
raw = ws.recv()
except websocket.WebSocketTimeoutException:
continue
if raw:
self.handle(json.loads(raw))
ws.close()
except Exception as exc:
self.rec.errors.append(f"{self.exchange}: {exc}")
self.stop_event.wait(3)
def parse_gecko_trades(data: dict, token: str) -> list[tuple[str, float, float, float, str]]:
"""GeckoTerminal /trades -> (id, block time, price of OUR token in USD, volume USD, buy/sell)."""
token = token.lower()
out = []
for item in data.get("data") or []:
a = item.get("attributes") or {}
try:
ts = datetime.fromisoformat(a["block_timestamp"].replace("Z", "+00:00")).timestamp()
except (KeyError, ValueError):
continue
if str(a.get("from_token_address", "")).lower() == token:
price = mm._f(a.get("price_from_in_usd"))
elif str(a.get("to_token_address", "")).lower() == token:
price = mm._f(a.get("price_to_in_usd"))
else:
continue
if price > 0:
out.append((item.get("id") or a.get("tx_hash", ""), ts, price, mm._f(a.get("volume_in_usd")),
a.get("kind", "")))
return out
class DexPoller(threading.Thread):
def __init__(self, targets: list[Target], rec: Recorder, stop: threading.Event) -> None:
super().__init__(daemon=True)
self.targets, self.rec, self.stop_event = targets, rec, stop
def run(self) -> None:
gap = 60.0 / GECKO_CALLS_PER_MIN
first = {t.symbol: True for t in self.targets}
while not self.stop_event.is_set():
cycle_start = time.time()
for t in self.targets:
if self.stop_event.is_set():
return
try:
data = mm.http_json(f"https://api.geckoterminal.com/api/v2/networks/{t.network}/pools/{t.pool}"
"/trades", retries=2)
trades = parse_gecko_trades(data or {}, t.token)
new = sum(self.rec.add_dex(t.symbol, *tr) for tr in trades)
if not first[t.symbol] and trades and new == len(trades) and len(trades) >= 300:
self.rec.gaps[t.symbol] += 1 # all 300 were new: some swaps were missed
first[t.symbol] = False
except Exception as exc:
self.rec.errors.append(f"GeckoTerminal {t.symbol}: {exc}")
self.stop_event.wait(gap)
rest = MIN_POLL_S - (time.time() - cycle_start)
if rest > 0:
self.stop_event.wait(rest)
def record(targets: list[Target], minutes: float, log=print, stop: threading.Event | None = None) -> Recorder:
rec = Recorder(targets)
stop = stop or threading.Event()
threads = [DexPoller(targets, rec, stop)]
for exchange in CEX_PRIORITY:
mine = [t for t in targets if t.cex == exchange]
if mine:
threads.append(CexFeed(exchange, mine, rec, stop))
for th in threads:
th.start()
end = time.time() + minutes * 60
while time.time() < end and not stop.is_set():
stop.wait(10)
counts = rec.counts()
left = max(0, end - time.time()) / 60
log(f"Запись: осталось {left:.1f} мин · " + ", ".join(f"{s} {c}/{d}" for s, (c, d) in counts.items())
+ " (сделок фьючерс/DEX)")
# GeckoTerminal shows swaps 1-2 min late: keep polling the DEX so the last minutes of CEX data are covered
if not stop.is_set():
log(f"Дозаписываю последние сделки DEX (они появляются с задержкой 1–2 мин), {TAIL_S // 60} мин…")
stop.wait(TAIL_S)
stop.set()
for th in threads:
th.join(timeout=10)
return rec
# --------------------------------------------------------------------------------------------
# Analysis
# --------------------------------------------------------------------------------------------
@dataclass
class LeadResult:
symbol: str
cex: str
pool: str
seconds: int
cex_trades: int
dex_trades: int
events: int # seconds with a DEX move of at least the threshold
corr: dict[int, float] # lag (s, + = futures after DEX) -> correlation of 1-s returns
best_lag: int
same_second: float # mean futures move in the DEX move's direction, same second, %
follow: dict[int, float] # mean futures move from t+1 to t+k in the DEX direction, %
hit: dict[int, float] # share of events where that move went the DEX way (of those that moved)
t_stat: float # of the follow move t+1 -> t+5
dex_delay_s: float # how late GeckoTerminal published the swaps (median)
gaps: int
verdict: str
notes: list[str] = field(default_factory=list)
def second_series(trades: list[tuple], t0: int, t1: int, vwap: bool) -> np.ndarray:
"""Price per second on [t0, t1], forward-filled. DEX: volume-weighted within the block second."""
n = t1 - t0 + 1
px = np.full(n, np.nan)
if vwap:
num, den = np.zeros(n), np.zeros(n)
for ts, price, vol, *_ in trades:
i = int(ts) - t0
if 0 <= i < n:
w = max(vol, 1e-9)
num[i] += price * w
den[i] += w
mask = den > 0
px[mask] = num[mask] / den[mask]
else:
for ts, price in sorted(trades):
i = int(math.floor(ts)) - t0
if 0 <= i < n:
px[i] = price # last trade of the second
# forward fill
last = np.nan
for i in range(n):
if np.isnan(px[i]):
px[i] = last
else:
last = px[i]
return px
def analyze_coin(target: Target, cex: list, dex: list, gaps: int = 0, threshold_pct: float = 0.15,
max_lag: int = 10) -> LeadResult:
notes = []
empty = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", 0, len(cex), len(dex), 0, {}, 0,
0.0, {}, {}, 0.0, 0.0, gaps, "мало данных", notes)
if len(cex) < 20 or len(dex) < 20:
return empty
t0 = int(max(min(t for t, _ in cex), min(r[0] for r in dex)))
t1 = int(min(max(t for t, _ in cex), max(r[0] for r in dex)))
if t1 - t0 < 120:
return empty
c = second_series(cex, t0, t1, vwap=False)
d = second_series(dex, t0, t1, vwap=True)
ok = ~(np.isnan(c) | np.isnan(d))
start = int(np.argmax(ok))
c, d = np.log(c[start:]), np.log(d[start:])
rc, rd = np.diff(c), np.diff(d)
n = len(rc)
corr = {}
for k in range(-max_lag, max_lag + 1):
a = rd[max(0, -k): n - max(0, k)]
b = rc[max(0, k): n - max(0, -k)]
corr[k] = float(np.corrcoef(a, b)[0, 1]) if len(a) > 30 and a.std() > 0 and b.std() > 0 else 0.0
best_lag = max(corr, key=lambda k: corr[k])
# events: DEX moved at least the threshold within one second (rd[i] = second i+1 vs i)
thr = threshold_pct / 100
horizons = (2, 3, 5, 10)
same, follow, hit = [], {k: [] for k in horizons}, {k: [] for k in horizons}
for i in np.nonzero(np.abs(rd) >= thr)[0]:
t = i + 1 # index of the second where the DEX move landed
if t + max(horizons) >= len(c) or t < 1:
continue
sign = 1.0 if rd[i] > 0 else -1.0
same.append(sign * (c[t] - c[t - 1]))
for k in horizons:
move = sign * (c[t + k] - c[t + 1]) # strictly after the DEX second and the next one
follow[k].append(move)
if abs(move) > 1e-12:
hit[k].append(move > 0)
events = len(same)
f5 = np.array(follow[5]) if follow[5] else np.array([0.0])
t_stat = float(f5.mean() / (f5.std(ddof=1) / math.sqrt(len(f5)))) if len(f5) > 2 and f5.std() > 0 else 0.0
# publication delay only for swaps made during the recording (the first poll returns old history)
first_cex = min(t for t, _ in cex)
delays = [r[4] - r[0] for r in dex if len(r) > 4 and r[0] >= first_cex]
res = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", n, len(cex), len(dex), events, corr,
best_lag, float(np.mean(same) * 100) if same else 0.0,
{k: float(np.mean(v) * 100) if v else 0.0 for k, v in follow.items()},
{k: float(np.mean(v)) if v else 0.0 for k, v in hit.items()}, t_stat,
float(np.median(delays)) if delays else 0.0, gaps, "", notes)
if gaps:
notes.append(f"пропуски DEX: {gaps} раз пришло 300 новых сделок подряд")
if events < 10:
res.verdict = "мало движений DEX"
elif t_stat >= 2 and res.hit[5] >= 0.6 and res.follow[5] > 0:
res.verdict = "DEX опережает ≥1 с"
elif best_lag < 0 and corr[best_lag] > corr.get(0, 0) and corr[best_lag] > 3 / math.sqrt(n):
res.verdict = "фьючерс опережает"
elif t_stat <= -2:
res.verdict = "после DEX фьючерс откатывает"
else:
res.verdict = "одновременно / нет опережения"
return res
def analyze(targets: list[Target], cex: dict, dex: dict, gaps: dict | None = None,
threshold_pct: float = 0.15) -> list[LeadResult]:
out = [analyze_coin(t, cex.get(t.symbol, []), dex.get(t.symbol, []), (gaps or {}).get(t.symbol, 0),
threshold_pct) for t in targets]
order = {"DEX опережает ≥1 с": 0, "одновременно / нет опережения": 1, "фьючерс опережает": 2,
"после DEX фьючерс откатывает": 3, "мало движений DEX": 4, "мало данных": 5}
out.sort(key=lambda r: (order.get(r.verdict, 9), -r.t_stat))
return out
RESULT_COLUMNS = ["symbol", "verdict", "cex", "dex_pool", "minutes", "cex_trades", "dex_trades", "dex_moves",
"best_lag_s", "corr_lag0", "corr_lag1", "corr_lag2", "corr_lag-1", "same_second_pct",
"follow_t1_t3_pct", "follow_t1_t5_pct", "follow_t1_t10_pct", "hit_t5", "t_stat",
"dex_publish_delay_s", "notes"]
def result_row(r: LeadResult) -> list:
return [r.symbol, r.verdict, r.cex, r.pool, f"{r.seconds / 60:.1f}", r.cex_trades, r.dex_trades, r.events,
r.best_lag, f"{r.corr.get(0, 0):.3f}", f"{r.corr.get(1, 0):.3f}", f"{r.corr.get(2, 0):.3f}",
f"{r.corr.get(-1, 0):.3f}", f"{r.same_second:+.3f}", f"{r.follow.get(3, 0):+.3f}",
f"{r.follow.get(5, 0):+.3f}", f"{r.follow.get(10, 0):+.3f}", f"{r.hit.get(5, 0):.2f}",
f"{r.t_stat:+.2f}", f"{r.dex_delay_s:.0f}", "; ".join(r.notes)]
def save_results(results: list[LeadResult], path: Path = RESULTS_CSV) -> None:
with path.open("w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f, delimiter=";")
w.writerow(RESULT_COLUMNS)
w.writerows(result_row(r) for r in results)
def print_results(results: list[LeadResult]) -> None:
print(f"\n{'Монета':10s} {'Вывод':30s} {'Фьючерс':8s} {'DEX':18s} {'Движ.':>5s} {'Лаг':>4s} "
f"{'Та же с':>8s} {'t+1→t+5':>8s} {'Попад.':>6s} {'t':>6s} {'Задержка':>8s}")
for r in results:
print(f"{r.symbol:10s} {r.verdict:30s} {r.cex:8s} {r.pool[:18]:18s} {r.events:5d} {r.best_lag:+4d} "
f"{r.same_second:+7.3f}% {r.follow.get(5, 0):+7.3f}% {r.hit.get(5, 0) * 100:5.0f}% {r.t_stat:+6.2f} "
f"{r.dex_delay_s:7.0f}с")
def open_window(parent, get_matches) -> None:
"""'Опережение DEX' dialog for the Meme Matcher window: pick coins, record N minutes, show the verdicts."""
import tkinter as tk
from tkinter import ttk
win = tk.Toplevel(parent)
win.title("Опережение DEX → фьючерсы")
win.geometry("1200x560")
form = ttk.Frame(win, padding=6)
form.pack(fill="x")
minutes, coins, min_txns, thr = (tk.StringVar(value=v) for v in ("20", "10", "120", "0.15"))
for label, var in (("Минут записи", minutes), ("Монет (до 13)", coins), ("Мин. сделок в пуле за час", min_txns),
("Движение DEX за 1 с, %", thr)):
ttk.Label(form, text=label).pack(side="left", padx=(0, 4))
ttk.Entry(form, textvariable=var, width=7).pack(side="left", padx=(0, 10))
start_btn = ttk.Button(form, text="Записать и проверить")
start_btn.pack(side="left", padx=4)
stop_btn = ttk.Button(form, text="Остановить", state="disabled")
stop_btn.pack(side="left")
columns = {"symbol": ("Монета", 80), "verdict": ("Вывод", 210), "cex": ("Фьючерс", 70), "pool": ("Пул DEX", 140),
"events": ("Движений DEX", 90), "lag": ("Лучший лаг, с", 85), "same": ("Та же секунда", 90),
"follow": ("После t+1 → t+5", 105), "hit": ("Попадание", 75), "t": ("t-стат.", 60),
"delay": ("Задержка данных DEX", 125)}
tree = ttk.Treeview(win, columns=list(columns), show="headings", height=14)
for key, (title, width) in columns.items():
tree.heading(key, text=title)
tree.column(key, width=width, anchor="w")
tree.tag_configure("lead", background="#e8f7e8")
tree.pack(fill="both", expand=True, padx=6)
status = tk.StringVar(value="Берутся монеты со статусом «совпадает», пулом на Solana/BSC/Base и фьючерсом на "
"Binance/Bybit/Gate/MEXC. «После t+1 → t+5» — движение фьючерса в сторону DEX, "
"начиная со следующей секунды после движения на DEX.")
ttk.Label(win, textvariable=status, padding=6, wraplength=1150).pack(fill="x")
stop_event = threading.Event()
def show(results):
tree.delete(*tree.get_children())
for r in results:
tree.insert("", "end", tags=("lead",) if r.verdict.startswith("DEX опережает") else (), values=(
r.symbol, r.verdict, r.cex, r.pool, r.events, f"{r.best_lag:+d}", f"{r.same_second:+.3f}%",
f"{r.follow.get(5, 0):+.3f}%", f"{r.hit.get(5, 0) * 100:.0f}%", f"{r.t_stat:+.2f}",
f"{r.dex_delay_s:.0f} с"))
def log(text):
win.after(0, status.set, text)
def start():
matches = get_matches()
if not matches:
status.set("Сначала дождитесь сканирования в главном окне")
return
try:
n_min, n_coins = float(minutes.get()), max(1, min(13, int(coins.get())))
n_txns, threshold = int(min_txns.get()), float(thr.get())
except ValueError:
status.set("Проверьте числа в полях")
return
targets = pick_targets(matches, n_coins, n_txns)
if not targets:
status.set("Нет подходящих монет — уменьшите «Мин. сделок в пуле за час»")
return
stop_event.clear()
start_btn.configure(state="disabled")
stop_btn.configure(state="normal")
def work():
rec = record(targets, n_min, log, stop_event)
path = rec.save()
results = analyze(targets, rec.cex, rec.dex, rec.gaps, threshold)
save_results(results)
win.after(0, finish, results, path)
threading.Thread(target=work, daemon=True).start()
def finish(results, path):
start_btn.configure(state="normal")
stop_btn.configure(state="disabled")
show(results)
leaders = [r.symbol for r in results if r.verdict.startswith("DEX опережает")]
status.set(f"Запись: {path.name} · результаты: {RESULTS_CSV.name} · DEX опережает: "
f"{', '.join(leaders) if leaders else 'не найдено'}")
start_btn.configure(command=start)
stop_btn.configure(command=lambda: (stop_event.set(), status.set("Останавливаю и считаю…")))
def main() -> None:
import sys
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description="DEX → CEX futures lead-lag for memecoins")
parser.add_argument("--minutes", type=float, default=20)
parser.add_argument("--coins", type=int, default=10)
parser.add_argument("--min-txns", type=int, default=120, help="min swaps per hour in the DEX pool")
parser.add_argument("--threshold", type=float, default=0.15, help="DEX move in one second, %%")
parser.add_argument("--analyze", type=Path, help="analyse an existing recording instead of recording")
args = parser.parse_args()
if args.analyze:
targets, cex, dex, meta = load(args.analyze)
results = analyze(targets, cex, dex, meta.get("gaps"), args.threshold)
else:
matches = mm.scan()
targets = pick_targets(matches, args.coins, args.min_txns)
if not targets:
print("Нет подходящих монет (совпадение цены, пул на Solana/BSC/Base, достаточно сделок в час)")
return
print("Монеты для записи:")
for t in targets:
print(f" {t.symbol:10s} {t.cex:8s} {t.cex_symbol:16s} {t.chain}/{t.dex} пул {t.pool[:10]}… "
f"сделок в час {t.txns_h1}")
rec = record(targets, args.minutes)
path = rec.save()
print(f"Запись: {path}")
for e in rec.errors:
print(" ошибка:", e)
results = analyze(targets, rec.cex, rec.dex, rec.gaps, args.threshold)
save_results(results)
print_results(results)
print(f"\nCSV: {RESULTS_CSV}")
if __name__ == "__main__":
main()
+718
View File
@@ -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("<Double-1>", open_row)
def log(text):
root.after(0, status.set, text)
def start():
chosen = [n for n, v in ex_vars.items() if v.get()]
if not chosen:
messagebox.showwarning("Meme Matcher", "Выберите хотя бы одну биржу", parent=root)
return
try:
n_pages = max(1, min(20, int(pages.get())))
except ValueError:
n_pages = 4
scan_btn.configure(state="disabled")
def work():
try:
result = scan(chosen, n_pages, log)
save_csv(result)
root.after(0, done, result, "")
except Exception as exc:
root.after(0, done, None, str(exc))
threading.Thread(target=work, daemon=True).start()
def done(result, error):
scan_btn.configure(state="normal")
if error:
status.set(f"Ошибка: {error}")
return
state["matches"] = result
fill()
def export():
save_csv(visible())
status.set(f"Сохранено: {OUT_CSV}")
root.after(200, start)
root.mainloop()
def main() -> None:
import sys
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--once", action="store_true", help="print the table and save meme_matches.csv")
parser.add_argument("--pages", type=int, default=4, help="CoinGecko meme pages of 250 coins")
parser.add_argument("--exchanges", default=",".join(CEX_SOURCES), help="comma-separated CEX list")
args = parser.parse_args()
if args.once:
matches = scan([e for e in args.exchanges.split(",") if e in CEX_SOURCES], args.pages)
save_csv(matches)
print_table([m for m in matches if m.dex is not None])
print(f"\nCSV: {OUT_CSV}")
else:
run_window()
if __name__ == "__main__":
main()
+94
View File
@@ -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()
+137
View File
@@ -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()
+117
View File
@@ -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()
+224
View File
@@ -0,0 +1,224 @@
"""The smallest orders the five exchanges accept, spot and USDT perpetual, and from them the smallest trade amount a
spot–futures trade can be entered with: the spot buy must reach the spot minimum (USDT and coins) and the coins
bought must make at least the perp's minimum lot (and its minimum notional) — both legs, or the trade is not made.
The rules come from the exchanges' public instrument lists (no keys), loaded in the background and renewed hourly.
Paper and real trading check the same figure, so the paper trades are only those a real account could make.
"""
from __future__ import annotations
import math
import threading
import time
import arb
REFRESH_S = 3600.0
RETRY_S = 300.0
MARGIN = 1.02 # prices move between the check and the order, and the lot is rounded down
AUTOLOAD = False # the program turns it on; tests fill the rules themselves (no network)
def _f(v, default: float = 0.0) -> float:
try:
return float(v)
except (TypeError, ValueError):
return default
def _units(symbol_base: str) -> float:
return arb.split_base(symbol_base)[1]
# --- loaders: {key: rule}; spot keyed by base coin, perp by the symbol the price lists use --------------------------
# spot rule: {"usd": smallest order in USDT, "coins": smallest quantity}; perp rule: {"coins": smallest order in
# coins (lot × contract size), "usd": smallest notional}
def _bybit(category: str) -> dict:
out, cursor = {}, ""
while True:
res = arb._get(f"https://api.bybit.com/v5/market/instruments-info?category={category}&limit=1000"
+ (f"&cursor={cursor}" if cursor else ""))["result"]
for x in res["list"]:
if x.get("quoteCoin") != "USDT" or x.get("status") != "Trading":
continue
lot = x.get("lotSizeFilter") or {}
if category == "spot":
out[x["baseCoin"]] = {"usd": _f(lot.get("minOrderAmt")), "coins": _f(lot.get("minOrderQty"))}
else:
out[x["symbol"]] = {"coins": max(_f(lot.get("minOrderQty")), _f(lot.get("qtyStep")))
* _units(x["symbol"][:-4]), "usd": _f(lot.get("minNotionalValue"))}
cursor = res.get("nextPageCursor") or ""
if not cursor or not res["list"]:
return out
def _binance_spot() -> dict:
out = {}
for s in arb._get("https://api.binance.com/api/v3/exchangeInfo?symbolStatus=TRADING")["symbols"]:
if s.get("quoteAsset") != "USDT":
continue
f = {x["filterType"]: x for x in s.get("filters", [])}
notional = f.get("NOTIONAL") or f.get("MIN_NOTIONAL") or {}
out[s["baseAsset"]] = {"usd": _f(notional.get("minNotional")), "coins": _f((f.get("LOT_SIZE") or {}).get("minQty"))}
return out
def _binance_fut() -> dict:
out = {}
for s in arb._get("https://fapi.binance.com/fapi/v1/exchangeInfo")["symbols"]:
if s.get("quoteAsset") != "USDT" or s.get("status") != "TRADING":
continue
f = {x["filterType"]: x for x in s.get("filters", [])}
lot = f.get("MARKET_LOT_SIZE") if _f((f.get("MARKET_LOT_SIZE") or {}).get("stepSize")) > 0 else f.get("LOT_SIZE", {})
out[s["symbol"]] = {"coins": max(_f(lot.get("minQty")), _f(lot.get("stepSize"))) * _units(s["symbol"][:-4]),
"usd": _f((f.get("MIN_NOTIONAL") or {}).get("notional"))}
return out
def _mexc_spot() -> dict:
out = {}
for s in arb._get("https://api.mexc.com/api/v3/exchangeInfo")["symbols"]:
if s.get("quoteAsset") != "USDT":
continue
out[s["baseAsset"]] = {"usd": _f(s.get("quoteAmountPrecisionMarket") or s.get("quoteAmountPrecision")),
"coins": _f(s.get("baseSizePrecision"))}
return out
def _mexc_fut() -> dict:
out = {}
for c in arb._get("https://contract.mexc.com/api/v1/contract/detail")["data"]:
if c.get("quoteCoin") != "USDT":
continue
out[c["symbol"]] = {"coins": _f(c.get("contractSize"), 1) * _units(c["symbol"][:-5]) * max(1.0, _f(c.get("minVol"), 1)),
"usd": 0.0}
return out
def _htx_spot() -> dict:
out = {}
for s in arb._get("https://api.huobi.pro/v1/settings/common/market-symbols")["data"]:
if s.get("qc") != "usdt" or s.get("state") != "online":
continue
# market buy: «minov» USDT; the market sale later: «smminoa» coins
out[s["bc"].upper()] = {"usd": _f(s.get("minov")), "coins": _f(s.get("smminoa") or s.get("minoa"))}
return out
def _htx_fut() -> dict:
out = {}
for c in arb._get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]:
if not c["contract_code"].endswith("-USDT"):
continue
out[c["contract_code"]] = {"coins": _f(c.get("contract_size"), 1) * _units(c["contract_code"][:-5]), "usd": 0.0}
return out
def _gate_spot() -> dict:
out = {}
for s in arb._get("https://api.gateio.ws/api/v4/spot/currency_pairs"):
if s.get("quote") != "USDT" or s.get("trade_status") not in (None, "tradable"):
continue
out[s["base"]] = {"usd": _f(s.get("min_quote_amount")), "coins": _f(s.get("min_base_amount"))}
return out
def _gate_fut() -> dict:
out = {}
for c in arb._get("https://api.gateio.ws/api/v4/futures/usdt/contracts"):
out[c["name"]] = {"coins": _f(c.get("quanto_multiplier"), 1) * _units(c["name"][:-5])
* max(1.0, _f(c.get("order_size_min"), 1)), "usd": 0.0}
return out
LOADERS = {("Bybit", "spot"): lambda: _bybit("spot"), ("Bybit", "fut"): lambda: _bybit("linear"),
("Binance", "spot"): _binance_spot, ("Binance", "fut"): _binance_fut,
("MEXC", "spot"): _mexc_spot, ("MEXC", "fut"): _mexc_fut,
("HTX", "spot"): _htx_spot, ("HTX", "fut"): _htx_fut,
("Gate", "spot"): _gate_spot, ("Gate", "fut"): _gate_fut}
class Rules:
def __init__(self) -> None:
self.data: dict[tuple[str, str], dict] = {}
self.loaded: dict[tuple[str, str], float] = {} # when loaded (or when the last try failed)
self.loading: set = set()
self.lock = threading.Lock()
def set(self, exchange: str, market: str, rules: dict) -> None:
with self.lock:
self.data[(exchange, market)] = rules
self.loaded[(exchange, market)] = time.time()
def _get(self, exchange: str, market: str) -> dict:
key = (exchange, market)
if AUTOLOAD and key in LOADERS:
with self.lock:
stale = time.time() - self.loaded.get(key, 0.0) > (REFRESH_S if key in self.data else RETRY_S)
start = stale and key not in self.loading
if start:
self.loading.add(key)
if start:
threading.Thread(target=self._load, args=(key,), daemon=True).start()
return self.data.get(key) or {}
def _load(self, key) -> None:
try:
rules = LOADERS[key]()
if rules:
self.set(*key, rules)
except Exception:
with self.lock:
self.loaded[key] = time.time() # tried: again in RETRY_S
finally:
with self.lock:
self.loading.discard(key)
def spot(self, exchange: str, base: str) -> dict | None:
return self._get(exchange, "spot").get(base)
def fut(self, exchange: str, symbol: str) -> dict | None:
return self._get(exchange, "fut").get(symbol)
def min_entry(self, spot_ex: str, base: str, spot_ask: float, fut_ex: str, fut_symbol: str, fut_bid: float,
spot_fee_pct: float) -> dict | None:
"""The smallest trade amount, $, both legs accept: {"usd": total, "spot": $ the spot leg needs (None:
unknown), "fut": $ the perp leg needs}; None when neither exchange's rules are known yet."""
sr, fr = self.spot(spot_ex, base), self.fut(fut_ex, fut_symbol)
if sr is None and fr is None or spot_ask <= 0 or fut_bid <= 0:
return None
keep = 1 - spot_fee_pct / 100 # the buy fee is taken in coins
spot_usd = None if sr is None else max(sr["usd"], sr["coins"] * spot_ask / keep)
fut_usd = None
if fr is not None: # the coins bought must make the perp's smallest order
coins = max(fr["coins"], fr["usd"] / fut_bid if fr["usd"] else 0.0)
fut_usd = coins * spot_ask / keep
need = max(v for v in (spot_usd, fut_usd) if v is not None) * MARGIN
return {"usd": math.ceil(need * 100) / 100, "spot": spot_usd, "fut": fut_usd}
def min_entry_ss(self, spot_ex: str, base: str, spot_ask: float, sell_ex: str, sell_bid: float,
spot_fee_pct: float) -> dict | None:
"""Spot–spot: the buy on A's spot and the sale of the same coins on B's spot must both pass their spot
minimums ("fut" = what B's sale needs)."""
ra, rb = self.spot(spot_ex, base), self.spot(sell_ex, base)
if ra is None and rb is None or spot_ask <= 0 or sell_bid <= 0:
return None
keep = 1 - spot_fee_pct / 100
buy_usd = None if ra is None else max(ra["usd"], ra["coins"] * spot_ask / keep)
sell_usd = None if rb is None else max(rb["coins"], rb["usd"] / sell_bid if rb["usd"] else 0.0) * spot_ask / keep
need = max(v for v in (buy_usd, sell_usd) if v is not None) * MARGIN
return {"usd": math.ceil(need * 100) / 100, "spot": buy_usd, "fut": sell_usd}
RULES = Rules()
def too_small(amount: float, m: dict | None, spot_ex: str, fut_ex: str, b_leg: str = "фьюч") -> str:
"""Why `amount` cannot enter the trade ("" when it can, or when the rules are not known)."""
if m is None or amount >= m["usd"]:
return ""
parts = ([f"спот {spot_ex} ≥ {m['spot']:.2f} $"] if m["spot"] is not None else []) + \
([f"{b_leg} {fut_ex} ≥ {m['fut']:.2f} $"] if m["fut"] is not None else [])
return f"сумма {amount:g} $ меньше мин. входа {m['usd']:.2f} $ ({', '.join(parts)})"
+574
View File
@@ -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_<coin>.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:]))}
+2
View File
@@ -0,0 +1,2 @@
websocket-client>=1.8,<2
numpy>=1.26
+11
View File
@@ -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
+11
View File
@@ -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
+9
View File
@@ -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
+1710
View File
File diff suppressed because it is too large. Load diff
+1394
View File
File diff suppressed because it is too large. Load diff
+86
View File
@@ -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
+73
View File
@@ -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
+396
View File
@@ -0,0 +1,396 @@
"""Shared strategy formulas used by simulation, live trading and the historical backtest.
Keeping these rules in one place prevents the three modes from drifting apart.
"""
from __future__ import annotations
import math
# Approximate maintenance-margin rate for Bybit USDT perpetuals at the lowest risk tier.
MAINTENANCE_MARGIN_RATE_PCT = 0.5
def fee_cover_pct(fee_pct: float) -> float:
"""Minimum gross price rise that offsets taker fees on entry and exit fills."""
fee = max(0.0, fee_pct) / 100
return ((1 + fee) / (1 - fee) - 1) * 100 if fee < 1 else math.inf
def effective_take_profit_pct(take_profit_pct: float, fee_pct: float) -> float:
"""TP percentage raised to cover round-trip fees; 0 keeps TP disabled."""
if take_profit_pct <= 0:
return 0.0
return max(take_profit_pct, fee_cover_pct(fee_pct))
def take_profit_price(avg_entry: float, take_profit_pct: float, fee_pct: float) -> float | None:
pct = effective_take_profit_pct(take_profit_pct, fee_pct)
return avg_entry * (1 + pct / 100) if pct > 0 else None
def stop_loss_price(avg_entry: float, stop_loss_pct: float) -> float | None:
return avg_entry * (1 - stop_loss_pct / 100) if stop_loss_pct > 0 else None
def entry_level(baseline_close: float, trigger_pct: float) -> float:
return baseline_close * (1 + trigger_pct / 100)
def add_level(last_add_price: float, add_step_pct: float) -> float | None:
return last_add_price * (1 - add_step_pct / 100) if add_step_pct > 0 else None
def can_add(add_count: int, max_adds: int, add_step_pct: float, averaging_frozen: bool = False) -> bool:
return add_step_pct > 0 and add_count < max_adds and not averaging_frozen
def liquidation_price(avg_entry: float, leverage: float,
mmr_pct: float = MAINTENANCE_MARGIN_RATE_PCT, side: str = "long") -> float | None:
"""Approximate isolated-margin liquidation price; None when leverage <= 1 for a LONG.
With leverage 1 a LONG cannot lose more than its margin before price reaches 0,
so liquidation is not modelled. For higher leverage the LONG price is
entry * (1 - 1/leverage + MMR) and the SHORT price is entry * (1 + 1/leverage - MMR).
A 1x SHORT is liquidated near a doubling of the price.
"""
if side == "short":
return avg_entry * (1 + 1 / max(leverage, 1.0) - mmr_pct / 100)
if leverage <= 1:
return None
return max(0.0, avg_entry * (1 - 1 / leverage + mmr_pct / 100))
# ---------------------------------------------------------------------------
# Strategy modes.
#
# "classic" — the original rule: entry on a rise above the previous 1-minute close,
# averaging down, TP/stop from the average price (settings per currency).
# "breakout" — mode A: LONG on a close above the N-hour high with a volume spike,
# ATR stop, partial take-profit, breakeven and ATR trailing stop.
# "fade" — mode B: SHORT after a pump stalls (24h growth, high funding, close back
# under the turnover-weighted average price and below the recent high).
# Modes A and B share one exit engine and one parameter set for all currencies.
# ---------------------------------------------------------------------------
STRATEGY_CLASSIC = "classic"
STRATEGY_BREAKOUT = "breakout"
STRATEGY_FADE = "fade"
STRATEGY_MODES = (STRATEGY_CLASSIC, STRATEGY_BREAKOUT, STRATEGY_FADE)
STRATEGY_TITLES = {
STRATEGY_CLASSIC: "Классика: пробой 1-мин свечи + усреднение",
STRATEGY_BREAKOUT: "A: пробой N-часового максимума (ATR)",
STRATEGY_FADE: "B: шорт затухающего пампа",
}
STRATEGY_DESCRIPTIONS = {
STRATEGY_CLASSIC: (
"LONG при росте от закрытия прошлой минутной свечи, доливки при снижении, TP и стоп от средней "
"цены. Настройки задаются для каждой валюты отдельно; здесь — шаблон, который применяется ко всем."
),
STRATEGY_BREAKOUT: (
"LONG, когда закрытие свечи таймфрейма выше максимума за N часов и оборот свечи в K раз выше "
"среднего. Стоп = вход − ATR × множитель, без усреднения. Часть позиции фиксируется на заданном R "
"(R — расстояние до стопа), стоп переносится в безубыток, остаток ведётся трейлинг-стопом по ATR. "
"Фильтры: BTC выше EMA на часовом графике и funding не выше порога."
),
STRATEGY_FADE: (
"SHORT монеты после пампа: рост за 24 ч выше порога, funding не ниже порога, максимум за "
"последние часы уже позади, закрытие ниже него на заданный процент и ниже средней цены по "
"обороту (VWAP). Стоп — над максимумом + ATR × буфер; сделка пропускается, если стоп дальше "
"заданного процента. Выход: частичная фиксация на R, безубыток, трейлинг по ATR. "
"Funding при положительной ставке получают шорты."
),
}
# (key, label, minimum, maximum, integer?) — minimum 0 usually means "0 = выключено".
_COMMON_RISK_FIELDS = (
("stake_pct", "Ставка, % депозита", 0.01, 100.0, False),
("leverage", "Плечо", 1.0, 100.0, False),
("timeframe_min", "Таймфрейм сигнала, мин (5/15/30/60)", 5.0, 60.0, True),
("atr_period", "Период ATR, свечей", 2.0, 200.0, True),
)
_COMMON_EXIT_FIELDS = (
("partial_r", "Частичная фиксация на R (0 = выкл.)", 0.0, 50.0, False),
("partial_pct", "Доля частичной фиксации, %", 0.0, 100.0, False),
("breakeven", "Безубыток после частичной (1/0)", 0.0, 1.0, True),
("trail_atr", "Трейлинг-стоп, ATR (0 = выкл.)", 0.0, 50.0, False),
("take_profit_r", "Финальный TP на R (0 = выкл.)", 0.0, 100.0, False),
("max_hold_hours", "Макс. удержание, ч (0 = выкл.)", 0.0, 10000.0, False),
)
MODE_FIELDS: dict[str, tuple[tuple[str, str, float, float, bool], ...]] = {
STRATEGY_BREAKOUT: _COMMON_RISK_FIELDS + (
("breakout_hours", "Пробой максимума за, ч", 0.25, 168.0, False),
("volume_mult", "Оборот свечи × среднего (0 = выкл.)", 0.0, 100.0, False),
("stop_atr", "Стоп, ATR от входа", 0.1, 50.0, False),
("btc_filter", "Фильтр BTC выше EMA 1ч (1/0)", 0.0, 1.0, True),
("btc_ema", "Период EMA BTC, часов", 2.0, 900.0, True),
("max_funding_pct", "Не входить при funding выше, % (0 = выкл.)", 0.0, 10.0, False),
) + _COMMON_EXIT_FIELDS,
STRATEGY_FADE: _COMMON_RISK_FIELDS + (
("min_growth_24h", "Рост за 24 ч, не меньше %", 0.0, 10000.0, False),
("min_funding_pct", "Funding не ниже, % (0 = выкл.)", 0.0, 10.0, False),
("high_lookback_hours", "Максимум пампа за последние, ч", 0.5, 72.0, False),
("pullback_pct", "Закрытие ниже максимума на, %", 0.0, 90.0, False),
("vwap_hours", "VWAP по обороту за, ч", 0.5, 72.0, False),
("stop_buffer_atr", "Стоп над максимумом, ATR", 0.0, 20.0, False),
("max_stop_pct", "Макс. расстояние до стопа, %", 0.1, 100.0, False),
) + _COMMON_EXIT_FIELDS,
}
MODE_DEFAULTS: dict[str, dict[str, float]] = {
STRATEGY_BREAKOUT: {
"stake_pct": 5.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0,
"breakout_hours": 4.0, "volume_mult": 2.0, "stop_atr": 2.0,
"btc_filter": 1.0, "btc_ema": 200.0, "max_funding_pct": 0.05,
"partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0,
"take_profit_r": 0.0, "max_hold_hours": 48.0,
},
STRATEGY_FADE: {
"stake_pct": 3.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0,
"min_growth_24h": 30.0, "min_funding_pct": 0.03, "high_lookback_hours": 6.0,
"pullback_pct": 3.0, "vwap_hours": 6.0, "stop_buffer_atr": 0.5, "max_stop_pct": 15.0,
"partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0,
"take_profit_r": 0.0, "max_hold_hours": 24.0,
},
}
ALLOWED_TIMEFRAMES = (5, 15, 30, 60)
def parse_mode_params(mode: str, raw: dict[str, object]) -> dict[str, float]:
"""Validate the text values of a mode's settings; raises ValueError with a readable message."""
params: dict[str, float] = {}
for key, label, minimum, maximum, integer in MODE_FIELDS[mode]:
value = raw.get(key, MODE_DEFAULTS[mode][key])
try:
number = float(str(value).strip().replace(",", "."))
except ValueError as exc:
raise ValueError(f"Проверьте значение «{label}».") from exc
if not math.isfinite(number) or not minimum <= number <= maximum:
raise ValueError(f"«{label}» должно быть от {minimum:g} до {maximum:g}.")
if integer and not number.is_integer():
raise ValueError(f"«{label}» должно быть целым числом.")
params[key] = number
if int(params["timeframe_min"]) not in ALLOWED_TIMEFRAMES:
raise ValueError("Таймфрейм сигнала: 5, 15, 30 или 60 минут.")
if params["partial_pct"] > 0 and params["partial_r"] <= 0:
raise ValueError("Для частичной фиксации укажите R больше 0 или долю 0%.")
if (params["trail_atr"] <= 0 and params["take_profit_r"] <= 0
and not (params["partial_r"] > 0 and params["partial_pct"] >= 100)
and params["max_hold_hours"] <= 0):
raise ValueError("Задайте выход по прибыли: трейлинг, финальный TP, 100% частичную фиксацию "
"или максимальное удержание.")
return params
def side_sign(side: str) -> float:
return -1.0 if side == "short" else 1.0
def unrealized_pnl(side: str, entry: float, mark: float, qty: float) -> float:
return side_sign(side) * (mark - entry) * qty
def bars_for_hours(hours: float, timeframe_min: float) -> int:
return max(1, int(round(hours * 60 / timeframe_min)))
def aggregate_candles(rows: list[list[float]], timeframe_min: int) -> list[list[float]]:
"""Group minute rows [start_ms, o, h, l, c, (turnover)] into timeframe candles."""
step = int(timeframe_min) * 60_000
output: list[list[float]] = []
for row in rows:
bucket = (int(row[0]) // step) * step
turnover = float(row[5]) if len(row) > 5 and row[5] is not None else 0.0
if output and output[-1][0] == bucket:
candle = output[-1]
candle[2] = max(candle[2], float(row[2]))
candle[3] = min(candle[3], float(row[3]))
candle[4] = float(row[4])
candle[5] += turnover
else:
output.append([bucket, float(row[1]), float(row[2]), float(row[3]), float(row[4]), turnover])
return output
def average_true_range(candles: list[list[float]], period: int) -> float | None:
"""Simple average of the true range over the last ``period`` candles."""
period = int(period)
if period < 1 or len(candles) < period + 1:
return None
ranges = []
for previous, current in zip(candles[-period - 1:-1], candles[-period:]):
high, low, prev_close = float(current[2]), float(current[3]), float(previous[4])
ranges.append(max(high - low, abs(high - prev_close), abs(low - prev_close)))
value = sum(ranges) / len(ranges)
return value if value > 0 else None
def turnover_vwap(candles: list[list[float]]) -> float | None:
"""Average typical price weighted by turnover (falls back to an equal-weight mean)."""
if not candles:
return None
typical = [(float(c[2]) + float(c[3]) + float(c[4])) / 3 for c in candles]
weights = [float(c[5]) if len(c) > 5 and c[5] else 0.0 for c in candles]
total = sum(weights)
if total > 0:
return sum(price * weight for price, weight in zip(typical, weights)) / total
return sum(typical) / len(typical)
def ema(values: list[float], period: int) -> float | None:
period = int(period)
if period < 1 or len(values) < period:
return None
alpha = 2 / (period + 1)
value = sum(values[:period]) / period
for item in values[period:]:
value = alpha * item + (1 - alpha) * value
return value
def btc_regime_ok(hourly_closes: list[float], ema_period: int) -> bool | None:
"""True when the last closed BTC hour is above its EMA; None without enough data."""
average = ema(hourly_closes, ema_period)
if average is None:
return None
return hourly_closes[-1] > average
def required_bars(mode: str, params: dict[str, float]) -> int:
"""Closed timeframe candles the signal needs (oldest to the just-closed one)."""
tf = params["timeframe_min"]
atr_bars = int(params["atr_period"]) + 1
if mode == STRATEGY_BREAKOUT:
return max(bars_for_hours(params["breakout_hours"], tf) + 1, atr_bars)
return max(bars_for_hours(24, tf) + 1, bars_for_hours(params["high_lookback_hours"], tf),
bars_for_hours(params["vwap_hours"], tf), atr_bars)
def evaluate_breakout(candles: list[list[float]], params: dict[str, float],
funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None:
"""Mode A signal on closed candles [start, o, h, l, c, turnover]; the last one has just closed."""
if len(candles) < required_bars(STRATEGY_BREAKOUT, params):
return None
lookback = bars_for_hours(params["breakout_hours"], params["timeframe_min"])
last = candles[-1]
prior = candles[-lookback - 1:-1]
level = max(float(c[2]) for c in prior)
close = float(last[4])
if close <= level:
return None
if params["volume_mult"] > 0:
average = sum(float(c[5]) if len(c) > 5 else 0.0 for c in prior) / len(prior)
turnover = float(last[5]) if len(last) > 5 else 0.0
if average > 0 and turnover < params["volume_mult"] * average:
return None
if params["btc_filter"] >= 1 and btc_ok is not True:
return None
if (params["max_funding_pct"] > 0 and funding_rate_pct is not None
and funding_rate_pct > params["max_funding_pct"]):
return None
atr = average_true_range(candles, int(params["atr_period"]))
if atr is None:
return None
return {"side": "long", "atr": atr, "level": level, "close": close, "candle_start": int(last[0])}
def evaluate_fade(candles: list[list[float]], params: dict[str, float],
funding_rate_pct: float | None = None) -> dict | None:
"""Mode B signal on closed candles; returns the planned SHORT stop above the pump high."""
if len(candles) < required_bars(STRATEGY_FADE, params):
return None
tf = params["timeframe_min"]
last = candles[-1]
close = float(last[4])
day_ago = float(candles[-bars_for_hours(24, tf) - 1][4])
if day_ago <= 0:
return None
growth = (close / day_ago - 1) * 100
if growth < params["min_growth_24h"]:
return None
if params["min_funding_pct"] > 0 and (funding_rate_pct is None
or funding_rate_pct < params["min_funding_pct"]):
return None
window = candles[-bars_for_hours(params["high_lookback_hours"], tf):]
high_index = max(range(len(window)), key=lambda index: float(window[index][2]))
high = float(window[high_index][2])
if high_index == len(window) - 1:
return None # the pump is still printing new highs
if close > high * (1 - params["pullback_pct"] / 100):
return None
vwap = turnover_vwap(candles[-bars_for_hours(params["vwap_hours"], tf):])
if vwap is None or close >= vwap:
return None
atr = average_true_range(candles, int(params["atr_period"]))
if atr is None:
return None
return {"side": "short", "atr": atr, "high": high, "stop": high + params["stop_buffer_atr"] * atr,
"vwap": vwap, "growth": growth, "close": close, "candle_start": int(last[0])}
def evaluate_signal(mode: str, candles: list[list[float]], params: dict[str, float],
funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None:
if mode == STRATEGY_BREAKOUT:
return evaluate_breakout(candles, params, funding_rate_pct, btc_ok)
if mode == STRATEGY_FADE:
return evaluate_fade(candles, params, funding_rate_pct)
return None
def entry_plan(signal: dict, entry_price: float, params: dict[str, float]) -> dict | None:
"""Stop and targets for an entry at ``entry_price``; None when the signal is no longer valid."""
side = signal["side"]
if entry_price <= 0:
return None
if side == "long":
if entry_price <= signal["level"]:
return None # price fell back under the breakout level before the fill
stop = entry_price - params["stop_atr"] * signal["atr"]
if stop <= 0:
return None
else:
stop = signal["stop"]
if entry_price >= stop or (stop / entry_price - 1) * 100 > params["max_stop_pct"]:
return None
risk = abs(entry_price - stop)
sign = side_sign(side)
partial = (entry_price + sign * params["partial_r"] * risk
if params["partial_r"] > 0 and params["partial_pct"] > 0 else None)
final = entry_price + sign * params["take_profit_r"] * risk if params["take_profit_r"] > 0 else None
if final is not None and final <= 0:
final = None
if partial is not None and partial <= 0:
partial = None
return {"side": side, "stop": stop, "risk": risk, "atr": signal["atr"],
"partial_target": partial, "final_target": final}
def breakeven_price(side: str, entry: float, fee_pct: float) -> float:
cover = fee_cover_pct(fee_pct) / 100
return entry * (1 + cover) if side == "long" else entry * (1 - cover)
def tighten_stop(side: str, stop: float, candidate: float) -> float:
"""Stops only move in the trade's favour."""
return max(stop, candidate) if side == "long" else min(stop, candidate)
def trailing_stop(side: str, stop: float, extreme: float, atr: float, trail_atr: float) -> float:
if trail_atr <= 0 or atr <= 0:
return stop
candidate = extreme - trail_atr * atr if side == "long" else extreme + trail_atr * atr
return tighten_stop(side, stop, candidate)
def trailing_active(partial_done: bool, params: dict[str, float]) -> bool:
"""Trail from the start without a partial exit, otherwise only after it."""
return params["trail_atr"] > 0 and (partial_done or params["partial_r"] <= 0 or params["partial_pct"] <= 0)
def stop_hit(side: str, price: float, stop: float) -> bool:
return price <= stop if side == "long" else price >= stop
def target_hit(side: str, price: float, target: float | None) -> bool:
if target is None or target <= 0:
return False
return price >= target if side == "long" else price <= target
+334
View File
@@ -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()
+148
View File
@@ -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()
+314
View File
@@ -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()
+124
View File
@@ -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()
+74
View File
@@ -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()
+175
View File
@@ -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()
+86
View File
@@ -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()
+523
View File
@@ -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()
+120
View File
@@ -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()
+131
View File
@@ -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()
+64
View File
@@ -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()
+523
View File
@@ -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("<iH", data, 76, -548, 30)
data[88:120] = bytes([7]) * 32
data[120:152] = bytes([9]) * 32
active_id, bin_step, mint_x, mint_y = sh.dlmm_state(bytes(data))
self.assertEqual((active_id, bin_step), (-548, 30))
self.assertEqual(mint_x, sh.b58encode(bytes([7]) * 32))
# SI/SOL pool seen live: (1.003) ** -548 × 10 ** (6 − 9) ≈ 0.0001937 SOL per SI
self.assertAlmostEqual(sh.dlmm_price(-548, 30, 6, 9), 0.0001937, delta=0.000001)
def test_clmm_layouts_and_price(self):
sqrt = int((2.0 ** 0.5) * 2 ** 64) # price 2.0 before decimals
orca = bytearray(653)
orca[65:81] = sqrt.to_bytes(16, "little")
orca[101:133], orca[181:213] = bytes([1]) * 32, bytes([2]) * 32
s, a, b = sh.clmm_state(sh.ORCA_WHIRLPOOL, bytes(orca))
self.assertEqual((s, a, b), (sqrt, sh.b58encode(bytes([1]) * 32), sh.b58encode(bytes([2]) * 32)))
cake = bytearray(1544)
cake[253:269] = sqrt.to_bytes(16, "little")
cake[73:105], cake[105:137] = bytes([3]) * 32, bytes([4]) * 32
s, a, b = sh.clmm_state(sh.PANCAKE_CLMM, bytes(cake))
self.assertEqual((s, a, b), (sqrt, sh.b58encode(bytes([3]) * 32), sh.b58encode(bytes([4]) * 32)))
self.assertAlmostEqual(sh.clmm_price(sqrt, 9, 6), 2000.0, places=6)
# PUMP/SOL PancakeSwap pool seen live: 22866 PUMP per SOL → ≈ 0.00458 $ at SOL 104.7
self.assertAlmostEqual(1 / 22866.39 * 104.73, 0.00458, delta=0.00001)
def test_mexc_messages_and_tickers(self):
import queue as q
feed = sh.MexcFeed("SI_USDT", q.Queue(), contract_size=10)
(kind, book), = feed.parse({"channel": "push.depth.full", "data": {
"asks": [[0.0202, 2104, 10], [0.02023, 149, 1]], "bids": [[0.02012, 17, 1]]}})
ob = sh.OrderBook()
ob.apply_snapshot(book)
self.assertEqual(ob.best(), (0.02012, 0.0202))
self.assertAlmostEqual(book["asks"][0]["size"], 2104 * 10 * 0.0202)
(kind, trades), = feed.parse({"channel": "push.deal", "data": [{"p": 0.02011, "v": 71, "T": 2,
"t": 1792184357496}]})
self.assertEqual((kind, trades[0]["side"]), ("trades", "Sell"))
self.assertEqual(lead_window.futures_ticker("siusdt", "mexc"), "SI_USDT")
self.assertEqual(lead_window.futures_ticker("SI_USDT", "bybit"), "SIUSDT")
def test_fees_follow_the_exchange(self):
for exchange, fee_in in (("mexc", 0.02), ("bybit", 0.055), ("binance", 0.05)):
tr = trader(mode="vector", vector_window_seconds=2, vector_min_move_pct=0.05, follow_exchange=exchange)
t = feed_quiet(tr, seconds=3)
tr.on_leader(t, 0.08008 - 5 * TICK, 0.08008 + 5 * TICK)
self.assertAlmostEqual(tr.position.fee_in, 100.0 * fee_in / 100, msg=exchange)
def test_connections_are_kept_and_added(self):
from unittest import mock
with tempfile.TemporaryDirectory() as folder, \
mock.patch.object(lead_window, "REMOVED_FILE", Path(folder) / "removed.json"): # not the user's own
path = Path(folder) / "c.json"
conns = lead_window.load_connections(path) # no file: the known ones
names = [lead_window.connection_name(c) for c in conns]
self.assertTrue(any(n.startswith("ZEREBRO: DEX пул 3sjNoC") and "Binance" in n for n in names))
self.assertTrue(any(n.startswith("SI: DEX пул") and "MEXC" in n for n in names))
new = {"lead_market": "futures", "lead_ticker": "WIFUSDTM", "lead_pool": "", "follow_exchange": "bybit",
"follow_ticker": "WIFUSDT"}
lead_window.remember_connection(conns, new, path)
lead_window.remember_connection(conns, new, path) # no duplicate
again = lead_window.load_connections(path)
self.assertEqual(sum(lead_window.same_connection(c, new) for c in again), 1)
self.assertEqual(len(again), len(lead_window.DEFAULT_CONNECTIONS) + 1)
def _random_walk(self, n, seed):
import random
rnd = random.Random(seed)
p, out = 0.08, []
for _ in range(n):
p *= 1 + rnd.choice((-1, 0, 1)) * 0.0008
out.append(p)
return out
def _feed_lagged(self, tr, path, follower_delay_steps, seconds=200):
"""Grid every 0.5 s; follower copies the leader `follower_delay_steps` steps later (negative: earlier)."""
n = int(seconds / 0.5)
for i in range(n):
t = T0 + i * 0.5
li = min(max(i, 0), len(path) - 1)
fi = min(max(i - follower_delay_steps, 0), len(path) - 1)
tr.on_leader(t, path[li], path[li])
tr.on_book(t + 0.01, follower_book(round(path[fi], 5)), TICK)
return T0 + n * 0.5
def test_live_leader_check(self):
path = self._random_walk(500, 7)
tr = trader(mode="vector", require_leader=True, enabled=False)
self._feed_lagged(tr, path, 2) # follower 1 s behind: the leader leads
self.assertGreater(tr.policy.leadership["edge"], 0.3)
self.assertEqual(tr.policy.leader_block(), "")
since = tr.policy.leadership["since"]
self.assertIsNotNone(since) # suitable since the first check that passed
self.assertLessEqual(since, tr.policy.next_check)
tr = trader(mode="vector", require_leader=True, enabled=False)
self._feed_lagged(tr, path, -2) # follower 1 s ahead: it leads, entries blocked
self.assertIsNone(tr.policy.leadership["since"])
self.assertLess(tr.policy.leadership["edge"], -0.3)
self.assertIn("сейчас ведёт Bybit", tr.policy.leader_block())
def test_basis_mode_enters_on_a_gap_and_closes_when_it_closes(self):
tr = trader(mode="basis", basis_window_seconds=30, basis_entry_z=2.0, basis_exit_z=0.5,
basis_min_gap_pct=0.15)
self.assertIsInstance(tr.policy, sp.BasisPolicy)
t = T0
for i in range(120): # 60 s: leader ≈ follower with small noise
wobble = 0.00001 if i % 2 else -0.00001
tr.on_leader(t, 0.08 + wobble, 0.08 + wobble)
tr.on_book(t + 0.01, follower_book(0.08), TICK)
t += 0.5
self.assertIsNone(tr.position)
tr.on_leader(t, 0.0804, 0.0804) # DEX jumps +0.5 %, futures not yet
tr.on_book(t + 0.01, follower_book(0.08), TICK)
pos = tr.position
self.assertIsNotNone(pos, tr.policy.status)
self.assertEqual(pos.side, "LONG")
self.assertIn("сверх обычного", pos.regime)
tr.on_book(t + 1.0, follower_book(0.0804), TICK) # futures caught up: gap closed
self.assertIsNone(tr.position)
self.assertEqual(tr.trades[-1].reason, "разрыв закрылся")
self.assertGreater(tr.trades[-1].pct, 0)
def test_window_validation(self):
good = {"budget": 300, "stake": 15, "leverage": 1, "min_target_pct": 0.2, "stop_loss_pct": 0.3,
"max_hold_seconds": 30, "cooldown_ms": 500, "lead_threshold_pct": 0.05, "lead_window_ms": 500,
"vector_window_seconds": 10, "vector_min_move_pct": 0.05, "max_positions": 3, "entry_gap_seconds": 1,
"min_confidence": 0.6, "auto_tp_share_pct": 100, "auto_tp_horizon_seconds": 10}
self.assertIn("доля", lead_window.validate(dict(good, auto_tp_share_pct=0)))
self.assertIn("уверенность", lead_window.validate(dict(good, min_confidence=1.5)))
self.assertIn("целое", lead_window.validate(dict(good, max_positions=1.5)))
self.assertEqual(lead_window.validate(good), "")
self.assertIn("стоп", lead_window.validate(dict(good, stop_loss_pct=0)))
self.assertIn("окно", lead_window.validate(dict(good, lead_window_ms=10)))
if __name__ == "__main__":
unittest.main()
+85
View File
@@ -0,0 +1,85 @@
"""The smallest trade amount both legs accept (spot minimum order, perp minimum lot and notional): paper and real
trades of the spot–futures tabs and «between exchanges» are made only above it. No network: rules are set by hand."""
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 minorder # noqa: E402
from test_basis import pair # noqa: E402
class MinEntryTests(unittest.TestCase):
def setUp(self):
self.rules = minorder.Rules()
self.patch = mock.patch.object(minorder, "RULES", self.rules)
self.patch.start()
self.dir = tempfile.TemporaryDirectory()
def tearDown(self):
self.patch.stop()
self.dir.cleanup()
def test_both_legs_decide(self):
# MEXC CATE: spot 1 $ minimum, perp 1 contract = 100 coins → 100 coins × 0.0754 / (1 − 0.05 %) ≈ 7.54 $
self.rules.set("MEXC", "spot", {"CATE": {"usd": 1.0, "coins": 1.0}})
self.rules.set("MEXC", "fut", {"CATE_USDT": {"coins": 100.0, "usd": 0.0}})
m = self.rules.min_entry("MEXC", "CATE", 0.0754, "MEXC", "CATE_USDT", 0.0786, 0.05)
self.assertAlmostEqual(m["fut"], 100 * 0.0754 / 0.9995)
self.assertEqual(m["usd"], 7.7) # × 1.02 margin, rounded up to a cent
# the spot leg can be the bigger one (Bybit spot 5 $), and the perp's minimum notional counts too
self.rules.set("Bybit", "spot", {"DOGE": {"usd": 5.0, "coins": 0.1}})
self.rules.set("Bybit", "fut", {"DOGEUSDT": {"coins": 1.0, "usd": 5.0}})
m = self.rules.min_entry("Bybit", "DOGE", 0.2, "Bybit", "DOGEUSDT", 0.2, 0.1)
self.assertAlmostEqual(m["spot"], 5.0)
self.assertAlmostEqual(m["fut"], 25 * 0.2 / 0.999) # 5 $ notional = 25 coins
self.assertIn("меньше мин. входа", minorder.too_small(5.0, m, "Bybit", "Bybit"))
self.assertEqual(minorder.too_small(6.0, m, "Bybit", "Bybit"), "")
def test_unknown_rules_do_not_block(self):
self.assertIsNone(self.rules.min_entry("Gate", "XYZ", 1.0, "Gate", "XYZ_USDT", 1.0, 0.1))
self.assertEqual(minorder.too_small(1.0, None, "Gate", "Gate"), "")
self.rules.set("Gate", "fut", {"XYZ_USDT": {"coins": 10.0, "usd": 0.0}}) # one leg known: it counts
self.assertIsNone(self.rules.min_entry("Gate", "XYZ", 1.0, "Gate", "XYZ_USDT", 1.0, 0.1)["spot"])
def test_basis_paper_not_entered_below_minimum(self):
e = basis.BasisEngine("mexc", Path(self.dir.name), start=False)
e.settings.running, e.settings.all_coins, e.settings.amount = True, True, 5.0
e.pairs = {"BIG": pair("BIG"), "OK": pair("OK")}
self.rules.set("MEXC", "fut", {"BIGUSDT": {"coins": 100.0, "usd": 0.0}, "OKUSDT": {"coins": 1.0, "usd": 0.0}})
e.step(1000.0)
self.assertEqual([p.base for p in e.positions], ["OK"])
row = {r["base"]: r for r in e.view()["rows"]}["BIG"]
self.assertFalse(row["fits"])
self.assertIn("меньше мин. входа 102.16 $ (фьюч MEXC ≥ 100.15 $)", row["why"]) # 100 × 1.001 / 0.9995 × 1.02
self.assertAlmostEqual(row["min_entry"], 102.16)
def test_cross_paper_not_entered_below_minimum(self):
e = cross.CrossEngine(Path(self.dir.name), start=False)
e.settings.running, e.settings.history_min, e.settings.amount = True, 0.0, 5.0
key = "XYZ|Gate|Binance"
e.links = {key: cross.Link("XYZ", "Gate", "Binance", "XYZUSDT", "XYZUSDT", 0.999, 1.0, 1.02, 1.021,
1e5, 1e5, 1e7, 1e7, 0.0001, 8.0)}
e.usual, e.seen_since = {key: 0.5}, {key: 0.0}
self.rules.set("Gate", "spot", {"XYZ": {"usd": 3.0, "coins": 0.01}})
self.rules.set("Binance", "fut", {"XYZUSDT": {"coins": 1.0, "usd": 5.0}}) # 5 $ notional at 1.02
e.step(1000.0)
self.assertEqual(e.positions, [])
row = e.view()["rows"][0]
self.assertIn("фьюч Binance ≥", row["why"])
e.settings.amount = 6.0
e.step(1001.0)
self.assertEqual(len(e.positions), 1)
if __name__ == "__main__":
unittest.main()
+115
View File
@@ -0,0 +1,115 @@
"""Accounts in the hedge (dual) position mode: Gate answers a position as a LIST (long + short rows), Bybit wants the
side's positionIdx (1 long, 2 short). No request reaches an exchange: the signed calls are fakes."""
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 GateDualModeTests(unittest.TestCase):
def gate(self, answer):
g = live.Gate("k", "s")
g.rules["fut:POD_USDT"] = {"size": 10.0, "min": 1.0}
def call(method, path, params=None, body=None):
if isinstance(answer, Exception):
raise answer
return answer
g._call = call
return g
def test_dual_mode_list_is_read(self):
# the user's POD short on 2026-10-22: read as 0 before — every Gate short looked closed
g = self.gate([{"mode": "dual_long", "size": 0, "liq_price": "0"},
{"mode": "dual_short", "size": -1, "liq_price": "3.5177"}])
self.assertEqual(g.fut_position("POD_USDT"), -10.0)
self.assertEqual(g.fut_liq_price("POD_USDT"), 3.5177)
def test_single_mode_and_no_position(self):
self.assertEqual(self.gate({"size": -2, "liq_price": "1"}).fut_position("POD_USDT"), -20.0)
self.assertEqual(self.gate(live.LiveError('HTTP 400: {"label":"POSITION_NOT_FOUND"}')).fut_position("POD_USDT"),
0.0)
with self.assertRaises(live.LiveError): # any other error is not «no position»
self.gate(live.LiveError("HTTP 500: busy")).fut_position("POD_USDT")
class BybitHedgeModeTests(unittest.TestCase):
def setUp(self):
self.b = live.Bybit("k", "s")
self.b.rules["linear:ZKUSDT"] = {"step": 1.0, "min": 1.0, "tick": 0.0001}
self.sent = []
def call(method, path, params=None):
if path == "/v5/order/create":
self.sent.append(dict(params))
want = 0 if self.mode == "oneway" else (2 if (params["side"] == "Sell") != bool(params.get("reduceOnly"))
else 1)
if params["positionIdx"] != want:
raise live.LiveError("Bybit 10001: position idx not match position mode")
return {"orderId": f"O{len(self.sent)}"}
raise AssertionError(path)
self.b._call = call
def test_hedge_mode_learned_from_the_refusal(self):
self.mode = "hedge"
self.assertEqual(self.b.fut_limit("ZKUSDT", "sell", 500, 0.0138), "O2") # refused once, then idx 2
self.assertEqual([p["positionIdx"] for p in self.sent], [0, 2])
self.b.fut_limit("ZKUSDT", "buy", 500, 0.0130, reduce_only=True) # closing the short: idx 2 at once
self.assertEqual(self.sent[-1]["positionIdx"], 2)
self.b.fut_take_profit("ZKUSDT", "buy", 500, 0.0125)
self.assertEqual(self.sent[-1]["positionIdx"], 2)
self.assertEqual(len(self.sent), 4)
def test_one_way_mode_unchanged(self):
self.mode = "oneway"
self.b.fut_limit("ZKUSDT", "sell", 500, 0.0138)
self.assertEqual([p["positionIdx"] for p in self.sent], [0])
class MexcQuantityScaleTests(unittest.TestCase):
def test_sale_retried_with_fewer_decimals(self):
# SUE on MEXC, 2026-10-22: 27481.05 refused («quantity scale is invalid») although 2 decimals are listed
m = live.Mexc("k", "s")
m.rules["SUEUSDT"] = {"step": 0.01}
sent = []
def order(params, base):
sent.append(params["quantity"])
if "." in params["quantity"]:
raise live.LiveError('HTTP 400: {"msg":" quantity scale is invalid","code":400}')
return live.Fill(float(params["quantity"]), 0.000328, 0.007, "1")
m._spot_order = order
fill = m.spot_sell("SUE", 27481.05)
self.assertEqual(sent, ["27481.05", "27481"]) # exact text, then one decimal fewer
self.assertEqual(fill.coins, 27481.0)
self.assertAlmostEqual(m.rules["SUEUSDT"]["step"], 0.1) # remembered for the next sale
m.spot_sell("SUE", 100.75)
self.assertEqual(sent[-2:], ["100.7", "100"])
self.assertEqual(m.rules["SUEUSDT"]["step"], 1.0)
def test_numbers_sent_exactly(self):
self.assertEqual([live._num(x) for x in (27481.05, 0.1 + 0.2, 1e-05, 10.0, 5.0600000000000005)],
["27481.05", "0.3", "0.00001", "10", "5.06"])
def test_other_errors_not_retried(self):
m = live.Mexc("k", "s")
m.rules["SUEUSDT"] = {"step": 0.01}
calls = []
def order(params, base):
calls.append(params)
raise live.LiveError("HTTP 400: insufficient balance")
m._spot_order = order
with self.assertRaises(live.LiveError):
m.spot_sell("SUE", 10.5)
self.assertEqual(len(calls), 1)
if __name__ == "__main__":
unittest.main()
+1030
View File
File diff suppressed because it is too large. Load diff
+133
View File
@@ -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()
+219
View File
@@ -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()
+219
View File
@@ -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()
+77
View File
@@ -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()
+272
View File
@@ -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()
+67
View File
@@ -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()
+1453
View File
File diff suppressed because it is too large. Load diff
+849
View File
@@ -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/<coin>.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()
+26
View File
@@ -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
+16
View File
@@ -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
+6
View File
@@ -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)
+5
View File
@@ -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
+52
View File
@@ -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.
- Удалить программу — остановите сервер и удалите папку (и ярлык из автозагрузки, если ставили).
@@ -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