Files
2026-10-22 20:19:52 +03:00

125 lines
5.6 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: gaps, entry rules, exit at convergence, result with fees and funding, settings."""
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 basis # noqa: E402
def pair(base="NEW", spot=(1.000, 1.001), fut=(1.010, 1.011), depth=10_000.0, age=5.0, innovation=False, meme=False,
funding=0.0001, next_funding=0.0, turnover=1e6):
return basis.Pair(base, f"{base}USDT", f"{base}USDT", 1.0, spot[0], spot[1], fut[0], fut[1], depth, depth, depth,
depth, funding, next_funding, 8.0, turnover, turnover, age, innovation, meme)
class BasisTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.e = basis.BasisEngine("bybit", Path(self.dir.name), start=False)
self.e.settings.running = True
def tearDown(self):
self.dir.cleanup()
def test_gaps(self):
p = pair()
self.assertAlmostEqual(p.entry_gap, (1.010 / 1.001 - 1) * 100)
self.assertAlmostEqual(p.exit_gap, (1.011 / 1.000 - 1) * 100)
def test_universe(self):
s = basis.BasisSettings()
self.assertTrue(basis.in_universe(pair(age=10), s))
self.assertFalse(basis.in_universe(pair(age=400), s))
self.assertTrue(basis.in_universe(pair(age=400, meme=True), s))
self.assertTrue(basis.in_universe(pair(age=None, innovation=True), s))
s.use_memes = False
self.assertFalse(basis.in_universe(pair(age=400, meme=True), s))
s.all_coins = True
self.assertTrue(basis.in_universe(pair(age=400), s))
def test_entry_limits(self):
e = self.e
e.pairs = {"SMALL": pair("SMALL", fut=(1.003, 1.004)), # +0.2% < min 0.6%
"HUGE": pair("HUGE", fut=(1.2, 1.21)), # +19.9% > max 10%
"THIN": pair("THIN", depth=50.0), # less than the 100 $ amount at the best price
"OK": pair("OK")}
e.step(1000.0)
self.assertEqual([p.base for p in e.positions], ["OK"])
e.step(1001.0)
self.assertEqual(len(e.positions), 1) # one position per coin
def test_unknown_depth_is_not_checked(self):
p = pair("MX")
p.fut_bid_usd = None # MEXC futures / Gate: size at the best price unknown
self.assertIsNone(basis.entry_depth(p))
self.assertTrue(basis.depth_ok(p, self.e.settings))
p.spot_ask_usd = 10.0 # a known leg that is too thin still blocks
self.assertFalse(basis.depth_ok(p, self.e.settings))
def test_all_exchanges_registered(self):
self.assertEqual(set(basis.VENUES), {"bybit", "binance", "mexc", "htx", "gate"})
for key in ("binance", "mexc", "htx", "gate"):
v = basis.VENUES[key]()
self.assertGreater(v.spot_fee, 0)
self.assertIn(v.name.lower()[:3], v.fut_url(pair("ABC")).lower() + v.name.lower())
def test_stopped_opens_nothing(self):
self.e.settings.running = False
self.e.pairs = {"OK": pair("OK")}
self.e.step(1000.0)
self.assertEqual(self.e.positions, [])
def test_exit_on_convergence_with_fees_and_funding(self):
e = self.e
e.pairs = {"OK": pair("OK", next_funding=1500.0)}
e.step(1000.0)
pos = e.positions[0]
qty = 100 / 1.001
self.assertAlmostEqual(pos.qty, qty)
# funding settles while open: the short receives 0.01% of the position
e.pairs = {"OK": pair("OK", spot=(1.050, 1.051), fut=(1.050, 1.0505), next_funding=30000.0)}
e.step(1600.0) # exit gap 1.0505 / 1.050 − 1 = 0.048% ≤ 0.05%
self.assertEqual(e.positions, [])
t = e.trades[0]
self.assertAlmostEqual(t.funding, qty * 1.05025 * 0.0001) # settled before the exit in the same step
s = e.settings
spot_pnl = qty * (1.050 - 1.001)
fut_pnl = qty * (1.010 - 1.0505)
fees = qty * 1.001 * s.spot_fee / 100 + qty * 1.010 * s.fut_fee / 100 + qty * 1.050 * s.spot_fee / 100 \
+ qty * 1.0505 * s.fut_fee / 100
self.assertAlmostEqual(t.spot_pnl, spot_pnl)
self.assertAlmostEqual(t.fut_pnl, fut_pnl)
self.assertAlmostEqual(t.fees, fees)
self.assertAlmostEqual(t.net, spot_pnl + fut_pnl - fees + t.funding)
self.assertGreater(t.funding, 0)
self.assertEqual(t.reason, "разница сошлась")
e.step(1610.0) # cooldown: no re-entry right away
self.assertEqual(e.positions, [])
def test_settings_saved_and_checked(self):
self.assertEqual(self.e.set_settings({"min_gap_pct": "0.8", "use_memes": False, "max_positions": "3"}), "")
again = basis.BasisEngine("bybit", Path(self.dir.name), start=False)
self.assertEqual((again.settings.min_gap_pct, again.settings.use_memes, again.settings.max_positions),
(0.8, False, 3))
self.assertTrue(self.e.set_settings({"min_gap_pct": "0.01", "exit_gap_pct": "0.05"}))
def test_manual_close_and_view(self):
e = self.e
e.pairs = {"OK": pair("OK")}
e.step(1000.0)
v = e.view()
self.assertEqual(v["stats"]["open"], 1)
self.assertTrue(v["rows"][0]["fits"] is False or v["rows"][0]["base"] == "OK")
self.assertIn("закрыто позиций: 1", e.close(None))
self.assertEqual(e.view()["stats"]["trades"], 1)
if __name__ == "__main__":
unittest.main()