test_okx_client.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. import base64
  2. import hashlib
  3. import hmac
  4. import json as json_module
  5. from dataclasses import dataclass
  6. from urllib.parse import urlencode, urlparse
  7. import pytest
  8. from okx_codex_trader.config import Config
  9. from okx_codex_trader.models import InstrumentMeta, TradeSignal
  10. from okx_codex_trader.okx_client import OkxClient, build_contract_size
  11. @dataclass
  12. class DummyResponse:
  13. payload: dict[str, object]
  14. status_code: int = 200
  15. json_error: Exception | None = None
  16. def json(self) -> dict[str, object]:
  17. if self.json_error is not None:
  18. raise self.json_error
  19. return self.payload
  20. @dataclass
  21. class RecordedRequest:
  22. method: str
  23. url: str
  24. headers: dict[str, str]
  25. params: dict[str, object] | None
  26. json_body: dict[str, object] | None
  27. body: str | None
  28. timeout: float | None
  29. class DummySession:
  30. def __init__(self, responses: list[DummyResponse | Exception] | None = None):
  31. self._responses = list(responses or [])
  32. self.last_request: RecordedRequest | None = None
  33. self.request_paths: list[str] = []
  34. self.request_bodies: list[dict[str, object] | None] = []
  35. @property
  36. def last_json_body(self) -> dict[str, object] | None:
  37. return self.last_request.json_body if self.last_request else None
  38. @property
  39. def last_body(self) -> str | None:
  40. return self.last_request.body if self.last_request else None
  41. def request(
  42. self,
  43. method: str,
  44. url: str,
  45. *,
  46. headers: dict[str, str] | None = None,
  47. params: dict[str, object] | None = None,
  48. json: dict[str, object] | None = None,
  49. data: str | None = None,
  50. timeout: float | None = None,
  51. ) -> DummyResponse:
  52. parsed_json = json
  53. if parsed_json is None and data is not None:
  54. parsed_json = json_module.loads(data)
  55. self.last_request = RecordedRequest(
  56. method=method,
  57. url=url,
  58. headers=headers or {},
  59. params=params,
  60. json_body=parsed_json,
  61. body=data,
  62. timeout=timeout,
  63. )
  64. self.request_paths.append(urlparse(url).path)
  65. self.request_bodies.append(parsed_json)
  66. if self._responses:
  67. response = self._responses.pop(0)
  68. if isinstance(response, Exception):
  69. raise response
  70. return response
  71. return candles_response()
  72. def sample_config() -> Config:
  73. return Config(api_key="key", api_secret="secret", api_passphrase="passphrase")
  74. def live_config() -> Config:
  75. return Config(api_key="key", api_secret="secret", api_passphrase="passphrase", trading_env="live")
  76. def candles_response() -> DummyResponse:
  77. return DummyResponse(
  78. {
  79. "code": "0",
  80. "msg": "",
  81. "data": [
  82. ["1710000000000", "25000", "25100", "24900", "25050", "100", "1000", "1000", "1"],
  83. ],
  84. }
  85. )
  86. def descending_candles_response() -> DummyResponse:
  87. return DummyResponse(
  88. {
  89. "code": "0",
  90. "msg": "",
  91. "data": [
  92. ["1710000001000", "25100", "25200", "25000", "25150", "110", "1100", "1100", "1"],
  93. ["1710000000000", "25000", "25100", "24900", "25050", "100", "1000", "1000", "1"],
  94. ],
  95. }
  96. )
  97. def older_candles_response() -> DummyResponse:
  98. return DummyResponse(
  99. {
  100. "code": "0",
  101. "msg": "",
  102. "data": [
  103. ["1709999701000", "24699", "24799", "24649", "24749", "90", "900", "900", "1"],
  104. ["1709999700000", "24698", "24798", "24648", "24748", "80", "800", "800", "1"],
  105. ],
  106. }
  107. )
  108. def full_page_candles_response() -> DummyResponse:
  109. data = []
  110. for offset in range(100):
  111. ts = 1710000001000 - (offset * 1000)
  112. close = 25050 - offset
  113. data.append([str(ts), str(close - 50), str(close + 50), str(close - 100), str(close), "100", "1000", "1000", "1"])
  114. return DummyResponse({"code": "0", "msg": "", "data": data})
  115. def instrument_response(symbol: str = "BTC-USDT-SWAP") -> DummyResponse:
  116. return DummyResponse(
  117. {
  118. "code": "0",
  119. "msg": "",
  120. "data": [
  121. {
  122. "instId": symbol,
  123. "instType": "SWAP",
  124. "ctVal": "0.001",
  125. "lotSz": "1",
  126. "minSz": "1",
  127. }
  128. ],
  129. }
  130. )
  131. def large_min_size_instrument_response() -> DummyResponse:
  132. return DummyResponse(
  133. {
  134. "code": "0",
  135. "msg": "",
  136. "data": [
  137. {
  138. "instId": "BTC-USDT-SWAP",
  139. "instType": "SWAP",
  140. "ctVal": "0.01",
  141. "lotSz": "1",
  142. "minSz": "100",
  143. }
  144. ],
  145. }
  146. )
  147. def ticker_response(last: str) -> DummyResponse:
  148. return DummyResponse({"code": "0", "msg": "", "data": [{"instId": "BTC-USDT-SWAP", "last": last}]})
  149. def balance_response() -> DummyResponse:
  150. return DummyResponse(
  151. {
  152. "code": "0",
  153. "msg": "",
  154. "data": [
  155. {
  156. "totalEq": "101.5",
  157. "details": [
  158. {
  159. "ccy": "USDT",
  160. "eq": "100.25",
  161. "availEq": "98.75",
  162. "cashBal": "100.0",
  163. }
  164. ],
  165. }
  166. ],
  167. }
  168. )
  169. def account_config_response(pos_mode: str) -> DummyResponse:
  170. return DummyResponse({"code": "0", "msg": "", "data": [{"posMode": pos_mode}]})
  171. def malformed_account_config_response(pos_mode: object) -> DummyResponse:
  172. return DummyResponse({"code": "0", "msg": "", "data": [{"posMode": pos_mode}]})
  173. def leverage_response() -> DummyResponse:
  174. return DummyResponse({"code": "0", "msg": "", "data": [{"lever": "2"}]})
  175. def place_order_response() -> DummyResponse:
  176. return DummyResponse({"code": "0", "msg": "", "data": [{"ordId": "123"}]})
  177. def place_order_response_without_order_id() -> DummyResponse:
  178. return DummyResponse({"code": "0", "msg": "", "data": [{}]})
  179. def error_response(code: str, msg: str) -> DummyResponse:
  180. return DummyResponse({"code": code, "msg": msg, "data": []})
  181. def positions_response() -> DummyResponse:
  182. return DummyResponse(
  183. {
  184. "code": "0",
  185. "msg": "",
  186. "data": [
  187. {
  188. "instId": "BTC-USDT-SWAP",
  189. "posSide": "long",
  190. "pos": "8",
  191. "avgPx": "25000",
  192. }
  193. ],
  194. }
  195. )
  196. def positions_with_zero_size_response() -> DummyResponse:
  197. return DummyResponse(
  198. {
  199. "code": "0",
  200. "msg": "",
  201. "data": [
  202. {
  203. "instId": "BTC-USDT-SWAP",
  204. "posSide": "long",
  205. "pos": "0",
  206. "avgPx": "25000",
  207. },
  208. {
  209. "instId": "BTC-USDT-SWAP",
  210. "posSide": "short",
  211. "pos": "3",
  212. "avgPx": "24900",
  213. },
  214. ],
  215. }
  216. )
  217. def positions_with_zero_size_malformed_avg_price_response() -> DummyResponse:
  218. return DummyResponse(
  219. {
  220. "code": "0",
  221. "msg": "",
  222. "data": [
  223. {
  224. "instId": "BTC-USDT-SWAP",
  225. "posSide": "long",
  226. "pos": "0",
  227. "avgPx": "bad",
  228. },
  229. {
  230. "instId": "BTC-USDT-SWAP",
  231. "posSide": "short",
  232. "pos": "3",
  233. "avgPx": "24900",
  234. },
  235. ],
  236. }
  237. )
  238. def positions_with_non_string_identity_response() -> DummyResponse:
  239. return DummyResponse(
  240. {
  241. "code": "0",
  242. "msg": "",
  243. "data": [
  244. {
  245. "instId": None,
  246. "posSide": ["long"],
  247. "pos": "3",
  248. "avgPx": "24900",
  249. }
  250. ],
  251. }
  252. )
  253. def candles_with_non_finite_numeric_response() -> DummyResponse:
  254. return DummyResponse(
  255. {
  256. "code": "0",
  257. "msg": "",
  258. "data": [
  259. ["1710000000000", "NaN", "25100", "24900", "25050", "100", "1000", "1000", "1"],
  260. ],
  261. }
  262. )
  263. def instrument_with_non_finite_numeric_response() -> DummyResponse:
  264. return DummyResponse(
  265. {
  266. "code": "0",
  267. "msg": "",
  268. "data": [
  269. {
  270. "instId": "BTC-USDT-SWAP",
  271. "instType": "SWAP",
  272. "ctVal": "NaN",
  273. "lotSz": "1",
  274. "minSz": "1",
  275. }
  276. ],
  277. }
  278. )
  279. def instrument_with_wrong_symbol_response() -> DummyResponse:
  280. return DummyResponse(
  281. {
  282. "code": "0",
  283. "msg": "",
  284. "data": [
  285. {
  286. "instId": "ETH-USDT-SWAP",
  287. "instType": "SWAP",
  288. "ctVal": "0.001",
  289. "lotSz": "1",
  290. "minSz": "1",
  291. }
  292. ],
  293. }
  294. )
  295. def instrument_with_wrong_type_response() -> DummyResponse:
  296. return DummyResponse(
  297. {
  298. "code": "0",
  299. "msg": "",
  300. "data": [
  301. {
  302. "instId": "BTC-USDT-SWAP",
  303. "instType": "FUTURES",
  304. "ctVal": "0.001",
  305. "lotSz": "1",
  306. "minSz": "1",
  307. }
  308. ],
  309. }
  310. )
  311. def ticker_with_non_finite_numeric_response() -> DummyResponse:
  312. return DummyResponse({"code": "0", "msg": "", "data": [{"instId": "BTC-USDT-SWAP", "last": "Infinity"}]})
  313. def positions_with_non_finite_numeric_response() -> DummyResponse:
  314. return DummyResponse(
  315. {
  316. "code": "0",
  317. "msg": "",
  318. "data": [
  319. {
  320. "instId": "BTC-USDT-SWAP",
  321. "posSide": "long",
  322. "pos": "1",
  323. "avgPx": "NaN",
  324. }
  325. ],
  326. }
  327. )
  328. def positions_with_wrong_symbol_response() -> DummyResponse:
  329. return DummyResponse(
  330. {
  331. "code": "0",
  332. "msg": "",
  333. "data": [
  334. {
  335. "instId": "ETH-USDT-SWAP",
  336. "posSide": "long",
  337. "pos": "1",
  338. "avgPx": "25000",
  339. }
  340. ],
  341. }
  342. )
  343. def positions_with_invalid_pos_side_response() -> DummyResponse:
  344. return DummyResponse(
  345. {
  346. "code": "0",
  347. "msg": "",
  348. "data": [
  349. {
  350. "instId": "BTC-USDT-SWAP",
  351. "posSide": "net",
  352. "pos": "1",
  353. "avgPx": "25000",
  354. }
  355. ],
  356. }
  357. )
  358. def market_long_signal() -> TradeSignal:
  359. return TradeSignal(
  360. action="long",
  361. confidence=0.9,
  362. leverage=2,
  363. entry_price=None,
  364. take_profit_price=26000.0,
  365. stop_loss_price=24000.0,
  366. reason="trend",
  367. )
  368. def limit_short_signal() -> TradeSignal:
  369. return TradeSignal(
  370. action="short",
  371. confidence=0.8,
  372. leverage=2,
  373. entry_price=25000.0,
  374. take_profit_price=24000.0,
  375. stop_loss_price=25500.0,
  376. reason="mean reversion",
  377. )
  378. def flat_signal() -> TradeSignal:
  379. return TradeSignal(
  380. action="flat",
  381. confidence=0.7,
  382. leverage=2,
  383. entry_price=None,
  384. take_profit_price=None,
  385. stop_loss_price=None,
  386. reason="exit",
  387. )
  388. def test_signed_demo_request_attaches_headers():
  389. session = DummySession()
  390. client = OkxClient(config=sample_config(), session=session)
  391. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  392. request = session.last_request
  393. assert request is not None
  394. assert request.headers["x-simulated-trading"] == "1"
  395. assert request.headers["OK-ACCESS-KEY"] == "key"
  396. assert request.headers["OK-ACCESS-PASSPHRASE"] == "passphrase"
  397. timestamp = request.headers["OK-ACCESS-TIMESTAMP"]
  398. path = urlparse(request.url).path
  399. query = urlencode(request.params or {})
  400. path_with_query = path if not query else f"{path}?{query}"
  401. expected_signature = base64.b64encode(
  402. hmac.new(
  403. b"secret",
  404. f"{timestamp}{request.method}{path_with_query}".encode(),
  405. hashlib.sha256,
  406. ).digest()
  407. ).decode()
  408. assert request.headers["OK-ACCESS-SIGN"] == expected_signature
  409. assert request.timeout is not None
  410. assert request.timeout > 0
  411. def test_signed_live_request_attaches_live_header():
  412. session = DummySession()
  413. client = OkxClient(config=live_config(), session=session)
  414. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  415. request = session.last_request
  416. assert request is not None
  417. assert request.headers["x-simulated-trading"] == "0"
  418. def test_signed_post_request_uses_actual_serialized_body_bytes():
  419. session = DummySession(
  420. [
  421. account_config_response(pos_mode="long_short_mode"),
  422. instrument_response(symbol="ETH-USDT-SWAP"),
  423. leverage_response(),
  424. place_order_response(),
  425. ]
  426. )
  427. client = OkxClient(config=sample_config(), session=session)
  428. client.place_order(symbol="ETH-USDT-SWAP", signal=limit_short_signal(), margin_usdt=100)
  429. request = session.last_request
  430. assert request is not None
  431. assert request.method == "POST"
  432. assert request.body is not None
  433. timestamp = request.headers["OK-ACCESS-TIMESTAMP"]
  434. path = urlparse(request.url).path
  435. expected_signature = base64.b64encode(
  436. hmac.new(
  437. b"secret",
  438. f"{timestamp}{request.method}{path}{request.body}".encode(),
  439. hashlib.sha256,
  440. ).digest()
  441. ).decode()
  442. assert request.headers["OK-ACCESS-SIGN"] == expected_signature
  443. def test_get_candles_returns_chronological_ascending_order():
  444. session = DummySession([descending_candles_response()])
  445. client = OkxClient(config=sample_config(), session=session)
  446. candles = client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  447. assert [candle.ts for candle in candles] == [1710000000000, 1710000001000]
  448. def test_get_candles_ignores_unconfirmed_history_rows():
  449. session = DummySession(
  450. [
  451. DummyResponse(
  452. {
  453. "code": "0",
  454. "msg": "",
  455. "data": [
  456. ["1710000001000", "25100", "25200", "25000", "25150", "110", "1100", "1100", "0"],
  457. ["1710000000000", "25000", "25100", "24900", "25050", "100", "1000", "1000", "1"],
  458. ],
  459. }
  460. )
  461. ]
  462. )
  463. client = OkxClient(config=sample_config(), session=session)
  464. candles = client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  465. assert [candle.ts for candle in candles] == [1710000000000]
  466. def test_get_candles_paginates_when_limit_exceeds_single_page():
  467. session = DummySession([full_page_candles_response(), older_candles_response()])
  468. client = OkxClient(config=sample_config(), session=session)
  469. candles = client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=102)
  470. assert len(candles) == 102
  471. assert candles[0].ts == 1709999700000
  472. assert candles[1].ts == 1709999701000
  473. assert len(session.request_paths) == 2
  474. def test_get_account_balance_returns_usdt_equity_fields():
  475. session = DummySession([balance_response()])
  476. client = OkxClient(config=sample_config(), session=session)
  477. balance = client.get_account_balance("USDT")
  478. assert session.request_paths == ["/api/v5/account/balance"]
  479. assert balance == {
  480. "total_equity_usd": 101.5,
  481. "equity": 100.25,
  482. "available_equity": 98.75,
  483. "cash_balance": 100.0,
  484. }
  485. def test_get_account_balance_returns_zero_when_currency_detail_is_absent():
  486. session = DummySession(
  487. [
  488. DummyResponse(
  489. {
  490. "code": "0",
  491. "msg": "",
  492. "data": [{"totalEq": "0", "details": []}],
  493. }
  494. )
  495. ]
  496. )
  497. client = OkxClient(config=sample_config(), session=session)
  498. balance = client.get_account_balance("USDT")
  499. assert balance == {
  500. "total_equity_usd": 0.0,
  501. "equity": 0.0,
  502. "available_equity": 0.0,
  503. "cash_balance": 0.0,
  504. }
  505. def test_build_contract_size_rounds_down_to_lot_size():
  506. metadata = InstrumentMeta(ct_val=0.01, lot_sz=0.1, min_sz=0.1)
  507. assert build_contract_size(notional=251, price=25_000, metadata=metadata) == 1.0
  508. def test_build_contract_size_fails_below_min_size():
  509. metadata = InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=5)
  510. with pytest.raises(ValueError):
  511. build_contract_size(notional=250, price=25_100, metadata=metadata)
  512. @pytest.mark.parametrize("notional", [0, -1, float("nan"), float("inf")])
  513. def test_build_contract_size_rejects_invalid_notional(notional):
  514. metadata = InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)
  515. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  516. build_contract_size(notional=notional, price=25_000, metadata=metadata)
  517. def test_build_contract_size_rejects_boolean_inputs():
  518. metadata = InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)
  519. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  520. build_contract_size(notional=True, price=25_000, metadata=metadata)
  521. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  522. build_contract_size(notional=100, price=False, metadata=metadata)
  523. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  524. build_contract_size(notional=100, price=25_000, metadata=InstrumentMeta(ct_val=True, lot_sz=1, min_sz=1))
  525. def test_post_only_limit_order_body_is_exact_okx_payload():
  526. body = OkxClient.build_post_only_limit_order_body(
  527. symbol="ETH-USDT-SWAP",
  528. action="long",
  529. price="2991.0000",
  530. size="2.000",
  531. client_order_id="eth-twap-1",
  532. )
  533. assert body == {
  534. "instId": "ETH-USDT-SWAP",
  535. "tdMode": "isolated",
  536. "side": "buy",
  537. "posSide": "long",
  538. "ordType": "post_only",
  539. "px": "2991",
  540. "sz": "2",
  541. "clOrdId": "eth-twap-1",
  542. }
  543. def test_short_post_only_limit_order_body_uses_sell_short():
  544. body = OkxClient.build_post_only_limit_order_body(
  545. symbol="ETH-USDT-SWAP",
  546. action="short",
  547. price="3018",
  548. size="1.5",
  549. client_order_id="eth-twap-short-2",
  550. )
  551. assert body["side"] == "sell"
  552. assert body["posSide"] == "short"
  553. assert body["ordType"] == "post_only"
  554. def test_entry_batch_order_body_uses_three_independent_post_only_levels():
  555. metadata = InstrumentMeta(ct_val=0.01, lot_sz=0.1, min_sz=0.1)
  556. body = OkxClient.build_entry_batch_order_body(
  557. symbol="ETH-USDT-SWAP",
  558. action="long",
  559. reference_price="3000",
  560. margin_usdt="90",
  561. leverage="2",
  562. metadata=metadata,
  563. client_order_id_prefix="eth-twap-20260430T000000Z",
  564. )
  565. assert body == [
  566. {
  567. "instId": "ETH-USDT-SWAP",
  568. "tdMode": "isolated",
  569. "side": "buy",
  570. "posSide": "long",
  571. "ordType": "post_only",
  572. "px": "2991",
  573. "sz": "2",
  574. "clOrdId": "eth-twap-20260430T000000Z-1",
  575. },
  576. {
  577. "instId": "ETH-USDT-SWAP",
  578. "tdMode": "isolated",
  579. "side": "buy",
  580. "posSide": "long",
  581. "ordType": "post_only",
  582. "px": "2982",
  583. "sz": "2",
  584. "clOrdId": "eth-twap-20260430T000000Z-2",
  585. },
  586. {
  587. "instId": "ETH-USDT-SWAP",
  588. "tdMode": "isolated",
  589. "side": "buy",
  590. "posSide": "long",
  591. "ordType": "post_only",
  592. "px": "2973",
  593. "sz": "2",
  594. "clOrdId": "eth-twap-20260430T000000Z-3",
  595. },
  596. ]
  597. def test_cancel_order_body_uses_exactly_one_identifier():
  598. assert OkxClient.build_cancel_order_body(symbol="ETH-USDT-SWAP", order_id="123") == {
  599. "instId": "ETH-USDT-SWAP",
  600. "ordId": "123",
  601. }
  602. assert OkxClient.build_cancel_order_body(symbol="ETH-USDT-SWAP", client_order_id="eth-twap-1") == {
  603. "instId": "ETH-USDT-SWAP",
  604. "clOrdId": "eth-twap-1",
  605. }
  606. def test_pending_orders_query_params_are_minimal_params():
  607. assert OkxClient.build_pending_orders_params(symbol="ETH-USDT-SWAP") == {
  608. "instType": "SWAP",
  609. "instId": "ETH-USDT-SWAP",
  610. }
  611. def test_market_order_body_supports_reduce_only_close():
  612. assert OkxClient.build_market_order_body(
  613. symbol="ETH-USDT-SWAP",
  614. side="sell",
  615. pos_side="long",
  616. size=2,
  617. client_order_id="eth-close-1",
  618. reduce_only=True,
  619. ) == {
  620. "instId": "ETH-USDT-SWAP",
  621. "tdMode": "isolated",
  622. "side": "sell",
  623. "posSide": "long",
  624. "ordType": "market",
  625. "sz": "2",
  626. "clOrdId": "eth-close-1",
  627. "reduceOnly": "true",
  628. }
  629. def test_submit_market_order_body_posts_body_and_returns_order_result():
  630. session = DummySession([place_order_response()])
  631. client = OkxClient(sample_config(), session=session)
  632. body = OkxClient.build_market_order_body(
  633. symbol="ETH-USDT-SWAP",
  634. side="sell",
  635. pos_side="long",
  636. size=2,
  637. client_order_id="eth-close-1",
  638. reduce_only=True,
  639. )
  640. result = client.submit_market_order_body(body)
  641. assert session.request_paths == ["/api/v5/trade/order"]
  642. assert session.last_json_body == body
  643. assert result.status == "placed"
  644. assert result.order_id == "123"
  645. assert result.symbol == "ETH-USDT-SWAP"
  646. assert result.side == "sell"
  647. assert result.pos_side == "long"
  648. assert result.order_type == "market"
  649. assert result.size == 2.0
  650. def test_submit_market_order_body_rejects_invalid_body_before_okx():
  651. session = DummySession([place_order_response()])
  652. client = OkxClient(sample_config(), session=session)
  653. with pytest.raises(ValueError, match="market order body is invalid"):
  654. client.submit_market_order_body({"instId": "ETH-USDT-SWAP", "ordType": "limit"})
  655. assert session.request_paths == []
  656. def test_fills_query_params_are_minimal_params():
  657. assert OkxClient.build_fills_params(symbol="ETH-USDT-SWAP") == {
  658. "instType": "SWAP",
  659. "instId": "ETH-USDT-SWAP",
  660. }
  661. @pytest.mark.parametrize(
  662. ("price", "metadata"),
  663. [
  664. (0, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  665. (-1, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  666. (25_000, InstrumentMeta(ct_val=0, lot_sz=1, min_sz=1)),
  667. (25_000, InstrumentMeta(ct_val=-0.01, lot_sz=1, min_sz=1)),
  668. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=0, min_sz=1)),
  669. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=-1, min_sz=1)),
  670. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=0)),
  671. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=-1)),
  672. ],
  673. )
  674. def test_build_contract_size_rejects_non_positive_inputs(price, metadata):
  675. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  676. build_contract_size(notional=250, price=price, metadata=metadata)
  677. @pytest.mark.parametrize(
  678. ("price", "metadata"),
  679. [
  680. (float("nan"), InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  681. (float("inf"), InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  682. (25_000, InstrumentMeta(ct_val=float("nan"), lot_sz=1, min_sz=1)),
  683. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=float("inf"), min_sz=1)),
  684. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=float("-inf"))),
  685. ],
  686. )
  687. def test_build_contract_size_rejects_non_finite_inputs(price, metadata):
  688. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  689. build_contract_size(notional=250, price=price, metadata=metadata)
  690. def test_market_order_fetches_latest_price_before_sizing():
  691. session = DummySession(
  692. [
  693. account_config_response(pos_mode="long_short_mode"),
  694. instrument_response(),
  695. ticker_response(last="25000"),
  696. leverage_response(),
  697. place_order_response(),
  698. ]
  699. )
  700. client = OkxClient(config=sample_config(), session=session)
  701. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  702. assert session.request_paths == [
  703. "/api/v5/account/config",
  704. "/api/v5/public/instruments",
  705. "/api/v5/market/ticker",
  706. "/api/v5/account/set-leverage",
  707. "/api/v5/trade/order",
  708. ]
  709. def test_fractional_margin_sizing_keeps_decimal_precision():
  710. session = DummySession(
  711. [
  712. account_config_response(pos_mode="long_short_mode"),
  713. instrument_response(),
  714. ticker_response(last="1"),
  715. leverage_response(),
  716. place_order_response(),
  717. ]
  718. )
  719. signal = TradeSignal(
  720. action="long",
  721. confidence=0.9,
  722. leverage=3,
  723. entry_price=None,
  724. take_profit_price=None,
  725. stop_loss_price=None,
  726. reason="x",
  727. )
  728. client = OkxClient(config=sample_config(), session=session)
  729. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=0.009)
  730. assert session.last_json_body is not None
  731. assert session.last_json_body["sz"] == "27"
  732. def test_place_order_fails_when_not_hedge_mode():
  733. session = DummySession(
  734. [
  735. account_config_response(pos_mode="net_mode"),
  736. ]
  737. )
  738. client = OkxClient(config=sample_config(), session=session)
  739. with pytest.raises(ValueError):
  740. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  741. assert session.request_paths == ["/api/v5/account/config"]
  742. def test_ensure_hedge_mode_rejects_malformed_config_payload():
  743. session = DummySession([malformed_account_config_response(pos_mode=None)])
  744. client = OkxClient(config=sample_config(), session=session)
  745. with pytest.raises(ValueError, match="okx response payload is invalid"):
  746. client.ensure_hedge_mode()
  747. def test_place_order_validates_size_before_setting_leverage():
  748. session = DummySession(
  749. [
  750. account_config_response(pos_mode="long_short_mode"),
  751. large_min_size_instrument_response(),
  752. ticker_response(last="25000"),
  753. ]
  754. )
  755. client = OkxClient(config=sample_config(), session=session)
  756. with pytest.raises(ValueError, match="contract size below minimum"):
  757. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  758. assert session.request_paths == [
  759. "/api/v5/account/config",
  760. "/api/v5/public/instruments",
  761. "/api/v5/market/ticker",
  762. ]
  763. def test_limit_short_order_uses_sell_and_short_pos_side():
  764. session = DummySession(
  765. [
  766. account_config_response(pos_mode="long_short_mode"),
  767. instrument_response(symbol="ETH-USDT-SWAP"),
  768. leverage_response(),
  769. place_order_response(),
  770. ]
  771. )
  772. client = OkxClient(config=sample_config(), session=session)
  773. client.place_order(symbol="ETH-USDT-SWAP", signal=limit_short_signal(), margin_usdt=100)
  774. order_request = session.last_json_body
  775. assert order_request is not None
  776. assert order_request["ordType"] == "limit"
  777. assert order_request["side"] == "sell"
  778. assert order_request["posSide"] == "short"
  779. assert order_request["px"] == "25000"
  780. assert session.request_bodies[2]["lever"] == "2"
  781. assert session.request_bodies[2]["mgnMode"] == "isolated"
  782. def test_flat_signal_returns_noop_without_order_submission():
  783. session = DummySession([])
  784. client = OkxClient(config=sample_config(), session=session)
  785. result = client.place_order(symbol="BTC-USDT-SWAP", signal=flat_signal(), margin_usdt=100)
  786. assert result.status == "noop"
  787. assert session.request_paths == []
  788. def test_place_order_sends_computed_sz_and_ignores_tp_sl_fields():
  789. session = DummySession(
  790. [
  791. account_config_response(pos_mode="long_short_mode"),
  792. instrument_response(),
  793. ticker_response(last="25000"),
  794. leverage_response(),
  795. place_order_response(),
  796. ]
  797. )
  798. client = OkxClient(config=sample_config(), session=session)
  799. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  800. order_request = session.last_json_body
  801. assert order_request is not None
  802. assert order_request["sz"] == "8"
  803. assert "tpTriggerPx" not in order_request
  804. assert "slTriggerPx" not in order_request
  805. def test_okx_error_payload_raises_value_error():
  806. session = DummySession([error_response(code="51000", msg="parameter error")])
  807. client = OkxClient(config=sample_config(), session=session)
  808. with pytest.raises(ValueError, match="parameter error"):
  809. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  810. def test_okx_error_payload_includes_operation_details():
  811. session = DummySession(
  812. [
  813. DummyResponse(
  814. {
  815. "code": "1",
  816. "msg": "All operations failed",
  817. "data": [{"sCode": "51000", "sMsg": "Parameter posSide error"}],
  818. }
  819. )
  820. ]
  821. )
  822. client = OkxClient(config=sample_config(), session=session)
  823. with pytest.raises(ValueError, match="All operations failed; 51000: Parameter posSide error"):
  824. client.submit_market_order_body(
  825. {
  826. "instId": "ETH-USDT-SWAP",
  827. "tdMode": "isolated",
  828. "side": "sell",
  829. "posSide": "short",
  830. "ordType": "market",
  831. "sz": "1.29",
  832. "clOrdId": "test",
  833. }
  834. )
  835. def test_get_candles_rejects_non_finite_numeric_fields():
  836. session = DummySession([candles_with_non_finite_numeric_response()])
  837. client = OkxClient(config=sample_config(), session=session)
  838. with pytest.raises(ValueError, match="okx response payload is invalid"):
  839. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  840. def test_transport_failure_raises_stable_value_error():
  841. session = DummySession([RuntimeError("socket closed")])
  842. client = OkxClient(config=sample_config(), session=session)
  843. with pytest.raises(ValueError, match="okx transport error"):
  844. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  845. def test_invalid_json_raises_stable_value_error():
  846. session = DummySession([DummyResponse({}, json_error=ValueError("bad json"))])
  847. client = OkxClient(config=sample_config(), session=session)
  848. with pytest.raises(ValueError, match="okx response payload is invalid"):
  849. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  850. def test_empty_positions_data_returns_empty_list():
  851. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": []})])
  852. client = OkxClient(config=sample_config(), session=session)
  853. assert client.get_positions(symbol="BTC-USDT-SWAP") == []
  854. def test_malformed_numeric_field_raises_stable_value_error():
  855. session = DummySession(
  856. [
  857. DummyResponse(
  858. {
  859. "code": "0",
  860. "msg": "",
  861. "data": [
  862. {
  863. "instId": "BTC-USDT-SWAP",
  864. "posSide": "long",
  865. "pos": "bad",
  866. "avgPx": "25000",
  867. }
  868. ],
  869. }
  870. )
  871. ]
  872. )
  873. client = OkxClient(config=sample_config(), session=session)
  874. with pytest.raises(ValueError, match="okx response payload is invalid"):
  875. client.get_positions(symbol="BTC-USDT-SWAP")
  876. def test_non_list_okx_data_raises_stable_value_error():
  877. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": {}})])
  878. client = OkxClient(config=sample_config(), session=session)
  879. with pytest.raises(ValueError, match="okx response payload is invalid"):
  880. client.get_positions(symbol="BTC-USDT-SWAP")
  881. def test_get_instrument_meta_rejects_non_finite_numeric_fields():
  882. session = DummySession([instrument_with_non_finite_numeric_response()])
  883. client = OkxClient(config=sample_config(), session=session)
  884. with pytest.raises(ValueError, match="okx response payload is invalid"):
  885. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  886. def test_get_last_price_rejects_non_finite_numeric_field():
  887. session = DummySession([ticker_with_non_finite_numeric_response()])
  888. client = OkxClient(config=sample_config(), session=session)
  889. with pytest.raises(ValueError, match="okx response payload is invalid"):
  890. client.get_last_price(symbol="BTC-USDT-SWAP")
  891. def test_get_last_price_rejects_mismatched_symbol():
  892. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": [{"instId": "ETH-USDT-SWAP", "last": "25000"}]})])
  893. client = OkxClient(config=sample_config(), session=session)
  894. with pytest.raises(ValueError, match="okx response payload is invalid"):
  895. client.get_last_price(symbol="BTC-USDT-SWAP")
  896. def test_get_instrument_meta_rejects_mismatched_symbol():
  897. session = DummySession([instrument_with_wrong_symbol_response()])
  898. client = OkxClient(config=sample_config(), session=session)
  899. with pytest.raises(ValueError, match="okx response payload is invalid"):
  900. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  901. def test_get_instrument_meta_rejects_non_swap_type():
  902. session = DummySession([instrument_with_wrong_type_response()])
  903. client = OkxClient(config=sample_config(), session=session)
  904. with pytest.raises(ValueError, match="okx response payload is invalid"):
  905. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  906. def test_place_order_raises_when_order_id_is_missing():
  907. session = DummySession(
  908. [
  909. account_config_response(pos_mode="long_short_mode"),
  910. instrument_response(),
  911. ticker_response(last="25000"),
  912. leverage_response(),
  913. place_order_response_without_order_id(),
  914. ]
  915. )
  916. client = OkxClient(config=sample_config(), session=session)
  917. with pytest.raises(ValueError, match="okx response payload is invalid"):
  918. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  919. assert session.request_paths[-1] == "/api/v5/trade/order"
  920. def test_place_order_rejects_invalid_leverage_before_okx():
  921. session = DummySession([])
  922. signal = TradeSignal(
  923. action="long",
  924. confidence=0.9,
  925. leverage=4,
  926. entry_price=None,
  927. take_profit_price=None,
  928. stop_loss_price=None,
  929. reason="x",
  930. )
  931. client = OkxClient(config=sample_config(), session=session)
  932. with pytest.raises(ValueError, match="leverage is invalid"):
  933. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  934. assert session.request_paths == []
  935. def test_place_order_rejects_fractional_leverage_before_okx():
  936. session = DummySession([])
  937. signal = TradeSignal(
  938. action="long",
  939. confidence=0.9,
  940. leverage=2.5,
  941. entry_price=None,
  942. take_profit_price=None,
  943. stop_loss_price=None,
  944. reason="x",
  945. )
  946. client = OkxClient(config=sample_config(), session=session)
  947. with pytest.raises(ValueError, match="leverage is invalid"):
  948. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  949. assert session.request_paths == []
  950. def test_place_order_rejects_boolean_leverage_before_okx():
  951. session = DummySession([])
  952. signal = TradeSignal(
  953. action="long",
  954. confidence=0.9,
  955. leverage=True,
  956. entry_price=None,
  957. take_profit_price=None,
  958. stop_loss_price=None,
  959. reason="x",
  960. )
  961. client = OkxClient(config=sample_config(), session=session)
  962. with pytest.raises(ValueError, match="leverage is invalid"):
  963. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  964. assert session.request_paths == []
  965. @pytest.mark.parametrize("margin_usdt", [0, -1, float("nan"), float("inf")])
  966. def test_place_order_rejects_invalid_margin_before_okx(margin_usdt):
  967. session = DummySession([])
  968. client = OkxClient(config=sample_config(), session=session)
  969. with pytest.raises(ValueError, match="margin_usdt is invalid"):
  970. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=margin_usdt)
  971. assert session.request_paths == []
  972. def test_place_order_rejects_boolean_margin_before_okx():
  973. session = DummySession([])
  974. client = OkxClient(config=sample_config(), session=session)
  975. with pytest.raises(ValueError, match="margin_usdt is invalid"):
  976. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=True)
  977. assert session.request_paths == []
  978. @pytest.mark.parametrize(
  979. ("symbol", "leverage", "pos_side", "expected_message"),
  980. [
  981. ("BTC-USDT", 2, "long", "swap instrument is required"),
  982. ("BTC-USDT-SWAP", 4, "long", "leverage is invalid"),
  983. ("BTC-USDT-SWAP", 2.5, "long", "leverage is invalid"),
  984. ("BTC-USDT-SWAP", 2, "net", "pos_side is invalid"),
  985. ],
  986. )
  987. def test_set_leverage_validates_public_boundary_inputs(symbol, leverage, pos_side, expected_message):
  988. session = DummySession([])
  989. client = OkxClient(config=sample_config(), session=session)
  990. with pytest.raises(ValueError, match=expected_message):
  991. client.set_leverage(symbol=symbol, leverage=leverage, pos_side=pos_side)
  992. assert session.request_paths == []
  993. def test_place_order_rejects_unknown_action_before_okx():
  994. session = DummySession([])
  995. signal = TradeSignal(
  996. action="hold",
  997. confidence=0.9,
  998. leverage=2,
  999. entry_price=None,
  1000. take_profit_price=None,
  1001. stop_loss_price=None,
  1002. reason="x",
  1003. )
  1004. client = OkxClient(config=sample_config(), session=session)
  1005. with pytest.raises(ValueError, match="action is invalid"):
  1006. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  1007. assert session.request_paths == []
  1008. def test_get_positions_returns_normalized_positions():
  1009. session = DummySession([positions_response()])
  1010. client = OkxClient(config=sample_config(), session=session)
  1011. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  1012. assert positions[0].symbol == "BTC-USDT-SWAP"
  1013. assert positions[0].pos_side == "long"
  1014. assert positions[0].size == 8.0
  1015. assert positions[0].avg_price == 25000.0
  1016. def test_get_positions_filters_zero_size_rows():
  1017. session = DummySession([positions_with_zero_size_response()])
  1018. client = OkxClient(config=sample_config(), session=session)
  1019. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  1020. assert len(positions) == 1
  1021. assert positions[0].pos_side == "short"
  1022. assert positions[0].size == 3.0
  1023. def test_get_positions_ignores_malformed_fields_on_zero_size_rows():
  1024. session = DummySession([positions_with_zero_size_malformed_avg_price_response()])
  1025. client = OkxClient(config=sample_config(), session=session)
  1026. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  1027. assert len(positions) == 1
  1028. assert positions[0].pos_side == "short"
  1029. assert positions[0].avg_price == 24900.0
  1030. def test_get_positions_rejects_non_string_inst_id_and_pos_side():
  1031. session = DummySession([positions_with_non_string_identity_response()])
  1032. client = OkxClient(config=sample_config(), session=session)
  1033. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1034. client.get_positions(symbol="BTC-USDT-SWAP")
  1035. def test_get_positions_rejects_non_finite_numeric_fields():
  1036. session = DummySession([positions_with_non_finite_numeric_response()])
  1037. client = OkxClient(config=sample_config(), session=session)
  1038. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1039. client.get_positions(symbol="BTC-USDT-SWAP")
  1040. def test_get_positions_rejects_mismatched_symbol():
  1041. session = DummySession([positions_with_wrong_symbol_response()])
  1042. client = OkxClient(config=sample_config(), session=session)
  1043. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1044. client.get_positions(symbol="BTC-USDT-SWAP")
  1045. def test_get_positions_rejects_invalid_pos_side():
  1046. session = DummySession([positions_with_invalid_pos_side_response()])
  1047. client = OkxClient(config=sample_config(), session=session)
  1048. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1049. client.get_positions(symbol="BTC-USDT-SWAP")