"""The one arbitrage mode (paper or real): buy the coin on spot on exchange A where it is cheap and sell the same coins where they are dear — close both legs when the gap is back to its usual level. Three kinds of link, each switched on in the settings: «sf» spot of A → perpetual of B (A ≠ B): the coins bought on A, the same coins shorted on B's perp; «in» spot → perpetual inside one exchange (A = B): the classic spot–futures basis; «ss» spot of A → spot of B: the coins bought on A, the same coins sold on B from a stock the user keeps there (spot cannot be shorted); the close sells A and buys the stock back on B. Between two exchanges nothing ties the perp of B to the spot of A (within one exchange the funding/index does), so the gap may stay wide for a long time: an offset between the exchanges, a coin whose deposits are closed on A, or a different token under the same ticker. That is why the entry is not «gap above X» but «gap above its USUAL level by X»: the usual gap of every (coin, spot exchange, perp exchange) is followed over the last ~30 minutes, and the position is closed when the gap returns to the usual level it had at the entry. entry gap = perp bid (B) / spot ask (A) − 1 exit gap = perp ask (B) / spot bid (A) − 1 usual = average of the mid gap over the last USUAL_WINDOW_S seconds (EMA), per coin|A|B Result of a trade = spot leg (A) + perp leg (B) − the four taker fees of the two exchanges + funding on B. Real mode: the short is opened first on B (a limit order at the signal's bid, or at market), then the same coins are bought on spot on A; the close buys the short back on B, checks that B shows no short left, then sells the coins on A. One entry at a time, the next only after the previous is confirmed. The fee rates of every exchange are settings; after each real trade they are replaced by what the exchanges actually charged, so the table counts with them. """ from __future__ import annotations import json from persistence import atomic_write_json import queue import threading import time from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, dataclass, field, fields from pathlib import Path import arb import minorder ROOT = Path(__file__).resolve().parent DATA_DIR = ROOT / "web_sim_data" POLL_S = 3.0 USUAL_WINDOW_S = 1800.0 KEEP_TRADES = 500 SPOT_FEE = dict(arb.SPOT_TAKER) FUT_FEE = {"Bybit": 0.055, "Binance": 0.05, "MEXC": 0.02, "HTX": 0.05, "Gate": 0.05} # perps of an exchange's own fee group with a higher rate: Bybit's Innovation Zone (bybit.com/fee, regular user) FUT_FEE_INNOVATION = {"Bybit": 0.11} INNOVATION_S = 3600.0 MAX_LEARNED_FEE = 1.0 # a «rate» above this from a fill is a misread, not a fee # Liquidation of the short on B: nothing on B hedges it (the coins are on A), so B's futures money alone carries # its loss when the coin rises. Cross margin, one short of N $ at P0 with E $ of futures money behind it: # liquidation when E − N·x = mmr·N·(1 + x) → x = (E/N − mmr) / (1 + mmr) (x = price rise to liquidation) DEFAULT_LIMIT = 3 # open trades per exchange (a trade counts on its spot exchange and its perp one) LIQ_MMR_PCT = 1.0 # maintenance margin rate assumed, % (small coins' tiers: 0.5–1 %, safe side) LIQ_CHECK_S = 30.0 # the exchange's own liquidation price of an open short is read this often def liq_distance(equity: float, notional: float, mmr_pct: float = LIQ_MMR_PCT) -> float: """Price rise, %, at which a short of `notional` $ backed by `equity` $ of futures money is liquidated.""" if notional <= 0: return float("inf") mmr = mmr_pct / 100 return (equity / notional - mmr) / (1 + mmr) * 100 def equity_for(distance_pct: float, notional: float, mmr_pct: float = LIQ_MMR_PCT) -> float: """Futures money, $, a short of `notional` $ needs to be liquidated only `distance_pct` % above the entry.""" mmr = mmr_pct / 100 return notional * ((1 + mmr) * distance_pct / 100 + mmr) def bybit_innovation_symbols() -> set[str]: """Bybit USDT perps of the Innovation Zone (symbolType «innovation»).""" out, cursor = set(), "" while True: res = arb._get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000" + (f"&cursor={cursor}" if cursor else ""))["result"] out |= {x["symbol"] for x in res["list"] if x.get("symbolType") == "innovation"} cursor = res.get("nextPageCursor") or "" if not cursor or not res["list"]: return out def fut_fee(exchange: str, fees: dict | None = None, innovation: bool = False) -> float: """The perp taker rate: the engine's table if given, else measured from the user's real fills where known (MEXC charges them 0.08 %), else the exchange's base rate. `innovation`: the coin is in the exchange's Innovation Zone, which has its own rate (Bybit 0.11 %).""" if innovation: if fees and "fut_innovation" in fees.get(exchange, {}): return fees[exchange]["fut_innovation"] if exchange in FUT_FEE_INNOVATION: return FUT_FEE_INNOVATION[exchange] if fees and exchange in fees: return fees[exchange]["fut"] try: import real_mirror return real_mirror.FEES.get(exchange.lower()) or FUT_FEE.get(exchange, 0.05) except Exception: return FUT_FEE.get(exchange, 0.05) def spot_fee(exchange: str, fees: dict | None = None) -> float: if fees and exchange in fees: return fees[exchange]["spot"] return SPOT_FEE.get(exchange, 0.1) def b_fee(exchange: str, fees: dict | None = None, innovation: bool = False, ss: bool = False) -> float: """Taker rate of the second leg: B's spot for a spot–spot link, B's perp otherwise.""" return spot_fee(exchange, fees) if ss else fut_fee(exchange, fees, innovation) def link_key(base: str, a: str, b: str, ss: bool = False) -> str: return f"{base}|{a}|{b}" + ("|ss" if ss else "") KIND_NAMES = {"sf": "спот → фьюч", "in": "внутри биржи", "ss": "спот → спот"} def kind_of(a: str, b: str, ss: bool) -> str: return "ss" if ss else "in" if a == b else "sf" def default_fees() -> dict: try: import real_mirror measured = set(real_mirror.FEES) except Exception: measured = set() out = {ex: {"spot": spot_fee(ex), "fut": fut_fee(ex), "spot_src": "", "fut_src": "по реальным сделкам" if ex.lower() in measured else ""} for ex in arb.EXCHANGES} for ex, rate in FUT_FEE_INNOVATION.items(): out[ex].update(fut_innovation=rate, fut_innovation_src="") return out FEE_LEGS = ("spot", "fut", "fut_innovation") @dataclass class CrossSettings: running: bool = False amount: float = 100.0 # $ spent on spot (A); the same coins shorted on the perp (B) # THE entry criterion: net profit % if the gap returns to its usual level = # (gap now − usual) − exit margin − the four taker fees of the two exchanges min_net_pct: float = 0.2 max_gap_pct: float = 10.0 # above: a broken price or a different token history_min: float = 15.0 # minutes of watching the pair before its «usual» is trusted exit_over_usual_pct: float = 0.05 # close when the gap is back to (usual at the entry + this) stop_widen_pct: float = 2.0 # close at a loss when the gap widens this much over the entry (0 = off) max_hold_hours: float = 24.0 # close after this long whatever the gap (0 = off) cooldown_s: float = 300.0 min_turnover: float = 200000.0 # 24h turnover of each leg, $ use_bybit: bool = True # an exchange switched off is neither searched nor traded use_binance: bool = True use_mexc: bool = True use_htx: bool = True use_gate: bool = True search_sf: bool = True # spot of A → perp of B between exchanges search_in: bool = True # spot → perp inside one exchange search_ss: bool = True # spot of A → spot of B (real: needs the coin's stock on B) real: bool = False # new trades as real orders with the API keys of both exchanges auto_transfer: bool = True # USDT moved between spot and futures WITHIN an exchange when one is short entry_limit: bool = True # real entry: LIMIT short at the signal's perp bid on B first, then spot on A limit_hold_s: float = 10.0 # …kept this long, then removed (nothing bought if it did not fill) fees_auto: bool = True # after a real trade the fee rates become what the exchanges charged exit_hold_s: float = 3.0 # «back to usual» closes only after the gap has stayed there this long (0 = at once) max_spread_pct: float = 0.5 # a leg whose bid–ask spread is wider is not traded (0 = no check) entry_ioc: bool = True # real: the first leg is a limit order at the confirmed price, the rest cancelled confirm_ms: float = 400.0 # real: the signal is checked twice on the order books, this far apart min_liq_pct: float = 50.0 # no short whose liquidation would be less than this % above the entry liq_close_pct: float = 20.0 # close both legs when the price is this close to the liquidation, % (0 = off) @dataclass class CrossPosition: uid: int base: str spot_ex: str fut_ex: str spot_symbol: str fut_symbol: str opened: float qty: float # coins shorted on B (real: rounded to B's lot) spot_entry: float fut_entry: float entry_gap: float usual: float # the usual gap at the entry: the level the position waits for fees: float next_funding: float funding: float = 0.0 # real positions: the coins held on A, the close in progress (short bought back first, then the spot sold) real: bool = False spot_qty: float = 0.0 closing: str = "" # "" / "fut_done" fut_exit: float = 0.0 exit_fees: float = 0.0 retry_at: float = 0.0 error: str = "" sold_coins: float = 0.0 sold_value: float = 0.0 sold_fees: float = 0.0 exact: bool = True fills: list = field(default_factory=list) # [exchange, fee leg, fee $, value $, exact] of every order innovation: bool = False # the perp is in B's Innovation Zone: its own fee rate liq_price: float = 0.0 # liquidation price of the short on B, per coin (the exchange's when it reports one) liq_calc: float = 0.0 # the program's own estimate at the entry liq_src: str = "" # "биржа" / "расчёт" liq_checked: float = 0.0 # when the exchange's figure was last read ss: bool = False # spot–spot: the B leg is a sale of the stock on B's spot (fut_* = B's spot) # the prices the decisions were taken at: [time, A price, B price, gap %] — to compare with the fills entry_signal: list = field(default_factory=list) # A ask, B bid confirmed right before the entry orders exit_signal: list = field(default_factory=list) # A bid, B ask when the close was decided exit_since: float = 0.0 # when the gap last came back to the usual level (0 = it is not there now) @property def kind(self) -> str: return kind_of(self.spot_ex, self.fut_ex, self.ss) @property def key(self) -> str: return link_key(self.base, self.spot_ex, self.fut_ex, self.ss) @dataclass class CrossTrade: uid: int base: str spot_ex: str fut_ex: str opened: float closed: float qty: float spot_entry: float spot_exit: float fut_entry: float fut_exit: float entry_gap: float exit_gap: float usual: float spot_pnl: float fut_pnl: float fees: float funding: float net: float reason: str amount: float real: bool = False exact: bool = True kind: str = "sf" entry_signal: list = field(default_factory=list) # [time, A ask, B bid, gap %] of the entry decision exit_signal: list = field(default_factory=list) # [time, A bid, B ask, gap %] of the close decision @dataclass class Link: """One coin, spot on A, perp on B (or B's spot for a spot–spot link), at this moment (prices per coin).""" base: str spot_ex: str fut_ex: str spot_symbol: str fut_symbol: str spot_bid: float spot_ask: float fut_bid: float fut_ask: float spot_depth: float | None # $ at the spot ask fut_depth: float | None # $ at the perp bid spot_turnover: float fut_turnover: float funding: float # per interval, fraction interval_h: float fut_mult: float = 1.0 # coins in one unit of the perp symbol (1000PEPE → 1000) innovation: bool = False # the perp is in B's Innovation Zone (Bybit): a higher fee rate ss: bool = False # spot–spot: fut_* are B's SPOT prices / symbol @property def fut_leg(self) -> str: """Which fee rate of B applies: B's spot (spot–spot), "fut_innovation" for an Innovation Zone coin, else "fut".""" return "spot" if self.ss else "fut_innovation" if self.innovation else "fut" @property def kind(self) -> str: return kind_of(self.spot_ex, self.fut_ex, self.ss) @property def key(self) -> str: return link_key(self.base, self.spot_ex, self.fut_ex, self.ss) @property def entry_gap(self) -> float: return (self.fut_bid / self.spot_ask - 1) * 100 @property def exit_gap(self) -> float: return (self.fut_ask / self.spot_bid - 1) * 100 @property def mid_gap(self) -> float: return ((self.fut_bid + self.fut_ask) / (self.spot_bid + self.spot_ask) - 1) * 100 def build_links(spots: list, futs: list, exchanges: set[str], innovation: set[str] | frozenset = frozenset(), kinds=("sf", "in", "ss")) -> dict[str, Link]: """Every link of the five exchanges' quotes: spot on A with a perp on B (A ≠ B: «sf», A = B: «in») and spot on A with spot on B (A ≠ B: «ss»). `innovation`: "exchange|perp symbol" of the Innovation Zone perps.""" by_base_spot: dict[str, list] = {} for q in spots: # a ticker in other letters (龙虾…) cannot be put into the exchanges' signed requests: not traded if q.exchange in exchanges and q.mult == 1 and q.base.isascii() and \ not (arb.LEVERAGED.search(q.base) and len(q.base) > 3): by_base_spot.setdefault(q.base, []).append(q) by_base_fut: dict[str, list] = {} for q in futs: if q.exchange in exchanges: by_base_fut.setdefault(q.base, []).append(q) out = {} for base, ss in by_base_spot.items(): for s in ss: if min(s.bid, s.ask) <= 0: continue for f in by_base_fut.get(base, []): kind = "in" if s.exchange == f.exchange else "sf" if kind not in kinds or min(f.bid, f.ask) <= 0: continue link = Link(base, s.exchange, f.exchange, s.symbol, f.symbol, s.bid, s.ask, f.bid, f.ask, s.ask_usd, f.bid_usd, s.volume_usd or 0.0, f.volume_usd or 0.0, f.funding or 0.0, f.interval_h or 8.0, f.mult or 1.0, f"{f.exchange}|{f.symbol}" in innovation) out[link.key] = link if "ss" not in kinds: continue for b in ss: # sold on B's spot from the stock kept there if b.exchange == s.exchange or min(b.bid, b.ask) <= 0: continue link = Link(base, s.exchange, b.exchange, s.symbol, b.symbol, s.bid, s.ask, b.bid, b.ask, s.ask_usd, b.bid_usd, s.volume_usd or 0.0, b.volume_usd or 0.0, 0.0, 8.0, 1.0, False, ss=True) out[link.key] = link return out def close_result(pos: CrossPosition, spot_bid: float, fut_ask: float, fees_table: dict | None = None) -> tuple[float, float, float, float]: """(spot leg $, perp leg $, all fees $, net $) of closing at these prices.""" spot_qty = pos.spot_qty or pos.qty # real: the spot leg can hold a little more than the perp's lot if pos.closing == "fut_done": # real close half done: the short is already bought back fut_ask = pos.fut_exit spot_pnl = spot_qty * (spot_bid - pos.spot_entry) fut_pnl = pos.qty * (pos.fut_entry - fut_ask) fees = pos.fees + spot_qty * spot_bid * spot_fee(pos.spot_ex, fees_table) / 100 \ + pos.qty * fut_ask * b_fee(pos.fut_ex, fees_table, pos.innovation, pos.ss) / 100 return spot_pnl, fut_pnl, fees, spot_pnl + fut_pnl - fees + pos.funding def round_trip_fee_pct(spot_ex: str, fut_ex: str, fees: dict | None = None, innovation: bool = False, ss: bool = False) -> float: return 2 * (spot_fee(spot_ex, fees) + b_fee(fut_ex, fees, innovation, ss)) def net_pct(l: "Link", usual: float | None, s: "CrossSettings", fees: dict | None = None) -> float | None: """Net profit, % of the amount, if the gap returns to its usual level: (entry gap − usual) − exit margin − the four taker fees (spot of A in and out, perp of B in and out). None while the usual gap is unknown.""" if usual is None: return None return l.entry_gap - usual - s.exit_over_usual_pct - round_trip_fee_pct(l.spot_ex, l.fut_ex, fees, l.innovation, l.ss) def _client(exchange: str): import live return live.client(exchange.lower()) class ThinBook(Exception): """The order book holds less than the trade amount at the moment.""" def _quote_now(l: "Link", usd: float) -> tuple[float, float, float, float, float, float]: """This link from the ORDER BOOKS right now, for a trade of `usd` $, per coin: (A best bid, A average buy price for the amount, B average sale price for the amount, B best ask, A spread %, B spread %).""" import fastquote a = fastquote.execution(l.spot_ex, "spot", l.spot_symbol, usd) b = fastquote.execution(l.fut_ex, "spot" if l.ss else "fut", l.fut_symbol, usd) if a["ask"] is None: raise ThinBook(f"на споте {l.spot_ex} в стакане меньше {usd:g} $") if b["bid"] is None: raise ThinBook(f"на {'споте' if l.ss else 'фьючерсе'} {l.fut_ex} в стакане меньше {usd:g} $") return (a["best_bid"], a["ask"], b["bid"] / l.fut_mult, b["best_ask"] / l.fut_mult, a["spread_pct"], b["spread_pct"]) class CrossEngine: """One engine per kind of trading: paper (simulation) or real — each started and stopped by itself. The real one follows the paper one: it is handed the same prices and usual gaps every cycle (no second set of requests).""" mode = "cross" def __init__(self, data_dir: Path = DATA_DIR, start: bool = True, real: bool = False, leader: "CrossEngine | None" = None) -> None: self.is_real = real self.key = "cross_real" if real else "cross" self.file = data_dir / ("basis_cross_real.json" if real else "basis_cross.json") self.followers: list[CrossEngine] = [] self.leader: CrossEngine | None = None self.lock = threading.RLock() self.settings = CrossSettings() self.positions: list[CrossPosition] = [] self.trades: list[CrossTrade] = [] self.next_uid = 1 self.last_close: dict[str, float] = {} self.links: dict[str, Link] = {} self.usual: dict[str, float] = {} # key → EMA of the mid gap self.seen_since: dict[str, float] = {} # key → when the pair was first seen (for the history check) self.last_seen: dict[str, float] = {} self.status, self.updated, self.cycle_ms = "загружаю цены пяти бирж…", 0.0, 0 self.ex_status: dict[str, str] = {} self.fut, self.spot = arb.Fetchers(), arb.SpotFetchers() self.usual_file = data_dir / "basis_cross_usual.json" self.usual_saved = 0.0 self.fast_seen: dict[str, float] = {} # link → when the fast watch last priced it self.fast_ms = 0 # fee rates of every exchange, %: {"MEXC": {"spot": .., "fut": .., "spot_src": "", "fut_src": ""}} self.fees: dict[str, dict] = default_fees() self.limits: dict[str, int] = {ex: DEFAULT_LIMIT for ex in arb.EXCHANGES} # open trades per exchange self.innovation: set[str] = set() # "Bybit|SYMBOL" of the Innovation Zone perps self.innovation_time = 0.0 # real trading self.client_for = _client self.quote_now = _quote_now if start else None # fresh prices right before a real entry (tests: none) self.balances: dict = {} # web_sim's BALANCES (exchange key → account figures) self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"} self.opening: set[str] = set() # coins with a real entry in progress self.jobs: queue.Queue = queue.Queue() self.busy: set[int] = set() # real positions whose close is being sent right now self.real_block: dict[str, tuple[str, float]] = {} # coin → (why it cannot be traded for real, until) self.real_pause_until, self.real_pause_reason = 0.0, "" self.pending: dict[str, dict] = {} # coin → real entry in progress (written BEFORE any order) self.recover: dict[str, dict] = {} # pending entries found after a restart self.funds_low: dict[str, str] = {} # exchange → why it is out of the search (too little money) self.migrated: list[str] = [] # single-exchange tabs whose positions were taken over self.cand: dict[str, dict] = {} # key → its row from the last cycle (+ hot refreshes) self.cand_time = 0.0 self.hot: list[str] = [] # links with a net profit > 0, priced every HOT_S if real and not self.file.exists(): self._seed_from(data_dir / "basis_cross.json") # the first real engine starts from the paper settings self._load() self.settings.real = real # fixed by the tab, not a setting self._migrate_venues(data_dir) if leader is None: self._load_usual() else: # the same learnt gaps, the same price list self.leader = leader self.usual, self.seen_since, self.last_seen = leader.usual, leader.seen_since, leader.last_seen self.innovation = leader.innovation leader.followers.append(self) if start: if leader is None: threading.Thread(target=self._loop, daemon=True).start() threading.Thread(target=self._hot_loop, daemon=True).start() threading.Thread(target=self._fast_loop, daemon=True).start() threading.Thread(target=self._worker, daemon=True).start() import basis basis.ENGINES.append(self) # --- persistence ----------------------------------------------------------------------------------------- def _load(self) -> None: try: d = json.loads(self.file.read_text(encoding="utf-8")) except (OSError, ValueError): return known = {f.name for f in fields(CrossSettings)} for k, v in (d.get("settings") or {}).items(): if k in known: setattr(self.settings, k, type(getattr(self.settings, k))(v)) import basis self.settings.max_gap_pct = min(self.settings.max_gap_pct, basis.HARD_MAX_GAP_PCT) for ex, f in (d.get("fees") or {}).items(): if ex in self.fees: self.fees[ex].update({k: f[k] for leg in FEE_LEGS for k in (leg, f"{leg}_src") if k in f and leg in self.fees[ex]}) # open trades per exchange; before, one limit for all: it becomes the limit of every exchange old = (d.get("settings") or {}).get("max_positions") for ex in self.limits: v = (d.get("limits") or {}).get(ex, old) if v is not None: self.limits[ex] = int(v) self.positions = [CrossPosition(**p) for p in d.get("positions", [])] self.trades = [CrossTrade(**t) for t in d.get("trades", [])] self.next_uid = d.get("next_uid", 1) self.baseline = d.get("baseline") or {} self.recover = dict(d.get("pending") or {}) self.migrated = list(d.get("migrated") or []) def _seed_from(self, paper_file: Path) -> None: """The real engine's first settings, fee table and limits: those of the simulation (stopped).""" try: d = json.loads(paper_file.read_text(encoding="utf-8")) except (OSError, ValueError): return settings = {**(d.get("settings") or {}), "running": False, "real": True} self.file.parent.mkdir(exist_ok=True) self.file.write_text(json.dumps({"settings": settings, "fees": d.get("fees") or {}, "limits": d.get("limits") or {}, "next_uid": d.get("next_uid", 1), "migrated": []}, ensure_ascii=False, indent=1), encoding="utf-8") def elsewhere(self, base: str) -> str: """Another engine of the same kind (paper / real) already trading this coin — "" if none. Paper and real are independent of each other.""" import basis for e in list(basis.ENGINES): if e is not self and getattr(e, "is_real", None) == self.is_real and \ (any(p.base == base for p in list(e.positions)) or base in getattr(e, "opening", set())): return "другой движок" return "" VENUE_FILES = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC", "htx": "HTX", "gate": "Gate"} def _migrate_venues(self, data_dir: Path) -> None: """The spot–futures tabs of single exchanges are now the «inside one exchange» links of this mode: their open positions (real ones included — the program keeps closing them) and their closed trades move here, and the old file is renamed so it is never read again.""" moved, done = [], False for key, ex in self.VENUE_FILES.items(): f = data_dir / f"basis_{key}.json" if key in self.migrated: continue try: d = json.loads(f.read_text(encoding="utf-8")) except (OSError, ValueError): continue done = True self.migrated.append(key) old_exit = float((d.get("settings") or {}).get("exit_gap_pct", 0.05)) for p in d.get("positions", []): if bool(p.get("real", False)) != self.is_real: # paper ones to the simulation, real ones here continue # the old rule closed at «gap ≤ exit_gap_pct»: the same level here (usual + exit margin) pos = CrossPosition( self.next_uid, p["base"], ex, ex, "", p.get("fut_symbol", ""), p["opened"], p["qty"], p["spot_entry"], p["fut_entry"], p["entry_gap"], old_exit - self.settings.exit_over_usual_pct, p.get("fees", 0.0), p.get("next_funding", 0.0), p.get("funding", 0.0), real=p.get("real", False), spot_qty=p.get("spot_qty", 0.0), closing=p.get("closing", ""), fut_exit=p.get("fut_exit", 0.0), exit_fees=p.get("exit_fees", 0.0), retry_at=p.get("retry_at", 0.0), error=p.get("error", ""), sold_coins=p.get("sold_coins", 0.0), sold_value=p.get("sold_value", 0.0), sold_fees=p.get("sold_fees", 0.0), exact=p.get("exact", True), innovation=p.get("innovation", False)) self.next_uid += 1 self.positions.append(pos) moved.append(f"{p['base']} ({ex}{', реальная' if pos.real else ''})") for t in d.get("trades", []): if bool(t.get("real", False)) != self.is_real: continue self.trades.append(CrossTrade( self.next_uid, t["base"], ex, ex, t["opened"], t["closed"], t["qty"], t["spot_entry"], t["spot_exit"], t["fut_entry"], t["fut_exit"], t["entry_gap"], t["exit_gap"], 0.0, t["spot_pnl"], t["fut_pnl"], t["fees"], t["funding"], t["net"], t["reason"], t.get("amount", 0.0), real=t.get("real", False), exact=t.get("exact", True), kind="in")) self.next_uid += 1 self.trades.sort(key=lambda t: t.closed) if d.get("pending") and self.is_real: self._journal("—", "open", False, f"{ex}: незавершённый вход из старой вкладки ({', '.join(d['pending'])})" f" не перенесён — проверьте баланс монет на {ex}") if done: self.save() if moved: self._journal("—", "open", True, "позиции вкладок «Спот-фьюч» отдельных бирж перенесены в «Арбитраж · " f"{'реальная торговля' if self.is_real else 'симуляция'}» (внутри биржи): " + ", ".join(moved)) def _load_usual(self) -> None: """The usual gaps learnt before a restart, if they are recent (otherwise 15 min of watching again).""" try: d = json.loads(self.usual_file.read_text(encoding="utf-8")) except (OSError, ValueError): return if time.time() - d.get("time", 0) > 600: return self.usual, self.seen_since, self.last_seen = d.get("usual", {}), d.get("since", {}), d.get("seen", {}) def _save_usual(self, now: float) -> None: if now - self.usual_saved < 60: return self.usual_saved = now try: self.usual_file.parent.mkdir(exist_ok=True) tmp = self.usual_file.with_suffix(".tmp") tmp.write_text(json.dumps({"time": now, "usual": self.usual, "since": self.seen_since, "seen": self.last_seen}), encoding="utf-8") tmp.replace(self.usual_file) except OSError: pass def save(self) -> None: self.file.parent.mkdir(exist_ok=True) data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions], "trades": [asdict(t) for t in self.trades[-KEEP_TRADES:]], "next_uid": self.next_uid, "fees": self.fees, "limits": self.limits, "baseline": self.baseline, "migrated": self.migrated, "pending": {**self.recover, **self.pending}} atomic_write_json(self.file, data) def set_settings(self, values: dict) -> str: with self.lock: was = (self.settings.running, self.settings.real) for f in fields(CrossSettings): if f.name not in values: continue try: v = values[f.name] v = (v in (True, "true", "1", 1, "on")) if f.type in ("bool", bool) \ else type(getattr(self.settings, f.name))(float(v)) except (TypeError, ValueError): return f"неверное значение: {f.name}" setattr(self.settings, f.name, v) self.settings.real = self.is_real # which tab it is, not a setting if "fees" in values: problem = self._set_fees(values["fees"]) if problem: return problem if "limits" in values: problem = self._set_limits(values["limits"]) if problem: return problem s = self.settings if s.amount <= 0: return "сумма должна быть больше 0" if s.running and s.real and (not was[0] or not was[1]): self.baseline = {"time": time.time(), "total": None, "by_ex": {}} # «since the start» from here if set(values) - {"running"}: self.real_block.clear() # new settings: coins and exchanges are checked anew self.real_pause_until, self.real_pause_reason = 0.0, "" import basis if s.max_gap_pct > basis.HARD_MAX_GAP_PCT: s.max_gap_pct = basis.HARD_MAX_GAP_PCT self.save() return (f"«Макс. разница» не может быть больше {basis.HARD_MAX_GAP_PCT:g}% (разные инструменты под " f"одним тикером). Установлено {basis.HARD_MAX_GAP_PCT:g}%, остальное сохранено") self.save() return "" def _set_fees(self, given) -> str: """Fee rates typed on the page: {"MEXC": {"spot": "0.05", "fut": "0.02"}, …}.""" if not isinstance(given, dict): return "неверные комиссии" new = {} for ex, legs in given.items(): if ex not in self.fees or not isinstance(legs, dict): continue for leg in FEE_LEGS: if leg not in legs or leg not in self.fees[ex]: continue try: v = float(legs[leg]) except (TypeError, ValueError): return f"неверная комиссия: {ex} {leg}" if not 0 <= v <= MAX_LEARNED_FEE: return f"комиссия {ex} должна быть от 0 до {MAX_LEARNED_FEE:g}%" new[(ex, leg)] = v for (ex, leg), v in new.items(): if abs(self.fees[ex][leg] - v) > 1e-9: self.fees[ex][leg], self.fees[ex][f"{leg}_src"] = v, "вручную" return "" def exchanges(self) -> set[str]: s = self.settings return {name for name, on in (("Bybit", s.use_bybit), ("Binance", s.use_binance), ("MEXC", s.use_mexc), ("HTX", s.use_htx), ("Gate", s.use_gate)) if on} def has_keys(self, exchange: str) -> bool: """The exchange has API keys (the balance reader keeps an entry for exactly those exchanges).""" return exchange.lower() in self.balances # --- open trades per exchange: a trade counts on both of its exchanges (spot on A, short on B) --------------- def limit(self, exchange: str) -> int: return int(self.limits.get(exchange, DEFAULT_LIMIT)) def open_on(self, exchange: str) -> list[str]: """Coins of the open trades of this mode (real ones in real mode, paper ones otherwise) that use the exchange, plus a real entry in progress there.""" real = self.settings.real out = [p.base for p in self.positions if p.real == real and exchange in (p.spot_ex, p.fut_ex)] out += [b for b, info in self.pending.items() if exchange in str(info.get("key", "")).split("|")[1:]] return out def full(self, l: Link) -> str: """Why a new trade on this link must wait (one of its exchanges has its limit of open trades), "" if not.""" for ex in (l.spot_ex, l.fut_ex): held = self.open_on(ex) if len(held) >= self.limit(ex): return f"на {ex} открыто сделок {len(held)} из {self.limit(ex)} ({', '.join(held) or '—'}) — ждёт закрытия" return "" def _set_limits(self, given) -> str: if not isinstance(given, dict): return "неверные лимиты" new = {} for ex, v in given.items(): if ex not in self.limits: continue try: n = int(float(v)) except (TypeError, ValueError): return f"неверный лимит сделок: {ex}" if not 0 <= n <= 100: return f"лимит сделок {ex} должен быть от 0 до 100" new[ex] = n self.limits.update(new) return "" SPOT_NEED, FUT_NEED = 1.01, 1.03 # × the amount: the spot buy (+ fee) / the short's margin (leverage 1) def funds(self, exchange: str) -> dict | None: """Can the exchange take a leg of a real trade of «Сумма» now? {"spot": bool (buy the coin, role A), "fut": bool (short, role B), "free": $, "need": $}; None while its free USDT is not known. With the auto-transfer (or one unified account) both accounts of the exchange count for either leg.""" b = self.balances.get(exchange.lower()) f = (b or {}).get("free") if not isinstance(f, dict): return None s = self.settings spot, fut = float(f.get("spot") or 0), float(f.get("futures") or 0) unified = bool(b.get("unified")) total = spot if unified else spot + fut pool = unified or s.auto_transfer need_spot, need_fut = s.amount * self.SPOT_NEED, s.amount * self.FUT_NEED return {"spot": (total if pool else spot) >= need_spot, "fut": (total if pool else fut) >= need_fut, "free": total, "free_spot": spot, "free_fut": fut, "need": min(need_spot, need_fut), "need_spot": need_spot, "need_fut": need_fut, "pool": pool} def stock(self, exchange: str, base: str) -> float | None: """Free coins of `base` on the exchange's spot account (from the balance reader), None when not known.""" coins = (self.balances.get(exchange.lower()) or {}).get("coins") return float(coins.get(base, 0.0)) if isinstance(coins, dict) else None def _short_of_money(self, l: Link, funds: dict) -> list[str]: """What a real trade on this link lacks: USDT for the spot buy on A, money for the short on B (or both on one exchange), or the coin's stock on B for a spot–spot sale.""" s = self.settings fa, fb = funds.get(l.spot_ex), funds.get(l.fut_ex) out = [] if l.kind == "in": # both legs on one exchange: both needs at once if fa is not None: both = fa["need_spot"] + fa["need_fut"] if (fa["free"] < both) if fa["pool"] else not (fa["spot"] and fa["fut"]): out.append(f"средств на {l.spot_ex} (обе ноги: нужно {both:.2f} $)") return out if fa is not None and not fa["spot"]: out.append(f"средств на споте {l.spot_ex}") if l.ss: have = self.stock(l.fut_ex, l.base) need = s.amount / l.spot_ask if have is not None and have < need: out.append(f"запаса {l.base} на {l.fut_ex} (есть {have:g}, нужно {need:.6g})") elif fb is not None and not fb["fut"]: out.append(f"средств на фьючерсах {l.fut_ex}") return out def low_funds(self, exchange: str) -> str: """Why the exchange is out of the search for now (it cannot take either leg), "" when it can.""" f = self.funds(exchange) if self.settings.real else None if f is None or f["spot"] or f["fut"]: return "" if f["pool"]: return f"мало средств: свободно {f['free']:.2f} $, нужно от {f['need']:.2f} $" return (f"мало средств: спот {f['free_spot']:.2f} $ (нужно {f['need_spot']:.2f}), фьючерсы " f"{f['free_fut']:.2f} $ (нужно {f['need_fut']:.2f})") def _watch_funds(self) -> None: """Journal when an exchange drops out for lack of money and when it is back (money arrived).""" for ex in arb.EXCHANGES: low = self.low_funds(ex) if bool(low) != bool(self.funds_low.get(ex)): self._journal("—", "funds", not low, f"{ex}: {low} — выключена из поиска и сделок до пополнения" if low else f"{ex}: средств достаточно — снова в поиске и сделках") if low: self.funds_low[ex] = low else: self.funds_low.pop(ex, None) # --- data ------------------------------------------------------------------------------------------------ def _fetch(self) -> tuple[list, list]: for refresh in (self.fut.refresh_reference, self.spot.refresh_volume): try: refresh() except Exception: pass jobs = {} status = {} with ThreadPoolExecutor(max_workers=10) as pool: for ex in arb.EXCHANGES: jobs[pool.submit(getattr(self.spot, ex.lower()))] = (ex, "спот") jobs[pool.submit(getattr(self.fut, ex.lower()))] = (ex, "фьюч") spots, futs = [], [] for job, (ex, kind) in jobs.items(): try: (spots if kind == "спот" else futs).extend(job.result()) except Exception as exc: status[f"{ex} {kind}"] = f"нет данных: {str(exc)[:60]}" self.ex_status = status return spots, futs def _loop(self) -> None: while True: start = time.time() try: spots, futs = self._fetch() if time.time() - self.innovation_time > INNOVATION_S: try: # which Bybit perps pay the Innovation Zone rate self.innovation = {f"Bybit|{s}" for s in bybit_innovation_symbols()} self.innovation_time = time.time() except Exception: self.innovation_time = time.time() - INNOVATION_S + 300 # again in 5 min links = build_links(spots, futs, set(arb.EXCHANGES), self.innovation) with self.lock: fresh_now = time.time() for k, seen in self.fast_seen.items(): # the fast watch's prices are newer than this list if k in links and k in self.links and fresh_now - seen < 2.0: links[k] = self.links[k] self.links = links self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000) self.status = "ok" self.learn(self.updated) self.step(self.updated) self._save_usual(self.updated) for e in self.followers: # the real engine: the same prices, its own trades e.take_prices(links, self) except Exception as exc: self.status = f"нет данных: {exc}" for e in self.followers: e.status = self.status time.sleep(max(0.5, POLL_S - (time.time() - start))) def take_prices(self, links: dict, leader: "CrossEngine") -> None: """A follower's cycle: the leader's fresh price list (its own fast prices kept where newer), then its own exits and entries.""" with self.lock: fresh = dict(links) now = time.time() for k, seen in self.fast_seen.items(): if k in fresh and k in self.links and now - seen < 2.0: fresh[k] = self.links[k] self.links = fresh self.innovation = leader.innovation self.ex_status, self.updated, self.cycle_ms = leader.ex_status, leader.updated, leader.cycle_ms self.status = "ok" self.step(self.updated) def learn(self, now: float) -> None: """The usual gap of every pair: an EMA over ~USUAL_WINDOW_S of the mid gap, updated each cycle.""" alpha_base = POLL_S / USUAL_WINDOW_S for key, link in self.links.items(): gap = link.mid_gap if abs(gap) > 50: # garbage (a different token, a dead book) continue prev = self.usual.get(key) last = self.last_seen.get(key) if prev is None or last is None or now - last > 600: self.usual[key], self.seen_since[key] = gap, now # (re)start after a long absence else: alpha = min(1.0, alpha_base * max(1.0, (now - last) / POLL_S)) self.usual[key] = prev + alpha * (gap - prev) self.last_seen[key] = now def history_min(self, key: str, now: float) -> float: return (now - self.seen_since[key]) / 60 if key in self.seen_since else 0.0 # --- trading --------------------------------------------------------------------------------------------- def candidates(self, now: float, keys=None) -> list[dict]: """Every link (or only `keys`) with what it would earn and why it is or is not entered now.""" import basis s = self.settings on = self.exchanges() if s.real: # an exchange without money for either leg: out until topped up on -= {ex for ex in on if self.low_funds(ex)} funds = {ex: self.funds(ex) for ex in on} if s.real else {} kinds = {k for k, flag in (("sf", s.search_sf), ("in", s.search_in), ("ss", s.search_ss)) if flag} hard_max = min(s.max_gap_pct, basis.HARD_MAX_GAP_PCT) rows = [] items = self.links.items() if keys is None else [(k, self.links[k]) for k in keys if k in self.links] for key, l in items: if l.spot_ex not in on or l.fut_ex not in on or l.kind not in kinds: continue if min(l.spot_turnover, l.fut_turnover) < s.min_turnover: continue short = self._short_of_money(l, funds) if s.real else [] usual = self.usual.get(key) hist = self.history_min(key, now) excess = None if usual is None else l.entry_gap - usual net = net_pct(l, usual, s, self.fees) depth_ok = all(v is None or v >= s.amount for v in (l.spot_depth, l.fut_depth)) elsewhere = self.elsewhere(l.base) no_keys = [ex for ex in (l.spot_ex, l.fut_ex) if s.real and not self.has_keys(ex)] # the smallest amount the spot of A and the perp of B both accept (paper too: only real-able trades) m = (minorder.RULES.min_entry_ss(l.spot_ex, l.base, l.spot_ask, l.fut_ex, l.fut_bid, spot_fee(l.spot_ex, self.fees)) if l.ss else minorder.RULES.min_entry(l.spot_ex, l.base, l.spot_ask, l.fut_ex, l.fut_symbol, l.fut_bid, spot_fee(l.spot_ex, self.fees))) small = minorder.too_small(s.amount, m, l.spot_ex, l.fut_ex, "спот" if l.ss else "фьюч") # a wide bid–ask spread: the quotes are thin and the fills land far from them (ZCAT 2.8 %, GSTOCKBSC 1.9 %) spread_a = (l.spot_ask / l.spot_bid - 1) * 100 if l.spot_bid > 0 else 100.0 spread_b = (l.fut_ask / l.fut_bid - 1) * 100 if l.fut_bid > 0 else 100.0 wide = (f"широкий спред: {l.spot_ex} {spread_a:.2f}%, {l.fut_ex} {spread_b:.2f}% (макс. {s.max_spread_pct:g}%)" if s.max_spread_pct > 0 and max(spread_a, spread_b) > s.max_spread_pct else "") # either way: −34 % (SIREN MEXC spot vs Gate perp) is as much «two different coins» as +30 000 % (EWT) fits = (net is not None and hist >= s.history_min and abs(l.entry_gap) <= hard_max and net >= s.min_net_pct and depth_ok and not elsewhere and not no_keys and not short and not small and not wide) why = ("" if fits else f"уже в сделке: {elsewhere}" if elsewhere else f"нет API-ключей {', '.join(no_keys)}" if no_keys else wide if wide else small if small else f"мало {' и '.join(short)} для суммы {s.amount:g} $" if short else "мало истории" if hist < s.history_min else f"разница больше ±{basis.HARD_MAX_GAP_PCT:g}% — разные инструменты под одним тикером" if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT else "разница больше максимальной (по модулю)" if abs(l.entry_gap) > hard_max else "чистая прибыль ниже порога" if net is None or net < s.min_net_pct else "мало объёма") rows.append({"key": key, "link": l, "usual": usual, "excess": excess, "net": net, "history": hist, "fits": fits, "why": why, "min": m}) return rows def step(self, now: float) -> None: s = self.settings for base, info in list(self.recover.items()): # an entry cut off by a stop of the program: whatever was opened becomes a position again if (info.get("key") in self.links or info.get("link")) and base not in self.opening and time.time() >= info.get("retry_at", 0): self.opening.add(base) self.pending[base] = info del self.recover[base] self.jobs.put(("recover", base, info)) if s.real: self._watch_funds() changed = self._check_exits(now) # every link once per cycle: the table and the entries both use this (the page never recomputes 17 000 # links itself); the hot links are refreshed in between by the hot watch rows = self.candidates(now) self.cand, self.cand_time = {r["key"]: r for r in rows}, now real_busy = s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until) if s.running and not real_busy: # real: the next trade only after the previous is confirmed changed = self._entries(now, rows) or changed if changed: self.save() def hot_step(self, keys: list[str], now: float) -> None: """The hot links have fresh prices: their rows again, and an entry if one of them fits now.""" with self.lock: rows = self.candidates(now, keys) for r in rows: self.cand[r["key"]] = r s = self.settings if s.running and not (s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until)): if self._entries(now, rows): self.save() def exit_level(self, pos: CrossPosition) -> tuple[float, float | None]: """(the usual gap the position closes at, the usual gap now). The usual of the entry, unless the market has moved it UP since (a regime shift: the old level may never come back) — then the current one; a usual that went down does not make the exit harder.""" now_usual = self.usual.get(pos.key) return (pos.usual if now_usual is None else max(pos.usual, now_usual)), now_usual def _check_exits(self, now: float) -> bool: """Open positions against the latest prices (the market cycle and the fast watch both call this).""" s = self.settings changed = False for pos in list(self.positions): l = self.links.get(pos.key) if l is None: continue while pos.next_funding and now >= pos.next_funding: pos.funding += pos.qty * (l.fut_bid + l.fut_ask) / 2 * l.funding # the short receives positive step = l.interval_h * 3600 pos.next_funding += step changed = True gap = l.exit_gap # «back to usual» must hold `exit_hold_s` without a break: a one-tick spike of one leg (SHROOM: a burst # of trades on MEXC that was gone 1.4 s later) does not close the position back = False level, now_usual = self.exit_level(pos) if gap <= level + s.exit_over_usual_pct: if not pos.exit_since: pos.exit_since = now back = now - pos.exit_since >= s.exit_hold_s elif not pos.closing: pos.exit_since = 0.0 shifted = (f" (обычная сместилась: при входе {pos.usual:+.2f}%, сейчас {now_usual:+.2f}%)" if level > pos.usual else "") reason = ((f"разница вернулась к обычной и держалась {now - pos.exit_since:.1f} с{shifted}" if s.exit_hold_s > 0 else f"разница вернулась к обычной{shifted}") if back else "стоп: разница расширилась" if s.stop_widen_pct > 0 and gap >= pos.entry_gap + s.stop_widen_pct else "время удержания" if s.max_hold_hours > 0 and now - pos.opened >= s.max_hold_hours * 3600 else "") if pos.real and pos.closing == "fut_done" and now >= pos.retry_at: reason = reason or "продажа спота после выкупа шорта" if pos.qty > 0 and not pos.closing and not pos.ss: # a spot sale on B has no liquidation to_liq = (pos.liq_price / l.fut_ask - 1) * 100 if pos.liq_price > 0 else None if to_liq is not None and s.liq_close_pct > 0 and to_liq < s.liq_close_pct: # the coin has risen: B would liquidate the short and leave the spot on A naked — close now reason = reason or f"до ликвидации шорта {to_liq:.1f}% < {s.liq_close_pct:g}%" if pos.real and not reason and now - pos.liq_checked >= LIQ_CHECK_S: pos.liq_checked = now # cross margin: it moves with B's whole account self.jobs.put(("liq", pos.uid)) if not reason: continue if pos.real: if pos.uid not in self.busy and now >= pos.retry_at: self.busy.add(pos.uid) if not pos.exit_signal: # the prices of the decision (a retry keeps the first) pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap] self.jobs.put(("close", pos.uid, reason)) else: self._close(pos, l, now, reason) changed = True return changed def _entries(self, now: float, rows: list[dict] | None = None) -> bool: import basis s = self.settings changed = False busy = {p.base for p in self.positions} | self.opening best: dict[str, dict] = {} for r in (self.candidates(now) if rows is None else rows): # per coin: the link with the highest net if r["fits"] and (r["link"].base not in best or r["net"] > best[r["link"].base]["net"]) \ and not self.full(r["link"]): # a link whose exchange is full gives way to the next one best[r["link"].base] = r for r in sorted(best.values(), key=lambda r: -r["net"]): l = r["link"] if self.full(l): # filled by an entry made a moment ago in this loop continue if l.base in busy or now - self.last_close.get(l.base, 0.0) < s.cooldown_s: continue if self.elsewhere(l.base): continue # the coin is already in a trade on a spot–futures tab if s.real: if self.real_block.get(l.base, ("", 0.0))[1] > now: continue # known: cannot be traded for real now (lot, instrument…) self.opening.add(l.base) self.jobs.put(("open", l, r["usual"], s.amount)) break # one real entry at a time qty = s.amount / l.spot_ask fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \ + qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100 step = l.interval_h * 3600 # paper: B holds the amount + 3 % as futures money (what the real entry makes sure of) liq = 0.0 if l.ss else l.fut_bid * (1 + liq_distance(self.FUT_NEED, 1.0) / 100) self.positions.append(CrossPosition( self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, qty, l.spot_ask, l.fut_bid, l.entry_gap, r["usual"], fee_in, 0.0 if l.ss else (now // step + 1) * step, innovation=l.innovation, liq_price=liq, liq_calc=liq, liq_src="" if l.ss else "расчёт", ss=l.ss)) self.next_uid += 1 busy.add(l.base) changed = True return changed # --- fast watch of open positions ------------------------------------------------------------------------ FAST_S = 0.25 def _fast_loop(self) -> None: """While positions are open: spot of A and perp of B of each, several times a second, and the exit rules.""" import dataclasses import fastquote pool = ThreadPoolExecutor(max_workers=8) while True: start = time.time() with self.lock: watch = {k: self.links[k] for k in (p.key for p in self.positions) if k in self.links} if not watch: time.sleep(0.5) continue jobs = {k: (pool.submit(fastquote.spot_top, l.spot_ex, l.spot_symbol), pool.submit(fastquote.spot_top if l.ss else fastquote.fut_top, l.fut_ex, l.fut_symbol)) for k, l in watch.items()} fresh = {} for k, (sj, fj) in jobs.items(): try: sb, sa, _, sau = sj.result() fb, fa, fbu, _ = fj.result() except Exception: continue l = watch[k] if min(sb, sa, fb, fa) <= 0: continue fresh[k] = dataclasses.replace(l, spot_bid=sb, spot_ask=sa, fut_bid=fb / l.fut_mult, fut_ask=fa / l.fut_mult) if fresh: now = time.time() with self.lock: self.links.update(fresh) for k in fresh: self.fast_seen[k] = now self.fast_ms = int((now - start) * 1000) if self._check_exits(now): self.save() time.sleep(max(0.05, self.FAST_S - (time.time() - start))) # --- hot watch: links already in profit on paper, priced every HOT_S so an entry point is not missed --------- HOT_S = 0.5 HOT_MAX = 8 # links at most (2 price requests each, legs shared are asked once): the exchanges' limits def pick_hot(self, engines: list) -> list[str]: """The links with the highest net profit > 0 of the running engines (not those already in a position).""" best: dict[str, float] = {} now = time.time() for e in engines: if not e.settings.running: continue held = {p.key for p in e.positions} for k, r in list(e.cand.items()): if e.settings.real and e.real_block.get(r["link"].base, ("", 0.0))[1] > now: continue # waiting after a failed book check: no slot for it if r["net"] is not None and r["net"] > 0 and k not in held: best[k] = max(best.get(k, -1e9), r["net"]) return sorted(best, key=lambda k: -best[k])[:self.HOT_MAX] def _hot_loop(self) -> None: import dataclasses import fastquote pool = ThreadPoolExecutor(max_workers=8) while True: start = time.time() engines = [self] + self.followers keys = [k for k in self.pick_hot(engines) if k in self.links] self.hot = keys if not keys: time.sleep(1.0) continue legs = {} # (spot?, exchange, symbol) → job: each leg asked once for k in keys: l = self.links[k] legs.setdefault((True, l.spot_ex, l.spot_symbol), None) legs.setdefault((l.ss, l.fut_ex, l.fut_symbol), None) jobs = {leg: pool.submit(fastquote.spot_top if leg[0] else fastquote.fut_top, leg[1], leg[2]) for leg in legs} quotes = {} for leg, job in jobs.items(): try: bid, ask, _, _ = job.result() if min(bid, ask) > 0: quotes[leg] = (bid, ask) except Exception: pass now = time.time() done = [] for e in engines: with e.lock: for k in keys: l = e.links.get(k) a, b = quotes.get((True, l.spot_ex, l.spot_symbol)) if l else None, \ quotes.get((l.ss, l.fut_ex, l.fut_symbol)) if l else None if not a or not b: continue e.links[k] = dataclasses.replace(l, spot_bid=a[0], spot_ask=a[1], fut_bid=b[0] / l.fut_mult, fut_ask=b[1] / l.fut_mult) e.fast_seen[k] = now if e is self: done.append(k) e.hot_step(done or keys, now) time.sleep(max(0.05, self.HOT_S - (time.time() - start))) def _close(self, pos: CrossPosition, l: Link, now: float, reason: str) -> None: spot_pnl, fut_pnl, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees) self.trades.append(CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty, pos.spot_entry, l.spot_bid, pos.fut_entry, l.fut_ask, pos.entry_gap, l.exit_gap, pos.usual, spot_pnl, fut_pnl, fees, pos.funding, net, reason, pos.qty * pos.spot_entry, kind=pos.kind)) self.positions.remove(pos) self.last_close[pos.base] = now def close(self, uid: int | None) -> str: with self.lock: n = real = 0 for pos in list(self.positions): if uid is not None and pos.uid != uid: continue if pos.real: if pos.uid not in self.busy: self.busy.add(pos.uid) pos.retry_at = 0.0 self.jobs.put(("close", pos.uid, "вручную")) real += 1 continue l = self.links.get(pos.key) if l is None: continue self._close(pos, l, time.time(), "вручную") n += 1 self.save() return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "") def reset(self) -> str: with self.lock: if any(p.real for p in self.positions): return "есть открытые реальные позиции — сначала закройте их" self.positions, self.trades, self.last_close = [], [], {} self.baseline = {"time": time.time(), "total": None, "by_ex": {}} if self.settings.real else {} self.save() return "статистика сброшена" # --- real orders (worker thread; never under the engine lock while waiting for an exchange) ------------------ def _journal(self, coin: str, action: str, ok: bool, text: str, **extra) -> None: import real_mirror real_mirror.journal("basis", "cross", coin, action, ok, text, **extra) def _worker(self) -> None: while True: self.do_job(self.jobs.get()) def do_job(self, job: tuple) -> None: kind, *args = job if True: try: if kind == "open": self._real_open(*args) elif kind == "close": self._real_close(*args) elif kind == "recover": self._recover(*args) elif kind == "liq": self._refresh_liq(*args) except Exception as exc: # the worker must survive anything base = args[0].base if kind == "open" else args[0] if kind == "recover" else "?" self._journal(str(base), kind, False, f"сбой: {exc}") finally: with self.lock: if kind == "close": self.busy.discard(args[0]) elif kind in ("open", "recover"): base = args[0].base if kind == "open" else args[0] self.opening.discard(base) info = self.pending.pop(base, None) if info is not None: # Only preparation is certainly unsent. Every later stage survives errors and restart. if info.get("phase") != "prepared": info["retry_at"] = time.time() + 5 self.recover[base] = info try: self.save() except (OSError, ValueError) as exc: self.real_pause_until = time.time() + 60 self.real_pause_reason = f"не удалось сохранить восстановление: {exc}" def _pending_update(self, base: str, **values) -> None: with self.lock: before = dict(self.pending[base]) self.pending[base].update(values) try: self.save() except Exception: self.pending[base] = before raise def _pending_done(self, base: str) -> None: with self.lock: pending, recovering = self.pending.pop(base, None), self.recover.pop(base, None) self.last_close[base] = time.time() try: self.save() except Exception: if pending is not None: self.pending[base] = pending if recovering is not None: self.recover[base] = recovering raise def _pending_problem(self, base: str, text: str) -> None: with self.lock: info = self.pending[base] changed = info.get("error") != text info["error"] = text self.save() if changed: self._journal(base, "recover", False, text + "; новые реальные входы заблокированы") def _cancel_entry(self, l: Link, cb, oid: str) -> dict | None: """A cancel acknowledgement is not terminal confirmation; never hedge a still-working entry.""" import live try: state = cb.fut_order_status(l.fut_symbol, oid) if state["final"]: return state except live.LiveError: pass try: cb.fut_cancel(l.fut_symbol, oid) except live.LiveError: pass try: state = cb.fut_order_status(l.fut_symbol, oid) if state["final"]: return state except live.LiveError: pass self._pending_problem(l.base, f"не подтверждена отмена входа {oid} на {l.fut_ex}; повторяю сверку") return None def _rollback_entry(self, l: Link, cb) -> None: """Retain the durable entry until the exchange confirms the short has actually gone.""" import live try: held = cb.fut_position(l.fut_symbol) if held < -1e-12: try: cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True) except live.LiveError as exc: if not exc.sent: raise held = cb.fut_position(l.fut_symbol) if abs(held) > 1e-12: raise live.LiveError(f"на фьючерсе осталось {held:+g} {l.base}") except live.LiveError as exc: self._pending_problem(l.base, f"откат входа не завершён: {exc}; повторяю закрытие") return self._pending_done(l.base) self._journal(l.base, "recover", True, "откат входа завершён: биржа подтвердила отсутствие позиции") @staticmethod def _api_closed(error: str) -> bool: """The exchange refuses the symbol to API orders for good (not a passing problem): MEXC 10007 «symbol not support api», «api trading is not enabled»…""" e = error.lower() return "not support api" in e or "10007" in e or "api trading" in e and "not" in e def _not_tradable(self, base: str, why: str, seconds: float) -> None: with self.lock: known = self.real_block.get(base, ("", 0.0))[0] == why self.real_block[base] = (why, time.time() + seconds) self.opening.discard(base) if not known: self._journal(base, "open", False, f"не открываю: {why} — ордеров не было") BALANCE_PAUSE_S = 900.0 def _pause_if_balance(self, error: str, exchange: str) -> None: if any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно", "не хватает")): with self.lock: self.real_pause_until = time.time() + self.BALANCE_PAUSE_S self.real_pause_reason = (f"не хватает баланса на {exchange} — пополните счёт или уменьшите " f"«Сумму сделки»") self._journal("—", "open", False, f"{self.real_pause_reason}; реальные входы на паузе 15 мин") def _real_open(self, l: Link, usual: float, amount: float) -> None: """Short on B first (limit at the signal's bid, or at market), then the same coins bought on spot on A. Nothing is bought on A when the short did not fill; the short is bought back when A's buy fails.""" import basis import live l = self._still_good(l, usual, amount) if l is None: return if l.ss: self._real_open_ss(l, usual, amount) return s = self.settings a_fee = spot_fee(l.spot_ex, self.fees) try: ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) min_coins = cb.fut_min_coins(l.fut_symbol) coins = cb.fut_round(l.fut_symbol, amount / l.spot_ask * (1 - a_fee / 100)) except (live.LiveError, AttributeError) as exc: self._not_tradable(l.base, f"нет правил контракта {l.fut_ex}: {exc}", 300) return # the same coins on both legs must be worth about the same: otherwise two different instruments if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT or coins * l.fut_bid > amount * basis.MAX_LEG_RATIO: self._not_tradable(l.base, f"шорт {coins:g} монет на {l.fut_ex} стоил бы {coins * l.fut_bid:.2f} $ при " f"сумме {amount:g} $ — разные инструменты под одним тикером", 86400) return if coins <= 0 or coins < min_coins: need = min_coins * l.spot_ask / (1 - a_fee / 100) * 1.02 self._not_tradable(l.base, f"сумма {amount:g} $ меньше минимального лота фьючерса {l.fut_ex} " f"({min_coins:g} монет ≈ {need:.2f} $)", 1800) return with self.lock: # last check right before money is spent held = [x.base for x in self.positions if x.real] if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l): return self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, "amount": amount, "link": asdict(l), "phase": "prepared"} self.save() notional = coins * l.fut_bid fut_need = max(notional * self.FUT_NEED, equity_for(s.min_liq_pct, notional)) if s.auto_transfer: # one exchange for both legs: one transfer that leaves enough on spot AND on futures plan = (((ca, l.spot_ex, amount * 1.01, fut_need),) if l.spot_ex == l.fut_ex else ((ca, l.spot_ex, amount * 1.01, 0.0), (cb, l.fut_ex, 0.0, fut_need))) for c, ex, spot_need, fut_need in plan: try: moved = live.ensure_usdt(c, spot_need, fut_need) if moved: self._journal(l.base, "transfer", True, f"{ex}: {moved}") except (live.LiveError, AttributeError) as exc: if "в сумме" in str(exc): self._journal(l.base, "open", False, f"не открываю: {ex}: {exc} — ордеров не было") self._pause_if_balance("не хватает", ex) return self._journal(l.base, "transfer", False, f"{ex}: перевод не удался: {exc} — пробую без него") # the liquidation of the short, from B's futures money right before it: far enough above the entry? try: fut_money = float(cb.usdt_free()["futures"]) except (live.LiveError, AttributeError, KeyError, TypeError, ValueError) as exc: self._not_tradable(l.base, f"не прочитан фьючерсный баланс {l.fut_ex} для расчёта ликвидации: {exc}", 120) return to_liq = liq_distance(fut_money, notional) if to_liq < s.min_liq_pct: self._not_tradable(l.base, f"ликвидация шорта на {l.fut_ex} была бы всего на {to_liq:.0f}% выше входа " f"(на фьючерсах {fut_money:.2f} $ при шорте {notional:.2f} $, нужно " f"{equity_for(s.min_liq_pct, notional):.2f} $ для запаса " f"{s.min_liq_pct:g}%)", 300) return # 1) the short on B shorted, fut_price, fut_fee_usd, fut_exact = 0.0, 0.0, 0.0, True if s.entry_limit or s.entry_ioc: # a limit order at the confirmed price (the average sale price of the amount in B's book): it fills # only at that price or better. IOC: looked at once, the rest cancelled at once — a gap that has gone # leaves nothing filled and nothing is bought on A; otherwise it waits «Лимитный вход: ждать, с» hold = 0.0 if s.entry_ioc else max(0.0, s.limit_hold_s) name = "IOC-шорт" if s.entry_ioc else "лимитный шорт" self._pending_update(l.base, phase="limit_submitted") try: oid = cb.fut_limit(l.fut_symbol, "sell", coins, l.fut_bid) except (live.LiveError, AttributeError) as exc: if getattr(exc, "sent", False): self._pending_update(l.base, order_id=getattr(exc, "order_id", "")) self._pending_problem(l.base, f"результат лимитного входа неизвестен: {exc}") return self._pending_done(l.base) self._journal(l.base, "open", False, f"{name} на {l.fut_ex} не выставлен: {exc}") with self.lock: self.last_close[l.base] = time.time() self._pause_if_balance(str(exc), l.fut_ex) return self._pending_update(l.base, order_id=oid) st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False} end = time.time() + hold while True: # one look a second: the exchange's request limit try: st = cb.fut_order_status(l.fut_symbol, oid) except live.LiveError: pass if st["final"] or st["coins"] >= coins * 0.999 or time.time() >= end: break time.sleep(1.0) if not st["final"]: st = self._cancel_entry(l, cb, oid) if st is None: return shorted, fut_price, fut_fee_usd = st["coins"], st["price"] or l.fut_bid, st["fee"] if shorted <= 0: self._pending_done(l.base) self._journal(l.base, "open", False, f"{name} на {l.fut_ex} по {l.fut_bid:.10g} не исполнился" f"{'' if s.entry_ioc else f' за {hold:g} с'} — снят, на {l.spot_ex} ничего не покупалось") with self.lock: self.last_close[l.base] = time.time() return else: self._pending_update(l.base, phase="market_submitted") try: fut = cb.fut_order(l.fut_symbol, "sell", coins, reduce_only=False) shorted, fut_price, fut_fee_usd, fut_exact = fut.coins, fut.price, fut.fee_usd, fut.exact except live.LiveError as exc: held = 0.0 if getattr(exc, "sent", False): try: held = max(0.0, -cb.fut_position(l.fut_symbol)) except live.LiveError: held = coins # unknown: assume open — the close is reduce-only if held <= 0: if getattr(exc, "sent", False): self._pending_update(l.base, order_id=exc.order_id) self._pending_problem(l.base, f"результат рыночного входа неизвестен: {exc}") return self._pending_done(l.base) self._journal(l.base, "open", False, f"шорт на {l.fut_ex} не открыт: {exc}") with self.lock: self.last_close[l.base] = time.time() self._pause_if_balance(str(exc), l.fut_ex) return shorted, fut_price = held, l.fut_bid fut_fee_usd, fut_exact = held * l.fut_bid * fut_fee(l.fut_ex, self.fees, l.innovation) / 100, False self._pending_update(l.base, phase="hedge_submitted", shorted=shorted) # 2) the hedge: the same coins on spot on A (the buy fee is taken in coins: a little more USDT) try: buy = ca.spot_buy(l.base, shorted * l.spot_ask * (1 + a_fee / 100) * 1.003) except live.LiveError as exc: bought = 0.0 if getattr(exc, "sent", False): try: bought = min(ca.spot_free(l.base), shorted * 1.02) except live.LiveError: bought = 0.0 if bought <= 0: if getattr(exc, "sent", False): self._pending_problem(l.base, f"результат покупки спота неизвестен: {exc}; требуется сверка") return self._pending_update(l.base, phase="rollback") self._rollback_entry(l, cb) if self._api_closed(str(exc)): self._not_tradable(l.base, f"биржа {l.spot_ex} не даёт торговать {l.base} через API: {exc}", 86400) self._pause_if_balance(str(exc), l.spot_ex) return buy = live.Fill(bought, l.spot_ask, bought * l.spot_ask * a_fee / 100, exc.order_id, exact=False) self._pending_update(l.base, phase="hedge_confirmed", buy=asdict(buy), shorted=shorted, fut_price=fut_price, fut_fee=fut_fee_usd) try: free = ca.spot_free(l.base) except live.LiveError: free = 0.0 held = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100) with self.lock: step = l.interval_h * 3600 now = time.time() pos = CrossPosition(self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, shorted, buy.price, fut_price, (fut_price / buy.price - 1) * 100, usual, buy.fee_usd + fut_fee_usd, (now // step + 1) * step, real=True, spot_qty=held, exact=buy.exact and fut_exact, innovation=l.innovation, liq_price=fut_price * (1 + to_liq / 100), liq_calc=fut_price * (1 + to_liq / 100), liq_src="расчёт", liq_checked=now, entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact], [l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]]) self.next_uid += 1 self.positions.append(pos) self.pending.pop(l.base, None) self.save() self._journal(l.base, "open", True, f"шорт {shorted:g} на {l.fut_ex} по {fut_price:.10g}, спот {held:g} на " f"{l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% (обычная {usual:+.3f}%), " f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount) self._refresh_liq(pos.uid, first=True) CONFIRM_CHECKS = 2 BOOK_BLOCK_S = 120.0 # a wide spread / thin book at the check: the coin is not tried again for this long SIGNAL_BLOCK_S = 30.0 # the gap was gone at the check def _still_good(self, l: Link, usual: float, amount: float) -> Link | None: """The signal came from the market cycle's list (tickers, seconds old): before real orders it is confirmed on the ORDER BOOKS twice, `confirm_ms` apart — each time the whole amount priced through the book (the average buy price on A, the average sale price on B), both spreads within «Макс. спред», and the net profit above the threshold. A gap that is only a lagging ticker on a fast move does not survive this.""" import dataclasses if self.quote_now is None: return l s = self.settings fresh = l for check in range(1, self.CONFIRM_CHECKS + 1): if check > 1: time.sleep(max(0.0, s.confirm_ms) / 1000) try: sb, sa, fb, fa, spread_a, spread_b = self.quote_now(l, amount) except ThinBook as exc: why = f"{exc}" except Exception as exc: why = f"нет стакана: {str(exc)[:80]}" else: why = "" if min(sb, sa, fb, fa) <= 0: why = "пустой стакан" elif s.max_spread_pct > 0 and max(spread_a, spread_b) > s.max_spread_pct: why = (f"широкий спред: {l.spot_ex} {spread_a:.2f}%, {l.fut_ex} {spread_b:.2f}% " f"(макс. {s.max_spread_pct:g}%)") else: fresh = dataclasses.replace(l, spot_bid=sb, spot_ask=sa, fut_bid=fb, fut_ask=fa) net = net_pct(fresh, usual, s, self.fees) if net is None or net < s.min_net_pct: why = (f"по стакану разница {fresh.entry_gap:+.3f}% (в сигнале {l.entry_gap:+.3f}%), чистая " f"прибыль {net if net is not None else 0:+.3f}% ниже порога {s.min_net_pct:g}%") if why: # the coin waits (the table shows why as «реально нельзя: …»): a wide or thin book does not change # in a second — without this the next cycle would ask the books again and again self._not_tradable(l.base, f"по стакану (проверка {check} из {self.CONFIRM_CHECKS}): {why}", self.BOOK_BLOCK_S if "стакан" in why or "спред" in why else self.SIGNAL_BLOCK_S) return None with self.lock: self.links[l.key] = fresh self.fast_seen[l.key] = time.time() return fresh def _real_open_ss(self, l: Link, usual: float, amount: float) -> None: """Spot–spot: sell coins from the stock on B's spot first (they are there: nothing can fail half-way on a missing coin), then buy the same coins on A's spot. A failed buy on A buys the stock back on B at once.""" import basis import live s = self.settings a_fee, b_fee_pct = spot_fee(l.spot_ex, self.fees), spot_fee(l.fut_ex, self.fees) coins = amount / l.spot_ask * (1 - a_fee / 100) if abs(l.entry_gap) > basis.HARD_MAX_GAP_PCT: self._not_tradable(l.base, f"разница {l.entry_gap:.1f}% — разные монеты под одним тикером на " f"{l.spot_ex} и {l.fut_ex}", 86400) return try: ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) have = cb.spot_free(l.base) except (live.LiveError, AttributeError) as exc: self._not_tradable(l.base, f"не прочитан запас {l.base} на {l.fut_ex}: {exc}", 120) return if have < coins: self._not_tradable(l.base, f"на споте {l.fut_ex} {have:g} {l.base}, а для продажи нужно {coins:.6g} — " f"положите монету на {l.fut_ex}", 300) return with self.lock: held = [x.base for x in self.positions if x.real] if l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l): return self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual, "amount": amount, "link": asdict(l), "phase": "prepared"} self.save() if s.auto_transfer: try: moved = live.ensure_usdt(ca, amount * 1.01, 0.0) if moved: self._journal(l.base, "transfer", True, f"{l.spot_ex}: {moved}") except (live.LiveError, AttributeError) as exc: if "в сумме" in str(exc): self._journal(l.base, "open", False, f"не открываю: {l.spot_ex}: {exc} — ордеров не было") self._pause_if_balance("не хватает", l.spot_ex) return self._journal(l.base, "transfer", False, f"{l.spot_ex}: перевод не удался: {exc} — пробую без него") # 1) sell the stock on B self._pending_update(l.base, phase="spot_submitted", stock_before=have) try: sold = cb.spot_sell(l.base, coins) except live.LiveError as exc: if not getattr(exc, "sent", False): self._pending_done(l.base) self._journal(l.base, "open", False, f"продажа {l.base} на споте {l.fut_ex} не прошла: {exc}") with self.lock: self.last_close[l.base] = time.time() return sold = live.Fill(coins, l.fut_bid, coins * l.fut_bid * b_fee_pct / 100, exc.order_id, exact=False) # 2) buy the same coins on A try: buy = ca.spot_buy(l.base, sold.coins * l.spot_ask * (1 + a_fee / 100) * 1.003) except live.LiveError as exc: if getattr(exc, "sent", False): buy = live.Fill(sold.coins, l.spot_ask, sold.coins * l.spot_ask * a_fee / 100, exc.order_id, exact=False) else: try: cb.spot_buy(l.base, sold.coins * l.fut_ask * (1 + b_fee_pct / 100) * 1.003) if cb.spot_free(l.base) >= have - 1e-9: self._pending_done(l.base) text = (f"{l.base} продан на {l.fut_ex}, но на {l.spot_ex} не куплен ({exc}); запас на " f"{l.fut_ex} выкуплен обратно") except live.LiveError as exc2: text = (f"{l.base} продан на {l.fut_ex}, на {l.spot_ex} не куплен ({exc}); ЗАПАС НЕ ВЫКУПЛЕН " f"({exc2}) — купите {sold.coins:g} {l.base} на {l.fut_ex} вручную") self._journal(l.base, "open", False, text) with self.lock: self.last_close[l.base] = time.time() self._pause_if_balance(str(exc), l.spot_ex) return try: free = ca.spot_free(l.base) except live.LiveError: free = 0.0 got = min(buy.coins, free) if free > 0 else buy.coins * (1 - a_fee / 100) with self.lock: now = time.time() pos = CrossPosition(self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, sold.coins, buy.price, sold.price, (sold.price / buy.price - 1) * 100, usual, buy.fee_usd + sold.fee_usd, 0.0, real=True, spot_qty=got, ss=True, exact=buy.exact and sold.exact, entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap], fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact], [l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]]) self.next_uid += 1 self.positions.append(pos) self.pending.pop(l.base, None) self.save() self._journal(l.base, "open", True, f"спот-спот: продано {sold.coins:g} на {l.fut_ex} по {sold.price:.10g}, " f"куплено {got:g} на {l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% " f"(обычная {usual:+.3f}%)", amount=amount) def _refresh_liq(self, uid: int, first: bool = False) -> None: """The exchange's own liquidation price of the short replaces the estimate (cross margin: it moves with everything on B's futures account). The first look is compared with the program's estimate.""" import live with self.lock: pos = next((x for x in self.positions if x.uid == uid), None) if pos is None or pos.qty <= 0 or pos.closing or pos.ss: return try: liq = self.client_for(pos.fut_ex).fut_liq_price(pos.fut_symbol) except (live.LiveError, AttributeError): return with self.lock: pos.liq_checked = time.time() if not liq or liq <= 0: return pos.liq_price, pos.liq_src = liq, "биржа" self.save() if first and pos.liq_calc: diff = (liq / pos.liq_calc - 1) * 100 self._journal(pos.base, "liq", abs(diff) < 10, f"ликвидация шорта на {pos.fut_ex}: биржа {liq:.10g} " f"(+{(liq / pos.fut_entry - 1) * 100:.0f}% от входа), расчёт {pos.liq_calc:.10g} — " f"расхождение {diff:+.1f}%") def _real_close(self, uid: int, reason: str) -> None: """Buy the short back on B (reduce-only), make sure B shows no short left, then sell the coins on A.""" import live with self.lock: pos = next((x for x in self.positions if x.uid == uid), None) if pos is None or not pos.real: return stage = f"выкуп шорта на {pos.fut_ex}" try: ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex) if pos.ss and pos.closing != "fut_done": # spot–spot: buy the coins sold on B back (the stock there is restored), a little over for the fee stage = f"выкуп монет на споте {pos.fut_ex}" l = self.links.get(pos.key) ask_b = l.fut_ask if l else pos.fut_entry usdt = pos.qty * ask_b * (1 + spot_fee(pos.fut_ex, self.fees) / 100) * 1.003 try: back = cb.spot_buy(pos.base, usdt) price, fee, exact = back.price, back.fee_usd, back.exact except live.LiveError as exc: if not getattr(exc, "sent", False): raise price, fee, exact = ask_b, usdt * spot_fee(pos.fut_ex, self.fees) / 100, False with self.lock: pos.fut_exit, pos.exit_fees, pos.closing = price, fee, "fut_done" pos.exact = pos.exact and exact pos.fills.append([pos.fut_ex, "spot", fee, usdt, exact]) self.save() if pos.closing != "fut_done": fut_coins, fut_price, fee, exact = 0.0, 0.0, 0.0, True if pos.qty > 0: try: fut = cb.fut_order(pos.fut_symbol, "buy", pos.qty, reduce_only=True) fut_coins, fut_price, fee, exact = fut.coins, fut.price, fut.fee_usd, fut.exact except live.LiveError as exc: if not getattr(exc, "sent", False): raise l = self.links.get(pos.key) fut_coins, fut_price = pos.qty, (l.fut_ask if l else pos.fut_entry) fee, exact = pos.qty * fut_price * fut_fee(pos.fut_ex, self.fees, pos.innovation) / 100, False with self.lock: pos.fut_exit = fut_price if fut_coins else pos.fut_entry pos.exit_fees, pos.closing = fee, "fut_done" pos.exact = pos.exact and exact if fut_coins: pos.fills.append([pos.fut_ex, "fut_innovation" if pos.innovation else "fut", fee, fut_coins * fut_price, exact]) self.save() stage = f"проверка фьючерса {pos.fut_ex}" held = cb.fut_position(pos.fut_symbol) if pos.qty > 0 and not pos.ss else 0.0 if held < -1e-12: cb.fut_order(pos.fut_symbol, "buy", -held, reduce_only=True) raise live.LiveError(f"на фьючерсе оставалось {held:+g} — докуплено, проверяю ещё раз") stage = f"продажа спота на {pos.spot_ex}" l = self.links.get(pos.key) price_now = l.spot_bid if l else pos.spot_entry left = pos.spot_qty - pos.sold_coins if left * price_now > 1.0: # more than dust left to sell free = ca.spot_free(pos.base) if free * price_now > 1.0: sell = ca.spot_sell(pos.base, min(free, left)) with self.lock: pos.sold_coins += sell.coins pos.sold_value += sell.coins * sell.price pos.sold_fees += sell.fee_usd pos.exact = pos.exact and sell.exact pos.fills.append([pos.spot_ex, "spot", sell.fee_usd, sell.coins * sell.price, sell.exact]) self.save() left = pos.spot_qty - pos.sold_coins if left * price_now > 1.0 and ca.spot_free(pos.base) * price_now > 1.0: raise live.LiveError(f"на споте ещё {left:g} {pos.base} — продам при следующей попытке") if pos.sold_coins <= 0 and pos.spot_qty * price_now > 1.0: raise live.LiveError("спот не продан") except live.LiveError as exc: with self.lock: pos.retry_at, pos.error = time.time() + 15, f"{stage}: {exc}" self.save() self._journal(pos.base, "close", False, f"{stage}: {exc} — следующая сделка не откроется, пока эта не " f"закрыта; повтор через 15 с") return with self.lock: now = time.time() sell_price = pos.sold_value / pos.sold_coins if pos.sold_coins else pos.spot_entry spot_pnl = pos.sold_value - pos.sold_coins * pos.spot_entry fut_pnl = pos.qty * (pos.fut_entry - pos.fut_exit) fees = pos.fees + pos.exit_fees + pos.sold_fees net = spot_pnl + fut_pnl - fees + pos.funding exit_gap = (pos.fut_exit / sell_price - 1) * 100 if pos.qty > 0 and sell_price else 0.0 t = CrossTrade(pos.uid, pos.base, pos.spot_ex, pos.fut_ex, pos.opened, now, pos.qty, pos.spot_entry, sell_price, pos.fut_entry, pos.fut_exit, pos.entry_gap, exit_gap, pos.usual, spot_pnl, fut_pnl, fees, pos.funding, net, f"{reason} (реально{'' if pos.exact else ', часть цифр оценочная'})", pos.spot_qty * pos.spot_entry, real=True, exact=pos.exact, kind=pos.kind, entry_signal=list(pos.entry_signal), exit_signal=list(pos.exit_signal)) if pos in self.positions: self.positions.remove(pos) self.trades.append(t) self.last_close[pos.base] = now learned = self._learn_fees(pos, now) if self.settings.fees_auto else [] self.save() first = (f"монеты на споте {pos.fut_ex} выкуплены по {pos.fut_exit:.10g}" if pos.ss else f"шорт на {pos.fut_ex} выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет)") self._journal(pos.base, "close", True, f"{first}, спот на {pos.spot_ex} продан по {sell_price:.10g}, итог " f"{net:+.4f} $, комиссии {fees:.4f} $ ({reason}){self._slippage_text(t)}", net=net) @staticmethod def _slippage_text(t: CrossTrade) -> str: """The prices of the decisions against the fills: how much each leg lost or won on the way to the exchange.""" def leg(name, want, got, sell): if not want or not got: return "" d = (got / want - 1) * 100 * (1 if sell else -1) # + = better than decided, − = worse return f"{name} {want:.8g} → {got:.8g} ({d:+.2f}%)" parts = [] if t.entry_signal: _, a, b, gap = t.entry_signal parts.append(f"вход: решение при разнице {gap:+.3f}%, факт {t.entry_gap:+.3f}% — " f"{leg('покупка A', a, t.spot_entry, False)}, {leg('продажа B', b, t.fut_entry, True)}") if t.exit_signal: _, a, b, gap = t.exit_signal parts.append(f"выход: решение при разнице {gap:+.3f}%, факт {t.exit_gap:+.3f}% — " f"{leg('продажа A', a, t.spot_exit, True)}, {leg('выкуп B', b, t.fut_exit, False)}") return ("; " + "; ".join(parts)) if parts else "" if learned: self._journal(pos.base, "fee", True, "комиссии по этой сделке: " + "; ".join(learned)) def _learn_fees(self, pos: CrossPosition, now: float) -> list[str]: """The rates the exchanges really charged in this trade (fee $ / value $ of its orders, the exchange's own figures only) become the rates of the table. A zero fee (paid in another token) is not taken: the table would then promise more than is earned.""" sums: dict[tuple[str, str], list[float]] = {} for ex, leg, fee, value, exact in pos.fills: if exact and value > 0 and fee > 0: acc = sums.setdefault((ex, leg), [0.0, 0.0]) acc[0] += fee acc[1] += value out = [] stamp = time.strftime("%d.%m %H:%M", time.localtime(now)) for (ex, leg), (fee, value) in sums.items(): rate = fee / value * 100 if ex not in self.fees or leg not in self.fees[ex] or not 0 < rate <= MAX_LEARNED_FEE: continue old = self.fees[ex][leg] self.fees[ex][leg] = round(rate, 5) self.fees[ex][f"{leg}_src"] = f"по сделке {pos.base} {stamp}" name = {"spot": "спот", "fut": "фьюч", "fut_innovation": "фьюч зоны инноваций"}[leg] out.append(f"{ex} {name} {old:g}% → {rate:.4f}%") return out def _recover(self, base: str, info: dict) -> None: """After a restart in the middle of an entry: the short on B and the coins on A that were opened become a real position (estimated prices), which the usual close then takes care of.""" import live with self.lock: l = self.links.get(info.get("key", "")) if l is None and info.get("link"): l = Link(**info["link"]) already_owned = any(p.real and p.base == base for p in self.positions) if already_owned or info.get("phase") == "prepared": self._pending_done(base) return if l is None: self._pending_problem(base, "нет сохранённых параметров незавершённой сделки") return phase = info.get("phase") if not l.ss and phase in ("limit_submitted", "market_submitted", "rollback"): cb = self.client_for(l.fut_ex) if phase != "rollback": oid = info.get("order_id") if not oid: self._pending_problem(base, "отправленный вход без ID: требуется ручная сверка ордеров биржи") # Retain the intent even when flat; a delayed fill must not permit another entry. held = cb.fut_position(l.fut_symbol) if held < -1e-12: cb.fut_order(l.fut_symbol, "buy", -held, reduce_only=True) return if self._cancel_entry(l, cb, oid) is None: return self._pending_update(base, phase="rollback") self._rollback_entry(l, cb) return if phase == "hedge_submitted": # Without an exchange order id, an unchanged spot balance does not prove rejection. self._pending_problem(base, "незавершённая покупка спота: требуется ручная сверка обеих ног") return if l.ss: # a spot sale cannot be told apart from the user's own trades: say so, no guess self._pending_problem(base, f"незавершённый вход спот-спот {l.spot_ex} → " f"{l.fut_ex} — проверьте {base} на обеих биржах вручную") return try: ca, cb = self.client_for(l.spot_ex), self.client_for(l.fut_ex) short = max(0.0, -cb.fut_position(l.fut_symbol)) coins = min(ca.spot_free(l.base), float(info.get("coins") or 0) * 1.05) except live.LiveError as exc: with self.lock: self.recover[base] = info # tried again on the next cycle self._journal(base, "open", False, f"после перезапуска: не удалось проверить незавершённый вход: {exc}") return if short <= 0 and coins * l.spot_bid < 1.0: self._pending_done(base) self._journal(base, "open", True, "после перезапуска: незавершённый вход — на биржах ничего не открыто") return with self.lock: now = time.time() step = l.interval_h * 3600 pos = CrossPosition(self.next_uid, base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, short, l.spot_ask, l.fut_bid if short else 0.0, l.entry_gap, float(info.get("usual") or 0.0), 0.0, (now // step + 1) * step, real=True, spot_qty=coins, exact=False, innovation=l.innovation, error="подхвачено после перезапуска — цены оценочные") if short <= 0 or coins * l.spot_bid < 1.0: # one leg only: close what there is at once pos.retry_at, pos.usual = 0.0, 1e9 self.next_uid += 1 self.positions.append(pos) self.pending.pop(base, None) self.recover.pop(base, None) self.save() self._journal(base, "open", True, f"после перезапуска: найден незавершённый вход — шорт {short:g} на " f"{l.fut_ex}, спот {coins:g} на {l.spot_ex}; ведётся программой") # --- balances -------------------------------------------------------------------------------------------- def coins_value(self, exchange: str) -> float: """$ of the coins that real positions of every spot–futures engine hold on this exchange's spot account (the account figures count USDT only).""" import basis total = 0.0 for e in list(basis.ENGINES) + ([] if self in basis.ENGINES else [self]): for pos in list(e.positions): if not getattr(pos, "real", False): continue if getattr(pos, "spot_ex", None) is not None: if pos.spot_ex != exchange: continue l = e.links.get(pos.key) price = l.spot_bid if l else pos.spot_entry else: if getattr(getattr(e, "venue", None), "name", "") != exchange: continue p = e.pairs.get(pos.base) price = p.spot_bid if p else pos.spot_entry total += max(0.0, pos.spot_qty - pos.sold_coins) * price return total def balance_view(self, now: float) -> dict: """Per exchange: spot USDT, futures USDT (equity), coins of open positions, total — and the change since trading was started (the first balance read after the start is the reference).""" on = self.exchanges() rows, total, newest_ok = [], 0.0, True for ex in arb.EXCHANGES: k = ex.lower() b = self.balances.get(k) row = {"exchange": ex, "on": ex in on, "keys": b is not None, "spot": None, "futures": None, "low_funds": self.low_funds(ex) if ex in on else "", "limit": self.limit(ex), "open_count": len(self.open_on(ex)), "coins": None, "total": None, "error": "", "age": None, "fee_spot": self.fees[ex]["spot"], "fee_fut": self.fees[ex]["fut"], "fee_spot_src": self.fees[ex]["spot_src"], "fee_fut_src": self.fees[ex]["fut_src"], "fee_fut_innovation": self.fees[ex].get("fut_innovation"), "fee_fut_innovation_src": self.fees[ex].get("fut_innovation_src", "")} if b is not None: vals = b.get("values") or {} row["error"] = b.get("error", "") row["age"] = now - b["time"] if b.get("time") else None if not row["age"] or b["time"] <= (self.baseline.get("time") or 0): newest_ok = False unified = vals.get("Единый счёт USDT") spot = unified if isinstance(unified, (int, float)) else vals.get("Спот USDT") fut = None if isinstance(unified, (int, float)) else vals.get("Фьючерсы USDT") row["unified"] = isinstance(unified, (int, float)) row["spot"] = spot if isinstance(spot, (int, float)) else None row["futures"] = fut if isinstance(fut, (int, float)) else None if not row["error"] and isinstance(vals.get("Фьючерсы"), str): row["error"] = vals["Фьючерсы"] if row["spot"] is not None: row["coins"] = self.coins_value(ex) row["total"] = row["spot"] + (row["futures"] or 0.0) + row["coins"] total += row["total"] rows.append(row) keyed = [r for r in rows if r["keys"]] base = self.baseline if base and base.get("total") is None and keyed and newest_ok and all(r["total"] is not None for r in keyed): with self.lock: # the reference: first full read after the start base["total"] = total base["by_ex"] = {r["exchange"]: r["total"] for r in keyed} base["read"] = now self.save() for r in rows: ref = (base.get("by_ex") or {}).get(r["exchange"]) r["start"] = ref r["change_pct"] = (r["total"] - ref) / ref * 100 if ref and r["total"] is not None else None ref_total = base.get("total") return {"rows": rows, "total": total if keyed else None, "start_total": ref_total, "start_time": base.get("time"), "change_usd": total - ref_total if ref_total and keyed else None, "change_pct": (total - ref_total) / ref_total * 100 if ref_total and keyed else None} # --- view ------------------------------------------------------------------------------------------------ def view(self) -> dict: with self.lock: s, now = self.settings, time.time() best: dict[str, dict] = {} # the last cycle's rows (the hot links refreshed every HOT_S); computed here only before the first cycle source = list(self.cand.values()) if now - self.cand_time < 60 else self.candidates(now) for r in source: b = r["link"].base score = r["net"] if r["net"] is not None else -1e9 if b not in best or score > best[b]["score"]: best[b] = {**r, "score": score} real_open = [p.base for p in self.positions if p.real] rows = [] for r in best.values(): l = r["link"] why = r["why"] block = self.real_block.get(l.base, ("", 0.0)) if r["fits"]: full = self.full(l) if l.base not in real_open else "" why = ("торговля остановлена (кнопка «Старт»)" if not s.running else f"реально нельзя: {block[0]}" if s.real and block[1] > now else full if full else "сейчас открывается другая реальная сделка" if s.real and (self.opening - {l.base}) else f"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until else f"пауза по монете после закрытия ({s.cooldown_s:g} с)" if now - self.last_close.get(l.base, 0) < s.cooldown_s else "") rows.append({"base": l.base, "spot_ex": l.spot_ex, "fut_ex": l.fut_ex, "kind": l.kind, "kind_name": KIND_NAMES[l.kind], "spot_ask": l.spot_ask, "fut_bid": l.fut_bid, "entry_gap": l.entry_gap, "exit_gap": l.exit_gap, "usual": r["usual"], "excess": r["excess"], "history": r["history"], "fits": r["fits"], "why": why, "funding_pct": l.funding * 100, "interval_h": l.interval_h, "depth": None if l.spot_depth is None or l.fut_depth is None else min(l.spot_depth, l.fut_depth), "turnover": min(l.spot_turnover, l.fut_turnover), "net_pct": r["net"], "innovation": l.innovation, "hot": r["key"] in self.hot or r["key"] in getattr(self.leader, "hot", ()), "price_age": (now - self.fast_seen[r["key"]]) if r["key"] in self.fast_seen else None, "min_entry": r["min"]["usd"] if r["min"] else None, "min_spot": r["min"]["spot"] if r["min"] else None, "min_fut": r["min"]["fut"] if r["min"] else None, "fees_pct": round_trip_fee_pct(l.spot_ex, l.fut_ex, self.fees, l.innovation, l.ss), "spot_url": arb.spot_url(l.spot_ex, l.spot_symbol, l.base), "fut_url": (arb.spot_url(l.fut_ex, l.fut_symbol, l.base) if l.ss else arb.exchange_url(l.fut_ex, l.fut_symbol))}) rows.sort(key=lambda r: -(r["net_pct"] if r["net_pct"] is not None else -1e9)) positions = [] for pos in self.positions: d = asdict(pos) d.pop("fills", None) d.update(kind=pos.kind, kind_name=KIND_NAMES[pos.kind]) level, now_usual = self.exit_level(pos) d.update(exit_level=level, usual_now=now_usual, exit_target=level + s.exit_over_usual_pct) l = self.links.get(pos.key) if l: _, _, fees, net = close_result(pos, l.spot_bid, l.fut_ask, self.fees) seen = self.fast_seen.get(pos.key) d.update(price_age=None if seen is None else now - seen, fast_ms=self.fast_ms) d.update(liq_pct=(pos.liq_price / l.fut_ask - 1) * 100 if pos.liq_price > 0 else None) if pos.exit_since and not pos.closing: # counting down to a «back to usual» close d["exit_held"] = now - pos.exit_since d.update(gap_now=l.exit_gap, spot_now=l.spot_bid, fut_now=l.fut_ask, net=net, fees_total=fees, spot_url=arb.spot_url(l.spot_ex, l.spot_symbol, l.base), fut_url=(arb.spot_url(l.fut_ex, l.fut_symbol, l.base) if l.ss else arb.exchange_url(l.fut_ex, l.fut_symbol))) positions.append(d) # real mode: the figures are those of the real trades only (prices and fees from the exchanges' fills) closed = [t for t in self.trades if t.real] if s.real else self.trades opened = [p for p in positions if p.get("real")] if s.real else positions wins = sum(t.net > 0 for t in closed) invested = sum(t.amount for t in closed) stats = {"trades": len(closed), "wins": wins, "net": sum(t.net for t in closed), "net_pct": sum(t.net for t in closed) / invested * 100 if invested else None, "fees": sum(t.fees for t in closed), "funding": sum(t.funding for t in closed), "open": len(opened), "unrealized": sum(p.get("net", 0) for p in opened), "real": s.real, "exact": all(t.exact for t in closed), "avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None} out = {"mode": "cross", "venue": "Арбитраж", "key": "cross", "settings": asdict(s), "status": self.status, "ex_status": self.ex_status, "updated": self.updated, "cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.links), "memes_source": "", "rows": rows[:300], "positions": positions, "trades": [asdict(t) for t in reversed(closed[-200:])], "stats": stats, "recovery": {base: dict(info) for base, info in {**self.recover, **self.pending}.items()}, "real_pause": ("сверка незавершённых ордеров: " + ", ".join({**self.recover, **self.pending}) if s.real and (self.pending or self.recover) else f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)" if s.real and now < self.real_pause_until else "")} out["balances"] = self.balance_view(now) return out