"""Real trades between exchanges: short on B first, then spot on A; the close buys B back and sells A; the fee rates follow what the exchanges charged; balances and their change since the start. No request reaches an exchange.""" from __future__ import annotations import json import sys import tempfile import time import unittest from pathlib import Path from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) sys.path.insert(0, str(Path(__file__).resolve().parent)) import cross # noqa: E402 import live # noqa: E402 import real_mirror # noqa: E402 from test_real import FakeClient # noqa: E402 KEY = "XYZ|Gate|Binance" def link(spot_bid=0.999, spot_ask=1.0, fut_bid=1.02, fut_ask=1.021): return cross.Link("XYZ", "Gate", "Binance", "XYZUSDT", "XYZUSDT", spot_bid, spot_ask, fut_bid, fut_ask, 1e5, 1e5, 1e7, 1e7, 0.0001, 8.0) class CrossRealTests(unittest.TestCase): def setUp(self): self.dir = tempfile.TemporaryDirectory() self.journal = mock.patch.object(real_mirror, "JOURNAL", Path(self.dir.name) / "j.jsonl") self.journal.start() self.e = cross.CrossEngine(Path(self.dir.name), start=False, real=True) # the «real trading» tab self.a, self.b = FakeClient(price=1.0), FakeClient(price=1.02) # A: spot (Gate), B: perp (Binance) self.e.client_for = lambda ex: {"Gate": self.a, "Binance": self.b}[ex] self.e.balances = {"gate": {"values": {"Спот USDT": 100.0, "Фьючерсы USDT": 0.0}, "time": 1.0}, "binance": {"values": {"Спот USDT": 0.0, "Фьючерсы USDT": 100.0}, "time": 1.0}} s = self.e.settings s.running = s.real = True s.entry_limit = s.entry_ioc = False s.amount, s.history_min = 100.0, 0.0 s.exit_hold_s = 0.0 # these tests close at once self.e.links = {KEY: link()} self.e.usual = {KEY: 0.5} self.e.seen_since = {KEY: 0.0} def tearDown(self): self.journal.stop() self.dir.cleanup() def run_jobs(self): while not self.e.jobs.empty(): self.e.do_job(self.e.jobs.get()) def test_short_on_b_then_spot_on_a_and_close(self): self.e.fees["Gate"]["spot"], self.e.fees["Binance"]["fut"] = 0.2, 0.08 # typed in, a bit off self.e.step(1000.0) self.assertEqual(self.e.opening, {"XYZ"}) self.e.step(1000.5) # no second entry while opening self.assertEqual(self.e.jobs.qsize(), 1) self.run_jobs() pos = self.e.positions[0] self.assertTrue(pos.real) self.assertEqual((pos.spot_ex, pos.fut_ex), ("Gate", "Binance")) self.assertEqual(pos.qty, 99.0) # B's lot self.assertEqual(self.b.position, -99.0) self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell")]) self.assertEqual([o[:2] for o in self.a.orders], [("spot", "buy")]) self.assertAlmostEqual(pos.usual, 0.5) self.assertEqual(self.e.opening, set()) self.assertEqual(self.e.pending, {}) # back to the usual gap → B bought back first, then A sold self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) self.e.step(1010.0) self.e.step(1010.5) self.assertEqual(self.e.jobs.qsize(), 1) self.run_jobs() self.assertEqual(self.e.positions, []) self.assertEqual(self.b.position, 0.0) self.assertEqual([o[:3] for o in self.b.orders[1:]], [("fut", "buy", 99.0)]) self.assertEqual([o[:2] for o in self.a.orders[1:]], [("spot", "sell")]) t = self.e.trades[0] self.assertTrue(t.real) self.assertIn("реально", t.reason) self.assertAlmostEqual(t.net, t.spot_pnl + t.fut_pnl - t.fees + t.funding) # the rates the exchanges charged (fake: spot 0.1 %, perp 0.05 %) are the table's rates now self.assertAlmostEqual(self.e.fees["Gate"]["spot"], 0.1, places=4) self.assertAlmostEqual(self.e.fees["Binance"]["fut"], 0.05, places=4) self.assertIn("по сделке XYZ", self.e.fees["Gate"]["spot_src"]) self.assertEqual(self.e.fees["MEXC"]["spot_src"], "") # not traded: untouched row = self.e.view()["rows"][0] self.assertAlmostEqual(row["fees_pct"], 2 * (0.1 + 0.05), places=4) def test_fees_not_learned_when_off(self): self.e.settings.fees_auto = False self.e.fees["Gate"]["spot"] = 0.2 self.e.step(1000.0) self.run_jobs() self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) self.e.step(1010.0) self.run_jobs() self.assertEqual(self.e.fees["Gate"]["spot"], 0.2) def test_no_keys_no_entry(self): del self.e.balances["binance"] self.e.step(1000.0) self.assertTrue(self.e.jobs.empty()) self.assertIn("нет API-ключей Binance", self.e.view()["rows"][0]["why"]) def test_spot_buy_fails_short_bought_back(self): def refuse(base, usdt): raise live.LiveError("отказ биржи") self.a.spot_buy = refuse self.e.step(1000.0) self.run_jobs() self.assertEqual(self.e.positions, []) self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell"), ("fut", "buy")]) self.assertEqual(self.b.position, 0.0) self.e.step(1001.0) # pause before the coin again self.assertTrue(self.e.jobs.empty()) def test_limit_short_not_filled_nothing_bought(self): self.e.settings.entry_limit, self.e.settings.limit_hold_s = True, 0.0 self.b.limit_fill = 0.0 self.e.step(1000.0) self.run_jobs() self.assertEqual(self.e.positions, []) self.assertEqual(self.a.orders, []) self.assertIn(("fut_cancel", "L1"), self.b.orders) def test_different_instruments_never_ordered(self): self.e.links[KEY] = link(spot_bid=0.339, spot_ask=0.3393, fut_bid=104.84, fut_ask=104.9) self.e.usual[KEY] = 0.0 self.e.settings.max_gap_pct = 1e6 self.e.step(1000.0) self.assertTrue(self.e.jobs.empty()) # even a request that slipped through stops before the exchange self.e.opening.add("XYZ") self.e.do_job(("open", self.e.links[KEY], 0.0, 100.0)) self.assertEqual(self.a.orders + self.b.orders, []) def test_close_retried_until_spot_sold(self): self.e.step(1000.0) self.run_jobs() self.a.fail_spot_sell = True self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) self.e.step(1010.0) self.run_jobs() pos = self.e.positions[0] self.assertEqual(pos.closing, "fut_done") # B already bought back self.assertIn("продажа спота", pos.error) self.e.step(1010.0 + 1) # before retry_at: nothing self.assertTrue(self.e.jobs.empty()) self.a.fail_spot_sell = False pos.retry_at = 0.0 self.e.step(1030.0) self.run_jobs() self.assertEqual(self.e.positions, []) self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell"), ("fut", "buy")]) # bought back once def test_restart_mid_entry_recovered(self): # the program stopped after the short on B and the buy on A, before the position was written self.e.pending["XYZ"] = {"time": 1.0, "key": KEY, "coins": 99.0, "usual": 0.5, "amount": 100.0} self.e.save() self.b.position = -99.0 self.a.spot_balance = 99.2 again = cross.CrossEngine(Path(self.dir.name), start=False, real=True) again.client_for = self.e.client_for again.balances = self.e.balances again.links, again.usual, again.seen_since = self.e.links, self.e.usual, self.e.seen_since again.step(1000.0) self.assertEqual(again.opening, {"XYZ"}) while not again.jobs.empty(): again.do_job(again.jobs.get()) pos = again.positions[0] self.assertEqual((pos.qty, round(pos.spot_qty, 6)), (99.0, 99.2)) self.assertFalse(pos.exact) self.assertEqual(again.pending, {}) def test_balances_and_change_since_start(self): self.e.settings.running = False self.assertEqual(self.e.set_settings({"running": True}), "") start = self.e.baseline["time"] bal = self.e.view()["balances"] self.assertIsNone(bal["start_total"]) # read before the start: not the reference self.e.balances["gate"]["time"] = self.e.balances["binance"]["time"] = start + 1 bal = self.e.view()["balances"] self.assertAlmostEqual(bal["total"], 200.0) self.assertAlmostEqual(bal["start_total"], 200.0) self.e.balances["binance"] = {"values": {"Спот USDT": 0.0, "Фьючерсы USDT": 103.0}, "time": start + 20} bal = self.e.view()["balances"] self.assertAlmostEqual(bal["change_pct"], 1.5) row = {r["exchange"]: r for r in bal["rows"]} self.assertAlmostEqual(row["Binance"]["change_pct"], 3.0) self.assertFalse(row["MEXC"]["keys"]) self.assertIsNone(row["MEXC"]["total"]) def test_coins_of_open_position_count_in_balance(self): self.e.step(1000.0) self.run_jobs() bal = {r["exchange"]: r for r in self.e.view()["balances"]["rows"]} self.assertAlmostEqual(bal["Gate"]["coins"], self.e.positions[0].spot_qty * 0.999, places=6) self.assertAlmostEqual(bal["Gate"]["total"], 100.0 + bal["Gate"]["coins"]) def money(self, ex, spot, fut, unified=False): self.e.balances[ex.lower()]["free"] = {"spot": spot, "futures": fut} self.e.balances[ex.lower()]["unified"] = unified def test_exchange_without_money_is_out_until_topped_up(self): self.money("Gate", 120.0, 0.0) self.money("Binance", 2.0, 1.0) # 3 $ for a 100 $ trade self.e.step(1000.0) self.assertTrue(self.e.jobs.empty()) view = self.e.view() self.assertEqual(view["rows"], []) # its links are not searched row = {r["exchange"]: r for r in view["balances"]["rows"]} self.assertIn("мало средств", row["Binance"]["low_funds"]) self.assertEqual(row["Gate"]["low_funds"], "") self.assertTrue(self.e.settings.use_binance) # the user's own switch is not touched self.money("Binance", 0.0, 150.0) # money arrived self.e.step(1001.0) self.assertEqual(self.e.jobs.qsize(), 1) self.assertEqual(self.e.view()["balances"]["rows"][1]["low_funds"], "") texts = [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] self.assertTrue(any("Binance: мало средств" in t for t in texts)) self.assertTrue(any("Binance: средств достаточно" in t for t in texts)) def test_money_for_each_leg_without_transfer(self): self.e.settings.auto_transfer = False self.money("Gate", 0.0, 150.0) # A has it on futures, the coin is bought on spot self.money("Binance", 0.0, 150.0) self.e.step(1000.0) self.assertTrue(self.e.jobs.empty()) self.assertIn("мало средств на споте Gate", self.e.view()["rows"][0]["why"]) self.e.settings.auto_transfer = True # moved inside Gate: enough self.e.step(1001.0) self.assertEqual(self.e.jobs.qsize(), 1) def test_paper_mode_ignores_money(self): self.e.settings.real = False self.money("Gate", 0.0, 0.0) self.money("Binance", 0.0, 0.0) self.e.step(1000.0) self.assertEqual(len(self.e.positions), 1) self.assertEqual(self.e.view()["balances"]["rows"][1]["low_funds"], "") # --- the signal is checked on fresh prices; no close at a loss «at the usual gap» --------------------------- def test_stale_signal_not_entered(self): # the cycle's list says +2 % (usual 0.5); right before the orders the market is at −0.9 % (the DNA case) self.e.quote_now = lambda l, usd: (0.2229, 0.223, 0.221, 0.2211, 0.04, 0.05) self.e.step(1000.0) self.run_jobs() self.assertEqual(self.a.orders + self.b.orders, []) texts = [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] self.assertTrue(any("по стакану разница -0.897%" in t and "ордеров не было" in t for t in texts)) self.e.step(1001.0) # the coin's pause: not tried again at once self.assertTrue(self.e.jobs.empty()) # --- confirmation on the order books, the spread filter, the IOC first leg --------------------------------- def journal_texts(self): return [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] def test_signal_must_hold_on_both_book_checks(self): self.e.settings.confirm_ms = 0 answers = iter([(0.999, 1.0, 1.021, 1.022, 0.1, 0.1), (0.999, 1.0, 1.003, 1.004, 0.1, 0.1)]) self.e.quote_now = lambda l, usd: next(answers) # good, then gone 0.4 s later self.e.step(1000.0) self.run_jobs() self.assertEqual(self.a.orders + self.b.orders, []) self.assertTrue(any("проверка 2 из 2" in t and "ордеров не было" in t for t in self.journal_texts())) def test_thin_book_or_wide_spread_at_the_check(self): self.e.settings.confirm_ms = 0 def thin(l, usd): raise cross.ThinBook("на фьючерсе Binance в стакане меньше 100 $") self.e.quote_now = thin self.e.step(1000.0) self.run_jobs() self.e.step(1001.0) self.assertTrue(self.e.jobs.empty()) # waits after the failed check self.assertIn("реально нельзя: по стакану", self.e.view()["rows"][0]["why"]) self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.9, 0.1) # spot spread 0.9 % > 0.5 self.e.real_block.clear() self.e.last_close.clear() self.e.step(1002.0) self.run_jobs() self.assertEqual(self.a.orders + self.b.orders, []) texts = self.journal_texts() self.assertTrue(any("в стакане меньше 100 $" in t for t in texts)) self.assertTrue(any("широкий спред: Gate 0.90%" in t for t in texts)) def test_wide_spread_link_not_searched(self): self.e.links[KEY] = link(spot_bid=0.98, spot_ask=1.0, fut_bid=1.02, fut_ask=1.021) # spot spread 2 % self.e.step(1000.0) self.assertTrue(self.e.jobs.empty()) self.assertIn("широкий спред: Gate 2.04%", self.e.view()["rows"][0]["why"]) def test_ioc_first_leg_at_the_confirmed_price(self): self.e.settings.entry_ioc, self.e.settings.confirm_ms = True, 0 self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.1, 0.1) self.b.limit_fill = 0.0 # the price has gone: nothing fills self.e.step(1000.0) self.run_jobs() self.assertEqual(self.a.orders, []) # nothing bought on A self.assertEqual([o[0] for o in self.b.orders], ["fut_limit", "fut_cancel"]) # placed, cancelled at once self.assertEqual(self.b.limits["L1"]["price"], 1.021) # at the confirmed average sale price self.assertTrue(any("IOC-шорт на Binance по 1.021 не исполнился" in t for t in self.journal_texts())) self.b.limit_fill = 1.0 # next time it fills: the hedge follows self.e.last_close.clear() self.e.step(1010.0) self.run_jobs() self.assertEqual(len(self.e.positions), 1) self.assertEqual([o[:2] for o in self.a.orders], [("spot", "buy")]) def test_back_to_usual_must_hold_before_the_close(self): self.e.settings.exit_hold_s = 3.0 self.e.step(1000.0) self.run_jobs() pos = self.e.positions[0] closes = lambda: [j for j in list(self.e.jobs.queue) if j[0] == "close"] at_usual = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) away = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.019, fut_ask=1.02) # a spike: at the usual gap for 1.5 s, then away again — not closed, the count starts anew self.e.links[KEY] = at_usual self.e.step(1010.0) self.e.step(1011.5) self.assertEqual(closes(), []) self.assertIn("exit_held", self.e.view()["positions"][0]) # the page shows the count self.e.links[KEY] = away self.e.step(1012.0) self.assertEqual(pos.exit_since, 0.0) # back again and held 3 s without a break → closed, with how long it held self.e.links[KEY] = at_usual self.e.step(1020.0) self.e.step(1022.9) self.assertEqual(closes(), []) self.e.step(1023.0) self.assertEqual(len(closes()), 1) self.assertIn("держалась 3.0 с", closes()[0][2]) def test_exit_follows_a_usual_gap_that_moved_up(self): # entered at +2 % over a usual of +0.5 %; since then the usual itself has risen to +1.8 % (the overnight # case: POD, NXPC… targets −6 % while the market sat at −1 %): closed when the gap is back to +1.8 % self.e.step(1000.0) self.run_jobs() pos = self.e.positions[0] closes = lambda: [j for j in list(self.e.jobs.queue) if j[0] == "close"] self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.0189, fut_ask=1.019) # gap 1.9 % self.e.step(1010.0) self.assertEqual(closes(), []) # the entry's usual (0.5): not yet self.e.usual[KEY] = 1.88 # the usual has moved up (+0.05 margin) self.e.step(1011.0) self.assertEqual(len(closes()), 1) self.assertIn("сместилась: при входе +0.50%, сейчас +1.88%", closes()[0][2]) view = self.e.view()["positions"][0] self.assertAlmostEqual(view["exit_level"], 1.88) def test_exit_not_harder_when_the_usual_moved_down(self): self.e.step(1000.0) self.run_jobs() self.e.usual[KEY] = -3.0 # dropped: the entry's 0.5 % stays the target self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.0049, fut_ask=1.005) # gap 0.5 % self.e.step(1010.0) self.assertEqual(len([j for j in list(self.e.jobs.queue) if j[0] == "close"]), 1) def test_stop_is_not_delayed(self): self.e.settings.exit_hold_s, self.e.settings.stop_widen_pct = 30.0, 1.0 self.e.step(1000.0) self.run_jobs() self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.034, fut_ask=1.035) # +3.5 %: stop self.e.step(1010.0) self.assertEqual([j[2] for j in list(self.e.jobs.queue) if j[0] == "close"], ["стоп: разница расширилась"]) def test_symbol_closed_to_api_blocked_for_a_day(self): # PTB on 2026-10-22: MEXC refused the spot buy 7 times, the short was opened and closed each time (fees) def refuse(base, usdt): raise live.LiveError('HTTP 400: {"code":10007,"msg":"symbol not support api"}') self.a.spot_buy = refuse self.e.step(1000.0) self.run_jobs() self.assertEqual([o[:2] for o in self.b.orders], [("fut", "sell"), ("fut", "buy")]) # once, closed back self.e.last_close.clear() self.e.step(cross.time.time()) self.assertTrue(self.e.jobs.empty()) # not tried again self.assertIn("не даёт торговать XYZ через API", self.e.real_block["XYZ"][0]) def test_negative_gap_beyond_limit_not_traded(self): self.e.links[KEY] = link(spot_bid=0.0343, spot_ask=0.0344, fut_bid=0.0227, fut_ask=0.02272) # −34 % (SIREN) self.e.usual[KEY] = -36.0 self.e.step(1000.0) self.assertTrue(self.e.jobs.empty()) self.assertIn("больше ±20%", self.e.view()["rows"][0]["why"]) def test_decision_prices_kept_and_compared_with_fills(self): self.e.settings.confirm_ms = 0 self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.1, 0.1) self.e.step(1000.0) self.run_jobs() pos = self.e.positions[0] self.assertEqual(pos.entry_signal[1:3], [1.0, 1.021]) # A ask, B bid confirmed for the entry self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.004, fut_ask=1.005) self.b.price = 1.0101 # the buy-back fills worse than decided self.e.step(1010.0) self.assertEqual(pos.exit_signal[1:3], [1.0, 1.005]) # A bid, B ask of the close decision self.run_jobs() t = self.e.trades[0] self.assertEqual((t.entry_signal[1], t.exit_signal[2]), (1.0, 1.005)) text = next(x for x in self.journal_texts() if "выкуплен" in x) self.assertIn("вход: решение при разнице +2.100%", text) self.assertIn("выкуп B 1.005 → 1.0101 (-0.51%)", text) def test_fresh_prices_used_when_still_good(self): self.e.quote_now = lambda l, usd: (0.999, 1.0, 1.021, 1.022, 0.1, 0.1) self.e.step(1000.0) self.run_jobs() self.assertEqual(len(self.e.positions), 1) self.assertEqual(self.e.links[KEY].fut_bid, 1.021) def test_closed_at_usual_gap_even_at_a_loss(self): # the exit rule is the gap, not the result: an entry worse than the signal is closed at the usual gap too self.e.step(1000.0) self.run_jobs() pos = self.e.positions[0] pos.usual = 2.5 self.e.links[KEY] = link(spot_bid=1.0, spot_ask=1.001, fut_bid=1.0249, fut_ask=1.025) # gap 2.5 = usual self.e.step(1010.0) self.assertEqual([j[0] for j in list(self.e.jobs.queue) if j[0] == "close"], ["close"]) def test_non_latin_ticker_not_traded(self): q = lambda ex, base: cross.arb.Quote(ex, f"{base}USDT", base, 1.0, 1.0, 1.001, 1e4, 1e4, 0.0001, 8.0, 1e6) links = cross.build_links([q("Gate", "龙虾"), q("Gate", "XYZ")], [q("Binance", "龙虾"), q("Binance", "XYZ")], set(cross.arb.EXCHANGES)) self.assertEqual({l.base for l in links.values()}, {"XYZ"}) def test_gate_fee_read_from_fills(self): g = live.Gate("k", "s") g._call = lambda m, path, params=None, body=None: [ {"order_id": "7", "fee": "0.003315"}, {"order_id": "7", "fee": "0.0000252"}, {"order_id": "8", "fee": "1"}] fee, exact = g._order_fee("DNA_USDT", "7") self.assertTrue(exact) self.assertAlmostEqual(fee, 0.0033402) # --- liquidation of the short on B ------------------------------------------------------------------------- def test_liquidation_formula(self): self.assertAlmostEqual(cross.liq_distance(100.0, 100.0), 0.99 / 1.01 * 100) # 1× money: ≈ +98 % self.assertAlmostEqual(cross.equity_for(50.0, 100.0), 51.5) self.assertAlmostEqual(cross.liq_distance(cross.equity_for(50.0, 100.0), 100.0), 50.0) def test_short_refused_when_liquidation_too_close(self): self.e.settings.auto_transfer = False self.b.usdt = {"spot": 0.0, "futures": 30.0} # 30 $ behind a ≈101 $ short: ≈ +28 % self.e.step(1000.0) self.run_jobs() self.assertEqual(self.e.positions, []) self.assertEqual(self.a.orders + self.b.orders, []) # nothing sent why = self.e.real_block["XYZ"][0] self.assertIn("ликвидация шорта на Binance была бы всего на 28%", why) self.assertIn("нужно 52.0", why) def test_transfer_covers_liquidation_margin_and_estimate_kept(self): self.b.usdt = {"spot": 200.0, "futures": 30.0} self.e.step(1000.0) self.run_jobs() self.assertEqual(self.b.orders[0][:2], ("transfer", "futures")) # moved inside Binance first pos = self.e.positions[0] self.assertEqual(pos.liq_src, "расчёт") # the fake reports no liquidation price to_liq = (pos.liq_calc / pos.fut_entry - 1) * 100 self.assertGreater(to_liq, 95) self.assertAlmostEqual(self.e.view()["positions"][0]["liq_pct"], (pos.liq_price / 1.021 - 1) * 100) def test_exchange_liquidation_price_replaces_estimate(self): self.b.fut_liq_price = lambda symbol: 1.9 self.e.step(1000.0) self.run_jobs() pos = self.e.positions[0] self.assertEqual((pos.liq_price, pos.liq_src), (1.9, "биржа")) self.assertGreater(pos.liq_calc, 1.9) # the estimate kept for the comparison texts = [json.loads(x)["text"] for x in (Path(self.dir.name) / "j.jsonl").read_text("utf-8").splitlines()] self.assertTrue(any("ликвидация шорта на Binance: биржа 1.9" in t for t in texts)) # read again every 30 s (cross margin: it moves with the whole account) self.b.fut_liq_price = lambda symbol: 1.8 self.e.step(time.time() + 31) self.run_jobs() self.assertEqual(pos.liq_price, 1.8) def test_both_legs_closed_near_liquidation(self): self.e.step(1000.0) self.run_jobs() pos = self.e.positions[0] pos.liq_price = 1.15 # the account has shrunk: liquidation close self.e.links[KEY] = link(spot_bid=1.05, spot_ask=1.051, fut_bid=1.0715, fut_ask=1.0716) # gap as at entry self.e.step(1010.0) self.run_jobs() self.assertEqual(self.e.positions, []) self.assertIn("до ликвидации шорта 7.3% < 20%", self.e.trades[0].reason) self.assertEqual([o[:2] for o in self.b.orders[1:]], [("fut", "buy")]) self.assertEqual([o[:2] for o in self.a.orders[1:]], [("spot", "sell")]) def test_paper_position_has_estimated_liquidation(self): self.e.settings.real = False self.e.step(1000.0) pos = self.e.positions[0] self.assertAlmostEqual(pos.liq_price, 1.02 * (1 + cross.liq_distance(1.03, 1.0) / 100)) self.assertEqual(pos.liq_src, "расчёт") def test_fees_typed_and_exchange_switched_off(self): msg = self.e.set_settings({"fees": {"Gate": {"spot": "0.08", "fut": "0.04"}}, "use_binance": False}) self.assertEqual(msg, "") self.assertEqual((self.e.fees["Gate"]["spot"], self.e.fees["Gate"]["fut"]), (0.08, 0.04)) self.assertEqual(self.e.fees["Gate"]["spot_src"], "вручную") self.e.step(1000.0) # Binance off: neither searched nor traded self.assertTrue(self.e.jobs.empty()) self.assertEqual(self.e.view()["rows"], []) again = cross.CrossEngine(Path(self.dir.name), start=False, real=True) # kept over a restart self.assertEqual(again.fees["Gate"]["spot"], 0.08) self.assertIn("от 0 до", self.e.set_settings({"fees": {"Gate": {"spot": "5"}}})) if __name__ == "__main__": unittest.main()