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
@@ -0,0 +1,2071 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
4
+ # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
5
+
6
+ from ccxt.async_support.base.exchange import Exchange
7
+ from ccxt.abstract.defx import ImplicitAPI
8
+ import asyncio
9
+ import hashlib
10
+ from ccxt.base.types import Any, Balances, Currency, Int, LedgerEntry, Leverage, Market, Num, Order, OrderBook, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, FundingRate, Trade, Transaction
11
+ from typing import List
12
+ from ccxt.base.errors import ExchangeError
13
+ from ccxt.base.errors import AuthenticationError
14
+ from ccxt.base.errors import ArgumentsRequired
15
+ from ccxt.base.errors import BadRequest
16
+ from ccxt.base.errors import InvalidOrder
17
+ from ccxt.base.errors import NotSupported
18
+ from ccxt.base.decimal_to_precision import TICK_SIZE
19
+ from ccxt.base.precise import Precise
20
+
21
+
22
+ class defx(Exchange, ImplicitAPI):
23
+
24
+ def describe(self) -> Any:
25
+ return self.deep_extend(super(defx, self).describe(), {
26
+ 'id': 'defx',
27
+ 'name': 'Defx X',
28
+ # 'countries': [''],
29
+ 'rateLimit': 100,
30
+ 'version': 'v1',
31
+ 'certified': False,
32
+ 'pro': False,
33
+ 'hostname': 'defx.com',
34
+ 'dex': True,
35
+ 'has': {
36
+ 'CORS': None,
37
+ 'spot': False,
38
+ 'margin': False,
39
+ 'swap': True,
40
+ 'future': False,
41
+ 'option': False,
42
+ 'addMargin': True,
43
+ 'cancelAllOrders': True,
44
+ 'cancelAllOrdersAfter': False,
45
+ 'cancelOrder': True,
46
+ 'cancelWithdraw': False,
47
+ 'closeAllPositions': True,
48
+ 'closePosition': True,
49
+ 'createConvertTrade': False,
50
+ 'createDepositAddress': False,
51
+ 'createMarketBuyOrderWithCost': False,
52
+ 'createMarketOrder': False,
53
+ 'createMarketOrderWithCost': False,
54
+ 'createMarketSellOrderWithCost': False,
55
+ 'createOrder': True,
56
+ 'createOrderWithTakeProfitAndStopLoss': True,
57
+ 'createReduceOnlyOrder': True,
58
+ 'createStopLimitOrder': False,
59
+ 'createStopLossOrder': False,
60
+ 'createStopMarketOrder': False,
61
+ 'createStopOrder': False,
62
+ 'createTakeProfitOrder': True,
63
+ 'createTrailingAmountOrder': False,
64
+ 'createTrailingPercentOrder': False,
65
+ 'createTriggerOrder': True,
66
+ 'fetchAccounts': False,
67
+ 'fetchBalance': True,
68
+ 'fetchCanceledOrders': True,
69
+ 'fetchClosedOrder': False,
70
+ 'fetchClosedOrders': True,
71
+ 'fetchConvertCurrencies': False,
72
+ 'fetchConvertQuote': False,
73
+ 'fetchConvertTrade': False,
74
+ 'fetchConvertTradeHistory': False,
75
+ 'fetchCurrencies': False,
76
+ 'fetchDepositAddress': False,
77
+ 'fetchDepositAddresses': False,
78
+ 'fetchDepositAddressesByNetwork': False,
79
+ 'fetchDeposits': False,
80
+ 'fetchDepositsWithdrawals': False,
81
+ 'fetchFundingHistory': False,
82
+ 'fetchFundingInterval': False,
83
+ 'fetchFundingIntervals': False,
84
+ 'fetchFundingRate': True,
85
+ 'fetchFundingRateHistory': False,
86
+ 'fetchFundingRates': False,
87
+ 'fetchIndexOHLCV': False,
88
+ 'fetchLedger': True,
89
+ 'fetchLeverage': False,
90
+ 'fetchMarginAdjustmentHistory': False,
91
+ 'fetchMarginMode': False,
92
+ 'fetchMarkets': True,
93
+ 'fetchMarkOHLCV': False,
94
+ 'fetchMarkPrice': False,
95
+ 'fetchMarkPrices': False,
96
+ 'fetchMyTrades': True,
97
+ 'fetchOHLCV': True,
98
+ 'fetchOpenInterestHistory': False,
99
+ 'fetchOpenOrder': False,
100
+ 'fetchOpenOrders': True,
101
+ 'fetchOrder': True,
102
+ 'fetchOrderBook': True,
103
+ 'fetchOrders': True,
104
+ 'fetchOrderTrades': False,
105
+ 'fetchPosition': True,
106
+ 'fetchPositionHistory': False,
107
+ 'fetchPositionMode': False,
108
+ 'fetchPositions': True,
109
+ 'fetchPositionsHistory': False,
110
+ 'fetchPremiumIndexOHLCV': False,
111
+ 'fetchStatus': True,
112
+ 'fetchTicker': True,
113
+ 'fetchTickers': True,
114
+ 'fetchTime': True,
115
+ 'fetchTrades': True,
116
+ 'fetchTradingFee': False,
117
+ 'fetchTradingFees': False,
118
+ 'fetchTransactions': False,
119
+ 'fetchTransfers': False,
120
+ 'fetchWithdrawals': False,
121
+ 'reduceMargin': False,
122
+ 'sandbox': True,
123
+ 'setLeverage': True,
124
+ 'setMargin': False,
125
+ 'setPositionMode': False,
126
+ 'transfer': False,
127
+ 'withdraw': True,
128
+ },
129
+ 'timeframes': {
130
+ '1m': '1m',
131
+ '3m': '3m',
132
+ '5m': '5m',
133
+ '15m': '15m',
134
+ '30m': '30m',
135
+ '1h': '1h',
136
+ '2h': '2h',
137
+ '4h': '4h',
138
+ '12h': '12h',
139
+ '1d': '1d',
140
+ '1w': '1w',
141
+ '1M': '1M',
142
+ },
143
+ 'urls': {
144
+ 'logo': 'https://github.com/user-attachments/assets/4e92bace-d7a9-45ea-92be-122168dc87e4',
145
+ 'api': {
146
+ 'public': 'https://api.{hostname}',
147
+ 'private': 'https://api.{hostname}',
148
+ },
149
+ 'test': {
150
+ 'public': 'https://api.testnet.{hostname}',
151
+ 'private': 'https://api.testnet.{hostname}',
152
+ },
153
+ 'www': 'https://defx.com/home',
154
+ 'doc': [
155
+ 'https://docs.defx.com/docs',
156
+ 'https://api-docs.defx.com/',
157
+ ],
158
+ 'fees': [
159
+ '',
160
+ ],
161
+ 'referral': {
162
+ 'url': 'https://app.defx.com/join/6I2CZ7',
163
+ },
164
+ },
165
+ 'api': {
166
+ 'v1': {
167
+ 'public': {
168
+ 'get': {
169
+ 'healthcheck/ping': 1,
170
+ 'symbols/{symbol}/ohlc': 1,
171
+ 'symbols/{symbol}/trades': 1,
172
+ 'symbols/{symbol}/prices': 1,
173
+ 'symbols/{symbol}/ticker/24hr': 1,
174
+ 'symbols/{symbol}/depth/{level}/{slab}': 1,
175
+ 'ticker/24HrAgg': 1,
176
+ 'c/markets': 1,
177
+ 'c/markets/metadata': 1,
178
+ 'analytics/market/stats/newUsers': 1,
179
+ 'analytics/market/stats/tvl': 1,
180
+ 'analytics/market/stats/volumeByInstrument': 1,
181
+ 'analytics/market/stats/liquidation': 1,
182
+ 'analytics/market/stats/totalVolume': 1,
183
+ 'analytics/market/stats/openInterest': 1,
184
+ 'analytics/market/stats/totalTrades': 1,
185
+ 'analytics/market/stats/basis': 1,
186
+ 'analytics/market/stats/insuranceFund': 1,
187
+ 'analytics/market/stats/longAndShortRatio': 1,
188
+ 'analytics/market/stats/fundingRate': 1,
189
+ 'analytics/market/overview': 1,
190
+ 'explorer/search': 1,
191
+ 'explorer/transactions': 1,
192
+ 'explorer/blocks': 1,
193
+ },
194
+ },
195
+ 'private': {
196
+ 'get': {
197
+ 'api/order/{orderId}': 1,
198
+ 'api/orders': 1,
199
+ 'api/orders/oco/{parentOrderId}': 1,
200
+ 'api/trades': 1,
201
+ 'api/position/active': 1,
202
+ 'api/users/metadata/leverage': 1,
203
+ 'api/users/metadata/feeMultiplier': 1,
204
+ 'api/users/metadata/slippage': 1,
205
+ 'api/users/referral': 1,
206
+ 'api/users/apikeys': 1,
207
+ 'connection-signature-message/evm': 1,
208
+ 'api/users/profile/wallets': 1,
209
+ 'api/notifications': 1,
210
+ 'api/wallet/balance': 1,
211
+ 'api/wallet/transactions': 1,
212
+ 'api/analytics/user/overview': 1,
213
+ 'api/analytics/user/pnl': 1,
214
+ 'api/analytics/points/overview': 1,
215
+ 'api/analytics/points/history': 1,
216
+ },
217
+ 'post': {
218
+ 'api/order': 1,
219
+ 'api/position/oco': 1,
220
+ 'api/users/socket/listenKeys': 1,
221
+ 'api/users/metadata/leverage': 1,
222
+ 'api/users/metadata/feeMultiplier': 1,
223
+ 'api/users/metadata/slippage': 1,
224
+ 'api/users/referral/recordReferralSignup': 1,
225
+ 'api/users/apikeys': 1,
226
+ 'api/users/profile/wallets': 1,
227
+ 'api/transfers/withdrawal': 1,
228
+ 'api/transfers/bridge/withdrawal': 1,
229
+ },
230
+ 'put': {
231
+ 'api/position/updatePositionMargin': 1,
232
+ 'api/users/socket/listenKeys/{listenKey}': 1,
233
+ 'api/users/apikeys/{accessKey}/status': 1,
234
+ 'api/users/referral': 1,
235
+ },
236
+ 'patch': {
237
+ 'api/users/apikeys/{accessKey}': 1,
238
+ },
239
+ 'delete': {
240
+ 'api/orders/allOpen': 1,
241
+ 'api/order/{orderId}': 1,
242
+ 'api/position/{positionId}': 1,
243
+ 'api/position/all': 1,
244
+ 'api/users/socket/listenKeys/{listenKey}': 1,
245
+ 'api/users/apikeys/{accessKey}': 1,
246
+ },
247
+ },
248
+ },
249
+ },
250
+ 'fees': {
251
+ 'trading': {
252
+ 'tierBased': True,
253
+ 'percentage': True,
254
+ 'maker': self.parse_number('0.0002'),
255
+ 'taker': self.parse_number('0.0005'),
256
+ },
257
+ },
258
+ 'options': {
259
+ 'sandboxMode': False,
260
+ },
261
+ 'features': {
262
+ 'spot': None,
263
+ 'forDerivatives': {
264
+ 'sandbox': True,
265
+ 'createOrder': {
266
+ 'marginMode': False,
267
+ 'triggerPrice': True,
268
+ # todo implement
269
+ 'triggerPriceType': {
270
+ 'last': True,
271
+ 'mark': True,
272
+ 'index': False,
273
+ },
274
+ 'triggerDirection': False,
275
+ 'stopLossPrice': False, # todo
276
+ 'takeProfitPrice': False, # todo
277
+ 'attachedStopLossTakeProfit': None,
278
+ 'timeInForce': {
279
+ 'IOC': True,
280
+ 'FOK': True,
281
+ 'PO': True,
282
+ 'GTD': False,
283
+ },
284
+ 'hedged': False,
285
+ 'selfTradePrevention': False,
286
+ 'trailing': False,
287
+ 'iceberg': False,
288
+ 'leverage': False,
289
+ 'marketBuyByCost': False,
290
+ 'marketBuyRequiresPrice': False,
291
+ },
292
+ 'createOrders': None,
293
+ 'fetchMyTrades': {
294
+ 'marginMode': False,
295
+ 'limit': 1000,
296
+ 'daysBack': None,
297
+ 'untilDays': None,
298
+ 'symbolRequired': False,
299
+ },
300
+ 'fetchOrder': {
301
+ 'marginMode': False,
302
+ 'trigger': False,
303
+ 'trailing': False,
304
+ 'symbolRequired': False,
305
+ },
306
+ 'fetchOpenOrders': {
307
+ 'marginMode': True,
308
+ 'limit': 100,
309
+ 'trigger': False,
310
+ 'trailing': False,
311
+ 'symbolRequired': False,
312
+ },
313
+ 'fetchOrders': {
314
+ 'marginMode': False,
315
+ 'limit': 500,
316
+ 'daysBack': 100000,
317
+ 'untilDays': 100000,
318
+ 'trigger': False,
319
+ 'trailing': False,
320
+ 'symbolRequired': False,
321
+ },
322
+ 'fetchClosedOrders': {
323
+ 'marginMode': False,
324
+ 'limit': 500,
325
+ 'daysBack': 100000,
326
+ 'daysBackCanceled': 1,
327
+ 'untilDays': 100000,
328
+ 'trigger': False,
329
+ 'trailing': False,
330
+ 'symbolRequired': False,
331
+ },
332
+ 'fetchOHLCV': {
333
+ 'limit': 1000,
334
+ },
335
+ },
336
+ 'swap': {
337
+ 'linear': {
338
+ 'extends': 'forDerivatives',
339
+ },
340
+ 'inverse': None,
341
+ },
342
+ 'future': {
343
+ 'linear': None,
344
+ 'inverse': None,
345
+ },
346
+ },
347
+ 'commonCurrencies': {},
348
+ 'exceptions': {
349
+ 'exact': {
350
+ '404': BadRequest, # {"errorCode":404,"errorMessage":"Not Found"}
351
+ 'missing_auth_signature': AuthenticationError, # {"msg":"Missing auth signature","code":"missing_auth_signature"}
352
+ 'order_rejected': InvalidOrder, # {"success":false,"err":{"msg":"Order has already been rejected","code":"order_rejected"}}
353
+ 'invalid_order_id': InvalidOrder, # {"success":false,"err":{"msg":"Invalid order id","code":"invalid_order_id"}}
354
+ 'filter_lotsize_maxqty': InvalidOrder, # {"errorCode":"filter_lotsize_maxqty","errorMessage":"LOT_SIZE filter failed, quantity more than maxQty","errorData":{"maxQty":"5000.00"}}
355
+ 'filter_notional_min': InvalidOrder, # {"errorCode":"filter_notional_min","errorMessage":"NOTIONAL filter failed, Notional value of quote asset less than minNotional","errorData":{"minNotional":"100.00000000"}}
356
+ 'failed_index_price_up_multiplier_filter': InvalidOrder, # {"errorCode":"failed_index_price_up_multiplier_filter","errorMessage":"failed_index_price_up_multiplier_filter","errorData":{"maxPrice":"307.81241042"}}
357
+ 'no_open_orders': InvalidOrder, # {"errorMessage":"No open orders found","errorCode":"no_open_orders"}
358
+ 'active_position_not_found': InvalidOrder, # {"errorCode":"active_position_not_found","errorMessage":"Active position not found"}
359
+ 'position_inactive': InvalidOrder, # {"errorCode":"position_inactive","errorMessage":"Position is already inactive"}
360
+ 'invalid_position_id': InvalidOrder, # {"errorCode":"invalid_position_id","errorMessage":"Position id is invalid"}
361
+ 'Internal server error': ExchangeError, # {"msg":"Internal server error","code":"internal_server_error"}
362
+ },
363
+ 'broad': {
364
+ 'Bad Request': BadRequest, # {"errorMessage":"Bad Request","data":[{"param":"symbol","message":"\"symbol\" must be one of [ETH_USDC, BTC_USDC, BNB_USDC, SOL_USDC, DOGE_USDC, TON_USDC, AVAX_USDC, WIF_USDC, KPEPE_USDC, KSHIB_USDC, KBONK_USDC, MOODENG_USDC, POPCAT_USDC, MOTHER_USDC]"}]}
365
+ },
366
+ },
367
+ 'precisionMode': TICK_SIZE,
368
+ })
369
+
370
+ async def fetch_status(self, params={}):
371
+ """
372
+ the latest known information on the availability of the exchange API
373
+
374
+ https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6
375
+
376
+ :param dict [params]: extra parameters specific to the exchange API endpoint
377
+ :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
378
+ """
379
+ response = await self.v1PublicGetHealthcheckPing(params)
380
+ #
381
+ # {
382
+ # "success": True,
383
+ # "t": 1709705048323,
384
+ # "v": "0.0.7",
385
+ # "msg": "A programmer’s wife tells him, “While you’re at the grocery store, buy some eggs.” He never comes back."
386
+ # }
387
+ #
388
+ status = None
389
+ success = self.safe_bool(response, 'success')
390
+ if success:
391
+ status = 'ok'
392
+ else:
393
+ status = 'error'
394
+ return {
395
+ 'status': status,
396
+ 'updated': None,
397
+ 'eta': None,
398
+ 'url': None,
399
+ 'info': response,
400
+ }
401
+
402
+ async def fetch_time(self, params={}) -> Int:
403
+ """
404
+ fetches the current integer timestamp in milliseconds from the exchange server
405
+
406
+ https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6
407
+
408
+ :param dict [params]: extra parameters specific to the exchange API endpoint
409
+ :returns int: the current integer timestamp in milliseconds from the exchange server
410
+ """
411
+ response = await self.v1PublicGetHealthcheckPing(params)
412
+ #
413
+ # {
414
+ # "success": True,
415
+ # "t": 1709705048323,
416
+ # "v": "0.0.7",
417
+ # "msg": "A programmer’s wife tells him, “While you’re at the grocery store, buy some eggs.” He never comes back."
418
+ # }
419
+ #
420
+ return self.safe_integer(response, 't')
421
+
422
+ async def fetch_markets(self, params={}) -> List[Market]:
423
+ """
424
+ retrieves data on all markets for defx
425
+
426
+ https://api-docs.defx.com/#73cce0c8-f842-4891-9145-01bb6d61324d
427
+ https://api-docs.defx.com/#24fd4e5b-840e-451e-99e0-7fea47c7f371
428
+
429
+ :param dict [params]: extra parameters specific to the exchange API endpoint
430
+ :returns dict[]: an array of objects representing market data
431
+ """
432
+ request = {
433
+ 'type': 'perps',
434
+ }
435
+ promises = [
436
+ self.v1PublicGetCMarkets(self.extend(request, params)),
437
+ self.v1PublicGetCMarketsMetadata(self.extend(request, params)),
438
+ ]
439
+ responses = await asyncio.gather(*promises)
440
+ #
441
+ # {
442
+ # "data": [
443
+ # {
444
+ # "market": "DOGE_USDC",
445
+ # "candleWindows": [
446
+ # "1m",
447
+ # "3m",
448
+ # "5m",
449
+ # "15m",
450
+ # "30m",
451
+ # "1h",
452
+ # "2h",
453
+ # "4h",
454
+ # "12h",
455
+ # "1d",
456
+ # "1w",
457
+ # "1M"
458
+ # ],
459
+ # "depthSlabs": [
460
+ # "0.00001",
461
+ # "0.00005",
462
+ # "0.0001",
463
+ # "0.001",
464
+ # "0.01"
465
+ # ],
466
+ # "filters": [
467
+ # {
468
+ # "filterType": "LOT_SIZE",
469
+ # "minQty": "1.00000",
470
+ # "maxQty": "1500000.00000",
471
+ # "stepSize": "1.00000"
472
+ # },
473
+ # {
474
+ # "filterType": "MARKET_LOT_SIZE",
475
+ # "minQty": "1.00000",
476
+ # "maxQty": "750000.00000",
477
+ # "stepSize": "1.00000"
478
+ # },
479
+ # {
480
+ # "filterType": "PRICE_FILTER",
481
+ # "minPrice": "0.00244000",
482
+ # "maxPrice": "30.00000000",
483
+ # "tickSize": "0.00001"
484
+ # },
485
+ # {
486
+ # "filterType": "NOTIONAL",
487
+ # "minNotional": "100.00000000"
488
+ # },
489
+ # {
490
+ # "filterType": "PERCENT_PRICE_BY_SIDE",
491
+ # "bidMultiplierUp": "1.5",
492
+ # "bidMultiplierDown": "0.5",
493
+ # "askMultiplierUp": "1.5",
494
+ # "askMultiplierDown": "0.5"
495
+ # },
496
+ # {
497
+ # "filterType": "INDEX_PRICE_FILTER",
498
+ # "multiplierUp": "1.3",
499
+ # "multiplierDown": "0.7"
500
+ # }
501
+ # ],
502
+ # "cappedLeverage": "25",
503
+ # "maintenanceMarginTiers": [
504
+ # {
505
+ # "tier": "1",
506
+ # "minMaintenanceMargin": "0",
507
+ # "maxMaintenanceMargin": "2500",
508
+ # "leverage": "25"
509
+ # },
510
+ # {
511
+ # "tier": "2",
512
+ # "minMaintenanceMargin": "2500",
513
+ # "maxMaintenanceMargin": "12500",
514
+ # "leverage": "20"
515
+ # },
516
+ # {
517
+ # "tier": "3",
518
+ # "minMaintenanceMargin": "12500",
519
+ # "maxMaintenanceMargin": "25000",
520
+ # "leverage": "15"
521
+ # },
522
+ # {
523
+ # "tier": "4",
524
+ # "minMaintenanceMargin": "25000",
525
+ # "maxMaintenanceMargin": "50000",
526
+ # "leverage": "10"
527
+ # },
528
+ # {
529
+ # "tier": "5",
530
+ # "minMaintenanceMargin": "50000",
531
+ # "maxMaintenanceMargin": "75000",
532
+ # "leverage": "8"
533
+ # },
534
+ # {
535
+ # "tier": "6",
536
+ # "minMaintenanceMargin": "75000",
537
+ # "maxMaintenanceMargin": "125000",
538
+ # "leverage": "7"
539
+ # },
540
+ # {
541
+ # "tier": "7",
542
+ # "minMaintenanceMargin": "125000",
543
+ # "maxMaintenanceMargin": "187500",
544
+ # "leverage": "5"
545
+ # },
546
+ # {
547
+ # "tier": "8",
548
+ # "minMaintenanceMargin": "187500",
549
+ # "maxMaintenanceMargin": "250000",
550
+ # "leverage": "3"
551
+ # },
552
+ # {
553
+ # "tier": "9",
554
+ # "minMaintenanceMargin": "250000",
555
+ # "maxMaintenanceMargin": "375000",
556
+ # "leverage": "2"
557
+ # },
558
+ # {
559
+ # "tier": "10",
560
+ # "minMaintenanceMargin": "375000",
561
+ # "maxMaintenanceMargin": "500000",
562
+ # "leverage": "1"
563
+ # }
564
+ # ],
565
+ # "fees": {
566
+ # "maker": "0.08",
567
+ # "taker": "0.1"
568
+ # }
569
+ # },
570
+ # ]
571
+ # }
572
+ #
573
+ activeMarkets = self.safe_list(responses[0], 'data')
574
+ activeMarketsByType = self.index_by(activeMarkets, 'market')
575
+ marketMetadatas = self.safe_list(responses[1], 'data')
576
+ for i in range(0, len(marketMetadatas)):
577
+ marketId = marketMetadatas[i]['market']
578
+ status = None
579
+ if marketId in activeMarketsByType:
580
+ status = activeMarketsByType[marketId]['status']
581
+ marketMetadatas[i]['status'] = status
582
+ return self.parse_markets(marketMetadatas)
583
+
584
+ def parse_market(self, market: dict) -> Market:
585
+ marketId = self.safe_string(market, 'market')
586
+ parts = marketId.split('_')
587
+ baseId = self.safe_string(parts, 0)
588
+ quoteId = self.safe_string(parts, 1)
589
+ base = self.safe_currency_code(baseId)
590
+ quote = self.safe_currency_code(quoteId)
591
+ symbol = base + '/' + quote + ':' + quote
592
+ filters = self.safe_list(market, 'filters', [])
593
+ fees = self.safe_dict(market, 'fees', {})
594
+ filtersByType = self.index_by(filters, 'filterType')
595
+ priceFilter = self.safe_dict(filtersByType, 'PRICE_FILTER', {})
596
+ lotFilter = self.safe_dict(filtersByType, 'LOT_SIZE', {})
597
+ marketLotFilter = self.safe_dict(filtersByType, 'MARKET_LOT_SIZE', {})
598
+ notionalFilter = self.safe_dict(filtersByType, 'NOTIONAL', {})
599
+ return {
600
+ 'id': marketId,
601
+ 'symbol': symbol,
602
+ 'base': base,
603
+ 'quote': quote,
604
+ 'settle': quote,
605
+ 'baseId': baseId,
606
+ 'quoteId': quoteId,
607
+ 'settleId': quoteId,
608
+ 'type': 'swap',
609
+ 'spot': False,
610
+ 'margin': False,
611
+ 'swap': True,
612
+ 'future': False,
613
+ 'option': False,
614
+ 'active': self.safe_string(market, 'status', '') == 'active',
615
+ 'contract': True,
616
+ 'linear': True,
617
+ 'inverse': False,
618
+ 'taker': self.safe_number(fees, 'taker'),
619
+ 'maker': self.safe_number(fees, 'maker'),
620
+ 'contractSize': self.parse_number('1'),
621
+ 'expiry': None,
622
+ 'expiryDatetime': None,
623
+ 'strike': None,
624
+ 'optionType': None,
625
+ 'precision': {
626
+ 'amount': self.safe_number(lotFilter, 'stepSize'),
627
+ 'price': self.safe_number(priceFilter, 'tickSize'),
628
+ },
629
+ 'limits': {
630
+ 'leverage': {
631
+ 'min': None,
632
+ 'max': self.safe_number(market, 'cappedLeverage'),
633
+ },
634
+ 'amount': {
635
+ 'min': self.safe_number(lotFilter, 'minQty'),
636
+ 'max': self.safe_number(lotFilter, 'maxQty'),
637
+ },
638
+ 'price': {
639
+ 'min': self.safe_number(priceFilter, 'minPrice'),
640
+ 'max': self.safe_number(priceFilter, 'maxPrice'),
641
+ },
642
+ 'cost': {
643
+ 'min': self.safe_number(notionalFilter, 'minNotional'),
644
+ 'max': None,
645
+ },
646
+ 'market': {
647
+ 'min': self.safe_number(marketLotFilter, 'minQty'),
648
+ 'max': self.safe_number(marketLotFilter, 'maxQty'),
649
+ },
650
+ },
651
+ 'created': None,
652
+ 'info': market,
653
+ }
654
+
655
+ async def fetch_ticker(self, symbol: str, params={}) -> Ticker:
656
+ """
657
+ fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
658
+
659
+ https://api-docs.defx.com/#fe6f81d0-2f3a-4eee-976f-c8fc8f4c5d56
660
+
661
+ :param str symbol: unified symbol of the market to fetch the ticker for
662
+ :param dict [params]: extra parameters specific to the exchange API endpoint
663
+ :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
664
+ """
665
+ await self.load_markets()
666
+ market = self.market(symbol)
667
+ request: dict = {
668
+ 'symbol': market['id'],
669
+ }
670
+ response = await self.v1PublicGetSymbolsSymbolTicker24hr(self.extend(request, params))
671
+ #
672
+ # {
673
+ # "symbol": "BTC_USDC",
674
+ # "priceChange": "0",
675
+ # "priceChangePercent": "0",
676
+ # "weightedAvgPrice": "0",
677
+ # "lastPrice": "2.00",
678
+ # "lastQty": "10.000",
679
+ # "bestBidPrice": "1646.00",
680
+ # "bestBidQty": "10.000",
681
+ # "bestAskPrice": "1646.00",
682
+ # "bestAskQty": "10.000",
683
+ # "openPrice": "0.00",
684
+ # "highPrice": "0.00",
685
+ # "lowPrice": "0.00",
686
+ # "volume": "0.000",
687
+ # "quoteVolume": "0.00",
688
+ # "openTime": 1700142658697,
689
+ # "closeTime": 1700142658697,
690
+ # "openInterestBase": "1.000",
691
+ # "openInterestQuote": "0.43112300"
692
+ # }
693
+ #
694
+ return self.parse_ticker(response, market)
695
+
696
+ async def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
697
+ """
698
+ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
699
+
700
+ https://api-docs.defx.com/#8c61cfbd-40d9-410e-b014-f5b36eba51d1
701
+
702
+ :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
703
+ :param dict [params]: extra parameters specific to the exchange API endpoint
704
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
705
+ """
706
+ await self.load_markets()
707
+ market = None
708
+ if symbols is not None:
709
+ symbols = self.market_symbols(symbols)
710
+ firstSymbol = self.safe_string(symbols, 0)
711
+ if firstSymbol is not None:
712
+ market = self.market(firstSymbol)
713
+ type = None
714
+ type, params = self.handle_market_type_and_params('fetchTickers', market, params)
715
+ if type == 'spot':
716
+ raise NotSupported(self.id + ' fetchTickers() is not supported for ' + type + ' markets')
717
+ response = await self.v1PublicGetTicker24HrAgg(params)
718
+ #
719
+ # {
720
+ # "ETH_USDC": {
721
+ # "priceChange": "0",
722
+ # "priceChangePercent": "0",
723
+ # "openPrice": "1646.15",
724
+ # "highPrice": "1646.15",
725
+ # "lowPrice": "1646.15",
726
+ # "lastPrice": "1646.15",
727
+ # "quoteVolume": "13.17",
728
+ # "volume": "0.008",
729
+ # "markPrice": "1645.15"
730
+ # }
731
+ # }
732
+ #
733
+ return self.parse_tickers(response, symbols)
734
+
735
+ def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
736
+ #
737
+ # fetchTicker
738
+ #
739
+ # {
740
+ # "symbol": "BTC_USDC",
741
+ # "priceChange": "0",
742
+ # "priceChangePercent": "0",
743
+ # "weightedAvgPrice": "0",
744
+ # "lastPrice": "2.00",
745
+ # "lastQty": "10.000",
746
+ # "bestBidPrice": "1646.00",
747
+ # "bestBidQty": "10.000",
748
+ # "bestAskPrice": "1646.00",
749
+ # "bestAskQty": "10.000",
750
+ # "openPrice": "0.00",
751
+ # "highPrice": "0.00",
752
+ # "lowPrice": "0.00",
753
+ # "volume": "0.000",
754
+ # "quoteVolume": "0.00",
755
+ # "openTime": 1700142658697,
756
+ # "closeTime": 1700142658697,
757
+ # "openInterestBase": "1.000",
758
+ # "openInterestQuote": "0.43112300"
759
+ # }
760
+ #
761
+ # fetchTickers
762
+ #
763
+ # "ETH_USDC": {
764
+ # "priceChange": "0",
765
+ # "priceChangePercent": "0",
766
+ # "openPrice": "1646.15",
767
+ # "highPrice": "1646.15",
768
+ # "lowPrice": "1646.15",
769
+ # "lastPrice": "1646.15",
770
+ # "quoteVolume": "13.17",
771
+ # "volume": "0.008",
772
+ # "markPrice": "1645.15"
773
+ # }
774
+ #
775
+ # fetchMarkPrice
776
+ #
777
+ # {
778
+ # "markPrice": "100.00",
779
+ # "indexPrice": "100.00",
780
+ # "ltp": "101.34",
781
+ # "movingFundingRate": "0.08",
782
+ # "payoutFundingRate": "-0.03",
783
+ # "nextFundingPayout": 1711555532146
784
+ # }
785
+ #
786
+ marketId = self.safe_string(ticker, 'symbol')
787
+ if marketId is not None:
788
+ market = self.market(marketId)
789
+ symbol = market['symbol']
790
+ open = self.safe_string(ticker, 'openPrice')
791
+ high = self.safe_string(ticker, 'highPrice')
792
+ low = self.safe_string(ticker, 'lowPrice')
793
+ close = self.safe_string(ticker, 'lastPrice')
794
+ quoteVolume = self.safe_string(ticker, 'quoteVolume')
795
+ baseVolume = self.safe_string(ticker, 'volume')
796
+ percentage = self.safe_string(ticker, 'priceChangePercent')
797
+ change = self.safe_string(ticker, 'priceChange')
798
+ ts = self.safe_integer(ticker, 'closeTime')
799
+ if ts == 0:
800
+ ts = None
801
+ datetime = self.iso8601(ts)
802
+ bid = self.safe_string(ticker, 'bestBidPrice')
803
+ bidVolume = self.safe_string(ticker, 'bestBidQty')
804
+ ask = self.safe_string(ticker, 'bestAskPrice')
805
+ askVolume = self.safe_string(ticker, 'bestAskQty')
806
+ return self.safe_ticker({
807
+ 'symbol': symbol,
808
+ 'timestamp': ts,
809
+ 'datetime': datetime,
810
+ 'high': high,
811
+ 'low': low,
812
+ 'bid': bid,
813
+ 'bidVolume': bidVolume,
814
+ 'ask': ask,
815
+ 'askVolume': askVolume,
816
+ 'vwap': None,
817
+ 'open': open,
818
+ 'close': close,
819
+ 'last': None,
820
+ 'previousClose': None,
821
+ 'change': change,
822
+ 'percentage': percentage,
823
+ 'average': None,
824
+ 'baseVolume': baseVolume,
825
+ 'quoteVolume': quoteVolume,
826
+ 'markPrice': self.safe_string(ticker, 'markPrice'),
827
+ 'indexPrice': self.safe_string(ticker, 'indexPrice'),
828
+ 'info': ticker,
829
+ }, market)
830
+
831
+ async def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
832
+ """
833
+
834
+ https://api-docs.defx.com/#54b71951-1472-4670-b5af-4c2dc41e73d0
835
+
836
+ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
837
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
838
+ :param str timeframe: the length of time each candle represents
839
+ :param int [since]: timestamp in ms of the earliest candle to fetch
840
+ :param int [limit]: max=1000, max=100 when since is defined and is less than(now - (999 * (timeframe in ms)))
841
+ :param dict [params]: extra parameters specific to the exchange API endpoint
842
+ :param int [params.until]: the latest time in ms to fetch orders for
843
+ :returns int[][]: A list of candles ordered, open, high, low, close, volume
844
+ """
845
+ await self.load_markets()
846
+ market = self.market(symbol)
847
+ maxLimit = 1000
848
+ if limit is None:
849
+ limit = maxLimit
850
+ limit = min(maxLimit, limit)
851
+ request: dict = {
852
+ 'symbol': market['id'],
853
+ 'interval': self.safe_string(self.timeframes, timeframe, timeframe),
854
+ 'limit': limit,
855
+ }
856
+ until = self.safe_integer_2(params, 'until', 'till')
857
+ params = self.omit(params, ['until', 'till'])
858
+ request['endTime'] = self.milliseconds() if (until is None) else until
859
+ if since is None:
860
+ request['startTime'] = 0
861
+ else:
862
+ request['startTime'] = since
863
+ if until is None:
864
+ timeframeInSeconds = self.parse_timeframe(timeframe)
865
+ timeframeInMilliseconds = timeframeInSeconds * 1000
866
+ totalTimeframeInMilliseconds = limit * timeframeInMilliseconds
867
+ request['endTime'] = self.sum(since, totalTimeframeInMilliseconds)
868
+ response = await self.v1PublicGetSymbolsSymbolOhlc(self.extend(request, params))
869
+ #
870
+ # [
871
+ # {
872
+ # "symbol": "BTC_USDC",
873
+ # "open": "0.00",
874
+ # "high": "0.00",
875
+ # "low": "0.00",
876
+ # "close": "0.00",
877
+ # "volume": "0.000",
878
+ # "quoteAssetVolume": "0.00",
879
+ # "takerBuyAssetVolume": "0.000",
880
+ # "takerBuyQuoteAssetVolume": "0.00",
881
+ # "numberOfTrades": 0,
882
+ # "start": 1702453663894,
883
+ # "end": 1702453663894,
884
+ # "isClosed": True
885
+ # }
886
+ # ]
887
+ #
888
+ return self.parse_ohlcvs(response, market, timeframe, since, limit)
889
+
890
+ def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
891
+ # example response in fetchOHLCV
892
+ return [
893
+ self.safe_integer(ohlcv, 'start'),
894
+ self.safe_number(ohlcv, 'open'),
895
+ self.safe_number(ohlcv, 'high'),
896
+ self.safe_number(ohlcv, 'low'),
897
+ self.safe_number(ohlcv, 'close'),
898
+ self.safe_number(ohlcv, 'volume'),
899
+ ]
900
+
901
+ async def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
902
+ """
903
+ get the list of most recent trades for a particular symbol
904
+
905
+ https://api-docs.defx.com/#5865452f-ea32-4f13-bfbc-03af5f5574fd
906
+
907
+ :param str symbol: unified symbol of the market to fetch trades for
908
+ :param int [since]: timestamp in ms of the earliest trade to fetch
909
+ :param int [limit]: the maximum amount of trades to fetch
910
+ :param dict [params]: extra parameters specific to the exchange API endpoint
911
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
912
+ """
913
+ await self.load_markets()
914
+ market = self.market(symbol)
915
+ maxLimit = 50
916
+ if limit is None:
917
+ limit = maxLimit
918
+ limit = min(maxLimit, limit)
919
+ request: dict = {
920
+ 'symbol': market['id'],
921
+ 'limit': limit,
922
+ }
923
+ response = await self.v1PublicGetSymbolsSymbolTrades(self.extend(request, params))
924
+ #
925
+ # [
926
+ # {
927
+ # "buyerMaker": "false",
928
+ # "price": "2.0000",
929
+ # "qty": "10.0000",
930
+ # "symbol": "BTC_USDC",
931
+ # "timestamp": "1702453663894"
932
+ # }
933
+ # ]
934
+ #
935
+ return self.parse_trades(response, market, since, limit)
936
+
937
+ async def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
938
+ """
939
+ fetch all trades made by the user
940
+
941
+ https://api-docs.defx.com/#06b5b33c-2fc6-48de-896c-fc316f5871a7
942
+
943
+ :param str symbol: unified symbol of the market to fetch trades for
944
+ :param int [since]: timestamp in ms of the earliest trade to fetch
945
+ :param int [limit]: the maximum amount of trades to fetch
946
+ :param dict [params]: extra parameters specific to the exchange API endpoint
947
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
948
+ """
949
+ await self.load_markets()
950
+ request: dict = {}
951
+ if symbol is not None:
952
+ market = self.market(symbol)
953
+ request['symbols'] = market['id']
954
+ if limit is not None:
955
+ maxLimit = 100
956
+ limit = min(maxLimit, limit)
957
+ request['pageSize'] = limit
958
+ response = await self.v1PrivateGetApiTrades(self.extend(request, params))
959
+ #
960
+ # {
961
+ # "data": [
962
+ # {
963
+ # "id": "0192f665-c05b-7ba0-a080-8b6c99083489",
964
+ # "orderId": "757730811259651728",
965
+ # "time": "2024-11-04T08:58:36.474Z",
966
+ # "symbol": "SOL_USDC",
967
+ # "side": "SELL",
968
+ # "price": "160.43600000",
969
+ # "qty": "1.00",
970
+ # "fee": "0.08823980",
971
+ # "role": "TAKER",
972
+ # "pnl": "0.00000000"
973
+ # }
974
+ # ]
975
+ # }
976
+ #
977
+ data = self.safe_list(response, 'data', [])
978
+ return self.parse_trades(data, None, since, limit)
979
+
980
+ def parse_trade(self, trade: dict, market: Market = None) -> Trade:
981
+ #
982
+ # fetchTrades
983
+ # {
984
+ # "buyerMaker": "false",
985
+ # "price": "2.0000",
986
+ # "qty": "10.0000",
987
+ # "symbol": "BTC_USDC",
988
+ # "timestamp": "1702453663894"
989
+ # }
990
+ #
991
+ # fetchMyTrades
992
+ # {
993
+ # "id": "0192f665-c05b-7ba0-a080-8b6c99083489",
994
+ # "orderId": "757730811259651728",
995
+ # "time": "2024-11-04T08:58:36.474Z",
996
+ # "symbol": "SOL_USDC",
997
+ # "side": "SELL",
998
+ # "price": "160.43600000",
999
+ # "qty": "1.00",
1000
+ # "fee": "0.08823980",
1001
+ # "role": "TAKER",
1002
+ # "pnl": "0.00000000"
1003
+ # }
1004
+ #
1005
+ time = self.safe_string(trade, 'time')
1006
+ timestamp = self.safe_integer(trade, 'timestamp', self.parse8601(time))
1007
+ marketId = self.safe_string(trade, 'symbol')
1008
+ market = self.safe_market(marketId, market)
1009
+ symbol = market['symbol']
1010
+ price = self.safe_string(trade, 'price')
1011
+ amount = self.safe_string(trade, 'qty')
1012
+ id = self.safe_string(trade, 'id')
1013
+ oid = self.safe_string(trade, 'orderId')
1014
+ takerOrMaker = self.safe_string_lower(trade, 'role')
1015
+ buyerMaker = self.safe_bool(trade, 'buyerMaker')
1016
+ side = self.safe_string_lower(trade, 'side')
1017
+ if buyerMaker is not None:
1018
+ if buyerMaker:
1019
+ side = 'sell'
1020
+ else:
1021
+ side = 'buy'
1022
+ return self.safe_trade({
1023
+ 'id': id,
1024
+ 'timestamp': timestamp,
1025
+ 'datetime': self.iso8601(timestamp),
1026
+ 'symbol': symbol,
1027
+ 'side': side,
1028
+ 'price': price,
1029
+ 'amount': amount,
1030
+ 'cost': None,
1031
+ 'order': oid,
1032
+ 'takerOrMaker': takerOrMaker,
1033
+ 'type': None,
1034
+ 'fee': {
1035
+ 'cost': self.safe_string(trade, 'fee'),
1036
+ 'currency': 'USDC',
1037
+ },
1038
+ 'info': trade,
1039
+ }, market)
1040
+
1041
+ async def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
1042
+ """
1043
+ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
1044
+
1045
+ https://api-docs.defx.com/#6c1a2971-8325-4e7d-9962-e0bfcaacf9c4
1046
+
1047
+ :param str symbol: unified symbol of the market to fetch the order book for
1048
+ :param int [limit]: the maximum amount of order book entries to return
1049
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1050
+ :param str [params.slab]: slab from market.info.depthSlabs
1051
+ :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
1052
+ """
1053
+ await self.load_markets()
1054
+ market = self.market(symbol)
1055
+ if limit is None:
1056
+ limit = 10 # limit must be one of [5, 10, 20]
1057
+ marketInfo = self.safe_dict(market, 'info', {})
1058
+ slab = self.safe_list(marketInfo, 'depthSlabs', [])
1059
+ request: dict = {
1060
+ 'symbol': market['id'],
1061
+ 'level': limit,
1062
+ 'slab': self.safe_string(slab, 0),
1063
+ }
1064
+ response = await self.v1PublicGetSymbolsSymbolDepthLevelSlab(self.extend(request, params))
1065
+ #
1066
+ # {
1067
+ # "symbol": "ETH_USDC",
1068
+ # "level": "5",
1069
+ # "slab": "1",
1070
+ # "lastTradeTimestamp": "1708313446812",
1071
+ # "timestamp": "1708313446812",
1072
+ # "bids": [
1073
+ # {
1074
+ # "price": "1646.16",
1075
+ # "qty": "0.001"
1076
+ # }
1077
+ # ],
1078
+ # "asks": [
1079
+ # {
1080
+ # "price": "1646.16",
1081
+ # "qty": "0.001"
1082
+ # }
1083
+ # ]
1084
+ # }
1085
+ #
1086
+ timestamp = self.safe_integer(response, 'timestamp')
1087
+ return self.parse_order_book(response, symbol, timestamp, 'bids', 'asks', 'price', 'qty')
1088
+
1089
+ async def fetch_mark_price(self, symbol: str, params={}) -> Ticker:
1090
+ """
1091
+ fetches mark price for the market
1092
+
1093
+ https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7
1094
+
1095
+ :param str symbol: unified symbol of the market to fetch the ticker for
1096
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1097
+ :param str [params.subType]: "linear" or "inverse"
1098
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
1099
+ """
1100
+ await self.load_markets()
1101
+ market = self.market(symbol)
1102
+ request = {
1103
+ 'symbol': market['id'],
1104
+ }
1105
+ response = await self.v1PublicGetSymbolsSymbolPrices(self.extend(request, params))
1106
+ #
1107
+ # {
1108
+ # "markPrice": "100.00",
1109
+ # "indexPrice": "100.00",
1110
+ # "ltp": "101.34",
1111
+ # "movingFundingRate": "0.08",
1112
+ # "payoutFundingRate": "-0.03",
1113
+ # "nextFundingPayout": 1711555532146
1114
+ # }
1115
+ #
1116
+ return self.parse_ticker(response, market)
1117
+
1118
+ async def fetch_funding_rate(self, symbol: str, params={}) -> FundingRate:
1119
+ """
1120
+ fetch the current funding rate
1121
+
1122
+ https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7
1123
+
1124
+ :param str symbol: unified market symbol
1125
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1126
+ :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
1127
+ """
1128
+ await self.load_markets()
1129
+ market = self.market(symbol)
1130
+ request = {
1131
+ 'symbol': market['id'],
1132
+ }
1133
+ response = await self.v1PublicGetSymbolsSymbolPrices(self.extend(request, params))
1134
+ #
1135
+ # {
1136
+ # "markPrice": "100.00",
1137
+ # "indexPrice": "100.00",
1138
+ # "ltp": "101.34",
1139
+ # "movingFundingRate": "0.08",
1140
+ # "payoutFundingRate": "-0.03",
1141
+ # "nextFundingPayout": 1711555532146
1142
+ # }
1143
+ #
1144
+ return self.parse_funding_rate(response, market)
1145
+
1146
+ def parse_funding_rate(self, contract, market: Market = None) -> FundingRate:
1147
+ #
1148
+ # {
1149
+ # "markPrice": "100.00",
1150
+ # "indexPrice": "100.00",
1151
+ # "ltp": "101.34",
1152
+ # "movingFundingRate": "0.08",
1153
+ # "payoutFundingRate": "-0.03",
1154
+ # "nextFundingPayout": 1711555532146
1155
+ # }
1156
+ #
1157
+ markPrice = self.safe_number(contract, 'markPrice')
1158
+ indexPrice = self.safe_number(contract, 'indexPrice')
1159
+ fundingRate = self.safe_number(contract, 'payoutFundingRate')
1160
+ fundingTime = self.safe_integer(contract, 'nextFundingPayout')
1161
+ return {
1162
+ 'info': contract,
1163
+ 'symbol': market['symbol'],
1164
+ 'markPrice': markPrice,
1165
+ 'indexPrice': indexPrice,
1166
+ 'interestRate': None,
1167
+ 'estimatedSettlePrice': None,
1168
+ 'timestamp': None,
1169
+ 'datetime': None,
1170
+ 'fundingRate': fundingRate,
1171
+ 'fundingTimestamp': fundingTime,
1172
+ 'fundingDatetime': self.iso8601(fundingTime),
1173
+ 'nextFundingRate': None,
1174
+ 'nextFundingTimestamp': None,
1175
+ 'nextFundingDatetime': None,
1176
+ 'previousFundingRate': None,
1177
+ 'previousFundingTimestamp': None,
1178
+ 'previousFundingDatetime': None,
1179
+ 'interval': None,
1180
+ }
1181
+
1182
+ async def fetch_balance(self, params={}) -> Balances:
1183
+ """
1184
+ query for balance and get the amount of funds available for trading or funds locked in orders
1185
+
1186
+ https://api-docs.defx.com/#26414338-14f7-40a1-b246-f8ea8571493f
1187
+
1188
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1189
+ :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
1190
+ """
1191
+ await self.load_markets()
1192
+ response = await self.v1PrivateGetApiWalletBalance(params)
1193
+ #
1194
+ # {
1195
+ # "assets": [
1196
+ # {
1197
+ # "asset": "USDC",
1198
+ # "balance": "0.000"
1199
+ # }
1200
+ # ]
1201
+ # }
1202
+ #
1203
+ data = self.safe_list(response, 'assets')
1204
+ return self.parse_balance(data)
1205
+
1206
+ def parse_balance(self, balances) -> Balances:
1207
+ result: dict = {
1208
+ 'info': balances,
1209
+ }
1210
+ for i in range(0, len(balances)):
1211
+ balance = balances[i]
1212
+ code = self.safe_currency_code(self.safe_string(balance, 'asset'))
1213
+ account = self.account()
1214
+ account['total'] = self.safe_string(balance, 'balance')
1215
+ result[code] = account
1216
+ return self.safe_balance(result)
1217
+
1218
+ async def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1219
+ """
1220
+ create a trade order
1221
+
1222
+ https://api-docs.defx.com/#ba222d88-8856-4d3c-87a9-7cec07bb2622
1223
+
1224
+ :param str symbol: unified symbol of the market to create an order in
1225
+ :param str type: 'market' or 'limit'
1226
+ :param str side: 'buy' or 'sell'
1227
+ :param float amount: how much of currency you want to trade in units of base currency
1228
+ :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1229
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1230
+ :param float [params.triggerPrice]: The price a trigger order is triggered at
1231
+ :param str [params.reduceOnly]: for swap and future reduceOnly is a string 'true' or 'false' that cant be sent with close position set to True or in hedge mode. For spot margin and option reduceOnly is a boolean.
1232
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1233
+ """
1234
+ await self.load_markets()
1235
+ market = self.market(symbol)
1236
+ reduceOnly = self.safe_bool_2(params, 'reduceOnly', 'reduce_only')
1237
+ params = self.omit(params, ['reduceOnly', 'reduce_only'])
1238
+ orderType = type.upper()
1239
+ orderSide = side.upper()
1240
+ request: dict = {
1241
+ 'symbol': market['id'],
1242
+ 'side': orderSide,
1243
+ 'type': orderType,
1244
+ }
1245
+ takeProfitPrice = self.safe_string(params, 'takeProfitPrice')
1246
+ triggerPrice = self.safe_string_2(params, 'stopPrice', 'triggerPrice')
1247
+ isMarket = orderType == 'MARKET'
1248
+ isLimit = orderType == 'LIMIT'
1249
+ timeInForce = self.safe_string_upper(params, 'timeInForce')
1250
+ if timeInForce is not None:
1251
+ # GTC, IOC, FOK, AON
1252
+ request['timeInForce'] = timeInForce
1253
+ else:
1254
+ if isLimit:
1255
+ request['timeInForce'] = 'GTC'
1256
+ if reduceOnly:
1257
+ request['reduceOnly'] = reduceOnly
1258
+ clientOrderId = self.safe_string(params, 'clientOrderId')
1259
+ if clientOrderId is not None:
1260
+ request['newClientOrderId'] = clientOrderId
1261
+ if triggerPrice is not None or takeProfitPrice is not None:
1262
+ request['workingType'] = 'MARK_PRICE'
1263
+ if takeProfitPrice is not None:
1264
+ request['stopPrice'] = self.price_to_precision(symbol, takeProfitPrice)
1265
+ if isMarket:
1266
+ request['type'] = 'TAKE_PROFIT_MARKET'
1267
+ else:
1268
+ request['type'] = 'TAKE_PROFIT_LIMIT'
1269
+ else:
1270
+ request['stopPrice'] = self.price_to_precision(symbol, triggerPrice)
1271
+ if isMarket:
1272
+ request['type'] = 'STOP_MARKET'
1273
+ else:
1274
+ request['type'] = 'STOP_LIMIT'
1275
+ if isLimit and price is not None:
1276
+ request['price'] = self.price_to_precision(symbol, price)
1277
+ request['quantity'] = self.amount_to_precision(symbol, amount)
1278
+ params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce', 'stopPrice', 'triggerPrice', 'takeProfitPrice'])
1279
+ response = await self.v1PrivatePostApiOrder(self.extend(request, params))
1280
+ #
1281
+ # {
1282
+ # "success": True,
1283
+ # "data": {
1284
+ # "orderId": "",
1285
+ # "clientOrderId": "",
1286
+ # "cumulativeQty": "",
1287
+ # "cumulativeQuote": "",
1288
+ # "executedQty": "",
1289
+ # "avgPrice": "",
1290
+ # "origQty": "",
1291
+ # "price": "",
1292
+ # "reduceOnly": True,
1293
+ # "side": "",
1294
+ # "status": "",
1295
+ # "symbol": "",
1296
+ # "timeInForce": "",
1297
+ # "type": "",
1298
+ # "workingType": ""
1299
+ # }
1300
+ # }
1301
+ #
1302
+ data = self.safe_dict(response, 'data')
1303
+ return self.parse_order(data, market)
1304
+
1305
+ def parse_order_status(self, status: Str):
1306
+ if status is not None:
1307
+ statuses: dict = {
1308
+ 'NEW': 'open',
1309
+ 'OPEN': 'open',
1310
+ 'CANCELLED': 'canceled',
1311
+ 'REJECTED': 'rejected',
1312
+ 'FILLED': 'closed',
1313
+ }
1314
+ return self.safe_string(statuses, status, status)
1315
+ return status
1316
+
1317
+ def parse_order(self, order: dict, market: Market = None) -> Order:
1318
+ #
1319
+ # {
1320
+ # "orderId": "746472647227344528",
1321
+ # "createdAt": "2024-10-25T16:49:31.077Z",
1322
+ # "updatedAt": "2024-10-25T16:49:31.378Z",
1323
+ # "clientOrderId": "0192c495-49c3-71ee-b3d3-7442a2090807",
1324
+ # "reduceOnly": False,
1325
+ # "side": "SELL",
1326
+ # "status": "FILLED",
1327
+ # "symbol": "SOL_USDC",
1328
+ # "timeInForce": "GTC",
1329
+ # "type": "MARKET",
1330
+ # "origQty": "0.80",
1331
+ # "executedQty": "0.80",
1332
+ # "cumulativeQuote": "137.87440000",
1333
+ # "avgPrice": "172.34300000",
1334
+ # "totalPnL": "0.00000000",
1335
+ # "totalFee": "0.07583092",
1336
+ # "workingType": null,
1337
+ # "postOnly": False,
1338
+ # "linkedOrderParentType": null,
1339
+ # "isTriggered": False,
1340
+ # "slippagePercentage": "5"
1341
+ # }
1342
+ #
1343
+ orderId = self.safe_string(order, 'orderId')
1344
+ clientOrderId = self.safe_string(order, 'clientOrderId')
1345
+ marketId = self.safe_string(order, 'symbol')
1346
+ market = self.safe_market(marketId, market)
1347
+ symbol = market['symbol']
1348
+ price = self.safe_string(order, 'price')
1349
+ amount = self.safe_string(order, 'origQty')
1350
+ orderType = self.safe_string_lower(order, 'type')
1351
+ status = self.safe_string(order, 'status')
1352
+ side = self.safe_string_lower(order, 'side')
1353
+ filled = self.omit_zero(self.safe_string(order, 'executedQty'))
1354
+ average = self.omit_zero(self.safe_string(order, 'avgPrice'))
1355
+ timeInForce = self.safe_string_lower(order, 'timeInForce')
1356
+ takeProfitPrice: Str = None
1357
+ triggerPrice: Str = None
1358
+ if orderType is not None:
1359
+ if orderType.find('take_profit') >= 0:
1360
+ takeProfitPrice = self.safe_string(order, 'stopPrice')
1361
+ else:
1362
+ triggerPrice = self.safe_string(order, 'stopPrice')
1363
+ timestamp = self.parse8601(self.safe_string(order, 'createdAt'))
1364
+ lastTradeTimestamp = self.parse8601(self.safe_string(order, 'updatedAt'))
1365
+ return self.safe_order({
1366
+ 'id': orderId,
1367
+ 'clientOrderId': clientOrderId,
1368
+ 'timestamp': timestamp,
1369
+ 'datetime': self.iso8601(timestamp),
1370
+ 'lastTradeTimestamp': lastTradeTimestamp,
1371
+ 'lastUpdateTimestamp': lastTradeTimestamp,
1372
+ 'status': self.parse_order_status(status),
1373
+ 'symbol': symbol,
1374
+ 'type': orderType,
1375
+ 'timeInForce': timeInForce,
1376
+ 'postOnly': self.safe_bool(order, 'postOnly'),
1377
+ 'reduceOnly': self.safe_bool(order, 'reduceOnly'),
1378
+ 'side': side,
1379
+ 'price': price,
1380
+ 'triggerPrice': triggerPrice,
1381
+ 'takeProfitPrice': takeProfitPrice,
1382
+ 'stopLossPrice': None,
1383
+ 'average': average,
1384
+ 'amount': amount,
1385
+ 'filled': filled,
1386
+ 'remaining': None,
1387
+ 'cost': None,
1388
+ 'trades': None,
1389
+ 'fee': {
1390
+ 'cost': self.safe_string(order, 'totalFee'),
1391
+ 'currency': 'USDC',
1392
+ },
1393
+ 'info': order,
1394
+ }, market)
1395
+
1396
+ async def cancel_order(self, id: str, symbol: Str = None, params={}):
1397
+ """
1398
+
1399
+ https://api-docs.defx.com/#09186f23-f8d1-4993-acf4-9974d8a6ddb0
1400
+
1401
+ cancels an open order
1402
+ :param str id: order id
1403
+ :param str symbol: unified symbol of the market the order was made in
1404
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1405
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1406
+ """
1407
+ await self.load_markets()
1408
+ request: dict = {
1409
+ 'orderId': id,
1410
+ 'idType': 'orderId',
1411
+ }
1412
+ clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1413
+ isByClientOrder = clientOrderId is not None
1414
+ if isByClientOrder:
1415
+ if symbol is None:
1416
+ raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
1417
+ market = self.market(symbol)
1418
+ request['orderId'] = clientOrderId
1419
+ request['idType'] = 'clientOrderId'
1420
+ request['symbol'] = market['id']
1421
+ params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1422
+ response = await self.v1PrivateDeleteApiOrderOrderId(self.extend(request, params))
1423
+ #
1424
+ # {
1425
+ # "success": True
1426
+ # }
1427
+ #
1428
+ extendParams: dict = {'symbol': symbol}
1429
+ if isByClientOrder:
1430
+ extendParams['clientOrderId'] = clientOrderId
1431
+ else:
1432
+ extendParams['id'] = id
1433
+ return self.extend(self.parse_order(response), extendParams)
1434
+
1435
+ async def cancel_all_orders(self, symbol: Str = None, params={}):
1436
+ """
1437
+ cancel all open orders
1438
+
1439
+ https://api-docs.defx.com/#db5531da-3692-4a53-841f-6ad6495f823a
1440
+
1441
+ :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
1442
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1443
+ :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1444
+ """
1445
+ await self.load_markets()
1446
+ market = self.market(symbol)
1447
+ request: dict = {
1448
+ 'symbols': [market['id']],
1449
+ }
1450
+ response = await self.v1PrivateDeleteApiOrdersAllOpen(self.extend(request, params))
1451
+ #
1452
+ # {
1453
+ # "data": {
1454
+ # "msg": "The operation of cancel all open order is done."
1455
+ # }
1456
+ # }
1457
+ #
1458
+ return [self.safe_order({'info': response})]
1459
+
1460
+ async def fetch_position(self, symbol: str, params={}):
1461
+ """
1462
+ fetch data on a single open contract trade position
1463
+
1464
+ https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e
1465
+
1466
+ :param str symbol: unified market symbol of the market the position is held in, default is None
1467
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1468
+ :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
1469
+ """
1470
+ if symbol is None:
1471
+ raise ArgumentsRequired(self.id + ' fetchPosition() requires a symbol argument')
1472
+ await self.load_markets()
1473
+ market = self.market(symbol)
1474
+ request: dict = {
1475
+ 'symbol': market['id'],
1476
+ }
1477
+ response = await self.v1PrivateGetApiPositionActive(self.extend(request, params))
1478
+ #
1479
+ # {
1480
+ # "data": [
1481
+ # {
1482
+ # "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
1483
+ # "symbol": "SOL_USDC",
1484
+ # "positionSide": "SHORT",
1485
+ # "entryPrice": "172.34300000",
1486
+ # "quantity": "0.80",
1487
+ # "marginAmount": "20.11561173",
1488
+ # "marginAsset": "USDC",
1489
+ # "pnl": "0.00000000"
1490
+ # }
1491
+ # ]
1492
+ # }
1493
+ #
1494
+ data = self.safe_list(response, 'data', [])
1495
+ first = self.safe_dict(data, 0, {})
1496
+ return self.parse_position(first, market)
1497
+
1498
+ async def fetch_positions(self, symbols: Strings = None, params={}) -> List[Position]:
1499
+ """
1500
+ fetch all open positions
1501
+
1502
+ https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e
1503
+
1504
+ :param str[] [symbols]: list of unified market symbols
1505
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1506
+ :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
1507
+ """
1508
+ await self.load_markets()
1509
+ response = await self.v1PrivateGetApiPositionActive(params)
1510
+ #
1511
+ # {
1512
+ # "data": [
1513
+ # {
1514
+ # "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
1515
+ # "symbol": "SOL_USDC",
1516
+ # "positionSide": "SHORT",
1517
+ # "entryPrice": "172.34300000",
1518
+ # "quantity": "0.80",
1519
+ # "marginAmount": "20.11561173",
1520
+ # "marginAsset": "USDC",
1521
+ # "pnl": "0.00000000"
1522
+ # }
1523
+ # ]
1524
+ # }
1525
+ #
1526
+ positions = self.safe_list(response, 'data', [])
1527
+ return self.parse_positions(positions, symbols)
1528
+
1529
+ def parse_position(self, position: dict, market: Market = None):
1530
+ #
1531
+ # {
1532
+ # "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
1533
+ # "symbol": "SOL_USDC",
1534
+ # "positionSide": "SHORT",
1535
+ # "entryPrice": "172.34300000",
1536
+ # "quantity": "0.80",
1537
+ # "marginAmount": "20.11561173",
1538
+ # "marginAsset": "USDC",
1539
+ # "pnl": "0.00000000"
1540
+ # }
1541
+ #
1542
+ marketId = self.safe_string(position, 'symbol')
1543
+ market = self.safe_market(marketId, market)
1544
+ size = Precise.string_abs(self.safe_string(position, 'quantity'))
1545
+ side = self.safe_string_lower(position, 'positionSide')
1546
+ unrealisedPnl = self.omit_zero(self.safe_string(position, 'pnl'))
1547
+ entryPrice = self.omit_zero(self.safe_string(position, 'entryPrice'))
1548
+ initialMargin = self.safe_string(position, 'marginAmount')
1549
+ return self.safe_position({
1550
+ 'info': position,
1551
+ 'id': self.safe_string(position, 'positionId'),
1552
+ 'symbol': market['symbol'],
1553
+ 'timestamp': None,
1554
+ 'datetime': None,
1555
+ 'lastUpdateTimestamp': None,
1556
+ 'initialMargin': self.parse_number(initialMargin),
1557
+ 'initialMarginPercentage': None,
1558
+ 'maintenanceMargin': None,
1559
+ 'maintenanceMarginPercentage': None,
1560
+ 'entryPrice': self.parse_number(entryPrice),
1561
+ 'notional': None,
1562
+ 'leverage': None,
1563
+ 'unrealizedPnl': self.parse_number(unrealisedPnl),
1564
+ 'realizedPnl': None,
1565
+ 'contracts': self.parse_number(size),
1566
+ 'contractSize': self.safe_number(market, 'contractSize'),
1567
+ 'marginRatio': None,
1568
+ 'liquidationPrice': None,
1569
+ 'markPrice': None,
1570
+ 'lastPrice': None,
1571
+ 'collateral': None,
1572
+ 'marginMode': None,
1573
+ 'side': side,
1574
+ 'percentage': None,
1575
+ 'stopLossPrice': None,
1576
+ 'takeProfitPrice': None,
1577
+ 'hedged': None,
1578
+ })
1579
+
1580
+ async def fetch_order(self, id: str, symbol: Str = None, params={}):
1581
+ """
1582
+ fetches information on an order made by the user
1583
+
1584
+ https://api-docs.defx.com/#44f82dd5-26b3-4e1f-b4aa-88ceddd65237
1585
+
1586
+ :param str id: the order id
1587
+ :param str symbol: unified symbol of the market the order was made in
1588
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1589
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1590
+ """
1591
+ await self.load_markets()
1592
+ request: dict = {
1593
+ 'orderId': id,
1594
+ 'idType': 'orderId',
1595
+ }
1596
+ clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1597
+ params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1598
+ if clientOrderId is not None:
1599
+ if symbol is None:
1600
+ raise ArgumentsRequired(self.id + ' fetchOrder() requires a symbol argument')
1601
+ market = self.market(symbol)
1602
+ request['orderId'] = clientOrderId
1603
+ request['idType'] = 'clientOrderId'
1604
+ request['symbol'] = market['id']
1605
+ response = await self.v1PrivateGetApiOrderOrderId(self.extend(request, params))
1606
+ #
1607
+ # {
1608
+ # "success": True,
1609
+ # "data": {
1610
+ # "orderId": "555068654076559792",
1611
+ # "createdAt": "2024-05-08T05:45:42.148Z",
1612
+ # "updatedAt": "2024-05-08T05:45:42.166Z",
1613
+ # "clientOrderId": "dummyClientOrderId",
1614
+ # "reduceOnly": False,
1615
+ # "side": "SELL",
1616
+ # "status": "REJECTED",
1617
+ # "symbol": "BTC_USDC",
1618
+ # "timeInForce": "GTC",
1619
+ # "type": "TAKE_PROFIT_MARKET",
1620
+ # "origQty": "1.000",
1621
+ # "executedQty": "0.000",
1622
+ # "cumulativeQuote": "0.00",
1623
+ # "avgPrice": "0.00",
1624
+ # "stopPrice": "65000.00",
1625
+ # "totalPnL": "0.00",
1626
+ # "workingType": "MARK_PRICE",
1627
+ # "postOnly": False
1628
+ # }
1629
+ # }
1630
+ #
1631
+ data = self.safe_dict(response, 'data')
1632
+ return self.parse_order(data)
1633
+
1634
+ async def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1635
+ """
1636
+ fetches information on multiple orders made by the user
1637
+
1638
+ https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1639
+
1640
+ :param str symbol: unified market symbol
1641
+ :param int [since]: the earliest time in ms to fetch open orders for
1642
+ :param int [limit]: the maximum number of open order structures to retrieve
1643
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1644
+ :param int [params.until]: the latest time in ms to fetch orders for
1645
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1646
+ """
1647
+ await self.load_markets()
1648
+ request: dict = {}
1649
+ if symbol is not None:
1650
+ market = self.market(symbol)
1651
+ request['symbols'] = market['id']
1652
+ until = self.safe_integer(params, 'until')
1653
+ if until is not None:
1654
+ params = self.omit(params, 'until')
1655
+ request['end'] = self.iso8601(until)
1656
+ if since is not None:
1657
+ request['start'] = self.iso8601(since)
1658
+ if limit is not None:
1659
+ maxLimit = 100
1660
+ limit = min(maxLimit, limit)
1661
+ request['pageSize'] = limit
1662
+ response = await self.v1PrivateGetApiOrders(self.extend(request, params))
1663
+ #
1664
+ # {
1665
+ # "data": [
1666
+ # {
1667
+ # "orderId": "746472647227344528",
1668
+ # "createdAt": "2024-10-25T16:49:31.077Z",
1669
+ # "updatedAt": "2024-10-25T16:49:31.378Z",
1670
+ # "clientOrderId": "0192c495-49c3-71ee-b3d3-7442a2090807",
1671
+ # "reduceOnly": False,
1672
+ # "side": "SELL",
1673
+ # "status": "FILLED",
1674
+ # "symbol": "SOL_USDC",
1675
+ # "timeInForce": "GTC",
1676
+ # "type": "MARKET",
1677
+ # "origQty": "0.80",
1678
+ # "executedQty": "0.80",
1679
+ # "cumulativeQuote": "137.87440000",
1680
+ # "avgPrice": "172.34300000",
1681
+ # "totalPnL": "0.00000000",
1682
+ # "totalFee": "0.07583092",
1683
+ # "workingType": null,
1684
+ # "postOnly": False,
1685
+ # "linkedOrderParentType": null,
1686
+ # "isTriggered": False,
1687
+ # "slippagePercentage": 5
1688
+ # }
1689
+ # ]
1690
+ # }
1691
+ #
1692
+ data = self.safe_list(response, 'data', [])
1693
+ return self.parse_orders(data, None, since, limit)
1694
+
1695
+ async def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1696
+ """
1697
+ fetch all unfilled currently open orders
1698
+
1699
+ https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1700
+
1701
+ :param str symbol: unified market symbol
1702
+ :param int [since]: the earliest time in ms to fetch open orders for
1703
+ :param int [limit]: the maximum number of open order structures to retrieve
1704
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1705
+ :param int [params.until]: the latest time in ms to fetch orders for
1706
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1707
+ """
1708
+ req = {
1709
+ 'statuses': 'OPEN',
1710
+ }
1711
+ return await self.fetch_orders(symbol, since, limit, self.extend(req, params))
1712
+
1713
+ async def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1714
+ """
1715
+ fetches information on multiple closed orders made by the user
1716
+
1717
+ https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1718
+
1719
+ :param str symbol: unified market symbol
1720
+ :param int [since]: the earliest time in ms to fetch open orders for
1721
+ :param int [limit]: the maximum number of open order structures to retrieve
1722
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1723
+ :param int [params.until]: the latest time in ms to fetch orders for
1724
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1725
+ """
1726
+ req = {
1727
+ 'statuses': 'FILLED',
1728
+ }
1729
+ return await self.fetch_orders(symbol, since, limit, self.extend(req, params))
1730
+
1731
+ async def fetch_canceled_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1732
+ """
1733
+ fetches information on multiple canceled orders made by the user
1734
+
1735
+ https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1736
+
1737
+ :param str symbol: unified market symbol
1738
+ :param int [since]: the earliest time in ms to fetch open orders for
1739
+ :param int [limit]: the maximum number of open order structures to retrieve
1740
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1741
+ :param int [params.until]: the latest time in ms to fetch orders for
1742
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1743
+ """
1744
+ req = {
1745
+ 'statuses': 'CANCELED',
1746
+ }
1747
+ return await self.fetch_orders(symbol, since, limit, self.extend(req, params))
1748
+
1749
+ async def close_position(self, symbol: str, side: OrderSide = None, params={}) -> Order:
1750
+ """
1751
+ closes an open position for a market
1752
+
1753
+ https://api-docs.defx.com/#b2c08074-c4d9-4e50-b637-0d6c498fa29e
1754
+
1755
+ :param str symbol: unified CCXT market symbol
1756
+ :param str [side]: one-way mode: 'buy' or 'sell', hedge-mode: 'long' or 'short'
1757
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1758
+ :param str [params.positionId]: the position id you want to close
1759
+ :param str [params.type]: 'MARKET' or 'LIMIT'
1760
+ :param str [params.quantity]: how much of currency you want to trade in units of base currency
1761
+ :param str [params.price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1762
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1763
+ """
1764
+ await self.load_markets()
1765
+ positionId = self.safe_string(params, 'positionId')
1766
+ if positionId is None:
1767
+ raise ArgumentsRequired(self.id + ' closePosition() requires a positionId')
1768
+ type = self.safe_string_upper(params, 'type')
1769
+ if type is None:
1770
+ raise ArgumentsRequired(self.id + ' closePosition() requires a type')
1771
+ quantity = self.safe_string(params, 'quantity')
1772
+ if quantity is None:
1773
+ raise ArgumentsRequired(self.id + ' closePosition() requires a quantity')
1774
+ request: dict = {
1775
+ 'positionId': positionId,
1776
+ 'type': type,
1777
+ 'quantity': quantity,
1778
+ }
1779
+ if type != 'MARKET':
1780
+ price = self.safe_string(params, 'price')
1781
+ if price is None:
1782
+ raise ArgumentsRequired(self.id + ' closePosition() requires a price')
1783
+ request['price'] = price
1784
+ params = self.omit(params, ['positionId', 'type', 'quantity', 'price'])
1785
+ response = await self.v1PrivateDeleteApiPositionPositionId(self.extend(request, params))
1786
+ #
1787
+ # {}
1788
+ #
1789
+ return response
1790
+
1791
+ async def close_all_positions(self, params={}) -> List[Position]:
1792
+ """
1793
+ closes all open positions for a market type
1794
+
1795
+ https://api-docs.defx.com/#d6f63b43-100e-47a9-998c-8b6c0c72d204
1796
+
1797
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1798
+ :returns dict[]: A list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
1799
+ """
1800
+ await self.load_markets()
1801
+ response = await self.v1PrivateDeleteApiPositionAll(params)
1802
+ #
1803
+ # {
1804
+ # "data": [
1805
+ # {
1806
+ # "positionId": "d6ca1a27-28ad-47ae-b244-0bda5ac37b2b",
1807
+ # "success": True
1808
+ # }
1809
+ # ]
1810
+ # }
1811
+ #
1812
+ data = self.safe_list(response, 'data', [])
1813
+ return self.parse_positions(data, None, params)
1814
+
1815
+ async def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[LedgerEntry]:
1816
+ """
1817
+ fetch the history of changes, actions done by the user or operations that altered the balance of the user
1818
+
1819
+ https://api-docs.defx.com/#38cc8974-794f-48c0-b959-db045a0ee565
1820
+
1821
+ :param str [code]: unified currency code
1822
+ :param int [since]: timestamp in ms of the earliest ledger entry
1823
+ :param int [limit]: max number of ledger entries to return
1824
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1825
+ :param int [params.until]: timestamp in ms of the latest ledger entry
1826
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
1827
+ :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
1828
+ """
1829
+ await self.load_markets()
1830
+ paginate = False
1831
+ paginate, params = self.handle_option_and_params(params, 'fetchLedger', 'paginate')
1832
+ if paginate:
1833
+ return await self.fetch_paginated_call_dynamic('fetchLedger', code, since, limit, params)
1834
+ request: dict = {}
1835
+ if since is not None:
1836
+ request['start'] = since
1837
+ else:
1838
+ request['start'] = 0
1839
+ until = self.safe_integer(params, 'until')
1840
+ if until is not None:
1841
+ params = self.omit(params, 'until')
1842
+ request['end'] = until
1843
+ else:
1844
+ request['end'] = self.milliseconds()
1845
+ response = await self.v1PrivateGetApiWalletTransactions(self.extend(request, params))
1846
+ data = self.safe_list(response, 'transactions', [])
1847
+ return self.parse_ledger(data, None, since, limit)
1848
+
1849
+ def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
1850
+ #
1851
+ # {
1852
+ # "id": "01JCSZS6H5VQND3GF5P98SJ29C",
1853
+ # "timestamp": 1731744012054,
1854
+ # "type": "FundingFee",
1855
+ # "amount": "0.02189287",
1856
+ # "asset": "USDC",
1857
+ # "operation": "CREDIT"
1858
+ # }
1859
+ #
1860
+ amount = self.safe_string(item, 'amount')
1861
+ currencyId = self.safe_string(item, 'asset')
1862
+ code = self.safe_currency_code(currencyId, currency)
1863
+ currency = self.safe_currency(currencyId, currency)
1864
+ timestamp = self.safe_integer(item, 'timestamp')
1865
+ type = self.safe_string(item, 'type')
1866
+ return self.safe_ledger_entry({
1867
+ 'info': item,
1868
+ 'id': self.safe_string(item, 'id'),
1869
+ 'direction': None,
1870
+ 'account': None,
1871
+ 'referenceAccount': None,
1872
+ 'referenceId': None,
1873
+ 'type': self.parse_ledger_entry_type(type),
1874
+ 'currency': code,
1875
+ 'amount': self.parse_number(amount),
1876
+ 'timestamp': timestamp,
1877
+ 'datetime': self.iso8601(timestamp),
1878
+ 'before': None,
1879
+ 'after': None,
1880
+ 'status': None,
1881
+ 'fee': None,
1882
+ }, currency)
1883
+
1884
+ def parse_ledger_entry_type(self, type):
1885
+ ledgerType: dict = {
1886
+ 'FundingFee': 'fee',
1887
+ 'FeeRebate': 'fee',
1888
+ 'FeeKickback': 'fee',
1889
+ 'RealizedPnl': 'trade',
1890
+ 'LiquidationClearance': 'trade',
1891
+ 'Transfer': 'transfer',
1892
+ 'ReferralPayout': 'referral',
1893
+ 'Commission': 'commission',
1894
+ }
1895
+ return self.safe_string(ledgerType, type, type)
1896
+
1897
+ async def withdraw(self, code: str, amount: float, address: str, tag: Str = None, params={}) -> Transaction:
1898
+ """
1899
+ make a withdrawal
1900
+
1901
+ https://api-docs.defx.com/#2600f503-63ed-4672-b8f6-69ea5f03203b
1902
+
1903
+ :param str code: unified currency code
1904
+ :param float amount: the amount to withdraw
1905
+ :param str address: the address to withdraw to
1906
+ :param str tag:
1907
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1908
+ :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
1909
+ """
1910
+ await self.load_markets()
1911
+ currency = self.currency(code)
1912
+ request: dict = {
1913
+ 'amount': self.currency_to_precision(code, amount),
1914
+ 'asset': currency['id'],
1915
+ # 'network': 'ARB_SEPOLIA',
1916
+ # 'chainId': '421614',
1917
+ }
1918
+ response = await self.v1PrivatePostApiTransfersBridgeWithdrawal(self.extend(request, params))
1919
+ #
1920
+ # {
1921
+ # "transactionId": "0x301e5851e5aefa733abfbc8b30817ca3b61601e0ddf1df8c59656fb888b0bc9c"
1922
+ # }
1923
+ #
1924
+ return self.parse_transaction(response, currency)
1925
+
1926
+ def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
1927
+ #
1928
+ # withdraw
1929
+ #
1930
+ # {
1931
+ # "transactionId": "0x301e5851e5aefa733abfbc8b30817ca3b61601e0ddf1df8c59656fb888b0bc9c"
1932
+ # }
1933
+ #
1934
+ txid = self.safe_string(transaction, 'transactionId')
1935
+ return {
1936
+ 'info': transaction,
1937
+ 'id': None,
1938
+ 'txid': txid,
1939
+ 'timestamp': None,
1940
+ 'datetime': None,
1941
+ 'network': None,
1942
+ 'address': None,
1943
+ 'addressTo': None,
1944
+ 'addressFrom': None,
1945
+ 'tag': None,
1946
+ 'tagTo': None,
1947
+ 'tagFrom': None,
1948
+ 'type': None,
1949
+ 'amount': None,
1950
+ 'currency': self.safe_currency_code(None, currency),
1951
+ 'status': None,
1952
+ 'updated': None,
1953
+ 'internal': None,
1954
+ 'comment': None,
1955
+ 'fee': None,
1956
+ }
1957
+
1958
+ async def set_leverage(self, leverage: int, symbol: Str = None, params={}):
1959
+ """
1960
+ set the level of leverage for a market
1961
+
1962
+ https://api-docs.defx.com/#4cb4ecc4-6c61-4194-8353-be67faaf7ca7
1963
+
1964
+ :param float leverage: the rate of leverage
1965
+ :param str symbol: unified market symbol
1966
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1967
+ :returns dict: response from the exchange
1968
+ """
1969
+ if symbol is None:
1970
+ raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
1971
+ await self.load_markets()
1972
+ request: dict = {
1973
+ 'leverage': self.number_to_string(leverage),
1974
+ }
1975
+ market = self.market(symbol)
1976
+ request['symbol'] = market['id']
1977
+ response = await self.v1PrivatePostApiUsersMetadataLeverage(self.extend(request, params))
1978
+ #
1979
+ # {
1980
+ # "success": True,
1981
+ # "data": {
1982
+ # "leverage": "11",
1983
+ # "symbol": "BTC_USDC"
1984
+ # }
1985
+ # }
1986
+ #
1987
+ data = self.safe_dict(response, 'data', {})
1988
+ return self.parse_leverage(data, market)
1989
+
1990
+ def parse_leverage(self, leverage: dict, market: Market = None) -> Leverage:
1991
+ #
1992
+ # "data": {
1993
+ # "leverage": "11",
1994
+ # "symbol": "BTC_USDC"
1995
+ # }
1996
+ #
1997
+ marketId = self.safe_string(leverage, 'symbol')
1998
+ leverageValue = self.safe_integer(leverage, 'leverage')
1999
+ return {
2000
+ 'info': leverage,
2001
+ 'symbol': self.safe_symbol(marketId, market),
2002
+ 'marginMode': None,
2003
+ 'longLeverage': leverageValue,
2004
+ 'shortLeverage': leverageValue,
2005
+ }
2006
+
2007
+ def nonce(self):
2008
+ return self.milliseconds()
2009
+
2010
+ def sign(self, path, section='public', method='GET', params={}, headers=None, body=None):
2011
+ version = section[0]
2012
+ access = section[1]
2013
+ pathWithParams = self.implode_params(path, params)
2014
+ url = self.implode_hostname(self.urls['api'][access])
2015
+ url += '/' + version + '/'
2016
+ params = self.omit(params, self.extract_params(path))
2017
+ params = self.keysort(params)
2018
+ if access == 'public':
2019
+ url += 'open/' + pathWithParams
2020
+ if params:
2021
+ url += '?' + self.rawencode(params)
2022
+ else:
2023
+ self.check_required_credentials()
2024
+ headers = {'X-DEFX-SOURCE': 'ccxt'}
2025
+ url += 'auth/' + pathWithParams
2026
+ nonce = str(self.milliseconds())
2027
+ payload = nonce
2028
+ if method == 'GET' or path == 'api/order/{orderId}':
2029
+ payload += self.rawencode(params)
2030
+ if params:
2031
+ url += '?' + self.rawencode(params)
2032
+ else:
2033
+ if params is not None:
2034
+ body = self.json(params)
2035
+ payload += body
2036
+ headers['Content-Type'] = 'application/json'
2037
+ signature = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256)
2038
+ headers['X-DEFX-APIKEY'] = self.apiKey
2039
+ headers['X-DEFX-TIMESTAMP'] = nonce
2040
+ headers['X-DEFX-SIGNATURE'] = signature
2041
+ return {'url': url, 'method': method, 'body': body, 'headers': headers}
2042
+
2043
+ def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
2044
+ if not response:
2045
+ return None # fallback to default error handler
2046
+ # {"errorCode":404,"errorMessage":"Not Found"}
2047
+ # {"msg":"Missing auth signature","code":"missing_auth_signature"}
2048
+ # {"success":false,"err":{"msg":"Invalid order id","code":"invalid_order_id"}}
2049
+ success = self.safe_bool(response, 'success')
2050
+ err = self.safe_dict(response, 'err', response)
2051
+ errorCode = self.safe_string_2(err, 'errorCode', 'code')
2052
+ if not success:
2053
+ feedback = self.id + ' ' + self.json(response)
2054
+ self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback)
2055
+ self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
2056
+ return None
2057
+
2058
+ def default_network_code_for_currency(self, code):
2059
+ currencyItem = self.currency(code)
2060
+ networks = currencyItem['networks']
2061
+ networkKeys = list(networks.keys())
2062
+ for i in range(0, len(networkKeys)):
2063
+ network = networkKeys[i]
2064
+ if network == 'ETH':
2065
+ return network
2066
+ # if it was not returned according to above options, then return the first network of currency
2067
+ return self.safe_value(networkKeys, 0)
2068
+
2069
+ def set_sandbox_mode(self, enable: bool):
2070
+ super(defx, self).set_sandbox_mode(enable)
2071
+ self.options['sandboxMode'] = enable