570 lines
27 KiB
Python
570 lines
27 KiB
Python
"""Cross-exchange arbitrage scanner for USDT perpetuals on Bybit, Binance, MEXC, HTX and Gate.
|
||
|
||
Every cycle (10 s) the best bid/ask of every perpetual on each exchange is fetched with one public request per
|
||
exchange; coins are matched by base ticker (contract-size prefixes such as 1000PEPE are converted to one coin). For
|
||
each coin listed on at least two exchanges the best pair "buy at the ask of A, sell at the bid of B" is taken:
|
||
|
||
* gross spread = bid_B / ask_A − 1 (what an instant entry would capture);
|
||
* costs = taker fees of both legs, on entry and on exit (round trip);
|
||
* usual spread of that pair = exponential average over ~30 min of this scanner's own readings;
|
||
* expected = gross − usual − round-trip costs: the profit if the gap goes back to its usual size;
|
||
* funding per 8 h: short leg receives its rate, long leg pays its rate (sign as each exchange quotes it);
|
||
* depth = USD available at those best prices (where the exchange reports it), 24 h turnover.
|
||
|
||
A spread above 10 % is flagged «разные монеты?» (the same ticker often means different tokens). Nothing is traded.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import threading
|
||
import time
|
||
import urllib.request
|
||
from pathlib import Path
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
from dataclasses import dataclass
|
||
|
||
EXCHANGES = ["Bybit", "MEXC", "HTX", "Gate"]
|
||
TAKER = {"Bybit": 0.055, "MEXC": 0.02, "HTX": 0.05, "Gate": 0.05} # % per market order, futures
|
||
# spot market-order fees at the base level (no VIP, no fee-token discount) — editable on the page
|
||
SPOT_TAKER = {"Bybit": 0.1, "MEXC": 0.05, "HTX": 0.2, "Gate": 0.1}
|
||
LEVERAGED = re.compile(r"(\d+[LS]|UP|DOWN|BULL|BEAR)$") # leveraged tokens, not the coin itself
|
||
CYCLE_S = 10.0
|
||
USUAL_WINDOW_S = 1800.0
|
||
DIFFERENT_COIN_PCT = 10.0
|
||
_PREFIX = re.compile(r"^(1000000|100000|10000|1000|100|1M)(?=[A-Z])")
|
||
_SUFFIX = re.compile(r"^([A-Z][A-Z0-9]*?)(1000000|10000|1000)$")
|
||
|
||
|
||
def split_base(raw: str) -> tuple[str, float]:
|
||
"""'1000PEPE' -> ('PEPE', 1000); 'SHIB1000' -> ('SHIB', 1000); '1INCH' stays."""
|
||
raw = raw.upper()
|
||
m = _PREFIX.match(raw)
|
||
if m:
|
||
return raw[m.end():], (1_000_000.0 if m.group(1) == "1M" else float(m.group(1)))
|
||
m = _SUFFIX.match(raw)
|
||
if m and len(m.group(1)) >= 2:
|
||
return m.group(1), float(m.group(2))
|
||
return raw, 1.0
|
||
|
||
|
||
def _f(v, default=0.0) -> float:
|
||
try:
|
||
return float(v)
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
def _get(url: str, timeout: float = 20):
|
||
# gzip: whole-market lists are megabytes of JSON; compressed they come several times faster
|
||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json",
|
||
"Accept-Encoding": "gzip"})
|
||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||
raw = resp.read()
|
||
if resp.headers.get("Content-Encoding", "").lower() == "gzip":
|
||
import gzip
|
||
raw = gzip.decompress(raw)
|
||
return json.loads(raw)
|
||
|
||
|
||
@dataclass
|
||
class Quote:
|
||
exchange: str
|
||
symbol: str # exchange's own symbol
|
||
base: str
|
||
mult: float # coins per quoted unit (1000PEPE -> 1000)
|
||
bid: float # per coin
|
||
ask: float
|
||
bid_usd: float | None # money at the best bid / ask (None: not reported)
|
||
ask_usd: float | None
|
||
funding: float | None # current rate, fraction per period
|
||
interval_h: float # funding period, hours
|
||
volume_usd: float
|
||
|
||
|
||
def _quote(exchange, symbol, raw_base, bid, ask, bid_coins, ask_coins, funding, interval_h, volume,
|
||
split: bool = True) -> Quote | None:
|
||
# spot tickers are the token's own name (1000SATS, 1INCH): no contract-size prefixes there
|
||
base, mult = split_base(raw_base) if split else (raw_base.upper(), 1.0)
|
||
bid, ask = _f(bid), _f(ask)
|
||
if not base or bid <= 0 or ask <= 0 or ask < bid:
|
||
return None
|
||
bid_c = None if bid_coins is None else _f(bid_coins)
|
||
ask_c = None if ask_coins is None else _f(ask_coins)
|
||
return Quote(exchange, symbol, base, mult, bid / mult, ask / mult,
|
||
None if bid_c is None else bid_c * bid, None if ask_c is None else ask_c * ask,
|
||
None if funding in (None, "") else _f(funding), interval_h or 8.0, _f(volume))
|
||
|
||
|
||
# --- per-exchange fetchers (all public, one request for the whole market + rare reference data) -----------------
|
||
|
||
class Fetchers:
|
||
def __init__(self) -> None:
|
||
self.ref: dict[str, dict] = {} # slowly changing reference data, refreshed hourly
|
||
self.ref_time = 0.0
|
||
self.binance_volume: dict[str, float] = {}
|
||
self.binance_volume_time = 0.0
|
||
|
||
def refresh_reference(self) -> None:
|
||
if time.time() - self.ref_time < 3600 and self.ref:
|
||
return
|
||
ref: dict[str, dict] = {"bybit_interval": {}, "htx_size": {}, "htx_interval": {},
|
||
"gate_interval": {}, "mexc_size": {}}
|
||
try:
|
||
for it in _get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000")["result"]["list"]:
|
||
ref["bybit_interval"][it["symbol"]] = _f(it.get("fundingInterval"), 480) / 60
|
||
except Exception:
|
||
pass
|
||
try:
|
||
for it in _get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]:
|
||
ref["htx_size"][it["contract_code"]] = _f(it.get("contract_size"), 1)
|
||
ref["htx_interval"][it["contract_code"]] = _f(it.get("settlement_period"), 8)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
for it in _get("https://api.gateio.ws/api/v4/futures/usdt/contracts"):
|
||
ref["gate_interval"][it["name"]] = _f(it.get("funding_interval"), 28800) / 3600
|
||
except Exception:
|
||
pass
|
||
try:
|
||
for it in _get("https://contract.mexc.com/api/v1/contract/detail")["data"]:
|
||
ref["mexc_size"][it["symbol"]] = _f(it.get("contractSize"), 1)
|
||
except Exception:
|
||
pass
|
||
self.ref, self.ref_time = ref, time.time()
|
||
|
||
def bybit(self) -> list[Quote]:
|
||
out = []
|
||
for t in _get("https://api.bybit.com/v5/market/tickers?category=linear")["result"]["list"]:
|
||
s = t["symbol"]
|
||
if s.endswith("USDT"):
|
||
out.append(_quote("Bybit", s, s[:-4], t.get("bid1Price"), t.get("ask1Price"), t.get("bid1Size"),
|
||
t.get("ask1Size"), t.get("fundingRate"),
|
||
self.ref.get("bybit_interval", {}).get(s, 8), t.get("turnover24h")))
|
||
return [q for q in out if q]
|
||
|
||
def binance(self) -> list[Quote]:
|
||
books = _get("https://fapi.binance.com/fapi/v1/ticker/bookTicker")
|
||
prem = {p["symbol"]: p for p in _get("https://fapi.binance.com/fapi/v1/premiumIndex")}
|
||
if time.time() - self.binance_volume_time > 60:
|
||
self.binance_volume = {t["symbol"]: _f(t.get("quoteVolume"))
|
||
for t in _get("https://fapi.binance.com/fapi/v1/ticker/24hr")}
|
||
self.binance_volume_time = time.time()
|
||
out = []
|
||
for t in books:
|
||
s = t["symbol"]
|
||
if s.endswith("USDT") and "_" not in s:
|
||
out.append(_quote("Binance", s, s[:-4], t.get("bidPrice"), t.get("askPrice"), t.get("bidQty"),
|
||
t.get("askQty"), prem.get(s, {}).get("lastFundingRate"),
|
||
self.ref.get("binance_interval", {}).get(s, 8), self.binance_volume.get(s)))
|
||
return [q for q in out if q]
|
||
|
||
def mexc(self) -> list[Quote]:
|
||
out = []
|
||
for t in _get("https://contract.mexc.com/api/v1/contract/ticker")["data"]:
|
||
s = t["symbol"]
|
||
if s.endswith("_USDT"):
|
||
out.append(_quote("MEXC", s, s[:-5], t.get("bid1"), t.get("ask1"), None, None, t.get("fundingRate"),
|
||
8, t.get("amount24")))
|
||
return [q for q in out if q]
|
||
|
||
def htx(self) -> list[Quote]:
|
||
funding = {}
|
||
try:
|
||
for f in _get("https://api.hbdm.com/linear-swap-api/v1/swap_batch_funding_rate")["data"]:
|
||
funding[f["contract_code"]] = f.get("funding_rate")
|
||
except Exception:
|
||
pass
|
||
out = []
|
||
sizes = self.ref.get("htx_size", {})
|
||
for t in _get("https://api.hbdm.com/linear-swap-ex/market/detail/batch_merged?business_type=swap")["ticks"]:
|
||
code = t.get("contract_code", "")
|
||
if not code.endswith("-USDT") or not t.get("bid") or not t.get("ask"):
|
||
continue
|
||
size = sizes.get(code)
|
||
out.append(_quote("HTX", code, code[:-5], t["bid"][0], t["ask"][0],
|
||
None if size is None else _f(t["bid"][1]) * size,
|
||
None if size is None else _f(t["ask"][1]) * size, funding.get(code),
|
||
self.ref.get("htx_interval", {}).get(code, 8), t.get("trade_turnover")))
|
||
return [q for q in out if q]
|
||
|
||
def gate(self) -> list[Quote]:
|
||
out = []
|
||
for t in _get("https://api.gateio.ws/api/v4/futures/usdt/tickers"):
|
||
s = t["contract"]
|
||
if s.endswith("_USDT"):
|
||
mult = _f(t.get("quanto_multiplier"), 0) or None
|
||
out.append(_quote("Gate", s, s[:-5], t.get("highest_bid"), t.get("lowest_ask"),
|
||
None if mult is None else _f(t.get("highest_size")) * mult,
|
||
None if mult is None else _f(t.get("lowest_size")) * mult, t.get("funding_rate"),
|
||
self.ref.get("gate_interval", {}).get(s, 8), t.get("volume_24h_quote")))
|
||
return [q for q in out if q]
|
||
|
||
|
||
def norm_chain(name: str) -> str:
|
||
"""Rough common name of a network across exchanges (ERC20 → ETH, BEP20 → BSC, TRC20 → TRX …)."""
|
||
n = (name or "").upper().replace("-", "").replace("_", "").replace(" ", "")
|
||
for key, value in (("ERC20", "ETH"), ("ETHEREUM", "ETH"), ("BEP20", "BSC"), ("BNBSMARTCHAIN", "BSC"),
|
||
("BSC", "BSC"), ("TRC20", "TRX"), ("TRON", "TRX"), ("SOLANA", "SOL"), ("SPL", "SOL"),
|
||
("ARBITRUM", "ARB"), ("ARBONE", "ARB"), ("OPTIMISM", "OP"), ("POLYGON", "MATIC"),
|
||
("MATIC", "MATIC"), ("BASE", "BASE"), ("TON", "TON"), ("AVAXC", "AVAX")):
|
||
if n.startswith(key) or n == key:
|
||
return value
|
||
return n
|
||
|
||
|
||
class SpotFetchers:
|
||
"""USDT spot pairs of the five exchanges; wallet status (deposit / withdraw per network) where public."""
|
||
|
||
def __init__(self) -> None:
|
||
self.volume: dict[str, dict[str, float]] = {}
|
||
self.volume_time = 0.0
|
||
self.wallet: dict[str, dict[str, dict]] = {} # exchange → coin → {"chains": {net: {...}}, ...}
|
||
self.wallet_time = 0.0
|
||
|
||
def refresh_volume(self) -> None:
|
||
if time.time() - self.volume_time < 60 and self.volume:
|
||
return
|
||
vol = {}
|
||
try:
|
||
vol["MEXC"] = {t["symbol"]: _f(t.get("quoteVolume")) for t in _get("https://api.mexc.com/api/v3/ticker/24hr")}
|
||
except Exception:
|
||
pass
|
||
self.volume, self.volume_time = vol, time.time()
|
||
|
||
def refresh_wallet(self) -> None:
|
||
"""HTX and Gate publish deposit/withdraw status per network (HTX also the withdrawal fee); hourly."""
|
||
if time.time() - self.wallet_time < 3600 and self.wallet:
|
||
return
|
||
wallet: dict[str, dict[str, dict]] = {"HTX": {}, "Gate": {}}
|
||
try:
|
||
for c in _get("https://api.huobi.pro/v2/reference/currencies")["data"]:
|
||
chains = {}
|
||
for ch in c.get("chains", []):
|
||
net = norm_chain(ch.get("baseChainProtocol") or ch.get("baseChain") or ch.get("displayName") or "")
|
||
chains[net] = {"deposit": ch.get("depositStatus") == "allowed",
|
||
"withdraw": ch.get("withdrawStatus") == "allowed",
|
||
"fee": _f(ch.get("transactFeeWithdraw"), None) if ch.get("transactFeeWithdraw")
|
||
not in (None, "") else None,
|
||
"addr": (ch.get("contractAddress") or "").lower(), "name": ch.get("displayName")}
|
||
wallet["HTX"][c["currency"].upper()] = {"chains": chains}
|
||
except Exception:
|
||
pass
|
||
try:
|
||
for c in _get("https://api.gateio.ws/api/v4/spot/currencies"):
|
||
chains = {}
|
||
for ch in c.get("chains") or []:
|
||
chains[norm_chain(ch.get("name", ""))] = {
|
||
"deposit": not ch.get("deposit_disabled"), "withdraw": not ch.get("withdraw_disabled"),
|
||
"fee": None, "addr": (ch.get("addr") or "").lower(), "name": ch.get("name")}
|
||
coin = c["currency"].upper()
|
||
if coin not in wallet["Gate"] or not c.get("delisted"):
|
||
wallet["Gate"][coin] = {"chains": chains, "delisted": bool(c.get("delisted"))}
|
||
except Exception:
|
||
pass
|
||
self.wallet, self.wallet_time = wallet, time.time()
|
||
|
||
def bybit(self) -> list[Quote]:
|
||
out = []
|
||
for t in _get("https://api.bybit.com/v5/market/tickers?category=spot")["result"]["list"]:
|
||
s = t["symbol"]
|
||
if s.endswith("USDT"):
|
||
out.append(_quote("Bybit", s, s[:-4], t.get("bid1Price"), t.get("ask1Price"), t.get("bid1Size"),
|
||
t.get("ask1Size"), None, 8, t.get("turnover24h"), split=False))
|
||
return [q for q in out if q]
|
||
|
||
def binance(self) -> list[Quote]:
|
||
vol = self.volume.get("Binance", {})
|
||
out = []
|
||
for t in _get("https://api.binance.com/api/v3/ticker/bookTicker"):
|
||
s = t["symbol"]
|
||
if s.endswith("USDT"):
|
||
out.append(_quote("Binance", s, s[:-4], t.get("bidPrice"), t.get("askPrice"), t.get("bidQty"),
|
||
t.get("askQty"), None, 8, vol.get(s), split=False))
|
||
return [q for q in out if q]
|
||
|
||
def mexc(self) -> list[Quote]:
|
||
vol = self.volume.get("MEXC", {})
|
||
out = []
|
||
for t in _get("https://api.mexc.com/api/v3/ticker/bookTicker"):
|
||
s = t["symbol"]
|
||
if s.endswith("USDT"):
|
||
out.append(_quote("MEXC", s, s[:-4], t.get("bidPrice"), t.get("askPrice"), t.get("bidQty"),
|
||
t.get("askQty"), None, 8, vol.get(s), split=False))
|
||
return [q for q in out if q]
|
||
|
||
def htx(self) -> list[Quote]:
|
||
out = []
|
||
for t in _get("https://api.huobi.pro/market/tickers")["data"]:
|
||
s = t["symbol"]
|
||
if s.endswith("usdt"):
|
||
out.append(_quote("HTX", s, s[:-4], t.get("bid"), t.get("ask"), t.get("bidSize"), t.get("askSize"),
|
||
None, 8, t.get("vol"), split=False))
|
||
return [q for q in out if q]
|
||
|
||
def gate(self) -> list[Quote]:
|
||
out = []
|
||
for t in _get("https://api.gateio.ws/api/v4/spot/tickers"):
|
||
s = t["currency_pair"]
|
||
if s.endswith("_USDT"):
|
||
out.append(_quote("Gate", s, s[:-5], t.get("highest_bid"), t.get("lowest_ask"), None, None, None, 8,
|
||
t.get("quote_volume"), split=False))
|
||
return [q for q in out if q]
|
||
|
||
|
||
def spot_url(exchange: str, symbol: str, base: str) -> str:
|
||
return {"Bybit": f"https://www.bybit.com/trade/spot/{base}/USDT",
|
||
"Binance": f"https://www.binance.com/en/trade/{base}_USDT?type=spot",
|
||
"MEXC": f"https://www.mexc.com/exchange/{base}_USDT",
|
||
"HTX": f"https://www.htx.com/trade/{base.lower()}_usdt",
|
||
"Gate": f"https://www.gate.com/trade/{base}_USDT"}.get(exchange, "")
|
||
|
||
|
||
def transfer_info(wallet: dict, base: str, src: str, dst: str, price: float) -> dict:
|
||
"""What is known about moving `base` from `src` (withdraw) to `dst` (deposit): status, common networks,
|
||
the cheapest known withdrawal fee in $, and a contract-address mismatch (= different tokens)."""
|
||
a = wallet.get(src, {}).get(base)
|
||
b = wallet.get(dst, {}).get(base)
|
||
info = {"withdraw": None, "deposit": None, "networks": [], "fee_usd": None, "fee_net": None,
|
||
"different_token": False}
|
||
if a:
|
||
info["withdraw"] = any(c["withdraw"] for c in a["chains"].values()) if a["chains"] else None
|
||
if b:
|
||
info["deposit"] = any(c["deposit"] for c in b["chains"].values()) if b["chains"] else None
|
||
if b.get("delisted"):
|
||
info["deposit"] = False
|
||
if a and b:
|
||
common = [n for n in a["chains"] if n in b["chains"]]
|
||
usable = [n for n in common if a["chains"][n]["withdraw"] and b["chains"][n]["deposit"]]
|
||
info["networks"] = usable
|
||
if common and not usable:
|
||
info["withdraw"] = info["withdraw"] and False
|
||
for n in common:
|
||
x, y = a["chains"][n]["addr"], b["chains"][n]["addr"]
|
||
if x and y and x != y:
|
||
info["different_token"] = True
|
||
elif a:
|
||
info["networks"] = [n for n, c in a["chains"].items() if c["withdraw"]]
|
||
elif b:
|
||
info["networks"] = [n for n, c in b["chains"].items() if c["deposit"]]
|
||
if a:
|
||
# a fee above 500 $ is not a real withdrawal fee (another token on that network, or a unit mix-up)
|
||
fees = [(c["fee"] * price, n) for n, c in a["chains"].items()
|
||
if c["fee"] is not None and c["withdraw"] and (not info["networks"] or n in info["networks"])
|
||
and c["fee"] * price < 500]
|
||
if fees:
|
||
info["fee_usd"], info["fee_net"] = min(fees)
|
||
return info
|
||
|
||
|
||
def exchange_url(exchange: str, symbol: str) -> str:
|
||
return {"Bybit": f"https://www.bybit.com/trade/usdt/{symbol}",
|
||
"Binance": f"https://www.binance.com/en/futures/{symbol}",
|
||
"MEXC": f"https://futures.mexc.com/exchange/{symbol}",
|
||
"HTX": f"https://www.htx.com/futures/exchange/{symbol.lower()}",
|
||
"Gate": f"https://www.gate.com/futures/USDT/{symbol}"}.get(exchange, "")
|
||
|
||
|
||
def funding_8h(q: Quote) -> float | None:
|
||
"""Funding rate in % per 8 hours."""
|
||
return None if q.funding is None else q.funding * 100 * 8 / max(q.interval_h, 0.1)
|
||
|
||
|
||
def best_pairs(quotes: list[Quote], usual: dict, taker: dict | None = None, market: str = "futures",
|
||
wallet: dict | None = None) -> list[dict]:
|
||
"""Best buy/sell pair for every coin listed on two or more exchanges.
|
||
|
||
futures: the spread is captured by opening and later closing both legs → fees ×2 (round trip);
|
||
spot: buy on one exchange, move the coin, sell on the other → fees of the two trades ×1, plus the transfer."""
|
||
spot = market == "spot"
|
||
taker = taker or (SPOT_TAKER if spot else TAKER)
|
||
url = (lambda q: spot_url(q.exchange, q.symbol, q.base)) if spot else (lambda q: exchange_url(q.exchange, q.symbol))
|
||
by_base: dict[str, list[Quote]] = {}
|
||
for q in quotes:
|
||
if spot and LEVERAGED.search(q.base) and len(q.base) > 3:
|
||
continue
|
||
by_base.setdefault(q.base, []).append(q)
|
||
rows = []
|
||
for base, qs in by_base.items():
|
||
if len({q.exchange for q in qs}) < 2:
|
||
continue
|
||
best = None
|
||
for a in qs: # buy at a.ask
|
||
for b in qs: # sell at b.bid
|
||
if a.exchange == b.exchange:
|
||
continue
|
||
gross = (b.bid / a.ask - 1) * 100
|
||
if best is None or gross > best[0]:
|
||
best = (gross, a, b)
|
||
gross, a, b = best
|
||
entry = taker.get(a.exchange, 0.1) + taker.get(b.exchange, 0.1)
|
||
cost = entry if spot else 2 * entry
|
||
key = f"{base}|{a.exchange}|{b.exchange}"
|
||
u = usual.get(key)
|
||
depth = None if a.ask_usd is None or b.bid_usd is None else min(a.ask_usd, b.bid_usd)
|
||
fa, fb = funding_8h(a), funding_8h(b)
|
||
carry = None if fa is None or fb is None else fb - fa # short receives fb, long pays fa
|
||
transfer = transfer_info(wallet or {}, base, a.exchange, b.exchange, a.ask) if spot else None
|
||
rows.append({
|
||
"coin": base, "key": key, "market": market, "buy": a.exchange, "buy_symbol": a.symbol,
|
||
"buy_price": a.ask, "sell": b.exchange, "sell_symbol": b.symbol, "sell_price": b.bid, "gross": gross,
|
||
"entry_cost": entry, "round_cost": cost, "usual": u,
|
||
"expected": None if u is None else gross - max(u, 0.0) - cost,
|
||
"net_now": gross - cost, "funding_buy": fa, "funding_sell": fb, "carry_8h": carry,
|
||
"depth_usd": depth, "volume_usd": min(a.volume_usd, b.volume_usd),
|
||
"exchanges": sorted({q.exchange for q in qs}),
|
||
"prices": {q.exchange: {"bid": q.bid, "ask": q.ask, "symbol": q.symbol, "funding_8h": funding_8h(q),
|
||
"funding": q.funding, "interval_h": q.interval_h, "mult": q.mult,
|
||
"bid_usd": q.bid_usd, "ask_usd": q.ask_usd, "url": url(q)} for q in qs},
|
||
"buy_url": url(a), "sell_url": url(b), "transfer": transfer,
|
||
"suspect": gross > DIFFERENT_COIN_PCT or bool(transfer and transfer["different_token"]),
|
||
})
|
||
rows.sort(key=lambda r: -r["gross"])
|
||
return rows
|
||
|
||
|
||
PAUSED_FILE = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", Path(__file__).resolve().parent / "web_sim_data")) \\
|
||
/ "arb_paused.json"
|
||
|
||
|
||
def load_paused() -> dict:
|
||
try:
|
||
data = json.loads(PAUSED_FILE.read_text(encoding="utf-8"))
|
||
return data if isinstance(data, dict) else {}
|
||
except (OSError, ValueError):
|
||
return {}
|
||
|
||
|
||
class ArbScanner:
|
||
"""Background loop: fetch all five exchanges every CYCLE_S seconds, keep the latest rows and the usual spreads."""
|
||
|
||
def __init__(self, market: str = "futures") -> None:
|
||
self.market = market
|
||
self.fetchers = SpotFetchers() if market == "spot" else Fetchers()
|
||
self.lock = threading.Lock()
|
||
self.rows: list[dict] = []
|
||
self.usual: dict[str, float] = {}
|
||
# per pair (coin|buy|sell): minute → lowest spread seen in that minute (for «does it survive a transfer»),
|
||
# and since when it has been above the round-trip costs without a break
|
||
self.history: dict[str, dict[int, float]] = {}
|
||
self.profitable_since: dict[str, float] = {}
|
||
self.status: dict[str, str] = {e: "жду" for e in EXCHANGES}
|
||
self.counts: dict[str, int] = {}
|
||
self.updated = 0.0
|
||
self.cycle_ms = 0
|
||
self.thread: threading.Thread | None = None
|
||
self.paused = load_paused().get(market, False) # «Стоп» on the page: no requests to the exchanges
|
||
|
||
def set_paused(self, paused: bool) -> None:
|
||
self.paused = paused
|
||
state = load_paused()
|
||
state[self.market] = paused
|
||
try:
|
||
PAUSED_FILE.parent.mkdir(exist_ok=True)
|
||
PAUSED_FILE.write_text(json.dumps(state), encoding="utf-8")
|
||
except OSError:
|
||
pass
|
||
|
||
def ensure_running(self) -> None:
|
||
if self.thread is None:
|
||
self.thread = threading.Thread(target=self._loop, daemon=True)
|
||
self.thread.start()
|
||
|
||
def _loop(self) -> None:
|
||
while True:
|
||
if self.paused:
|
||
time.sleep(0.5)
|
||
continue
|
||
start = time.time()
|
||
try:
|
||
self.scan_once()
|
||
except Exception:
|
||
pass
|
||
time.sleep(max(1.0, CYCLE_S - (time.time() - start)))
|
||
|
||
def scan_once(self) -> None:
|
||
start = time.time()
|
||
for refresh in ("refresh_reference", "refresh_volume", "refresh_wallet"):
|
||
if hasattr(self.fetchers, refresh):
|
||
try:
|
||
getattr(self.fetchers, refresh)()
|
||
except Exception:
|
||
pass
|
||
calls = {"Bybit": self.fetchers.bybit, "MEXC": self.fetchers.mexc,
|
||
"HTX": self.fetchers.htx, "Gate": self.fetchers.gate}
|
||
quotes, status, counts = [], {}, {}
|
||
|
||
def one(name):
|
||
try:
|
||
qs = calls[name]()
|
||
return name, qs, "ok"
|
||
except Exception as exc:
|
||
return name, [], f"ошибка: {str(exc)[:80]}"
|
||
|
||
with ThreadPoolExecutor(max_workers=len(EXCHANGES)) as pool:
|
||
for name, qs, st in pool.map(one, EXCHANGES):
|
||
quotes += qs
|
||
status[name], counts[name] = st, len(qs)
|
||
rows = best_pairs(quotes, self.usual, market=self.market, wallet=getattr(self.fetchers, "wallet", None))
|
||
alpha = min(1.0, CYCLE_S / USUAL_WINDOW_S)
|
||
now = time.time()
|
||
minute = int(now // 60)
|
||
for r in rows: # the usual spread of the chosen pair (updated after use)
|
||
prev = self.usual.get(r["key"])
|
||
self.usual[r["key"]] = r["gross"] if prev is None else prev + alpha * (r["gross"] - prev)
|
||
self.record(r["key"], r["gross"], r["net_now"] > 0, now, minute)
|
||
self._prune(minute)
|
||
with self.lock:
|
||
self.rows, self.status, self.counts = rows, status, counts
|
||
self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000)
|
||
|
||
HISTORY_MIN = 180
|
||
|
||
def record(self, key: str, gross: float, profitable: bool, now: float, minute: int) -> None:
|
||
h = self.history.setdefault(key, {})
|
||
h[minute] = min(h.get(minute, gross), gross)
|
||
if profitable:
|
||
self.profitable_since.setdefault(key, now)
|
||
else:
|
||
self.profitable_since.pop(key, None)
|
||
|
||
def _prune(self, minute: int) -> None:
|
||
if minute % 10:
|
||
return
|
||
for key in list(self.history):
|
||
h = self.history[key]
|
||
for m in [m for m in h if m < minute - self.HISTORY_MIN]:
|
||
del h[m]
|
||
if not h:
|
||
del self.history[key]
|
||
|
||
def window_min(self, key: str, minutes: float, now: float) -> tuple[float | None, float]:
|
||
"""(lowest spread over the last `minutes`, minutes of history actually available for this pair)."""
|
||
h = self.history.get(key, {})
|
||
current = int(now // 60)
|
||
span = int(max(1, round(minutes)))
|
||
recent = [v for m, v in h.items() if m > current - span]
|
||
have = len([m for m in h if m > current - self.HISTORY_MIN])
|
||
return (min(recent) if recent else None), float(have)
|
||
|
||
def view(self, transfer_min: float | None = None) -> dict:
|
||
self.ensure_running()
|
||
with self.lock:
|
||
now = time.time()
|
||
rows = []
|
||
for r in self.rows:
|
||
r = dict(r)
|
||
since = self.profitable_since.get(r["key"])
|
||
r["held_min"] = None if since is None else (now - since) / 60
|
||
if transfer_min:
|
||
low, have = self.window_min(r["key"], transfer_min, now)
|
||
r["window_low"] = low
|
||
r["history_min"] = have
|
||
rows.append(r)
|
||
return {"rows": rows, "status": self.status, "counts": self.counts, "updated": self.updated,
|
||
"cycle_ms": self.cycle_ms, "taker": SPOT_TAKER if self.market == "spot" else TAKER,
|
||
"market": self.market, "cycle_s": CYCLE_S, "paused": self.paused,
|
||
"usual_minutes": USUAL_WINDOW_S / 60, "transfer_min": transfer_min}
|