ccxt-ir 4.3.46.0.2__py2.py3-none-any.whl → 4.5.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (528) hide show
  1. ccxt/__init__.py +39 -35
  2. ccxt/abantether.py +9 -9
  3. ccxt/abstract/alpaca.py +4 -0
  4. ccxt/abstract/apex.py +31 -0
  5. ccxt/abstract/bigone.py +1 -1
  6. ccxt/abstract/binance.py +106 -48
  7. ccxt/abstract/binancecoinm.py +106 -48
  8. ccxt/abstract/binanceus.py +141 -83
  9. ccxt/abstract/binanceusdm.py +106 -48
  10. ccxt/abstract/bingx.py +50 -1
  11. ccxt/abstract/bitbank.py +5 -0
  12. ccxt/abstract/bitfinex.py +136 -65
  13. ccxt/abstract/bitflyer.py +1 -0
  14. ccxt/abstract/bitget.py +67 -0
  15. ccxt/abstract/bitmart.py +19 -1
  16. ccxt/abstract/bitopro.py +1 -0
  17. ccxt/abstract/bitrue.py +68 -68
  18. ccxt/abstract/bitstamp.py +1 -0
  19. ccxt/abstract/blofin.py +30 -0
  20. ccxt/abstract/btcbox.py +2 -0
  21. ccxt/abstract/bybit.py +28 -13
  22. ccxt/abstract/cex.py +28 -29
  23. ccxt/abstract/coinbaseexchange.py +1 -0
  24. ccxt/abstract/coinbaseinternational.py +1 -1
  25. ccxt/abstract/cryptocom.py +16 -0
  26. ccxt/abstract/cryptomus.py +20 -0
  27. ccxt/abstract/defx.py +69 -0
  28. ccxt/abstract/deribit.py +1 -0
  29. ccxt/abstract/derive.py +117 -0
  30. ccxt/abstract/digifinex.py +1 -0
  31. ccxt/abstract/ellipx.py +25 -0
  32. ccxt/abstract/foxbit.py +26 -0
  33. ccxt/abstract/gate.py +19 -0
  34. ccxt/abstract/gateio.py +19 -0
  35. ccxt/abstract/gemini.py +1 -0
  36. ccxt/abstract/hibachi.py +26 -0
  37. ccxt/abstract/hyperliquid.py +1 -1
  38. ccxt/abstract/independentreserve.py +6 -0
  39. ccxt/abstract/kraken.py +1 -0
  40. ccxt/abstract/krakenfutures.py +4 -0
  41. ccxt/abstract/kucoin.py +10 -0
  42. ccxt/abstract/kucoinfutures.py +18 -0
  43. ccxt/abstract/lbank.py +2 -1
  44. ccxt/abstract/luno.py +1 -0
  45. ccxt/abstract/mexc.py +2 -0
  46. ccxt/abstract/modetrade.py +119 -0
  47. ccxt/abstract/myokx.py +349 -0
  48. ccxt/abstract/oceanex.py +5 -0
  49. ccxt/abstract/okx.py +25 -0
  50. ccxt/abstract/okxus.py +349 -0
  51. ccxt/abstract/onetrading.py +0 -12
  52. ccxt/abstract/paradex.py +23 -0
  53. ccxt/abstract/phemex.py +2 -0
  54. ccxt/abstract/poloniex.py +36 -0
  55. ccxt/abstract/tradeogre.py +3 -1
  56. ccxt/abstract/upbit.py +51 -34
  57. ccxt/abstract/whitebit.py +16 -0
  58. ccxt/abstract/woo.py +64 -6
  59. ccxt/abstract/xt.py +10 -5
  60. ccxt/afratether.py +7 -7
  61. ccxt/alpaca.py +828 -51
  62. ccxt/apex.py +1875 -0
  63. ccxt/arzinja.py +7 -7
  64. ccxt/arzplus.py +9 -9
  65. ccxt/ascendex.py +501 -306
  66. ccxt/async_support/__init__.py +39 -35
  67. ccxt/async_support/abantether.py +10 -10
  68. ccxt/async_support/afratether.py +9 -9
  69. ccxt/async_support/alpaca.py +828 -51
  70. ccxt/async_support/apex.py +1875 -0
  71. ccxt/async_support/arzinja.py +10 -10
  72. ccxt/async_support/arzplus.py +12 -12
  73. ccxt/async_support/ascendex.py +502 -306
  74. ccxt/async_support/base/exchange.py +303 -89
  75. ccxt/async_support/base/ws/cache.py +9 -3
  76. ccxt/async_support/base/ws/client.py +173 -38
  77. ccxt/async_support/base/ws/future.py +25 -37
  78. ccxt/async_support/bequant.py +5 -3
  79. ccxt/async_support/bigone.py +279 -144
  80. ccxt/async_support/binance.py +2347 -1158
  81. ccxt/async_support/binancecoinm.py +9 -3
  82. ccxt/async_support/binanceus.py +17 -3
  83. ccxt/async_support/binanceusdm.py +9 -4
  84. ccxt/async_support/bingx.py +2962 -920
  85. ccxt/async_support/bit2c.py +147 -27
  86. ccxt/async_support/bitbank.py +151 -23
  87. ccxt/async_support/bitbns.py +104 -30
  88. ccxt/async_support/bitfinex.py +3291 -1113
  89. ccxt/async_support/bitflyer.py +202 -27
  90. ccxt/async_support/bitget.py +3683 -1538
  91. ccxt/async_support/bithumb.py +195 -38
  92. ccxt/async_support/bitimen.py +12 -12
  93. ccxt/async_support/bitir.py +38 -38
  94. ccxt/async_support/bitmart.py +1288 -350
  95. ccxt/async_support/bitmex.py +260 -75
  96. ccxt/async_support/bitopro.py +262 -62
  97. ccxt/async_support/bitpin.py +17 -16
  98. ccxt/async_support/bitrue.py +459 -290
  99. ccxt/async_support/bitso.py +199 -54
  100. ccxt/async_support/bitstamp.py +230 -96
  101. ccxt/async_support/bitteam.py +167 -25
  102. ccxt/async_support/{huobijp.py → bittrade.py} +158 -30
  103. ccxt/async_support/bitvavo.py +213 -49
  104. ccxt/async_support/blockchaincom.py +160 -46
  105. ccxt/async_support/blofin.py +502 -120
  106. ccxt/async_support/btcalpha.py +169 -31
  107. ccxt/async_support/btcbox.py +292 -23
  108. ccxt/async_support/btcmarkets.py +211 -58
  109. ccxt/async_support/btcturk.py +161 -38
  110. ccxt/async_support/bybit.py +1775 -1030
  111. ccxt/async_support/cex.py +1440 -1303
  112. ccxt/async_support/coinbase.py +724 -212
  113. ccxt/async_support/coinbaseadvanced.py +2 -1
  114. ccxt/async_support/coinbaseexchange.py +388 -89
  115. ccxt/async_support/coinbaseinternational.py +412 -57
  116. ccxt/async_support/coincatch.py +177 -78
  117. ccxt/async_support/coincheck.py +135 -19
  118. ccxt/async_support/coinex.py +606 -232
  119. ccxt/async_support/coinmate.py +189 -63
  120. ccxt/async_support/coinmetro.py +195 -54
  121. ccxt/async_support/coinone.py +158 -51
  122. ccxt/async_support/coinsph.py +336 -61
  123. ccxt/async_support/coinspot.py +151 -52
  124. ccxt/async_support/cryptocom.py +661 -111
  125. ccxt/async_support/cryptomus.py +1137 -0
  126. ccxt/async_support/defx.py +2071 -0
  127. ccxt/async_support/delta.py +299 -99
  128. ccxt/async_support/deribit.py +348 -126
  129. ccxt/async_support/derive.py +2572 -0
  130. ccxt/async_support/digifinex.py +430 -214
  131. ccxt/async_support/ellipx.py +2029 -0
  132. ccxt/async_support/eterex.py +10 -10
  133. ccxt/async_support/excoino.py +31 -31
  134. ccxt/async_support/exir.py +14 -14
  135. ccxt/async_support/exmo.py +344 -131
  136. ccxt/async_support/exnovin.py +10 -10
  137. ccxt/async_support/farhadexchange.py +12 -12
  138. ccxt/async_support/fmfwio.py +2 -1
  139. ccxt/async_support/foxbit.py +1935 -0
  140. ccxt/async_support/gate.py +1351 -529
  141. ccxt/async_support/gateio.py +2 -1
  142. ccxt/async_support/gemini.py +144 -39
  143. ccxt/async_support/hashkey.py +152 -109
  144. ccxt/async_support/hibachi.py +2080 -0
  145. ccxt/async_support/hitbtc.py +395 -167
  146. ccxt/async_support/hitobit.py +12 -12
  147. ccxt/async_support/hollaex.py +307 -119
  148. ccxt/async_support/htx.py +851 -383
  149. ccxt/async_support/huobi.py +2 -1
  150. ccxt/async_support/hyperliquid.py +1848 -536
  151. ccxt/async_support/independentreserve.py +288 -15
  152. ccxt/async_support/indodax.py +190 -33
  153. ccxt/async_support/jibitex.py +12 -12
  154. ccxt/async_support/kraken.py +795 -351
  155. ccxt/async_support/krakenfutures.py +214 -62
  156. ccxt/async_support/kucoin.py +715 -396
  157. ccxt/async_support/kucoinfutures.py +652 -89
  158. ccxt/async_support/latoken.py +217 -113
  159. ccxt/async_support/lbank.py +425 -97
  160. ccxt/async_support/luno.py +382 -35
  161. ccxt/async_support/mercado.py +113 -6
  162. ccxt/async_support/mexc.py +874 -437
  163. ccxt/async_support/modetrade.py +2818 -0
  164. ccxt/async_support/myokx.py +54 -0
  165. ccxt/async_support/ndax.py +221 -64
  166. ccxt/async_support/nobitex.py +31 -37
  167. ccxt/async_support/novadax.py +190 -34
  168. ccxt/async_support/oceanex.py +217 -28
  169. ccxt/async_support/okcoin.py +253 -145
  170. ccxt/async_support/okexchange.py +11 -11
  171. ccxt/async_support/okx.py +1088 -351
  172. ccxt/async_support/okxus.py +54 -0
  173. ccxt/async_support/ompfinex.py +25 -24
  174. ccxt/async_support/onetrading.py +213 -392
  175. ccxt/async_support/oxfun.py +245 -166
  176. ccxt/async_support/p2b.py +151 -29
  177. ccxt/async_support/paradex.py +562 -49
  178. ccxt/async_support/paymium.py +82 -19
  179. ccxt/async_support/phemex.py +713 -172
  180. ccxt/async_support/poloniex.py +1602 -283
  181. ccxt/async_support/probit.py +224 -95
  182. ccxt/async_support/ramzinex.py +30 -27
  183. ccxt/async_support/sarmayex.py +9 -9
  184. ccxt/async_support/sarrafex.py +13 -13
  185. ccxt/async_support/tabdeal.py +14 -13
  186. ccxt/async_support/tetherland.py +9 -9
  187. ccxt/async_support/timex.py +210 -51
  188. ccxt/async_support/tokocrypto.py +167 -47
  189. ccxt/async_support/tradeogre.py +266 -31
  190. ccxt/async_support/twox.py +9 -9
  191. ccxt/async_support/ubitex.py +12 -12
  192. ccxt/async_support/upbit.py +568 -165
  193. ccxt/async_support/vertex.py +160 -32
  194. ccxt/async_support/wallex.py +12 -12
  195. ccxt/async_support/wavesexchange.py +165 -30
  196. ccxt/async_support/whitebit.py +975 -127
  197. ccxt/async_support/woo.py +1918 -1016
  198. ccxt/async_support/woofipro.py +433 -141
  199. ccxt/async_support/xt.py +649 -193
  200. ccxt/async_support/yobit.py +195 -70
  201. ccxt/async_support/zaif.py +91 -15
  202. ccxt/async_support/zonda.py +151 -36
  203. ccxt/base/decimal_to_precision.py +14 -10
  204. ccxt/base/errors.py +49 -18
  205. ccxt/base/exchange.py +1556 -450
  206. ccxt/base/precise.py +10 -0
  207. ccxt/base/types.py +114 -6
  208. ccxt/bequant.py +5 -3
  209. ccxt/bigone.py +279 -144
  210. ccxt/binance.py +2347 -1158
  211. ccxt/binancecoinm.py +9 -3
  212. ccxt/binanceus.py +17 -3
  213. ccxt/binanceusdm.py +9 -4
  214. ccxt/bingx.py +2962 -920
  215. ccxt/bit2c.py +147 -27
  216. ccxt/bitbank.py +151 -23
  217. ccxt/bitbns.py +104 -30
  218. ccxt/bitfinex.py +3290 -1113
  219. ccxt/bitflyer.py +202 -27
  220. ccxt/bitget.py +3683 -1538
  221. ccxt/bithumb.py +194 -38
  222. ccxt/bitimen.py +9 -9
  223. ccxt/bitir.py +35 -35
  224. ccxt/bitmart.py +1288 -350
  225. ccxt/bitmex.py +260 -75
  226. ccxt/bitopro.py +262 -62
  227. ccxt/bitpin.py +15 -14
  228. ccxt/bitrue.py +459 -290
  229. ccxt/bitso.py +199 -54
  230. ccxt/bitstamp.py +230 -96
  231. ccxt/bitteam.py +167 -25
  232. ccxt/{huobijp.py → bittrade.py} +158 -30
  233. ccxt/bitvavo.py +213 -49
  234. ccxt/blockchaincom.py +160 -46
  235. ccxt/blofin.py +502 -120
  236. ccxt/btcalpha.py +169 -31
  237. ccxt/btcbox.py +291 -23
  238. ccxt/btcmarkets.py +211 -58
  239. ccxt/btcturk.py +161 -38
  240. ccxt/bybit.py +1775 -1030
  241. ccxt/cex.py +1439 -1303
  242. ccxt/coinbase.py +724 -212
  243. ccxt/coinbaseadvanced.py +2 -1
  244. ccxt/coinbaseexchange.py +388 -89
  245. ccxt/coinbaseinternational.py +412 -57
  246. ccxt/coincatch.py +177 -78
  247. ccxt/coincheck.py +135 -19
  248. ccxt/coinex.py +606 -232
  249. ccxt/coinmate.py +189 -63
  250. ccxt/coinmetro.py +194 -54
  251. ccxt/coinone.py +158 -51
  252. ccxt/coinsph.py +336 -61
  253. ccxt/coinspot.py +151 -52
  254. ccxt/cryptocom.py +661 -111
  255. ccxt/cryptomus.py +1137 -0
  256. ccxt/defx.py +2070 -0
  257. ccxt/delta.py +299 -99
  258. ccxt/deribit.py +348 -126
  259. ccxt/derive.py +2571 -0
  260. ccxt/digifinex.py +430 -214
  261. ccxt/ellipx.py +2029 -0
  262. ccxt/eterex.py +7 -7
  263. ccxt/excoino.py +29 -29
  264. ccxt/exir.py +11 -11
  265. ccxt/exmo.py +343 -131
  266. ccxt/exnovin.py +8 -8
  267. ccxt/farhadexchange.py +10 -10
  268. ccxt/fmfwio.py +2 -1
  269. ccxt/foxbit.py +1935 -0
  270. ccxt/gate.py +1351 -529
  271. ccxt/gateio.py +2 -1
  272. ccxt/gemini.py +144 -39
  273. ccxt/hashkey.py +152 -109
  274. ccxt/hibachi.py +2079 -0
  275. ccxt/hitbtc.py +395 -167
  276. ccxt/hitobit.py +9 -9
  277. ccxt/hollaex.py +307 -119
  278. ccxt/htx.py +851 -383
  279. ccxt/huobi.py +2 -1
  280. ccxt/hyperliquid.py +1848 -536
  281. ccxt/independentreserve.py +287 -15
  282. ccxt/indodax.py +190 -33
  283. ccxt/jibitex.py +9 -9
  284. ccxt/kraken.py +794 -351
  285. ccxt/krakenfutures.py +214 -62
  286. ccxt/kucoin.py +715 -396
  287. ccxt/kucoinfutures.py +652 -89
  288. ccxt/latoken.py +217 -113
  289. ccxt/lbank.py +425 -97
  290. ccxt/luno.py +382 -35
  291. ccxt/mercado.py +113 -6
  292. ccxt/mexc.py +873 -437
  293. ccxt/modetrade.py +2818 -0
  294. ccxt/myokx.py +54 -0
  295. ccxt/ndax.py +221 -64
  296. ccxt/nobitex.py +29 -35
  297. ccxt/novadax.py +190 -34
  298. ccxt/oceanex.py +217 -28
  299. ccxt/okcoin.py +253 -145
  300. ccxt/okexchange.py +9 -9
  301. ccxt/okx.py +1088 -351
  302. ccxt/okxus.py +54 -0
  303. ccxt/ompfinex.py +22 -21
  304. ccxt/onetrading.py +213 -392
  305. ccxt/oxfun.py +245 -166
  306. ccxt/p2b.py +151 -29
  307. ccxt/paradex.py +562 -49
  308. ccxt/paymium.py +82 -19
  309. ccxt/phemex.py +712 -172
  310. ccxt/poloniex.py +1601 -283
  311. ccxt/pro/__init__.py +76 -17
  312. ccxt/pro/alpaca.py +21 -6
  313. ccxt/pro/apex.py +984 -0
  314. ccxt/pro/ascendex.py +58 -10
  315. ccxt/pro/bequant.py +6 -1
  316. ccxt/pro/binance.py +728 -156
  317. ccxt/pro/binancecoinm.py +6 -2
  318. ccxt/pro/binanceus.py +8 -4
  319. ccxt/pro/binanceusdm.py +7 -2
  320. ccxt/pro/bingx.py +333 -142
  321. ccxt/pro/bitfinex.py +727 -262
  322. ccxt/pro/bitget.py +570 -79
  323. ccxt/pro/bithumb.py +20 -6
  324. ccxt/pro/bitmart.py +216 -87
  325. ccxt/pro/bitmex.py +47 -9
  326. ccxt/pro/bitopro.py +26 -14
  327. ccxt/pro/bitrue.py +22 -22
  328. ccxt/pro/bitstamp.py +54 -21
  329. ccxt/pro/{huobijp.py → bittrade.py} +7 -6
  330. ccxt/pro/bitvavo.py +191 -67
  331. ccxt/pro/blockchaincom.py +21 -8
  332. ccxt/pro/blofin.py +9 -1
  333. ccxt/pro/bybit.py +632 -245
  334. ccxt/pro/cex.py +59 -24
  335. ccxt/pro/coinbase.py +102 -73
  336. ccxt/pro/coinbaseadvanced.py +2 -1
  337. ccxt/pro/coinbaseexchange.py +8 -8
  338. ccxt/pro/coinbaseinternational.py +181 -25
  339. ccxt/pro/coincatch.py +6 -7
  340. ccxt/pro/coincheck.py +11 -6
  341. ccxt/pro/coinex.py +967 -665
  342. ccxt/pro/coinone.py +16 -9
  343. ccxt/pro/cryptocom.py +448 -45
  344. ccxt/pro/defx.py +831 -0
  345. ccxt/pro/deribit.py +150 -14
  346. ccxt/pro/derive.py +704 -0
  347. ccxt/pro/exmo.py +239 -6
  348. ccxt/pro/gate.py +623 -65
  349. ccxt/pro/gateio.py +2 -1
  350. ccxt/pro/gemini.py +27 -11
  351. ccxt/pro/hashkey.py +2 -2
  352. ccxt/pro/hitbtc.py +196 -91
  353. ccxt/pro/hollaex.py +23 -7
  354. ccxt/pro/htx.py +51 -14
  355. ccxt/pro/huobi.py +2 -1
  356. ccxt/pro/hyperliquid.py +591 -27
  357. ccxt/pro/independentreserve.py +9 -6
  358. ccxt/pro/kraken.py +640 -320
  359. ccxt/pro/krakenfutures.py +62 -35
  360. ccxt/pro/kucoin.py +267 -46
  361. ccxt/pro/kucoinfutures.py +165 -21
  362. ccxt/pro/lbank.py +102 -21
  363. ccxt/pro/luno.py +12 -8
  364. ccxt/pro/mexc.py +877 -111
  365. ccxt/pro/modetrade.py +1271 -0
  366. ccxt/pro/myokx.py +38 -0
  367. ccxt/pro/ndax.py +15 -2
  368. ccxt/pro/okcoin.py +23 -4
  369. ccxt/pro/okx.py +573 -98
  370. ccxt/pro/okxus.py +38 -0
  371. ccxt/pro/onetrading.py +30 -13
  372. ccxt/pro/oxfun.py +131 -27
  373. ccxt/pro/p2b.py +88 -22
  374. ccxt/pro/paradex.py +3 -3
  375. ccxt/pro/phemex.py +75 -21
  376. ccxt/pro/poloniex.py +124 -41
  377. ccxt/pro/probit.py +87 -80
  378. ccxt/pro/tradeogre.py +272 -0
  379. ccxt/pro/upbit.py +152 -12
  380. ccxt/pro/vertex.py +8 -3
  381. ccxt/pro/whitebit.py +58 -5
  382. ccxt/pro/woo.py +228 -37
  383. ccxt/pro/woofipro.py +106 -18
  384. ccxt/pro/xt.py +111 -5
  385. ccxt/probit.py +224 -95
  386. ccxt/protobuf/__init__.py +0 -0
  387. ccxt/protobuf/mexc/PrivateAccountV3Api_pb2.py +37 -0
  388. ccxt/protobuf/mexc/PrivateDealsV3Api_pb2.py +37 -0
  389. ccxt/protobuf/mexc/PrivateOrdersV3Api_pb2.py +37 -0
  390. ccxt/protobuf/mexc/PublicAggreBookTickerV3Api_pb2.py +37 -0
  391. ccxt/protobuf/mexc/PublicAggreDealsV3Api_pb2.py +39 -0
  392. ccxt/protobuf/mexc/PublicAggreDepthsV3Api_pb2.py +39 -0
  393. ccxt/protobuf/mexc/PublicBookTickerBatchV3Api_pb2.py +38 -0
  394. ccxt/protobuf/mexc/PublicBookTickerV3Api_pb2.py +37 -0
  395. ccxt/protobuf/mexc/PublicDealsV3Api_pb2.py +39 -0
  396. ccxt/protobuf/mexc/PublicIncreaseDepthsBatchV3Api_pb2.py +38 -0
  397. ccxt/protobuf/mexc/PublicIncreaseDepthsV3Api_pb2.py +39 -0
  398. ccxt/protobuf/mexc/PublicLimitDepthsV3Api_pb2.py +39 -0
  399. ccxt/protobuf/mexc/PublicMiniTickerV3Api_pb2.py +37 -0
  400. ccxt/protobuf/mexc/PublicMiniTickersV3Api_pb2.py +38 -0
  401. ccxt/protobuf/mexc/PublicSpotKlineV3Api_pb2.py +37 -0
  402. ccxt/protobuf/mexc/PushDataV3ApiWrapper_pb2.py +52 -0
  403. ccxt/protobuf/mexc/__init__.py +0 -0
  404. ccxt/ramzinex.py +28 -25
  405. ccxt/sarmayex.py +7 -7
  406. ccxt/sarrafex.py +10 -10
  407. ccxt/static_dependencies/__init__.py +1 -1
  408. ccxt/static_dependencies/lark/py.typed +0 -0
  409. ccxt/static_dependencies/marshmallow/py.typed +0 -0
  410. ccxt/static_dependencies/marshmallow_dataclass/py.typed +0 -0
  411. ccxt/static_dependencies/marshmallow_oneofschema/py.typed +0 -0
  412. ccxt/tabdeal.py +12 -11
  413. ccxt/test/tests_async.py +261 -57
  414. ccxt/test/tests_helpers.py +1 -3
  415. ccxt/test/tests_init.py +4 -3
  416. ccxt/test/tests_sync.py +261 -57
  417. ccxt/tetherland.py +7 -7
  418. ccxt/timex.py +210 -51
  419. ccxt/tokocrypto.py +167 -47
  420. ccxt/tradeogre.py +266 -31
  421. ccxt/twox.py +7 -7
  422. ccxt/ubitex.py +9 -9
  423. ccxt/upbit.py +568 -165
  424. ccxt/vertex.py +160 -32
  425. ccxt/wallex.py +9 -9
  426. ccxt/wavesexchange.py +165 -30
  427. ccxt/whitebit.py +975 -127
  428. ccxt/woo.py +1917 -1016
  429. ccxt/woofipro.py +432 -141
  430. ccxt/xt.py +649 -193
  431. ccxt/yobit.py +194 -70
  432. ccxt/zaif.py +91 -15
  433. ccxt/zonda.py +151 -36
  434. {ccxt_ir-4.3.46.0.2.dist-info → ccxt_ir-4.5.0.dist-info}/METADATA +225 -73
  435. ccxt_ir-4.5.0.dist-info/RECORD +743 -0
  436. {ccxt_ir-4.3.46.0.2.dist-info → ccxt_ir-4.5.0.dist-info}/WHEEL +1 -1
  437. ccxt/abstract/ace.py +0 -15
  438. ccxt/abstract/bitbay.py +0 -53
  439. ccxt/abstract/bitcoincom.py +0 -115
  440. ccxt/abstract/bitfinex2.py +0 -139
  441. ccxt/abstract/bitpanda.py +0 -35
  442. ccxt/abstract/bl3p.py +0 -19
  443. ccxt/abstract/coinlist.py +0 -54
  444. ccxt/abstract/currencycom.py +0 -68
  445. ccxt/abstract/hitbtc3.py +0 -115
  446. ccxt/abstract/idex.py +0 -26
  447. ccxt/abstract/kuna.py +0 -182
  448. ccxt/abstract/lykke.py +0 -29
  449. ccxt/abstract/poloniexfutures.py +0 -48
  450. ccxt/abstract/wazirx.py +0 -30
  451. ccxt/ace.py +0 -1012
  452. ccxt/async_support/ace.py +0 -1012
  453. ccxt/async_support/base/ws/aiohttp_client.py +0 -125
  454. ccxt/async_support/base/ws/fast_client.py +0 -96
  455. ccxt/async_support/bitbay.py +0 -17
  456. ccxt/async_support/bitcoincom.py +0 -17
  457. ccxt/async_support/bitfinex2.py +0 -3552
  458. ccxt/async_support/bitpanda.py +0 -16
  459. ccxt/async_support/bl3p.py +0 -485
  460. ccxt/async_support/coinlist.py +0 -2243
  461. ccxt/async_support/currencycom.py +0 -1950
  462. ccxt/async_support/hitbtc3.py +0 -16
  463. ccxt/async_support/idex.py +0 -1766
  464. ccxt/async_support/kuna.py +0 -1841
  465. ccxt/async_support/lykke.py +0 -1270
  466. ccxt/async_support/poloniexfutures.py +0 -1717
  467. ccxt/async_support/wazirx.py +0 -1224
  468. ccxt/bitbay.py +0 -17
  469. ccxt/bitcoincom.py +0 -17
  470. ccxt/bitfinex2.py +0 -3552
  471. ccxt/bitpanda.py +0 -16
  472. ccxt/bl3p.py +0 -485
  473. ccxt/coinlist.py +0 -2243
  474. ccxt/currencycom.py +0 -1950
  475. ccxt/hitbtc3.py +0 -16
  476. ccxt/idex.py +0 -1766
  477. ccxt/kuna.py +0 -1841
  478. ccxt/lykke.py +0 -1270
  479. ccxt/poloniexfutures.py +0 -1717
  480. ccxt/pro/bitcoincom.py +0 -34
  481. ccxt/pro/bitfinex2.py +0 -1083
  482. ccxt/pro/bitpanda.py +0 -15
  483. ccxt/pro/currencycom.py +0 -536
  484. ccxt/pro/idex.py +0 -672
  485. ccxt/pro/poloniexfutures.py +0 -990
  486. ccxt/pro/wazirx.py +0 -749
  487. ccxt/test/base/__init__.py +0 -29
  488. ccxt/test/base/test_account.py +0 -26
  489. ccxt/test/base/test_balance.py +0 -56
  490. ccxt/test/base/test_borrow_interest.py +0 -35
  491. ccxt/test/base/test_borrow_rate.py +0 -32
  492. ccxt/test/base/test_calculate_fee.py +0 -51
  493. ccxt/test/base/test_crypto.py +0 -127
  494. ccxt/test/base/test_currency.py +0 -76
  495. ccxt/test/base/test_datetime.py +0 -109
  496. ccxt/test/base/test_decimal_to_precision.py +0 -392
  497. ccxt/test/base/test_deep_extend.py +0 -68
  498. ccxt/test/base/test_deposit_withdrawal.py +0 -50
  499. ccxt/test/base/test_exchange_datetime_functions.py +0 -76
  500. ccxt/test/base/test_funding_rate_history.py +0 -29
  501. ccxt/test/base/test_last_price.py +0 -31
  502. ccxt/test/base/test_ledger_entry.py +0 -45
  503. ccxt/test/base/test_ledger_item.py +0 -48
  504. ccxt/test/base/test_leverage_tier.py +0 -33
  505. ccxt/test/base/test_liquidation.py +0 -50
  506. ccxt/test/base/test_margin_mode.py +0 -24
  507. ccxt/test/base/test_margin_modification.py +0 -35
  508. ccxt/test/base/test_market.py +0 -193
  509. ccxt/test/base/test_number.py +0 -411
  510. ccxt/test/base/test_ohlcv.py +0 -33
  511. ccxt/test/base/test_open_interest.py +0 -32
  512. ccxt/test/base/test_order.py +0 -64
  513. ccxt/test/base/test_order_book.py +0 -69
  514. ccxt/test/base/test_position.py +0 -60
  515. ccxt/test/base/test_shared_methods.py +0 -353
  516. ccxt/test/base/test_status.py +0 -24
  517. ccxt/test/base/test_throttle.py +0 -126
  518. ccxt/test/base/test_ticker.py +0 -92
  519. ccxt/test/base/test_trade.py +0 -47
  520. ccxt/test/base/test_trading_fee.py +0 -26
  521. ccxt/test/base/test_transaction.py +0 -39
  522. ccxt/test/test_async.py +0 -1649
  523. ccxt/test/test_sync.py +0 -1648
  524. ccxt/wazirx.py +0 -1224
  525. ccxt_ir-4.3.46.0.2.dist-info/RECORD +0 -772
  526. /ccxt/abstract/{huobijp.py → bittrade.py} +0 -0
  527. {ccxt_ir-4.3.46.0.2.dist-info → ccxt_ir-4.5.0.dist-info/licenses}/LICENSE.txt +0 -0
  528. {ccxt_ir-4.3.46.0.2.dist-info → ccxt_ir-4.5.0.dist-info}/top_level.txt +0 -0
ccxt/cex.py CHANGED
@@ -6,75 +6,101 @@
6
6
  from ccxt.base.exchange import Exchange
7
7
  from ccxt.abstract.cex import ImplicitAPI
8
8
  import hashlib
9
- import json
10
- from ccxt.base.types import Balances, Currencies, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFees
9
+ from ccxt.base.types import Account, Any, Balances, Currencies, Currency, DepositAddress, Int, LedgerEntry, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFeeInterface, TradingFees, Transaction, TransferEntry
11
10
  from typing import List
12
11
  from ccxt.base.errors import ExchangeError
13
12
  from ccxt.base.errors import AuthenticationError
13
+ from ccxt.base.errors import PermissionDenied
14
14
  from ccxt.base.errors import ArgumentsRequired
15
- from ccxt.base.errors import BadSymbol
16
- from ccxt.base.errors import NullResponse
15
+ from ccxt.base.errors import BadRequest
17
16
  from ccxt.base.errors import InsufficientFunds
18
- from ccxt.base.errors import InvalidOrder
19
- from ccxt.base.errors import OrderNotFound
20
- from ccxt.base.errors import DDoSProtection
21
- from ccxt.base.errors import RateLimitExceeded
22
- from ccxt.base.errors import InvalidNonce
17
+ from ccxt.base.errors import NullResponse
23
18
  from ccxt.base.decimal_to_precision import TICK_SIZE
24
19
  from ccxt.base.precise import Precise
25
20
 
26
21
 
27
22
  class cex(Exchange, ImplicitAPI):
28
23
 
29
- def describe(self):
24
+ def describe(self) -> Any:
30
25
  return self.deep_extend(super(cex, self).describe(), {
31
26
  'id': 'cex',
32
27
  'name': 'CEX.IO',
33
28
  'countries': ['GB', 'EU', 'CY', 'RU'],
34
- 'rateLimit': 1500,
29
+ 'rateLimit': 300, # 200 req/min
35
30
  'pro': True,
36
31
  'has': {
37
32
  'CORS': None,
38
33
  'spot': True,
39
- 'margin': False, # has but not through api
34
+ 'margin': False, # has, but not through api
40
35
  'swap': False,
41
36
  'future': False,
42
37
  'option': False,
43
38
  'addMargin': False,
39
+ 'borrowCrossMargin': False,
40
+ 'borrowIsolatedMargin': False,
41
+ 'borrowMargin': False,
44
42
  'cancelAllOrders': True,
45
43
  'cancelOrder': True,
46
- 'cancelOrders': False,
47
- 'createDepositAddress': False,
48
- 'createMarketBuyOrderWithCost': True,
49
- 'createMarketOrderWithCost': False,
50
- 'createMarketSellOrderWithCost': False,
44
+ 'closeAllPositions': False,
45
+ 'closePosition': False,
51
46
  'createOrder': True,
52
- 'createStopLimitOrder': False,
53
- 'createStopMarketOrder': False,
54
- 'createStopOrder': False,
55
- 'editOrder': True,
47
+ 'createOrderWithTakeProfitAndStopLoss': False,
48
+ 'createOrderWithTakeProfitAndStopLossWs': False,
49
+ 'createPostOnlyOrder': False,
50
+ 'createReduceOnlyOrder': False,
51
+ 'createStopOrder': True,
52
+ 'createTriggerOrder': True,
53
+ 'fetchAccounts': True,
56
54
  'fetchBalance': True,
55
+ 'fetchBorrowInterest': False,
56
+ 'fetchBorrowRate': False,
57
+ 'fetchBorrowRateHistories': False,
58
+ 'fetchBorrowRateHistory': False,
59
+ 'fetchBorrowRates': False,
60
+ 'fetchBorrowRatesPerSymbol': False,
61
+ 'fetchClosedOrder': True,
57
62
  'fetchClosedOrders': True,
63
+ 'fetchCrossBorrowRate': False,
64
+ 'fetchCrossBorrowRates': False,
58
65
  'fetchCurrencies': True,
59
- 'fetchDeposit': False,
60
66
  'fetchDepositAddress': True,
61
- 'fetchDepositAddresses': False,
62
- 'fetchDeposits': False,
63
- 'fetchDepositsWithdrawals': False,
67
+ 'fetchDepositsWithdrawals': True,
64
68
  'fetchFundingHistory': False,
69
+ 'fetchFundingInterval': False,
70
+ 'fetchFundingIntervals': False,
65
71
  'fetchFundingRate': False,
66
72
  'fetchFundingRateHistory': False,
67
73
  'fetchFundingRates': False,
74
+ 'fetchGreeks': False,
68
75
  'fetchIndexOHLCV': False,
76
+ 'fetchIsolatedBorrowRate': False,
77
+ 'fetchIsolatedBorrowRates': False,
78
+ 'fetchIsolatedPositions': False,
79
+ 'fetchLedger': True,
80
+ 'fetchLeverage': False,
81
+ 'fetchLeverages': False,
82
+ 'fetchLeverageTiers': False,
83
+ 'fetchLiquidations': False,
84
+ 'fetchLongShortRatio': False,
85
+ 'fetchLongShortRatioHistory': False,
86
+ 'fetchMarginAdjustmentHistory': False,
69
87
  'fetchMarginMode': False,
88
+ 'fetchMarginModes': False,
89
+ 'fetchMarketLeverageTiers': False,
70
90
  'fetchMarkets': True,
71
91
  'fetchMarkOHLCV': False,
92
+ 'fetchMarkPrices': False,
93
+ 'fetchMyLiquidations': False,
94
+ 'fetchMySettlementHistory': False,
72
95
  'fetchOHLCV': True,
96
+ 'fetchOpenInterest': False,
73
97
  'fetchOpenInterestHistory': False,
98
+ 'fetchOpenInterests': False,
99
+ 'fetchOpenOrder': True,
74
100
  'fetchOpenOrders': True,
75
- 'fetchOrder': True,
101
+ 'fetchOption': False,
102
+ 'fetchOptionChain': False,
76
103
  'fetchOrderBook': True,
77
- 'fetchOrders': True,
78
104
  'fetchPosition': False,
79
105
  'fetchPositionHistory': False,
80
106
  'fetchPositionMode': False,
@@ -83,1523 +109,1633 @@ class cex(Exchange, ImplicitAPI):
83
109
  'fetchPositionsHistory': False,
84
110
  'fetchPositionsRisk': False,
85
111
  'fetchPremiumIndexOHLCV': False,
112
+ 'fetchSettlementHistory': False,
86
113
  'fetchTicker': True,
87
114
  'fetchTickers': True,
115
+ 'fetchTime': True,
88
116
  'fetchTrades': True,
89
- 'fetchTradingFee': False,
90
117
  'fetchTradingFees': True,
91
- 'fetchTransactions': False,
92
- 'fetchTransfer': False,
93
- 'fetchTransfers': False,
94
- 'fetchWithdrawal': False,
95
- 'fetchWithdrawals': False,
96
- 'fetchWithdrawalWhitelist': False,
118
+ 'fetchVolatilityHistory': False,
97
119
  'reduceMargin': False,
120
+ 'repayCrossMargin': False,
121
+ 'repayIsolatedMargin': False,
122
+ 'repayMargin': False,
98
123
  'setLeverage': False,
99
124
  'setMargin': False,
100
125
  'setMarginMode': False,
101
- 'transfer': False,
102
- 'withdraw': False,
103
- },
104
- 'timeframes': {
105
- '1m': '1m',
106
- '1h': '1h',
107
- '1d': '1d',
126
+ 'setPositionMode': False,
127
+ 'transfer': True,
108
128
  },
109
129
  'urls': {
110
130
  'logo': 'https://user-images.githubusercontent.com/1294454/27766442-8ddc33b0-5ed8-11e7-8b98-f786aef0f3c9.jpg',
111
131
  'api': {
112
- 'rest': 'https://cex.io/api',
132
+ 'public': 'https://trade.cex.io/api/spot/rest-public',
133
+ 'private': 'https://trade.cex.io/api/spot/rest',
113
134
  },
114
135
  'www': 'https://cex.io',
115
- 'doc': 'https://cex.io/cex-api',
136
+ 'doc': 'https://trade.cex.io/docs/',
116
137
  'fees': [
117
138
  'https://cex.io/fee-schedule',
118
139
  'https://cex.io/limits-commissions',
119
140
  ],
120
141
  'referral': 'https://cex.io/r/0/up105393824/0/',
121
142
  },
122
- 'requiredCredentials': {
123
- 'apiKey': True,
124
- 'secret': True,
125
- 'uid': True,
126
- },
127
143
  'api': {
128
144
  'public': {
129
- 'get': [
130
- 'currency_profile',
131
- 'currency_limits/',
132
- 'last_price/{pair}/',
133
- 'last_prices/{currencies}/',
134
- 'ohlcv/hd/{yyyymmdd}/{pair}',
135
- 'order_book/{pair}/',
136
- 'ticker/{pair}/',
137
- 'tickers/{currencies}/',
138
- 'trade_history/{pair}/',
139
- ],
140
- 'post': [
141
- 'convert/{pair}',
142
- 'price_stats/{pair}',
143
- ],
145
+ 'get': {},
146
+ 'post': {
147
+ 'get_server_time': 1,
148
+ 'get_pairs_info': 1,
149
+ 'get_currencies_info': 1,
150
+ 'get_processing_info': 10,
151
+ 'get_ticker': 1,
152
+ 'get_trade_history': 1,
153
+ 'get_order_book': 1,
154
+ 'get_candles': 1,
155
+ },
144
156
  },
145
157
  'private': {
146
- 'post': [
147
- 'active_orders_status/',
148
- 'archived_orders/{pair}/',
149
- 'balance/',
150
- 'cancel_order/',
151
- 'cancel_orders/{pair}/',
152
- 'cancel_replace_order/{pair}/',
153
- 'close_position/{pair}/',
154
- 'get_address/',
155
- 'get_crypto_address',
156
- 'get_myfee/',
157
- 'get_order/',
158
- 'get_order_tx/',
159
- 'open_orders/{pair}/',
160
- 'open_orders/',
161
- 'open_position/{pair}/',
162
- 'open_positions/{pair}/',
163
- 'place_order/{pair}/',
164
- 'raw_tx_history',
165
- ],
158
+ 'get': {},
159
+ 'post': {
160
+ 'get_my_current_fee': 5,
161
+ 'get_fee_strategy': 1,
162
+ 'get_my_volume': 5,
163
+ 'do_create_account': 1,
164
+ 'get_my_account_status_v3': 5,
165
+ 'get_my_wallet_balance': 5,
166
+ 'get_my_orders': 5,
167
+ 'do_my_new_order': 1,
168
+ 'do_cancel_my_order': 1,
169
+ 'do_cancel_all_orders': 5,
170
+ 'get_order_book': 1,
171
+ 'get_candles': 1,
172
+ 'get_trade_history': 1,
173
+ 'get_my_transaction_history': 1,
174
+ 'get_my_funding_history': 5,
175
+ 'do_my_internal_transfer': 1,
176
+ 'get_processing_info': 10,
177
+ 'get_deposit_address': 5,
178
+ 'do_deposit_funds_from_wallet': 1,
179
+ 'do_withdrawal_funds_to_wallet': 1,
180
+ },
166
181
  },
167
182
  },
168
- 'fees': {
169
- 'trading': {
170
- 'maker': self.parse_number('0.0016'),
171
- 'taker': self.parse_number('0.0025'),
172
- },
173
- 'funding': {
174
- 'withdraw': {},
175
- 'deposit': {
176
- # 'USD': amount => amount * 0.035 + 0.25,
177
- # 'EUR': amount => amount * 0.035 + 0.24,
178
- # 'RUB': amount => amount * 0.05 + 15.57,
179
- # 'GBP': amount => amount * 0.035 + 0.2,
180
- 'BTC': 0.0,
181
- 'ETH': 0.0,
182
- 'BCH': 0.0,
183
- 'DASH': 0.0,
184
- 'BTG': 0.0,
185
- 'ZEC': 0.0,
186
- 'XRP': 0.0,
187
- 'XLM': 0.0,
183
+ 'features': {
184
+ 'spot': {
185
+ 'sandbox': False,
186
+ 'createOrder': {
187
+ 'marginMode': False,
188
+ 'triggerPrice': True,
189
+ 'triggerPriceType': None,
190
+ 'triggerDirection': False,
191
+ 'stopLossPrice': False, # todo
192
+ 'takeProfitPrice': False, # todo
193
+ 'attachedStopLossTakeProfit': None,
194
+ 'timeInForce': {
195
+ 'IOC': True,
196
+ 'FOK': True,
197
+ 'PO': False, # todo check
198
+ 'GTD': True,
199
+ },
200
+ 'hedged': False,
201
+ 'leverage': False,
202
+ 'marketBuyRequiresPrice': False,
203
+ 'marketBuyByCost': True, # todo check
204
+ 'selfTradePrevention': False,
205
+ 'trailing': False,
206
+ 'iceberg': False,
188
207
  },
208
+ 'createOrders': None,
209
+ 'fetchMyTrades': None,
210
+ 'fetchOrder': None,
211
+ 'fetchOpenOrders': {
212
+ 'marginMode': False,
213
+ 'limit': 1000,
214
+ 'trigger': False,
215
+ 'trailing': False,
216
+ 'symbolRequired': False,
217
+ },
218
+ 'fetchOrders': None,
219
+ 'fetchClosedOrders': {
220
+ 'marginMode': False,
221
+ 'limit': 1000,
222
+ 'daysBack': 100000,
223
+ 'daysBackCanceled': 1,
224
+ 'untilDays': 100000,
225
+ 'trigger': False,
226
+ 'trailing': False,
227
+ 'symbolRequired': False,
228
+ },
229
+ 'fetchOHLCV': {
230
+ 'limit': 1000,
231
+ },
232
+ },
233
+ 'swap': {
234
+ 'linear': None,
235
+ 'inverse': None,
236
+ },
237
+ 'future': {
238
+ 'linear': None,
239
+ 'inverse': None,
189
240
  },
190
241
  },
191
242
  'precisionMode': TICK_SIZE,
192
243
  'exceptions': {
193
244
  'exact': {},
194
245
  'broad': {
246
+ 'You have negative balance on following accounts': InsufficientFunds,
247
+ 'Mandatory parameter side should be one of BUY,SELL': BadRequest,
248
+ 'API orders from Main account are not allowed': BadRequest,
249
+ 'check failed': BadRequest,
195
250
  'Insufficient funds': InsufficientFunds,
196
- 'Nonce must be incremented': InvalidNonce,
197
- 'Invalid Order': InvalidOrder,
198
- 'Order not found': OrderNotFound,
199
- 'limit exceeded': RateLimitExceeded, # {"error":"rate limit exceeded"}
200
- 'Invalid API key': AuthenticationError,
201
- 'There was an error while placing your order': InvalidOrder,
202
- 'Sorry, too many clients already': DDoSProtection,
203
- 'Invalid Symbols Pair': BadSymbol,
204
- 'Wrong currency pair': BadSymbol, # {"error":"There was an error while placing your order: Wrong currency pair.","safe":true}
251
+ 'Get deposit address for main account is not allowed': PermissionDenied,
252
+ 'Market Trigger orders are not allowed': BadRequest, # for some reason, triggerPrice does not work for market orders
253
+ 'key not passed or incorrect': AuthenticationError,
205
254
  },
206
255
  },
256
+ 'timeframes': {
257
+ '1m': '1m',
258
+ '5m': '5m',
259
+ '15m': '15m',
260
+ '30m': '30m',
261
+ '1h': '1h',
262
+ '2h': '2h',
263
+ '4h': '4h',
264
+ '1d': '1d',
265
+ },
207
266
  'options': {
208
- 'fetchOHLCVWarning': True,
209
- 'createMarketBuyOrderRequiresPrice': True,
210
- 'order': {
211
- 'status': {
212
- 'c': 'canceled',
213
- 'd': 'closed',
214
- 'cd': 'canceled',
215
- 'a': 'open',
216
- },
217
- },
218
- 'defaultNetwork': 'ERC20',
219
- 'defaultNetworks': {
220
- 'USDT': 'TRC20',
221
- },
222
267
  'networks': {
223
- 'ERC20': 'Ethereum',
224
- 'BTC': 'BTC',
225
- 'BEP20': 'Binance Smart Chain',
226
- 'TRC20': 'Tron',
268
+ 'BTC': 'bitcoin',
269
+ 'ERC20': 'ERC20',
270
+ 'BSC20': 'binancesmartchain',
271
+ 'DOGE': 'dogecoin',
272
+ 'ALGO': 'algorand',
273
+ 'XLM': 'stellar',
274
+ 'ATOM': 'cosmos',
275
+ 'LTC': 'litecoin',
276
+ 'XRP': 'ripple',
277
+ 'FTM': 'fantom',
278
+ 'MINA': 'mina',
279
+ 'THETA': 'theta',
280
+ 'XTZ': 'tezos',
281
+ 'TIA': 'celestia',
282
+ 'CRONOS': 'cronos', # CRC20
283
+ 'MATIC': 'polygon',
284
+ 'TON': 'ton',
285
+ 'TRC20': 'tron',
286
+ 'SOLANA': 'solana',
287
+ 'SGB': 'songbird',
288
+ 'DYDX': 'dydx',
289
+ 'DASH': 'dash',
290
+ 'ZIL': 'zilliqa',
291
+ 'EOS': 'eos',
292
+ 'AVALANCHEC': 'avalanche',
293
+ 'ETHPOW': 'ethereumpow',
294
+ 'NEAR': 'near',
295
+ 'ARB': 'arbitrum',
296
+ 'DOT': 'polkadot',
297
+ 'OPT': 'optimism',
298
+ 'INJ': 'injective',
299
+ 'ADA': 'cardano',
300
+ 'ONT': 'ontology',
301
+ 'ICP': 'icp',
302
+ 'KAVA': 'kava',
303
+ 'KSM': 'kusama',
304
+ 'SEI': 'sei',
305
+ # 'OSM': 'osmosis',
306
+ 'NEO': 'neo',
307
+ 'NEO3': 'neo3',
308
+ # 'TERRAOLD': 'terra', # tbd
309
+ # 'TERRA': 'terra2', # tbd
310
+ # 'EVER': 'everscale', # tbd
311
+ 'XDC': 'xdc',
227
312
  },
228
313
  },
229
314
  })
230
315
 
231
- def fetch_currencies_from_cache(self, params={}):
232
- # self method is now redundant
233
- # currencies are now fetched before markets
234
- options = self.safe_value(self.options, 'fetchCurrencies', {})
235
- timestamp = self.safe_integer(options, 'timestamp')
236
- expires = self.safe_integer(options, 'expires', 1000)
237
- now = self.milliseconds()
238
- if (timestamp is None) or ((now - timestamp) > expires):
239
- response = self.publicGetCurrencyProfile(params)
240
- self.options['fetchCurrencies'] = self.extend(options, {
241
- 'response': response,
242
- 'timestamp': now,
243
- })
244
- return self.safe_value(self.options['fetchCurrencies'], 'response')
245
-
246
316
  def fetch_currencies(self, params={}) -> Currencies:
247
317
  """
248
318
  fetches all available currencies on an exchange
319
+
320
+ https://trade.cex.io/docs/#rest-public-api-calls-currencies-info
321
+
249
322
  :param dict [params]: extra parameters specific to the exchange API endpoint
250
323
  :returns dict: an associative dictionary of currencies
251
324
  """
252
- response = self.fetch_currencies_from_cache(params)
253
- self.options['currencies'] = {
254
- 'timestamp': self.milliseconds(),
255
- 'response': response,
256
- }
325
+ promises = []
326
+ promises.append(self.publicPostGetCurrenciesInfo(params))
257
327
  #
258
- # {
259
- # "e":"currency_profile",
260
- # "ok":"ok",
261
- # "data":{
262
- # "symbols":[
263
- # {
264
- # "code":"GHS",
265
- # "contract":true,
266
- # "commodity":true,
267
- # "fiat":false,
268
- # "description":"CEX.IO doesn't provide cloud mining services anymore.",
269
- # "precision":8,
270
- # "scale":0,
271
- # "minimumCurrencyAmount":"0.00000001",
272
- # "minimalWithdrawalAmount":-1
273
- # },
274
- # {
275
- # "code":"BTC",
276
- # "contract":false,
277
- # "commodity":false,
278
- # "fiat":false,
279
- # "description":"",
280
- # "precision":8,
281
- # "scale":0,
282
- # "minimumCurrencyAmount":"0.00000001",
283
- # "minimalWithdrawalAmount":0.002
284
- # },
285
- # {
286
- # "code":"ETH",
287
- # "contract":false,
288
- # "commodity":false,
289
- # "fiat":false,
290
- # "description":"",
291
- # "precision":8,
292
- # "scale":2,
293
- # "minimumCurrencyAmount":"0.00000100",
294
- # "minimalWithdrawalAmount":0.01
295
- # }
296
- # ],
297
- # "pairs":[
298
- # {
299
- # "symbol1":"BTC",
300
- # "symbol2":"USD",
301
- # "pricePrecision":1,
302
- # "priceScale":"/1000000",
303
- # "minLotSize":0.002,
304
- # "minLotSizeS2":20
305
- # },
306
- # {
307
- # "symbol1":"ETH",
308
- # "symbol2":"USD",
309
- # "pricePrecision":2,
310
- # "priceScale":"/10000",
311
- # "minLotSize":0.1,
312
- # "minLotSizeS2":20
313
- # }
314
- # ]
315
- # }
316
- # }
328
+ # {
329
+ # "ok": "ok",
330
+ # "data": [
331
+ # {
332
+ # "currency": "ZAP",
333
+ # "fiat": False,
334
+ # "precision": "8",
335
+ # "walletPrecision": "6",
336
+ # "walletDeposit": True,
337
+ # "walletWithdrawal": True
338
+ # },
339
+ # ...
317
340
  #
318
- data = self.safe_value(response, 'data', [])
319
- currencies = self.safe_value(data, 'symbols', [])
320
- result: dict = {}
321
- for i in range(0, len(currencies)):
322
- currency = currencies[i]
323
- id = self.safe_string(currency, 'code')
324
- code = self.safe_currency_code(id)
325
- active = True
326
- result[code] = {
327
- 'id': id,
328
- 'code': code,
329
- 'name': id,
330
- 'active': active,
331
- 'deposit': None,
332
- 'withdraw': None,
333
- 'precision': self.parse_number(self.parse_precision(self.safe_string(currency, 'precision'))),
334
- 'fee': None,
341
+ promises.append(self.publicPostGetProcessingInfo(params))
342
+ #
343
+ # {
344
+ # "ok": "ok",
345
+ # "data": {
346
+ # "ADA": {
347
+ # "name": "Cardano",
348
+ # "blockchains": {
349
+ # "cardano": {
350
+ # "type": "coin",
351
+ # "deposit": "enabled",
352
+ # "minDeposit": "1",
353
+ # "withdrawal": "enabled",
354
+ # "minWithdrawal": "5",
355
+ # "withdrawalFee": "1",
356
+ # "withdrawalFeePercent": "0",
357
+ # "depositConfirmations": "15"
358
+ # }
359
+ # }
360
+ # },
361
+ # ...
362
+ #
363
+ responses = promises
364
+ dataCurrencies = self.safe_list(responses[0], 'data', [])
365
+ dataNetworks = self.safe_dict(responses[1], 'data', {})
366
+ currenciesIndexed = self.index_by(dataCurrencies, 'currency')
367
+ data = self.deep_extend(currenciesIndexed, dataNetworks)
368
+ return self.parse_currencies(self.to_array(data))
369
+
370
+ def parse_currency(self, rawCurrency: dict) -> Currency:
371
+ id = self.safe_string(rawCurrency, 'currency')
372
+ code = self.safe_currency_code(id)
373
+ type = 'fiat' if self.safe_bool(rawCurrency, 'fiat') else 'crypto'
374
+ currencyPrecision = self.parse_number(self.parse_precision(self.safe_string(rawCurrency, 'precision')))
375
+ networks: dict = {}
376
+ rawNetworks = self.safe_dict(rawCurrency, 'blockchains', {})
377
+ keys = list(rawNetworks.keys())
378
+ for j in range(0, len(keys)):
379
+ networkId = keys[j]
380
+ rawNetwork = rawNetworks[networkId]
381
+ networkCode = self.network_id_to_code(networkId)
382
+ deposit = self.safe_string(rawNetwork, 'deposit') == 'enabled'
383
+ withdraw = self.safe_string(rawNetwork, 'withdrawal') == 'enabled'
384
+ networks[networkCode] = {
385
+ 'id': networkId,
386
+ 'network': networkCode,
387
+ 'margin': None,
388
+ 'deposit': deposit,
389
+ 'withdraw': withdraw,
390
+ 'active': None,
391
+ 'fee': self.safe_number(rawNetwork, 'withdrawalFee'),
392
+ 'precision': currencyPrecision,
335
393
  'limits': {
336
- 'amount': {
337
- 'min': self.safe_number(currency, 'minimumCurrencyAmount'),
394
+ 'deposit': {
395
+ 'min': self.safe_number(rawNetwork, 'minDeposit'),
338
396
  'max': None,
339
397
  },
340
398
  'withdraw': {
341
- 'min': self.safe_number(currency, 'minimalWithdrawalAmount'),
399
+ 'min': self.safe_number(rawNetwork, 'minWithdrawal'),
342
400
  'max': None,
343
401
  },
344
402
  },
345
- 'info': currency,
403
+ 'info': rawNetwork,
346
404
  }
347
- return result
405
+ return self.safe_currency_structure({
406
+ 'id': id,
407
+ 'code': code,
408
+ 'name': None,
409
+ 'type': type,
410
+ 'active': None,
411
+ 'deposit': self.safe_bool(rawCurrency, 'walletDeposit'),
412
+ 'withdraw': self.safe_bool(rawCurrency, 'walletWithdrawal'),
413
+ 'fee': None,
414
+ 'precision': currencyPrecision,
415
+ 'limits': {
416
+ 'amount': {
417
+ 'min': None,
418
+ 'max': None,
419
+ },
420
+ 'withdraw': {
421
+ 'min': None,
422
+ 'max': None,
423
+ },
424
+ },
425
+ 'networks': networks,
426
+ 'info': rawCurrency,
427
+ })
348
428
 
349
429
  def fetch_markets(self, params={}) -> List[Market]:
350
430
  """
351
- retrieves data on all markets for cex
431
+ retrieves data on all markets for ace
432
+
433
+ https://trade.cex.io/docs/#rest-public-api-calls-pairs-info
434
+
352
435
  :param dict [params]: extra parameters specific to the exchange API endpoint
353
436
  :returns dict[]: an array of objects representing market data
354
437
  """
355
- currenciesResponse = self.fetch_currencies_from_cache(params)
356
- currenciesData = self.safe_value(currenciesResponse, 'data', {})
357
- currencies = self.safe_value(currenciesData, 'symbols', [])
358
- currenciesById = self.index_by(currencies, 'code')
359
- pairs = self.safe_value(currenciesData, 'pairs', [])
360
- response = self.publicGetCurrencyLimits(params)
438
+ response = self.publicPostGetPairsInfo(params)
361
439
  #
362
- # {
363
- # "e":"currency_limits",
364
- # "ok":"ok",
365
- # "data": {
366
- # "pairs":[
367
- # {
368
- # "symbol1":"BTC",
369
- # "symbol2":"USD",
370
- # "minLotSize":0.002,
371
- # "minLotSizeS2":20,
372
- # "maxLotSize":30,
373
- # "minPrice":"1500",
374
- # "maxPrice":"35000"
375
- # },
376
- # {
377
- # "symbol1":"BCH",
378
- # "symbol2":"EUR",
379
- # "minLotSize":0.1,
380
- # "minLotSizeS2":20,
381
- # "maxLotSize":null,
382
- # "minPrice":"25",
383
- # "maxPrice":"8192"
384
- # }
385
- # ]
386
- # }
387
- # }
440
+ # {
441
+ # "ok": "ok",
442
+ # "data": [
443
+ # {
444
+ # "base": "AI",
445
+ # "quote": "USD",
446
+ # "baseMin": "30",
447
+ # "baseMax": "2516000",
448
+ # "baseLotSize": "0.000001",
449
+ # "quoteMin": "10",
450
+ # "quoteMax": "1000000",
451
+ # "quoteLotSize": "0.01000000",
452
+ # "basePrecision": "6",
453
+ # "quotePrecision": "8",
454
+ # "pricePrecision": "4",
455
+ # "minPrice": "0.0377",
456
+ # "maxPrice": "19.5000"
457
+ # },
458
+ # ...
388
459
  #
389
- result = []
390
- markets = self.safe_value(response['data'], 'pairs')
391
- for i in range(0, len(markets)):
392
- market = markets[i]
393
- baseId = self.safe_string(market, 'symbol1')
394
- quoteId = self.safe_string(market, 'symbol2')
395
- base = self.safe_currency_code(baseId)
396
- quote = self.safe_currency_code(quoteId)
397
- baseCurrency = self.safe_value(currenciesById, baseId, {})
398
- quoteCurrency = self.safe_value(currenciesById, quoteId, {})
399
- pricePrecisionString = self.safe_string(quoteCurrency, 'precision', '8')
400
- for j in range(0, len(pairs)):
401
- pair = pairs[j]
402
- if (pair['symbol1'] == baseId) and (pair['symbol2'] == quoteId):
403
- # we might need to account for `priceScale` here
404
- pricePrecisionString = self.safe_string(pair, 'pricePrecision', pricePrecisionString)
405
- baseCurrencyPrecision = self.safe_string(baseCurrency, 'precision', '8')
406
- baseCurrencyScale = self.safe_string(baseCurrency, 'scale', '0')
407
- amountPrecisionString = Precise.string_sub(baseCurrencyPrecision, baseCurrencyScale)
408
- result.append({
409
- 'id': baseId + '/' + quoteId,
410
- 'symbol': base + '/' + quote,
411
- 'base': base,
412
- 'quote': quote,
413
- 'settle': None,
414
- 'baseId': baseId,
415
- 'quoteId': quoteId,
416
- 'settleId': None,
417
- 'type': 'spot',
418
- 'spot': True,
419
- 'margin': None,
420
- 'swap': False,
421
- 'future': False,
422
- 'option': False,
423
- 'active': None,
424
- 'contract': False,
425
- 'linear': None,
426
- 'inverse': None,
427
- 'contractSize': None,
428
- 'expiry': None,
429
- 'expiryDatetime': None,
430
- 'strike': None,
431
- 'optionType': None,
432
- 'precision': {
433
- 'amount': self.parse_number(self.parse_precision(amountPrecisionString)),
434
- 'price': self.parse_number(self.parse_precision(pricePrecisionString)),
460
+ data = self.safe_list(response, 'data', [])
461
+ return self.parse_markets(data)
462
+
463
+ def parse_market(self, market: dict) -> Market:
464
+ baseId = self.safe_string(market, 'base')
465
+ base = self.safe_currency_code(baseId)
466
+ quoteId = self.safe_string(market, 'quote')
467
+ quote = self.safe_currency_code(quoteId)
468
+ id = base + '-' + quote # not actual id, but for self exchange we can use self abbreviation, because e.g. tickers have hyphen in between
469
+ symbol = base + '/' + quote
470
+ return self.safe_market_structure({
471
+ 'id': id,
472
+ 'symbol': symbol,
473
+ 'base': base,
474
+ 'baseId': baseId,
475
+ 'quote': quote,
476
+ 'quoteId': quoteId,
477
+ 'settle': None,
478
+ 'settleId': None,
479
+ 'type': 'spot',
480
+ 'spot': True,
481
+ 'margin': False,
482
+ 'swap': False,
483
+ 'future': False,
484
+ 'option': False,
485
+ 'contract': False,
486
+ 'linear': None,
487
+ 'inverse': None,
488
+ 'contractSize': None,
489
+ 'expiry': None,
490
+ 'expiryDatetime': None,
491
+ 'strike': None,
492
+ 'optionType': None,
493
+ 'limits': {
494
+ 'amount': {
495
+ 'min': self.safe_number(market, 'baseMin'),
496
+ 'max': self.safe_number(market, 'baseMax'),
435
497
  },
436
- 'limits': {
437
- 'leverage': {
438
- 'min': None,
439
- 'max': None,
440
- },
441
- 'amount': {
442
- 'min': self.safe_number(market, 'minLotSize'),
443
- 'max': self.safe_number(market, 'maxLotSize'),
444
- },
445
- 'price': {
446
- 'min': self.safe_number(market, 'minPrice'),
447
- 'max': self.safe_number(market, 'maxPrice'),
448
- },
449
- 'cost': {
450
- 'min': self.safe_number(market, 'minLotSizeS2'),
451
- 'max': None,
452
- },
498
+ 'price': {
499
+ 'min': self.safe_number(market, 'minPrice'),
500
+ 'max': self.safe_number(market, 'maxPrice'),
453
501
  },
454
- 'created': None,
455
- 'info': market,
456
- })
457
- return result
458
-
459
- def parse_balance(self, response) -> Balances:
460
- result: dict = {'info': response}
461
- ommited = ['username', 'timestamp']
462
- balances = self.omit(response, ommited)
463
- currencyIds = list(balances.keys())
464
- for i in range(0, len(currencyIds)):
465
- currencyId = currencyIds[i]
466
- balance = self.safe_value(balances, currencyId, {})
467
- account = self.account()
468
- account['free'] = self.safe_string(balance, 'available')
469
- # https://github.com/ccxt/ccxt/issues/5484
470
- account['used'] = self.safe_string(balance, 'orders', '0')
471
- code = self.safe_currency_code(currencyId)
472
- result[code] = account
473
- return self.safe_balance(result)
502
+ 'cost': {
503
+ 'min': self.safe_number(market, 'quoteMin'),
504
+ 'max': self.safe_number(market, 'quoteMax'),
505
+ },
506
+ 'leverage': {
507
+ 'min': None,
508
+ 'max': None,
509
+ },
510
+ },
511
+ 'precision': {
512
+ 'amount': self.safe_string(market, 'baseLotSize'),
513
+ 'price': self.parse_number(self.parse_precision(self.safe_string(market, 'pricePrecision'))),
514
+ # 'cost': self.parse_number(self.parse_precision(self.safe_string(market, 'quoteLotSize'))), # buggy, doesn't reflect their documentation
515
+ 'base': self.parse_number(self.parse_precision(self.safe_string(market, 'basePrecision'))),
516
+ 'quote': self.parse_number(self.parse_precision(self.safe_string(market, 'quotePrecision'))),
517
+ },
518
+ 'active': None,
519
+ 'created': None,
520
+ 'info': market,
521
+ })
474
522
 
475
- def fetch_balance(self, params={}) -> Balances:
523
+ def fetch_time(self, params={}) -> Int:
476
524
  """
477
- :see: https://docs.cex.io/#account-balance
478
- query for balance and get the amount of funds available for trading or funds locked in orders
525
+ fetches the current integer timestamp in milliseconds from the exchange server
479
526
  :param dict [params]: extra parameters specific to the exchange API endpoint
480
- :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
527
+ :returns int: the current integer timestamp in milliseconds from the exchange server
481
528
  """
482
- self.load_markets()
483
- response = self.privatePostBalance(params)
484
- return self.parse_balance(response)
529
+ response = self.publicPostGetServerTime(params)
530
+ #
531
+ # {
532
+ # "ok": "ok",
533
+ # "data": {
534
+ # "timestamp": "1728472063472",
535
+ # "ISODate": "2024-10-09T11:07:43.472Z"
536
+ # }
537
+ # }
538
+ #
539
+ data = self.safe_dict(response, 'data')
540
+ timestamp = self.safe_integer(data, 'timestamp')
541
+ return timestamp
485
542
 
486
- def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
543
+ def fetch_ticker(self, symbol: str, params={}) -> Ticker:
487
544
  """
488
- :see: https://docs.cex.io/#orderbook
489
- fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
490
- :param str symbol: unified symbol of the market to fetch the order book for
491
- :param int [limit]: the maximum amount of order book entries to return
545
+ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
546
+
547
+ https://trade.cex.io/docs/#rest-public-api-calls-ticker
548
+
549
+ :param str symbol:
492
550
  :param dict [params]: extra parameters specific to the exchange API endpoint
493
- :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
551
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
494
552
  """
495
553
  self.load_markets()
496
- market = self.market(symbol)
497
- request: dict = {
498
- 'pair': market['id'],
499
- }
500
- if limit is not None:
501
- request['depth'] = limit
502
- response = self.publicGetOrderBookPair(self.extend(request, params))
503
- timestamp = self.safe_timestamp(response, 'timestamp')
504
- return self.parse_order_book(response, market['symbol'], timestamp)
505
-
506
- def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
507
- #
508
- # [
509
- # 1591403940,
510
- # 0.024972,
511
- # 0.024972,
512
- # 0.024969,
513
- # 0.024969,
514
- # 0.49999900
515
- # ]
516
- #
517
- return [
518
- self.safe_timestamp(ohlcv, 0),
519
- self.safe_number(ohlcv, 1),
520
- self.safe_number(ohlcv, 2),
521
- self.safe_number(ohlcv, 3),
522
- self.safe_number(ohlcv, 4),
523
- self.safe_number(ohlcv, 5),
524
- ]
554
+ response = self.fetch_tickers([symbol], params)
555
+ return self.safe_dict(response, symbol, {})
525
556
 
526
- def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
557
+ def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
527
558
  """
528
- :see: https://docs.cex.io/#historical-ohlcv-chart
529
- fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
530
- :param str symbol: unified symbol of the market to fetch OHLCV data for
531
- :param str timeframe: the length of time each candle represents
532
- :param int [since]: timestamp in ms of the earliest candle to fetch
533
- :param int [limit]: the maximum amount of candles to fetch
559
+ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
560
+
561
+ https://trade.cex.io/docs/#rest-public-api-calls-ticker
562
+
563
+ :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
534
564
  :param dict [params]: extra parameters specific to the exchange API endpoint
535
- :returns int[][]: A list of candles ordered, open, high, low, close, volume
565
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
536
566
  """
537
567
  self.load_markets()
538
- market = self.market(symbol)
539
- if since is None:
540
- since = self.milliseconds() - 86400000 # yesterday
541
- else:
542
- if self.options['fetchOHLCVWarning']:
543
- raise ExchangeError(self.id + " fetchOHLCV warning: CEX can return historical candles for a certain date only, self might produce an empty or None reply. Set exchange.options['fetchOHLCVWarning'] = False or add({'options': {'fetchOHLCVWarning': False}}) to constructor params to suppress self warning message.")
544
- request: dict = {
545
- 'pair': market['id'],
546
- 'yyyymmdd': self.yyyymmdd(since, ''),
547
- }
548
- try:
549
- response = self.publicGetOhlcvHdYyyymmddPair(self.extend(request, params))
550
- #
551
- # {
552
- # "time":20200606,
553
- # "data1m":"[[1591403940,0.024972,0.024972,0.024969,0.024969,0.49999900]]",
554
- # }
555
- #
556
- key = 'data' + self.safe_string(self.timeframes, timeframe, timeframe)
557
- data = self.safe_string(response, key)
558
- ohlcvs = json.loads(data)
559
- return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)
560
- except Exception as e:
561
- if isinstance(e, NullResponse):
562
- return []
563
- return None
568
+ request = {}
569
+ if symbols is not None:
570
+ request['pairs'] = self.market_ids(symbols)
571
+ response = self.publicPostGetTicker(self.extend(request, params))
572
+ #
573
+ # {
574
+ # "ok": "ok",
575
+ # "data": {
576
+ # "AI-USD": {
577
+ # "bestBid": "0.3917",
578
+ # "bestAsk": "0.3949",
579
+ # "bestBidChange": "0.0035",
580
+ # "bestBidChangePercentage": "0.90",
581
+ # "bestAskChange": "0.0038",
582
+ # "bestAskChangePercentage": "0.97",
583
+ # "low": "0.3787",
584
+ # "high": "0.3925",
585
+ # "volume30d": "2945.722277",
586
+ # "lastTradeDateISO": "2024-10-11T06:18:42.077Z",
587
+ # "volume": "120.736000",
588
+ # "quoteVolume": "46.65654070",
589
+ # "lastTradeVolume": "67.914000",
590
+ # "volumeUSD": "46.65",
591
+ # "last": "0.3949",
592
+ # "lastTradePrice": "0.3925",
593
+ # "priceChange": "0.0038",
594
+ # "priceChangePercentage": "0.97"
595
+ # },
596
+ # ...
597
+ #
598
+ data = self.safe_dict(response, 'data', {})
599
+ return self.parse_tickers(data, symbols)
564
600
 
565
601
  def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
566
- timestamp = self.safe_timestamp(ticker, 'timestamp')
567
- volume = self.safe_string(ticker, 'volume')
568
- high = self.safe_string(ticker, 'high')
569
- low = self.safe_string(ticker, 'low')
570
- bid = self.safe_string(ticker, 'bid')
571
- ask = self.safe_string(ticker, 'ask')
572
- last = self.safe_string(ticker, 'last')
573
- symbol = self.safe_symbol(None, market)
602
+ marketId = self.safe_string(ticker, 'id')
603
+ symbol = self.safe_symbol(marketId, market)
574
604
  return self.safe_ticker({
575
605
  'symbol': symbol,
576
- 'timestamp': timestamp,
577
- 'datetime': self.iso8601(timestamp),
578
- 'high': high,
579
- 'low': low,
580
- 'bid': bid,
606
+ 'timestamp': None,
607
+ 'datetime': None,
608
+ 'high': self.safe_number(ticker, 'high'),
609
+ 'low': self.safe_number(ticker, 'low'),
610
+ 'bid': self.safe_number(ticker, 'bestBid'),
581
611
  'bidVolume': None,
582
- 'ask': ask,
612
+ 'ask': self.safe_number(ticker, 'bestAsk'),
583
613
  'askVolume': None,
584
614
  'vwap': None,
585
615
  'open': None,
586
- 'close': last,
587
- 'last': last,
616
+ 'close': self.safe_string(ticker, 'last'), # last indicative price per api docs(difference also seen here: https://github.com/ccxt/ccxt/actions/runs/14593899575/job/40935513901?pr=25767#step:11:456 )
588
617
  'previousClose': None,
589
- 'change': None,
590
- 'percentage': None,
618
+ 'change': self.safe_number(ticker, 'priceChange'),
619
+ 'percentage': self.safe_number(ticker, 'priceChangePercentage'),
591
620
  'average': None,
592
- 'baseVolume': volume,
593
- 'quoteVolume': None,
621
+ 'baseVolume': self.safe_string(ticker, 'volume'),
622
+ 'quoteVolume': self.safe_string(ticker, 'quoteVolume'),
594
623
  'info': ticker,
595
624
  }, market)
596
625
 
597
- def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
598
- """
599
- fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
600
- :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
601
- :param dict [params]: extra parameters specific to the exchange API endpoint
602
- :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
626
+ def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
603
627
  """
604
- self.load_markets()
605
- symbols = self.market_symbols(symbols)
606
- currencies = list(self.currencies.keys())
607
- request: dict = {
608
- 'currencies': '/'.join(currencies),
609
- }
610
- response = self.publicGetTickersCurrencies(self.extend(request, params))
611
- tickers = self.safe_value(response, 'data', [])
612
- result: dict = {}
613
- for t in range(0, len(tickers)):
614
- ticker = tickers[t]
615
- marketId = self.safe_string(ticker, 'pair')
616
- market = self.safe_market(marketId, None, ':')
617
- symbol = market['symbol']
618
- result[symbol] = self.parse_ticker(ticker, market)
619
- return self.filter_by_array_tickers(result, 'symbol', symbols)
628
+ get the list of most recent trades for a particular symbol
620
629
 
621
- def fetch_ticker(self, symbol: str, params={}) -> Ticker:
622
- """
623
- :see: https://docs.cex.io/#ticker
624
- fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
625
- :param str symbol: unified symbol of the market to fetch the ticker for
630
+ https://trade.cex.io/docs/#rest-public-api-calls-trade-history
631
+
632
+ :param str symbol: unified symbol of the market to fetch trades for
633
+ :param int [since]: timestamp in ms of the earliest trade to fetch
634
+ :param int [limit]: the maximum amount of trades to fetch
626
635
  :param dict [params]: extra parameters specific to the exchange API endpoint
627
- :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
636
+ :param int [params.until]: timestamp in ms of the latest entry
637
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
628
638
  """
629
639
  self.load_markets()
630
640
  market = self.market(symbol)
631
641
  request: dict = {
632
642
  'pair': market['id'],
633
643
  }
634
- ticker = self.publicGetTickerPair(self.extend(request, params))
635
- return self.parse_ticker(ticker, market)
644
+ if since is not None:
645
+ request['fromDateISO'] = self.iso8601(since)
646
+ until = None
647
+ until, params = self.handle_param_integer_2(params, 'until', 'till')
648
+ if until is not None:
649
+ request['toDateISO'] = self.iso8601(until)
650
+ if limit is not None:
651
+ request['pageSize'] = min(limit, 10000) # has a bug, still returns more trades
652
+ response = self.publicPostGetTradeHistory(self.extend(request, params))
653
+ #
654
+ # {
655
+ # "ok": "ok",
656
+ # "data": {
657
+ # "pageSize": "10",
658
+ # "trades": [
659
+ # {
660
+ # "tradeId": "1728630559823-0",
661
+ # "dateISO": "2024-10-11T07:09:19.823Z",
662
+ # "side": "SELL",
663
+ # "price": "60879.5",
664
+ # "amount": "0.00165962"
665
+ # },
666
+ # ... followed by older trades
667
+ #
668
+ data = self.safe_dict(response, 'data', {})
669
+ trades = self.safe_list(data, 'trades', [])
670
+ return self.parse_trades(trades, market, since, limit)
636
671
 
637
672
  def parse_trade(self, trade: dict, market: Market = None) -> Trade:
638
673
  #
639
- # fetchTrades(public)
674
+ # public fetchTrades
640
675
  #
641
- # {
642
- # "type": "sell",
643
- # "date": "1638401878",
644
- # "amount": "0.401000",
645
- # "price": "249",
646
- # "tid": "11922"
647
- # }
676
+ # {
677
+ # "tradeId": "1728630559823-0",
678
+ # "dateISO": "2024-10-11T07:09:19.823Z",
679
+ # "side": "SELL",
680
+ # "price": "60879.5",
681
+ # "amount": "0.00165962"
682
+ # },
648
683
  #
649
- timestamp = self.safe_timestamp(trade, 'date')
650
- id = self.safe_string(trade, 'tid')
651
- type = None
652
- side = self.safe_string(trade, 'type')
653
- priceString = self.safe_string(trade, 'price')
654
- amountString = self.safe_string(trade, 'amount')
684
+ dateStr = self.safe_string(trade, 'dateISO')
685
+ timestamp = self.parse8601(dateStr)
655
686
  market = self.safe_market(None, market)
656
687
  return self.safe_trade({
657
688
  'info': trade,
658
- 'id': id,
659
689
  'timestamp': timestamp,
660
690
  'datetime': self.iso8601(timestamp),
661
691
  'symbol': market['symbol'],
662
- 'type': type,
663
- 'side': side,
692
+ 'id': self.safe_string(trade, 'tradeId'),
664
693
  'order': None,
694
+ 'type': None,
665
695
  'takerOrMaker': None,
666
- 'price': priceString,
667
- 'amount': amountString,
696
+ 'side': self.safe_string_lower(trade, 'side'),
697
+ 'price': self.safe_string(trade, 'price'),
698
+ 'amount': self.safe_string(trade, 'amount'),
668
699
  'cost': None,
669
700
  'fee': None,
670
701
  }, market)
671
702
 
672
- def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
703
+ def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
673
704
  """
674
- :see: https://docs.cex.io/#trade-history
675
- get the list of most recent trades for a particular symbol
676
- :param str symbol: unified symbol of the market to fetch trades for
677
- :param int [since]: timestamp in ms of the earliest trade to fetch
678
- :param int [limit]: the maximum amount of trades to fetch
705
+ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
706
+
707
+ https://trade.cex.io/docs/#rest-public-api-calls-order-book
708
+
709
+ :param str symbol: unified symbol of the market to fetch the order book for
710
+ :param int [limit]: the maximum amount of order book entries to return
679
711
  :param dict [params]: extra parameters specific to the exchange API endpoint
680
- :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
712
+ :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
713
+ """
714
+ self.load_markets()
715
+ market = self.market(symbol)
716
+ request: dict = {
717
+ 'pair': market['id'],
718
+ }
719
+ response = self.publicPostGetOrderBook(self.extend(request, params))
720
+ #
721
+ # {
722
+ # "ok": "ok",
723
+ # "data": {
724
+ # "timestamp": "1728636922648",
725
+ # "currency1": "BTC",
726
+ # "currency2": "USDT",
727
+ # "bids": [
728
+ # [
729
+ # "60694.1",
730
+ # "13.12849761"
731
+ # ],
732
+ # [
733
+ # "60694.0",
734
+ # "0.71829244"
735
+ # ],
736
+ # ...
737
+ #
738
+ orderBook = self.safe_dict(response, 'data', {})
739
+ timestamp = self.safe_integer(orderBook, 'timestamp')
740
+ return self.parse_order_book(orderBook, market['symbol'], timestamp)
741
+
742
+ def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
743
+ """
744
+ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
745
+
746
+ https://trade.cex.io/docs/#rest-public-api-calls-candles
747
+
748
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
749
+ :param str timeframe: the length of time each candle represents
750
+ :param int [since]: timestamp in ms of the earliest candle to fetch
751
+ :param int [limit]: the maximum amount of candles to fetch
752
+ :param dict [params]: extra parameters specific to the exchange API endpoint
753
+ :param int [params.until]: timestamp in ms of the latest entry
754
+ :returns int[][]: A list of candles ordered, open, high, low, close, volume
681
755
  """
756
+ dataType = None
757
+ dataType, params = self.handle_option_and_params(params, 'fetchOHLCV', 'dataType')
758
+ if dataType is None:
759
+ raise ArgumentsRequired(self.id + ' fetchOHLCV requires a parameter "dataType" to be either "bestBid" or "bestAsk"')
682
760
  self.load_markets()
683
761
  market = self.market(symbol)
684
762
  request: dict = {
685
763
  'pair': market['id'],
764
+ 'resolution': self.timeframes[timeframe],
765
+ 'dataType': dataType,
686
766
  }
687
- response = self.publicGetTradeHistoryPair(self.extend(request, params))
688
- return self.parse_trades(response, market, since, limit)
767
+ if since is not None:
768
+ request['fromISO'] = self.iso8601(since)
769
+ until = None
770
+ until, params = self.handle_param_integer_2(params, 'until', 'till')
771
+ if until is not None:
772
+ request['toISO'] = self.iso8601(until)
773
+ elif since is None:
774
+ # exchange still requires that we provide one of them
775
+ request['toISO'] = self.iso8601(self.milliseconds())
776
+ if since is not None and until is not None and limit is not None:
777
+ raise ArgumentsRequired(self.id + ' fetchOHLCV does not support fetching candles with both a limit and since/until')
778
+ elif (since is not None or until is not None) and limit is None:
779
+ raise ArgumentsRequired(self.id + ' fetchOHLCV requires a limit parameter when fetching candles with since or until')
780
+ if limit is not None:
781
+ request['limit'] = limit
782
+ response = self.publicPostGetCandles(self.extend(request, params))
783
+ #
784
+ # {
785
+ # "ok": "ok",
786
+ # "data": [
787
+ # {
788
+ # "timestamp": "1728643320000",
789
+ # "open": "61061",
790
+ # "high": "61095.1",
791
+ # "low": "61048.5",
792
+ # "close": "61087.8",
793
+ # "volume": "0",
794
+ # "resolution": "1m",
795
+ # "isClosed": True,
796
+ # "timestampISO": "2024-10-11T10:42:00.000Z"
797
+ # },
798
+ # ...
799
+ #
800
+ data = self.safe_list(response, 'data', [])
801
+ return self.parse_ohlcvs(data, market, timeframe, since, limit)
802
+
803
+ def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
804
+ return [
805
+ self.safe_integer(ohlcv, 'timestamp'),
806
+ self.safe_number(ohlcv, 'open'),
807
+ self.safe_number(ohlcv, 'high'),
808
+ self.safe_number(ohlcv, 'low'),
809
+ self.safe_number(ohlcv, 'close'),
810
+ self.safe_number(ohlcv, 'volume'),
811
+ ]
689
812
 
690
813
  def fetch_trading_fees(self, params={}) -> TradingFees:
691
814
  """
692
- :see: https://docs.cex.io/#get-my-fee
693
815
  fetch the trading fees for multiple markets
816
+
817
+ https://trade.cex.io/docs/#rest-public-api-calls-candles
818
+
694
819
  :param dict [params]: extra parameters specific to the exchange API endpoint
695
820
  :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
696
821
  """
697
822
  self.load_markets()
698
- response = self.privatePostGetMyfee(params)
823
+ response = self.privatePostGetMyCurrentFee(params)
699
824
  #
700
- # {
701
- # "e": "get_myfee",
702
- # "ok": "ok",
703
- # "data": {
704
- # 'BTC:USD': {buy: '0.25', sell: '0.25', buyMaker: '0.15', sellMaker: "0.15"},
705
- # 'ETH:USD': {buy: '0.25', sell: '0.25', buyMaker: '0.15', sellMaker: "0.15"},
706
- # ..
707
- # }
708
- # }
825
+ # {
826
+ # "ok": "ok",
827
+ # "data": {
828
+ # "tradingFee": {
829
+ # "AI-USD": {
830
+ # "percent": "0.25"
831
+ # },
832
+ # ...
709
833
  #
710
- data = self.safe_value(response, 'data', {})
834
+ data = self.safe_dict(response, 'data', {})
835
+ fees = self.safe_dict(data, 'tradingFee', {})
836
+ return self.parse_trading_fees(fees, True)
837
+
838
+ def parse_trading_fees(self, response, useKeyAsId=False) -> TradingFees:
711
839
  result: dict = {}
840
+ keys = list(response.keys())
841
+ for i in range(0, len(keys)):
842
+ key = keys[i]
843
+ market = None
844
+ if useKeyAsId:
845
+ market = self.safe_market(key)
846
+ parsed = self.parse_trading_fee(response[key], market)
847
+ result[parsed['symbol']] = parsed
712
848
  for i in range(0, len(self.symbols)):
713
849
  symbol = self.symbols[i]
714
- market = self.market(symbol)
715
- fee = self.safe_value(data, market['id'], {})
716
- makerString = self.safe_string(fee, 'buyMaker')
717
- takerString = self.safe_string(fee, 'buy')
718
- maker = self.parse_number(Precise.string_div(makerString, '100'))
719
- taker = self.parse_number(Precise.string_div(takerString, '100'))
720
- result[symbol] = {
721
- 'info': fee,
722
- 'symbol': symbol,
723
- 'maker': maker,
724
- 'taker': taker,
725
- 'percentage': True,
726
- }
850
+ if not (symbol in result):
851
+ market = self.market(symbol)
852
+ result[symbol] = self.parse_trading_fee(response, market)
727
853
  return result
728
854
 
855
+ def parse_trading_fee(self, fee: dict, market: Market = None) -> TradingFeeInterface:
856
+ return {
857
+ 'info': fee,
858
+ 'symbol': self.safe_string(market, 'symbol'),
859
+ 'maker': self.safe_number(fee, 'percent'),
860
+ 'taker': self.safe_number(fee, 'percent'),
861
+ 'percentage': None,
862
+ 'tierBased': None,
863
+ }
864
+
865
+ def fetch_accounts(self, params={}) -> List[Account]:
866
+ self.load_markets()
867
+ response = self.privatePostGetMyAccountStatusV3(params)
868
+ #
869
+ # {
870
+ # "ok": "ok",
871
+ # "data": {
872
+ # "convertedCurrency": "USD",
873
+ # "balancesPerAccounts": {
874
+ # "": {
875
+ # "AI": {
876
+ # "balance": "0.000000",
877
+ # "balanceOnHold": "0.000000"
878
+ # },
879
+ # "USDT": {
880
+ # "balance": "0.00000000",
881
+ # "balanceOnHold": "0.00000000"
882
+ # }
883
+ # }
884
+ # }
885
+ # }
886
+ # }
887
+ #
888
+ data = self.safe_dict(response, 'data', {})
889
+ balances = self.safe_dict(data, 'balancesPerAccounts', {})
890
+ arrays = self.to_array(balances)
891
+ return self.parse_accounts(arrays, params)
892
+
893
+ def parse_account(self, account: dict) -> Account:
894
+ return {
895
+ 'id': None,
896
+ 'type': None,
897
+ 'code': None,
898
+ 'info': account,
899
+ }
900
+
901
+ def fetch_balance(self, params={}) -> Balances:
902
+ """
903
+ query for balance and get the amount of funds available for trading or funds locked in orders
904
+
905
+ https://trade.cex.io/docs/#rest-private-api-calls-account-status-v3
906
+
907
+ :param dict [params]: extra parameters specific to the exchange API endpoint
908
+ :param dict [params.method]: 'privatePostGetMyWalletBalance' or 'privatePostGetMyAccountStatusV3'
909
+ :param dict [params.account]: in case 'privatePostGetMyAccountStatusV3' is chosen, self can specify the account name(default is empty string)
910
+ :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
911
+ """
912
+ accountName = None
913
+ accountName, params = self.handle_param_string(params, 'account', '') # default is empty string
914
+ method = None
915
+ method, params = self.handle_param_string(params, 'method', 'privatePostGetMyWalletBalance')
916
+ accountBalance = None
917
+ if method == 'privatePostGetMyAccountStatusV3':
918
+ response = self.privatePostGetMyAccountStatusV3(params)
919
+ #
920
+ # {
921
+ # "ok": "ok",
922
+ # "data": {
923
+ # "convertedCurrency": "USD",
924
+ # "balancesPerAccounts": {
925
+ # "": {
926
+ # "AI": {
927
+ # "balance": "0.000000",
928
+ # "balanceOnHold": "0.000000"
929
+ # },
930
+ # ....
931
+ #
932
+ data = self.safe_dict(response, 'data', {})
933
+ balances = self.safe_dict(data, 'balancesPerAccounts', {})
934
+ accountBalance = self.safe_dict(balances, accountName, {})
935
+ else:
936
+ response = self.privatePostGetMyWalletBalance(params)
937
+ #
938
+ # {
939
+ # "ok": "ok",
940
+ # "data": {
941
+ # "AI": {
942
+ # "balance": "25.606429"
943
+ # },
944
+ # "USDT": {
945
+ # "balance": "7.935449"
946
+ # },
947
+ # ...
948
+ #
949
+ accountBalance = self.safe_dict(response, 'data', {})
950
+ return self.parse_balance(accountBalance)
951
+
952
+ def parse_balance(self, response) -> Balances:
953
+ result: dict = {
954
+ 'info': response,
955
+ }
956
+ keys = list(response.keys())
957
+ for i in range(0, len(keys)):
958
+ key = keys[i]
959
+ balance = self.safe_dict(response, key, {})
960
+ code = self.safe_currency_code(key)
961
+ account: dict = {
962
+ 'used': self.safe_string(balance, 'balanceOnHold'),
963
+ 'total': self.safe_string(balance, 'balance'),
964
+ }
965
+ result[code] = account
966
+ return self.safe_balance(result)
967
+
968
+ def fetch_orders_by_status(self, status: str, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
969
+ """
970
+ fetches information on multiple orders made by the user
971
+
972
+ https://trade.cex.io/docs/#rest-private-api-calls-orders
973
+
974
+ :param str status: order status to fetch for
975
+ :param str symbol: unified market symbol of the market orders were made in
976
+ :param int [since]: the earliest time in ms to fetch orders for
977
+ :param int [limit]: the maximum number of order structures to retrieve
978
+ :param dict [params]: extra parameters specific to the exchange API endpoint
979
+ :param int [params.until]: timestamp in ms of the latest entry
980
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
981
+ """
982
+ self.load_markets()
983
+ request: dict = {}
984
+ isClosedOrders = (status == 'closed')
985
+ if isClosedOrders:
986
+ request['archived'] = True
987
+ market = None
988
+ if symbol is not None:
989
+ market = self.market(symbol)
990
+ request['pair'] = market['id']
991
+ if limit is not None:
992
+ request['pageSize'] = limit
993
+ if since is not None:
994
+ request['serverCreateTimestampFrom'] = since
995
+ elif isClosedOrders:
996
+ # exchange requires a `since` parameter for closed orders, so set default to allowed 365
997
+ request['serverCreateTimestampFrom'] = self.milliseconds() - 364 * 24 * 60 * 60 * 1000
998
+ until = None
999
+ until, params = self.handle_param_integer_2(params, 'until', 'till')
1000
+ if until is not None:
1001
+ request['serverCreateTimestampTo'] = until
1002
+ response = self.privatePostGetMyOrders(self.extend(request, params))
1003
+ #
1004
+ # if called without `pair`
1005
+ #
1006
+ # {
1007
+ # "ok": "ok",
1008
+ # "data": [
1009
+ # {
1010
+ # "orderId": "1313003",
1011
+ # "clientOrderId": "037F0AFEB93A",
1012
+ # "clientId": "up421412345",
1013
+ # "accountId": null,
1014
+ # "status": "FILLED",
1015
+ # "statusIsFinal": True,
1016
+ # "currency1": "AI",
1017
+ # "currency2": "USDT",
1018
+ # "side": "BUY",
1019
+ # "orderType": "Market",
1020
+ # "timeInForce": "IOC",
1021
+ # "comment": null,
1022
+ # "rejectCode": null,
1023
+ # "rejectReason": null,
1024
+ # "initialOnHoldAmountCcy1": null,
1025
+ # "initialOnHoldAmountCcy2": "10.23456700",
1026
+ # "executedAmountCcy1": "25.606429",
1027
+ # "executedAmountCcy2": "10.20904439",
1028
+ # "requestedAmountCcy1": null,
1029
+ # "requestedAmountCcy2": "10.20904439",
1030
+ # "originalAmountCcy2": "10.23456700",
1031
+ # "feeAmount": "0.02552261",
1032
+ # "feeCurrency": "USDT",
1033
+ # "price": null,
1034
+ # "averagePrice": "0.3986",
1035
+ # "clientCreateTimestamp": "1728474625320",
1036
+ # "serverCreateTimestamp": "1728474624956",
1037
+ # "lastUpdateTimestamp": "1728474628015",
1038
+ # "expireTime": null,
1039
+ # "effectiveTime": null
1040
+ # },
1041
+ # ...
1042
+ #
1043
+ data = self.safe_list(response, 'data', [])
1044
+ return self.parse_orders(data, market, since, limit)
1045
+
1046
+ def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1047
+ """
1048
+
1049
+ https://trade.cex.io/docs/#rest-private-api-calls-orders
1050
+
1051
+ fetches information on multiple canceled orders made by the user
1052
+ :param str symbol: unified market symbol of the market orders were made in
1053
+ :param int [since]: timestamp in ms of the earliest order, default is None
1054
+ :param int [limit]: max number of orders to return, default is None
1055
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1056
+ :returns dict: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1057
+ """
1058
+ return self.fetch_orders_by_status('closed', symbol, since, limit, params)
1059
+
1060
+ def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1061
+ """
1062
+
1063
+ https://trade.cex.io/docs/#rest-private-api-calls-orders
1064
+
1065
+ fetches information on multiple canceled orders made by the user
1066
+ :param str symbol: unified market symbol of the market orders were made in
1067
+ :param int [since]: timestamp in ms of the earliest order, default is None
1068
+ :param int [limit]: max number of orders to return, default is None
1069
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1070
+ :returns dict: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1071
+ """
1072
+ return self.fetch_orders_by_status('open', symbol, since, limit, params)
1073
+
1074
+ def fetch_open_order(self, id: str, symbol: Str = None, params={}):
1075
+ """
1076
+ fetches information on an open order made by the user
1077
+
1078
+ https://trade.cex.io/docs/#rest-private-api-calls-orders
1079
+
1080
+ :param str id: order id
1081
+ :param str [symbol]: unified symbol of the market the order was made in
1082
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1083
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1084
+ """
1085
+ self.load_markets()
1086
+ request: dict = {
1087
+ 'orderId': int(id),
1088
+ }
1089
+ result = self.fetch_open_orders(symbol, None, None, self.extend(request, params))
1090
+ return result[0]
1091
+
1092
+ def fetch_closed_order(self, id: str, symbol: Str = None, params={}):
1093
+ """
1094
+ fetches information on an closed order made by the user
1095
+
1096
+ https://trade.cex.io/docs/#rest-private-api-calls-orders
1097
+
1098
+ :param str id: order id
1099
+ :param str [symbol]: unified symbol of the market the order was made in
1100
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1101
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1102
+ """
1103
+ self.load_markets()
1104
+ request: dict = {
1105
+ 'orderId': int(id),
1106
+ }
1107
+ result = self.fetch_closed_orders(symbol, None, None, self.extend(request, params))
1108
+ return result[0]
1109
+
1110
+ def parse_order_status(self, status: Str):
1111
+ statuses: dict = {
1112
+ 'PENDING_NEW': 'open',
1113
+ 'NEW': 'open',
1114
+ 'PARTIALLY_FILLED': 'open',
1115
+ 'FILLED': 'closed',
1116
+ 'EXPIRED': 'expired',
1117
+ 'REJECTED': 'rejected',
1118
+ 'PENDING_CANCEL': 'canceling',
1119
+ 'CANCELLED': 'canceled',
1120
+ }
1121
+ return self.safe_string(statuses, status, status)
1122
+
1123
+ def parse_order(self, order: dict, market: Market = None) -> Order:
1124
+ #
1125
+ # "orderId": "1313003",
1126
+ # "clientOrderId": "037F0AFEB93A",
1127
+ # "clientId": "up421412345",
1128
+ # "accountId": null,
1129
+ # "status": "FILLED",
1130
+ # "statusIsFinal": True,
1131
+ # "currency1": "AI",
1132
+ # "currency2": "USDT",
1133
+ # "side": "BUY",
1134
+ # "orderType": "Market",
1135
+ # "timeInForce": "IOC",
1136
+ # "comment": null,
1137
+ # "rejectCode": null,
1138
+ # "rejectReason": null,
1139
+ # "initialOnHoldAmountCcy1": null,
1140
+ # "initialOnHoldAmountCcy2": "10.23456700",
1141
+ # "executedAmountCcy1": "25.606429",
1142
+ # "executedAmountCcy2": "10.20904439",
1143
+ # "requestedAmountCcy1": null,
1144
+ # "requestedAmountCcy2": "10.20904439",
1145
+ # "originalAmountCcy2": "10.23456700",
1146
+ # "feeAmount": "0.02552261",
1147
+ # "feeCurrency": "USDT",
1148
+ # "price": null,
1149
+ # "averagePrice": "0.3986",
1150
+ # "clientCreateTimestamp": "1728474625320",
1151
+ # "serverCreateTimestamp": "1728474624956",
1152
+ # "lastUpdateTimestamp": "1728474628015",
1153
+ # "expireTime": null,
1154
+ # "effectiveTime": null
1155
+ #
1156
+ currency1 = self.safe_string(order, 'currency1')
1157
+ currency2 = self.safe_string(order, 'currency2')
1158
+ marketId = None
1159
+ if currency1 is not None and currency2 is not None:
1160
+ marketId = currency1 + '-' + currency2
1161
+ market = self.safe_market(marketId, market)
1162
+ symbol = market['symbol']
1163
+ status = self.parse_order_status(self.safe_string(order, 'status'))
1164
+ fee = {}
1165
+ feeAmount = self.safe_number(order, 'feeAmount')
1166
+ if feeAmount is not None:
1167
+ currencyId = self.safe_string(order, 'feeCurrency')
1168
+ feeCode = self.safe_currency_code(currencyId)
1169
+ fee['currency'] = feeCode
1170
+ fee['cost'] = feeAmount
1171
+ timestamp = self.safe_integer(order, 'serverCreateTimestamp')
1172
+ requestedBase = self.safe_number(order, 'requestedAmountCcy1')
1173
+ executedBase = self.safe_number(order, 'executedAmountCcy1')
1174
+ # requestedQuote = self.safe_number(order, 'requestedAmountCcy2')
1175
+ executedQuote = self.safe_number(order, 'executedAmountCcy2')
1176
+ return self.safe_order({
1177
+ 'id': self.safe_string(order, 'orderId'),
1178
+ 'clientOrderId': self.safe_string(order, 'clientOrderId'),
1179
+ 'timestamp': timestamp,
1180
+ 'datetime': self.iso8601(timestamp),
1181
+ 'lastUpdateTimestamp': self.safe_integer(order, 'lastUpdateTimestamp'),
1182
+ 'lastTradeTimestamp': None,
1183
+ 'symbol': symbol,
1184
+ 'type': self.safe_string_lower(order, 'orderType'),
1185
+ 'timeInForce': self.safe_string(order, 'timeInForce'),
1186
+ 'postOnly': None,
1187
+ 'side': self.safe_string_lower(order, 'side'),
1188
+ 'price': self.safe_number(order, 'price'),
1189
+ 'triggerPrice': self.safe_number(order, 'stopPrice'),
1190
+ 'amount': requestedBase,
1191
+ 'cost': executedQuote,
1192
+ 'average': self.safe_number(order, 'averagePrice'),
1193
+ 'filled': executedBase,
1194
+ 'remaining': None,
1195
+ 'status': status,
1196
+ 'fee': fee,
1197
+ 'trades': None,
1198
+ 'info': order,
1199
+ }, market)
1200
+
729
1201
  def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
730
1202
  """
731
- :see: https://docs.cex.io/#place-order
732
1203
  create a trade order
733
- :see: https://cex.io/rest-api#place-order
1204
+
1205
+ https://trade.cex.io/docs/#rest-private-api-calls-new-order
1206
+
734
1207
  :param str symbol: unified symbol of the market to create an order in
735
1208
  :param str type: 'market' or 'limit'
736
1209
  :param str side: 'buy' or 'sell'
737
1210
  :param float amount: how much of currency you want to trade in units of base currency
738
- :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
1211
+ :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
739
1212
  :param dict [params]: extra parameters specific to the exchange API endpoint
740
- :param float [params.cost]: the quote quantity that can be used alternative for the amount for market buy orders
1213
+ :param str [params.accountId]: account-id to use(default is empty string)
1214
+ :param float [params.triggerPrice]: the price at which a trigger order is triggered at
741
1215
  :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
742
1216
  """
1217
+ accountId = None
1218
+ accountId, params = self.handle_option_and_params(params, 'createOrder', 'accountId')
1219
+ if accountId is None:
1220
+ raise ArgumentsRequired(self.id + ' createOrder() : API trading is now allowed from main account, set params["accountId"] or .options["createOrder"]["accountId"] to the name of your sub-account')
743
1221
  self.load_markets()
744
1222
  market = self.market(symbol)
745
1223
  request: dict = {
746
- 'pair': market['id'],
747
- 'type': side,
1224
+ 'clientOrderId': self.uuid(),
1225
+ 'currency1': market['baseId'],
1226
+ 'currency2': market['quoteId'],
1227
+ 'accountId': accountId,
1228
+ 'orderType': self.capitalize(type.lower()),
1229
+ 'side': side.upper(),
1230
+ 'timestamp': self.milliseconds(),
1231
+ 'amountCcy1': self.amount_to_precision(symbol, amount),
748
1232
  }
749
- # for market buy it requires the amount of quote currency to spend
750
- if (type == 'market') and (side == 'buy'):
751
- quoteAmount = None
752
- createMarketBuyOrderRequiresPrice = True
753
- createMarketBuyOrderRequiresPrice, params = self.handle_option_and_params(params, 'createOrder', 'createMarketBuyOrderRequiresPrice', True)
754
- cost = self.safe_string(params, 'cost')
755
- params = self.omit(params, 'cost')
756
- if cost is not None:
757
- quoteAmount = self.cost_to_precision(symbol, cost)
758
- elif createMarketBuyOrderRequiresPrice:
759
- if price is None:
760
- raise InvalidOrder(self.id + ' createOrder() requires the price argument for market buy orders to calculate the total cost to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to False and pass the cost to spend in the amount argument')
761
- else:
762
- amountString = self.number_to_string(amount)
763
- priceString = self.number_to_string(price)
764
- costRequest = Precise.string_mul(amountString, priceString)
765
- quoteAmount = self.cost_to_precision(symbol, costRequest)
766
- else:
767
- quoteAmount = self.cost_to_precision(symbol, amount)
768
- request['amount'] = quoteAmount
769
- else:
770
- request['amount'] = self.amount_to_precision(symbol, amount)
1233
+ timeInForce = None
1234
+ timeInForce, params = self.handle_option_and_params(params, 'createOrder', 'timeInForce', 'GTC')
771
1235
  if type == 'limit':
772
- request['price'] = self.number_to_string(price)
773
- else:
774
- request['order_type'] = type
775
- response = self.privatePostPlaceOrderPair(self.extend(request, params))
1236
+ request['price'] = self.price_to_precision(symbol, price)
1237
+ request['timeInForce'] = timeInForce
1238
+ triggerPrice = None
1239
+ triggerPrice, params = self.handle_param_string(params, 'triggerPrice')
1240
+ if triggerPrice is not None:
1241
+ request['type'] = 'Stop Limit'
1242
+ request['stopPrice'] = triggerPrice
1243
+ response = self.privatePostDoMyNewOrder(self.extend(request, params))
776
1244
  #
777
- # {
778
- # "id": "12978363524",
779
- # "time": 1586610022259,
780
- # "type": "buy",
781
- # "price": "0.033934",
782
- # "amount": "0.10722802",
783
- # "pending": "0.10722802",
784
- # "complete": False
785
- # }
1245
+ # on success
786
1246
  #
787
- placedAmount = self.safe_string(response, 'amount')
788
- remaining = self.safe_string(response, 'pending')
789
- timestamp = self.safe_value(response, 'time')
790
- complete = self.safe_value(response, 'complete')
791
- status = 'closed' if complete else 'open'
792
- filled = None
793
- if (placedAmount is not None) and (remaining is not None):
794
- filled = Precise.string_max(Precise.string_sub(placedAmount, remaining), '0')
795
- return self.safe_order({
796
- 'id': self.safe_string(response, 'id'),
797
- 'info': response,
798
- 'clientOrderId': None,
799
- 'timestamp': timestamp,
800
- 'datetime': self.iso8601(timestamp),
801
- 'lastTradeTimestamp': None,
802
- 'type': type,
803
- 'side': self.safe_string(response, 'type'),
804
- 'symbol': market['symbol'],
805
- 'status': status,
806
- 'price': self.safe_string(response, 'price'),
807
- 'amount': placedAmount,
808
- 'cost': None,
809
- 'average': None,
810
- 'remaining': remaining,
811
- 'filled': filled,
812
- 'fee': None,
813
- 'trades': None,
814
- })
1247
+ # {
1248
+ # "ok": "ok",
1249
+ # "data": {
1250
+ # "messageType": "executionReport",
1251
+ # "clientId": "up132245425",
1252
+ # "orderId": "1318485",
1253
+ # "clientOrderId": "b5b6cd40-154c-4c1c-bd51-4a442f3d50b9",
1254
+ # "accountId": "sub1",
1255
+ # "status": "FILLED",
1256
+ # "currency1": "LTC",
1257
+ # "currency2": "USDT",
1258
+ # "side": "BUY",
1259
+ # "executedAmountCcy1": "0.23000000",
1260
+ # "executedAmountCcy2": "15.09030000",
1261
+ # "requestedAmountCcy1": "0.23000000",
1262
+ # "requestedAmountCcy2": null,
1263
+ # "orderType": "Market",
1264
+ # "timeInForce": null,
1265
+ # "comment": null,
1266
+ # "executionType": "Trade",
1267
+ # "executionId": "1726747124624_101_41116",
1268
+ # "transactTime": "2024-10-15T15:08:12.794Z",
1269
+ # "expireTime": null,
1270
+ # "effectiveTime": null,
1271
+ # "averagePrice": "65.61",
1272
+ # "lastQuantity": "0.23000000",
1273
+ # "lastAmountCcy1": "0.23000000",
1274
+ # "lastAmountCcy2": "15.09030000",
1275
+ # "lastPrice": "65.61",
1276
+ # "feeAmount": "0.03772575",
1277
+ # "feeCurrency": "USDT",
1278
+ # "clientCreateTimestamp": "1729004892014",
1279
+ # "serverCreateTimestamp": "1729004891628",
1280
+ # "lastUpdateTimestamp": "1729004892786"
1281
+ # }
1282
+ # }
1283
+ #
1284
+ # on failure, there are extra fields
1285
+ #
1286
+ # "status": "REJECTED",
1287
+ # "requestedAmountCcy1": null,
1288
+ # "orderRejectReason": "{\\" code \\ ":405,\\" reason \\ ":\\" Either AmountCcy1(OrderQty)or AmountCcy2(CashOrderQty)should be specified for market order not both \\ "}",
1289
+ # "rejectCode": 405,
1290
+ # "rejectReason": "Either AmountCcy1(OrderQty) or AmountCcy2(CashOrderQty) should be specified for market order not both",
1291
+ #
1292
+ data = self.safe_dict(response, 'data')
1293
+ return self.parse_order(data, market)
815
1294
 
816
1295
  def cancel_order(self, id: str, symbol: Str = None, params={}):
817
1296
  """
818
- :see: https://docs.cex.io/#cancel-order
819
1297
  cancels an open order
1298
+
1299
+ https://trade.cex.io/docs/#rest-private-api-calls-cancel-order
1300
+
820
1301
  :param str id: order id
821
- :param str symbol: not used by cex cancelOrder()
1302
+ :param str symbol: unified symbol of the market the order was made in
822
1303
  :param dict [params]: extra parameters specific to the exchange API endpoint
823
1304
  :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
824
1305
  """
825
1306
  self.load_markets()
826
1307
  request: dict = {
827
- 'id': id,
1308
+ 'orderId': int(id),
1309
+ 'cancelRequestId': 'c_' + str((self.milliseconds())),
1310
+ 'timestamp': self.milliseconds(),
828
1311
  }
829
- response = self.privatePostCancelOrder(self.extend(request, params))
830
- # 'true'
831
- return self.extend(self.parse_order({}), {'info': response, 'type': None, 'id': id, 'status': 'canceled'})
1312
+ response = self.privatePostDoCancelMyOrder(self.extend(request, params))
1313
+ #
1314
+ # {"ok":"ok","data":{}}
1315
+ #
1316
+ data = self.safe_dict(response, 'data', {})
1317
+ return self.parse_order(data)
832
1318
 
833
1319
  def cancel_all_orders(self, symbol: Str = None, params={}):
834
1320
  """
835
- :see: https://docs.cex.io/#cancel-all-orders-for-given-pair
836
1321
  cancel all open orders in a market
837
- :param str symbol: unified market symbol of the market to cancel orders in
838
- :param dict [params]: extra parameters specific to the cex api endpoint
839
- :param str [params.marginMode]: 'cross' or 'isolated', for spot margin trading
1322
+
1323
+ https://trade.cex.io/docs/#rest-private-api-calls-cancel-all-orders
1324
+
1325
+ :param str symbol: alpaca cancelAllOrders cannot setting symbol, it will cancel all open orders
1326
+ :param dict [params]: extra parameters specific to the exchange API endpoint
840
1327
  :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
841
1328
  """
842
- if symbol is None:
843
- raise ArgumentsRequired(self.id + ' cancelAllOrders requires a symbol.')
844
1329
  self.load_markets()
845
- market = self.market(symbol)
846
- request: dict = {
847
- 'pair': market['id'],
848
- }
849
- orders = self.privatePostCancelOrdersPair(self.extend(request, params))
1330
+ response = self.privatePostDoCancelAllOrders(params)
850
1331
  #
851
- # {
852
- # "e":"cancel_orders",
853
- # "ok":"ok",
854
- # "data":[
855
- # ]
856
- # }
1332
+ # {
1333
+ # "ok": "ok",
1334
+ # "data": {
1335
+ # "clientOrderIds": [
1336
+ # "3AF77B67109F"
1337
+ # ]
1338
+ # }
1339
+ # }
857
1340
  #
858
- return orders
859
-
860
- def parse_order(self, order: dict, market: Market = None) -> Order:
861
- # Depending on the call, 'time' can be a unix int, unix string or ISO string
862
- # Yes, really
863
- timestamp = self.safe_value(order, 'time')
864
- if isinstance(timestamp, str) and timestamp.find('T') >= 0:
865
- # ISO8601 string
866
- timestamp = self.parse8601(timestamp)
867
- elif timestamp is not None:
868
- # either integer or string integer
869
- timestamp = int(timestamp)
870
- symbol = None
871
- baseId = self.safe_string(order, 'symbol1')
872
- quoteId = self.safe_string(order, 'symbol2')
873
- if market is None and baseId is not None and quoteId is not None:
874
- base = self.safe_currency_code(baseId)
875
- quote = self.safe_currency_code(quoteId)
876
- if (base is not None) and (quote is not None):
877
- symbol = base + '/' + quote
878
- if symbol in self.markets:
879
- market = self.market(symbol)
880
- status = self.parse_order_status(self.safe_string(order, 'status'))
881
- price = self.safe_string(order, 'price')
882
- amount = self.omit_zero(self.safe_string(order, 'amount'))
883
- # sell orders can have a negative amount
884
- # https://github.com/ccxt/ccxt/issues/5338
885
- if amount is not None:
886
- amount = Precise.string_abs(amount)
887
- elif market is not None:
888
- amountKey = 'a:' + market['base'] + 'cds:'
889
- amount = Precise.string_abs(self.safe_string(order, amountKey))
890
- remaining = self.safe_string_2(order, 'pending', 'remains')
891
- filled = Precise.string_sub(amount, remaining)
892
- fee = None
893
- cost = None
894
- if market is not None:
895
- symbol = market['symbol']
896
- taCost = self.safe_string(order, 'ta:' + market['quote'])
897
- ttaCost = self.safe_string(order, 'tta:' + market['quote'])
898
- cost = Precise.string_add(taCost, ttaCost)
899
- baseFee = 'fa:' + market['base']
900
- baseTakerFee = 'tfa:' + market['base']
901
- quoteFee = 'fa:' + market['quote']
902
- quoteTakerFee = 'tfa:' + market['quote']
903
- feeRate = self.safe_string(order, 'tradingFeeMaker')
904
- if not feeRate:
905
- feeRate = self.safe_string(order, 'tradingFeeTaker', feeRate)
906
- if feeRate:
907
- feeRate = Precise.string_div(feeRate, '100') # convert to mathematically-correct percentage coefficients: 1.0 = 100%
908
- if (baseFee in order) or (baseTakerFee in order):
909
- baseFeeCost = self.safe_number_2(order, baseFee, baseTakerFee)
910
- fee = {
911
- 'currency': market['base'],
912
- 'rate': self.parse_number(feeRate),
913
- 'cost': baseFeeCost,
914
- }
915
- elif (quoteFee in order) or (quoteTakerFee in order):
916
- quoteFeeCost = self.safe_number_2(order, quoteFee, quoteTakerFee)
917
- fee = {
918
- 'currency': market['quote'],
919
- 'rate': self.parse_number(feeRate),
920
- 'cost': quoteFeeCost,
921
- }
922
- if not cost:
923
- cost = Precise.string_mul(price, filled)
924
- side = self.safe_string(order, 'type')
925
- trades = None
926
- orderId = self.safe_string(order, 'id')
927
- if 'vtx' in order:
928
- trades = []
929
- for i in range(0, len(order['vtx'])):
930
- item = order['vtx'][i]
931
- tradeSide = self.safe_string(item, 'type')
932
- if tradeSide == 'cancel':
933
- # looks like self might represent the cancelled part of an order
934
- # {"id": "4426729543",
935
- # "type": "cancel",
936
- # "time": "2017-09-22T00:24:30.476Z",
937
- # "user": "up106404164",
938
- # "c": "user:up106404164:a:BCH",
939
- # "d": "order:4426728375:a:BCH",
940
- # "a": "0.09935956",
941
- # "amount": "0.09935956",
942
- # "balance": "0.42580261",
943
- # "symbol": "BCH",
944
- # "order": "4426728375",
945
- # "buy": null,
946
- # "sell": null,
947
- # "pair": null,
948
- # "pos": null,
949
- # "cs": "0.42580261",
950
- # "ds": 0}
951
- continue
952
- tradePrice = self.safe_string(item, 'price')
953
- if tradePrice is None:
954
- # self represents the order
955
- # {
956
- # "a": "0.47000000",
957
- # "c": "user:up106404164:a:EUR",
958
- # "d": "order:6065499239:a:EUR",
959
- # "cs": "1432.93",
960
- # "ds": "476.72",
961
- # "id": "6065499249",
962
- # "buy": null,
963
- # "pos": null,
964
- # "pair": null,
965
- # "sell": null,
966
- # "time": "2018-04-22T13:07:22.152Z",
967
- # "type": "buy",
968
- # "user": "up106404164",
969
- # "order": "6065499239",
970
- # "amount": "-715.97000000",
971
- # "symbol": "EUR",
972
- # "balance": "1432.93000000"}
973
- continue
974
- # todo: deal with these
975
- if tradeSide == 'costsNothing':
976
- continue
977
- # --
978
- # if side != tradeSide:
979
- # raise Error(json.dumps(order, null, 2))
980
- # if orderId != item['order']:
981
- # raise Error(json.dumps(order, null, 2))
982
- # --
983
- # partial buy trade
984
- # {
985
- # "a": "0.01589885",
986
- # "c": "user:up106404164:a:BTC",
987
- # "d": "order:6065499239:a:BTC",
988
- # "cs": "0.36300000",
989
- # "ds": 0,
990
- # "id": "6067991213",
991
- # "buy": "6065499239",
992
- # "pos": null,
993
- # "pair": null,
994
- # "sell": "6067991206",
995
- # "time": "2018-04-22T23:09:11.773Z",
996
- # "type": "buy",
997
- # "user": "up106404164",
998
- # "order": "6065499239",
999
- # "price": 7146.5,
1000
- # "amount": "0.01589885",
1001
- # "symbol": "BTC",
1002
- # "balance": "0.36300000",
1003
- # "symbol2": "EUR",
1004
- # "fee_amount": "0.19"}
1005
- # --
1006
- # trade with zero amount, but non-zero fee
1007
- # {
1008
- # "a": "0.00000000",
1009
- # "c": "user:up106404164:a:EUR",
1010
- # "d": "order:5840654423:a:EUR",
1011
- # "cs": 559744,
1012
- # "ds": 0,
1013
- # "id": "5840654429",
1014
- # "buy": "5807238573",
1015
- # "pos": null,
1016
- # "pair": null,
1017
- # "sell": "5840654423",
1018
- # "time": "2018-03-15T03:20:14.010Z",
1019
- # "type": "sell",
1020
- # "user": "up106404164",
1021
- # "order": "5840654423",
1022
- # "price": 730,
1023
- # "amount": "0.00000000",
1024
- # "symbol": "EUR",
1025
- # "balance": "5597.44000000",
1026
- # "symbol2": "BCH",
1027
- # "fee_amount": "0.01"}
1028
- # --
1029
- # trade which should have an amount of exactly 0.002BTC
1030
- # {
1031
- # "a": "16.70000000",
1032
- # "c": "user:up106404164:a:GBP",
1033
- # "d": "order:9927386681:a:GBP",
1034
- # "cs": "86.90",
1035
- # "ds": 0,
1036
- # "id": "9927401610",
1037
- # "buy": "9927401601",
1038
- # "pos": null,
1039
- # "pair": null,
1040
- # "sell": "9927386681",
1041
- # "time": "2019-08-21T15:25:37.777Z",
1042
- # "type": "sell",
1043
- # "user": "up106404164",
1044
- # "order": "9927386681",
1045
- # "price": 8365,
1046
- # "amount": "16.70000000",
1047
- # "office": "UK",
1048
- # "symbol": "GBP",
1049
- # "balance": "86.90000000",
1050
- # "symbol2": "BTC",
1051
- # "fee_amount": "0.03"
1052
- # }
1053
- tradeTimestamp = self.parse8601(self.safe_string(item, 'time'))
1054
- tradeAmount = self.safe_string(item, 'amount')
1055
- feeCost = self.safe_string(item, 'fee_amount')
1056
- absTradeAmount = Precise.string_abs(tradeAmount)
1057
- tradeCost = None
1058
- if tradeSide == 'sell':
1059
- tradeCost = absTradeAmount
1060
- absTradeAmount = Precise.string_div(Precise.string_add(feeCost, tradeCost), tradePrice)
1061
- else:
1062
- tradeCost = Precise.string_mul(absTradeAmount, tradePrice)
1063
- trades.append({
1064
- 'id': self.safe_string(item, 'id'),
1065
- 'timestamp': tradeTimestamp,
1066
- 'datetime': self.iso8601(tradeTimestamp),
1067
- 'order': orderId,
1068
- 'symbol': symbol,
1069
- 'price': self.parse_number(tradePrice),
1070
- 'amount': self.parse_number(absTradeAmount),
1071
- 'cost': self.parse_number(tradeCost),
1072
- 'side': tradeSide,
1073
- 'fee': {
1074
- 'cost': self.parse_number(feeCost),
1075
- 'currency': market['quote'],
1076
- },
1077
- 'info': item,
1078
- 'type': None,
1079
- 'takerOrMaker': None,
1080
- })
1081
- return self.safe_order({
1082
- 'info': order,
1083
- 'id': orderId,
1084
- 'clientOrderId': None,
1085
- 'datetime': self.iso8601(timestamp),
1086
- 'timestamp': timestamp,
1087
- 'lastTradeTimestamp': None,
1088
- 'status': status,
1089
- 'symbol': symbol,
1090
- 'type': 'market' if (price is None) else 'limit',
1091
- 'timeInForce': None,
1092
- 'postOnly': None,
1093
- 'side': side,
1094
- 'price': price,
1095
- 'stopPrice': None,
1096
- 'triggerPrice': None,
1097
- 'cost': cost,
1098
- 'amount': amount,
1099
- 'filled': filled,
1100
- 'remaining': remaining,
1101
- 'trades': trades,
1102
- 'fee': fee,
1103
- 'average': None,
1104
- })
1341
+ data = self.safe_dict(response, 'data', {})
1342
+ ids = self.safe_list(data, 'clientOrderIds', [])
1343
+ orders = []
1344
+ for i in range(0, len(ids)):
1345
+ id = ids[i]
1346
+ orders.append({'clientOrderId': id})
1347
+ return self.parse_orders(orders)
1105
1348
 
1106
- def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1349
+ def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[LedgerEntry]:
1107
1350
  """
1108
- :see: https://docs.cex.io/#open-orders
1109
- fetch all unfilled currently open orders
1110
- :param str symbol: unified market symbol
1111
- :param int [since]: the earliest time in ms to fetch open orders for
1112
- :param int [limit]: the maximum number of open orders structures to retrieve
1351
+ fetch the history of changes, actions done by the user or operations that altered the balance of the user
1352
+
1353
+ https://trade.cex.io/docs/#rest-private-api-calls-transaction-history
1354
+
1355
+ :param str [code]: unified currency code
1356
+ :param int [since]: timestamp in ms of the earliest ledger entry
1357
+ :param int [limit]: max number of ledger entries to return
1113
1358
  :param dict [params]: extra parameters specific to the exchange API endpoint
1114
- :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1359
+ :param int [params.until]: timestamp in ms of the latest ledger entry
1360
+ :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
1115
1361
  """
1116
1362
  self.load_markets()
1363
+ currency = None
1117
1364
  request: dict = {}
1118
- market = None
1119
- orders = None
1120
- if symbol is not None:
1121
- market = self.market(symbol)
1122
- request['pair'] = market['id']
1123
- orders = self.privatePostOpenOrdersPair(self.extend(request, params))
1365
+ if code is not None:
1366
+ currency = self.currency(code)
1367
+ request['currency'] = currency['id']
1368
+ if since is not None:
1369
+ request['dateFrom'] = since
1370
+ if limit is not None:
1371
+ request['pageSize'] = limit
1372
+ until = None
1373
+ until, params = self.handle_param_integer_2(params, 'until', 'till')
1374
+ if until is not None:
1375
+ request['dateTo'] = until
1376
+ response = self.privatePostGetMyTransactionHistory(self.extend(request, params))
1377
+ #
1378
+ # {
1379
+ # "ok": "ok",
1380
+ # "data": [
1381
+ # {
1382
+ # "transactionId": "30367722",
1383
+ # "timestamp": "2024-10-14T14:08:49.987Z",
1384
+ # "accountId": "",
1385
+ # "type": "withdraw",
1386
+ # "amount": "-12.39060600",
1387
+ # "details": "Withdraw fundingId=1235039 clientId=up421412345 walletTxId=76337154166",
1388
+ # "currency": "USDT"
1389
+ # },
1390
+ # ...
1391
+ #
1392
+ data = self.safe_list(response, 'data', [])
1393
+ return self.parse_ledger(data, currency, since, limit)
1394
+
1395
+ def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
1396
+ amount = self.safe_string(item, 'amount')
1397
+ direction = None
1398
+ if Precise.string_le(amount, '0'):
1399
+ direction = 'out'
1400
+ amount = Precise.string_mul('-1', amount)
1124
1401
  else:
1125
- orders = self.privatePostOpenOrders(self.extend(request, params))
1126
- for i in range(0, len(orders)):
1127
- orders[i] = self.extend(orders[i], {'status': 'open'})
1128
- return self.parse_orders(orders, market, since, limit)
1402
+ direction = 'in'
1403
+ currencyId = self.safe_string(item, 'currency')
1404
+ currency = self.safe_currency(currencyId, currency)
1405
+ code = self.safe_currency_code(currencyId, currency)
1406
+ timestampString = self.safe_string(item, 'timestamp')
1407
+ timestamp = self.parse8601(timestampString)
1408
+ type = self.safe_string(item, 'type')
1409
+ return self.safe_ledger_entry({
1410
+ 'info': item,
1411
+ 'id': self.safe_string(item, 'transactionId'),
1412
+ 'direction': direction,
1413
+ 'account': self.safe_string(item, 'accountId', ''),
1414
+ 'referenceAccount': None,
1415
+ 'referenceId': None,
1416
+ 'type': self.parse_ledger_entry_type(type),
1417
+ 'currency': code,
1418
+ 'amount': self.parse_number(amount),
1419
+ 'timestamp': timestamp,
1420
+ 'datetime': self.iso8601(timestamp),
1421
+ 'before': None,
1422
+ 'after': None,
1423
+ 'status': None,
1424
+ 'fee': None,
1425
+ }, currency)
1129
1426
 
1130
- def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1427
+ def parse_ledger_entry_type(self, type):
1428
+ ledgerType: dict = {
1429
+ 'deposit': 'deposit',
1430
+ 'withdraw': 'withdrawal',
1431
+ 'commission': 'fee',
1432
+ }
1433
+ return self.safe_string(ledgerType, type, type)
1434
+
1435
+ def fetch_deposits_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
1131
1436
  """
1132
- :see: https://docs.cex.io/#archived-orders
1133
- fetches information on multiple closed orders made by the user
1134
- :param str symbol: unified market symbol of the market orders were made in
1135
- :param int [since]: the earliest time in ms to fetch orders for
1136
- :param int [limit]: the maximum number of order structures to retrieve
1437
+ fetch history of deposits and withdrawals
1438
+
1439
+ https://trade.cex.io/docs/#rest-private-api-calls-funding-history
1440
+
1441
+ :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
1442
+ :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
1443
+ :param int [limit]: max number of deposit/withdrawals to return, default is None
1137
1444
  :param dict [params]: extra parameters specific to the exchange API endpoint
1138
- :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1445
+ :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
1139
1446
  """
1140
- if symbol is None:
1141
- raise ArgumentsRequired(self.id + ' fetchClosedOrders() requires a symbol argument')
1142
1447
  self.load_markets()
1143
- market = self.market(symbol)
1144
- request: dict = {'pair': market['id']}
1145
- response = self.privatePostArchivedOrdersPair(self.extend(request, params))
1146
- return self.parse_orders(response, market, since, limit)
1448
+ request: dict = {}
1449
+ currency = None
1450
+ if code is not None:
1451
+ currency = self.currency(code)
1452
+ if since is not None:
1453
+ request['dateFrom'] = since
1454
+ if limit is not None:
1455
+ request['pageSize'] = limit
1456
+ until = None
1457
+ until, params = self.handle_param_integer_2(params, 'until', 'till')
1458
+ if until is not None:
1459
+ request['dateTo'] = until
1460
+ response = self.privatePostGetMyFundingHistory(self.extend(request, params))
1461
+ #
1462
+ # {
1463
+ # "ok": "ok",
1464
+ # "data": [
1465
+ # {
1466
+ # "clientId": "up421412345",
1467
+ # "accountId": "",
1468
+ # "currency": "USDT",
1469
+ # "direction": "withdraw",
1470
+ # "amount": "12.39060600",
1471
+ # "commissionAmount": "0.00000000",
1472
+ # "status": "approved",
1473
+ # "updatedAt": "2024-10-14T14:08:50.013Z",
1474
+ # "txId": "30367718",
1475
+ # "details": {}
1476
+ # },
1477
+ # ...
1478
+ #
1479
+ data = self.safe_list(response, 'data', [])
1480
+ return self.parse_transactions(data, currency, since, limit)
1481
+
1482
+ def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
1483
+ currencyId = self.safe_string(transaction, 'currency')
1484
+ direction = self.safe_string(transaction, 'direction')
1485
+ type = 'withdrawal' if (direction == 'withdraw') else 'deposit'
1486
+ code = self.safe_currency_code(currencyId, currency)
1487
+ updatedAt = self.safe_string(transaction, 'updatedAt')
1488
+ timestamp = self.parse8601(updatedAt)
1489
+ return {
1490
+ 'info': transaction,
1491
+ 'id': self.safe_string(transaction, 'txId'),
1492
+ 'txid': None,
1493
+ 'type': type,
1494
+ 'currency': code,
1495
+ 'network': None,
1496
+ 'amount': self.safe_number(transaction, 'amount'),
1497
+ 'status': self.parse_transaction_status(self.safe_string(transaction, 'status')),
1498
+ 'timestamp': timestamp,
1499
+ 'datetime': self.iso8601(timestamp),
1500
+ 'address': None,
1501
+ 'addressFrom': None,
1502
+ 'addressTo': None,
1503
+ 'tag': None,
1504
+ 'tagFrom': None,
1505
+ 'tagTo': None,
1506
+ 'updated': None,
1507
+ 'comment': None,
1508
+ 'fee': {
1509
+ 'currency': code,
1510
+ 'cost': self.safe_number(transaction, 'commissionAmount'),
1511
+ },
1512
+ 'internal': None,
1513
+ }
1514
+
1515
+ def parse_transaction_status(self, status: Str):
1516
+ statuses: dict = {
1517
+ 'rejected': 'rejected',
1518
+ 'pending': 'pending',
1519
+ 'approved': 'ok',
1520
+ }
1521
+ return self.safe_string(statuses, status, status)
1147
1522
 
1148
- def fetch_order(self, id: str, symbol: Str = None, params={}):
1523
+ def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
1149
1524
  """
1150
- :see: https://docs.cex.io/?python#get-order-details
1151
- fetches information on an order made by the user
1152
- :param str symbol: not used by cex fetchOrder
1525
+ transfer currency internally between wallets on the same account
1526
+
1527
+ https://trade.cex.io/docs/#rest-private-api-calls-internal-transfer
1528
+
1529
+ :param str code: unified currency code
1530
+ :param float amount: amount to transfer
1531
+ :param str fromAccount: 'SPOT', 'FUND', or 'CONTRACT'
1532
+ :param str toAccount: 'SPOT', 'FUND', or 'CONTRACT'
1153
1533
  :param dict [params]: extra parameters specific to the exchange API endpoint
1154
- :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1534
+ :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
1155
1535
  """
1536
+ transfer = None
1537
+ if toAccount != '' and fromAccount != '':
1538
+ transfer = self.transfer_between_sub_accounts(code, amount, fromAccount, toAccount, params)
1539
+ else:
1540
+ transfer = self.transfer_between_main_and_sub_account(code, amount, fromAccount, toAccount, params)
1541
+ fillResponseFromRequest = self.handle_option('transfer', 'fillResponseFromRequest', True)
1542
+ if fillResponseFromRequest:
1543
+ transfer['fromAccount'] = fromAccount
1544
+ transfer['toAccount'] = toAccount
1545
+ return transfer
1546
+
1547
+ def transfer_between_main_and_sub_account(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
1156
1548
  self.load_markets()
1549
+ currency = self.currency(code)
1550
+ fromMain = (fromAccount == '')
1551
+ targetAccount = toAccount if fromMain else fromAccount
1552
+ guid = self.safe_string(params, 'guid', self.uuid())
1157
1553
  request: dict = {
1158
- 'id': str(id),
1554
+ 'currency': currency['id'],
1555
+ 'amount': self.currency_to_precision(code, amount),
1556
+ 'accountId': targetAccount,
1557
+ 'clientTxId': guid,
1159
1558
  }
1160
- response = self.privatePostGetOrderTx(self.extend(request, params))
1161
- data = self.safe_value(response, 'data', {})
1559
+ response = None
1560
+ if fromMain:
1561
+ response = self.privatePostDoDepositFundsFromWallet(self.extend(request, params))
1562
+ else:
1563
+ response = self.privatePostDoWithdrawalFundsToWallet(self.extend(request, params))
1564
+ # both endpoints return the same structure, the only difference is that
1565
+ # the "accountId" is filled with the "subAccount"
1162
1566
  #
1163
1567
  # {
1164
- # "id": "5442731603",
1165
- # "type": "sell",
1166
- # "time": 1516132358071,
1167
- # "lastTxTime": 1516132378452,
1168
- # "lastTx": "5442734452",
1169
- # "pos": null,
1170
- # "user": "up106404164",
1171
- # "status": "d",
1172
- # "symbol1": "ETH",
1173
- # "symbol2": "EUR",
1174
- # "amount": "0.50000000",
1175
- # "kind": "api",
1176
- # "price": "923.3386",
1177
- # "tfacf": "1",
1178
- # "fa:EUR": "0.55",
1179
- # "ta:EUR": "369.77",
1180
- # "remains": "0.00000000",
1181
- # "tfa:EUR": "0.22",
1182
- # "tta:EUR": "91.95",
1183
- # "a:ETH:cds": "0.50000000",
1184
- # "a:EUR:cds": "461.72",
1185
- # "f:EUR:cds": "0.77",
1186
- # "tradingFeeMaker": "0.15",
1187
- # "tradingFeeTaker": "0.23",
1188
- # "tradingFeeStrategy": "userVolumeAmount",
1189
- # "tradingFeeUserVolumeAmount": "2896912572",
1190
- # "orderId": "5442731603",
1191
- # "next": False,
1192
- # "vtx": [
1193
- # {
1194
- # "id": "5442734452",
1195
- # "type": "sell",
1196
- # "time": "2018-01-16T19:52:58.452Z",
1197
- # "user": "up106404164",
1198
- # "c": "user:up106404164:a:EUR",
1199
- # "d": "order:5442731603:a:EUR",
1200
- # "a": "104.53000000",
1201
- # "amount": "104.53000000",
1202
- # "balance": "932.71000000",
1203
- # "symbol": "EUR",
1204
- # "order": "5442731603",
1205
- # "buy": "5442734443",
1206
- # "sell": "5442731603",
1207
- # "pair": null,
1208
- # "pos": null,
1209
- # "office": null,
1210
- # "cs": "932.71",
1211
- # "ds": 0,
1212
- # "price": 923.3386,
1213
- # "symbol2": "ETH",
1214
- # "fee_amount": "0.16"
1215
- # },
1216
- # {
1217
- # "id": "5442731609",
1218
- # "type": "sell",
1219
- # "time": "2018-01-16T19:52:38.071Z",
1220
- # "user": "up106404164",
1221
- # "c": "user:up106404164:a:EUR",
1222
- # "d": "order:5442731603:a:EUR",
1223
- # "a": "91.73000000",
1224
- # "amount": "91.73000000",
1225
- # "balance": "563.49000000",
1226
- # "symbol": "EUR",
1227
- # "order": "5442731603",
1228
- # "buy": "5442618127",
1229
- # "sell": "5442731603",
1230
- # "pair": null,
1231
- # "pos": null,
1232
- # "office": null,
1233
- # "cs": "563.49",
1234
- # "ds": 0,
1235
- # "price": 924.0092,
1236
- # "symbol2": "ETH",
1237
- # "fee_amount": "0.22"
1238
- # },
1239
- # {
1240
- # "id": "5442731604",
1241
- # "type": "sell",
1242
- # "time": "2018-01-16T19:52:38.071Z",
1243
- # "user": "up106404164",
1244
- # "c": "order:5442731603:a:ETH",
1245
- # "d": "user:up106404164:a:ETH",
1246
- # "a": "0.50000000",
1247
- # "amount": "-0.50000000",
1248
- # "balance": "15.80995000",
1249
- # "symbol": "ETH",
1250
- # "order": "5442731603",
1251
- # "buy": null,
1252
- # "sell": null,
1253
- # "pair": null,
1254
- # "pos": null,
1255
- # "office": null,
1256
- # "cs": "0.50000000",
1257
- # "ds": "15.80995000"
1258
- # }
1259
- # ]
1568
+ # "ok": "ok",
1569
+ # "data": {
1570
+ # "accountId": "sub1",
1571
+ # "clientTxId": "27ba8284-67cf-4386-9ec7-80b3871abd45",
1572
+ # "currency": "USDT",
1573
+ # "status": "approved"
1574
+ # }
1260
1575
  # }
1261
1576
  #
1262
- return self.parse_order(data)
1577
+ data = self.safe_dict(response, 'data', {})
1578
+ return self.parse_transfer(data, currency)
1263
1579
 
1264
- def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1265
- """
1266
- :see: https://docs.cex.io/#archived-orders
1267
- fetches information on multiple orders made by the user
1268
- :param str symbol: unified market symbol of the market orders were made in
1269
- :param int [since]: the earliest time in ms to fetch orders for
1270
- :param int [limit]: the maximum number of order structures to retrieve
1271
- :param dict [params]: extra parameters specific to the exchange API endpoint
1272
- :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1273
- """
1580
+ def transfer_between_sub_accounts(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
1274
1581
  self.load_markets()
1275
- market = self.market(symbol)
1582
+ currency = self.currency(code)
1276
1583
  request: dict = {
1277
- 'limit': limit,
1278
- 'pair': market['id'],
1279
- 'dateFrom': since,
1584
+ 'currency': currency['id'],
1585
+ 'amount': self.currency_to_precision(code, amount),
1586
+ 'fromAccountId': fromAccount,
1587
+ 'toAccountId': toAccount,
1280
1588
  }
1281
- response = self.privatePostArchivedOrdersPair(self.extend(request, params))
1282
- results = []
1283
- for i in range(0, len(response)):
1284
- # cancelled(unfilled):
1285
- # {"id": "4005785516",
1286
- # "type": "sell",
1287
- # "time": "2017-07-18T19:08:34.223Z",
1288
- # "lastTxTime": "2017-07-18T19:08:34.396Z",
1289
- # "lastTx": "4005785522",
1290
- # "pos": null,
1291
- # "status": "c",
1292
- # "symbol1": "ETH",
1293
- # "symbol2": "GBP",
1294
- # "amount": "0.20000000",
1295
- # "price": "200.5625",
1296
- # "remains": "0.20000000",
1297
- # 'a:ETH:cds': "0.20000000",
1298
- # "tradingFeeMaker": "0",
1299
- # "tradingFeeTaker": "0.16",
1300
- # "tradingFeeUserVolumeAmount": "10155061217",
1301
- # "orderId": "4005785516"}
1302
- # --
1303
- # cancelled(partially filled buy):
1304
- # {"id": "4084911657",
1305
- # "type": "buy",
1306
- # "time": "2017-08-05T03:18:39.596Z",
1307
- # "lastTxTime": "2019-03-19T17:37:46.404Z",
1308
- # "lastTx": "8459265833",
1309
- # "pos": null,
1310
- # "status": "cd",
1311
- # "symbol1": "BTC",
1312
- # "symbol2": "GBP",
1313
- # "amount": "0.05000000",
1314
- # "price": "2241.4692",
1315
- # "tfacf": "1",
1316
- # "remains": "0.03910535",
1317
- # 'tfa:GBP': "0.04",
1318
- # 'tta:GBP': "24.39",
1319
- # 'a:BTC:cds': "0.01089465",
1320
- # 'a:GBP:cds': "112.26",
1321
- # 'f:GBP:cds': "0.04",
1322
- # "tradingFeeMaker": "0",
1323
- # "tradingFeeTaker": "0.16",
1324
- # "tradingFeeUserVolumeAmount": "13336396963",
1325
- # "orderId": "4084911657"}
1326
- # --
1327
- # cancelled(partially filled sell):
1328
- # {"id": "4426728375",
1329
- # "type": "sell",
1330
- # "time": "2017-09-22T00:24:20.126Z",
1331
- # "lastTxTime": "2017-09-22T00:24:30.476Z",
1332
- # "lastTx": "4426729543",
1333
- # "pos": null,
1334
- # "status": "cd",
1335
- # "symbol1": "BCH",
1336
- # "symbol2": "BTC",
1337
- # "amount": "0.10000000",
1338
- # "price": "0.11757182",
1339
- # "tfacf": "1",
1340
- # "remains": "0.09935956",
1341
- # 'tfa:BTC': "0.00000014",
1342
- # 'tta:BTC': "0.00007537",
1343
- # 'a:BCH:cds': "0.10000000",
1344
- # 'a:BTC:cds': "0.00007537",
1345
- # 'f:BTC:cds': "0.00000014",
1346
- # "tradingFeeMaker": "0",
1347
- # "tradingFeeTaker": "0.18",
1348
- # "tradingFeeUserVolumeAmount": "3466715450",
1349
- # "orderId": "4426728375"}
1350
- # --
1351
- # filled:
1352
- # {"id": "5342275378",
1353
- # "type": "sell",
1354
- # "time": "2018-01-04T00:28:12.992Z",
1355
- # "lastTxTime": "2018-01-04T00:28:12.992Z",
1356
- # "lastTx": "5342275393",
1357
- # "pos": null,
1358
- # "status": "d",
1359
- # "symbol1": "BCH",
1360
- # "symbol2": "BTC",
1361
- # "amount": "0.10000000",
1362
- # "kind": "api",
1363
- # "price": "0.17",
1364
- # "remains": "0.00000000",
1365
- # 'tfa:BTC': "0.00003902",
1366
- # 'tta:BTC': "0.01699999",
1367
- # 'a:BCH:cds': "0.10000000",
1368
- # 'a:BTC:cds': "0.01699999",
1369
- # 'f:BTC:cds': "0.00003902",
1370
- # "tradingFeeMaker": "0.15",
1371
- # "tradingFeeTaker": "0.23",
1372
- # "tradingFeeUserVolumeAmount": "1525951128",
1373
- # "orderId": "5342275378"}
1374
- # --
1375
- # market order(buy):
1376
- # {"id": "6281946200",
1377
- # "pos": null,
1378
- # "time": "2018-05-23T11:55:43.467Z",
1379
- # "type": "buy",
1380
- # "amount": "0.00000000",
1381
- # "lastTx": "6281946210",
1382
- # "status": "d",
1383
- # "amount2": "20.00",
1384
- # "orderId": "6281946200",
1385
- # "remains": "0.00000000",
1386
- # "symbol1": "ETH",
1387
- # "symbol2": "EUR",
1388
- # "tfa:EUR": "0.05",
1389
- # "tta:EUR": "19.94",
1390
- # "a:ETH:cds": "0.03764100",
1391
- # "a:EUR:cds": "20.00",
1392
- # "f:EUR:cds": "0.05",
1393
- # "lastTxTime": "2018-05-23T11:55:43.467Z",
1394
- # "tradingFeeTaker": "0.25",
1395
- # "tradingFeeUserVolumeAmount": "55998097"}
1396
- # --
1397
- # market order(sell):
1398
- # {"id": "6282200948",
1399
- # "pos": null,
1400
- # "time": "2018-05-23T12:42:58.315Z",
1401
- # "type": "sell",
1402
- # "amount": "-0.05000000",
1403
- # "lastTx": "6282200958",
1404
- # "status": "d",
1405
- # "orderId": "6282200948",
1406
- # "remains": "0.00000000",
1407
- # "symbol1": "ETH",
1408
- # "symbol2": "EUR",
1409
- # "tfa:EUR": "0.07",
1410
- # "tta:EUR": "26.49",
1411
- # "a:ETH:cds": "0.05000000",
1412
- # "a:EUR:cds": "26.49",
1413
- # "f:EUR:cds": "0.07",
1414
- # "lastTxTime": "2018-05-23T12:42:58.315Z",
1415
- # "tradingFeeTaker": "0.25",
1416
- # "tradingFeeUserVolumeAmount": "56294576"}
1417
- order = response[i]
1418
- status = self.parse_order_status(self.safe_string(order, 'status'))
1419
- baseId = self.safe_string(order, 'symbol1')
1420
- quoteId = self.safe_string(order, 'symbol2')
1421
- base = self.safe_currency_code(baseId)
1422
- quote = self.safe_currency_code(quoteId)
1423
- symbolInner = base + '/' + quote
1424
- side = self.safe_string(order, 'type')
1425
- baseAmount = self.safe_number(order, 'a:' + baseId + ':cds')
1426
- quoteAmount = self.safe_number(order, 'a:' + quoteId + ':cds')
1427
- fee = self.safe_number(order, 'f:' + quoteId + ':cds')
1428
- amount = self.safe_string(order, 'amount')
1429
- price = self.safe_string(order, 'price')
1430
- remaining = self.safe_string(order, 'remains')
1431
- filled = Precise.string_sub(amount, remaining)
1432
- orderAmount = None
1433
- cost = None
1434
- average = None
1435
- type = None
1436
- if not price:
1437
- type = 'market'
1438
- orderAmount = baseAmount
1439
- cost = quoteAmount
1440
- average = Precise.string_div(orderAmount, cost)
1441
- else:
1442
- ta = self.safe_string(order, 'ta:' + quoteId, '0')
1443
- tta = self.safe_string(order, 'tta:' + quoteId, '0')
1444
- fa = self.safe_string(order, 'fa:' + quoteId, '0')
1445
- tfa = self.safe_string(order, 'tfa:' + quoteId, '0')
1446
- if side == 'sell':
1447
- cost = Precise.string_add(Precise.string_add(ta, tta), Precise.string_add(fa, tfa))
1448
- else:
1449
- cost = Precise.string_sub(Precise.string_add(ta, tta), Precise.string_add(fa, tfa))
1450
- type = 'limit'
1451
- orderAmount = amount
1452
- average = Precise.string_div(cost, filled)
1453
- time = self.safe_string(order, 'time')
1454
- lastTxTime = self.safe_string(order, 'lastTxTime')
1455
- timestamp = self.parse8601(time)
1456
- safeOrder = self.safe_order({
1457
- 'info': order,
1458
- 'id': self.safe_string(order, 'id'),
1459
- 'timestamp': timestamp,
1460
- 'datetime': self.iso8601(timestamp),
1461
- 'lastUpdated': self.parse8601(lastTxTime),
1462
- 'status': status,
1463
- 'symbol': symbolInner,
1464
- 'side': side,
1465
- 'price': price,
1466
- 'amount': orderAmount,
1467
- 'average': average,
1468
- 'type': type,
1469
- 'filled': filled,
1470
- 'cost': cost,
1471
- 'remaining': remaining,
1472
- 'fee': {
1473
- 'cost': fee,
1474
- 'currency': quote,
1475
- },
1476
- })
1477
- results.append(safeOrder)
1478
- return results
1479
-
1480
- def parse_order_status(self, status: Str):
1481
- return self.safe_string(self.options['order']['status'], status, status)
1589
+ response = self.privatePostDoMyInternalTransfer(self.extend(request, params))
1590
+ #
1591
+ # {
1592
+ # "ok": "ok",
1593
+ # "data": {
1594
+ # "transactionId": "30225415"
1595
+ # }
1596
+ # }
1597
+ #
1598
+ data = self.safe_dict(response, 'data', {})
1599
+ return self.parse_transfer(data, currency)
1482
1600
 
1483
- def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
1484
- """
1485
- edit a trade order
1486
- :see: https://docs.cex.io/#cancel-replace-order
1487
- :param str id: order id
1488
- :param str symbol: unified symbol of the market to create an order in
1489
- :param str type: 'market' or 'limit'
1490
- :param str side: 'buy' or 'sell'
1491
- :param float amount: how much of the currency you want to trade in units of the base currency
1492
- :param float|None [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
1493
- :param dict [params]: extra parameters specific to the cex api endpoint
1494
- :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
1495
- """
1496
- if amount is None:
1497
- raise ArgumentsRequired(self.id + ' editOrder() requires a amount argument')
1498
- if price is None:
1499
- raise ArgumentsRequired(self.id + ' editOrder() requires a price argument')
1500
- self.load_markets()
1501
- market = self.market(symbol)
1502
- # see: https://cex.io/rest-api#/definitions/CancelReplaceOrderRequest
1503
- request: dict = {
1504
- 'pair': market['id'],
1505
- 'type': side,
1506
- 'amount': amount,
1507
- 'price': price,
1508
- 'order_id': id,
1601
+ def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry:
1602
+ #
1603
+ # transferBetweenSubAccounts
1604
+ #
1605
+ # {
1606
+ # "ok": "ok",
1607
+ # "data": {
1608
+ # "transactionId": "30225415"
1609
+ # }
1610
+ # }
1611
+ #
1612
+ # transfer between main/sub
1613
+ #
1614
+ # {
1615
+ # "ok": "ok",
1616
+ # "data": {
1617
+ # "accountId": "sub1",
1618
+ # "clientTxId": "27ba8284-67cf-4386-9ec7-80b3871abd45",
1619
+ # "currency": "USDT",
1620
+ # "status": "approved"
1621
+ # }
1622
+ # }
1623
+ #
1624
+ currencyId = self.safe_string(transfer, 'currency')
1625
+ currencyCode = self.safe_currency_code(currencyId, currency)
1626
+ return {
1627
+ 'info': transfer,
1628
+ 'id': self.safe_string_2(transfer, 'transactionId', 'clientTxId'),
1629
+ 'timestamp': None,
1630
+ 'datetime': None,
1631
+ 'currency': currencyCode,
1632
+ 'amount': None,
1633
+ 'fromAccount': None,
1634
+ 'toAccount': None,
1635
+ 'status': self.parse_transaction_status(self.safe_string(transfer, 'status')),
1509
1636
  }
1510
- response = self.privatePostCancelReplaceOrderPair(self.extend(request, params))
1511
- return self.parse_order(response, market)
1512
1637
 
1513
- def fetch_deposit_address(self, code: str, params={}):
1638
+ def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
1514
1639
  """
1515
- :see: https://docs.cex.io/#get-crypto-address
1516
1640
  fetch the deposit address for a currency associated with self account
1641
+
1642
+ https://trade.cex.io/docs/#rest-private-api-calls-deposit-address
1643
+
1517
1644
  :param str code: unified currency code
1518
1645
  :param dict [params]: extra parameters specific to the exchange API endpoint
1646
+ :param str [params.accountId]: account-id(default to empty string) to refer to(at self moment, only sub-accounts allowed by exchange)
1519
1647
  :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
1520
1648
  """
1649
+ accountId = None
1650
+ accountId, params = self.handle_option_and_params(params, 'createOrder', 'accountId')
1651
+ if accountId is None:
1652
+ raise ArgumentsRequired(self.id + ' fetchDepositAddress() : main account is not allowed to fetch deposit address from api, set params["accountId"] or .options["createOrder"]["accountId"] to the name of your sub-account')
1521
1653
  self.load_markets()
1654
+ networkCode = None
1655
+ networkCode, params = self.handle_network_code_and_params(params)
1522
1656
  currency = self.currency(code)
1523
1657
  request: dict = {
1524
- 'currency': currency['id'],
1658
+ 'accountId': accountId,
1659
+ 'currency': currency['id'], # documentation is wrong about self param
1660
+ 'blockchain': self.network_code_to_id(networkCode),
1525
1661
  }
1526
- networkCode, query = self.handle_network_code_and_params(params)
1527
- # atm, cex doesn't support network in the request
1528
- response = self.privatePostGetCryptoAddress(self.extend(request, query))
1662
+ response = self.privatePostGetDepositAddress(self.extend(request, params))
1529
1663
  #
1530
1664
  # {
1531
- # "e": "get_crypto_address",
1532
- # "ok": "ok",
1533
- # "data": {
1534
- # "name": "BTC",
1535
- # "addresses": [
1536
- # {
1537
- # "blockchain": "Bitcoin",
1538
- # "address": "2BvKwe1UwrdTjq2nzhscFYXwqCjCaaHCeq"
1665
+ # "ok": "ok",
1666
+ # "data": {
1667
+ # "address": "TCr..................1AE",
1668
+ # "accountId": "sub1",
1669
+ # "currency": "USDT",
1670
+ # "blockchain": "tron"
1671
+ # }
1672
+ # }
1539
1673
  #
1540
- # # for others coins(i.e. XRP, XLM) other keys are present:
1541
- # # "destination": "rF1sdh25BJX3qFwneeTBwaq3zPEWYcwjp2",
1542
- # # "destinationTag": "7519113655",
1543
- # # "memo": "XLM-memo12345",
1544
- # }
1545
- # ]
1546
- # }
1547
- # }
1548
- #
1549
- data = self.safe_value(response, 'data', {})
1550
- addresses = self.safe_value(data, 'addresses', [])
1551
- chainsIndexedById = self.index_by(addresses, 'blockchain')
1552
- selectedNetworkId = self.select_network_id_from_raw_networks(code, networkCode, chainsIndexedById)
1553
- addressObject = self.safe_value(chainsIndexedById, selectedNetworkId, {})
1554
- address = self.safe_string_2(addressObject, 'address', 'destination')
1674
+ data = self.safe_dict(response, 'data', {})
1675
+ return self.parse_deposit_address(data, currency)
1676
+
1677
+ def parse_deposit_address(self, depositAddress, currency: Currency = None) -> DepositAddress:
1678
+ address = self.safe_string(depositAddress, 'address')
1679
+ currencyId = self.safe_string(depositAddress, 'currency')
1680
+ currency = self.safe_currency(currencyId, currency)
1555
1681
  self.check_address(address)
1556
1682
  return {
1557
- 'currency': code,
1683
+ 'info': depositAddress,
1684
+ 'currency': currency['code'],
1685
+ 'network': self.network_id_to_code(self.safe_string(depositAddress, 'blockchain')),
1558
1686
  'address': address,
1559
- 'tag': self.safe_string_2(addressObject, 'destinationTag', 'memo'),
1560
- 'network': self.network_id_to_code(selectedNetworkId),
1561
- 'info': data,
1687
+ 'tag': None,
1562
1688
  }
1563
1689
 
1564
- def nonce(self):
1565
- return self.milliseconds()
1566
-
1567
1690
  def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
1568
- url = self.urls['api']['rest'] + '/' + self.implode_params(path, params)
1691
+ url = self.urls['api'][api] + '/' + self.implode_params(path, params)
1569
1692
  query = self.omit(params, self.extract_params(path))
1570
1693
  if api == 'public':
1571
- if query:
1572
- url += '?' + self.urlencode(query)
1694
+ if method == 'GET':
1695
+ if query:
1696
+ url += '?' + self.urlencode(query)
1697
+ else:
1698
+ body = self.json(query)
1699
+ headers = {
1700
+ 'Content-Type': 'application/json',
1701
+ }
1573
1702
  else:
1574
1703
  self.check_required_credentials()
1575
- nonce = str(self.nonce())
1576
- auth = nonce + self.uid + self.apiKey
1577
- signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256)
1578
- body = self.json(self.extend({
1579
- 'key': self.apiKey,
1580
- 'signature': signature.upper(),
1581
- 'nonce': nonce,
1582
- }, query))
1704
+ seconds = str(self.seconds())
1705
+ body = self.json(query)
1706
+ auth = path + seconds + body
1707
+ signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256, 'base64')
1583
1708
  headers = {
1584
1709
  'Content-Type': 'application/json',
1710
+ 'X-AGGR-KEY': self.apiKey,
1711
+ 'X-AGGR-TIMESTAMP': seconds,
1712
+ 'X-AGGR-SIGNATURE': signature,
1585
1713
  }
1586
1714
  return {'url': url, 'method': method, 'body': body, 'headers': headers}
1587
1715
 
1588
1716
  def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
1589
- if isinstance(response, list):
1590
- return response # public endpoints may return []-arrays
1591
- if body == 'true':
1592
- return None
1717
+ # in some cases, like from createOrder, exchange returns nested escaped JSON string:
1718
+ # {"ok":"ok","data":{"messageType":"executionReport", "orderRejectReason":"{\"code\":405}"}}
1719
+ # and because of `.parseJson` bug, we need extra fix
1593
1720
  if response is None:
1594
- raise NullResponse(self.id + ' returned ' + self.json(response))
1595
- if 'e' in response:
1596
- if 'ok' in response:
1597
- if response['ok'] == 'ok':
1598
- return None
1599
- if 'error' in response:
1600
- message = self.safe_string(response, 'error')
1721
+ if body is None:
1722
+ raise NullResponse(self.id + ' returned empty response')
1723
+ elif body[0] == '{':
1724
+ fixed = self.fix_stringified_json_members(body)
1725
+ response = self.parse_json(fixed)
1726
+ else:
1727
+ raise NullResponse(self.id + ' returned unparsed response: ' + body)
1728
+ error = self.safe_string(response, 'error')
1729
+ if error is not None:
1601
1730
  feedback = self.id + ' ' + body
1602
- self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
1603
- self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
1731
+ self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
1732
+ self.throw_broadly_matched_exception(self.exceptions['broad'], error, feedback)
1604
1733
  raise ExchangeError(feedback)
1734
+ # check errors in order-engine(the responses are not standard, so we parse here)
1735
+ if url.find('do_my_new_order') >= 0:
1736
+ data = self.safe_dict(response, 'data', {})
1737
+ rejectReason = self.safe_string(data, 'rejectReason')
1738
+ if rejectReason is not None:
1739
+ self.throw_broadly_matched_exception(self.exceptions['broad'], rejectReason, rejectReason)
1740
+ raise ExchangeError(self.id + ' createOrder() ' + rejectReason)
1605
1741
  return None