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

176 lines
8.4 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 between exchanges (paper): links A→B, the usual gap, entry above it, exit back to it."""
from __future__ import annotations
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import arb # noqa: E402
import cross # noqa: E402
def q(ex, base, bid, ask, vol=1e6, depth=1e4, funding=0.0001):
return arb.Quote(ex, f"{base}USDT", base, 1.0, bid, ask, depth, depth, funding, 8.0, vol)
class CrossTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.e = cross.CrossEngine(Path(self.dir.name), start=False)
self.e.settings.running = True
self.e.settings.exit_hold_s = 0.0
def tearDown(self):
self.dir.cleanup()
def feed(self, now, spot_ask, fut_bid, spot_ex="Gate", fut_ex="Binance"):
spots = [q(spot_ex, "XYZ", spot_ask - 0.001, spot_ask)]
futs = [q(fut_ex, "XYZ", fut_bid, fut_bid + 0.001), q(spot_ex, "XYZ", 99, 100)] # same exchange: ignored
self.e.links = cross.build_links(spots, futs, set(arb.EXCHANGES))
self.e.learn(now)
self.e.step(now)
def test_links_only_between_different_exchanges(self):
spots = [q("Gate", "XYZ", 0.99, 1.0), q("MEXC", "XYZ", 0.995, 1.005), q("Gate", "BTC3L", 1, 1.01)]
futs = [q("Binance", "XYZ", 1.02, 1.021), q("Gate", "XYZ", 1.03, 1.031)]
links = cross.build_links(spots, futs, set(arb.EXCHANGES), kinds=("sf",))
self.assertEqual(set(links), {"XYZ|Gate|Binance", "XYZ|MEXC|Binance", "XYZ|MEXC|Gate"})
self.assertAlmostEqual(links["XYZ|Gate|Binance"].entry_gap, (1.02 / 1.0 - 1) * 100)
# all three kinds: inside one exchange (Gate spot → Gate perp) and spot → spot both ways
links = cross.build_links(spots, futs, set(arb.EXCHANGES))
self.assertEqual({k for k, l in links.items() if l.kind == "in"}, {"XYZ|Gate|Gate"})
self.assertEqual({k for k, l in links.items() if l.kind == "ss"}, {"XYZ|Gate|MEXC|ss", "XYZ|MEXC|Gate|ss"})
ss = links["XYZ|Gate|MEXC|ss"]
self.assertEqual((ss.fut_bid, ss.fut_ask), (0.995, 1.005)) # MEXC's SPOT prices
self.assertAlmostEqual(cross.round_trip_fee_pct("Gate", "MEXC", ss=True),
2 * (cross.SPOT_FEE["Gate"] + cross.SPOT_FEE["MEXC"]))
def test_persistent_offset_is_not_traded(self):
# the perp on Binance always 3 % above Gate's spot: that is its usual gap, nothing to capture
for i in range(400): # 20 minutes of history
self.feed(1000.0 + i * 3, 1.0, 1.03)
self.assertGreater(self.e.history_min("XYZ|Gate|Binance", 1000.0 + 399 * 3), 15)
self.assertAlmostEqual(self.e.usual["XYZ|Gate|Binance"], (1.0305 / 0.9995 - 1) * 100, delta=0.01)
self.assertEqual(self.e.positions, [])
def test_enter_above_usual_exit_when_back(self):
t = 1000.0
for i in range(400):
self.feed(t + i * 3, 1.0, 1.01) # usual ≈ +1.1 % (mid to mid)
t += 400 * 3
self.feed(t, 1.0, 1.02) # +2 %: about 0.9 % above the usual
self.assertEqual(len(self.e.positions), 1)
pos = self.e.positions[0]
self.assertEqual((pos.spot_ex, pos.fut_ex), ("Gate", "Binance"))
self.assertAlmostEqual(pos.usual, 1.1, delta=0.05)
self.feed(t + 30, 1.0, 1.0145) # exit gap 1.65 % > usual + 0.05 → held
self.assertEqual(len(self.e.positions), 1)
self.feed(t + 60, 1.0, 1.008) # exit gap 1.0 %: back to the usual → closed
self.assertEqual(self.e.positions, [])
tr = self.e.trades[0]
self.assertIn("обычной", tr.reason)
fees = tr.qty * (1.0 * 0.1 + 1.02 * cross.fut_fee("Binance") + 0.999 * 0.1 + 1.009 * cross.fut_fee("Binance")) / 100
self.assertAlmostEqual(tr.fees, fees, places=6)
self.assertAlmostEqual(tr.net, tr.spot_pnl + tr.fut_pnl - tr.fees + tr.funding)
def test_not_before_enough_history(self):
for i in range(60): # 3 minutes only
self.feed(1000.0 + i * 3, 1.0, 1.01)
self.feed(1000.0 + 180, 1.0, 1.03)
self.assertEqual(self.e.positions, [])
def test_stop_when_gap_widens(self):
t = 1000.0
for i in range(400):
self.feed(t + i * 3, 1.0, 1.01)
t += 400 * 3
self.feed(t, 1.0, 1.02)
self.assertEqual(len(self.e.positions), 1)
self.feed(t + 30, 1.0, 1.045) # widened by > 2 %
self.assertIn("стоп", self.e.trades[0].reason)
def test_exchange_switched_off(self):
self.e.settings.use_gate = False
t = 1000.0
for i in range(400):
self.feed(t + i * 3, 1.0, 1.01)
self.feed(t + 1200, 1.0, 1.03)
self.assertEqual(self.e.positions, [])
self.assertEqual(self.e.view()["rows"], [])
def test_fast_watch_closes_on_fresh_prices(self):
import threading
import time
from unittest import mock
t = 1000.0
for i in range(400):
self.feed(t + i * 3, 1.0, 1.01)
self.feed(t + 1200, 1.0, 1.02)
self.assertEqual(len(self.e.positions), 1)
seen = []
with mock.patch("fastquote.spot_top", lambda ex, s: seen.append(("spot", ex)) or (0.999, 1.0, None, None)), \
mock.patch("fastquote.fut_top", lambda ex, s: seen.append(("fut", ex)) or (1.008, 1.009, None, None)):
threading.Thread(target=self.e._fast_loop, daemon=True).start()
end = time.time() + 3
while self.e.positions and time.time() < end:
time.sleep(0.02)
self.assertEqual(self.e.positions, [])
self.assertIn(("spot", "Gate"), seen) # spot from A, perp from B
self.assertIn(("fut", "Binance"), seen)
self.assertIn("обычной", self.e.trades[0].reason)
def test_usual_survives_restart(self):
for i in range(400):
self.feed(1000.0 + i * 3, 1.0, 1.01)
self.e._save_usual(cross.time.time())
again = cross.CrossEngine(Path(self.dir.name), start=False)
self.assertAlmostEqual(again.usual["XYZ|Gate|Binance"], self.e.usual["XYZ|Gate|Binance"])
self.assertEqual(again.seen_since["XYZ|Gate|Binance"], 1000.0)
def test_settings_saved(self):
self.assertEqual(self.e.set_settings({"min_net_pct": "0.7", "use_mexc": False}), "")
again = cross.CrossEngine(Path(self.dir.name), start=False)
self.assertEqual((again.settings.min_net_pct, again.settings.use_mexc), (0.7, False))
def test_entry_decided_by_net_profit(self):
t = 1000.0
for i in range(400):
self.feed(t + i * 3, 1.0, 1.01) # usual ≈ 1.1 %
t += 400 * 3
self.e.settings.running = False
self.feed(t, 1.0, 1.0155) # +0.45 % over usual: net ≈ 0.45 − 0.05 − 0.3
row = self.e.view()["rows"][0]
fees = cross.round_trip_fee_pct("Gate", "Binance")
self.assertAlmostEqual(row["net_pct"], row["excess"] - 0.05 - fees, places=9)
self.assertLess(row["net_pct"], 0.2)
self.assertFalse(row["fits"])
self.assertEqual(row["why"], "чистая прибыль ниже порога")
self.e.settings.min_net_pct = 0.05 # the same link above a lower threshold
self.e.settings.running = True
self.e.settings.exit_hold_s = 0.0
self.e.step(t)
self.assertEqual(len(self.e.positions), 1)
def test_best_net_link_wins(self):
# the same coin on two perp exchanges: the link with the higher net profit is taken
t = 1000.0
for i in range(400):
spots = [q("Gate", "XYZ", 0.999, 1.0)]
futs = [q("Binance", "XYZ", 1.01, 1.011), q("Bybit", "XYZ", 1.01, 1.011)]
self.e.links = cross.build_links(spots, futs, set(arb.EXCHANGES))
self.e.learn(t + i * 3)
t += 1200
spots = [q("Gate", "XYZ", 0.999, 1.0)]
futs = [q("Binance", "XYZ", 1.02, 1.021), q("Bybit", "XYZ", 1.03, 1.031)]
self.e.links = cross.build_links(spots, futs, set(arb.EXCHANGES))
self.e.step(t)
self.assertEqual(self.e.positions[0].fut_ex, "Bybit")
if __name__ == "__main__":
unittest.main()