121 lines
6.0 KiB
Python
121 lines
6.0 KiB
Python
"""HTX in the Multi-Assets Collateral mode: v1 answers 6023, so orders, positions and the account go through V5.
|
|
No request reaches the exchange: the signed call is replaced by a fake."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
import live # noqa: E402
|
|
|
|
|
|
class FakeHtx(live.Htx):
|
|
def __init__(self, mode=2):
|
|
super().__init__("k", "s")
|
|
self.mode, self.calls = mode, []
|
|
self.rules["fut:DOGE-USDT"] = {"size": 100.0}
|
|
|
|
def _call(self, method, host, path, params=None, body=None):
|
|
self.calls.append((method, path, params, body))
|
|
if path == "/v5/account/asset_mode":
|
|
return {"asset_mode": self.mode}
|
|
if path == "/v5/trade/order" and method == "POST":
|
|
return {"order_id": "77", "client_order_id": "77"}
|
|
if path == "/v5/trade/order":
|
|
return {"order_id": "77", "state": "filled", "trade_volume": "3", "trade_avg_price": "0.2", "fee": "-0.03"}
|
|
if path == "/v5/trade/cancel_order":
|
|
return {"order_id": body["order_id"]}
|
|
if path == "/v5/trade/position/opens":
|
|
return [{"contract_code": "DOGE-USDT", "position_side": "both", "direction": "sell", "volume": "3"}]
|
|
if path == "/v5/account/balance":
|
|
return {"equity": "12.5", "available_margin": "10.25", "details": []}
|
|
if path == "/linear-swap-api/v1/swap_cross_order":
|
|
return {"order_id_str": "v1"}
|
|
if path.startswith("/v1/account/accounts"):
|
|
return {"list": [{"currency": "usdt", "type": "trade", "balance": "4"}]} if "balance" in path \
|
|
else [{"type": "spot", "id": 1}]
|
|
raise AssertionError(path)
|
|
|
|
|
|
class HtxV5Tests(unittest.TestCase):
|
|
def test_market_short_through_v5(self):
|
|
c = FakeHtx()
|
|
fill = c.fut_order("DOGE-USDT", "sell", 350, reduce_only=False)
|
|
method, path, _, body = c.calls[1]
|
|
self.assertEqual((method, path), ("POST", "/v5/trade/order"))
|
|
self.assertEqual(body, {"contract_code": "DOGE-USDT", "margin_mode": "cross", "side": "sell", "volume": 3,
|
|
"type": "market"})
|
|
self.assertEqual((fill.coins, fill.price, fill.fee_usd, fill.order_id), (300.0, 0.2, 0.03, "77"))
|
|
self.assertFalse(any("/linear-swap-api/" in p for _, p, _, _ in c.calls))
|
|
|
|
def test_reduce_only_limit_status_cancel_position(self):
|
|
c = FakeHtx()
|
|
self.assertEqual(c.fut_limit("DOGE-USDT", "buy", 300, 0.19, reduce_only=True), "77")
|
|
body = c.calls[1][3]
|
|
self.assertEqual((body["type"], body["price"], body["reduce_only"], body["time_in_force"]), ("limit", 0.19, 1, "gtc"))
|
|
st = c.fut_order_status("DOGE-USDT", "77")
|
|
self.assertEqual((st["coins"], st["final"]), (300.0, True))
|
|
c.fut_cancel("DOGE-USDT", "77")
|
|
self.assertEqual(c.calls[-1][1], "/v5/trade/cancel_order")
|
|
self.assertEqual(c.fut_position("DOGE-USDT"), -300.0) # one-way: the side from direction
|
|
|
|
def test_account_through_v5(self):
|
|
c = FakeHtx()
|
|
self.assertEqual(c.balances(), {"Спот USDT": 4.0, "Фьючерсы USDT": 12.5})
|
|
self.assertEqual(c.usdt_free(), {"spot": 4.0, "futures": 10.25})
|
|
|
|
def test_liquidation_price_from_position(self):
|
|
c = FakeHtx()
|
|
orig = c._call
|
|
|
|
def call(method, host, path, params=None, body=None):
|
|
if path == "/v5/trade/position/opens":
|
|
return [{"contract_code": "DOGE-USDT", "volume": "3", "direction": "sell", "liquidation_price": "0.41"}]
|
|
return orig(method, host, path, params, body)
|
|
c._call = call
|
|
self.assertEqual(c.fut_liq_price("DOGE-USDT"), 0.41)
|
|
self.assertIsNone(live._liq([{"volume": "0", "liquidation_price": "1"}], "liquidation_price", 1.0,
|
|
lambda r: float(r["volume"]))) # no position
|
|
self.assertIsNone(live._liq([{"size": "5", "liqPrice": ""}], "liqPrice", 1.0,
|
|
lambda r: float(r["size"]))) # not reported
|
|
self.assertEqual(live._liq([{"size": "5", "liqPrice": "2000"}], "liqPrice", 1000.0,
|
|
lambda r: float(r["size"])), 2.0) # 1000PEPE: per coin
|
|
|
|
def test_market_sale_refused_by_circuit_breaker_goes_as_ioc_limit(self):
|
|
# AEVO on HTX, 2026-10-22: bid 0.0222 / ask 0.0257 — every sell-market cancelled (410), the close stuck
|
|
from unittest import mock
|
|
c = live.Htx("k", "s")
|
|
c.account_id = "1"
|
|
c.rules["spot:AEVO"] = {"step": 0.0001, "tick": 0.0001}
|
|
placed = []
|
|
|
|
def call(method, host, path, params=None, body=None):
|
|
if path == "/v1/order/orders/place":
|
|
placed.append(body)
|
|
return str(len(placed))
|
|
o = placed[int(path.rsplit("/", 1)[1]) - 1]
|
|
if o["type"] == "sell-market":
|
|
return {"state": "canceled", "field-amount": "0", "canceled-source": None} # as the detail answers
|
|
return {"state": "filled", "field-amount": o["amount"], "field-cash-amount": str(float(o["amount"]) * 0.0222),
|
|
"field-fees": "0.0171"}
|
|
c._call = call
|
|
book = ([(0.0222, 1335.0), (0.0221, 3044.0)], [(0.0257, 3891.0)])
|
|
with mock.patch("fastquote.book", lambda ex, market, symbol: book):
|
|
fill = c.spot_sell("AEVO", 383.0621)
|
|
self.assertEqual([p["type"] for p in placed], ["sell-market", "sell-ioc"])
|
|
self.assertEqual((placed[1]["amount"], placed[1]["price"]), ("383.0621", "0.0222"))
|
|
self.assertAlmostEqual(fill.price, 0.0222)
|
|
self.assertEqual(fill.coins, 383.0621)
|
|
|
|
def test_single_asset_mode_keeps_v1(self):
|
|
c = FakeHtx(mode=1)
|
|
self.assertEqual(c.fut_limit("DOGE-USDT", "sell", 300, 0.21), "v1")
|
|
self.assertEqual(c.calls[-1][1], "/linear-swap-api/v1/swap_cross_order")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|