Merge main into codex/reliability-and-safety
This commit is contained in:
commit
dbc044fc49
5 files changed
+211
-25
No files matched your search
@@ -172,6 +172,10 @@ class CrossSettings:
|
|||||||
confirm_ms: float = 400.0 # real: the signal is checked twice on the order books, this far apart
|
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
|
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)
|
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
|
@dataclass
|
||||||
@@ -438,6 +442,8 @@ class CrossEngine:
|
|||||||
self.balances: dict = {} # web_sim's BALANCES (exchange key → account figures)
|
self.balances: dict = {} # web_sim's BALANCES (exchange key → account figures)
|
||||||
self.baseline: dict = {} # balances when trading was started: {"time", "total", "by_ex"}
|
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.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.jobs: queue.Queue = queue.Queue()
|
||||||
self.busy: set[int] = set() # real positions whose close is being sent right now
|
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_block: dict[str, tuple[str, float]] = {} # coin → (why it cannot be traded for real, until)
|
||||||
@@ -1015,13 +1021,24 @@ class CrossEngine:
|
|||||||
spread_b = (l.fut_ask / l.fut_bid - 1) * 100 if l.fut_bid > 0 else 100.0
|
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}%)"
|
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 "")
|
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)
|
# 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
|
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 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
|
why = ("" if fits else f"уже в сделке: {elsewhere}" if elsewhere
|
||||||
else f"нет API-ключей {', '.join(no_keys)}" if no_keys
|
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 small if small
|
||||||
else f"мало {' и '.join(short)} для суммы {s.amount:g} $" if short
|
else f"мало {' и '.join(short)} для суммы {s.amount:g} $" if short
|
||||||
else "мало истории" if hist < s.history_min
|
else "мало истории" if hist < s.history_min
|
||||||
@@ -1050,12 +1067,26 @@ class CrossEngine:
|
|||||||
# links itself); the hot links are refreshed in between by the hot watch
|
# links itself); the hot links are refreshed in between by the hot watch
|
||||||
rows = self.candidates(now)
|
rows = self.candidates(now)
|
||||||
self.cand, self.cand_time = {r["key"]: r for r in rows}, now
|
self.cand, self.cand_time = {r["key"]: r for r in rows}, now
|
||||||
real_busy = s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until)
|
real_busy = s.real and (self.opening or self.pending or self.recover
|
||||||
|
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
|
if s.running and not real_busy: # real: the next trade only after the previous is confirmed
|
||||||
changed = self._entries(now, rows) or changed
|
changed = self._entries(now, rows) or changed
|
||||||
if changed:
|
if changed:
|
||||||
self.save(event="Арбитраж: обновление позиций и funding")
|
self.save(event="Арбитраж: обновление позиций и funding")
|
||||||
|
|
||||||
|
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:
|
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."""
|
"""The hot links have fresh prices: their rows again, and an entry if one of them fits now."""
|
||||||
with self.lock:
|
with self.lock:
|
||||||
@@ -1063,7 +1094,8 @@ class CrossEngine:
|
|||||||
for r in rows:
|
for r in rows:
|
||||||
self.cand[r["key"]] = r
|
self.cand[r["key"]] = r
|
||||||
s = self.settings
|
s = self.settings
|
||||||
if s.running and not (s.real and (self.opening or self.pending or self.recover or now < self.real_pause_until)):
|
if s.running and not (s.real and (self.opening or self.pending or self.recover
|
||||||
|
or now < self.real_pause_until or self.waiting_baseline(now))):
|
||||||
if self._entries(now, rows):
|
if self._entries(now, rows):
|
||||||
self.save()
|
self.save()
|
||||||
|
|
||||||
@@ -1079,6 +1111,8 @@ class CrossEngine:
|
|||||||
s = self.settings
|
s = self.settings
|
||||||
changed = False
|
changed = False
|
||||||
for pos in list(self.positions):
|
for pos in list(self.positions):
|
||||||
|
if not pos.real and pos.uid in self.paper_closing:
|
||||||
|
continue
|
||||||
l = self.links.get(pos.key)
|
l = self.links.get(pos.key)
|
||||||
# Once a real unwind has started it must not depend on a fresh listing or another exit signal.
|
# Once a real unwind has started it must not depend on a fresh listing or another exit signal.
|
||||||
if pos.real and pos.closing and pos.uid not in self.busy and now >= pos.retry_at:
|
if pos.real and pos.closing and pos.uid not in self.busy and now >= pos.retry_at:
|
||||||
@@ -1132,11 +1166,71 @@ class CrossEngine:
|
|||||||
pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap]
|
pos.exit_signal = [now, l.spot_bid, l.fut_ask, l.exit_gap]
|
||||||
self.jobs.put(("close", pos.uid, reason))
|
self.jobs.put(("close", pos.uid, reason))
|
||||||
else:
|
else:
|
||||||
if not self._close(pos, l, now, reason):
|
if self._schedule_paper_close(pos.uid, reason):
|
||||||
|
changed = True
|
||||||
|
elif self.account_error:
|
||||||
return False
|
return False
|
||||||
changed = True
|
|
||||||
return changed
|
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:
|
||||||
|
return 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) -> bool:
|
||||||
|
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 False
|
||||||
|
l = self.links.get(pos.key)
|
||||||
|
if l is None:
|
||||||
|
return False
|
||||||
|
now = time.time()
|
||||||
|
if not self._close(pos, l, now, reason):
|
||||||
|
return False
|
||||||
|
return self.save()
|
||||||
|
|
||||||
|
def _paper_open(self, base: str, key: str, usual: float, amount: float, signal_time: float) -> bool:
|
||||||
|
with self.lock:
|
||||||
|
self.paper_opening.discard(base)
|
||||||
|
if self.account is not None and self.account_error:
|
||||||
|
return False
|
||||||
|
if any(p.base == base for p in self.positions) or self.elsewhere(base):
|
||||||
|
return False
|
||||||
|
l = self.links.get(key)
|
||||||
|
if l is None or l.spot_ask <= 0 or l.fut_bid <= 0 or self.full(l):
|
||||||
|
return False
|
||||||
|
now = time.time() if self._paper_delay() > 0 else signal_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.positions[-1].paper_reserve = self._position_reserve(self.positions[-1])
|
||||||
|
self.next_uid += 1
|
||||||
|
if self.account is not None:
|
||||||
|
self.cash_total -= fee_in
|
||||||
|
return self.save(event=f"Арбитраж: вход {base}")
|
||||||
|
|
||||||
def _entries(self, now: float, rows: list[dict] | None = None) -> bool:
|
def _entries(self, now: float, rows: list[dict] | None = None) -> bool:
|
||||||
import basis
|
import basis
|
||||||
s = self.settings
|
s = self.settings
|
||||||
@@ -1145,7 +1239,7 @@ class CrossEngine:
|
|||||||
if s.real and any(p.real and p.closing for p in self.positions):
|
if s.real and any(p.real and p.closing for p in self.positions):
|
||||||
return False
|
return False
|
||||||
changed = False
|
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] = {}
|
best: dict[str, dict] = {}
|
||||||
for r in (self.candidates(now) if rows is None else rows): # per coin: the link with the highest net
|
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"]) \
|
if r["fits"] and (r["link"].base not in best or r["net"] > best[r["link"].base]["net"]) \
|
||||||
@@ -1165,22 +1259,16 @@ class CrossEngine:
|
|||||||
self.opening.add(l.base)
|
self.opening.add(l.base)
|
||||||
self.jobs.put(("open", l, r["usual"], s.amount))
|
self.jobs.put(("open", l, r["usual"], s.amount))
|
||||||
break # one real entry at a time
|
break # one real entry at a time
|
||||||
qty = s.amount / l.spot_ask
|
self.paper_opening.add(l.base)
|
||||||
fee_in = qty * l.spot_ask * spot_fee(l.spot_ex, self.fees) / 100 \
|
delay = self._paper_delay()
|
||||||
+ qty * l.fut_bid * b_fee(l.fut_ex, self.fees, l.innovation, l.ss) / 100
|
if delay <= 0:
|
||||||
step = l.interval_h * 3600
|
if not self._paper_open(l.base, l.key, r["usual"], s.amount, now):
|
||||||
# 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.positions[-1].paper_reserve = self._position_reserve(self.positions[-1])
|
|
||||||
self.next_uid += 1
|
|
||||||
if self.account is not None:
|
|
||||||
self.cash_total -= fee_in
|
|
||||||
if not self.save(event=f"Арбитраж: вход {l.base}"):
|
|
||||||
break
|
break
|
||||||
|
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)
|
busy.add(l.base)
|
||||||
changed = True
|
changed = True
|
||||||
return changed
|
return changed
|
||||||
@@ -1320,9 +1408,9 @@ class CrossEngine:
|
|||||||
l = self.links.get(pos.key)
|
l = self.links.get(pos.key)
|
||||||
if l is None:
|
if l is None:
|
||||||
continue
|
continue
|
||||||
if self._close(pos, l, time.time(), "вручную"):
|
if self._schedule_paper_close(pos.uid, "вручную"):
|
||||||
n += 1
|
n += 1
|
||||||
else:
|
elif self.account_error:
|
||||||
return self.account_error
|
return self.account_error
|
||||||
if not self.save():
|
if not self.save():
|
||||||
return self.account_error
|
return self.account_error
|
||||||
@@ -1906,10 +1994,46 @@ class CrossEngine:
|
|||||||
def _real_close(self, uid: int, reason: str) -> None:
|
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."""
|
"""Buy the short back on B (reduce-only), make sure B shows no short left, then sell the coins on A."""
|
||||||
import live
|
import live
|
||||||
|
import fastquote
|
||||||
with self.lock:
|
with self.lock:
|
||||||
pos = next((x for x in self.positions if x.uid == uid), None)
|
pos = next((x for x in self.positions if x.uid == uid), None)
|
||||||
if pos is None or not pos.real:
|
if pos is None or not pos.real:
|
||||||
return
|
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 not pos.closing and 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}"
|
stage = f"выкуп шорта на {pos.fut_ex}"
|
||||||
try:
|
try:
|
||||||
ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex)
|
ca, cb = self.client_for(pos.spot_ex), self.client_for(pos.fut_ex)
|
||||||
@@ -2206,6 +2330,7 @@ class CrossEngine:
|
|||||||
if b not in best or score > best[b]["score"]:
|
if b not in best or score > best[b]["score"]:
|
||||||
best[b] = {**r, "score": score}
|
best[b] = {**r, "score": score}
|
||||||
real_open = [p.base for p in self.positions if p.real]
|
real_open = [p.base for p in self.positions if p.real]
|
||||||
|
wait_base = s.real and self.waiting_baseline(now)
|
||||||
rows = []
|
rows = []
|
||||||
for r in best.values():
|
for r in best.values():
|
||||||
l = r["link"]
|
l = r["link"]
|
||||||
@@ -2216,6 +2341,7 @@ class CrossEngine:
|
|||||||
why = ("торговля остановлена (кнопка «Старт»)" if not s.running
|
why = ("торговля остановлена (кнопка «Старт»)" if not s.running
|
||||||
else f"реально нельзя: {block[0]}" if s.real and block[1] > now
|
else f"реально нельзя: {block[0]}" if s.real and block[1] > now
|
||||||
else full if full
|
else full if full
|
||||||
|
else "жду балансы всех бирж после «Старт» — точка отсчёта «С запуска»" if wait_base
|
||||||
else "сейчас открывается другая реальная сделка" if s.real and (self.opening - {l.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"пауза: {self.real_pause_reason}" if s.real and now < self.real_pause_until
|
||||||
else f"пауза по монете после закрытия ({s.cooldown_s:g} с)"
|
else f"пауза по монете после закрытия ({s.cooldown_s:g} с)"
|
||||||
|
|||||||
@@ -50,6 +50,38 @@ class CrossAccountTests(unittest.TestCase):
|
|||||||
self.e.save()
|
self.e.save()
|
||||||
self.assertAlmostEqual(self.account.view()["balance"], 300 + net)
|
self.assertAlmostEqual(self.account.view()["balance"], 300 + net)
|
||||||
|
|
||||||
|
def test_delayed_fill_charges_and_reserves_once_then_close_settles(self):
|
||||||
|
self.e.quote_now = mock.Mock()
|
||||||
|
with mock.patch.object(cross.threading, "Timer") as timer:
|
||||||
|
self.assertTrue(self.enter())
|
||||||
|
self.assertEqual(self.e.positions, [])
|
||||||
|
self.assertEqual(self.account.view()["balance"], 300)
|
||||||
|
self.assertFalse(self.enter())
|
||||||
|
self.assertEqual(timer.call_count, 1)
|
||||||
|
_, callback = timer.call_args.args
|
||||||
|
self.assertTrue(callback(*timer.call_args.kwargs["args"]))
|
||||||
|
pos = self.e.positions[0]
|
||||||
|
self.assertAlmostEqual(self.account.view()["balance"], 300 - pos.fees)
|
||||||
|
self.assertGreater(self.account.view()["reserved"], 200)
|
||||||
|
self.assertTrue(self.e._schedule_paper_close(pos.uid, "test"))
|
||||||
|
self.assertFalse(self.e._schedule_paper_close(pos.uid, "test"))
|
||||||
|
_, callback = timer.call_args.args
|
||||||
|
self.assertTrue(callback(*timer.call_args.kwargs["args"]))
|
||||||
|
self.assertEqual(self.account.view()["reserved"], 0)
|
||||||
|
self.assertAlmostEqual(self.account.view()["balance"], 300 + self.e.trades[0].net)
|
||||||
|
|
||||||
|
def test_delayed_fill_rechecks_shared_cash_at_execution(self):
|
||||||
|
self.e.quote_now = mock.Mock()
|
||||||
|
with mock.patch.object(cross.threading, "Timer") as timer:
|
||||||
|
self.assertTrue(self.enter())
|
||||||
|
self.account.commit("simulator:other", {}, cash_total=0, reserved=150)
|
||||||
|
_, callback = timer.call_args.args
|
||||||
|
self.assertFalse(callback(*timer.call_args.kwargs["args"]))
|
||||||
|
self.assertEqual(self.e.positions, [])
|
||||||
|
self.assertEqual(self.account.view()["balance"], 300)
|
||||||
|
self.assertEqual(self.account.view()["reserved"], 150)
|
||||||
|
self.assertFalse(self.e.settings.running)
|
||||||
|
|
||||||
def test_other_owner_reservation_blocks_entry_without_cash_or_state_change(self):
|
def test_other_owner_reservation_blocks_entry_without_cash_or_state_change(self):
|
||||||
self.account.commit("simulator:other", {}, cash_total=0, reserved=150)
|
self.account.commit("simulator:other", {}, cash_total=0, reserved=150)
|
||||||
before = self.account.view()["balance"]
|
before = self.account.view()["balance"]
|
||||||
|
|||||||
@@ -197,6 +197,24 @@ class CrossRealTests(unittest.TestCase):
|
|||||||
self.assertFalse(row["MEXC"]["keys"])
|
self.assertFalse(row["MEXC"]["keys"])
|
||||||
self.assertIsNone(row["MEXC"]["total"])
|
self.assertIsNone(row["MEXC"]["total"])
|
||||||
|
|
||||||
|
def test_no_entry_before_the_balance_reference(self):
|
||||||
|
# ALT, 2026-10-22: entered 7 s after «Старт», the reference read 10 s later — its costs were never counted
|
||||||
|
self.e.settings.running = False
|
||||||
|
self.e.set_settings({"running": True})
|
||||||
|
start = self.e.baseline["time"]
|
||||||
|
self.e.step(cross.time.time())
|
||||||
|
self.assertTrue(self.e.jobs.empty()) # the balances are older than the start
|
||||||
|
self.assertIn("жду балансы всех бирж", self.e.view()["rows"][0]["why"])
|
||||||
|
self.e.balances["gate"]["time"] = self.e.balances["binance"]["time"] = start + 1 # read after the start
|
||||||
|
self.e.step(cross.time.time())
|
||||||
|
self.assertEqual(self.e.jobs.qsize(), 1)
|
||||||
|
self.assertAlmostEqual(self.e.baseline["total"], 200.0) # taken BEFORE the entry
|
||||||
|
|
||||||
|
def test_an_exchange_that_never_answers_holds_entries_a_minute_at_most(self):
|
||||||
|
self.e.baseline = {"time": cross.time.time() - 61, "total": None, "by_ex": {}}
|
||||||
|
self.e.step(cross.time.time())
|
||||||
|
self.assertEqual(self.e.jobs.qsize(), 1)
|
||||||
|
|
||||||
def test_coins_of_open_position_count_in_balance(self):
|
def test_coins_of_open_position_count_in_balance(self):
|
||||||
self.e.step(1000.0)
|
self.e.step(1000.0)
|
||||||
self.run_jobs()
|
self.run_jobs()
|
||||||
|
|||||||
+6
-1
@@ -837,6 +837,9 @@ const CX_FIELDS = [
|
|||||||
["stop_widen_pct", "Стоп: разница шире входа на, % (0 — нет)"],
|
["stop_widen_pct", "Стоп: разница шире входа на, % (0 — нет)"],
|
||||||
["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["cooldown_s", "Пауза по монете, с"],
|
["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["cooldown_s", "Пауза по монете, с"],
|
||||||
["min_turnover", "Мин. оборот каждой ноги 24ч, $"], ["limit_hold_s", "Лимитный вход: ждать, с"],
|
["min_turnover", "Мин. оборот каждой ноги 24ч, $"], ["limit_hold_s", "Лимитный вход: ждать, с"],
|
||||||
|
["negative_funding_before_minutes", "При отрицательном funding не входить за, мин"],
|
||||||
|
["min_funding_pct", "Не входить, если funding ниже, %"],
|
||||||
|
["simulation_execution_delay_ms", "Задержка исполнения в симуляции, мс"],
|
||||||
["max_spread_pct", "Макс. спред каждой ноги, % (0 — нет)"],
|
["max_spread_pct", "Макс. спред каждой ноги, % (0 — нет)"],
|
||||||
["confirm_ms", "Подтверждение по стакану: пауза между 2 проверками, мс"],
|
["confirm_ms", "Подтверждение по стакану: пауза между 2 проверками, мс"],
|
||||||
["min_liq_pct", "Мин. запас до ликвидации шорта при входе, %"],
|
["min_liq_pct", "Мин. запас до ликвидации шорта при входе, %"],
|
||||||
@@ -846,6 +849,7 @@ const CX_CHECKS = [["search_sf", "Искать: спот → фьючерс ме
|
|||||||
["auto_transfer", "Автоперевод USDT между спотом и фьючерсами внутри биржи (реальный режим)"],
|
["auto_transfer", "Автоперевод USDT между спотом и фьючерсами внутри биржи (реальный режим)"],
|
||||||
["entry_ioc", "Вход первой ногой лимитным IOC по подтверждённой цене: не исполнился — сделки нет (реальный режим)"],
|
["entry_ioc", "Вход первой ногой лимитным IOC по подтверждённой цене: не исполнился — сделки нет (реальный режим)"],
|
||||||
["entry_limit", "Вход лимитным шортом с ожиданием «Лимитный вход: ждать, с» (если IOC выключен)"],
|
["entry_limit", "Вход лимитным шортом с ожиданием «Лимитный вход: ждать, с» (если IOC выключен)"],
|
||||||
|
["block_negative_funding", "Не открывать сделку при отрицательном funding"],
|
||||||
["fees_auto", "Комиссии сами корректируются по завершённым реальным сделкам"]];
|
["fees_auto", "Комиссии сами корректируются по завершённым реальным сделкам"]];
|
||||||
const CX_EX = ["Bybit", "Binance", "MEXC", "HTX", "Gate"];
|
const CX_EX = ["Bybit", "Binance", "MEXC", "HTX", "Gate"];
|
||||||
// the balances card: built once (the fee fields keep what is typed), its figures refreshed with every update
|
// the balances card: built once (the fee fields keep what is typed), its figures refreshed with every update
|
||||||
@@ -973,7 +977,8 @@ const BX_FIELDS = [
|
|||||||
const BX_CHECKS = [["use_new", "Новые монеты"], ["use_innovation", "Зона инноваций / метка «новая» биржи"], ["use_memes", "Мемкойны"],
|
const BX_CHECKS = [["use_new", "Новые монеты"], ["use_innovation", "Зона инноваций / метка «новая» биржи"], ["use_memes", "Мемкойны"],
|
||||||
["all_coins", "Все монеты со спотом и фьючем"],
|
["all_coins", "Все монеты со спотом и фьючем"],
|
||||||
["auto_transfer", "Автоперевод USDT между спотом и фьючерсами (реальный режим)"],
|
["auto_transfer", "Автоперевод USDT между спотом и фьючерсами (реальный режим)"],
|
||||||
["entry_limit", "Вход лимитным шортом по цене сигнала, потом спот (реальный режим)"]];
|
["entry_limit", "Вход лимитным шортом по цене сигнала, потом спот (реальный режим)"],
|
||||||
|
["block_negative_funding", "Не открывать сделку при отрицательном funding"]];
|
||||||
function bxTabs() {
|
function bxTabs() {
|
||||||
document.getElementById("bxTabs").innerHTML = BX_VENUES.map(([k, n]) => BX_READY.has(k)
|
document.getElementById("bxTabs").innerHTML = BX_VENUES.map(([k, n]) => BX_READY.has(k)
|
||||||
? `<button class="${k === bxVenue ? "on" : ""}" onclick="bxSelect('${k}')">${n}</button>`
|
? `<button class="${k === bxVenue ? "on" : ""}" onclick="bxSelect('${k}')">${n}</button>`
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ const HELP_SETTINGS = {
|
|||||||
cut_loss: "Дополнительно закрывать позицию при небольшом неблагоприятном движении, заданном числом шагов цены. Может приводить к частым закрытиям и расходам на комиссии."
|
cut_loss: "Дополнительно закрывать позицию при небольшом неблагоприятном движении, заданном числом шагов цены. Может приводить к частым закрытиям и расходам на комиссии."
|
||||||
},
|
},
|
||||||
cross: {
|
cross: {
|
||||||
|
block_negative_funding: "Запрещает вход при отрицательном funding в указанное окно перед выплатой.",
|
||||||
|
negative_funding_before_minutes: "Длительность окна перед выплатой funding в минутах. Применяется при включённом запрете отрицательного funding.",
|
||||||
|
min_funding_pct: "Нижний порог funding в процентах за период выплаты. Ставка ниже порога блокирует вход независимо от окна.",
|
||||||
|
simulation_execution_delay_ms: "Задержка виртуального входа и выхода в миллисекундах. Исполнение использует цены на момент окончания задержки; 0 отключает задержку.",
|
||||||
amount: "Номинальная сумма одной ноги сделки, в долларах. Общий виртуальный счёт должен покрыть обе ноги, резерв и комиссии. Это не размер всего счёта.",
|
amount: "Номинальная сумма одной ноги сделки, в долларах. Общий виртуальный счёт должен покрыть обе ноги, резерв и комиссии. Это не размер всего счёта.",
|
||||||
min_net_pct: "Минимальная расчётная чистая прибыль для входа: превышение разницы над обычной минус запас выхода и комиссии обеих ног. Проценты от суммы одной ноги; фактический результат может отличаться.",
|
min_net_pct: "Минимальная расчётная чистая прибыль для входа: превышение разницы над обычной минус запас выхода и комиссии обеих ног. Проценты от суммы одной ноги; фактический результат может отличаться.",
|
||||||
max_gap_pct: "Максимально допустимое расхождение цен, в процентах. Слишком большой разрыв может означать разные инструменты под похожим тикером или плохие котировки.",
|
max_gap_pct: "Максимально допустимое расхождение цен, в процентах. Слишком большой разрыв может означать разные инструменты под похожим тикером или плохие котировки.",
|
||||||
@@ -56,6 +60,7 @@ const HELP_SETTINGS = {
|
|||||||
fees_auto: "Уточнять значения комиссии по данным завершённых реальных сделок. В таблице бирж виден источник комиссии."
|
fees_auto: "Уточнять значения комиссии по данным завершённых реальных сделок. В таблице бирж виден источник комиссии."
|
||||||
},
|
},
|
||||||
basis: {
|
basis: {
|
||||||
|
block_negative_funding: "Запрещает новые входы при отрицательном funding.",
|
||||||
amount: "Номинальная сумма сделки спот-фьючерс в долларах.",
|
amount: "Номинальная сумма сделки спот-фьючерс в долларах.",
|
||||||
min_gap_pct: "Минимальная разница между фьючерсным bid и спотовым ask для входа, в процентах.",
|
min_gap_pct: "Минимальная разница между фьючерсным bid и спотовым ask для входа, в процентах.",
|
||||||
max_gap_pct: "Максимально допустимая разница для входа, в процентах.",
|
max_gap_pct: "Максимально допустимая разница для входа, в процентах.",
|
||||||
|
|||||||
Reference in new issue
Block a user