225 lines
10 KiB
Python
225 lines
10 KiB
Python
"""The smallest orders the five exchanges accept, spot and USDT perpetual, and from them the smallest trade amount a
|
||
spot–futures trade can be entered with: the spot buy must reach the spot minimum (USDT and coins) and the coins
|
||
bought must make at least the perp's minimum lot (and its minimum notional) — both legs, or the trade is not made.
|
||
|
||
The rules come from the exchanges' public instrument lists (no keys), loaded in the background and renewed hourly.
|
||
Paper and real trading check the same figure, so the paper trades are only those a real account could make.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import math
|
||
import threading
|
||
import time
|
||
|
||
import arb
|
||
|
||
REFRESH_S = 3600.0
|
||
RETRY_S = 300.0
|
||
MARGIN = 1.02 # prices move between the check and the order, and the lot is rounded down
|
||
AUTOLOAD = False # the program turns it on; tests fill the rules themselves (no network)
|
||
|
||
|
||
def _f(v, default: float = 0.0) -> float:
|
||
try:
|
||
return float(v)
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
def _units(symbol_base: str) -> float:
|
||
return arb.split_base(symbol_base)[1]
|
||
|
||
|
||
# --- loaders: {key: rule}; spot keyed by base coin, perp by the symbol the price lists use --------------------------
|
||
# spot rule: {"usd": smallest order in USDT, "coins": smallest quantity}; perp rule: {"coins": smallest order in
|
||
# coins (lot × contract size), "usd": smallest notional}
|
||
def _bybit(category: str) -> dict:
|
||
out, cursor = {}, ""
|
||
while True:
|
||
res = arb._get(f"https://api.bybit.com/v5/market/instruments-info?category={category}&limit=1000"
|
||
+ (f"&cursor={cursor}" if cursor else ""))["result"]
|
||
for x in res["list"]:
|
||
if x.get("quoteCoin") != "USDT" or x.get("status") != "Trading":
|
||
continue
|
||
lot = x.get("lotSizeFilter") or {}
|
||
if category == "spot":
|
||
out[x["baseCoin"]] = {"usd": _f(lot.get("minOrderAmt")), "coins": _f(lot.get("minOrderQty"))}
|
||
else:
|
||
out[x["symbol"]] = {"coins": max(_f(lot.get("minOrderQty")), _f(lot.get("qtyStep")))
|
||
* _units(x["symbol"][:-4]), "usd": _f(lot.get("minNotionalValue"))}
|
||
cursor = res.get("nextPageCursor") or ""
|
||
if not cursor or not res["list"]:
|
||
return out
|
||
|
||
|
||
def _binance_spot() -> dict:
|
||
out = {}
|
||
for s in arb._get("https://api.binance.com/api/v3/exchangeInfo?symbolStatus=TRADING")["symbols"]:
|
||
if s.get("quoteAsset") != "USDT":
|
||
continue
|
||
f = {x["filterType"]: x for x in s.get("filters", [])}
|
||
notional = f.get("NOTIONAL") or f.get("MIN_NOTIONAL") or {}
|
||
out[s["baseAsset"]] = {"usd": _f(notional.get("minNotional")), "coins": _f((f.get("LOT_SIZE") or {}).get("minQty"))}
|
||
return out
|
||
|
||
|
||
def _binance_fut() -> dict:
|
||
out = {}
|
||
for s in arb._get("https://fapi.binance.com/fapi/v1/exchangeInfo")["symbols"]:
|
||
if s.get("quoteAsset") != "USDT" or s.get("status") != "TRADING":
|
||
continue
|
||
f = {x["filterType"]: x for x in s.get("filters", [])}
|
||
lot = f.get("MARKET_LOT_SIZE") if _f((f.get("MARKET_LOT_SIZE") or {}).get("stepSize")) > 0 else f.get("LOT_SIZE", {})
|
||
out[s["symbol"]] = {"coins": max(_f(lot.get("minQty")), _f(lot.get("stepSize"))) * _units(s["symbol"][:-4]),
|
||
"usd": _f((f.get("MIN_NOTIONAL") or {}).get("notional"))}
|
||
return out
|
||
|
||
|
||
def _mexc_spot() -> dict:
|
||
out = {}
|
||
for s in arb._get("https://api.mexc.com/api/v3/exchangeInfo")["symbols"]:
|
||
if s.get("quoteAsset") != "USDT":
|
||
continue
|
||
out[s["baseAsset"]] = {"usd": _f(s.get("quoteAmountPrecisionMarket") or s.get("quoteAmountPrecision")),
|
||
"coins": _f(s.get("baseSizePrecision"))}
|
||
return out
|
||
|
||
|
||
def _mexc_fut() -> dict:
|
||
out = {}
|
||
for c in arb._get("https://contract.mexc.com/api/v1/contract/detail")["data"]:
|
||
if c.get("quoteCoin") != "USDT":
|
||
continue
|
||
out[c["symbol"]] = {"coins": _f(c.get("contractSize"), 1) * _units(c["symbol"][:-5]) * max(1.0, _f(c.get("minVol"), 1)),
|
||
"usd": 0.0}
|
||
return out
|
||
|
||
|
||
def _htx_spot() -> dict:
|
||
out = {}
|
||
for s in arb._get("https://api.huobi.pro/v1/settings/common/market-symbols")["data"]:
|
||
if s.get("qc") != "usdt" or s.get("state") != "online":
|
||
continue
|
||
# market buy: «minov» USDT; the market sale later: «smminoa» coins
|
||
out[s["bc"].upper()] = {"usd": _f(s.get("minov")), "coins": _f(s.get("smminoa") or s.get("minoa"))}
|
||
return out
|
||
|
||
|
||
def _htx_fut() -> dict:
|
||
out = {}
|
||
for c in arb._get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]:
|
||
if not c["contract_code"].endswith("-USDT"):
|
||
continue
|
||
out[c["contract_code"]] = {"coins": _f(c.get("contract_size"), 1) * _units(c["contract_code"][:-5]), "usd": 0.0}
|
||
return out
|
||
|
||
|
||
def _gate_spot() -> dict:
|
||
out = {}
|
||
for s in arb._get("https://api.gateio.ws/api/v4/spot/currency_pairs"):
|
||
if s.get("quote") != "USDT" or s.get("trade_status") not in (None, "tradable"):
|
||
continue
|
||
out[s["base"]] = {"usd": _f(s.get("min_quote_amount")), "coins": _f(s.get("min_base_amount"))}
|
||
return out
|
||
|
||
|
||
def _gate_fut() -> dict:
|
||
out = {}
|
||
for c in arb._get("https://api.gateio.ws/api/v4/futures/usdt/contracts"):
|
||
out[c["name"]] = {"coins": _f(c.get("quanto_multiplier"), 1) * _units(c["name"][:-5])
|
||
* max(1.0, _f(c.get("order_size_min"), 1)), "usd": 0.0}
|
||
return out
|
||
|
||
|
||
LOADERS = {("Bybit", "spot"): lambda: _bybit("spot"), ("Bybit", "fut"): lambda: _bybit("linear"),
|
||
("Binance", "spot"): _binance_spot, ("Binance", "fut"): _binance_fut,
|
||
("MEXC", "spot"): _mexc_spot, ("MEXC", "fut"): _mexc_fut,
|
||
("HTX", "spot"): _htx_spot, ("HTX", "fut"): _htx_fut,
|
||
("Gate", "spot"): _gate_spot, ("Gate", "fut"): _gate_fut}
|
||
|
||
|
||
class Rules:
|
||
def __init__(self) -> None:
|
||
self.data: dict[tuple[str, str], dict] = {}
|
||
self.loaded: dict[tuple[str, str], float] = {} # when loaded (or when the last try failed)
|
||
self.loading: set = set()
|
||
self.lock = threading.Lock()
|
||
|
||
def set(self, exchange: str, market: str, rules: dict) -> None:
|
||
with self.lock:
|
||
self.data[(exchange, market)] = rules
|
||
self.loaded[(exchange, market)] = time.time()
|
||
|
||
def _get(self, exchange: str, market: str) -> dict:
|
||
key = (exchange, market)
|
||
if AUTOLOAD and key in LOADERS:
|
||
with self.lock:
|
||
stale = time.time() - self.loaded.get(key, 0.0) > (REFRESH_S if key in self.data else RETRY_S)
|
||
start = stale and key not in self.loading
|
||
if start:
|
||
self.loading.add(key)
|
||
if start:
|
||
threading.Thread(target=self._load, args=(key,), daemon=True).start()
|
||
return self.data.get(key) or {}
|
||
|
||
def _load(self, key) -> None:
|
||
try:
|
||
rules = LOADERS[key]()
|
||
if rules:
|
||
self.set(*key, rules)
|
||
except Exception:
|
||
with self.lock:
|
||
self.loaded[key] = time.time() # tried: again in RETRY_S
|
||
finally:
|
||
with self.lock:
|
||
self.loading.discard(key)
|
||
|
||
def spot(self, exchange: str, base: str) -> dict | None:
|
||
return self._get(exchange, "spot").get(base)
|
||
|
||
def fut(self, exchange: str, symbol: str) -> dict | None:
|
||
return self._get(exchange, "fut").get(symbol)
|
||
|
||
def min_entry(self, spot_ex: str, base: str, spot_ask: float, fut_ex: str, fut_symbol: str, fut_bid: float,
|
||
spot_fee_pct: float) -> dict | None:
|
||
"""The smallest trade amount, $, both legs accept: {"usd": total, "spot": $ the spot leg needs (None:
|
||
unknown), "fut": $ the perp leg needs}; None when neither exchange's rules are known yet."""
|
||
sr, fr = self.spot(spot_ex, base), self.fut(fut_ex, fut_symbol)
|
||
if sr is None and fr is None or spot_ask <= 0 or fut_bid <= 0:
|
||
return None
|
||
keep = 1 - spot_fee_pct / 100 # the buy fee is taken in coins
|
||
spot_usd = None if sr is None else max(sr["usd"], sr["coins"] * spot_ask / keep)
|
||
fut_usd = None
|
||
if fr is not None: # the coins bought must make the perp's smallest order
|
||
coins = max(fr["coins"], fr["usd"] / fut_bid if fr["usd"] else 0.0)
|
||
fut_usd = coins * spot_ask / keep
|
||
need = max(v for v in (spot_usd, fut_usd) if v is not None) * MARGIN
|
||
return {"usd": math.ceil(need * 100) / 100, "spot": spot_usd, "fut": fut_usd}
|
||
|
||
|
||
def min_entry_ss(self, spot_ex: str, base: str, spot_ask: float, sell_ex: str, sell_bid: float,
|
||
spot_fee_pct: float) -> dict | None:
|
||
"""Spot–spot: the buy on A's spot and the sale of the same coins on B's spot must both pass their spot
|
||
minimums ("fut" = what B's sale needs)."""
|
||
ra, rb = self.spot(spot_ex, base), self.spot(sell_ex, base)
|
||
if ra is None and rb is None or spot_ask <= 0 or sell_bid <= 0:
|
||
return None
|
||
keep = 1 - spot_fee_pct / 100
|
||
buy_usd = None if ra is None else max(ra["usd"], ra["coins"] * spot_ask / keep)
|
||
sell_usd = None if rb is None else max(rb["coins"], rb["usd"] / sell_bid if rb["usd"] else 0.0) * spot_ask / keep
|
||
need = max(v for v in (buy_usd, sell_usd) if v is not None) * MARGIN
|
||
return {"usd": math.ceil(need * 100) / 100, "spot": buy_usd, "fut": sell_usd}
|
||
|
||
|
||
RULES = Rules()
|
||
|
||
|
||
def too_small(amount: float, m: dict | None, spot_ex: str, fut_ex: str, b_leg: str = "фьюч") -> str:
|
||
"""Why `amount` cannot enter the trade ("" when it can, or when the rules are not known)."""
|
||
if m is None or amount >= m["usd"]:
|
||
return ""
|
||
parts = ([f"спот {spot_ex} ≥ {m['spot']:.2f} $"] if m["spot"] is not None else []) + \
|
||
([f"{b_leg} {fut_ex} ≥ {m['fut']:.2f} $"] if m["fut"] is not None else [])
|
||
return f"сумма {amount:g} $ меньше мин. входа {m['usd']:.2f} $ ({', '.join(parts)})"
|