test_okx_client.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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(300):
  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=302)
  470. assert len(candles) == 302
  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. @pytest.mark.parametrize(
  526. ("price", "metadata"),
  527. [
  528. (0, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  529. (-1, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  530. (25_000, InstrumentMeta(ct_val=0, lot_sz=1, min_sz=1)),
  531. (25_000, InstrumentMeta(ct_val=-0.01, lot_sz=1, min_sz=1)),
  532. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=0, min_sz=1)),
  533. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=-1, min_sz=1)),
  534. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=0)),
  535. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=-1)),
  536. ],
  537. )
  538. def test_build_contract_size_rejects_non_positive_inputs(price, metadata):
  539. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  540. build_contract_size(notional=250, price=price, metadata=metadata)
  541. @pytest.mark.parametrize(
  542. ("price", "metadata"),
  543. [
  544. (float("nan"), InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  545. (float("inf"), InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=1)),
  546. (25_000, InstrumentMeta(ct_val=float("nan"), lot_sz=1, min_sz=1)),
  547. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=float("inf"), min_sz=1)),
  548. (25_000, InstrumentMeta(ct_val=0.01, lot_sz=1, min_sz=float("-inf"))),
  549. ],
  550. )
  551. def test_build_contract_size_rejects_non_finite_inputs(price, metadata):
  552. with pytest.raises(ValueError, match="contract sizing inputs are invalid"):
  553. build_contract_size(notional=250, price=price, metadata=metadata)
  554. def test_market_order_fetches_latest_price_before_sizing():
  555. session = DummySession(
  556. [
  557. account_config_response(pos_mode="long_short_mode"),
  558. instrument_response(),
  559. ticker_response(last="25000"),
  560. leverage_response(),
  561. place_order_response(),
  562. ]
  563. )
  564. client = OkxClient(config=sample_config(), session=session)
  565. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  566. assert session.request_paths == [
  567. "/api/v5/account/config",
  568. "/api/v5/public/instruments",
  569. "/api/v5/market/ticker",
  570. "/api/v5/account/set-leverage",
  571. "/api/v5/trade/order",
  572. ]
  573. def test_fractional_margin_sizing_keeps_decimal_precision():
  574. session = DummySession(
  575. [
  576. account_config_response(pos_mode="long_short_mode"),
  577. instrument_response(),
  578. ticker_response(last="1"),
  579. leverage_response(),
  580. place_order_response(),
  581. ]
  582. )
  583. signal = TradeSignal(
  584. action="long",
  585. confidence=0.9,
  586. leverage=3,
  587. entry_price=None,
  588. take_profit_price=None,
  589. stop_loss_price=None,
  590. reason="x",
  591. )
  592. client = OkxClient(config=sample_config(), session=session)
  593. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=0.009)
  594. assert session.last_json_body is not None
  595. assert session.last_json_body["sz"] == "27"
  596. def test_place_order_fails_when_not_hedge_mode():
  597. session = DummySession(
  598. [
  599. account_config_response(pos_mode="net_mode"),
  600. ]
  601. )
  602. client = OkxClient(config=sample_config(), session=session)
  603. with pytest.raises(ValueError):
  604. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  605. assert session.request_paths == ["/api/v5/account/config"]
  606. def test_ensure_hedge_mode_rejects_malformed_config_payload():
  607. session = DummySession([malformed_account_config_response(pos_mode=None)])
  608. client = OkxClient(config=sample_config(), session=session)
  609. with pytest.raises(ValueError, match="okx response payload is invalid"):
  610. client.ensure_hedge_mode()
  611. def test_place_order_validates_size_before_setting_leverage():
  612. session = DummySession(
  613. [
  614. account_config_response(pos_mode="long_short_mode"),
  615. large_min_size_instrument_response(),
  616. ticker_response(last="25000"),
  617. ]
  618. )
  619. client = OkxClient(config=sample_config(), session=session)
  620. with pytest.raises(ValueError, match="contract size below minimum"):
  621. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  622. assert session.request_paths == [
  623. "/api/v5/account/config",
  624. "/api/v5/public/instruments",
  625. "/api/v5/market/ticker",
  626. ]
  627. def test_limit_short_order_uses_sell_and_short_pos_side():
  628. session = DummySession(
  629. [
  630. account_config_response(pos_mode="long_short_mode"),
  631. instrument_response(symbol="ETH-USDT-SWAP"),
  632. leverage_response(),
  633. place_order_response(),
  634. ]
  635. )
  636. client = OkxClient(config=sample_config(), session=session)
  637. client.place_order(symbol="ETH-USDT-SWAP", signal=limit_short_signal(), margin_usdt=100)
  638. order_request = session.last_json_body
  639. assert order_request is not None
  640. assert order_request["ordType"] == "limit"
  641. assert order_request["side"] == "sell"
  642. assert order_request["posSide"] == "short"
  643. assert order_request["px"] == "25000"
  644. assert session.request_bodies[2]["lever"] == "2"
  645. assert session.request_bodies[2]["mgnMode"] == "isolated"
  646. def test_flat_signal_returns_noop_without_order_submission():
  647. session = DummySession([])
  648. client = OkxClient(config=sample_config(), session=session)
  649. result = client.place_order(symbol="BTC-USDT-SWAP", signal=flat_signal(), margin_usdt=100)
  650. assert result.status == "noop"
  651. assert session.request_paths == []
  652. def test_place_order_sends_computed_sz_and_ignores_tp_sl_fields():
  653. session = DummySession(
  654. [
  655. account_config_response(pos_mode="long_short_mode"),
  656. instrument_response(),
  657. ticker_response(last="25000"),
  658. leverage_response(),
  659. place_order_response(),
  660. ]
  661. )
  662. client = OkxClient(config=sample_config(), session=session)
  663. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  664. order_request = session.last_json_body
  665. assert order_request is not None
  666. assert order_request["sz"] == "8"
  667. assert "tpTriggerPx" not in order_request
  668. assert "slTriggerPx" not in order_request
  669. def test_okx_error_payload_raises_value_error():
  670. session = DummySession([error_response(code="51000", msg="parameter error")])
  671. client = OkxClient(config=sample_config(), session=session)
  672. with pytest.raises(ValueError):
  673. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  674. def test_get_candles_rejects_non_finite_numeric_fields():
  675. session = DummySession([candles_with_non_finite_numeric_response()])
  676. client = OkxClient(config=sample_config(), session=session)
  677. with pytest.raises(ValueError, match="okx response payload is invalid"):
  678. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  679. def test_transport_failure_raises_stable_value_error():
  680. session = DummySession([RuntimeError("socket closed")])
  681. client = OkxClient(config=sample_config(), session=session)
  682. with pytest.raises(ValueError, match="okx transport error"):
  683. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  684. def test_invalid_json_raises_stable_value_error():
  685. session = DummySession([DummyResponse({}, json_error=ValueError("bad json"))])
  686. client = OkxClient(config=sample_config(), session=session)
  687. with pytest.raises(ValueError, match="okx response payload is invalid"):
  688. client.get_candles(symbol="BTC-USDT-SWAP", bar="1H", limit=20)
  689. def test_empty_positions_data_returns_empty_list():
  690. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": []})])
  691. client = OkxClient(config=sample_config(), session=session)
  692. assert client.get_positions(symbol="BTC-USDT-SWAP") == []
  693. def test_malformed_numeric_field_raises_stable_value_error():
  694. session = DummySession(
  695. [
  696. DummyResponse(
  697. {
  698. "code": "0",
  699. "msg": "",
  700. "data": [
  701. {
  702. "instId": "BTC-USDT-SWAP",
  703. "posSide": "long",
  704. "pos": "bad",
  705. "avgPx": "25000",
  706. }
  707. ],
  708. }
  709. )
  710. ]
  711. )
  712. client = OkxClient(config=sample_config(), session=session)
  713. with pytest.raises(ValueError, match="okx response payload is invalid"):
  714. client.get_positions(symbol="BTC-USDT-SWAP")
  715. def test_non_list_okx_data_raises_stable_value_error():
  716. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": {}})])
  717. client = OkxClient(config=sample_config(), session=session)
  718. with pytest.raises(ValueError, match="okx response payload is invalid"):
  719. client.get_positions(symbol="BTC-USDT-SWAP")
  720. def test_get_instrument_meta_rejects_non_finite_numeric_fields():
  721. session = DummySession([instrument_with_non_finite_numeric_response()])
  722. client = OkxClient(config=sample_config(), session=session)
  723. with pytest.raises(ValueError, match="okx response payload is invalid"):
  724. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  725. def test_get_last_price_rejects_non_finite_numeric_field():
  726. session = DummySession([ticker_with_non_finite_numeric_response()])
  727. client = OkxClient(config=sample_config(), session=session)
  728. with pytest.raises(ValueError, match="okx response payload is invalid"):
  729. client.get_last_price(symbol="BTC-USDT-SWAP")
  730. def test_get_last_price_rejects_mismatched_symbol():
  731. session = DummySession([DummyResponse({"code": "0", "msg": "", "data": [{"instId": "ETH-USDT-SWAP", "last": "25000"}]})])
  732. client = OkxClient(config=sample_config(), session=session)
  733. with pytest.raises(ValueError, match="okx response payload is invalid"):
  734. client.get_last_price(symbol="BTC-USDT-SWAP")
  735. def test_get_instrument_meta_rejects_mismatched_symbol():
  736. session = DummySession([instrument_with_wrong_symbol_response()])
  737. client = OkxClient(config=sample_config(), session=session)
  738. with pytest.raises(ValueError, match="okx response payload is invalid"):
  739. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  740. def test_get_instrument_meta_rejects_non_swap_type():
  741. session = DummySession([instrument_with_wrong_type_response()])
  742. client = OkxClient(config=sample_config(), session=session)
  743. with pytest.raises(ValueError, match="okx response payload is invalid"):
  744. client.get_instrument_meta(symbol="BTC-USDT-SWAP")
  745. def test_place_order_raises_when_order_id_is_missing():
  746. session = DummySession(
  747. [
  748. account_config_response(pos_mode="long_short_mode"),
  749. instrument_response(),
  750. ticker_response(last="25000"),
  751. leverage_response(),
  752. place_order_response_without_order_id(),
  753. ]
  754. )
  755. client = OkxClient(config=sample_config(), session=session)
  756. with pytest.raises(ValueError, match="okx response payload is invalid"):
  757. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=100)
  758. assert session.request_paths[-1] == "/api/v5/trade/order"
  759. def test_place_order_rejects_invalid_leverage_before_okx():
  760. session = DummySession([])
  761. signal = TradeSignal(
  762. action="long",
  763. confidence=0.9,
  764. leverage=4,
  765. entry_price=None,
  766. take_profit_price=None,
  767. stop_loss_price=None,
  768. reason="x",
  769. )
  770. client = OkxClient(config=sample_config(), session=session)
  771. with pytest.raises(ValueError, match="leverage is invalid"):
  772. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  773. assert session.request_paths == []
  774. def test_place_order_rejects_fractional_leverage_before_okx():
  775. session = DummySession([])
  776. signal = TradeSignal(
  777. action="long",
  778. confidence=0.9,
  779. leverage=2.5,
  780. entry_price=None,
  781. take_profit_price=None,
  782. stop_loss_price=None,
  783. reason="x",
  784. )
  785. client = OkxClient(config=sample_config(), session=session)
  786. with pytest.raises(ValueError, match="leverage is invalid"):
  787. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  788. assert session.request_paths == []
  789. def test_place_order_rejects_boolean_leverage_before_okx():
  790. session = DummySession([])
  791. signal = TradeSignal(
  792. action="long",
  793. confidence=0.9,
  794. leverage=True,
  795. entry_price=None,
  796. take_profit_price=None,
  797. stop_loss_price=None,
  798. reason="x",
  799. )
  800. client = OkxClient(config=sample_config(), session=session)
  801. with pytest.raises(ValueError, match="leverage is invalid"):
  802. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  803. assert session.request_paths == []
  804. @pytest.mark.parametrize("margin_usdt", [0, -1, float("nan"), float("inf")])
  805. def test_place_order_rejects_invalid_margin_before_okx(margin_usdt):
  806. session = DummySession([])
  807. client = OkxClient(config=sample_config(), session=session)
  808. with pytest.raises(ValueError, match="margin_usdt is invalid"):
  809. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=margin_usdt)
  810. assert session.request_paths == []
  811. def test_place_order_rejects_boolean_margin_before_okx():
  812. session = DummySession([])
  813. client = OkxClient(config=sample_config(), session=session)
  814. with pytest.raises(ValueError, match="margin_usdt is invalid"):
  815. client.place_order(symbol="BTC-USDT-SWAP", signal=market_long_signal(), margin_usdt=True)
  816. assert session.request_paths == []
  817. @pytest.mark.parametrize(
  818. ("symbol", "leverage", "pos_side", "expected_message"),
  819. [
  820. ("BTC-USDT", 2, "long", "swap instrument is required"),
  821. ("BTC-USDT-SWAP", 4, "long", "leverage is invalid"),
  822. ("BTC-USDT-SWAP", 2.5, "long", "leverage is invalid"),
  823. ("BTC-USDT-SWAP", 2, "net", "pos_side is invalid"),
  824. ],
  825. )
  826. def test_set_leverage_validates_public_boundary_inputs(symbol, leverage, pos_side, expected_message):
  827. session = DummySession([])
  828. client = OkxClient(config=sample_config(), session=session)
  829. with pytest.raises(ValueError, match=expected_message):
  830. client.set_leverage(symbol=symbol, leverage=leverage, pos_side=pos_side)
  831. assert session.request_paths == []
  832. def test_place_order_rejects_unknown_action_before_okx():
  833. session = DummySession([])
  834. signal = TradeSignal(
  835. action="hold",
  836. confidence=0.9,
  837. leverage=2,
  838. entry_price=None,
  839. take_profit_price=None,
  840. stop_loss_price=None,
  841. reason="x",
  842. )
  843. client = OkxClient(config=sample_config(), session=session)
  844. with pytest.raises(ValueError, match="action is invalid"):
  845. client.place_order(symbol="BTC-USDT-SWAP", signal=signal, margin_usdt=100)
  846. assert session.request_paths == []
  847. def test_get_positions_returns_normalized_positions():
  848. session = DummySession([positions_response()])
  849. client = OkxClient(config=sample_config(), session=session)
  850. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  851. assert positions[0].symbol == "BTC-USDT-SWAP"
  852. assert positions[0].pos_side == "long"
  853. assert positions[0].size == 8.0
  854. assert positions[0].avg_price == 25000.0
  855. def test_get_positions_filters_zero_size_rows():
  856. session = DummySession([positions_with_zero_size_response()])
  857. client = OkxClient(config=sample_config(), session=session)
  858. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  859. assert len(positions) == 1
  860. assert positions[0].pos_side == "short"
  861. assert positions[0].size == 3.0
  862. def test_get_positions_ignores_malformed_fields_on_zero_size_rows():
  863. session = DummySession([positions_with_zero_size_malformed_avg_price_response()])
  864. client = OkxClient(config=sample_config(), session=session)
  865. positions = client.get_positions(symbol="BTC-USDT-SWAP")
  866. assert len(positions) == 1
  867. assert positions[0].pos_side == "short"
  868. assert positions[0].avg_price == 24900.0
  869. def test_get_positions_rejects_non_string_inst_id_and_pos_side():
  870. session = DummySession([positions_with_non_string_identity_response()])
  871. client = OkxClient(config=sample_config(), session=session)
  872. with pytest.raises(ValueError, match="okx response payload is invalid"):
  873. client.get_positions(symbol="BTC-USDT-SWAP")
  874. def test_get_positions_rejects_non_finite_numeric_fields():
  875. session = DummySession([positions_with_non_finite_numeric_response()])
  876. client = OkxClient(config=sample_config(), session=session)
  877. with pytest.raises(ValueError, match="okx response payload is invalid"):
  878. client.get_positions(symbol="BTC-USDT-SWAP")
  879. def test_get_positions_rejects_mismatched_symbol():
  880. session = DummySession([positions_with_wrong_symbol_response()])
  881. client = OkxClient(config=sample_config(), session=session)
  882. with pytest.raises(ValueError, match="okx response payload is invalid"):
  883. client.get_positions(symbol="BTC-USDT-SWAP")
  884. def test_get_positions_rejects_invalid_pos_side():
  885. session = DummySession([positions_with_invalid_pos_side_response()])
  886. client = OkxClient(config=sample_config(), session=session)
  887. with pytest.raises(ValueError, match="okx response payload is invalid"):
  888. client.get_positions(symbol="BTC-USDT-SWAP")