test_okx_client.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  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_market_order_body_attaches_stop_loss_for_open_order():
  630. assert OkxClient.build_market_order_body(
  631. symbol="ETH-USDT-SWAP",
  632. side="sell",
  633. pos_side="short",
  634. size=1.38,
  635. client_order_id="eth-open-1",
  636. reduce_only=False,
  637. stop_loss_trigger_price=2140.25,
  638. ) == {
  639. "instId": "ETH-USDT-SWAP",
  640. "tdMode": "isolated",
  641. "side": "sell",
  642. "posSide": "short",
  643. "ordType": "market",
  644. "sz": "1.38",
  645. "clOrdId": "eth-open-1",
  646. "attachAlgoOrds": [{"slTriggerPx": "2140.25", "slOrdPx": "-1"}],
  647. }
  648. def test_market_order_body_rejects_stop_loss_on_reduce_only_order():
  649. with pytest.raises(ValueError, match="stop loss is invalid"):
  650. OkxClient.build_market_order_body(
  651. symbol="ETH-USDT-SWAP",
  652. side="sell",
  653. pos_side="long",
  654. size=1.0,
  655. client_order_id="eth-close-1",
  656. reduce_only=True,
  657. stop_loss_trigger_price=2000.0,
  658. )
  659. def test_submit_market_order_body_posts_body_and_returns_order_result():
  660. session = DummySession([place_order_response()])
  661. client = OkxClient(sample_config(), session=session)
  662. body = OkxClient.build_market_order_body(
  663. symbol="ETH-USDT-SWAP",
  664. side="sell",
  665. pos_side="long",
  666. size=2,
  667. client_order_id="eth-close-1",
  668. reduce_only=True,
  669. )
  670. result = client.submit_market_order_body(body)
  671. assert session.request_paths == ["/api/v5/trade/order"]
  672. assert session.last_json_body == body
  673. assert result.status == "placed"
  674. assert result.order_id == "123"
  675. assert result.symbol == "ETH-USDT-SWAP"
  676. assert result.side == "sell"
  677. assert result.pos_side == "long"
  678. assert result.order_type == "market"
  679. assert result.size == 2.0
  680. def test_submit_market_order_body_rejects_invalid_body_before_okx():
  681. session = DummySession([place_order_response()])
  682. client = OkxClient(sample_config(), session=session)
  683. with pytest.raises(ValueError, match="market order body is invalid"):
  684. client.submit_market_order_body({"instId": "ETH-USDT-SWAP", "ordType": "limit"})
  685. assert session.request_paths == []
  686. def test_fills_query_params_are_minimal_params():
  687. assert OkxClient.build_fills_params(symbol="ETH-USDT-SWAP") == {
  688. "instType": "SWAP",
  689. "instId": "ETH-USDT-SWAP",
  690. }
  691. @pytest.mark.parametrize(
  692. ("price", "metadata"),
  693. [
  694. (0, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  695. (-1, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  696. (25_000, InstrumentMeta(ct_val=0, lot_sz=1, min_sz=1)),
  697. (25_000, InstrumentMeta(ct_val=-0.01, lot_sz=1, min_sz=1)),
  698. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=0, min_sz=1)),
  699. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=-1, min_sz=1)),
  700. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=0)),
  701. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=-1)),
  702. ],
  703. )
  704. def test_build_contract_size_rejects_non_positive_inputs(price, metadata):
  705. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  706. build_contract_size(notional=250, price=price, metadata=metadata)
  707. @pytest.mark.parametrize(
  708. ("price", "metadata"),
  709. [
  710. (float("nan"), InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  711. (float("inf"), InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  712. (25_000, InstrumentMeta(ct_val=float("nan"), lot_sz=1, min_sz=1)),
  713. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=float("inf"), min_sz=1)),
  714. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=float("-inf"))),
  715. ],
  716. )
  717. def test_build_contract_size_rejects_non_finite_inputs(price, metadata):
  718. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  719. build_contract_size(notional=250, price=price, metadata=metadata)
  720. def test_market_order_fetches_latest_price_before_sizing():
  721. session = DummySession(
  722. [
  723. account_config_response(pos_mode="long_short_mode"),
  724. instrument_response(),
  725. ticker_response(last="25000"),
  726. leverage_response(),
  727. place_order_response(),
  728. ]
  729. )
  730. client = OkxClient(config=sample_config(), session=session)
  731. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  732. assert session.request_paths == [
  733. "/api/v5/account/config",
  734. "/api/v5/public/instruments",
  735. "/api/v5/market/ticker",
  736. "/api/v5/account/set-leverage",
  737. "/api/v5/trade/order",
  738. ]
  739. def test_fractional_margin_sizing_keeps_decimal_precision():
  740. session = DummySession(
  741. [
  742. account_config_response(pos_mode="long_short_mode"),
  743. instrument_response(),
  744. ticker_response(last="1"),
  745. leverage_response(),
  746. place_order_response(),
  747. ]
  748. )
  749. signal = TradeSignal(
  750. action="long",
  751. confidence=0.9,
  752. leverage=3,
  753. entry_price=None,
  754. take_profit_price=None,
  755. stop_loss_price=None,
  756. reason="x",
  757. )
  758. client = OkxClient(config=sample_config(), session=session)
  759. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=0.009)
  760. assert session.last_json_body is not None
  761. assert session.last_json_body["sz"] == "27"
  762. def test_place_order_fails_when_not_hedge_mode():
  763. session = DummySession(
  764. [
  765. account_config_response(pos_mode="net_mode"),
  766. ]
  767. )
  768. client = OkxClient(config=sample_config(), session=session)
  769. with pytest.raises(ValueError):
  770. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  771. assert session.request_paths == ["/api/v5/account/config"]
  772. def test_ensure_hedge_mode_rejects_malformed_config_payload():
  773. session = DummySession([malformed_account_config_response(pos_mode=None)])
  774. client = OkxClient(config=sample_config(), session=session)
  775. with pytest.raises(ValueError, match="okx response payload is invalid"):
  776. client.ensure_hedge_mode()
  777. def test_place_order_validates_size_before_setting_leverage():
  778. session = DummySession(
  779. [
  780. account_config_response(pos_mode="long_short_mode"),
  781. large_min_size_instrument_response(),
  782. ticker_response(last="25000"),
  783. ]
  784. )
  785. client = OkxClient(config=sample_config(), session=session)
  786. with pytest.raises(ValueError, match="contract size below minimum"):
  787. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  788. assert session.request_paths == [
  789. "/api/v5/account/config",
  790. "/api/v5/public/instruments",
  791. "/api/v5/market/ticker",
  792. ]
  793. def test_limit_short_order_uses_sell_and_short_pos_side():
  794. session = DummySession(
  795. [
  796. account_config_response(pos_mode="long_short_mode"),
  797. instrument_response(symbol="ETH-USDT-SWAP"),
  798. leverage_response(),
  799. place_order_response(),
  800. ]
  801. )
  802. client = OkxClient(config=sample_config(), session=session)
  803. client.place_order(symbol="ETH-USDT-SWAP", signal=limit_short_signal(), margin_usdt=100)
  804. order_request = session.last_json_body
  805. assert order_request is not None
  806. assert order_request["ordType"] == "limit"
  807. assert order_request["side"] == "sell"
  808. assert order_request["posSide"] == "short"
  809. assert order_request["px"] == "25000"
  810. assert session.request_bodies[2]["lever"] == "2"
  811. assert session.request_bodies[2]["mgnMode"] == "isolated"
  812. def test_flat_signal_returns_noop_without_order_submission():
  813. session = DummySession([])
  814. client = OkxClient(config=sample_config(), session=session)
  815. result = client.place_order(symbol="BTC-USDT-SWAP", signal=flat_signal(), margin_usdt=100)
  816. assert result.status == "noop"
  817. assert session.request_paths == []
  818. def test_place_order_sends_computed_sz_and_ignores_tp_sl_fields():
  819. session = DummySession(
  820. [
  821. account_config_response(pos_mode="long_short_mode"),
  822. instrument_response(),
  823. ticker_response(last="25000"),
  824. leverage_response(),
  825. place_order_response(),
  826. ]
  827. )
  828. client = OkxClient(config=sample_config(), session=session)
  829. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  830. order_request = session.last_json_body
  831. assert order_request is not None
  832. assert order_request["sz"] == "8"
  833. assert "tpTriggerPx" not in order_request
  834. assert "slTriggerPx" not in order_request
  835. def test_okx_error_payload_raises_value_error():
  836. session = DummySession([error_response(code="51000", msg="parameter error")])
  837. client = OkxClient(config=sample_config(), session=session)
  838. with pytest.raises(ValueError, match="parameter error"):
  839. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  840. def test_okx_error_payload_includes_operation_details():
  841. session = DummySession(
  842. [
  843. DummyResponse(
  844. {
  845. "code": "1",
  846. "msg": "All operations failed",
  847. "data": [{"sCode": "51000", "sMsg": "Parameter posSide error"}],
  848. }
  849. )
  850. ]
  851. )
  852. client = OkxClient(config=sample_config(), session=session)
  853. with pytest.raises(ValueError, match="All operations failed; 51000: Parameter posSide error"):
  854. client.submit_market_order_body(
  855. {
  856. "instId": "ETH-USDT-SWAP",
  857. "tdMode": "isolated",
  858. "side": "sell",
  859. "posSide": "short",
  860. "ordType": "market",
  861. "sz": "1.29",
  862. "clOrdId": "test",
  863. }
  864. )
  865. def test_get_candles_rejects_non_finite_numeric_fields():
  866. session = DummySession([candles_with_non_finite_numeric_response()])
  867. client = OkxClient(config=sample_config(), session=session)
  868. with pytest.raises(ValueError, match="okx response payload is invalid"):
  869. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  870. def test_transport_failure_raises_stable_value_error():
  871. session = DummySession([RuntimeError("socket closed")])
  872. client = OkxClient(config=sample_config(), session=session)
  873. with pytest.raises(ValueError, match="okx transport error"):
  874. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  875. def test_invalid_json_raises_stable_value_error():
  876. session = DummySession([DummyResponse({}, json_error=ValueError("bad json"))])
  877. client = OkxClient(config=sample_config(), session=session)
  878. with pytest.raises(ValueError, match="okx response payload is invalid"):
  879. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  880. def test_empty_positions_data_returns_empty_list():
  881. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": []})])
  882. client = OkxClient(config=sample_config(), session=session)
  883. assert client.get_positions(symbol="BTC-USDT-SWAP") == []
  884. def test_malformed_numeric_field_raises_stable_value_error():
  885. session = DummySession(
  886. [
  887. DummyResponse(
  888. {
  889. "code": "0",
  890. "msg": "",
  891. "data": [
  892. {
  893. "instId": "BTC-USDT-SWAP",
  894. "posSide": "long",
  895. "pos": "bad",
  896. "avgPx": "25000",
  897. }
  898. ],
  899. }
  900. )
  901. ]
  902. )
  903. client = OkxClient(config=sample_config(), session=session)
  904. with pytest.raises(ValueError, match="okx response payload is invalid"):
  905. client.get_positions(symbol="BTC-USDT-SWAP")
  906. def test_non_list_okx_data_raises_stable_value_error():
  907. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": {}})])
  908. client = OkxClient(config=sample_config(), session=session)
  909. with pytest.raises(ValueError, match="okx response payload is invalid"):
  910. client.get_positions(symbol="BTC-USDT-SWAP")
  911. def test_get_instrument_meta_rejects_non_finite_numeric_fields():
  912. session = DummySession([instrument_with_non_finite_numeric_response()])
  913. client = OkxClient(config=sample_config(), session=session)
  914. with pytest.raises(ValueError, match="okx response payload is invalid"):
  915. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  916. def test_get_last_price_rejects_non_finite_numeric_field():
  917. session = DummySession([ticker_with_non_finite_numeric_response()])
  918. client = OkxClient(config=sample_config(), session=session)
  919. with pytest.raises(ValueError, match="okx response payload is invalid"):
  920. client.get_last_price(symbol="BTC-USDT-SWAP")
  921. def test_get_last_price_rejects_mismatched_symbol():
  922. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": [{"instId": "ETH-USDT-SWAP", "last": "25000"}]})])
  923. client = OkxClient(config=sample_config(), session=session)
  924. with pytest.raises(ValueError, match="okx response payload is invalid"):
  925. client.get_last_price(symbol="BTC-USDT-SWAP")
  926. def test_get_instrument_meta_rejects_mismatched_symbol():
  927. session = DummySession([instrument_with_wrong_symbol_response()])
  928. client = OkxClient(config=sample_config(), session=session)
  929. with pytest.raises(ValueError, match="okx response payload is invalid"):
  930. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  931. def test_get_instrument_meta_rejects_non_swap_type():
  932. session = DummySession([instrument_with_wrong_type_response()])
  933. client = OkxClient(config=sample_config(), session=session)
  934. with pytest.raises(ValueError, match="okx response payload is invalid"):
  935. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  936. def test_place_order_raises_when_order_id_is_missing():
  937. session = DummySession(
  938. [
  939. account_config_response(pos_mode="long_short_mode"),
  940. instrument_response(),
  941. ticker_response(last="25000"),
  942. leverage_response(),
  943. place_order_response_without_order_id(),
  944. ]
  945. )
  946. client = OkxClient(config=sample_config(), session=session)
  947. with pytest.raises(ValueError, match="okx response payload is invalid"):
  948. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  949. assert session.request_paths[-1] == "/api/v5/trade/order"
  950. def test_place_order_rejects_invalid_leverage_before_okx():
  951. session = DummySession([])
  952. signal = TradeSignal(
  953. action="long",
  954. confidence=0.9,
  955. leverage=4,
  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. def test_place_order_rejects_fractional_leverage_before_okx():
  966. session = DummySession([])
  967. signal = TradeSignal(
  968. action="long",
  969. confidence=0.9,
  970. leverage=2.5,
  971. entry_price=None,
  972. take_profit_price=None,
  973. stop_loss_price=None,
  974. reason="x",
  975. )
  976. client = OkxClient(config=sample_config(), session=session)
  977. with pytest.raises(ValueError, match="leverage is invalid"):
  978. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  979. assert session.request_paths == []
  980. def test_place_order_rejects_boolean_leverage_before_okx():
  981. session = DummySession([])
  982. signal = TradeSignal(
  983. action="long",
  984. confidence=0.9,
  985. leverage=True,
  986. entry_price=None,
  987. take_profit_price=None,
  988. stop_loss_price=None,
  989. reason="x",
  990. )
  991. client = OkxClient(config=sample_config(), session=session)
  992. with pytest.raises(ValueError, match="leverage is invalid"):
  993. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  994. assert session.request_paths == []
  995. @pytest.mark.parametrize("margin_usdt", [0, -1, float("nan"), float("inf")])
  996. def test_place_order_rejects_invalid_margin_before_okx(margin_usdt):
  997. session = DummySession([])
  998. client = OkxClient(config=sample_config(), session=session)
  999. with pytest.raises(ValueError, match="margin_usdt is invalid"):
  1000. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=margin_usdt)
  1001. assert session.request_paths == []
  1002. def test_place_order_rejects_boolean_margin_before_okx():
  1003. session = DummySession([])
  1004. client = OkxClient(config=sample_config(), session=session)
  1005. with pytest.raises(ValueError, match="margin_usdt is invalid"):
  1006. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=True)
  1007. assert session.request_paths == []
  1008. @pytest.mark.parametrize(
  1009. ("symbol", "leverage", "pos_side", "expected_message"),
  1010. [
  1011. ("BTC-USDT", 2, "long", "swap instrument is required"),
  1012. ("BTC-USDT-SWAP", 4, "long", "leverage is invalid"),
  1013. ("BTC-USDT-SWAP", 2.5, "long", "leverage is invalid"),
  1014. ("BTC-USDT-SWAP", 2, "net", "pos_side is invalid"),
  1015. ],
  1016. )
  1017. def test_set_leverage_validates_public_boundary_inputs(symbol, leverage, pos_side, expected_message):
  1018. session = DummySession([])
  1019. client = OkxClient(config=sample_config(), session=session)
  1020. with pytest.raises(ValueError, match=expected_message):
  1021. client.set_leverage(symbol=symbol, leverage=leverage, pos_side=pos_side)
  1022. assert session.request_paths == []
  1023. def test_place_order_rejects_unknown_action_before_okx():
  1024. session = DummySession([])
  1025. signal = TradeSignal(
  1026. action="hold",
  1027. confidence=0.9,
  1028. leverage=2,
  1029. entry_price=None,
  1030. take_profit_price=None,
  1031. stop_loss_price=None,
  1032. reason="x",
  1033. )
  1034. client = OkxClient(config=sample_config(), session=session)
  1035. with pytest.raises(ValueError, match="action is invalid"):
  1036. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  1037. assert session.request_paths == []
  1038. def test_get_positions_returns_normalized_positions():
  1039. session = DummySession([positions_response()])
  1040. client = OkxClient(config=sample_config(), session=session)
  1041. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  1042. assert positions[0].symbol == "BTC-USDT-SWAP"
  1043. assert positions[0].pos_side == "long"
  1044. assert positions[0].size == 8.0
  1045. assert positions[0].avg_price == 25000.0
  1046. def test_get_positions_filters_zero_size_rows():
  1047. session = DummySession([positions_with_zero_size_response()])
  1048. client = OkxClient(config=sample_config(), session=session)
  1049. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  1050. assert len(positions) == 1
  1051. assert positions[0].pos_side == "short"
  1052. assert positions[0].size == 3.0
  1053. def test_get_positions_ignores_malformed_fields_on_zero_size_rows():
  1054. session = DummySession([positions_with_zero_size_malformed_avg_price_response()])
  1055. client = OkxClient(config=sample_config(), session=session)
  1056. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  1057. assert len(positions) == 1
  1058. assert positions[0].pos_side == "short"
  1059. assert positions[0].avg_price == 24900.0
  1060. def test_get_positions_rejects_non_string_inst_id_and_pos_side():
  1061. session = DummySession([positions_with_non_string_identity_response()])
  1062. client = OkxClient(config=sample_config(), session=session)
  1063. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1064. client.get_positions(symbol="BTC-USDT-SWAP")
  1065. def test_get_positions_rejects_non_finite_numeric_fields():
  1066. session = DummySession([positions_with_non_finite_numeric_response()])
  1067. client = OkxClient(config=sample_config(), session=session)
  1068. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1069. client.get_positions(symbol="BTC-USDT-SWAP")
  1070. def test_get_positions_rejects_mismatched_symbol():
  1071. session = DummySession([positions_with_wrong_symbol_response()])
  1072. client = OkxClient(config=sample_config(), session=session)
  1073. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1074. client.get_positions(symbol="BTC-USDT-SWAP")
  1075. def test_get_positions_rejects_invalid_pos_side():
  1076. session = DummySession([positions_with_invalid_pos_side_response()])
  1077. client = OkxClient(config=sample_config(), session=session)
  1078. with pytest.raises(ValueError, match="okx response payload is invalid"):
  1079. client.get_positions(symbol="BTC-USDT-SWAP")