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

No files matched your search

+159
View File
@@ -0,0 +1,159 @@
"""Best bid / ask of ONE symbol, fast (public REST, kept-alive connections): used to watch open positions several
times a second, instead of the whole-market lists that take 1–20 s per cycle.
spot_top(exchange, symbol) -> (bid, ask, bid $ size or None, ask $ size or None)
fut_top(exchange, symbol) -> the same for the USDT perpetual, prices per the symbol's unit (1000PEPE…)
`exchange` is "Bybit" / "Binance" / "MEXC" / "HTX" / "Gate"; symbols are the exchange's own (as the scanners have them).
"""
from __future__ import annotations
import urllib.parse
from live import LiveError, _http
def _f(v) -> float:
try:
return float(v)
except (TypeError, ValueError):
return 0.0
def _q(s: str) -> str:
return urllib.parse.quote(s, safe="")
def spot_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]:
if exchange == "Bybit":
t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=spot&symbol={_q(symbol)}")["result"]["list"][0]
b, a = _f(t["bid1Price"]), _f(t["ask1Price"])
return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size"))
if exchange in ("Binance", "MEXC"):
host = "https://api.binance.com" if exchange == "Binance" else "https://api.mexc.com"
t = _http("GET", f"{host}/api/v3/ticker/bookTicker?symbol={_q(symbol)}")
b, a = _f(t["bidPrice"]), _f(t["askPrice"])
return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty"))
if exchange == "HTX":
t = _http("GET", f"https://api.huobi.pro/market/detail/merged?symbol={_q(symbol.lower())}")["tick"]
return _f(t["bid"][0]), _f(t["ask"][0]), _f(t["bid"][0]) * _f(t["bid"][1]), _f(t["ask"][0]) * _f(t["ask"][1])
if exchange == "Gate":
t = _http("GET", f"https://api.gateio.ws/api/v4/spot/tickers?currency_pair={_q(symbol)}")[0]
return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None
raise LiveError(f"нет быстрых цен для {exchange}")
def fut_top(exchange: str, symbol: str) -> tuple[float, float, float | None, float | None]:
if exchange == "Bybit":
t = _http("GET", f"https://api.bybit.com/v5/market/tickers?category=linear&symbol={_q(symbol)}")["result"]["list"][0]
b, a = _f(t["bid1Price"]), _f(t["ask1Price"])
return b, a, b * _f(t.get("bid1Size")), a * _f(t.get("ask1Size"))
if exchange == "Binance":
t = _http("GET", f"https://fapi.binance.com/fapi/v1/ticker/bookTicker?symbol={_q(symbol)}")
b, a = _f(t["bidPrice"]), _f(t["askPrice"])
return b, a, b * _f(t.get("bidQty")), a * _f(t.get("askQty"))
if exchange == "MEXC":
t = _http("GET", f"https://contract.mexc.com/api/v1/contract/ticker?symbol={_q(symbol)}")["data"]
return _f(t["bid1"]), _f(t["ask1"]), None, None
if exchange == "HTX":
t = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/detail/merged?contract_code={_q(symbol)}")["tick"]
return _f(t["bid"][0]), _f(t["ask"][0]), None, None
if exchange == "Gate":
t = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/tickers?contract={_q(symbol)}")[0]
return _f(t["highest_bid"]), _f(t["lowest_ask"]), None, None
raise LiveError(f"нет быстрых цен для {exchange}")
# --- order books: what an order of N $ would really get --------------------------------------------------------------
# The tickers above can lag the book by a second or two on a fast move (seen on Gate: a «gap» that was gone when the
# orders arrived). Before a real entry the program reads the books themselves and prices the whole trade amount.
_SIZES: dict[tuple[str, str], float] = {} # (exchange, perp symbol) → coins (of the symbol's unit) per contract
def _contract_size(exchange: str, symbol: str) -> float:
key = (exchange, symbol)
if key not in _SIZES:
if exchange == "MEXC":
d = _http("GET", f"https://contract.mexc.com/api/v1/contract/detail?symbol={_q(symbol)}")["data"]
_SIZES[key] = _f(d.get("contractSize")) or 1.0
elif exchange == "HTX":
d = _http("GET", f"https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?contract_code={_q(symbol)}")["data"]
_SIZES[key] = _f(d[0].get("contract_size")) or 1.0
elif exchange == "Gate":
d = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/contracts/{_q(symbol)}")
_SIZES[key] = _f(d.get("quanto_multiplier")) or 1.0
else:
_SIZES[key] = 1.0
return _SIZES[key]
def book(exchange: str, market: str, symbol: str) -> tuple[list, list]:
"""(bids, asks) of the order book, best first, as [(price per symbol unit, quantity in symbol units)];
market "spot" or "fut"."""
fut = market == "fut"
if exchange == "Bybit":
r = _http("GET", f"https://api.bybit.com/v5/market/orderbook?category={'linear' if fut else 'spot'}"
f"&symbol={_q(symbol)}&limit=50")["result"]
bids, asks = r["b"], r["a"]
elif exchange == "Binance":
host = "https://fapi.binance.com/fapi/v1" if fut else "https://api.binance.com/api/v3"
r = _http("GET", f"{host}/depth?symbol={_q(symbol)}&limit=20")
bids, asks = r["bids"], r["asks"]
elif exchange == "MEXC":
if fut:
r = _http("GET", f"https://contract.mexc.com/api/v1/contract/depth/{_q(symbol)}?limit=20")["data"]
size = _contract_size(exchange, symbol)
bids = [(b[0], _f(b[1]) * size) for b in r["bids"]]
asks = [(a[0], _f(a[1]) * size) for a in r["asks"]]
else:
r = _http("GET", f"https://api.mexc.com/api/v3/depth?symbol={_q(symbol)}&limit=20")
bids, asks = r["bids"], r["asks"]
elif exchange == "HTX":
if fut:
r = _http("GET", f"https://api.hbdm.com/linear-swap-ex/market/depth?contract_code={_q(symbol)}&type=step0")["tick"]
size = _contract_size(exchange, symbol)
bids = [(b[0], _f(b[1]) * size) for b in r["bids"]]
asks = [(a[0], _f(a[1]) * size) for a in r["asks"]]
else:
r = _http("GET", f"https://api.huobi.pro/market/depth?symbol={_q(symbol.lower())}&depth=20&type=step0")["tick"]
bids, asks = r["bids"], r["asks"]
elif exchange == "Gate":
if fut:
r = _http("GET", f"https://api.gateio.ws/api/v4/futures/usdt/order_book?contract={_q(symbol)}&limit=20")
size = _contract_size(exchange, symbol)
bids = [(b["p"], abs(_f(b["s"])) * size) for b in r["bids"]]
asks = [(a["p"], abs(_f(a["s"])) * size) for a in r["asks"]]
else:
r = _http("GET", f"https://api.gateio.ws/api/v4/spot/order_book?currency_pair={_q(symbol)}&limit=20")
bids, asks = r["bids"], r["asks"]
else:
raise LiveError(f"нет стакана для {exchange}")
return [(_f(p), _f(q)) for p, q in bids[:50]], [(_f(p), _f(q)) for p, q in asks[:50]]
def fill_price(levels: list, usd: float) -> float | None:
"""Average price of an order for `usd` $ walking the book from the best level; None when the book (as read)
holds less than that."""
left, cost, qty = usd, 0.0, 0.0
for price, q in levels:
if price <= 0 or q <= 0:
continue
take = min(left, price * q)
cost += take
qty += take / price
left -= take
if left <= 1e-9:
return cost / qty
return None
def execution(exchange: str, market: str, symbol: str, usd: float) -> dict:
"""What an order of `usd` $ gets now: {"bid": average sale price, "ask": average purchase price (None: not
enough in the book), "best_bid", "best_ask", "spread_pct"} — prices per symbol unit."""
bids, asks = book(exchange, market, symbol)
if not bids or not asks:
raise LiveError(f"{exchange}: пустой стакан {symbol}")
bb, ba = bids[0][0], asks[0][0]
return {"bid": fill_price(bids, usd), "ask": fill_price(asks, usd), "best_bid": bb, "best_ask": ba,
"spread_pct": (ba / bb - 1) * 100 if bb > 0 else 100.0}