This commit is contained in:
listik committed 2026-10-23 10:02:22 +03:00
1 parent b9185b166e
commit 2ea1a79bda
3 files changed
+164 -20

No files matched your search

+140 -19
View File
@@ -171,6 +171,10 @@ class CrossSettings:
confirm_ms: float = 400.0 # real: the signal is checked twice on the order books, this far apart
min_liq_pct: float = 50.0 # no short whose liquidation would be less than this % above the entry
liq_close_pct: float = 20.0 # close both legs when the price is this close to the liquidation, % (0 = off)
block_negative_funding: bool = True # do not open a short-futures hedge when funding is negative
negative_funding_before_minutes: float = 60.0 # block negative funding only this long before settlement
min_funding_pct: float = -1.0 # block entry when funding is below this rate, per funding interval
simulation_execution_delay_ms: float = 600.0 # paper orders fill this long after the signal
@dataclass
@@ -430,6 +434,8 @@ class CrossEngine:
self.balances: dict = {} # web_sim's BALANCES (exchange key → account figures)
self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"}
self.opening: set[str] = set() # coins with a real entry in progress
self.paper_opening: set[str] = set() # paper entries waiting for simulated execution
self.paper_closing: set[int] = set() # paper exits waiting for simulated execution
self.jobs: queue.Queue = queue.Queue()
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)
@@ -901,13 +907,24 @@ class CrossEngine:
spread_b = (l.fut_ask / l.fut_bid - 1) * 100 if l.fut_bid > 0 else 100.0
wide = (f"широкий спред: {l.spot_ex} {spread_a:.2f}%, {l.fut_ex} {spread_b:.2f}% (макс. {s.max_spread_pct:g}%)"
if s.max_spread_pct > 0 and max(spread_a, spread_b) > s.max_spread_pct else "")
funding_period = max(1.0, l.interval_h * 3600.0)
funding_left = funding_period - (now % funding_period)
funding_pct = l.funding * 100.0
funding_too_negative = funding_pct < s.min_funding_pct
bad_funding_window = (s.block_negative_funding and l.funding < 0 and
funding_left <= max(0.0, s.negative_funding_before_minutes) * 60.0)
bad_funding = funding_too_negative or bad_funding_window
# either way: −34 % (SIREN MEXC spot vs Gate perp) is as much «two different coins» as +30 000 % (EWT)
fits = (net is not None and hist >= s.history_min and abs(l.entry_gap) <= hard_max
and net >= s.min_net_pct and depth_ok and not elsewhere and not no_keys and not short
and not small and not wide)
and not small and not wide and not bad_funding)
why = ("" if fits else f"уже в сделке: {elsewhere}" if elsewhere
else f"нет API-ключей {', '.join(no_keys)}" if no_keys
else wide if wide
else wide if wide
else (f"funding {funding_pct:+.4f}% ниже порога {s.min_funding_pct:+g}%")
if funding_too_negative
else (f"отрицательный funding {funding_pct:+.4f}% — до выплаты "
f"{funding_left / 60:.0f} мин") if bad_funding_window
else small if small
else f"мало {' и '.join(short)} для суммы {s.amount:g} $" if short
else "мало истории" if hist < s.history_min
@@ -934,12 +951,25 @@ class CrossEngine:
# links itself); the hot links are refreshed in between by the hot watch
rows = self.candidates(now)
self.cand, self.cand_time = {r["key"]: r for r in rows}, now
real_busy = s.real and (self.opening or now < self.real_pause_until)
real_busy = s.real and (self.opening or now < self.real_pause_until or self.waiting_baseline(now))
if s.running and not real_busy: # real: the next trade only after the previous is confirmed
changed = self._entries(now, rows) or changed
if changed:
self.save()
BASELINE_WAIT_S = 60.0
def waiting_baseline(self, now: float) -> bool:
"""Right after «Старт» of real trading: no entry before the balances of every exchange have been read once
(balances come every 10 s) — otherwise the first trade's fee and slippage land inside the «было» of «С
запуска» and are never counted (ALT, 2026-10-22: entered 7 s after the start, the reference read 10 s
later). An exchange that does not answer holds the entries a minute at most."""
base = self.baseline
if not base or base.get("total") is not None or now - (base.get("time") or 0) > self.BASELINE_WAIT_S:
return False
self.balance_view(time.time()) # takes the reference as soon as the balances are all there
return base.get("total") is None
def hot_step(self, keys: list[str], now: float) -> None:
"""The hot links have fresh prices: their rows again, and an entry if one of them fits now."""
with self.lock:
@@ -947,7 +977,8 @@ class CrossEngine:
for r in rows:
self.cand[r["key"]] = r
s = self.settings
if s.running and not (s.real and (self.opening or now < self.real_pause_until)):
if s.running and not (s.real and (self.opening or now < self.real_pause_until
or self.waiting_baseline(now))):
if self._entries(now, rows):
self.save()
@@ -963,6 +994,8 @@ class CrossEngine:
s = self.settings
changed = False
for pos in list(self.positions):
if not pos.real and pos.uid in self.paper_closing:
continue
l = self.links.get(pos.key)
if l is None:
continue
@@ -1008,15 +1041,67 @@ class CrossEngine:
pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap]
self.jobs.put(("close", pos.uid, reason))
else:
self._close(pos, l, now, reason)
changed = True
if self._schedule_paper_close(pos.uid, reason):
changed = True
return changed
def _paper_delay(self) -> float:
"""Delay used only by the simulator; tests without a running loop stay synchronous."""
if self.quote_now is None:
return 0.0
return max(0.0, float(self.settings.simulation_execution_delay_ms)) / 1000.0
def _schedule_paper_close(self, uid: int, reason: str) -> bool:
if uid in self.paper_closing:
return False
self.paper_closing.add(uid)
delay = self._paper_delay()
if delay <= 0:
self._paper_close(uid, reason)
else:
timer = threading.Timer(delay, self._paper_close, args=(uid, reason))
timer.daemon = True
timer.start()
return True
def _paper_close(self, uid: int, reason: str) -> None:
with self.lock:
self.paper_closing.discard(uid)
pos = next((p for p in self.positions if p.uid == uid), None)
if pos is None:
return
l = self.links.get(pos.key)
if l is None:
return
self._close(pos, l, time.time(), reason)
self.save()
def _paper_open(self, base: str, key: str, usual: float, amount: float, signal_time: float) -> None:
with self.lock:
self.paper_opening.discard(base)
if any(p.base == base for p in self.positions) or self.elsewhere(base):
return
l = self.links.get(key)
if l is None or l.spot_ask <= 0 or l.fut_bid <= 0:
return
now = time.time()
qty = amount / l.spot_ask
fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \
+ qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100
step = l.interval_h * 3600
liq = 0.0 if l.ss else l.fut_bid * (1 + liq_distance(self.FUT_NEED, 1.0) / 100)
self.positions.append(CrossPosition(
self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, qty, l.spot_ask,
l.fut_bid, l.entry_gap, usual, fee_in, 0.0 if l.ss else (now // step + 1) * step,
innovation=l.innovation, liq_price=liq, liq_calc=liq, liq_src="" if l.ss else "расчёт", ss=l.ss))
self.next_uid += 1
self.save()
def _entries(self, now: float, rows: list[dict] | None = None) -> bool:
import basis
s = self.settings
changed = False
busy = {p.base for p in self.positions} | self.opening
busy = {p.base for p in self.positions} | self.opening | self.paper_opening
best: dict[str, dict] = {}
for r in (self.candidates(now) if rows is None else rows): # per coin: the link with the highest net
if r["fits"] and (r["link"].base not in best or r["net"] > best[r["link"].base]["net"]) \
@@ -1036,17 +1121,15 @@ class CrossEngine:
self.opening.add(l.base)
self.jobs.put(("open", l, r["usual"], s.amount))
break # one real entry at a time
qty = s.amount / l.spot_ask
fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \
+ qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100
step = l.interval_h * 3600
# paper: B holds the amount + 3 % as futures money (what the real entry makes sure of)
liq = 0.0 if l.ss else l.fut_bid * (1 + liq_distance(self.FUT_NEED, 1.0) / 100)
self.positions.append(CrossPosition(
self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now, qty, l.spot_ask,
l.fut_bid, l.entry_gap, r["usual"], fee_in, 0.0 if l.ss else (now // step + 1) * step,
innovation=l.innovation, liq_price=liq, liq_calc=liq, liq_src="" if l.ss else "расчёт", ss=l.ss))
self.next_uid += 1
self.paper_opening.add(l.base)
delay = self._paper_delay()
if delay <= 0:
self._paper_open(l.base, l.key, r["usual"], s.amount, now)
else:
timer = threading.Timer(delay, self._paper_open,
args=(l.base, l.key, r["usual"], s.amount, now))
timer.daemon = True
timer.start()
busy.add(l.base)
changed = True
return changed
@@ -1181,7 +1264,7 @@ class CrossEngine:
l = self.links.get(pos.key)
if l is None:
continue
self._close(pos, l, time.time(), "вручную")
self._schedule_paper_close(pos.uid, "вручную")
n += 1
self.save()
return f"закрыто позиций: {n}" + (f", реальных отправлено на закрытие: {real}" if real else "")
@@ -1600,10 +1683,46 @@ class CrossEngine:
def _real_close(self, uid: int, reason: str) -> None:
"""Buy the short back on B (reduce-only), make sure B shows no short left, then sell the coins on A."""
import live
import fastquote
with self.lock:
pos = next((x for x in self.positions if x.uid == uid), None)
if pos is None or not pos.real:
return
# Refresh both executable sides immediately before the first close order. The fast watcher normally
# updates every 250 ms, but its previous snapshot may have been taken before the close job reached here.
# A normal convergence close is postponed when the current executable prices are already losing after fees.
if reason != "вручную" and "стоп:" not in reason and "ликвидац" not in reason:
try:
l0 = self.links.get(pos.key)
if l0 is not None:
with ThreadPoolExecutor(max_workers=2) as qpool:
sj = qpool.submit(fastquote.spot_top, l0.spot_ex, l0.spot_symbol)
fj = qpool.submit(fastquote.spot_top if l0.ss else fastquote.fut_top,
l0.fut_ex, l0.fut_symbol)
sb, sa, _, _ = sj.result(timeout=3)
fb, fa, _, _ = fj.result(timeout=3)
if min(sb, sa, fb, fa) <= 0:
raise RuntimeError("пустой стакан при повторной проверке закрытия")
l_now = __import__("dataclasses").replace(l0, spot_bid=sb, spot_ask=sa,
fut_bid=fb / l0.fut_mult, fut_ask=fa / l0.fut_mult)
with self.lock:
self.links[pos.key] = l_now
self.fast_seen[pos.key] = time.time()
_, _, _, current_net = close_result(pos, l_now.spot_bid, l_now.fut_ask, self.fees)
if current_net < 0:
with self.lock:
pos.retry_at = time.time() + 1.0
pos.error = f"закрытие отложено: текущий расчётный net {current_net:+.4f} $"
self.busy.discard(pos.uid)
self.save()
self._journal(pos.base, "close", False,
f"закрытие отложено: по свежему стакану net {current_net:+.4f} $ — сделка остаётся открытой")
return
except Exception as exc:
# If a quote refresh is temporarily unavailable, keep the previous fast snapshot and let the
# existing exchange-side close/retry path handle it. This is also important for venues whose
# public order-book endpoint is unavailable while private order APIs are still reachable.
self._journal(pos.base, "close", False, f"свежий стакан не получен, используется последний снимок: {exc}")
stage = f"выкуп шорта на {pos.fut_ex}"
try:
ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex)
@@ -1875,6 +1994,7 @@ class CrossEngine:
if b not in best or score > best[b]["score"]:
best[b] = {**r, "score": score}
real_open = [p.base for p in self.positions if p.real]
wait_base = s.real and self.waiting_baseline(now)
rows = []
for r in best.values():
l = r["link"]
@@ -1885,6 +2005,7 @@ class CrossEngine:
why = ("торговля остановлена (кнопка «Старт»)" if not s.running
else f"реально нельзя: {block[0]}" if s.real and block[1] > now
else full if full
else "жду балансы всех бирж после «Старт» — точка отсчёта «С запуска»" if wait_base
else "сейчас открывается другая реальная сделка" if s.real and (self.opening - {l.base})
else f"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until
else f"пауза по монете после закрытия ({s.cooldown_s:g} с)"