Files
Crypto_Scam/live.py
T

1454 lines
79 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Real orders on the exchanges (signed REST): balances, market orders on spot and on USDT perpetuals.
Every client speaks in coins and per-coin prices, whatever the exchange's own units are (1000PEPE units on Bybit /
Binance, contracts on MEXC / HTX / Gate); quantities are rounded down to the exchange's lot step.
spot_buy(base, usdt) market buy for a USDT amount
spot_sell(base, coins) market sell
spot_free(base) coins available on the spot / unified account
fut_order(symbol, side, coins, reduce_only) market order on the perpetual ("buy" / "sell")
fut_round(symbol, coins) the coins an order can actually have (lot step)
balances() USDT on spot and futures, for the «Проверить» button
Errors from the exchange are raised as LiveError with the exchange's own message.
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import http.client
import json
import math
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from datetime import datetime, timezone
from arb import split_base
TIMEOUT = 15
class LiveError(Exception):
"""sent=True: the order may have reached the exchange (no answer, or its fill could not be confirmed) —
the caller must treat the position as possibly open and close it later; sent=False: certainly not placed."""
def __init__(self, message: str, sent: bool = False, order_id: str = "") -> None:
super().__init__(message)
self.sent, self.order_id = sent, order_id
class CircuitBreaker(LiveError):
"""The exchange cancelled a market order unfilled to protect it from a wide spread (HTX 410): nothing was
traded — the same order can go as a limit at the book's price."""
def _unsent(fn):
"""Run the preparation of an order (rules, rounding): any failure there means nothing was sent."""
try:
return fn()
except LiveError as exc:
raise LiveError(str(exc), sent=False) from None
def _placed(order_id: str, fn):
"""Confirm the fill of an order the exchange has accepted: a failure here leaves the order possibly filled."""
try:
return fn()
except LiveError as exc:
raise LiveError(f"ордер {order_id} принят биржей, но исполнение не подтверждено: {exc}", sent=True,
order_id=order_id) from None
@dataclass
class Fill:
coins: float # filled, in coins
price: float # average per coin
fee_usd: float # fee in $ as charged by the exchange (estimated from the taker rate only if exact=False)
order_id: str
raw: dict = field(default_factory=dict, repr=False)
exact: bool = True # price and fee are the exchange's own figures
tpsl: str = "" # opening order: "на бирже" — TP/SL set on the exchange; otherwise why not
def _floor(value: float, step: float) -> float:
if step <= 0:
return value
n = math.floor(value / step + 1e-9)
decimals = max(0, -int(math.floor(math.log10(step)))) if step < 1 else 0
return round(n * step, decimals + 2)
def _tick(price: float, tick: float) -> float:
"""Price rounded to the exchange's price step."""
if tick <= 0:
return price
decimals = max(0, -int(math.floor(math.log10(tick)))) if tick < 1 else 0
return round(round(price / tick) * tick, decimals + 2)
def _liq(rows: list, key: str, units: float, size) -> float | None:
"""Liquidation price per coin from the exchange's position rows (the first row with a size); None when there
is no position or the exchange reports none (0 / empty: e.g. too much margin to ever be liquidated)."""
for r in rows or []:
if not isinstance(r, dict) or size(r) <= 0:
continue
try:
v = float(r.get(key) or 0)
except (TypeError, ValueError):
return None
return v / units if v > 0 else None
return None
def _num(text: float) -> str:
"""A number for an order: its shortest exact decimal form, never an exponent. (12 fixed decimals printed the
float's noise on large amounts: 27481.05 → «27481.049999999999», refused by MEXC as a wrong quantity scale.)"""
from decimal import Decimal
s = format(Decimal(repr(round(float(text), 12))), "f") # 0.1 + 0.2 → «0.3», not «0.30000000000000004»
return s.rstrip("0").rstrip(".") if "." in s else s
# --- persistent connections ----------------------------------------------------------------------------------
# A new HTTPS connection costs a TCP + TLS handshake (~70 ms more per order through the VPN, measured to MEXC);
# connections are kept open per host and reused, and warm_up() keeps one per exchange alive between orders.
IDLE_S = 15.0 # a connection idle longer than this is not reused (servers drop idle keep-alive ones)
_pool: dict[tuple[str, str], list[tuple[http.client.HTTPConnection, float]]] = {}
_pool_lock = threading.Lock()
def _take(scheme: str, host: str) -> tuple[http.client.HTTPConnection, bool]:
"""(connection, reused) — an idle open connection to the host, or a new one."""
now = time.monotonic()
with _pool_lock:
idle = _pool.get((scheme, host), [])
while idle:
conn, last = idle.pop()
if now - last < IDLE_S:
return conn, True
conn.close()
cls = http.client.HTTPSConnection if scheme == "https" else http.client.HTTPConnection
return cls(host, timeout=TIMEOUT), False
def _give_back(scheme: str, host: str, conn: http.client.HTTPConnection) -> None:
with _pool_lock:
idle = _pool.setdefault((scheme, host), [])
if len(idle) < 4:
idle.append((conn, time.monotonic()))
return
conn.close()
def _http(method: str, url: str, headers: dict | None = None, body: bytes | None = None) -> dict | list:
parts = urllib.parse.urlsplit(url)
target = parts.path + (f"?{parts.query}" if parts.query else "")
hdrs = {"User-Agent": "Mozilla/5.0", "Connection": "keep-alive", **(headers or {})}
for attempt in (1, 2):
conn, reused = _take(parts.scheme, parts.netloc)
try:
conn.request(method, target, body=body, headers=hdrs)
resp = conn.getresponse()
data = resp.read()
except (http.client.HTTPException, OSError) as exc:
conn.close()
# a reused connection the server had already closed: a read is simply repeated on a new one
if reused and method == "GET" and attempt == 1:
continue
# no answer: a POST may still have been executed by the exchange
raise LiveError(f"нет связи: {exc}", sent=method in ("POST", "DELETE")) from None
if resp.getheader("Connection", "").lower() == "close" or resp.will_close:
conn.close()
else:
_give_back(parts.scheme, parts.netloc, conn)
if resp.status >= 400:
raise LiveError(f"HTTP {resp.status}: {data.decode('utf-8', 'replace')[:300]}",
sent=method in ("POST", "DELETE") and resp.status >= 500)
try:
return json.loads(data or b"{}")
except (ValueError, UnicodeDecodeError) as exc:
raise LiveError(f"не удалось прочитать ответ биржи: {exc}",
sent=method in ("POST", "DELETE")) from None
raise LiveError("нет связи")
WARM_URLS = {"bybit": ["https://api.bybit.com/v5/market/time"],
"binance": ["https://fapi.binance.com/fapi/v1/ping", "https://api.binance.com/api/v3/ping"],
"mexc": ["https://contract.mexc.com/api/v1/contract/ping", "https://api.mexc.com/api/v3/ping"],
"htx": ["https://api.hbdm.com/api/v1/timestamp", "https://api.huobi.pro/v1/common/timestamp"],
"gate": ["https://api.gateio.ws/api/v4/spot/time"]}
def warm_up(exchanges) -> dict[str, float]:
"""One cheap public request per API host of these exchanges, so an open connection is waiting for the next
order; returns the round trip per host in ms (shown on the page)."""
out = {}
for ex in exchanges:
for url in WARM_URLS.get(ex, []):
t = time.perf_counter()
try:
_http("GET", url)
out[urllib.parse.urlsplit(url).netloc] = (time.perf_counter() - t) * 1000
except LiveError:
pass
return out
def _units(symbol_base: str) -> float:
"""Coins in one unit of the symbol: 1000PEPE → 1000."""
return split_base(symbol_base)[1]
# --------------------------------------------------------------------------------------------------------------
class Bybit:
name, host = "Bybit", "https://api.bybit.com"
spot_fee, fut_fee = 0.1, 0.055
def __init__(self, key: str, secret: str) -> None:
self.key, self.secret = key, secret
self.rules: dict[str, dict] = {}
def _call(self, method: str, path: str, params: dict | None = None) -> dict:
ts, recv = str(int(time.time() * 1000)), "10000"
if method == "GET":
query = urllib.parse.urlencode(params or {})
payload, url, body = ts + self.key + recv + query, f"{self.host}{path}?{query}", None
else:
text = json.dumps(params or {})
payload, url, body = ts + self.key + recv + text, self.host + path, text.encode()
sign = hmac.new(self.secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
d = _http(method, url, {"X-BAPI-API-KEY": self.key, "X-BAPI-TIMESTAMP": ts, "X-BAPI-RECV-WINDOW": recv,
"X-BAPI-SIGN": sign, "Content-Type": "application/json"}, body)
if d.get("retCode") != 0:
raise LiveError(f"Bybit {d.get('retCode')}: {d.get('retMsg')}")
return d["result"]
def _rule(self, category: str, symbol: str) -> dict:
k = f"{category}:{symbol}"
if k not in self.rules:
items = _http("GET", f"{self.host}/v5/market/instruments-info?category={category}&symbol={symbol}")
items = items.get("result", {}).get("list") or []
if not items:
raise LiveError(f"Bybit: нет инструмента {symbol}")
lot = items[0]["lotSizeFilter"]
self.rules[k] = {"step": float(lot.get("qtyStep") or lot.get("basePrecision") or 0),
"min": float(lot.get("minOrderQty") or 0),
"tick": float((items[0].get("priceFilter") or {}).get("tickSize") or 0)}
return self.rules[k]
def _fill(self, category: str, order_id: str) -> dict:
for attempt in range(10):
for path in ("/v5/order/realtime", "/v5/order/history"):
items = self._call("GET", path, {"category": category, "orderId": order_id}).get("list") or []
if items and items[0].get("orderStatus") in ("Filled", "PartiallyFilledCanceled", "Cancelled",
"Rejected", "Deactivated"):
return items[0]
time.sleep(0.3)
raise LiveError(f"Bybit: ордер {order_id} не исполнился за 3 с")
# The perp account's position mode: one-way (positionIdx 0) or hedge (1 = the long side, 2 = the short side).
# Learned from the exchange: an order with the wrong index is refused (10001 «position idx not match position
# mode») — nothing was placed, so it is sent once more with the other mode's index.
hedge = False
def _idx(self, side: str, reduce_only: bool) -> int:
if not self.hedge:
return 0
short = (side == "Sell") != bool(reduce_only) # a sale opens a short, a reduce-only buy closes one
return 2 if short else 1
def _create(self, params: dict) -> dict:
if params.get("category") == "linear":
params["positionIdx"] = self._idx(params["side"], params.get("reduceOnly", False))
try:
return self._call("POST", "/v5/order/create", params)
except LiveError as exc:
if params.get("category") != "linear" or "10001" not in str(exc) or "position idx" not in str(exc).lower():
raise
self.hedge = not self.hedge
params["positionIdx"] = self._idx(params["side"], params.get("reduceOnly", False))
return self._call("POST", "/v5/order/create", params)
def _order(self, category: str, params: dict, fee_rate: float, mult: float = 1.0) -> Fill:
oid = self._create({"category": category, "orderType": "Market", **params})["orderId"]
o = _placed(oid, lambda: self._fill(category, oid))
units, value = float(o.get("cumExecQty") or 0), float(o.get("cumExecValue") or 0)
if units <= 0:
raise LiveError(f"Bybit: ордер не исполнен ({o.get('orderStatus')})")
coins = units * mult
fee = float(o.get("cumExecFee") or 0)
fee_usd = fee * value / units if category == "spot" and params["side"] == "Buy" else fee # buy fee is in coins
return Fill(coins, value / coins, fee_usd or value * fee_rate / 100, oid, o)
def spot_buy(self, base: str, usdt: float) -> Fill:
return self._order("spot", {"symbol": f"{base}USDT", "side": "Buy", "qty": _num(round(usdt, 2)),
"marketUnit": "quoteCoin"}, self.spot_fee)
def spot_sell(self, base: str, coins: float) -> Fill:
qty = _unsent(lambda: _floor(coins, self._rule("spot", f"{base}USDT")["step"]))
return self._order("spot", {"symbol": f"{base}USDT", "side": "Sell", "qty": _num(qty),
"marketUnit": "baseCoin"}, self.spot_fee)
def spot_coins(self) -> dict[str, float]:
"""Free coins on the spot account, all at once (the stock spot–spot trades sell from)."""
acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})["list"]
return {c["coin"]: float(c.get("walletBalance") or 0) - float(c.get("locked") or 0)
for c in ((acc[0].get("coin") or []) if acc else []) if c.get("coin") != "USDT"}
def spot_free(self, base: str) -> float:
acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": base})["list"]
coins = acc[0].get("coin") or [] if acc else []
return float(coins[0].get("walletBalance") or 0) - float(coins[0].get("locked") or 0) if coins else 0.0
def fut_round(self, symbol: str, coins: float) -> float:
mult = _units(symbol[:-4])
r = self._rule("linear", symbol)
units = _floor(coins / mult, r["step"])
return units * mult if units >= r["min"] else 0.0
def fut_min_coins(self, symbol: str) -> float:
"""The smallest perp order, in coins."""
r = self._rule("linear", symbol)
return max(r["min"], r["step"]) * _units(symbol[:-4])
def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None,
sl: float | None = None) -> Fill:
"""tp / sl (per coin): take-profit and stop-loss of the whole position, kept by the exchange itself and
executed at market when the last price reaches them (removed by Bybit when the position closes)."""
mult = _units(symbol[:-4])
rule = _unsent(lambda: self._rule("linear", symbol))
units = _floor(coins / mult, rule["step"])
if units <= 0:
raise LiveError("Bybit: количество меньше шага лота")
params = {"symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "qty": _num(units),
"reduceOnly": reduce_only}
if not reduce_only and (tp or sl):
params["tpslMode"] = "Full"
if tp:
params.update(takeProfit=_num(_tick(tp * mult, rule["tick"])), tpTriggerBy="LastPrice")
if sl:
params.update(stopLoss=_num(_tick(sl * mult, rule["tick"])), slTriggerBy="LastPrice")
fill = self._order("linear", params, self.fut_fee, mult)
if not reduce_only and (tp or sl):
fill.tpsl = "на бирже"
return fill
def fut_position(self, symbol: str) -> float:
"""Coins of the open perp position on the exchange: + long, − short, 0 none."""
items = self._call("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}).get("list") or []
mult = _units(symbol[:-4])
return sum(float(i.get("size") or 0) * mult * (1 if i.get("side") == "Buy" else -1) for i in items)
def fut_liq_price(self, symbol: str) -> float | None:
"""The exchange's liquidation price of the open position, per coin (None: no position / not reported)."""
items = self._call("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}).get("list") or []
return _liq(items, "liqPrice", _units(symbol[:-4]), lambda i: float(i.get("size") or 0))
def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]:
"""Fills on `side` ("buy" / "sell") of the symbol since `since` (unix s): how the exchange closed it."""
items = self._call("GET", "/v5/execution/list", {"category": "linear", "symbol": symbol, "limit": 100,
"startTime": int(since * 1000)}).get("list") or []
mult, want = _units(symbol[:-4]), "Buy" if side == "buy" else "Sell"
return [Fill(float(e["execQty"]) * mult, float(e["execPrice"]) / mult, float(e.get("execFee") or 0),
e.get("orderId", "")) for e in items if e.get("side") == want and e.get("execType", "Trade") == "Trade"]
def fut_cancel_all(self, symbol: str) -> None:
self._call("POST", "/v5/order/cancel-all", {"category": "linear", "symbol": symbol})
def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str:
"""Reduce-only LIMIT order closing the position at `price` (per coin) or better; `side` closes it."""
mult = _units(symbol[:-4])
rule = self._rule("linear", symbol)
return self._create({
"category": "linear", "symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "orderType": "Limit",
"qty": _num(_floor(coins / mult, rule["step"])), "price": _num(_tick(price * mult, rule["tick"])),
"timeInForce": "GTC", "reduceOnly": True})["orderId"]
# --- resting limit orders on the perp: placed, watched, cancelled ---------------------------------------
def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str:
mult = _units(symbol[:-4])
rule = _unsent(lambda: self._rule("linear", symbol))
units = _floor(coins / mult, rule["step"])
if units <= 0:
raise LiveError("Bybit: количество меньше шага лота")
return self._create({
"category": "linear", "symbol": symbol, "side": "Buy" if side == "buy" else "Sell", "orderType": "Limit",
"qty": _num(units), "price": _num(_tick(price * mult, rule["tick"])), "timeInForce": "GTC",
"reduceOnly": reduce_only})["orderId"]
def fut_order_status(self, symbol: str, order_id: str) -> dict:
"""{"coins": filled, "price": average per coin, "fee": $, "final": no longer working}."""
mult = _units(symbol[:-4])
for path in ("/v5/order/realtime", "/v5/order/history"):
items = self._call("GET", path, {"category": "linear", "symbol": symbol, "orderId": order_id}).get("list") or []
if items:
o = items[0]
units, value = float(o.get("cumExecQty") or 0), float(o.get("cumExecValue") or 0)
return {"coins": units * mult, "price": value / (units * mult) if units else 0.0,
"fee": float(o.get("cumExecFee") or 0),
"final": o.get("orderStatus") not in ("New", "PartiallyFilled", "Untriggered")}
raise LiveError(f"Bybit: ордер {order_id} не найден")
def fut_cancel(self, symbol: str, order_id: str) -> None:
self._call("POST", "/v5/order/cancel", {"category": "linear", "symbol": symbol, "orderId": order_id})
def fut_fills(self, symbol: str, since: float) -> list[dict]:
"""Every fill of the symbol since `since` as the exchange recorded it (for trades and statistics)."""
mult, out, cursor = _units(symbol[:-4]), [], ""
for _ in range(10):
params = {"category": "linear", "symbol": symbol, "limit": 100, "startTime": int(since * 1000)}
if cursor:
params["cursor"] = cursor
res = self._call("GET", "/v5/execution/list", params)
for e in res.get("list") or []:
if e.get("execType", "Trade") != "Trade":
continue
out.append({"time": int(e["execTime"]) / 1000, "side": "buy" if e["side"] == "Buy" else "sell",
"coins": float(e["execQty"]) * mult, "price": float(e["execPrice"]) / mult,
"fee": float(e.get("execFee") or 0), "pnl": None, "order": e.get("orderId", ""),
"close": float(e.get("closedSize") or 0) > 0})
cursor = res.get("nextPageCursor") or ""
if not cursor:
break
return sorted(out, key=lambda f: f["time"])
def balances(self) -> dict:
acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"})["list"]
coin = (acc[0].get("coin") or [{}])[0] if acc else {}
usdt = float(coin.get("equity") or coin.get("walletBalance") or 0) # incl. unrealized result
return {"Единый счёт USDT": usdt}
unified = True # one account for spot and perps: nothing to move between them
def usdt_free(self) -> dict:
acc = self._call("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"})["list"]
coin = (acc[0].get("coin") or [{}])[0] if acc else {}
free = float(coin.get("walletBalance") or 0) - float(coin.get("locked") or 0) - float(coin.get("totalPositionIM") or 0)
return {"spot": free, "futures": free}
def transfer_usdt(self, to: str, amount: float) -> None:
raise LiveError("Bybit: единый счёт — перевод не нужен")
# --------------------------------------------------------------------------------------------------------------
class _BinanceLike:
"""Binance spot / USDⓈ-M futures and MEXC spot share the signing scheme: HMAC-SHA256 of the query string."""
name = ""
key_header = "X-MBX-APIKEY"
def __init__(self, key: str, secret: str) -> None:
self.key, self.secret = key, secret
self.rules: dict[str, dict] = {}
def _signed(self, method: str, url: str, params: dict | None = None) -> dict | list:
q = dict(params or {})
q["timestamp"] = int(time.time() * 1000)
q["recvWindow"] = 10000
query = urllib.parse.urlencode(q)
query += "&signature=" + hmac.new(self.secret.encode(), query.encode(), hashlib.sha256).hexdigest()
return _http(method, f"{url}?{query}", {self.key_header: self.key})
class Binance(_BinanceLike):
name = "Binance"
spot_fee, fut_fee = 0.1, 0.05
SPOT, FUT = "https://api.binance.com", "https://fapi.binance.com"
def _rule(self, market: str, symbol: str) -> dict:
k = f"{market}:{symbol}"
if k not in self.rules:
url = f"{self.SPOT}/api/v3/exchangeInfo?symbol={symbol}" if market == "spot" else f"{self.FUT}/fapi/v1/exchangeInfo"
info = next((s for s in _http("GET", url)["symbols"] if s["symbol"] == symbol), None)
if info is None:
raise LiveError(f"Binance: нет инструмента {symbol}")
f = {x["filterType"]: x for x in info["filters"]}
lot = f.get("MARKET_LOT_SIZE") if float((f.get("MARKET_LOT_SIZE") or {}).get("stepSize") or 0) > 0 else f["LOT_SIZE"]
self.rules[k] = {"step": float(lot["stepSize"]), "min": float(lot["minQty"]),
"tick": float((f.get("PRICE_FILTER") or {}).get("tickSize") or 0)}
return self.rules[k]
def spot_buy(self, base: str, usdt: float) -> Fill:
o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"symbol": f"{base}USDT", "side": "BUY", "type": "MARKET",
"quoteOrderQty": _num(round(usdt, 2)),
"newOrderRespType": "FULL"})
return self._spot_fill(o, base)
def spot_sell(self, base: str, coins: float) -> Fill:
qty = _unsent(lambda: _floor(coins, self._rule("spot", f"{base}USDT")["step"]))
o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"symbol": f"{base}USDT", "side": "SELL", "type": "MARKET",
"quantity": _num(qty), "newOrderRespType": "FULL"})
return self._spot_fill(o, base)
def _spot_fill(self, o: dict, base: str) -> Fill:
qty, quote = float(o.get("executedQty") or 0), float(o.get("cummulativeQuoteQty") or 0)
if qty <= 0:
raise LiveError(f"Binance: ордер не исполнен ({o.get('status')})")
price = quote / qty
fee = 0.0
for f in o.get("fills") or []:
c, asset = float(f.get("commission") or 0), f.get("commissionAsset")
fee += c if asset == "USDT" else c * price if asset == base else quote * self.spot_fee / 100 / max(1, len(o["fills"]))
return Fill(qty, price, fee, str(o.get("orderId")), o)
def spot_coins(self) -> dict[str, float]:
return {b["asset"]: float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account",
{"omitZeroBalances": "true"})["balances"]
if b["asset"] != "USDT" and float(b["free"]) > 0}
def spot_free(self, base: str) -> float:
for b in self._signed("GET", f"{self.SPOT}/api/v3/account", {"omitZeroBalances": "true"})["balances"]:
if b["asset"] == base:
return float(b["free"])
return 0.0
def fut_round(self, symbol: str, coins: float) -> float:
mult = _units(symbol[:-4])
r = self._rule("fut", symbol)
units = _floor(coins / mult, r["step"])
return units * mult if units >= r["min"] else 0.0
def fut_min_coins(self, symbol: str) -> float:
r = self._rule("fut", symbol)
return max(r["min"], r["step"]) * _units(symbol[:-4])
def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None,
sl: float | None = None) -> Fill:
fill = self._fut_market(symbol, side, coins, reduce_only)
if not reduce_only and (tp or sl):
# Binance has no TP/SL on a market order: two conditional orders that close the whole position
mult, tick = _units(symbol[:-4]), self._rule("fut", symbol)["tick"]
close_side = "SELL" if side == "buy" else "BUY"
problems = []
for kind, price in (("TAKE_PROFIT_MARKET", tp), ("STOP_MARKET", sl)):
if not price:
continue
try:
self._signed("POST", f"{self.FUT}/fapi/v1/order", {
"symbol": symbol, "side": close_side, "type": kind, "stopPrice": _num(_tick(price * mult, tick)),
"closePosition": "true", "workingType": "CONTRACT_PRICE"})
except LiveError as exc:
problems.append(f"{'TP' if kind.startswith('TAKE') else 'SL'}: {exc}")
fill.tpsl = "; ".join(problems) if problems else "на бирже"
return fill
def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]:
rows = self._signed("GET", f"{self.FUT}/fapi/v1/userTrades", {"symbol": symbol, "startTime": int(since * 1000)})
mult = _units(symbol[:-4])
return [Fill(float(t["qty"]) * mult, float(t["price"]) / mult, float(t.get("commission") or 0),
str(t.get("orderId", ""))) for t in rows if t.get("side") == side.upper()]
def fut_cancel_all(self, symbol: str) -> None:
self._signed("DELETE", f"{self.FUT}/fapi/v1/allOpenOrders", {"symbol": symbol})
def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str:
mult = _units(symbol[:-4])
rule = self._rule("fut", symbol)
o = self._signed("POST", f"{self.FUT}/fapi/v1/order", {
"symbol": symbol, "side": side.upper(), "type": "LIMIT", "timeInForce": "GTC", "reduceOnly": "true",
"quantity": _num(_floor(coins / mult, rule["step"])), "price": _num(_tick(price * mult, rule["tick"]))})
return str(o.get("orderId"))
def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str:
mult = _units(symbol[:-4])
rule = _unsent(lambda: self._rule("fut", symbol))
units = _floor(coins / mult, rule["step"])
if units <= 0:
raise LiveError("Binance: количество меньше шага лота")
params = {"symbol": symbol, "side": side.upper(), "type": "LIMIT", "timeInForce": "GTC",
"quantity": _num(units), "price": _num(_tick(price * mult, rule["tick"]))}
if reduce_only:
params["reduceOnly"] = "true"
return str(self._signed("POST", f"{self.FUT}/fapi/v1/order", params).get("orderId"))
def fut_order_status(self, symbol: str, order_id: str) -> dict:
o = self._signed("GET", f"{self.FUT}/fapi/v1/order", {"symbol": symbol, "orderId": order_id})
mult = _units(symbol[:-4])
units, quote = float(o.get("executedQty") or 0), float(o.get("cumQuote") or 0)
return {"coins": units * mult, "price": quote / (units * mult) if units else 0.0,
"fee": quote * self.fut_fee / 100, "final": o.get("status") not in ("NEW", "PARTIALLY_FILLED")}
def fut_cancel(self, symbol: str, order_id: str) -> None:
self._signed("DELETE", f"{self.FUT}/fapi/v1/order", {"symbol": symbol, "orderId": order_id})
def fut_fills(self, symbol: str, since: float) -> list[dict]:
rows = self._signed("GET", f"{self.FUT}/fapi/v1/userTrades",
{"symbol": symbol, "startTime": int(since * 1000), "limit": 1000})
mult = _units(symbol[:-4])
return sorted(({"time": t["time"] / 1000, "side": t["side"].lower(), "coins": float(t["qty"]) * mult,
"price": float(t["price"]) / mult, "fee": float(t.get("commission") or 0),
"pnl": float(t.get("realizedPnl") or 0), "order": str(t.get("orderId", "")),
"close": float(t.get("realizedPnl") or 0) != 0}
for t in rows), key=lambda f: f["time"])
def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill:
mult = _units(symbol[:-4])
units = _unsent(lambda: _floor(coins / mult, self._rule("fut", symbol)["step"]))
if units <= 0:
raise LiveError("Binance: количество меньше шага лота")
params = {"symbol": symbol, "side": side.upper(), "type": "MARKET", "quantity": _num(units),
"newOrderRespType": "RESULT"}
if reduce_only:
params["reduceOnly"] = "true"
o = self._signed("POST", f"{self.FUT}/fapi/v1/order", params)
units_done, quote = float(o.get("executedQty") or 0), float(o.get("cumQuote") or 0)
if units_done <= 0:
raise LiveError(f"Binance: ордер не исполнен ({o.get('status')})")
coins_done = units_done * mult
# no extra request for the fee: the estimate is replaced by the charged one at the next history sync
return Fill(coins_done, quote / coins_done, quote * self.fut_fee / 100, str(o.get("orderId")), o, False)
def fut_position(self, symbol: str) -> float:
rows = self._signed("GET", f"{self.FUT}/fapi/v2/positionRisk", {"symbol": symbol})
return sum(float(r.get("positionAmt") or 0) for r in rows) * _units(symbol[:-4])
def fut_liq_price(self, symbol: str) -> float | None:
rows = self._signed("GET", f"{self.FUT}/fapi/v2/positionRisk", {"symbol": symbol})
return _liq(rows, "liquidationPrice", _units(symbol[:-4]), lambda r: abs(float(r.get("positionAmt") or 0)))
def balances(self) -> dict:
spot = next((float(b["free"]) + float(b.get("locked") or 0) # incl. USDT held by open orders
for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] if b["asset"] == "USDT"), 0.0)
fut = next((float(b.get("balance") or 0) + float(b.get("crossUnPnl") or 0)
for b in self._signed("GET", f"{self.FUT}/fapi/v2/balance")
if b["asset"] == "USDT"), 0.0)
return {"Спот USDT": spot, "Фьючерсы USDT": fut}
unified = False
def usdt_free(self) -> dict:
spot = next((float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"]
if b["asset"] == "USDT"), 0.0)
fut = next((float(b.get("availableBalance") or 0) for b in self._signed("GET", f"{self.FUT}/fapi/v2/balance")
if b["asset"] == "USDT"), 0.0)
return {"spot": spot, "futures": fut}
def transfer_usdt(self, to: str, amount: float) -> None:
"""Between the spot (MAIN) and USDⓈ-M futures accounts; the key needs «Permits Universal Transfer»."""
self._signed("POST", f"{self.SPOT}/sapi/v1/asset/transfer", {
"type": "MAIN_UMFUTURE" if to == "futures" else "UMFUTURE_MAIN", "asset": "USDT", "amount": _num(amount)})
# --------------------------------------------------------------------------------------------------------------
def mexc_order_id(data) -> str:
"""MEXC futures answer a submit with the id itself or with {"orderId": "...", "ts": ...} (the newer form)."""
if isinstance(data, dict):
data = data.get("orderId") or data.get("order_id")
if not data:
raise LiveError("MEXC: биржа не вернула номер ордера", sent=True)
return str(data)
class Mexc(_BinanceLike):
name = "MEXC"
key_header = "X-MEXC-APIKEY"
spot_fee, fut_fee = 0.05, 0.02
SPOT, FUT = "https://api.mexc.com", "https://contract.mexc.com"
def _spot_rule(self, symbol: str) -> dict:
if symbol not in self.rules:
info = (_http("GET", f"{self.SPOT}/api/v3/exchangeInfo?symbol={symbol}").get("symbols") or [None])[0]
if info is None:
raise LiveError(f"MEXC: нет пары {symbol}")
self.rules[symbol] = {"step": 10 ** -int(info.get("baseAssetPrecision") or 2)}
return self.rules[symbol]
def _spot_order(self, params: dict, base: str) -> Fill:
o = self._signed("POST", f"{self.SPOT}/api/v3/order", {"type": "MARKET", **params})
oid = str(o.get("orderId"))
def poll():
for _ in range(10):
d = self._signed("GET", f"{self.SPOT}/api/v3/order", {"symbol": params["symbol"], "orderId": oid})
if d.get("status") in ("FILLED", "CANCELED", "PARTIALLY_CANCELED", "REJECTED"):
return d
time.sleep(0.3)
raise LiveError("ордер не исполнился за 3 с")
d = _placed(oid, poll)
qty, quote = float(d.get("executedQty") or 0), float(d.get("cummulativeQuoteQty") or 0)
if qty <= 0:
raise LiveError(f"MEXC: ордер не исполнен ({d.get('status')})")
price = quote / qty
fee, exact = quote * self.spot_fee / 100, False
try: # commission actually charged, from the order's trades
trades = self._signed("GET", f"{self.SPOT}/api/v3/myTrades", {"symbol": params["symbol"], "orderId": oid})
if isinstance(trades, list) and trades:
fee, exact = 0.0, True
for t in trades:
c, asset = float(t.get("commission") or 0), t.get("commissionAsset")
fee += c if asset == "USDT" else c * price if asset == base else 0.0
except LiveError:
pass
return Fill(qty, price, fee, oid, d, exact)
def spot_buy(self, base: str, usdt: float) -> Fill:
return self._spot_order({"symbol": f"{base}USDT", "side": "BUY", "quoteOrderQty": _num(round(usdt, 2))}, base)
def spot_sell(self, base: str, coins: float) -> Fill:
symbol = f"{base}USDT"
rule = _unsent(lambda: self._spot_rule(symbol))
while True:
qty = _floor(coins, rule["step"])
try:
return self._spot_order({"symbol": symbol, "side": "SELL", "quantity": _num(qty)}, base)
except LiveError as exc:
# MEXC's exchangeInfo does not always tell the real quantity step (SUE: 2 decimals listed, refused
# with 400 «quantity scale is invalid»): the order was not taken — one decimal fewer, remembered
if "scale is invalid" not in str(exc) or getattr(exc, "sent", False) or rule["step"] >= 1:
raise
rule["step"] = min(1.0, rule["step"] * 10)
def spot_coins(self) -> dict[str, float]:
return {b["asset"]: float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"]
if b["asset"] != "USDT" and float(b["free"]) > 0}
def spot_free(self, base: str) -> float:
for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"]:
if b["asset"] == base:
return float(b["free"])
return 0.0
# futures: contract.mexc.com, signature = HMAC-SHA256(key + time + params); order placing through the API is
# closed for most accounts by MEXC itself — the exchange's refusal is shown as is
def _fut(self, method: str, path: str, params: dict | None = None) -> dict:
# MEXC answers reads now and then with 513 «try again later»: a read is simply repeated (never an order)
for attempt in range(3):
try:
return self._fut_once(method, path, params)
except LiveError as exc:
if method != "GET" or "513" not in str(exc) or attempt == 2:
raise
time.sleep(0.4 * (attempt + 1))
def _fut_once(self, method: str, path: str, params: dict | None = None) -> dict:
ts = str(int(time.time() * 1000))
if method == "GET":
query = urllib.parse.urlencode(sorted((params or {}).items()))
text, url, body = query, f"{self.FUT}{path}" + (f"?{query}" if query else ""), None
else:
text = json.dumps(params or {})
url, body = self.FUT + path, text.encode()
sign = hmac.new(self.secret.encode(), (self.key + ts + text).encode(), hashlib.sha256).hexdigest()
d = _http(method, url, {"ApiKey": self.key, "Request-Time": ts, "Signature": sign,
"Content-Type": "application/json"}, body)
if not d.get("success"):
raise LiveError(f"MEXC фьючерсы {d.get('code')}: {d.get('message')}")
return d.get("data")
def _contract(self, symbol: str) -> dict:
k = f"fut:{symbol}"
if k not in self.rules:
d = _http("GET", f"{self.FUT}/api/v1/contract/detail?symbol={symbol}").get("data") or {}
if not d:
raise LiveError(f"MEXC: нет контракта {symbol}")
self.rules[k] = {"size": float(d["contractSize"]) * _units(symbol[:-5]), "min": float(d.get("minVol") or 1),
"tick": float(d.get("priceUnit") or 0)}
return self.rules[k]
def fut_round(self, symbol: str, coins: float) -> float:
c = self._contract(symbol)
vol = math.floor(coins / c["size"] + 1e-9)
return vol * c["size"] if vol >= c["min"] else 0.0
def fut_min_coins(self, symbol: str) -> float:
c = self._contract(symbol)
return c["size"] * max(1.0, c["min"])
def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None,
sl: float | None = None) -> Fill:
c = _unsent(lambda: self._contract(symbol))
vol = math.floor(coins / c["size"] + 1e-9)
if vol <= 0:
raise LiveError("MEXC: количество меньше одного контракта")
# side: 1 open long, 2 close short, 3 open short, 4 close long; type 5 = market; openType 2 = cross
code = (2 if side == "buy" else 4) if reduce_only else (1 if side == "buy" else 3)
params = {"symbol": symbol, "vol": vol, "side": code, "type": 5, "openType": 2}
units = _units(symbol[:-5])
if not reduce_only: # TP / SL attached to the opening order, kept by MEXC
if tp:
params["takeProfitPrice"] = _tick(tp * units, c["tick"])
if sl:
params["stopLossPrice"] = _tick(sl * units, c["tick"])
oid = mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", params))
def check():
# ONE look at the order (a market order is filled by now): MEXC limits private requests, a series of
# polls ran into «510 too frequent»; if it is not confirmed, the caller checks the position instead
time.sleep(0.15)
o = self._fut("GET", f"/api/v1/private/order/get/{oid}")
if float(o.get("dealVol") or 0) > 0 and o.get("state") in (3, 4):
return o
raise LiveError(f"исполнение ещё не видно (state {o.get('state')})")
o = _placed(oid, check)
coins_done = float(o.get("dealVol") or 0) * c["size"]
if coins_done <= 0:
raise LiveError("MEXC: фьючерсный ордер не исполнен")
price = float(o.get("dealAvgPrice") or 0) / _units(symbol[:-5])
charged = [o.get(k) for k in ("takerFee", "makerFee") if o.get(k) not in (None, "")]
tpsl = "на бирже" if not reduce_only and ("takeProfitPrice" in params or "stopLossPrice" in params) else ""
if charged:
return Fill(coins_done, price, sum(abs(float(x)) for x in charged), oid, o, tpsl=tpsl)
return Fill(coins_done, price, coins_done * price * self.fut_fee / 100, oid, o, False, tpsl)
def fut_closes(self, symbol: str, side: str, since: float) -> list[Fill]:
"""Closing orders (side 4 closes a long by selling, 2 closes a short by buying) since `since`."""
size, units = self._contract(symbol)["size"], _units(symbol[:-5])
want = 2 if side == "buy" else 4
d = self._fut("GET", "/api/v1/private/order/list/history_orders",
{"symbol": symbol, "start_time": int(since * 1000), "page_num": 1, "page_size": 50}) or []
rows = d if isinstance(d, list) else d.get("resultList") or []
out = []
for o in rows:
if o.get("side") == want and float(o.get("dealVol") or 0) > 0:
fee = sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee"))
out.append(Fill(float(o["dealVol"]) * size, float(o.get("dealAvgPrice") or 0) / units, fee,
str(o.get("orderId", ""))))
return out
def fut_cancel_all(self, symbol: str) -> None:
"""Every open order of the symbol: limit orders (the TP) and the TP/SL plans."""
problems = []
for path in ("/api/v1/private/order/cancel_all", "/api/v1/private/stoporder/cancel_all"):
try:
self._fut("POST", path, {"symbol": symbol})
except LiveError as exc:
problems.append(str(exc))
if len(problems) == 2:
raise LiveError("; ".join(problems))
def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str:
"""Reduce-only limit close: side 2 closes a short (buy), 4 closes a long (sell); type 1 = limit."""
c = self._contract(symbol)
vol = math.floor(coins / c["size"] + 1e-9)
return mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", {
"symbol": symbol, "vol": vol, "side": 2 if side == "buy" else 4, "type": 1, "openType": 2,
"price": _tick(price * _units(symbol[:-5]), c["tick"])}))
def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str:
"""Resting limit order (type 1): opens (1 long / 3 short) or, reduce-only, closes (2 short / 4 long)."""
c = _unsent(lambda: self._contract(symbol))
vol = math.floor(coins / c["size"] + 1e-9)
if vol <= 0:
raise LiveError("MEXC: количество меньше одного контракта")
code = (2 if side == "buy" else 4) if reduce_only else (1 if side == "buy" else 3)
return mexc_order_id(self._fut("POST", "/api/v1/private/order/submit", {
"symbol": symbol, "vol": vol, "side": code, "type": 1, "openType": 2,
"price": _tick(price * _units(symbol[:-5]), c["tick"])}))
def fut_order_status(self, symbol: str, order_id: str) -> dict:
c = self._contract(symbol)
o = self._fut("GET", f"/api/v1/private/order/get/{order_id}")
coins = float(o.get("dealVol") or 0) * c["size"]
return {"coins": coins, "price": float(o.get("dealAvgPrice") or 0) / _units(symbol[:-5]),
"fee": sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")),
"final": o.get("state") in (3, 4, 5)} # 1/2 waiting · 3 filled · 4 cancelled · 5 invalid
def fut_cancel(self, symbol: str, order_id: str) -> None:
self._fut("POST", "/api/v1/private/order/cancel", [order_id])
def fut_fills(self, symbol: str, since: float) -> list[dict]:
"""Filled orders of the symbol since `since` (MEXC: per order — side 1/2 buy, 3/4 sell; `profit` is the
realized result of a closing order before fees, as in the exchange's trade history)."""
size, units = self._contract(symbol)["size"], _units(symbol[:-5])
out = []
for page in range(1, 11):
d = self._fut("GET", "/api/v1/private/order/list/history_orders",
{"symbol": symbol, "start_time": int(since * 1000), "page_num": page, "page_size": 100}) or []
rows = d if isinstance(d, list) else d.get("resultList") or []
for o in rows:
vol = float(o.get("dealVol") or 0)
if vol <= 0:
continue
code = o.get("side")
out.append({"time": (o.get("updateTime") or o.get("createTime") or 0) / 1000,
"side": "buy" if code in (1, 2) else "sell", "coins": vol * size,
"price": float(o.get("dealAvgPrice") or 0) / units,
"fee": sum(abs(float(o.get(k) or 0)) for k in ("takerFee", "makerFee")),
"pnl": float(o["profit"]) if code in (2, 4) and o.get("profit") not in (None, "") else None,
"close": code in (2, 4),
"order": str(o.get("orderId", ""))})
if len(rows) < 100:
break
return sorted(out, key=lambda f: f["time"])
def fut_position(self, symbol: str) -> float:
size = self._contract(symbol)["size"]
rows = self._fut("GET", "/api/v1/private/position/open_positions", {"symbol": symbol}) or []
return sum(float(r.get("holdVol") or 0) * size * (1 if r.get("positionType") == 1 else -1) for r in rows)
def fut_liq_price(self, symbol: str) -> float | None:
rows = self._fut("GET", "/api/v1/private/position/open_positions", {"symbol": symbol}) or []
return _liq(rows, "liquidatePrice", _units(symbol[:-5]), lambda r: float(r.get("holdVol") or 0))
def balances(self) -> dict:
spot = next((float(b["free"]) + float(b.get("locked") or 0) # incl. USDT held by open orders
for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"] if b["asset"] == "USDT"), 0.0)
out = {"Спот USDT": spot}
try:
acc = next((a for a in self._fut("GET", "/api/v1/private/account/assets") if a.get("currency") == "USDT"), {})
# equity: what the account is worth now (free + margin in positions + their unrealized result)
out["Фьючерсы USDT"] = float(acc.get("equity") or acc.get("availableBalance") or 0)
except LiveError as exc:
out["Фьючерсы"] = str(exc)
return out
unified = False
def usdt_free(self) -> dict:
spot = next((float(b["free"]) for b in self._signed("GET", f"{self.SPOT}/api/v3/account")["balances"]
if b["asset"] == "USDT"), 0.0)
acc = next((a for a in self._fut("GET", "/api/v1/private/account/assets") if a.get("currency") == "USDT"), {})
return {"spot": spot, "futures": float(acc.get("availableBalance") or 0)}
def transfer_usdt(self, to: str, amount: float) -> None:
"""Between the spot and futures accounts (spot API capital/transfer; the key needs the transfer right)."""
self._signed("POST", f"{self.SPOT}/api/v3/capital/transfer", {
"fromAccountType": "SPOT" if to == "futures" else "FUTURES",
"toAccountType": "FUTURES" if to == "futures" else "SPOT", "asset": "USDT", "amount": _num(amount)})
# --------------------------------------------------------------------------------------------------------------
class Htx:
name = "HTX"
spot_fee, fut_fee = 0.2, 0.05
SPOT, FUT = "api.huobi.pro", "api.hbdm.com"
def __init__(self, key: str, secret: str) -> None:
self.key, self.secret = key, secret
self.rules: dict[str, dict] = {}
self.account_id: str | None = None
def _call(self, method: str, host: str, path: str, params: dict | None = None, body: dict | None = None):
q = {"AccessKeyId": self.key, "SignatureMethod": "HmacSHA256", "SignatureVersion": "2",
"Timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S"), **(params or {})}
query = urllib.parse.urlencode(sorted(q.items()), quote_via=urllib.parse.quote)
payload = f"{method}\n{host}\n{path}\n{query}"
sign = base64.b64encode(hmac.new(self.secret.encode(), payload.encode(), hashlib.sha256).digest()).decode()
url = f"https://{host}{path}?{query}&Signature={urllib.parse.quote(sign, safe='')}"
data = None if body is None else json.dumps(body).encode()
d = _http(method, url, {"Content-Type": "application/json"}, data)
if d.get("status") not in ("ok", None) or (d.get("code") not in (None, 200) and "data" not in d):
raise LiveError(f"HTX {d.get('err-code') or d.get('err_code') or d.get('code')}: "
f"{d.get('err-msg') or d.get('err_msg') or d.get('message')}")
return d.get("data")
def _account(self) -> str:
if self.account_id is None:
acc = next((a for a in self._call("GET", self.SPOT, "/v1/account/accounts") if a.get("type") == "spot"), None)
if acc is None:
raise LiveError("HTX: спотовый счёт не найден")
self.account_id = str(acc["id"])
return self.account_id
def _spot_order(self, base: str, kind: str, amount: str, fee_rate: float, price: str | None = None) -> Fill:
body = {"account-id": self._account(), "symbol": f"{base.lower()}usdt", "type": kind, "amount": amount,
"source": "spot-api"}
if price is not None:
body["price"] = price
oid = self._call("POST", self.SPOT, "/v1/order/orders/place", body=body)
def poll():
for _ in range(10):
o = self._call("GET", self.SPOT, f"/v1/order/orders/{oid}")
if o.get("state") in ("filled", "partial-canceled", "canceled"):
return o
time.sleep(0.3)
raise LiveError("ордер не исполнился за 3 с")
o = _placed(str(oid), poll)
qty, quote = float(o.get("field-amount") or o.get("filled-amount") or 0), float(
o.get("field-cash-amount") or o.get("filled-cash-amount") or 0)
if qty <= 0:
# a market order cancelled with nothing filled: HTX's circuit breaker on a wide spread (410 — the order
# detail does not report the source, only the history does); nothing traded, a limit can go instead
if kind.endswith("-market") and o.get("state") == "canceled":
raise CircuitBreaker("HTX: рыночный ордер отменён защитой биржи (широкий спред)")
raise LiveError(f"HTX: ордер не исполнен ({o.get('state')})")
fee = float(o.get("field-fees") or o.get("filled-fees") or 0)
fee_usd = fee * quote / qty if kind.startswith("buy") else fee # a buy pays its fee in coins
return Fill(qty, quote / qty, fee_usd or quote * fee_rate / 100, str(oid), o)
def _spot_rule(self, base: str) -> dict:
k = f"spot:{base}"
if k not in self.rules:
sym = next((s for s in _http("GET", f"https://{self.SPOT}/v1/common/symbols")["data"]
if s["symbol"] == f"{base.lower()}usdt"), None)
if sym is None:
raise LiveError(f"HTX: нет пары {base}/USDT")
self.rules[k] = {"step": 10 ** -int(sym.get("amount-precision", 4)),
"tick": 10 ** -int(sym.get("price-precision", 8))}
return self.rules[k]
def _spot_step(self, base: str) -> float:
return self._spot_rule(base)["step"]
def _book_price(self, base: str, side: str, size: float, in_quote: bool) -> float:
"""The price an IOC limit order needs to fill `size` (coins, or USDT for a buy) from the book now: the last
level it reaches. For when HTX refuses a market order (its circuit breaker on a wide spread)."""
import fastquote
bids, asks = fastquote.book("HTX", "spot", f"{base.lower()}usdt")
levels, got = (asks if side == "buy" else bids), 0.0
for p, q in levels:
got += p * q if in_quote else q
if got >= size:
return p
raise LiveError(f"HTX: в стакане {base} меньше нужного объёма")
def spot_buy(self, base: str, usdt: float) -> Fill:
try:
return self._spot_order(base, "buy-market", _num(round(usdt, 2)), self.spot_fee)
except CircuitBreaker:
r = _unsent(lambda: self._spot_rule(base))
price = _unsent(lambda: self._book_price(base, "buy", usdt, True))
price = math.ceil(price / r["tick"] - 1e-9) * r["tick"]
coins = _floor(usdt / price, r["step"])
return self._spot_order(base, "buy-ioc", _num(coins), self.spot_fee, _num(price))
def spot_sell(self, base: str, coins: float) -> Fill:
step = _unsent(lambda: self._spot_step(base))
amount = _num(_floor(coins, step))
try:
return self._spot_order(base, "sell-market", amount, self.spot_fee)
except CircuitBreaker:
# nothing was sold: the same coins as an IOC limit at the book price that takes them all
r = _unsent(lambda: self._spot_rule(base))
price = _unsent(lambda: self._book_price(base, "sell", float(amount), False))
price = math.floor(price / r["tick"] + 1e-9) * r["tick"]
return self._spot_order(base, "sell-ioc", amount, self.spot_fee, _num(price))
def spot_coins(self) -> dict[str, float]:
out: dict[str, float] = {}
for i in self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"]:
if i["type"] == "trade" and i["currency"] != "usdt" and float(i["balance"]) > 0:
out[i["currency"].upper()] = out.get(i["currency"].upper(), 0.0) + float(i["balance"])
return out
def spot_free(self, base: str) -> float:
items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"]
return sum(float(i["balance"]) for i in items if i["currency"] == base.lower() and i["type"] == "trade")
def _contract(self, code: str) -> dict:
k = f"fut:{code}"
if k not in self.rules:
d = _http("GET", f"https://{self.FUT}/linear-swap-api/v1/swap_contract_info?contract_code={code}")["data"]
if not d:
raise LiveError(f"HTX: нет контракта {code}")
self.rules[k] = {"size": float(d[0]["contract_size"]) * _units(code[:-5])}
return self.rules[k]
def fut_round(self, symbol: str, coins: float) -> float:
size = self._contract(symbol)["size"]
return math.floor(coins / size + 1e-9) * size
def fut_min_coins(self, symbol: str) -> float:
return self._contract(symbol)["size"]
# A futures account in the Multi-Assets Collateral mode (asset_mode 2) answers the v1 interface with 6023
# «The current API version has expired»: it is traded through the V5 interface (same signature, host api.hbdm.com).
_v5_mode: bool | None = None
def _v5(self) -> bool:
if self._v5_mode is None:
try:
self._v5_mode = int((self._call("GET", self.FUT, "/v5/account/asset_mode") or {}).get("asset_mode")
or 0) == 2
except LiveError:
return False # not known yet: v1, asked again next time
return self._v5_mode
V5_FINAL = ("filled", "partially_canceled", "canceled")
def _v5_order(self, symbol: str, oid: str) -> dict:
o = self._call("GET", self.FUT, "/v5/trade/order", {"contract_code": symbol, "order_id": oid}) or {}
return o[0] if isinstance(o, list) and o else o if isinstance(o, dict) else {}
def _v5_place(self, symbol: str, side: str, vol: int, reduce_only: bool, price: float | None) -> str:
body = {"contract_code": symbol, "margin_mode": "cross", "side": side, "volume": vol,
"type": "limit" if price else "market"}
if price:
body["price"] = price * _units(symbol[:-5])
body["time_in_force"] = "gtc"
if reduce_only:
body["reduce_only"] = 1
d = self._call("POST", self.FUT, "/v5/trade/order", body=body) or {}
oid = str(d.get("order_id") or d.get("order_id_str") or "")
if not oid:
raise LiveError(f"HTX: биржа не вернула номер ордера ({d})", sent=True)
return oid
def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None,
sl: float | None = None) -> Fill:
fill = self._fut_market(symbol, side, coins, reduce_only)
if not reduce_only and (tp or sl):
fill.tpsl = "HTX: TP/SL на бирже не поддерживается программой — закрывает программа"
return fill
def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill:
size = _unsent(lambda: self._contract(symbol))["size"]
vol = math.floor(coins / size + 1e-9)
if vol <= 0:
raise LiveError("HTX: количество меньше одного контракта")
if _unsent(self._v5):
oid = self._v5_place(symbol, side, vol, reduce_only, None)
def poll_v5():
for _ in range(10):
o = self._v5_order(symbol, oid)
if o.get("state") in self.V5_FINAL:
return o
time.sleep(0.3)
raise LiveError("ордер не исполнился за 3 с")
o = _placed(oid, poll_v5)
done = float(o.get("trade_volume") or 0) * size
if done <= 0:
raise LiveError(f"HTX: фьючерсный ордер не исполнен ({o.get('state')})")
price = float(o.get("trade_avg_price") or 0) / _units(symbol[:-5])
fee = abs(float(o.get("fee") or 0))
return Fill(done, price, fee or done * price * self.fut_fee / 100, oid, o, bool(fee))
d = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order", body={
"contract_code": symbol, "volume": vol, "direction": side, "offset": "close" if reduce_only else "open",
"lever_rate": 1, "order_price_type": "optimal_20"})
oid = d["order_id_str"]
def poll():
for _ in range(10):
info = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order_info",
body={"order_id": oid, "contract_code": symbol})
o = info[0] if info else {}
if o.get("status") in (6, 5, 7): # filled / partially filled then cancelled / cancelled
return o
time.sleep(0.3)
raise LiveError("ордер не исполнился за 3 с")
o = _placed(oid, poll)
done = float(o.get("trade_volume") or 0) * size
if done <= 0:
raise LiveError("HTX: фьючерсный ордер не исполнен")
price = float(o.get("trade_avg_price") or 0) / _units(symbol[:-5])
fee = abs(float(o.get("fee") or 0))
return Fill(done, price, fee or done * price * self.fut_fee / 100, oid, o, bool(fee))
def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str:
size = _unsent(lambda: self._contract(symbol))["size"]
vol = math.floor(coins / size + 1e-9)
if vol <= 0:
raise LiveError("HTX: количество меньше одного контракта")
if _unsent(self._v5):
return self._v5_place(symbol, side, vol, reduce_only, price)
d = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order", body={
"contract_code": symbol, "volume": vol, "direction": side, "offset": "close" if reduce_only else "open",
"lever_rate": 1, "order_price_type": "limit", "price": price * _units(symbol[:-5])})
return str(d["order_id_str"])
def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str:
return self.fut_limit(symbol, side, coins, price, reduce_only=True)
def fut_order_status(self, symbol: str, order_id: str) -> dict:
size = self._contract(symbol)["size"]
if self._v5():
o = self._v5_order(symbol, order_id)
return {"coins": float(o.get("trade_volume") or 0) * size,
"price": float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]),
"fee": abs(float(o.get("fee") or 0)), "final": o.get("state") in self.V5_FINAL}
info = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_order_info",
body={"order_id": order_id, "contract_code": symbol})
o = info[0] if info else {}
return {"coins": float(o.get("trade_volume") or 0) * size,
"price": float(o.get("trade_avg_price") or 0) / _units(symbol[:-5]),
"fee": abs(float(o.get("fee") or 0)), "final": o.get("status") in (5, 6, 7)}
def fut_cancel(self, symbol: str, order_id: str) -> None:
if self._v5():
self._call("POST", self.FUT, "/v5/trade/cancel_order", body={"order_id": order_id, "contract_code": symbol})
return
self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_cancel",
body={"order_id": order_id, "contract_code": symbol})
def fut_cancel_all(self, symbol: str) -> None:
if self._v5():
self._call("POST", self.FUT, "/v5/trade/cancel_all_orders", body={"contract_code": symbol})
return
self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_cancelall", body={"contract_code": symbol})
def fut_position(self, symbol: str) -> float:
size = self._contract(symbol)["size"]
if self._v5():
rows = self._call("GET", self.FUT, "/v5/trade/position/opens", {"contract_code": symbol}) or []
def sign(r: dict) -> int: # one-way mode: position_side "both", the side is direction
side = r.get("position_side")
return 1 if side == "long" or (side not in ("long", "short") and r.get("direction") == "buy") else -1
return sum(float(r.get("volume") or 0) * size * sign(r) for r in rows
if r.get("contract_code", symbol) == symbol)
rows = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_position_info",
body={"contract_code": symbol}) or []
return sum(float(r.get("volume") or 0) * size * (1 if r.get("direction") == "buy" else -1) for r in rows)
def fut_liq_price(self, symbol: str) -> float | None:
if self._v5():
rows = self._call("GET", self.FUT, "/v5/trade/position/opens", {"contract_code": symbol}) or []
else:
rows = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_position_info",
body={"contract_code": symbol}) or []
return _liq([r for r in rows if r.get("contract_code", symbol) == symbol], "liquidation_price",
_units(symbol[:-5]), lambda r: float(r.get("volume") or 0))
def _fut_account(self) -> tuple[float, float]:
"""(equity, free margin) of the USDT futures account, $."""
if self._v5():
acc = self._call("GET", self.FUT, "/v5/account/balance") or {}
return float(acc.get("equity") or 0), float(acc.get("available_margin") or 0)
acc = self._call("POST", self.FUT, "/linear-swap-api/v1/swap_cross_account_info", body={"margin_account": "USDT"})
a = acc[0] if acc else {}
return float(a.get("margin_balance") or 0), float(a.get("withdraw_available") or a.get("margin_available") or 0)
def balances(self) -> dict:
items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"]
spot = sum(float(i["balance"]) for i in items if i["currency"] == "usdt" and i["type"] in ("trade", "frozen"))
out = {"Спот USDT": spot}
try:
out["Фьючерсы USDT"] = self._fut_account()[0]
except LiveError as exc:
out["Фьючерсы"] = str(exc)
return out
unified = False
def usdt_free(self) -> dict:
items = self._call("GET", self.SPOT, f"/v1/account/accounts/{self._account()}/balance")["list"]
spot = sum(float(i["balance"]) for i in items if i["currency"] == "usdt" and i["type"] == "trade")
return {"spot": spot, "futures": self._fut_account()[1]}
def transfer_usdt(self, to: str, amount: float) -> None:
self._call("POST", self.SPOT, "/v2/account/transfer", body={
"from": "spot" if to == "futures" else "linear-swap", "to": "linear-swap" if to == "futures" else "spot",
"currency": "usdt", "amount": float(_num(amount)), "margin-account": "USDT"})
# --------------------------------------------------------------------------------------------------------------
class Gate:
name = "Gate"
spot_fee, fut_fee = 0.1, 0.05
HOST, PREFIX = "https://api.gateio.ws", "/api/v4"
def __init__(self, key: str, secret: str) -> None:
self.key, self.secret = key, secret
self.rules: dict[str, dict] = {}
def _call(self, method: str, path: str, params: dict | None = None, body: dict | None = None):
query = urllib.parse.urlencode(params or {})
text = "" if body is None else json.dumps(body)
ts = str(int(time.time()))
payload = "\n".join([method, self.PREFIX + path, query, hashlib.sha512(text.encode()).hexdigest(), ts])
sign = hmac.new(self.secret.encode(), payload.encode(), hashlib.sha512).hexdigest()
url = self.HOST + self.PREFIX + path + (f"?{query}" if query else "")
d = _http(method, url, {"KEY": self.key, "Timestamp": ts, "SIGN": sign, "Content-Type": "application/json",
"Accept": "application/json"}, text.encode() if body is not None else None)
if isinstance(d, dict) and d.get("label"):
raise LiveError(f"Gate {d.get('label')}: {d.get('message')}")
return d
def _spot_step(self, base: str) -> float:
k = f"spot:{base}"
if k not in self.rules:
d = _http("GET", f"{self.HOST}{self.PREFIX}/spot/currency_pairs/{base}_USDT")
self.rules[k] = {"step": 10 ** -int(d.get("amount_precision", 4))}
return self.rules[k]["step"]
def _spot_order(self, base: str, side: str, amount: str, fee_rate: float) -> Fill:
o = self._call("POST", "/spot/orders", body={"currency_pair": f"{base}_USDT", "type": "market", "side": side,
"amount": amount, "time_in_force": "ioc"})
quote = float(o.get("filled_total") or 0)
price = float(o.get("avg_deal_price") or 0)
qty = float(o.get("filled_amount") or 0) or (quote / price if price else 0)
if qty <= 0:
raise LiveError(f"Gate: ордер не исполнен ({o.get('status')})")
fee, cur = float(o.get("fee") or 0), (o.get("fee_currency") or "").upper()
fee_usd = fee if cur == "USDT" else fee * quote / qty if cur == base else quote * fee_rate / 100
return Fill(qty, quote / qty, fee_usd, str(o.get("id")), o)
def spot_buy(self, base: str, usdt: float) -> Fill:
return self._spot_order(base, "buy", _num(round(usdt, 2)), self.spot_fee)
def spot_sell(self, base: str, coins: float) -> Fill:
step = _unsent(lambda: self._spot_step(base))
return self._spot_order(base, "sell", _num(_floor(coins, step)), self.spot_fee)
def spot_coins(self) -> dict[str, float]:
return {a["currency"]: float(a.get("available") or 0) for a in self._call("GET", "/spot/accounts") or []
if a.get("currency") != "USDT" and float(a.get("available") or 0) > 0}
def spot_free(self, base: str) -> float:
items = self._call("GET", "/spot/accounts", {"currency": base})
return float(items[0]["available"]) if items else 0.0
def _contract(self, symbol: str) -> dict:
k = f"fut:{symbol}"
if k not in self.rules:
d = _http("GET", f"{self.HOST}{self.PREFIX}/futures/usdt/contracts/{symbol}")
self.rules[k] = {"size": float(d.get("quanto_multiplier") or 1) * _units(symbol[:-5]),
"min": float(d.get("order_size_min") or 1)}
return self.rules[k]
def fut_round(self, symbol: str, coins: float) -> float:
c = self._contract(symbol)
n = math.floor(coins / c["size"] + 1e-9)
return n * c["size"] if n >= c["min"] else 0.0
def fut_min_coins(self, symbol: str) -> float:
c = self._contract(symbol)
return c["size"] * max(1.0, c["min"])
def fut_order(self, symbol: str, side: str, coins: float, reduce_only: bool, tp: float | None = None,
sl: float | None = None) -> Fill:
fill = self._fut_market(symbol, side, coins, reduce_only)
if not reduce_only and (tp or sl):
fill.tpsl = "Gate: TP/SL на бирже не поддерживается программой — закрывает программа"
return fill
def _fut_market(self, symbol: str, side: str, coins: float, reduce_only: bool) -> Fill:
c = _unsent(lambda: self._contract(symbol))
n = math.floor(coins / c["size"] + 1e-9)
if n <= 0:
raise LiveError("Gate: количество меньше одного контракта")
o = self._call("POST", "/futures/usdt/orders", body={"contract": symbol, "size": n if side == "buy" else -n,
"price": "0", "tif": "ioc", "reduce_only": reduce_only})
done = (abs(int(o.get("size") or 0)) - abs(int(o.get("left") or 0))) * c["size"]
if done <= 0:
raise LiveError(f"Gate: фьючерсный ордер не исполнен ({o.get('finish_as')})")
price = float(o.get("fill_price") or 0) / _units(symbol[:-5])
fee, exact = self._order_fee(symbol, str(o.get("id")))
return Fill(done, price, fee if exact else done * price * self.fut_fee / 100, str(o.get("id")), o, exact)
def _order_fee(self, symbol: str, order_id: str) -> tuple[float, bool]:
"""The fee Gate charged for the order, from its fills (the order answer has none); (0, False) if unread."""
try:
fills = self._call("GET", "/futures/usdt/my_trades", {"contract": symbol, "order": order_id, "limit": 100})
except LiveError:
return 0.0, False
fills = [f for f in fills or [] if str(f.get("order_id")) == order_id]
if not fills:
return 0.0, False
return sum(abs(float(f.get("fee") or 0)) for f in fills), True
def fut_limit(self, symbol: str, side: str, coins: float, price: float, reduce_only: bool = False) -> str:
c = _unsent(lambda: self._contract(symbol))
n = math.floor(coins / c["size"] + 1e-9)
if n <= 0:
raise LiveError("Gate: количество меньше одного контракта")
o = self._call("POST", "/futures/usdt/orders", body={
"contract": symbol, "size": n if side == "buy" else -n, "price": _num(price * _units(symbol[:-5])),
"tif": "gtc", "reduce_only": reduce_only})
return str(o.get("id"))
def fut_take_profit(self, symbol: str, side: str, coins: float, price: float) -> str:
return self.fut_limit(symbol, side, coins, price, reduce_only=True)
def fut_order_status(self, symbol: str, order_id: str) -> dict:
c = self._contract(symbol)
o = self._call("GET", f"/futures/usdt/orders/{order_id}")
done = (abs(int(o.get("size") or 0)) - abs(int(o.get("left") or 0))) * c["size"]
price = float(o.get("fill_price") or 0) / _units(symbol[:-5])
fee, exact = self._order_fee(symbol, str(order_id)) if done > 0 else (0.0, False)
return {"coins": done, "price": price, "fee": fee if exact else done * price * self.fut_fee / 100,
"final": o.get("status") == "finished"}
def fut_cancel(self, symbol: str, order_id: str) -> None:
self._call("DELETE", f"/futures/usdt/orders/{order_id}")
def fut_cancel_all(self, symbol: str) -> None:
self._call("DELETE", "/futures/usdt/orders", {"contract": symbol})
def _position_rows(self, symbol: str) -> list[dict]:
"""The symbol's position rows: one in the single mode; two (dual_long + dual_short) when the account is in
the hedge (dual) mode — then Gate answers with a LIST, which must not read as «no position»."""
try:
d = self._call("GET", f"/futures/usdt/positions/{symbol}")
except LiveError as exc:
if "POSITION_NOT_FOUND" in str(exc): # never traded on this account: no position
return []
raise
if isinstance(d, list):
return [r for r in d if isinstance(r, dict)]
return [d] if isinstance(d, dict) else []
def fut_position(self, symbol: str) -> float:
"""Coins of the open position: + long, − short (both sides summed in the hedge mode)."""
size = self._contract(symbol)["size"]
return sum(float(r.get("size") or 0) for r in self._position_rows(symbol)) * size
def fut_liq_price(self, symbol: str) -> float | None:
return _liq(self._position_rows(symbol), "liq_price", _units(symbol[:-5]),
lambda r: abs(float(r.get("size") or 0)))
def balances(self) -> dict:
spot = self._call("GET", "/spot/accounts", {"currency": "USDT"})
out = {"Спот USDT": float(spot[0]["available"]) + float(spot[0].get("locked") or 0) if spot else 0.0}
try:
# equity: the balance plus the open positions' unrealized result (not only the free part)
acc = self._fut_account()
out["Фьючерсы USDT"] = float(acc.get("total") or 0) + float(acc.get("unrealised_pnl") or 0)
except LiveError as exc:
out["Фьючерсы"] = str(exc)
return out
unified = False
def usdt_free(self) -> dict:
spot = self._call("GET", "/spot/accounts", {"currency": "USDT"})
return {"spot": float(spot[0]["available"]) if spot else 0.0,
"futures": float(self._fut_account().get("available") or 0)}
def _fut_account(self) -> dict:
"""The USDT futures account; {} while it does not exist (Gate creates it with the first transfer:
USER_NOT_FOUND «please transfer funds first») — an empty account, not an error."""
try:
return self._call("GET", "/futures/usdt/accounts") or {}
except LiveError as exc:
if "USER_NOT_FOUND" in str(exc):
return {}
raise
def transfer_usdt(self, to: str, amount: float) -> None:
self._call("POST", "/wallet/transfers", body={
"currency": "USDT", "from": "spot" if to == "futures" else "futures",
"to": "futures" if to == "futures" else "spot", "amount": _num(amount), "settle": "usdt"})
def ensure_usdt(c, spot_need: float, futures_need: float) -> str:
"""Make `spot_need` USDT free on the spot account and `futures_need` on the futures one by moving the shortfall
from the other account. Returns what was done ("" = nothing needed); LiveError when the total is not enough."""
if getattr(c, "unified", False):
return ""
free = c.usdt_free()
spot_gap = max(0.0, spot_need - free["spot"])
fut_gap = max(0.0, futures_need - free["futures"])
if spot_gap <= 0 and fut_gap <= 0:
return ""
if spot_gap > 0 and fut_gap > 0 or free["spot"] + free["futures"] < spot_need + futures_need:
raise LiveError(f"не хватает USDT в сумме: нужно {spot_need:.2f} на споте и {futures_need:.2f} на фьючерсах, "
f"есть {free['spot']:.2f} и {free['futures']:.2f}")
to, gap = ("futures", fut_gap) if fut_gap > 0 else ("spot", spot_gap)
amount = math.ceil(gap * 100) / 100 + 0.01 # a cent of margin for rounding
c.transfer_usdt(to, amount)
return f"переведено {amount:.2f} USDT {'со спота на фьючерсы' if to == 'futures' else 'с фьючерсов на спот'}"
CLIENTS = {"bybit": Bybit, "binance": Binance, "mexc": Mexc, "htx": Htx, "gate": Gate}
_cache: dict[str, tuple[tuple[str, str], object]] = {}
def client(exchange: str):
"""Client with the exchange's saved keys (rebuilt when the keys change); LiveError when no keys."""
import keystore
keys = keystore.get(exchange)
if keys is None:
raise LiveError(f"{keystore.EXCHANGES.get(exchange, exchange)}: API-ключи не заданы")
cached = _cache.get(exchange)
if cached is None or cached[0] != keys:
cached = (keys, CLIENTS[exchange](*keys))
_cache[exchange] = cached
return cached[1]