1031 lines
52 KiB
Python
1031 lines
52 KiB
Python
"""Real trading: encrypted key storage, request signing, the simulator's order mirror and real spot–futures trades.
|
||
No request reaches an exchange: the HTTP layer and the clients are replaced by fakes."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import hmac
|
||
import json
|
||
import sys
|
||
import tempfile
|
||
import threading
|
||
import time
|
||
import unittest
|
||
import urllib.parse
|
||
from pathlib import Path
|
||
from types import SimpleNamespace
|
||
from unittest import mock
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
|
||
import basis # noqa: E402
|
||
import keystore # noqa: E402
|
||
import live # noqa: E402
|
||
import real_mirror # noqa: E402
|
||
|
||
|
||
_TEST_DIR = tempfile.mkdtemp()
|
||
|
||
|
||
def setUpModule():
|
||
# for the whole run (no stop): background threads of the fakes outlive single tests and must never write
|
||
# into the user's own journal of real orders
|
||
mock.patch.object(real_mirror, "JOURNAL", Path(_TEST_DIR) / "journal.jsonl").start()
|
||
|
||
|
||
def wait(cond, timeout=3.0):
|
||
end = time.time() + timeout
|
||
while time.time() < end:
|
||
if cond():
|
||
return True
|
||
time.sleep(0.02)
|
||
return False
|
||
|
||
|
||
class KeystoreTests(unittest.TestCase):
|
||
def test_encrypted_roundtrip_and_no_secret_in_summary(self):
|
||
with tempfile.TemporaryDirectory() as folder:
|
||
path = Path(folder) / "k.bin"
|
||
self.assertEqual(keystore.set_keys("bybit", " KEY1234567890 ", "SECRETabcdef", path), "")
|
||
raw = path.read_bytes()
|
||
self.assertNotIn(b"SECRETabcdef", raw) # not stored in plain text
|
||
self.assertNotIn(b"KEY1234567890", raw)
|
||
self.assertEqual(keystore.get("bybit", path), ("KEY1234567890", "SECRETabcdef"))
|
||
summary = keystore.summary(path)
|
||
self.assertTrue(summary["bybit"]["set"])
|
||
self.assertEqual(summary["bybit"]["key"], "KEY1…7890")
|
||
self.assertNotIn("SECRET", json.dumps(summary))
|
||
self.assertFalse(summary["gate"]["set"])
|
||
self.assertTrue(keystore.set_keys("bybit", "", "x", path)) # both needed
|
||
self.assertTrue(keystore.set_keys("bybit", "a b", "x", path)) # no spaces
|
||
keystore.delete_keys("bybit", path)
|
||
self.assertIsNone(keystore.get("bybit", path))
|
||
|
||
|
||
class SigningTests(unittest.TestCase):
|
||
def test_binance_signature_matches_documentation_example(self):
|
||
# the example from Binance's API documentation (SIGNED endpoint security)
|
||
secret = "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
|
||
query = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000×tamp=1499827319559"
|
||
self.assertEqual(hmac.new(secret.encode(), query.encode(), hashlib.sha256).hexdigest(),
|
||
"c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71")
|
||
|
||
def test_binance_request_is_signed_query(self):
|
||
seen = {}
|
||
|
||
def fake(method, url, headers=None, body=None):
|
||
if "/userTrades" in url: # the fee actually charged
|
||
return [{"commission": "0.0021"}, {"commission": "0.0004"}]
|
||
seen.update(method=method, url=url, headers=headers)
|
||
return {"executedQty": "10", "cumQuote": "5", "orderId": 7, "status": "FILLED"}
|
||
|
||
c = live.Binance("K", "S")
|
||
c.rules["fut:XUSDT"] = {"step": 1.0, "min": 1.0}
|
||
with mock.patch.object(live, "_http", fake):
|
||
fill = c.fut_order("XUSDT", "sell", 10.7, reduce_only=True)
|
||
query = seen["url"].split("?", 1)[1]
|
||
unsigned, sig = query.rsplit("&signature=", 1)
|
||
self.assertEqual(sig, hmac.new(b"S", unsigned.encode(), hashlib.sha256).hexdigest())
|
||
self.assertIn("quantity=10", unsigned) # rounded down to the lot step
|
||
self.assertIn("reduceOnly=true", unsigned)
|
||
self.assertEqual(seen["headers"]["X-MBX-APIKEY"], "K")
|
||
self.assertAlmostEqual(fill.price, 0.5)
|
||
self.assertAlmostEqual(fill.fee_usd, 5 * 0.05 / 100) # estimate: the charged fee comes with the sync
|
||
self.assertFalse(fill.exact)
|
||
|
||
def test_bybit_units_for_1000_symbols(self):
|
||
calls = []
|
||
|
||
def fake_call(method, path, params=None):
|
||
calls.append((method, path, params))
|
||
if path == "/v5/order/create":
|
||
return {"orderId": "A1"}
|
||
return {"list": [{"orderStatus": "Filled", "cumExecQty": "3", "cumExecValue": "0.03", "cumExecFee": "0"}]}
|
||
|
||
c = live.Bybit("K", "S")
|
||
c.rules["linear:1000PEPEUSDT"] = {"step": 1.0, "min": 1.0}
|
||
with mock.patch.object(c, "_call", fake_call):
|
||
fill = c.fut_order("1000PEPEUSDT", "sell", 3500.0, reduce_only=False)
|
||
order = calls[0][2]
|
||
self.assertEqual(order["qty"], "3") # 3500 PEPE = 3 units of 1000PEPE
|
||
self.assertEqual(order["side"], "Sell")
|
||
self.assertEqual(fill.coins, 3000.0)
|
||
self.assertAlmostEqual(fill.price, 0.03 / 3000)
|
||
|
||
def test_bybit_tp_sl_on_the_opening_order(self):
|
||
calls = []
|
||
|
||
def fake_call(method, path, params=None):
|
||
calls.append((path, params))
|
||
if path == "/v5/order/create":
|
||
return {"orderId": "A1"}
|
||
return {"list": [{"orderStatus": "Filled", "cumExecQty": "4", "cumExecValue": "0.048", "cumExecFee": "0"}]}
|
||
|
||
c = live.Bybit("K", "S")
|
||
c.rules["linear:1000PEPEUSDT"] = {"step": 1.0, "min": 1.0, "tick": 0.0000001}
|
||
with mock.patch.object(c, "_call", fake_call):
|
||
fill = c.fut_order("1000PEPEUSDT", "buy", 4000.0, reduce_only=False, tp=0.00001234567, sl=0.0000110)
|
||
order = calls[0][1]
|
||
self.assertEqual((order["takeProfit"], order["stopLoss"], order["tpslMode"]), ("0.0123457", "0.011", "Full"))
|
||
self.assertEqual(fill.tpsl, "на бирже")
|
||
|
||
def test_binance_tp_sl_as_close_position_orders(self):
|
||
posts = []
|
||
|
||
def fake(method, url, headers=None, body=None):
|
||
q = dict(urllib.parse.parse_qsl(url.split("?", 1)[1]))
|
||
if "/fapi/v1/order" in url:
|
||
posts.append(q)
|
||
return {"executedQty": "10", "cumQuote": "5", "orderId": 7, "status": "FILLED"}
|
||
return []
|
||
|
||
c = live.Binance("K", "S")
|
||
c.rules["fut:XUSDT"] = {"step": 1.0, "min": 1.0, "tick": 0.001}
|
||
with mock.patch.object(live, "_http", fake):
|
||
fill = c.fut_order("XUSDT", "sell", 10, reduce_only=False, tp=0.4512, sl=0.5523)
|
||
kinds = [(p["type"], p.get("stopPrice"), p.get("side"), p.get("closePosition")) for p in posts]
|
||
self.assertEqual(kinds, [("MARKET", None, "SELL", None), ("TAKE_PROFIT_MARKET", "0.451", "BUY", "true"),
|
||
("STOP_MARKET", "0.552", "BUY", "true")])
|
||
self.assertEqual(fill.tpsl, "на бирже")
|
||
|
||
def test_mexc_tp_sl_attached(self):
|
||
sent = {}
|
||
|
||
def fake_fut(method, path, params=None):
|
||
if path.endswith("/submit"):
|
||
sent.update(params)
|
||
return {"orderId": "1"}
|
||
return {"dealVol": 10, "dealAvgPrice": 0.5, "state": 3, "takerFee": 0.0025}
|
||
|
||
c = live.Mexc("K", "S")
|
||
c.rules["fut:X_USDT"] = {"size": 1.0, "min": 1.0, "tick": 0.0001}
|
||
with mock.patch.object(c, "_fut", fake_fut):
|
||
fill = c.fut_order("X_USDT", "buy", 10, reduce_only=False, tp=0.51234, sl=0.48)
|
||
self.assertEqual((sent["takeProfitPrice"], sent["stopLossPrice"]), (0.5123, 0.48))
|
||
self.assertEqual((fill.fee_usd, fill.tpsl), (0.0025, "на бирже"))
|
||
|
||
def test_gate_signature(self):
|
||
seen = {}
|
||
|
||
def fake(method, url, headers=None, body=None):
|
||
seen.update(headers=headers, body=body)
|
||
return [{"available": "12.5"}]
|
||
|
||
c = live.Gate("K", "S")
|
||
with mock.patch.object(live, "_http", fake), mock.patch.object(live.time, "time", return_value=1700000000):
|
||
self.assertEqual(c.spot_free("PEPE"), 12.5)
|
||
payload = "\n".join(["GET", "/api/v4/spot/accounts", "currency=PEPE", hashlib.sha512(b"").hexdigest(), "1700000000"])
|
||
self.assertEqual(seen["headers"]["SIGN"], hmac.new(b"S", payload.encode(), hashlib.sha512).hexdigest())
|
||
|
||
def test_mexc_order_id_in_new_answer_form(self):
|
||
# MEXC answers a futures submit with {"orderId": "...", "ts": ...}; the id went into the URL as a dict
|
||
self.assertEqual(live.mexc_order_id({"orderId": "866514674990256896", "ts": 1}), "866514674990256896")
|
||
self.assertEqual(live.mexc_order_id(866514674990256896), "866514674990256896")
|
||
calls = []
|
||
|
||
def fake_fut(method, path, params=None):
|
||
calls.append(path)
|
||
if path.endswith("/submit"):
|
||
return {"orderId": "8665", "ts": 1}
|
||
return {"dealVol": 83, "dealAvgPrice": 0.00626, "state": 3}
|
||
|
||
c = live.Mexc("K", "S")
|
||
c.rules["fut:CLAUDIA_USDT"] = {"size": 1.0, "min": 1.0}
|
||
with mock.patch.object(c, "_fut", fake_fut):
|
||
fill = c.fut_order("CLAUDIA_USDT", "buy", 83.4, reduce_only=False)
|
||
self.assertEqual(calls[1], "/api/v1/private/order/get/8665")
|
||
self.assertEqual((fill.coins, fill.price), (83.0, 0.00626))
|
||
|
||
def test_failure_after_accept_is_marked_sent(self):
|
||
def fake_fut(method, path, params=None):
|
||
if path.endswith("/submit"):
|
||
return {"orderId": "77"}
|
||
raise live.LiveError("MEXC фьючерсы 513: Invalid request")
|
||
|
||
c = live.Mexc("K", "S")
|
||
c.rules["fut:X_USDT"] = {"size": 1.0, "min": 1.0}
|
||
with mock.patch.object(c, "_fut", fake_fut):
|
||
with self.assertRaises(live.LiveError) as err:
|
||
c.fut_order("X_USDT", "buy", 10, reduce_only=False)
|
||
self.assertTrue(err.exception.sent)
|
||
self.assertEqual(err.exception.order_id, "77")
|
||
# an exchange refusing the order itself: nothing was placed
|
||
with mock.patch.object(c, "_fut", side_effect=live.LiveError("отказ")):
|
||
with self.assertRaises(live.LiveError) as err:
|
||
c.fut_order("X_USDT", "buy", 10, reduce_only=False)
|
||
self.assertFalse(err.exception.sent)
|
||
|
||
def test_ensure_usdt(self):
|
||
fake = FakeClient()
|
||
fake.usdt = {"spot": 10.0, "futures": 1.0}
|
||
self.assertEqual(live.ensure_usdt(fake, 2.0, 5.0), "переведено 4.01 USDT со спота на фьючерсы")
|
||
self.assertEqual(live.ensure_usdt(fake, 2.0, 5.0), "") # nothing more needed
|
||
with self.assertRaises(live.LiveError):
|
||
live.ensure_usdt(fake, 8.0, 8.0) # 11 in total < 16
|
||
bybit = live.Bybit("K", "S")
|
||
self.assertEqual(live.ensure_usdt(bybit, 100, 100), "") # unified: never moves
|
||
|
||
def test_mexc_transfer_request(self):
|
||
seen = {}
|
||
|
||
def fake(method, url, headers=None, body=None):
|
||
seen.update(method=method, url=url)
|
||
return {"tranId": "1"}
|
||
|
||
with mock.patch.object(live, "_http", fake):
|
||
live.Mexc("K", "S").transfer_usdt("futures", 5.47)
|
||
self.assertEqual(seen["method"], "POST")
|
||
self.assertIn("/api/v3/capital/transfer?", seen["url"])
|
||
self.assertIn("fromAccountType=SPOT&toAccountType=FUTURES&asset=USDT&amount=5.47", seen["url"])
|
||
|
||
def test_no_keys(self):
|
||
with mock.patch.object(keystore, "get", return_value=None):
|
||
with self.assertRaises(live.LiveError):
|
||
live.client("bybit")
|
||
|
||
|
||
class FakeClient:
|
||
def __init__(self, fail_fut=False, price=1.0):
|
||
self.orders = []
|
||
self.fail_fut, self.price = fail_fut, price
|
||
self.spot_balance = 0.0
|
||
self.fail_spot_sell = False
|
||
self.unconfirmed = 0 # next N futures orders: executed, but the fill is not confirmed (MEXC 513)
|
||
self.fail_close = 0 # next N reduce-only closes refused
|
||
self.partial_close = 0.0 # next reduce-only close leaves this many coins open
|
||
self.position = 0.0 # the exchange's perp position, coins (+ long, − short)
|
||
self.tpsl = [] # (tp, sl) sent with opening orders
|
||
self.limits = {} # resting limit orders by id
|
||
self.exchange_closes = [] # fills of closes the exchange made itself (TP / SL)
|
||
self.cancelled = 0
|
||
self.take_profits = [] # reduce-only limit TP orders: (side, coins, price)
|
||
|
||
def exchange_hits(self, price):
|
||
"""The exchange's TP or SL fires: the whole position closed at `price`."""
|
||
coins = abs(self.position)
|
||
self.exchange_closes.append(live.Fill(coins, price, coins * price * 0.0005, "TP1"))
|
||
self.position = 0.0
|
||
|
||
def fut_closes(self, symbol, side, since):
|
||
return list(self.exchange_closes)
|
||
|
||
def fut_cancel_all(self, symbol):
|
||
self.cancelled += 1
|
||
|
||
def fut_take_profit(self, symbol, side, coins, price):
|
||
self.take_profits.append((side, round(coins, 6), price))
|
||
oid = f"TPL{len(self.take_profits)}"
|
||
self.limits[oid] = {"coins": coins, "filled": 0.0, "price": price, "side": side, "open": True}
|
||
return oid
|
||
|
||
# resting limit orders: `limit_fill` = the share of an entry order that fills at once
|
||
limit_fill = 1.0
|
||
|
||
def fut_limit(self, symbol, side, coins, price, reduce_only=False):
|
||
self.orders.append(("fut_limit", side, round(coins, 6), reduce_only))
|
||
oid = f"L{len(self.limits) + 1}"
|
||
filled = coins * self.limit_fill
|
||
self.position += filled if side == "buy" else -filled
|
||
self.limits[oid] = {"coins": coins, "filled": filled, "price": price, "side": side, "open": filled < coins}
|
||
return oid
|
||
|
||
def fill_take_profit(self, oid):
|
||
"""The exchange fills a resting TP completely (the short is bought back)."""
|
||
o = self.limits[oid]
|
||
self.position += o["coins"] if o["side"] == "buy" else -o["coins"]
|
||
o["filled"], o["open"] = o["coins"], False
|
||
|
||
def fut_order_status(self, symbol, oid):
|
||
o = self.limits[oid]
|
||
return {"coins": o["filled"], "price": o["price"], "fee": o["filled"] * o["price"] * 0.0002,
|
||
"final": not o["open"]}
|
||
|
||
def fut_cancel(self, symbol, oid):
|
||
self.orders.append(("fut_cancel", oid))
|
||
self.limits[oid]["open"] = False
|
||
|
||
def fut_order(self, symbol, side, coins, reduce_only, tp=None, sl=None):
|
||
self.orders.append(("fut", side, round(coins, 6), reduce_only))
|
||
if tp or sl:
|
||
self.tpsl.append((tp, sl))
|
||
if reduce_only and self.fail_close:
|
||
self.fail_close -= 1
|
||
raise live.LiveError("сеть")
|
||
if self.fail_fut and not reduce_only:
|
||
raise live.LiveError("отказ биржи")
|
||
sign = 1 if side == "buy" else -1
|
||
done = coins
|
||
if reduce_only:
|
||
done = min(coins, abs(self.position)) - self.partial_close
|
||
self.partial_close = 0.0
|
||
self.position += sign * done
|
||
if self.unconfirmed:
|
||
self.unconfirmed -= 1
|
||
raise live.LiveError("принят, не подтверждён", sent=True, order_id="X1")
|
||
return live.Fill(done, self.price, done * self.price * 0.0005, "F1", tpsl="на бирже" if tp or sl else "")
|
||
|
||
def fut_position(self, symbol):
|
||
return self.position
|
||
|
||
unified = False
|
||
usdt = None # {"spot": x, "futures": y}; None = plenty everywhere
|
||
|
||
def usdt_free(self):
|
||
return dict(self.usdt) if self.usdt is not None else {"spot": 1e6, "futures": 1e6}
|
||
|
||
def transfer_usdt(self, to, amount):
|
||
self.orders.append(("transfer", to, round(amount, 2)))
|
||
other = "spot" if to == "futures" else "futures"
|
||
self.usdt[to] += amount
|
||
self.usdt[other] -= amount
|
||
|
||
def fut_min_coins(self, symbol):
|
||
return 1.0
|
||
|
||
def fut_round(self, symbol, coins):
|
||
return float(int(coins))
|
||
|
||
def spot_buy(self, base, usdt):
|
||
coins = usdt / self.price
|
||
self.orders.append(("spot", "buy", round(coins, 6)))
|
||
self.spot_balance += coins * 0.999
|
||
return live.Fill(coins, self.price, usdt * 0.001, "S1")
|
||
|
||
def spot_sell(self, base, coins):
|
||
if self.fail_spot_sell:
|
||
raise live.LiveError("сеть")
|
||
self.orders.append(("spot", "sell", round(coins, 6)))
|
||
self.spot_balance -= coins
|
||
return live.Fill(coins, self.price, coins * self.price * 0.001, "S2")
|
||
|
||
def spot_free(self, base):
|
||
return self.spot_balance
|
||
|
||
|
||
class FillsToTradesTests(unittest.TestCase):
|
||
# the user's real CLAUDIA trades on MEXC (2026-10-17): fills as the exchange reports them
|
||
MEXC = [
|
||
{"time": 1, "side": "buy", "coins": 700.0, "price": 0.007371, "fee": 0.00412776, "pnl": None, "order": "a"},
|
||
{"time": 2, "side": "sell", "coins": 700.0, "price": 0.00738, "fee": 0.0041328, "pnl": 0.0063, "order": "b"},
|
||
{"time": 3, "side": "sell", "coins": 710.0, "price": 0.007311, "fee": 0.00415264, "pnl": None, "order": "c"},
|
||
{"time": 4, "side": "buy", "coins": 710.0, "price": 0.007275, "fee": 0.0041322, "pnl": 0.02556, "order": "d"},
|
||
]
|
||
|
||
def test_mexc_trades_match_the_exchange(self):
|
||
long_, short = real_mirror.trades_from_fills(self.MEXC)
|
||
self.assertEqual((long_["side"], short["side"]), ("LONG", "SHORT"))
|
||
self.assertAlmostEqual(long_["gross"], 0.0063) # exchange PNL column
|
||
self.assertAlmostEqual(short["gross"], 0.02556)
|
||
self.assertAlmostEqual(short["fees"], 0.00415264 + 0.0041322) # both sides' fees
|
||
self.assertAlmostEqual(short["net"], 0.02556 - 0.00415264 - 0.0041322)
|
||
self.assertAlmostEqual(short["entry"], 0.007311)
|
||
self.assertAlmostEqual(short["exit"], 0.007275)
|
||
|
||
def test_without_exchange_pnl_partial_closes(self):
|
||
fills = [{"time": 1, "side": "sell", "coins": 10.0, "price": 2.0, "fee": 0.01, "pnl": None, "order": "1"},
|
||
{"time": 2, "side": "buy", "coins": 4.0, "price": 1.9, "fee": 0.004, "pnl": None, "order": "2"},
|
||
{"time": 3, "side": "buy", "coins": 6.0, "price": 1.8, "fee": 0.006, "pnl": None, "order": "3"}]
|
||
(t,) = real_mirror.trades_from_fills(fills)
|
||
self.assertAlmostEqual(t["gross"], 4 * 0.1 + 6 * 0.2)
|
||
self.assertAlmostEqual(t["fees"], 0.02)
|
||
self.assertAlmostEqual(t["exit"], (4 * 1.9 + 6 * 1.8) / 10)
|
||
|
||
def test_open_and_close_in_the_same_second(self):
|
||
# the user's 22:52:59 long: MEXC reports both with the same second, the close listed first
|
||
fills = [{"time": 10, "side": "sell", "coins": 720.0, "price": 0.00718, "fee": 0.00413568, "pnl": -0.0144,
|
||
"order": "866528018455402243", "close": True},
|
||
{"time": 10, "side": "buy", "coins": 720.0, "price": 0.0072, "fee": 0.0041472, "pnl": None,
|
||
"order": "866528018103081728", "close": False}]
|
||
(t,) = real_mirror.trades_from_fills(fills)
|
||
self.assertEqual(t["side"], "LONG")
|
||
self.assertAlmostEqual(t["entry"], 0.0072)
|
||
self.assertAlmostEqual(t["gross"], -0.0144)
|
||
|
||
def test_open_position_is_not_a_trade(self):
|
||
self.assertEqual(real_mirror.trades_from_fills(self.MEXC + [
|
||
{"time": 5, "side": "buy", "coins": 5.0, "price": 1.0, "fee": 0.0, "pnl": None, "order": "e"}]).__len__(), 2)
|
||
|
||
|
||
class MirrorTests(unittest.TestCase):
|
||
def setUp(self):
|
||
self.dir = tempfile.TemporaryDirectory()
|
||
self.client = FakeClient(price=0.5)
|
||
self.settings = {"coins": {"k": {"on": True, "since": time.time() - 60}}, "exchange_tpsl": True}
|
||
self.journal = mock.patch.object(real_mirror, "JOURNAL", Path(self.dir.name) / "j.jsonl")
|
||
self.journal.start()
|
||
|
||
def tearDown(self):
|
||
self.journal.stop()
|
||
self.dir.cleanup()
|
||
|
||
def mirror(self, symbol="XUSDT"):
|
||
m = real_mirror.FuturesMirror("k", "X", "bybit", symbol, Path(self.dir.name),
|
||
client_for=lambda ex: self.client, settings=lambda: self.settings)
|
||
m.RETRY_S = 0.05
|
||
return m
|
||
|
||
def test_one_trade_at_a_time_until_exchange_confirms_close(self):
|
||
m = self.mirror()
|
||
self.assertEqual(m.gate(), "")
|
||
m.hook("open", SimpleNamespace(uid=1, side="SHORT", qty=30.0, entry=0.5))
|
||
self.assertTrue(m.gate()) # blocked from the very first moment
|
||
m.hook("open", SimpleNamespace(uid=2, side="SHORT", qty=30.0, entry=0.5)) # ignored: one at a time
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
self.assertTrue(m.gate())
|
||
m.hook("close", SimpleNamespace(uid=2)) # not the real one: nothing sent
|
||
m.hook("close", SimpleNamespace(uid=1))
|
||
self.assertTrue(wait(lambda: len(m.trades) == 1))
|
||
self.assertEqual(m.gate(), "")
|
||
self.assertEqual(self.client.orders, [("fut", "sell", 30.0, False), ("fut", "buy", 30.0, True)])
|
||
t = m.trades[0]
|
||
self.assertAlmostEqual(t["fees"], 2 * 30 * 0.5 * 0.0005) # the exchange's fees, not estimates
|
||
self.assertEqual(m.view()["trades"], 1)
|
||
|
||
def test_switch_off_opens_nothing_but_still_closes(self):
|
||
m = self.mirror()
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
self.settings["coins"]["k"]["on"] = False
|
||
self.assertEqual(m.gate(), "") # real mode off: paper trades free
|
||
m.hook("close", SimpleNamespace(uid=1))
|
||
self.assertTrue(wait(lambda: len(m.trades) == 1))
|
||
self.assertEqual([o[1:] for o in self.client.orders], [("buy", 10.0, False), ("sell", 10.0, True)])
|
||
|
||
def test_multiplied_symbol_sends_coins(self):
|
||
m = self.mirror("1000PEPEUSDT")
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=4.0, entry=0.012))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
self.assertEqual(self.client.orders[0], ("fut", "buy", 4000.0, False))
|
||
|
||
def test_unconfirmed_open_checked_on_exchange_and_closed(self):
|
||
# the incident: MEXC filled the open, the fill check failed → the position must still be closed
|
||
self.client.unconfirmed = 1
|
||
m = self.mirror()
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=83.0, entry=0.00626))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
self.assertFalse(m.position["exact"])
|
||
m.hook("close", SimpleNamespace(uid=1))
|
||
self.assertTrue(wait(lambda: len(m.trades) == 1))
|
||
self.assertEqual(self.client.orders[-1], ("fut", "sell", 83.0, True))
|
||
self.assertEqual(self.client.position, 0)
|
||
|
||
def test_failed_real_open_closes_paper_twin(self):
|
||
self.client.fail_fut = True
|
||
closed = []
|
||
m = self.mirror()
|
||
m.on_failed_open = closed.append
|
||
m.hook("open", SimpleNamespace(uid=7, side="LONG", qty=10.0, entry=0.5))
|
||
self.assertTrue(wait(lambda: closed == [7]))
|
||
self.assertIn("пауза", m.gate()) # a short pause after a refusal
|
||
self.assertEqual(m.state, "")
|
||
|
||
def test_close_retried_and_remainder_closed(self):
|
||
m = self.mirror()
|
||
m.hook("open", SimpleNamespace(uid=1, side="SHORT", qty=10.0, entry=0.5))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
self.client.fail_close = 2 # two refusals
|
||
self.client.partial_close = 3.0 # then 3 coins stay open
|
||
m.hook("close", SimpleNamespace(uid=1))
|
||
self.assertTrue(wait(lambda: len(m.trades) == 1))
|
||
closes = [o for o in self.client.orders if o[3]]
|
||
self.assertEqual([o[2] for o in closes], [10.0, 10.0, 10.0, 3.0]) # refused ×2, partial, remainder
|
||
self.assertEqual(self.client.position, 0)
|
||
self.assertEqual(m.gate(), "")
|
||
|
||
def test_sl_with_entry_tp_limit_from_real_fill_and_exchange_close_detected(self):
|
||
self.settings["sl_pct"] = 1.5
|
||
m = self.mirror("1000PEPEUSDT")
|
||
m.WATCH_S = 0.05
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=4.0, entry=0.0120, target=0.0123, stop=0.0060))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
tp, sl = self.client.tpsl[0]
|
||
self.assertIsNone(tp) # no TP on the market entry any more
|
||
self.assertAlmostEqual(sl, 0.0120 / 1000 * (1 - 0.015)) # stop 1.5 % (setting), per coin
|
||
side, coins, tp_price = self.client.take_profits[0]
|
||
self.assertEqual((side, coins), ("sell", 4000.0)) # reduce-only limit closing the long
|
||
self.assertAlmostEqual(tp_price, 0.5 * 1.025) # the paper distance (+2.5 %) from the REAL fill
|
||
self.client.exchange_hits(0.6) # the exchange's TP fires by itself
|
||
self.assertTrue(wait(lambda: len(m.trades) == 1))
|
||
t = m.trades[0]
|
||
self.assertIn("TP/SL", t["reason"])
|
||
self.assertAlmostEqual(t["exit"], 0.6) # the exchange's own fill
|
||
self.assertEqual(self.client.cancelled, 1) # orders cancelled once, not twice
|
||
self.assertEqual(m.gate(), "")
|
||
n = len(self.client.orders)
|
||
m.hook("close", SimpleNamespace(uid=1)) # the paper twin closes later
|
||
time.sleep(0.15)
|
||
self.assertEqual(len(self.client.orders), n) # nothing more is sent
|
||
|
||
def test_paper_close_after_exchange_tp_uses_exchange_fills(self):
|
||
self.settings["exchange_tpsl"] = True
|
||
m = self.mirror()
|
||
m.WATCH_S = 30 # the watcher does not get there first
|
||
m.hook("open", SimpleNamespace(uid=1, side="SHORT", qty=10.0, entry=0.5, target=0.49, stop=0.52))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
self.client.exchange_hits(0.49)
|
||
m.hook("close", SimpleNamespace(uid=1))
|
||
self.assertTrue(wait(lambda: len(m.trades) == 1))
|
||
self.assertEqual([o for o in self.client.orders if o[3]], []) # no reduce-only order was needed
|
||
self.assertEqual(self.client.cancelled, 1) # orders cancelled once, not twice
|
||
self.assertAlmostEqual(m.trades[0]["exit"], 0.49)
|
||
self.assertGreater(m.trades[0]["net"], 0)
|
||
|
||
def test_tp_never_closer_than_two_fees_and_on_the_right_side(self):
|
||
# the incident: the real long filled ABOVE the paper TP — the TP must still be above the real entry
|
||
self.client.price = 0.007200
|
||
m = self.mirror()
|
||
# paper TP only +0.083 % — less than two real fees: pushed out to two fees + margin
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=720.0, entry=0.007189, target=0.007195, stop=0.0036))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
_, _, tp = self.client.take_profits[0]
|
||
fee = 0.05 # the fake exchange charges 0.05 %
|
||
self.assertGreater(tp, 0.007200)
|
||
self.assertAlmostEqual(tp, 0.007200 * (1 + (2 * fee + m.TP_MARGIN_PCT) / 100))
|
||
self.assertAlmostEqual(real_mirror.FEES["bybit"], fee) # the measured rate, for the paper model
|
||
|
||
def test_short_tp_below_real_fill(self):
|
||
self.client.price = 0.007075
|
||
m = self.mirror()
|
||
m.hook("open", SimpleNamespace(uid=1, side="SHORT", qty=720.0, entry=0.007137, target=0.007107, stop=0.0107))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
side, _, tp = self.client.take_profits[0]
|
||
self.assertEqual(side, "buy")
|
||
self.assertLess(tp, 0.007075) # below the real short entry
|
||
_, sl = self.client.tpsl[0]
|
||
self.assertAlmostEqual(sl, 0.007137 * 1.015)
|
||
|
||
def test_tpsl_off_sends_plain_order(self):
|
||
self.settings["exchange_tpsl"] = False
|
||
m = self.mirror()
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5, target=0.51, stop=0.49))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
self.assertEqual(self.client.tpsl, [])
|
||
self.assertEqual(self.client.take_profits, [])
|
||
|
||
def test_refused_entry_pauses_the_coin(self):
|
||
# MEXC 6002: the account may not open positions — no new trade (paper or real) for a long pause
|
||
self.client.fail_fut = True
|
||
closed = []
|
||
m = self.mirror()
|
||
m.on_failed_open = closed.append
|
||
with mock.patch.object(self.client, "fut_order", side_effect=live.LiveError(
|
||
"MEXC фьючерсы 6002: Your futures position-opening has been restricted.")):
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5))
|
||
self.assertTrue(wait(lambda: closed == [1]))
|
||
self.assertIn("пауза", m.gate())
|
||
self.assertGreater(m.view()["paused_s"], 800)
|
||
m.hook("open", SimpleNamespace(uid=2, side="LONG", qty=10.0, entry=0.5)) # a bypassed gate: still ignored
|
||
time.sleep(0.1)
|
||
self.assertEqual(closed, [1])
|
||
m.paused_until = 0 # the pause is over
|
||
self.assertEqual(m.gate(), "")
|
||
|
||
def test_ordinary_refusal_short_pause(self):
|
||
self.client.fail_fut = True
|
||
m = self.mirror()
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5))
|
||
self.assertTrue(wait(lambda: m.view()["paused_s"] > 0))
|
||
self.assertLessEqual(m.view()["paused_s"], m.PAUSE_S)
|
||
|
||
def test_no_entry_while_ping_is_high(self):
|
||
self.settings["max_ping_ms"] = 400
|
||
m = self.mirror()
|
||
m.ping = lambda: 650.0
|
||
self.assertIn("пинг до биржи 650 мс", m.gate())
|
||
m.ping = lambda: 200.0
|
||
self.assertEqual(m.gate(), "")
|
||
m.ping = lambda: None # no fresh measurement: not blocked
|
||
self.assertEqual(m.gate(), "")
|
||
self.settings["max_ping_ms"] = 0 # check switched off
|
||
m.ping = lambda: 5000.0
|
||
self.assertEqual(m.gate(), "")
|
||
|
||
def test_ping_and_slippage_go_to_the_journal(self):
|
||
m = self.mirror()
|
||
m.ping = lambda: 230.0
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5))
|
||
self.assertTrue(wait(lambda: m.state == "open"))
|
||
event = next(e for e in reversed(real_mirror.RECENT) if e["action"] == "open" and e["ok"])
|
||
self.assertEqual(event["ping"], 230.0)
|
||
self.assertIn("пинг 230 мс", event["text"])
|
||
|
||
def test_fee_rate_learned_from_history_sync(self):
|
||
fills = [{"time": 1, "side": "buy", "coins": 100.0, "price": 1.0, "fee": 0.08, "pnl": None, "order": "1"},
|
||
{"time": 2, "side": "sell", "coins": 100.0, "price": 1.0, "fee": 0.08, "pnl": 0.0, "order": "2"}]
|
||
self.client.fut_fills = lambda symbol, since: fills
|
||
m = self.mirror()
|
||
m.sync()
|
||
self.assertAlmostEqual(real_mirror.FEES["bybit"], 0.08)
|
||
|
||
def test_close_retry_backs_off(self):
|
||
m = self.mirror()
|
||
m.RETRY_S, m.RETRY_MAX_S = 10.0, 30.0 # only the delays are looked at
|
||
m.position = {"side": "LONG"}
|
||
delays = []
|
||
with mock.patch.object(real_mirror.threading, "Timer", lambda d, fn: delays.append(d) or mock.Mock()):
|
||
for _ in range(5):
|
||
m._retry_close("x")
|
||
self.assertEqual(delays, [10.0, 15.0, 22.5, 30.0, 30.0])
|
||
|
||
def test_real_mode_is_per_coin(self):
|
||
other = real_mirror.FuturesMirror("other", "Y", "bybit", "YUSDT", Path(self.dir.name),
|
||
client_for=lambda ex: self.client, settings=lambda: self.settings)
|
||
other.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5))
|
||
time.sleep(0.1)
|
||
self.assertEqual(self.client.orders, []) # not switched on for this coin
|
||
self.assertFalse(other.view()["enabled"])
|
||
self.assertTrue(self.mirror().view()["enabled"])
|
||
|
||
def test_statistics_come_from_exchange_history(self):
|
||
fills = [{"time": time.time() - 30, "side": "buy", "coins": 700.0, "price": 0.007371, "fee": 0.00412776,
|
||
"pnl": None, "order": "1"},
|
||
{"time": time.time() - 28, "side": "sell", "coins": 700.0, "price": 0.00738, "fee": 0.0041328,
|
||
"pnl": 0.0063, "order": "2"}]
|
||
self.client.fut_fills = lambda symbol, since: fills
|
||
m = self.mirror()
|
||
m.sync()
|
||
v = m.view()
|
||
self.assertEqual(v["source"], "биржа")
|
||
self.assertEqual(v["trades"], 1)
|
||
self.assertAlmostEqual(v["gross"], 0.0063)
|
||
self.assertAlmostEqual(v["fees"], 0.00412776 + 0.0041328)
|
||
self.assertAlmostEqual(v["net"], 0.0063 - 0.00412776 - 0.0041328)
|
||
|
||
def test_orphan_closed_after_restart(self):
|
||
m = self.mirror()
|
||
m.hook("open", SimpleNamespace(uid=1, side="LONG", qty=10.0, entry=0.5))
|
||
self.assertTrue(wait(lambda: m.state == "open" and m.file.exists()))
|
||
self.client.orders.clear()
|
||
again = self.mirror() # paper positions are gone after a restart
|
||
self.assertTrue(wait(lambda: len(again.trades) == 1))
|
||
self.assertEqual(self.client.orders, [("fut", "sell", 10.0, True)])
|
||
self.assertEqual(again.view()["open"], 0)
|
||
|
||
|
||
class BasisRealTests(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 = basis.BasisEngine("bybit", Path(self.dir.name), start=False)
|
||
self.client = FakeClient(price=1.0)
|
||
self.e.client_for = lambda ex: self.client
|
||
self.e.settings.running = self.e.settings.real = True
|
||
# the market entry (spot first) unless a test switches the limit entry / exchange TP on
|
||
self.e.settings.entry_limit = self.e.settings.exchange_tp = False
|
||
self.e.pairs = {"OK": basis.Pair("OK", "OKUSDT", "OKUSDT", 1.0, 1.0, 1.001, 1.010, 1.011, 1e4, 1e4, 1e4, 1e4,
|
||
0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False)}
|
||
|
||
def tearDown(self):
|
||
self.journal.stop()
|
||
self.dir.cleanup()
|
||
|
||
def run_jobs(self):
|
||
while not self.e.jobs.empty():
|
||
kind, *args = self.e.jobs.get()
|
||
getattr(self.e, "_real_open" if kind == "open" else "_real_close")(*args)
|
||
if kind == "close":
|
||
self.e.busy.discard(args[0])
|
||
|
||
def test_open_hedged_then_close(self):
|
||
self.e.step(1000.0)
|
||
self.assertEqual(self.e.opening, {"OK"})
|
||
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.qty, 99.0) # perp rounded down to the lot
|
||
self.assertAlmostEqual(pos.spot_qty, 99.9) # coins really held after the buy fee
|
||
self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("fut", "sell")])
|
||
# gap closes → perp bought back first, then the spot sold
|
||
self.e.pairs["OK"] = basis.Pair("OK", "OKUSDT", "OKUSDT", 1.0, 1.0, 1.001, 1.0, 1.0002, 1e4, 1e4, 1e4, 1e4,
|
||
0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False)
|
||
self.e.step(1010.0)
|
||
self.e.step(1010.5) # close already in progress
|
||
self.assertEqual(self.e.jobs.qsize(), 1)
|
||
self.run_jobs()
|
||
self.assertEqual(self.e.positions, [])
|
||
self.assertEqual([o[:2] for o in self.client.orders[2:]], [("fut", "buy"), ("spot", "sell")])
|
||
self.assertIn("реально", self.e.trades[0].reason)
|
||
|
||
def test_failed_short_sells_spot_back(self):
|
||
self.client.fail_fut = True
|
||
self.e.step(1000.0)
|
||
self.run_jobs()
|
||
self.assertEqual(self.e.positions, [])
|
||
self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("fut", "sell"), ("spot", "sell")])
|
||
self.assertEqual(self.e.opening, set())
|
||
self.e.step(1001.0) # pause before trying the coin again
|
||
self.assertTrue(self.e.jobs.empty())
|
||
|
||
def test_spot_sale_retried_after_perp_bought_back(self):
|
||
self.e.step(1000.0)
|
||
self.run_jobs()
|
||
uid = self.e.positions[0].uid
|
||
self.client.fail_spot_sell = True
|
||
self.assertIn("реальных отправлено на закрытие: 1", self.e.close(uid))
|
||
self.run_jobs()
|
||
pos = self.e.positions[0]
|
||
self.assertEqual(pos.closing, "fut_done")
|
||
self.assertTrue(pos.error)
|
||
self.client.fail_spot_sell = False
|
||
self.e.step(pos.retry_at + 1) # retried: only the spot sale is left
|
||
self.run_jobs()
|
||
self.assertEqual(self.e.positions, [])
|
||
self.assertEqual(sum(1 for o in self.client.orders if o[:2] == ("fut", "buy")), 1) # perp not bought twice
|
||
|
||
def test_unconfirmed_short_keeps_position(self):
|
||
self.client.unconfirmed = 1
|
||
self.e.step(1000.0)
|
||
self.run_jobs()
|
||
self.assertEqual(len(self.e.positions), 1) # not sold back: the short may be open
|
||
self.assertIn("не подтверждён", self.e.positions[0].error)
|
||
self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("fut", "sell")])
|
||
|
||
def test_lot_too_big_no_spot_bought(self):
|
||
# the incident: CATE, 5.2 $ ≈ 70 coins, the perp's minimum lot is bigger — spot was bought and sold back
|
||
self.client.fut_min_coins = lambda symbol: 1000.0
|
||
self.e.step(1000.0)
|
||
self.run_jobs()
|
||
self.assertEqual(self.client.orders, []) # nothing bought at all
|
||
self.assertIn("меньше минимального лота", self.e.real_block["OK"][0])
|
||
self.e.step(1100.0) # not tried again on every step
|
||
self.assertTrue(self.e.jobs.empty())
|
||
self.assertIn("лота", self.e.view()["rows"][0]["real_block"]) # the reason is shown in the table
|
||
self.assertEqual(self.e.set_settings({"amount": "2000"}), "") # a bigger amount saved: checked anew
|
||
self.assertEqual(self.e.real_block, {})
|
||
self.assertEqual(self.e.view()["rows"][0]["real_block"], "")
|
||
|
||
def test_balance_insufficient_pauses_the_exchange(self):
|
||
self.client.fut_order = mock.Mock(side_effect=live.LiveError("MEXC фьючерсы 2005: Balance insufficient"))
|
||
self.e.step(1000.0)
|
||
self.run_jobs()
|
||
self.assertEqual([o[:2] for o in self.client.orders], [("spot", "buy"), ("spot", "sell")]) # sold back
|
||
self.assertIn("не хватает баланса", self.e.view()["real_pause"])
|
||
self.e.step(time.time() + 10)
|
||
self.assertTrue(self.e.jobs.empty()) # no new tries during the pause
|
||
|
||
def run_all(self):
|
||
while not self.e.jobs.empty():
|
||
kind, *args = self.e.jobs.get()
|
||
{"open": self.e._real_open, "close": self.e._real_close, "short": self.e._real_short,
|
||
"adopt": self.e.adopt, "watch": self.e._watch_tp, "untp": self.e._remove_tp,
|
||
"tp": lambda uid: self.e._place_tp(self.client, next(x for x in self.e.positions if x.uid == uid))
|
||
}[kind](*args)
|
||
if kind in ("close", "short", "watch", "tp", "untp"):
|
||
self.e.busy.discard(args[0])
|
||
if kind == "adopt":
|
||
self.e.opening.discard(args[0])
|
||
|
||
def test_adopt_spot_then_short_then_normal_close(self):
|
||
# the incident: 346.2 SI on the spot account, unknown to the program
|
||
self.client.spot_balance = 346.2
|
||
self.e.settings.running = False
|
||
msg = self.e.adopt("ok", price=1.0, fee_usd=0.0042)
|
||
self.assertIn("подхвачено", msg)
|
||
pos = self.e.positions[0]
|
||
self.assertTrue(pos.short_pending)
|
||
self.assertEqual((pos.spot_qty, pos.qty), (346.2, 0.0))
|
||
self.e.step(1000.0) # the short is opened next
|
||
self.run_all()
|
||
self.assertFalse(pos.short_pending)
|
||
self.assertEqual(pos.qty, 346.0) # rounded down to the lot
|
||
self.assertEqual(self.client.orders, [("fut", "sell", 346.0, False)])
|
||
self.assertIn("уже ведётся", self.e.adopt("OK"))
|
||
|
||
def test_short_refused_retried_later_spot_can_be_sold(self):
|
||
self.client.spot_balance = 346.2
|
||
self.e.settings.running = False
|
||
self.client.fut_order = mock.Mock(side_effect=live.LiveError("MEXC фьючерсы 2005: Balance insufficient"))
|
||
self.e.adopt("OK", price=1.0)
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
pos = self.e.positions[0]
|
||
self.assertTrue(pos.short_pending)
|
||
self.assertIn("шорт не открыт", pos.error)
|
||
self.e.step(1001.0) # not retried right away
|
||
self.assertTrue(self.e.jobs.empty())
|
||
self.assertIn("отправлено на закрытие", self.e.close(pos.uid)) # «×»: sell the spot, no perp involved
|
||
self.run_all()
|
||
self.assertEqual(self.e.positions, [])
|
||
self.assertEqual(self.client.orders, [("spot", "sell", 346.2)])
|
||
|
||
def test_no_spot_bought_while_another_real_position_exists(self):
|
||
# the race of 10:25:31: an entry queued just before a coin was adopted must not buy anything
|
||
self.e.step(1000.0) # entry queued (nothing held yet)
|
||
self.client.spot_balance = 346.2
|
||
self.e.adopt("OK", price=1.0) # meanwhile: coins taken over
|
||
self.run_all()
|
||
self.assertNotIn(("spot", "buy"), [o[:2] for o in self.client.orders])
|
||
|
||
def test_entry_cut_by_restart_is_recovered(self):
|
||
self.e.pending["OK"] = {"time": 1.0, "amount": 100}
|
||
self.e.save()
|
||
self.client.spot_balance = 99.9 # bought, then the program stopped
|
||
again = basis.BasisEngine("bybit", Path(self.dir.name), start=False)
|
||
again.client_for = lambda ex: self.client
|
||
again.pairs = self.e.pairs
|
||
self.assertEqual(again.recover, {"OK"})
|
||
again.step(1000.0)
|
||
kind, base = again.jobs.get()
|
||
self.assertEqual((kind, base), ("adopt", "OK"))
|
||
again.adopt(base)
|
||
self.assertTrue(again.positions[0].short_pending)
|
||
self.assertAlmostEqual(again.positions[0].spot_qty, 99.9)
|
||
|
||
def test_spot_usdt_moved_to_futures_before_entry(self):
|
||
self.client.usdt = {"spot": 300.0, "futures": 20.0} # the short's margin is missing
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
first = self.client.orders[0]
|
||
self.assertEqual(first[:2], ("transfer", "futures")) # moved BEFORE anything was bought
|
||
self.assertAlmostEqual(first[2], 100 * 1.03 - 20 + 0.01, places=2)
|
||
self.assertEqual([o[:2] for o in self.client.orders[1:3]], [("spot", "buy"), ("fut", "sell")])
|
||
|
||
def test_not_enough_in_total_nothing_bought(self):
|
||
self.client.usdt = {"spot": 60.0, "futures": 40.0} # 100 in total, 204 needed
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
self.assertEqual(self.client.orders, [])
|
||
self.assertIn("не хватает", self.e.view()["real_pause"])
|
||
|
||
def test_transfer_switched_off(self):
|
||
self.e.settings.auto_transfer = False
|
||
self.client.usdt = {"spot": 300.0, "futures": 0.0}
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
self.assertNotIn("transfer", [o[0] for o in self.client.orders])
|
||
|
||
def test_short_for_adopted_coins_gets_margin_from_spot(self):
|
||
self.client.spot_balance = 346.2
|
||
self.client.usdt = {"spot": 6.37, "futures": 0.0}
|
||
self.e.settings.running = False
|
||
self.client.price = 0.015
|
||
self.e.pairs["OK"] = basis.Pair("OK", "OKUSDT", "OKUSDT", 1.0, 0.015, 0.01502, 0.015, 0.01502, 1e4, 1e4, 1e4,
|
||
1e4, 0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False)
|
||
self.e.adopt("OK", price=0.01502)
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
self.assertEqual([o[:2] for o in self.client.orders], [("transfer", "futures"), ("fut", "sell")])
|
||
self.assertFalse(self.e.positions[0].short_pending)
|
||
|
||
def limit_mode(self, hold=0.0):
|
||
self.e.settings.entry_limit = self.e.settings.exchange_tp = True
|
||
self.e.settings.limit_hold_s = hold
|
||
|
||
def test_limit_entry_short_first_then_spot_then_tp(self):
|
||
self.limit_mode()
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
kinds = [o[:2] for o in self.client.orders]
|
||
self.assertEqual(kinds, [("fut_limit", "sell"), ("spot", "buy")]) # short first, then the hedge
|
||
pos = self.e.positions[0]
|
||
self.assertAlmostEqual(pos.fut_entry, 1.010) # at the signal's perp bid
|
||
self.assertTrue(pos.tp_order)
|
||
side, coins, tp = self.client.take_profits[0]
|
||
self.assertEqual((side, coins), ("buy", pos.qty))
|
||
self.assertAlmostEqual(tp, pos.spot_entry * (1 + self.e.settings.exit_gap_pct / 100))
|
||
|
||
def test_limit_not_filled_nothing_bought(self):
|
||
self.limit_mode()
|
||
self.client.limit_fill = 0.0
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
self.assertEqual([o[0] for o in self.client.orders], ["fut_limit", "fut_cancel"])
|
||
self.assertEqual(self.e.positions, [])
|
||
self.assertEqual(self.e.opening, set())
|
||
|
||
def test_limit_partly_filled_spot_for_that_part(self):
|
||
self.limit_mode()
|
||
self.client.limit_fill = 0.5
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
pos = self.e.positions[0]
|
||
self.assertAlmostEqual(pos.qty, 49.5) # half of 99 coins
|
||
buy = next(o for o in self.client.orders if o[:2] == ("spot", "buy"))
|
||
self.assertAlmostEqual(buy[2], 49.5 * 1.001 * 1.001 * 1.003 / 1.0, places=3)
|
||
|
||
def test_exchange_tp_filled_then_spot_sold(self):
|
||
self.limit_mode()
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
pos = self.e.positions[0]
|
||
self.client.fill_take_profit(pos.tp_order) # the TP fills on the exchange
|
||
self.e.step(1010.0) # the watch notices it
|
||
self.run_all()
|
||
self.assertEqual(self.e.positions, [])
|
||
after = [o[:2] for o in self.client.orders[2:]]
|
||
self.assertNotIn(("fut", "buy"), after) # no market buy-back: the TP did it
|
||
self.assertIn(("spot", "sell"), after)
|
||
t = self.e.trades[-1]
|
||
self.assertAlmostEqual(t.fut_exit, pos.tp_price)
|
||
|
||
def test_program_close_cancels_tp_first(self):
|
||
self.limit_mode()
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
uid = self.e.positions[0].uid
|
||
self.e.close(uid)
|
||
self.run_all()
|
||
kinds = [o[0] for o in self.client.orders[2:]]
|
||
self.assertEqual(kinds[:2], ["fut_cancel", "fut"]) # TP removed, then the market buy-back
|
||
self.assertEqual(self.e.positions, [])
|
||
|
||
def test_old_exchange_tp_is_removed(self):
|
||
self.limit_mode()
|
||
self.e.step(1000.0)
|
||
self.run_all()
|
||
pos = self.e.positions[0]
|
||
self.assertTrue(pos.tp_order)
|
||
self.e.settings.exchange_tp = False # the program watches by itself now
|
||
self.e.step(1001.0)
|
||
kind, uid = self.e.jobs.get()
|
||
self.assertEqual((kind, uid), ("untp", pos.uid))
|
||
self.e._remove_tp(uid)
|
||
self.assertEqual(pos.tp_order, "")
|
||
self.assertEqual(self.client.orders[-1][0], "fut_cancel")
|
||
self.assertEqual(len(self.e.positions), 1) # the position itself stays
|
||
|
||
def test_exchange_tp_never_set_from_saved_settings(self):
|
||
self.e.settings.exchange_tp = True
|
||
self.e.save()
|
||
again = basis.BasisEngine("bybit", Path(self.dir.name), start=False)
|
||
self.assertFalse(again.settings.exchange_tp)
|
||
|
||
def test_fast_watch_closes_on_fresh_prices(self):
|
||
# paper position; the market list is not refreshed, only the fast per-symbol prices are
|
||
self.e.settings.real = False
|
||
self.e.step(1000.0)
|
||
self.assertEqual(len(self.e.positions), 1)
|
||
quotes = {"spot": (1.0, 1.001, None, None), "fut": (1.0, 1.0002, None, None)} # the gap has closed
|
||
with mock.patch("fastquote.spot_top", lambda ex, s: quotes["spot"]), \
|
||
mock.patch("fastquote.fut_top", lambda ex, s: quotes["fut"]):
|
||
threading.Thread(target=self.e._fast_loop, daemon=True).start()
|
||
self.assertTrue(wait(lambda: not self.e.positions))
|
||
self.assertEqual(self.e.trades[-1].reason, "разница сошлась")
|
||
self.assertIn("OK", self.e.fast_seen)
|
||
|
||
def test_several_real_positions_when_allowed(self):
|
||
second = basis.Pair("TWO", "TWOUSDT", "TWOUSDT", 1.0, 1.0, 1.001, 1.012, 1.013, 1e4, 1e4, 1e4, 1e4,
|
||
0.0001, 0.0, 8.0, 1e6, 1e6, 5.0, False, False)
|
||
self.e.pairs["TWO"] = second
|
||
self.e.step(1000.0) # one entry at a time…
|
||
self.assertEqual(self.e.jobs.qsize(), 1)
|
||
self.run_all()
|
||
self.assertEqual(len(self.e.positions), 1)
|
||
self.e.step(1100.0) # limit 1: the second waits
|
||
self.assertTrue(self.e.jobs.empty())
|
||
self.assertIn("ждёт закрытия", next(r["why"] for r in self.e.view()["rows"] if not r["base"] in
|
||
{p.base for p in self.e.positions}))
|
||
self.e.settings.max_real_positions = 2 # two at the same time allowed
|
||
self.e.step(1200.0)
|
||
self.run_all()
|
||
self.assertEqual(sorted(p.base for p in self.e.positions), ["OK", "TWO"])
|
||
self.e.step(1300.0) # and not a third
|
||
self.assertTrue(self.e.jobs.empty())
|
||
|
||
def test_coin_in_a_trade_elsewhere_is_not_opened(self):
|
||
other = basis.BasisEngine("gate", Path(self.dir.name), start=False)
|
||
other.positions.append(basis.Position(1, "OK", 0.0, 10.0, 1.0, 1.01, 1.0, 0.0, 0.0))
|
||
basis.ENGINES.append(other)
|
||
try:
|
||
self.e.step(1000.0)
|
||
self.assertTrue(self.e.jobs.empty()) # OK is in a trade on Gate
|
||
self.assertIn("уже в сделке: Gate", self.e.view()["rows"][0]["why"])
|
||
other.positions.clear()
|
||
self.e.step(1001.0)
|
||
self.assertEqual(self.e.jobs.qsize(), 1) # free again
|
||
finally:
|
||
basis.ENGINES.remove(other)
|
||
|
||
def test_different_instruments_never_traded(self):
|
||
# the incident: MEXC EWT — spot 0.339 $, perp 104.84 $: +30 797 %, a perp leg of ~1 570 $ for a 5 $ trade
|
||
ewt = basis.Pair("EWT", "EWTUSDT", "EWT_USDT", 1.0, 0.3388, 0.3393, 104.84, 104.9, 1e4, 1e4, 1e4, 1e4,
|
||
0.0, 0.0, 8.0, 1e6, 1e6, 100.0, False, True)
|
||
self.e.pairs = {"EWT": ewt}
|
||
self.e.settings.max_gap_pct = 300000.0 # whatever is typed in the settings…
|
||
self.e.settings.all_coins = True
|
||
self.e.step(1000.0)
|
||
self.assertTrue(self.e.jobs.empty()) # …it is not entered
|
||
row = self.e.view()["rows"][0]
|
||
self.assertFalse(row["fits"])
|
||
self.assertIn("разные инструменты", row["why"])
|
||
msg = self.e.set_settings({"max_gap_pct": "300000"})
|
||
self.assertIn("не может быть больше", msg)
|
||
self.assertEqual(self.e.settings.max_gap_pct, basis.HARD_MAX_GAP_PCT)
|
||
# even an order request that slipped through stops right before the exchange
|
||
self.limit_mode()
|
||
self.e._open_limit_first(self.client, ewt, 5.1)
|
||
self.assertEqual(self.client.orders, [])
|
||
self.assertIn("разные инструменты", self.e.real_block["EWT"][0])
|
||
|
||
def test_reset_refused_with_real_positions(self):
|
||
self.e.step(1000.0)
|
||
self.run_jobs()
|
||
self.assertIn("реальные позиции", self.e.reset())
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|