Files
Crypto_Scam/basis.py
2026-10-22 20:19:52 +03:00

1335 lines
71 KiB
Python
Raw Permalink 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.
"""Spot–futures basis trades on one exchange (paper): buy the coin on spot while it is cheaper than the perpetual,
short the same amount of coins on the perpetual, close both legs when the gap has closed (≈ 0).
Coins: new listings, the exchange's innovation zone and memecoins that have both a USDT spot pair and a USDT
perpetual. Only Bybit is implemented; other exchanges plug in as another Venue.
entry gap = perp bid / spot ask − 1 (buy spot at the ask, short the perp at the bid)
exit gap = perp ask / spot bid − 1 (sell spot at the bid, buy the perp back at the ask)
Result of one trade = spot leg + perp leg − 4 taker fees + funding the short received while it was open.
"""
from __future__ import annotations
import json
import queue
import threading
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict, dataclass, field, fields
from pathlib import Path
from arb import _f, _get, split_base
ROOT = Path(__file__).resolve().parent
DATA_DIR = ROOT / "web_sim_data"
POLL_S = 1.0
INSTRUMENTS_S = 3600.0
MEMES_S = 6 * 3600.0
KEEP_TRADES = 500
# used when CoinGecko's meme-token list cannot be fetched (it rate-limits often)
MEME_FALLBACK = set("""DOGE SHIB PEPE FLOKI BONK WIF BOME MEW POPCAT BRETT MOG TURBO NEIRO NEIROCTO PNUT GOAT MOODENG ACT
CHILLGUY FARTCOIN TRUMP MELANIA PENGU SPX GIGA PONKE MYRO SLERF BABYDOGE DOGS NOT CAT MEME BAN AI16Z ZEREBRO
LADYS WEN SATS ORDI RATS COQ TOSHI MICHI BILLY DEGEN HIPPO SUNDOG HMSTR CATI MOTHER DADDY RETARDIO SIGMA LUCE
FWOG SC DOG BOOK BOOKOFMEME KEKIUS VINE TST BROCCOLI MUBARAK JELLYJELLY HOUSE USELESS PUMP TROLL ANSEM CLAUDIA
MANYU BUTTCOIN ELON KISHU BONE LEASH SNEK GME AIDOGE PEOPLE WOJAK HPOS10I APU MAGA LOBO QUBIC SHIB2""".split())
@dataclass
class Pair:
"""One coin with both a spot pair and a perpetual on the venue; prices per coin."""
base: str
spot_symbol: str
fut_symbol: str
mult: float
spot_bid: float
spot_ask: float
fut_bid: float
fut_ask: float
spot_bid_usd: float | None # $ at the best price (None: the exchange does not report it)
spot_ask_usd: float | None
fut_bid_usd: float | None
fut_ask_usd: float | None
funding: float # per interval, fraction (0.0001 = 0.01%)
next_funding: float # unix seconds
interval_h: float
spot_turnover: float
fut_turnover: float
age_days: float | None
innovation: bool
meme: bool
@property
def entry_gap(self) -> float:
return (self.fut_bid / self.spot_ask - 1) * 100
@property
def exit_gap(self) -> float:
return (self.fut_ask / self.spot_bid - 1) * 100
class BybitVenue:
name = "Bybit"
spot_fee = 0.1
fut_fee = 0.055
innovation_fee = 0.11 # perps of the Innovation Zone: their own taker rate (bybit.com/fee, regular user)
def __init__(self) -> None:
self.instruments: dict[str, dict] = {} # base → {fut_symbol, spot_symbol, mult, launch, innovation}
self.instruments_time = 0.0
@staticmethod
def spot_url(p: Pair) -> str:
return f"https://www.bybit.com/trade/spot/{p.base}/USDT"
@staticmethod
def fut_url(p: Pair) -> str:
return f"https://www.bybit.com/trade/usdt/{p.fut_symbol}"
def refresh_instruments(self) -> None:
if self.instruments and time.time() - self.instruments_time < INSTRUMENTS_S:
return
spot = {s["symbol"] for s in _get("https://api.bybit.com/v5/market/instruments-info?category=spot")["result"]
["list"] if s.get("status") == "Trading" and s.get("quoteCoin") == "USDT"
and s.get("symbolType") in ("", "adventure")}
out = {}
cursor = ""
while True:
res = _get("https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000"
+ (f"&cursor={cursor}" if cursor else ""))["result"]
for x in res["list"]:
# stock / ETF / commodity / forex perps are not the same thing as a spot coin
if (x.get("status") != "Trading" or x.get("contractType") != "LinearPerpetual"
or x.get("quoteCoin") != "USDT" or x.get("symbolType") not in ("", "innovation")):
continue
base, mult = split_base(x["baseCoin"])
spot_symbol = f"{base}USDT"
if spot_symbol not in spot:
continue
out[base] = {"fut_symbol": x["symbol"], "spot_symbol": spot_symbol, "mult": mult,
"launch": int(x.get("launchTime") or 0) / 1000 or None,
"innovation": x.get("symbolType") == "innovation",
"interval_h": int(x.get("fundingInterval") or 480) / 60}
cursor = res.get("nextPageCursor") or ""
if not cursor or not res["list"]:
break
self.instruments, self.instruments_time = out, time.time()
def pairs(self, memes: set[str]) -> list[Pair]:
self.refresh_instruments()
spot = {t["symbol"]: t for t in _get("https://api.bybit.com/v5/market/tickers?category=spot")["result"]["list"]}
fut = {t["symbol"]: t for t in _get("https://api.bybit.com/v5/market/tickers?category=linear")["result"]["list"]}
now = time.time()
out = []
for base, ins in self.instruments.items():
s, f = spot.get(ins["spot_symbol"]), fut.get(ins["fut_symbol"])
if not s or not f:
continue
m = ins["mult"]
sb, sa, fb, fa = _f(s.get("bid1Price")), _f(s.get("ask1Price")), _f(f.get("bid1Price")), _f(f.get("ask1Price"))
if min(sb, sa, fb, fa) <= 0:
continue
out.append(Pair(
base, ins["spot_symbol"], ins["fut_symbol"], m, sb, sa, fb / m, fa / m,
sb * _f(s.get("bid1Size")), sa * _f(s.get("ask1Size")), fb * _f(f.get("bid1Size")),
fa * _f(f.get("ask1Size")), _f(f.get("fundingRate")), _f(f.get("nextFundingTime")) / 1000,
_f(f.get("fundingIntervalHour"), ins["interval_h"]) or ins["interval_h"],
_f(s.get("turnover24h")), _f(f.get("turnover24h")),
None if not ins["launch"] else (now - ins["launch"]) / 86400, ins["innovation"], base in memes))
return out
def _listing_binance() -> dict[str, dict]:
out = {}
for s in _get("https://fapi.binance.com/fapi/v1/exchangeInfo")["symbols"]:
# TradFi perps (stocks, gold…) are not the spot coin of the same name
if (s.get("contractType") != "PERPETUAL" or s.get("status") != "TRADING" or s.get("quoteAsset") != "USDT"
or s.get("underlyingType") != "COIN" or "TradFi" in (s.get("underlyingSubType") or [])):
continue
out[s["symbol"]] = {"launch": _f(s.get("onboardDate")) / 1000 or None,
"meme": "Meme" in (s.get("underlyingSubType") or []), "innovation": False}
return out
def _listing_mexc() -> dict[str, dict]:
out = {}
for c in _get("https://contract.mexc.com/api/v1/contract/detail")["data"]:
if c.get("quoteCoin") != "USDT" or c.get("state") not in (0, None) or c.get("futureType") not in (1, None):
continue
zones = " ".join(c.get("conceptPlate") or []).lower()
out[c["symbol"]] = {"launch": _f(c.get("openingTime") or c.get("createTime")) / 1000 or None,
"meme": "meme" in zones, "innovation": bool(c.get("isNew"))}
return out
def _listing_htx() -> dict[str, dict]:
out = {}
for c in _get("https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=swap")["data"]:
if c.get("contract_status") != 1 or not c["contract_code"].endswith("-USDT"):
continue
try:
launch = time.mktime(time.strptime(c.get("create_date", ""), "%Y%m%d"))
except ValueError:
launch = None
labels = [x.lower() for x in c.get("labels") or []]
out[c["contract_code"]] = {"launch": launch, "meme": "meme" in labels, "innovation": "new" in labels}
return out
def _listing_gate() -> dict[str, dict]:
out = {}
for c in _get("https://api.gateio.ws/api/v4/futures/usdt/contracts"):
if c.get("in_delisting") or (c.get("status") not in (None, "trading")):
continue
out[c["name"]] = {"launch": _f(c.get("launch_time") or c.get("create_time")) or None, "meme": False,
"innovation": False}
return out
class ArbVenue:
"""Binance, MEXC, HTX, Gate: prices from the arbitrage scanner's fetchers (one request per market), listing
date / meme tag from the exchange's contract list (hourly). Funding is settled every `interval_h` hours on the
UTC grid. Where an exchange does not report the size at the best price (MEXC futures, Gate spot) the depth is
unknown (None) and not checked."""
innovation_fee = 0.0 # their «new» label is not a fee group
SETUP = {"binance": ("Binance", 0.1, 0.05, _listing_binance),
"mexc": ("MEXC", 0.05, 0.02, _listing_mexc),
"htx": ("HTX", 0.2, 0.05, _listing_htx),
"gate": ("Gate", 0.1, 0.05, _listing_gate)}
def __init__(self, key: str) -> None:
import arb
self.arb = arb
self.key = key
self.name, self.spot_fee, self.fut_fee, self._listing = self.SETUP[key]
self.fut, self.spot = arb.Fetchers(), arb.SpotFetchers()
self.listing: dict[str, dict] = {}
self.listing_time = 0.0
def spot_url(self, p: Pair) -> str:
return self.arb.spot_url(self.name, p.spot_symbol, p.base)
def fut_url(self, p: Pair) -> str:
return self.arb.exchange_url(self.name, p.fut_symbol)
def pairs(self, memes: set[str]) -> list[Pair]:
if not self.listing or time.time() - self.listing_time > INSTRUMENTS_S:
try:
self.listing, self.listing_time = self._listing(), time.time()
self.fut.refresh_reference() # funding intervals, contract sizes
except Exception:
if not self.listing:
raise
if self.key in ("binance", "mexc"):
self.spot.refresh_volume()
# both markets at once: a slow exchange (Gate) then costs one wait, not two
with ThreadPoolExecutor(max_workers=2) as pool:
fut_job = pool.submit(getattr(self.fut, self.key))
spot_job = pool.submit(getattr(self.spot, self.key))
futs = fut_job.result()
spots = {q.base: q for q in spot_job.result() if q.mult == 1}
now = time.time()
out = []
for f in futs:
info = self.listing.get(f.symbol)
s = spots.get(f.base)
if info is None or s is None:
continue
interval = f.interval_h or 8.0
step = interval * 3600
out.append(Pair(
f.base, s.symbol, f.symbol, f.mult, s.bid, s.ask, f.bid, f.ask, s.bid_usd, s.ask_usd, f.bid_usd,
f.ask_usd, f.funding or 0.0, (now // step + 1) * step, interval, s.volume_usd, f.volume_usd,
None if not info["launch"] else (now - info["launch"]) / 86400, info["innovation"],
info["meme"] or f.base in memes))
return out
VENUES = {"bybit": BybitVenue, "binance": lambda: ArbVenue("binance"), "mexc": lambda: ArbVenue("mexc"),
"htx": lambda: ArbVenue("htx"), "gate": lambda: ArbVenue("gate")}
PLANNED: list[str] = []
@dataclass
class BasisSettings:
running: bool = False # open new trades (prices and exits go on when stopped)
amount: float = 100.0 # $ per trade: spent on spot, the same coins shorted on the perp
min_gap_pct: float = 0.6 # open when perp is at least this much above spot (after the spread)
max_gap_pct: float = 10.0 # …and not more (bigger = broken price, delisting, different coin)
exit_gap_pct: float = 0.05 # close both legs when the gap is back to this or below
stop_gap_pct: float = 0.0 # close at a loss when the gap widens to this (0 = off)
max_hold_hours: float = 0.0 # close after this long whatever the gap (0 = off)
max_positions: int = 10
cooldown_s: float = 60.0 # no new entry on the same coin this soon after a close
new_days: float = 90.0 # «new coin»: perpetual listed within this many days
use_new: bool = True
use_innovation: bool = True
use_memes: bool = True
all_coins: bool = False # ignore the three above and take every coin with spot + perp
min_turnover: float = 200000.0 # 24h turnover of the thinner market, $
min_depth: float = 0.0 # $ at the best prices on both legs (0 = only the trade amount itself)
spot_fee: float = 0.1
fut_fee: float = 0.055
fut_fee_innovation: float = 0.0 # perp taker rate of the Innovation Zone coins (Bybit 0.11); 0 = as «fut_fee»
real: bool = False # new trades as real orders with the exchange's API keys
auto_transfer: bool = True # move USDT between the spot and futures accounts when one of them is short
max_real_positions: int = 1 # real positions held at the same time (entries still go one after another)
entry_limit: bool = True # real entry: LIMIT short at the signal's perp bid first, then the spot hedge
limit_hold_s: float = 10.0 # …kept this long, then removed (nothing bought if it did not fill)
exchange_tp: bool = False # (off: the program watches the prices itself; kept for old settings files)
@dataclass
class Position:
uid: int
base: str
opened: float
qty: float # coins bought on spot = coins shorted
spot_entry: float
fut_entry: float
entry_gap: float
fees: float
next_funding: float
funding: float = 0.0 # $ received by the short (negative = paid)
# real positions: actual coins of each leg (the perp is rounded down to its lot), the perp symbol, and the
# close in progress (perp bought back first, then the spot sold; a failed spot sale is retried)
real: bool = False
spot_qty: float = 0.0
fut_symbol: str = ""
closing: str = "" # "" / "fut_done" (perp bought back, spot still to sell)
fut_exit: float = 0.0
exit_fees: float = 0.0
retry_at: float = 0.0
error: str = ""
sold_coins: float = 0.0 # spot sold so far by the close (from the exchange's fills)
sold_value: float = 0.0
sold_fees: float = 0.0
short_pending: bool = False # the spot leg is held but the perp short is not open yet (adopted coins…)
tp_order: str = "" # TP on the exchange (reduce-only limit buy of the short), "" = none
tp_price: float = 0.0
exact: bool = True # all prices and fees are the exchange's own figures
innovation: bool = False # an Innovation Zone perp: its own fee rate
@dataclass
class Trade:
uid: int
base: str
opened: float
closed: float
qty: float
spot_entry: float
spot_exit: float
fut_entry: float
fut_exit: float
entry_gap: float
exit_gap: float
spot_pnl: float
fut_pnl: float
fees: float
funding: float
net: float
reason: str
amount: float = 0.0
real: bool = False # done with real orders (figures from the exchange's fills)
exact: bool = True
def fut_rate(s: BasisSettings, innovation: bool) -> float:
"""Perp taker rate, %: the Innovation Zone coins of Bybit have their own (higher) rate."""
return s.fut_fee_innovation if innovation and s.fut_fee_innovation > 0 else s.fut_fee
def entry_fees(qty: float, spot_ask: float, fut_bid: float, s: BasisSettings, innovation: bool = False) -> float:
return qty * spot_ask * s.spot_fee / 100 + qty * fut_bid * fut_rate(s, innovation) / 100
def close_result(pos: Position, spot_bid: float, fut_ask: float, s: BasisSettings) -> tuple[float, float, float, float]:
"""(spot leg $, perp leg $, all fees $, net $) of closing `pos` at these prices."""
spot_qty = pos.spot_qty or pos.qty # real: the spot leg can hold a little more than the perp's lot
if pos.closing == "fut_done": # real close half done: the perp is already bought back
fut_ask = pos.fut_exit
spot_pnl = spot_qty * (spot_bid - pos.spot_entry)
fut_pnl = pos.qty * (pos.fut_entry - fut_ask)
fees = pos.fees + spot_qty * spot_bid * s.spot_fee / 100 + pos.qty * fut_ask * fut_rate(s, pos.innovation) / 100
return spot_pnl, fut_pnl, fees, spot_pnl + fut_pnl - fees + pos.funding
ENGINES: list = [] # every running spot–futures engine (each exchange and «between exchanges»)
# A gap this large is not a premium but two different instruments under one ticker (MEXC EWT: spot 0.34 $, perp
# 104.84 $): never traded, whatever «Макс. расхождение» says.
HARD_MAX_GAP_PCT = 20.0
# Right before an order: the perp leg may not be worth more than the trade amount × this (same coins on both legs).
MAX_LEG_RATIO = 1.25
def busy_elsewhere(base: str, me) -> str:
"""Name of another spot–futures engine where this coin is already in a trade (or being entered), "" if none:
one coin is never traded twice at the same time, whichever exchange or mode."""
for e in list(ENGINES):
if e is me:
continue
if any(p.base == base for p in list(e.positions)) or base in getattr(e, "opening", set()):
return getattr(getattr(e, "venue", None), "name", None) or "Между биржами"
return ""
def live_client(exchange: str):
import live
return live.client(exchange)
def entry_depth(p: Pair) -> float | None:
"""$ available at the entry prices on both legs (spot ask, perp bid); None when either is not reported."""
known = [v for v in (p.spot_ask_usd, p.fut_bid_usd) if v is not None]
return min(known) if len(known) == 2 else None
def depth_ok(p: Pair, s: BasisSettings) -> bool:
need = max(s.amount, s.min_depth)
return all(v is None or v >= need for v in (p.spot_ask_usd, p.fut_bid_usd))
def in_universe(p: Pair, s: BasisSettings) -> bool:
if s.all_coins:
return True
return ((s.use_new and p.age_days is not None and p.age_days <= s.new_days)
or (s.use_innovation and p.innovation) or (s.use_memes and p.meme))
class BasisEngine:
def __init__(self, venue_key: str = "bybit", data_dir: Path = DATA_DIR, start: bool = True) -> None:
self.key = venue_key
self.venue = VENUES[venue_key]()
self.file = data_dir / f"basis_{venue_key}.json"
self.lock = threading.RLock()
self.settings = BasisSettings(spot_fee=self.venue.spot_fee, fut_fee=self.venue.fut_fee,
fut_fee_innovation=self.venue.innovation_fee)
self.positions: list[Position] = []
self.trades: list[Trade] = []
self.next_uid = 1
self.last_close: dict[str, float] = {}
self.pairs: dict[str, Pair] = {}
self.memes: set[str] = set(MEME_FALLBACK)
self.memes_source = "встроенный список"
self.status, self.updated, self.cycle_ms = "загружаю…", 0.0, 0
self.message = ""
self.opening: set[str] = set() # coins with a real entry in progress
self.jobs: queue.Queue = queue.Queue() # real orders, sent one by one from a worker thread
self.client_for = live_client
self.busy: set[int] = set() # real positions whose close is being sent right now
self.real_block: dict[str, tuple[str, float]] = {} # coin → (why it cannot be traded for real, until)
self.real_pause_until, self.real_pause_reason = 0.0, "" # the whole exchange (e.g. balance too small)
self.pending: dict[str, dict] = {} # coin → real entry in progress (written BEFORE the spot is bought)
self.recover: set[str] = set() # pending entries found after a restart: adopt what was bought
self.adopting: set[str] = set() # coins being taken over from the spot balance right now
self.tp_checked: dict[int, float] = {} # position → when its TP on the exchange was last looked at
self.tp_tried: set[int] = set() # positions a TP was tried for in this run
self.fast_seen: dict[str, float] = {} # coin → when the fast watch last priced it
self.fast_ms = 0 # how long the last fast look took
self._load()
if start:
threading.Thread(target=self._loop, daemon=True).start()
threading.Thread(target=self._memes_loop, daemon=True).start()
threading.Thread(target=self._worker, daemon=True).start()
threading.Thread(target=self._fast_loop, daemon=True).start()
ENGINES.append(self)
# --- persistence ---------------------------------------------------------------------------
def _load(self) -> None:
try:
d = json.loads(self.file.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
known = {f.name for f in fields(BasisSettings)}
for k, v in (d.get("settings") or {}).items():
if k in known:
setattr(self.settings, k, type(getattr(self.settings, k))(v))
self.settings.exchange_tp = False # no TP orders on the exchange any more: the program closes by itself
self.settings.max_gap_pct = min(self.settings.max_gap_pct, HARD_MAX_GAP_PCT)
self.positions = [Position(**p) for p in d.get("positions", [])]
self.trades = [Trade(**t) for t in d.get("trades", [])]
self.next_uid = d.get("next_uid", 1)
# entries that were in progress when the program stopped: the coins may be on the spot account now
self.recover = set(d.get("pending") or {})
def save(self) -> None:
self.file.parent.mkdir(exist_ok=True)
data = {"settings": asdict(self.settings), "positions": [asdict(p) for p in self.positions],
"trades": [asdict(t) for t in self.trades[-KEEP_TRADES:]], "next_uid": self.next_uid,
"pending": self.pending}
tmp = self.file.with_suffix(".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(self.file)
def set_settings(self, values: dict) -> str:
with self.lock:
for f in fields(BasisSettings):
if f.name not in values:
continue
try:
v = values[f.name]
v = (v in (True, "true", "1", 1, "on")) if f.type in ("bool", bool) else type(getattr(self.settings, f.name))(float(v))
except (TypeError, ValueError):
return f"неверное значение: {f.name}"
setattr(self.settings, f.name, v)
s = self.settings
if s.amount <= 0 or s.max_positions < 0:
return "сумма и число позиций должны быть больше 0"
if s.max_gap_pct > HARD_MAX_GAP_PCT:
s.max_gap_pct = HARD_MAX_GAP_PCT
self.save()
return (f"«Макс. расхождение» не может быть больше {HARD_MAX_GAP_PCT:g}%: такая разница — это разные "
f"инструменты под одним тикером, а не премия. Установлено {HARD_MAX_GAP_PCT:g}%, остальное сохранено")
if s.min_gap_pct <= s.exit_gap_pct:
return "разница для входа должна быть больше разницы для выхода"
if set(values) - {"running"}:
# new settings (a bigger amount, a topped-up account…): coins and the exchange are checked anew
self.real_block.clear()
self.real_pause_until, self.real_pause_reason = 0.0, ""
self.save()
return ""
# --- data ----------------------------------------------------------------------------------
def _memes_loop(self) -> None:
while True:
got: set[str] = set()
try:
for page in (1, 2, 3, 4):
req = urllib.request.Request(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=meme-token"
f"&per_page=250&page={page}", headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=30) as resp:
items = json.loads(resp.read())
got |= {x["symbol"].upper() for x in items}
if len(items) < 250:
break
time.sleep(8)
except Exception:
pass
if len(got) > 100:
self.memes, self.memes_source = got | MEME_FALLBACK, f"CoinGecko meme-token ({len(got)})"
time.sleep(MEMES_S)
else:
time.sleep(600)
def _loop(self) -> None:
while True:
start = time.time()
try:
pairs = self.venue.pairs(self.memes)
with self.lock:
fresh_now = time.time()
new = {p.base: p for p in pairs}
for b, seen in self.fast_seen.items(): # the fast watch's prices are newer than this list
if b in new and b in self.pairs and fresh_now - seen < 2.0:
new[b] = self.pairs[b]
self.pairs = new
self.updated, self.cycle_ms = time.time(), int((time.time() - start) * 1000)
self.status = "ok"
self.step(self.updated)
except Exception as exc:
self.status = f"нет данных: {exc}"
time.sleep(max(0.2, POLL_S - (time.time() - start)))
# --- trading -------------------------------------------------------------------------------
def candidates(self) -> list[Pair]:
s = self.settings
return [p for p in self.pairs.values() if in_universe(p, s)
and min(p.spot_turnover, p.fut_turnover) >= s.min_turnover]
def step(self, now: float) -> None:
"""Exits first (gap closed, stop, time), funding on the shorts, then new entries."""
s = self.settings
changed = False
for base in list(self.recover):
# an entry cut off by a stop of the program: whatever spot it bought becomes a position again
if base in self.pairs and base not in self.opening:
self.opening.add(base)
self.recover.discard(base)
self.jobs.put(("adopt", base))
changed = self._check_exits(now)
# real: one entry at a time (never two buys in parallel), and no more open real positions than allowed
real_busy = s.real and (self.opening or self.adopting or now < self.real_pause_until
or sum(pos.real for pos in self.positions) >= max(1, s.max_real_positions))
if s.running and not real_busy: # real: the next trade only after the previous is confirmed closed
changed = self._entries(now) or changed
if changed:
self.save()
def _check_exits(self, now: float) -> bool:
"""Every open position against the latest prices: funding, then the exit rules. Called by the market cycle
AND by the fast watch of open positions (several times a second) — the program, not a TP on the exchange,
decides the close, whichever way the gap converges."""
s = self.settings
changed = False
for pos in list(self.positions):
p = self.pairs.get(pos.base)
if p is None:
continue
if pos.real and pos.short_pending:
# spot held without its hedge: open the short (retried while the exchange refuses); no auto exit —
# the gap logic needs both legs; «×» sells the spot
if pos.uid not in self.busy and now >= pos.retry_at:
self.busy.add(pos.uid)
self.jobs.put(("short", pos.uid))
continue
while pos.next_funding and now >= pos.next_funding:
pos.funding += pos.qty * (p.fut_bid + p.fut_ask) / 2 * p.funding # short receives positive funding
pos.next_funding = p.next_funding if p.next_funding > pos.next_funding else pos.next_funding + p.interval_h * 3600
changed = True
gap = p.exit_gap
reason = ("разница сошлась" if gap <= s.exit_gap_pct
else "стоп: разница расширилась" if s.stop_gap_pct > 0 and gap >= s.stop_gap_pct
else "время удержания" if s.max_hold_hours > 0 and now - pos.opened >= s.max_hold_hours * 3600
else "")
if pos.real and pos.closing == "fut_done" and now >= pos.retry_at:
reason = reason or "продажа спота после выкупа шорта"
if reason:
if pos.real:
if pos.uid not in self.busy and now >= pos.retry_at:
self.busy.add(pos.uid)
self.jobs.put(("close", pos.uid, reason))
else:
self._close(pos, p, now, reason)
changed = True
elif pos.real and pos.tp_order and not pos.closing and pos.uid not in self.busy:
self.busy.add(pos.uid) # a TP left on the exchange by the older version: remove it
self.jobs.put(("untp", pos.uid))
return changed
def _entries(self, now: float) -> bool:
s = self.settings
changed = False
if True:
busy = {pos.base for pos in self.positions} | self.opening
for p in sorted(self.candidates(), key=lambda p: -p.entry_gap):
if len(self.positions) + len(self.opening) >= s.max_positions:
break
if p.base in busy or now - self.last_close.get(p.base, 0) < s.cooldown_s:
continue
if busy_elsewhere(p.base, self):
continue # the same coin is already in a trade on another exchange / mode
if not (s.min_gap_pct <= p.entry_gap <= min(s.max_gap_pct, HARD_MAX_GAP_PCT)):
continue
if not depth_ok(p, s):
continue
if self._too_small(p):
continue # paper too: only trades the exchange would accept on both legs
if s.real and self.real_block.get(p.base, ("", 0.0))[1] > now:
continue # known: cannot be traded for real (lot too big for the amount…)
if s.real:
self.opening.add(p.base)
self.jobs.put(("open", p, s.amount))
break # one real trade at a time
qty = s.amount / p.spot_ask
inno = self._innovation(p)
self.positions.append(Position(self.next_uid, p.base, now, qty, p.spot_ask, p.fut_bid, p.entry_gap,
entry_fees(qty, p.spot_ask, p.fut_bid, s, inno), p.next_funding,
innovation=inno))
self.next_uid += 1
busy.add(p.base)
changed = True
return changed
# --- fast watch of open positions ------------------------------------------------------------------------
FAST_S = 0.25 # target pause between two looks at the open positions' prices
def _fast_loop(self) -> None:
"""While positions are open: their spot and perp best prices, several times a second (one symbol each,
kept-alive connections), and the exit rules on those fresh prices."""
import dataclasses
import fastquote
pool = ThreadPoolExecutor(max_workers=8)
while True:
start = time.time()
with self.lock:
watch = {pos.base: self.pairs[pos.base] for pos in self.positions
if pos.base in self.pairs and not pos.short_pending}
if not watch:
time.sleep(0.5)
continue
ex = self.venue.name
jobs = {b: (pool.submit(fastquote.spot_top, ex, p.spot_symbol), pool.submit(fastquote.fut_top, ex, p.fut_symbol))
for b, p in watch.items()}
fresh = {}
for b, (sj, fj) in jobs.items():
try:
sb, sa, sbu, sau = sj.result()
fb, fa, fbu, fau = fj.result()
except Exception:
continue
p, m = watch[b], watch[b].mult
if min(sb, sa, fb, fa) <= 0:
continue
fresh[b] = dataclasses.replace(p, spot_bid=sb, spot_ask=sa, fut_bid=fb / m, fut_ask=fa / m,
spot_bid_usd=sbu, spot_ask_usd=sau,
fut_bid_usd=fbu if fbu is not None else p.fut_bid_usd,
fut_ask_usd=fau if fau is not None else p.fut_ask_usd)
if fresh:
now = time.time()
with self.lock:
self.pairs.update(fresh)
for b in fresh:
self.fast_seen[b] = now
self.fast_ms = int((now - start) * 1000)
if self._check_exits(now):
self.save()
time.sleep(max(0.05, self.FAST_S - (time.time() - start)))
def _min_entry(self, p: Pair) -> dict | None:
"""The smallest amount both the spot buy and the perp short of this coin accept (exchange rules)."""
import minorder
return minorder.RULES.min_entry(self.venue.name, p.base, p.spot_ask, self.venue.name, p.fut_symbol, p.fut_bid,
self.settings.spot_fee)
def _too_small(self, p: Pair) -> str:
import minorder
return minorder.too_small(self.settings.amount, self._min_entry(p), self.venue.name, self.venue.name)
def _innovation(self, p: Pair) -> bool:
"""The coin's perp pays the Innovation Zone rate (Bybit only: other exchanges' «new» label is no fee group)."""
return bool(p.innovation and self.venue.innovation_fee)
def _fut_rate(self, p: Pair | None) -> float:
return fut_rate(self.settings, bool(p) and self._innovation(p))
def _close(self, pos: Position, p: Pair, now: float, reason: str) -> Trade:
spot_pnl, fut_pnl, fees, net = close_result(pos, p.spot_bid, p.fut_ask, self.settings)
t = Trade(pos.uid, pos.base, pos.opened, now, pos.qty, pos.spot_entry, p.spot_bid, pos.fut_entry, p.fut_ask,
pos.entry_gap, p.exit_gap, spot_pnl, fut_pnl, fees, pos.funding, net, reason,
pos.qty * pos.spot_entry)
self.positions.remove(pos)
self.trades.append(t)
self.last_close[pos.base] = now
return t
def close(self, uid: int | None) -> str:
with self.lock:
n = real = 0
for pos in list(self.positions):
if uid is not None and pos.uid != uid:
continue
if pos.real:
if pos.uid not in self.busy:
self.busy.add(pos.uid)
pos.retry_at = 0.0
self.jobs.put(("close", pos.uid, "вручную"))
real += 1
continue
p = self.pairs.get(pos.base)
if p is None:
continue
self._close(pos, p, time.time(), "вручную")
n += 1
self.save()
return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "")
# --- real orders (worker thread; never under the engine lock while waiting for the exchange) -----------------
def _journal(self, coin: str, action: str, ok: bool, text: str, **extra) -> None:
import real_mirror
real_mirror.journal("basis", self.key, coin, action, ok, text, **extra)
def _worker(self) -> None:
while True:
kind, *args = self.jobs.get()
try:
if kind == "open":
self._real_open(*args)
elif kind == "close":
self._real_close(*args)
elif kind == "short":
self._real_short(*args)
elif kind == "watch":
self._watch_tp(*args)
elif kind == "untp":
self._remove_tp(*args)
elif kind == "tp":
pos = next((x for x in self.positions if x.uid == args[0]), None)
if pos is not None and not pos.tp_order:
self._place_tp(self.client_for(self.key), pos)
elif kind == "adopt":
msg = self.adopt(args[0])
if "подхвачено" not in msg:
self._journal(args[0], "open", True, f"после перезапуска: незавершённый вход — {msg}")
except Exception as exc: # the worker must survive anything
self._journal(getattr(args[0], "base", "?") if args else "?", kind, False, f"сбой: {exc}")
if kind == "open" and args:
with self.lock:
self.opening.discard(args[0].base)
finally:
if kind in ("close", "short", "watch", "tp", "untp") and args:
with self.lock:
self.busy.discard(args[0])
if kind == "open" and args and args[0].base in self.pending:
with self.lock: # the entry is finished (position, sold back or refused)
self.pending.pop(args[0].base, None)
self.save()
if kind == "adopt" and args:
with self.lock:
self.recover.discard(args[0])
self.opening.discard(args[0])
self.pending.pop(args[0], None)
self.save()
SHORT_RETRY_S = 300.0
def _real_short(self, uid: int) -> None:
"""Open the missing perp short for a held spot leg (the same coins, rounded down to the lot)."""
import live
with self.lock:
pos = next((x for x in self.positions if x.uid == uid), None)
p = self.pairs.get(pos.base) if pos else None
if pos is None or not pos.short_pending or p is None:
return
fut = None
try:
c = self.client_for(self.key)
coins = c.fut_round(pos.fut_symbol, pos.spot_qty)
if coins <= 0:
raise live.LiveError(f"монет {pos.spot_qty:g} меньше минимального лота фьючерса")
if coins * p.fut_bid > pos.spot_qty * pos.spot_entry * MAX_LEG_RATIO:
raise live.LiveError(f"шорт стоил бы {coins * p.fut_bid:.2f} $ при споте на "
f"{pos.spot_qty * pos.spot_entry:.2f} $ — разные инструменты под одним тикером")
if self.settings.auto_transfer:
try: # margin for the short, from the spot USDT if needed
moved = live.ensure_usdt(c, 0.0, coins * p.fut_bid * 1.03)
if moved:
self._journal(pos.base, "transfer", True, moved)
except (live.LiveError, AttributeError) as exc:
self._journal(pos.base, "transfer", False, f"перевод не удался: {exc}")
fut = c.fut_order(pos.fut_symbol, "sell", coins, reduce_only=False)
except live.LiveError as exc:
if getattr(exc, "sent", False):
fut = None # may be open: the position check decides
try:
held = -c.fut_position(pos.fut_symbol)
except live.LiveError:
held = 0.0
if held > 0:
fut = live.Fill(held, p.fut_bid, held * p.fut_bid * self._fut_rate(p) / 100, exc.order_id,
exact=False)
if fut is None:
with self.lock:
changed = pos.error != f"шорт не открыт: {exc}"
pos.error, pos.retry_at = f"шорт не открыт: {exc}", time.time() + self.SHORT_RETRY_S
self.save()
if changed:
self._journal(pos.base, "open", False, f"шорт не открыт: {exc} — спот {pos.spot_qty:g} держится "
f"без хеджа, повтор через {self.SHORT_RETRY_S / 60:.0f} мин (× у позиции — продать спот)")
self._pause_if_balance(str(exc))
return
with self.lock:
pos.qty, pos.fut_entry, pos.short_pending, pos.error = fut.coins, fut.price, False, ""
pos.fees += fut.fee_usd
pos.entry_gap = (fut.price / pos.spot_entry - 1) * 100
pos.next_funding = p.next_funding
pos.exact = pos.exact and fut.exact
self.save()
self._journal(pos.base, "open", True, f"шорт к споту открыт: {fut.coins:g} по {fut.price:.10g}, разница к цене "
f"покупки спота {pos.entry_gap:+.3f}% — дальше обычное закрытие при схождении")
self._place_tp(c, pos)
def adopt(self, base: str, price: float | None = None, fee_usd: float | None = None) -> str:
"""Take coins that are on the spot account into the program as a real position (spot leg; the short is
opened next). `price` — what they were bought at (from the exchange's history), else the current ask."""
import live
base = base.upper().strip()
with self.lock:
p = self.pairs.get(base)
if any(pos.base == base and pos.real for pos in self.positions):
return f"{base} уже ведётся программой"
if p is not None:
self.adopting.add(base) # «busy» for the entry logic while the balance is read
if p is None:
return f"{base}: нет пары спот + фьючерс на {self.venue.name}"
try:
free = self.client_for(self.key).spot_free(base)
except live.LiveError as exc:
with self.lock:
self.adopting.discard(base)
return f"не удалось прочитать баланс: {exc}"
if free * p.spot_bid < 1.0:
with self.lock:
self.adopting.discard(base)
return f"на споте нет {base} (свободно {free:g})"
price = price or p.spot_ask
fee = fee_usd if fee_usd is not None else free * price * self.settings.spot_fee / 100
with self.lock:
pos = Position(self.next_uid, base, time.time(), 0.0, price, 0.0, 0.0, fee, p.next_funding, real=True,
spot_qty=free, fut_symbol=p.fut_symbol, short_pending=True,
error="подхвачена с баланса: шорт ещё не открыт", innovation=self._innovation(p))
self.next_uid += 1
self.positions.append(pos)
self.adopting.discard(base)
self.save()
self._journal(base, "open", True, f"подхвачено со спота {free:g} {base} по {price:.10g} — открываю шорт")
return f"{base}: подхвачено {free:g} монет, шорт откроется следующим шагом"
def _real_open(self, p: Pair, amount: float) -> None:
import live
notes = []
# BEFORE buying anything: can the perp be shorted for this amount at all (its minimum lot)?
try:
c = self.client_for(self.key)
min_coins = c.fut_min_coins(p.fut_symbol)
except (live.LiveError, AttributeError) as exc:
self._not_tradable(p.base, f"нет правил контракта: {exc}", 300)
return
coins_est = amount / p.spot_ask * (1 - self.settings.spot_fee / 100)
if not self._legs_match(p, coins_est, amount):
return
if coins_est < min_coins:
need = min_coins * p.spot_ask / (1 - self.settings.spot_fee / 100) * 1.02
self._not_tradable(p.base, f"сумма {amount:g} $ меньше минимального лота фьючерса ({min_coins:g} монет ≈ "
f"{need:.2f} $)", 1800)
return
with self.lock:
# last check right before money is spent: no other entry in progress, the limit of real positions kept
held = [x.base for x in self.positions if x.real]
if (p.base in held or self.adopting or self.opening - {p.base} or busy_elsewhere(p.base, self)
or len(held) >= max(1, self.settings.max_real_positions)):
self.opening.discard(p.base)
return
self.pending[p.base] = {"time": time.time(), "amount": amount} # a stop now: found again at start
self.save()
# money where it is needed: the amount on spot for the buy, the same on futures for the short's margin
# (leverage 1 assumed — the safe side); moved from the other account when one of them is short
if self.settings.auto_transfer:
try:
moved = live.ensure_usdt(c, amount * 1.01, amount * 1.03)
if moved:
self._journal(p.base, "transfer", True, moved)
except (live.LiveError, AttributeError) as exc:
if "в сумме" in str(exc):
self._journal(p.base, "open", False, f"не открываю: {exc} — спот не покупался")
self._pause_if_balance(str(exc))
with self.lock:
self.opening.discard(p.base)
return
self._journal(p.base, "transfer", False, f"перевод не удался: {exc} — пробую без него")
if self.settings.entry_limit:
self._open_limit_first(c, p, amount)
return
try:
buy = c.spot_buy(p.base, amount)
except live.LiveError as exc:
# accepted but not confirmed: what is on the account decides whether the coin was bought
bought = 0.0
if getattr(exc, "sent", False):
try:
bought = min(c.spot_free(p.base), amount / p.spot_ask * 1.02)
except live.LiveError:
bought = 0.0
if bought <= 0:
self._journal(p.base, "open", False, f"покупка на споте: {exc}")
with self.lock:
self.opening.discard(p.base)
self.last_close[p.base] = time.time() # pause before trying this coin again
self._pause_if_balance(str(exc))
return
buy = live.Fill(bought, p.spot_ask, amount * self.settings.spot_fee / 100, exc.order_id)
notes.append("покупка не подтверждена биржей — цена оценочная")
try:
free = c.spot_free(p.base)
except live.LiveError:
free = 0.0
held = min(buy.coins, free) if free > 0 else buy.coins * (1 - self.settings.spot_fee / 100)
fut, failure, coins = None, "", 0.0
try:
coins = c.fut_round(p.fut_symbol, held)
if coins <= 0:
raise live.LiveError("монет меньше минимального лота фьючерса")
fut = c.fut_order(p.fut_symbol, "sell", coins, reduce_only=False)
except live.LiveError as exc:
failure = str(exc)
if getattr(exc, "sent", False) and coins > 0:
# the short may be open: keep the position (estimated price) — closing it is reduce-only
fut = live.Fill(coins, p.fut_bid, coins * p.fut_bid * self._fut_rate(p) / 100, exc.order_id)
notes.append("шорт не подтверждён биржей — проверьте позицию, цена оценочная")
if fut is None:
# no hedge → sell the spot back at once
try:
back = c.spot_sell(p.base, held)
text = f"шорт не открылся ({failure}); спот продан обратно по {back.price:.10g}"
except live.LiveError as exc2:
text = f"шорт не открылся ({failure}); СПОТ НЕ ПРОДАН ({exc2}) — продайте {held:g} {p.base} вручную"
self._journal(p.base, "open", False, text)
with self.lock:
self.opening.discard(p.base)
self.last_close[p.base] = time.time()
self._pause_if_balance(failure)
return
with self.lock:
self.opening.discard(p.base)
pos = Position(self.next_uid, p.base, time.time(), fut.coins, buy.price, fut.price,
(fut.price / buy.price - 1) * 100, buy.fee_usd + fut.fee_usd, p.next_funding,
real=True, spot_qty=held, fut_symbol=p.fut_symbol, error="; ".join(notes),
exact=buy.exact and fut.exact and not notes, innovation=self._innovation(p))
self.next_uid += 1
self.positions.append(pos)
self.save()
self._journal(p.base, "open", True, f"куплено {held:g} по {buy.price:.10g}, шорт {fut.coins:g} по "
f"{fut.price:.10g}, разница {pos.entry_gap:+.3f}%" + (f" ({'; '.join(notes)})" if notes else ""),
amount=amount)
self._place_tp(c, pos)
def _open_limit_first(self, c, p: Pair, amount: float) -> None:
"""Entry with a LIMIT short at the signal's perp bid, kept up to `limit_hold_s` seconds; whatever part of it
fills is hedged at once by buying the same coins on spot. Nothing filled → the order is removed, no spot."""
import live
s = self.settings
coins = c.fut_round(p.fut_symbol, amount / p.spot_ask * (1 - s.spot_fee / 100))
if not self._legs_match(p, coins, amount):
return
try:
oid = c.fut_limit(p.fut_symbol, "sell", coins, p.fut_bid)
except (live.LiveError, AttributeError) as exc:
self._journal(p.base, "open", False, f"лимитный шорт не выставлен: {exc}")
with self.lock:
self.opening.discard(p.base)
self.last_close[p.base] = time.time()
self._pause_if_balance(str(exc))
return
st = {"coins": 0.0, "price": 0.0, "fee": 0.0, "final": False}
end = time.time() + max(0.0, s.limit_hold_s)
while True: # one look a second: the exchange's request limit
try:
st = c.fut_order_status(p.fut_symbol, oid)
except live.LiveError:
pass
if st["final"] or st["coins"] >= coins * 0.999 or time.time() >= end:
break
time.sleep(1.0)
if not st["final"]:
try:
c.fut_cancel(p.fut_symbol, oid)
except live.LiveError:
pass
try: # what filled until the cancel
st = c.fut_order_status(p.fut_symbol, oid)
except live.LiveError:
try:
st = {**st, "coins": max(0.0, -c.fut_position(p.fut_symbol))}
except live.LiveError:
pass
shorted = st["coins"]
if shorted <= 0:
self._journal(p.base, "open", False, f"лимитный шорт по {p.fut_bid:.10g} не исполнился за "
f"{s.limit_hold_s:g} с — снят, спот не покупался")
with self.lock:
self.opening.discard(p.base)
self.last_close[p.base] = time.time()
return
fut_price = st["price"] or p.fut_bid
# hedge: the same coins on spot (the buy fee is taken in coins: a little more USDT)
try:
buy = c.spot_buy(p.base, shorted * p.spot_ask * (1 + s.spot_fee / 100) * 1.003)
except live.LiveError as exc:
try:
c.fut_order(p.fut_symbol, "buy", shorted, reduce_only=True)
text = f"шорт {shorted:g} исполнился, но спот не куплен ({exc}); шорт закрыт"
except live.LiveError as exc2:
text = f"шорт {shorted:g} исполнился, спот не куплен ({exc}); ШОРТ НЕ ЗАКРЫТ ({exc2}) — закройте вручную"
self._journal(p.base, "open", False, text)
with self.lock:
self.opening.discard(p.base)
self.last_close[p.base] = time.time()
self._pause_if_balance(str(exc))
return
try:
free = c.spot_free(p.base)
except live.LiveError:
free = 0.0
held = min(buy.coins, free) if free > 0 else buy.coins * (1 - s.spot_fee / 100)
with self.lock:
self.opening.discard(p.base)
pos = Position(self.next_uid, p.base, time.time(), shorted, buy.price, fut_price,
(fut_price / buy.price - 1) * 100, buy.fee_usd + st["fee"], p.next_funding,
real=True, spot_qty=held, fut_symbol=p.fut_symbol, exact=buy.exact,
innovation=self._innovation(p))
self.next_uid += 1
self.positions.append(pos)
self.save()
self._journal(p.base, "open", True, f"лимитный шорт {shorted:g} по {fut_price:.10g} (заявка {p.fut_bid:.10g}), "
f"спот куплен {held:g} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}%", amount=amount)
self._place_tp(c, pos)
def _place_tp(self, c, pos: Position) -> None:
"""TP on the exchange: a reduce-only LIMIT buy of the short at the price where the gap has closed against
the spot bought (perp = spot entry + «Закрыть при»). When it fills, the program sells the spot."""
import live
if not self.settings.exchange_tp or pos.qty <= 0:
return
tp = pos.spot_entry * (1 + self.settings.exit_gap_pct / 100)
if tp >= pos.fut_entry:
return # the gap is already as small as the exit level
try:
oid = c.fut_take_profit(pos.fut_symbol, "buy", pos.qty, tp)
except (live.LiveError, AttributeError) as exc:
self._journal(pos.base, "open", False, f"TP на бирже не выставлен: {exc} — закрытие по схождению программой")
return
with self.lock:
pos.tp_order, pos.tp_price = str(oid), tp
self.save()
self._journal(pos.base, "open", True, f"TP на бирже: выкуп шорта лимитом по {tp:.10g} "
f"({(tp / pos.fut_entry - 1) * 100:+.3f}% от входа)")
def _remove_tp(self, uid: int) -> None:
"""Take a TP order off the exchange (the program watches the gap itself now). If it filled meanwhile, the
position is closed through the usual path, which counts what the TP bought back."""
import live
with self.lock:
pos = next((x for x in self.positions if x.uid == uid), None)
if pos is None or not pos.tp_order or pos.closing:
return
c = self.client_for(self.key)
try:
c.fut_cancel(pos.fut_symbol, pos.tp_order)
except (live.LiveError, AttributeError):
pass
try:
filled = c.fut_order_status(pos.fut_symbol, pos.tp_order)["coins"]
except (live.LiveError, AttributeError):
filled = 0.0
if filled > 0:
self._real_close(uid, "TP на бирже исполнился до снятия")
return
with self.lock:
pos.tp_order, pos.tp_price = "", 0.0
self.save()
self._journal(pos.base, "open", True, "TP на бирже снят — закрытие решает программа по свежим ценам")
WATCH_TP_S = 3.0
def _watch_tp(self, uid: int) -> None:
"""Has the TP on the exchange bought the short back? Then the spot is sold now (via the usual close)."""
import live
with self.lock:
pos = next((x for x in self.positions if x.uid == uid), None)
if pos is None or not pos.tp_order or pos.closing:
return
try:
held = self.client_for(self.key).fut_position(pos.fut_symbol)
except live.LiveError:
return
if held > -pos.qty * 1e-6: # no short left: the TP has filled
self._real_close(uid, "TP на бирже")
def _legs_match(self, p: Pair, coins: float, amount: float) -> bool:
"""Last guard before an order: the same coins on spot and perp must be worth about the same. A perp leg
worth far more than the amount means two different instruments under one ticker — no order at all."""
fut_value = coins * p.fut_bid
if p.entry_gap > HARD_MAX_GAP_PCT or fut_value > amount * MAX_LEG_RATIO:
self._not_tradable(p.base, f"шорт {coins:g} монет стоил бы {fut_value:.2f} $ при сумме {amount:g} $ — "
f"спот и фьючерс под этим тикером разные инструменты", 86400)
return False
return True
def _not_tradable(self, base: str, why: str, seconds: float) -> None:
"""The coin cannot be traded for real now: skip it (no spot bought) and say why in the table, once."""
with self.lock:
known = self.real_block.get(base, ("", 0.0))[0] == why
self.real_block[base] = (why, time.time() + seconds)
self.opening.discard(base)
if not known:
self._journal(base, "open", False, f"не открываю: {why} — спот не покупался")
BALANCE_PAUSE_S = 900.0
def _pause_if_balance(self, error: str) -> None:
"""Not enough money on the account (MEXC 2005 «Balance insufficient», …): no real entries on this exchange
for a while — every new try would only buy the spot and sell it back."""
if any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно", "не хватает")):
with self.lock:
self.real_pause_until = time.time() + self.BALANCE_PAUSE_S
self.real_pause_reason = ("не хватает баланса на бирже — пополните счёт (фьючерсы и спот) "
"или уменьшите «Сумму сделки»")
self._journal("—", "open", False, f"{self.real_pause_reason}; реальные входы на паузе 15 мин")
def _real_close(self, uid: int, reason: str) -> None:
import live
with self.lock:
pos = next((x for x in self.positions if x.uid == uid), None)
if pos is None:
return
stage = "выкуп шорта"
try:
c = self.client_for(self.key)
if pos.qty <= 0 and pos.closing != "fut_done":
with self.lock: # no short was ever opened: only the spot is sold
pos.closing, pos.fut_exit = "fut_done", pos.fut_entry
self.save()
# 1) buy the short back (reduce-only: it can never open anything); what the TP on the exchange has
# already bought back counts, the rest is bought at market
if pos.closing != "fut_done":
tp_coins = tp_price = tp_fee = 0.0
if pos.tp_order:
try:
c.fut_cancel(pos.fut_symbol, pos.tp_order)
except (live.LiveError, AttributeError):
pass # already filled or gone
try:
st = c.fut_order_status(pos.fut_symbol, pos.tp_order)
tp_coins, tp_price, tp_fee = st["coins"], st["price"], st["fee"]
except (live.LiveError, AttributeError):
pass
with self.lock:
pos.tp_order = ""
self.save()
rest = pos.qty - tp_coins
fut_coins, fut_price, fut_fee, exact = 0.0, 0.0, 0.0, True
if rest > pos.qty * 1e-6:
try:
fut = c.fut_order(pos.fut_symbol, "buy", rest, reduce_only=True)
fut_coins, fut_price, fut_fee, exact = fut.coins, fut.price, fut.fee_usd, fut.exact
except live.LiveError as exc:
if not getattr(exc, "sent", False):
raise
p = self.pairs.get(pos.base) # accepted, not confirmed: the position check decides
fut_coins, fut_price = rest, (p.fut_ask if p else pos.fut_entry)
fut_fee, exact = rest * fut_price * fut_rate(self.settings, pos.innovation) / 100, False
done = tp_coins + fut_coins
avg = (tp_coins * tp_price + fut_coins * fut_price) / done if done else pos.fut_entry
with self.lock:
pos.fut_exit, pos.exit_fees, pos.closing = avg, tp_fee + fut_fee, "fut_done"
pos.exact = pos.exact and exact
self.save()
# 2) the exchange must show no short left; a remainder is bought back too
stage = "проверка фьючерса"
held = c.fut_position(pos.fut_symbol) if pos.qty > 0 else 0.0
if held < -1e-12:
c.fut_order(pos.fut_symbol, "buy", -held, reduce_only=True)
raise live.LiveError(f"на фьючерсе оставалось {held:+g} — докуплено, проверяю ещё раз")
# 3) sell the coins this trade bought (never more: other coins on the account are not ours)
stage = "продажа спота"
p = self.pairs.get(pos.base)
price_now = p.spot_bid if p else pos.spot_entry
left = pos.spot_qty - pos.sold_coins
if left * price_now > 1.0: # more than dust left to sell
free = c.spot_free(pos.base)
if free * price_now > 1.0:
sell = c.spot_sell(pos.base, min(free, left))
with self.lock:
pos.sold_coins += sell.coins
pos.sold_value += sell.coins * sell.price
pos.sold_fees += sell.fee_usd
pos.exact = pos.exact and sell.exact
self.save()
left = pos.spot_qty - pos.sold_coins
if left * price_now > 1.0 and c.spot_free(pos.base) * price_now > 1.0:
raise live.LiveError(f"на споте ещё {left:g} {pos.base} — продам при следующей попытке")
if pos.sold_coins <= 0:
raise live.LiveError("спот не продан")
except live.LiveError as exc:
with self.lock:
pos.retry_at, pos.error = time.time() + 15, f"{stage}: {exc}"
self.save()
self._journal(pos.base, "close", False, f"{stage}: {exc} — следующая сделка не откроется, пока эта не "
f"закрыта; повтор через 15 с")
return
with self.lock:
now = time.time()
sell_price = pos.sold_value / pos.sold_coins
spot_pnl = pos.sold_value - pos.sold_coins * pos.spot_entry
fut_pnl = pos.qty * (pos.fut_entry - pos.fut_exit)
fees = pos.fees + pos.exit_fees + pos.sold_fees
net = spot_pnl + fut_pnl - fees + pos.funding
t = Trade(pos.uid, pos.base, pos.opened, now, pos.qty, pos.spot_entry, sell_price, pos.fut_entry,
pos.fut_exit, pos.entry_gap, (pos.fut_exit / sell_price - 1) * 100 if pos.qty > 0 else 0.0,
spot_pnl, fut_pnl, fees,
pos.funding, net, f"{reason} (реально{'' if pos.exact else ', часть цифр оценочная'})",
pos.spot_qty * pos.spot_entry, real=True, exact=pos.exact)
if pos in self.positions:
self.positions.remove(pos)
self.trades.append(t)
self.last_close[pos.base] = now
self.save()
self._journal(pos.base, "close", True, f"шорт выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет), спот "
f"продан по {sell_price:.10g}, итог {net:+.4f} $, комиссии {fees:.4f} $ ({reason})", net=net)
def reset(self) -> str:
with self.lock:
if any(p.real for p in self.positions):
return "есть открытые реальные позиции — сначала закройте их"
self.positions, self.trades, self.last_close = [], [], {}
self.save()
return "статистика сброшена"
# --- view ----------------------------------------------------------------------------------
def view(self) -> dict:
with self.lock:
s = self.settings
now = time.time()
rows = []
real_open = [x.base for x in self.positions if x.real]
for p in self.candidates():
m = self._min_entry(p)
import minorder
small = minorder.too_small(s.amount, m, self.venue.name, self.venue.name)
fits = (s.min_gap_pct <= p.entry_gap <= min(s.max_gap_pct, HARD_MAX_GAP_PCT) and depth_ok(p, s)
and not small)
# why this coin is not entered now — shown in the table instead of an empty cell
elsewhere = busy_elsewhere(p.base, self)
why = (f"разница больше {HARD_MAX_GAP_PCT:g}% — это разные инструменты под одним тикером, не торгуется"
if p.entry_gap > HARD_MAX_GAP_PCT
else f"уже в сделке: {elsewhere}" if elsewhere
else "разница ниже «Мин. расхождения»" if p.entry_gap < s.min_gap_pct
else "разница выше «Макс.»" if p.entry_gap > s.max_gap_pct
else "мало объёма по лучшей цене" if not depth_ok(p, s)
else small if small
else "торговля остановлена (кнопка «Старт»)" if not s.running
else (f"открыто реальных позиций {len(real_open)} из {max(1, s.max_real_positions)} "
f"({', '.join(real_open)}) — ждёт закрытия"
if s.real and len(real_open) >= max(1, s.max_real_positions) and p.base not in real_open else
"сейчас открывается другая реальная сделка" if s.real and (self.opening - {p.base}) else
f"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until else
f"пауза по монете после закрытия ({s.cooldown_s:g} с)"
if now - self.last_close.get(p.base, 0) < s.cooldown_s else ""))
rows.append({**asdict(p), "entry_gap": p.entry_gap, "exit_gap": p.exit_gap, "why": why,
"funding_pct": p.funding * 100, "spot_url": self.venue.spot_url(p),
"fut_url": self.venue.fut_url(p),
"net_if_closed_pct": p.entry_gap - s.exit_gap_pct - 2 * (s.spot_fee + self._fut_rate(p)),
"fut_fee_pct": self._fut_rate(p),
"min_entry": m["usd"] if m else None, "min_spot": m["spot"] if m else None,
"min_fut": m["fut"] if m else None,
"depth": entry_depth(p),
"real_block": (self.real_block.get(p.base, ("", 0.0))[0]
if s.real and self.real_block.get(p.base, ("", 0.0))[1] > now else ""),
"fits": fits})
rows.sort(key=lambda r: -r["entry_gap"])
positions = []
for pos in self.positions:
p = self.pairs.get(pos.base)
d = asdict(pos)
if p:
spot_pnl, fut_pnl, fees, net = close_result(pos, p.spot_bid, p.fut_ask, s)
seen = self.fast_seen.get(pos.base)
d.update(price_age=None if seen is None else now - seen, fast_ms=self.fast_ms)
d.update(gap_now=p.exit_gap, spot_now=p.spot_bid, fut_now=p.fut_ask, net=net, fees_total=fees,
spot_url=self.venue.spot_url(p), fut_url=self.venue.fut_url(p))
positions.append(d)
# real mode: the figures are those of the real trades only (prices and fees from the exchange's fills)
closed = [t for t in self.trades if t.real] if s.real else self.trades
opened = [p for p in positions if p.get("real")] if s.real else positions
wins = sum(t.net > 0 for t in closed)
invested = sum(t.amount for t in closed)
stats = {"trades": len(closed), "wins": wins, "net": sum(t.net for t in closed),
"net_pct": sum(t.net for t in closed) / invested * 100 if invested else None,
"fees": sum(t.fees for t in closed), "funding": sum(t.funding for t in closed),
"open": len(opened), "unrealized": sum(p.get("net", 0) for p in opened),
"real": s.real, "exact": all(t.exact for t in closed),
"avg_hold_min": (sum(t.closed - t.opened for t in closed) / len(closed) / 60) if closed else None}
return {"venue": self.venue.name, "key": self.key, "settings": asdict(s), "status": self.status,
"updated": self.updated, "cycle_ms": self.cycle_ms, "now": now, "pairs_total": len(self.pairs),
"memes_source": self.memes_source, "rows": rows, "positions": positions,
"real_pause": (f"{self.real_pause_reason} (ещё {(self.real_pause_until - now) / 60:.0f} мин)"
if s.real and now < self.real_pause_until else ""),
"trades": [asdict(t) for t in reversed(closed[-200:])], "stats": stats,
"planned": PLANNED}