ccxt-ir 4.3.46.0.1__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 (772) hide show
  1. ccxt/__init__.py +358 -0
  2. ccxt/abantether.py +316 -0
  3. ccxt/abstract/__init__.py +0 -0
  4. ccxt/abstract/abantether.py +5 -0
  5. ccxt/abstract/ace.py +15 -0
  6. ccxt/abstract/afratether.py +6 -0
  7. ccxt/abstract/alpaca.py +70 -0
  8. ccxt/abstract/arzinja.py +5 -0
  9. ccxt/abstract/arzplus.py +7 -0
  10. ccxt/abstract/ascendex.py +77 -0
  11. ccxt/abstract/bequant.py +115 -0
  12. ccxt/abstract/bigone.py +45 -0
  13. ccxt/abstract/binance.py +712 -0
  14. ccxt/abstract/binancecoinm.py +712 -0
  15. ccxt/abstract/binanceus.py +764 -0
  16. ccxt/abstract/binanceusdm.py +712 -0
  17. ccxt/abstract/bingx.py +113 -0
  18. ccxt/abstract/bit2c.py +27 -0
  19. ccxt/abstract/bitbank.py +27 -0
  20. ccxt/abstract/bitbay.py +53 -0
  21. ccxt/abstract/bitbns.py +40 -0
  22. ccxt/abstract/bitcoincom.py +115 -0
  23. ccxt/abstract/bitfinex.py +69 -0
  24. ccxt/abstract/bitfinex2.py +139 -0
  25. ccxt/abstract/bitflyer.py +38 -0
  26. ccxt/abstract/bitget.py +508 -0
  27. ccxt/abstract/bithumb.py +32 -0
  28. ccxt/abstract/bitimen.py +7 -0
  29. ccxt/abstract/bitir.py +7 -0
  30. ccxt/abstract/bitmart.py +99 -0
  31. ccxt/abstract/bitmex.py +97 -0
  32. ccxt/abstract/bitopro.py +29 -0
  33. ccxt/abstract/bitpanda.py +35 -0
  34. ccxt/abstract/bitpin.py +7 -0
  35. ccxt/abstract/bitrue.py +72 -0
  36. ccxt/abstract/bitso.py +43 -0
  37. ccxt/abstract/bitstamp.py +258 -0
  38. ccxt/abstract/bitteam.py +29 -0
  39. ccxt/abstract/bitvavo.py +27 -0
  40. ccxt/abstract/bl3p.py +19 -0
  41. ccxt/abstract/blockchaincom.py +28 -0
  42. ccxt/abstract/blofin.py +37 -0
  43. ccxt/abstract/btcalpha.py +18 -0
  44. ccxt/abstract/btcbox.py +13 -0
  45. ccxt/abstract/btcmarkets.py +39 -0
  46. ccxt/abstract/btcturk.py +20 -0
  47. ccxt/abstract/bybit.py +298 -0
  48. ccxt/abstract/cex.py +33 -0
  49. ccxt/abstract/coinbase.py +94 -0
  50. ccxt/abstract/coinbaseadvanced.py +94 -0
  51. ccxt/abstract/coinbaseexchange.py +67 -0
  52. ccxt/abstract/coinbaseinternational.py +39 -0
  53. ccxt/abstract/coincatch.py +94 -0
  54. ccxt/abstract/coincheck.py +33 -0
  55. ccxt/abstract/coinex.py +237 -0
  56. ccxt/abstract/coinlist.py +54 -0
  57. ccxt/abstract/coinmate.py +62 -0
  58. ccxt/abstract/coinmetro.py +34 -0
  59. ccxt/abstract/coinone.py +67 -0
  60. ccxt/abstract/coinsph.py +54 -0
  61. ccxt/abstract/coinspot.py +28 -0
  62. ccxt/abstract/cryptocom.py +107 -0
  63. ccxt/abstract/currencycom.py +68 -0
  64. ccxt/abstract/delta.py +50 -0
  65. ccxt/abstract/deribit.py +125 -0
  66. ccxt/abstract/digifinex.py +91 -0
  67. ccxt/abstract/eterex.py +5 -0
  68. ccxt/abstract/excoino.py +7 -0
  69. ccxt/abstract/exir.py +8 -0
  70. ccxt/abstract/exmo.py +55 -0
  71. ccxt/abstract/exnovin.py +6 -0
  72. ccxt/abstract/farhadexchange.py +5 -0
  73. ccxt/abstract/fmfwio.py +115 -0
  74. ccxt/abstract/gate.py +265 -0
  75. ccxt/abstract/gateio.py +265 -0
  76. ccxt/abstract/gemini.py +58 -0
  77. ccxt/abstract/hashkey.py +67 -0
  78. ccxt/abstract/hitbtc.py +115 -0
  79. ccxt/abstract/hitbtc3.py +115 -0
  80. ccxt/abstract/hitobit.py +8 -0
  81. ccxt/abstract/hollaex.py +33 -0
  82. ccxt/abstract/htx.py +548 -0
  83. ccxt/abstract/huobi.py +548 -0
  84. ccxt/abstract/huobijp.py +114 -0
  85. ccxt/abstract/hyperliquid.py +6 -0
  86. ccxt/abstract/idex.py +26 -0
  87. ccxt/abstract/independentreserve.py +37 -0
  88. ccxt/abstract/indodax.py +26 -0
  89. ccxt/abstract/jibitex.py +7 -0
  90. ccxt/abstract/kraken.py +57 -0
  91. ccxt/abstract/krakenfutures.py +38 -0
  92. ccxt/abstract/kucoin.py +214 -0
  93. ccxt/abstract/kucoinfutures.py +233 -0
  94. ccxt/abstract/kuna.py +182 -0
  95. ccxt/abstract/latoken.py +56 -0
  96. ccxt/abstract/lbank.py +61 -0
  97. ccxt/abstract/luno.py +37 -0
  98. ccxt/abstract/lykke.py +29 -0
  99. ccxt/abstract/mercado.py +25 -0
  100. ccxt/abstract/mexc.py +178 -0
  101. ccxt/abstract/ndax.py +97 -0
  102. ccxt/abstract/nobitex.py +7 -0
  103. ccxt/abstract/novadax.py +29 -0
  104. ccxt/abstract/oceanex.py +22 -0
  105. ccxt/abstract/okcoin.py +74 -0
  106. ccxt/abstract/okexchange.py +8 -0
  107. ccxt/abstract/okx.py +324 -0
  108. ccxt/abstract/ompfinex.py +7 -0
  109. ccxt/abstract/onetrading.py +35 -0
  110. ccxt/abstract/oxfun.py +34 -0
  111. ccxt/abstract/p2b.py +22 -0
  112. ccxt/abstract/paradex.py +40 -0
  113. ccxt/abstract/paymium.py +28 -0
  114. ccxt/abstract/phemex.py +115 -0
  115. ccxt/abstract/poloniex.py +69 -0
  116. ccxt/abstract/poloniexfutures.py +48 -0
  117. ccxt/abstract/probit.py +23 -0
  118. ccxt/abstract/ramzinex.py +7 -0
  119. ccxt/abstract/sarmayex.py +5 -0
  120. ccxt/abstract/sarrafex.py +7 -0
  121. ccxt/abstract/tabdeal.py +7 -0
  122. ccxt/abstract/tetherland.py +5 -0
  123. ccxt/abstract/timex.py +62 -0
  124. ccxt/abstract/tokocrypto.py +37 -0
  125. ccxt/abstract/tradeogre.py +16 -0
  126. ccxt/abstract/twox.py +5 -0
  127. ccxt/abstract/ubitex.py +7 -0
  128. ccxt/abstract/upbit.py +38 -0
  129. ccxt/abstract/vertex.py +19 -0
  130. ccxt/abstract/wallex.py +8 -0
  131. ccxt/abstract/wavesexchange.py +154 -0
  132. ccxt/abstract/wazirx.py +30 -0
  133. ccxt/abstract/whitebit.py +98 -0
  134. ccxt/abstract/woo.py +83 -0
  135. ccxt/abstract/woofipro.py +119 -0
  136. ccxt/abstract/xt.py +152 -0
  137. ccxt/abstract/yobit.py +16 -0
  138. ccxt/abstract/zaif.py +38 -0
  139. ccxt/abstract/zonda.py +53 -0
  140. ccxt/ace.py +1012 -0
  141. ccxt/afratether.py +293 -0
  142. ccxt/alpaca.py +1083 -0
  143. ccxt/arzinja.py +285 -0
  144. ccxt/arzplus.py +412 -0
  145. ccxt/ascendex.py +3330 -0
  146. ccxt/async_support/__init__.py +337 -0
  147. ccxt/async_support/abantether.py +316 -0
  148. ccxt/async_support/ace.py +1012 -0
  149. ccxt/async_support/afratether.py +293 -0
  150. ccxt/async_support/alpaca.py +1083 -0
  151. ccxt/async_support/arzinja.py +285 -0
  152. ccxt/async_support/arzplus.py +412 -0
  153. ccxt/async_support/ascendex.py +3330 -0
  154. ccxt/async_support/base/__init__.py +1 -0
  155. ccxt/async_support/base/exchange.py +1966 -0
  156. ccxt/async_support/base/throttler.py +50 -0
  157. ccxt/async_support/base/ws/__init__.py +38 -0
  158. ccxt/async_support/base/ws/aiohttp_client.py +125 -0
  159. ccxt/async_support/base/ws/cache.py +212 -0
  160. ccxt/async_support/base/ws/client.py +193 -0
  161. ccxt/async_support/base/ws/fast_client.py +96 -0
  162. ccxt/async_support/base/ws/functions.py +59 -0
  163. ccxt/async_support/base/ws/future.py +58 -0
  164. ccxt/async_support/base/ws/order_book.py +78 -0
  165. ccxt/async_support/base/ws/order_book_side.py +174 -0
  166. ccxt/async_support/bequant.py +33 -0
  167. ccxt/async_support/bigone.py +2113 -0
  168. ccxt/async_support/binance.py +12234 -0
  169. ccxt/async_support/binancecoinm.py +45 -0
  170. ccxt/async_support/binanceus.py +211 -0
  171. ccxt/async_support/binanceusdm.py +58 -0
  172. ccxt/async_support/bingx.py +4325 -0
  173. ccxt/async_support/bit2c.py +866 -0
  174. ccxt/async_support/bitbank.py +1001 -0
  175. ccxt/async_support/bitbay.py +17 -0
  176. ccxt/async_support/bitbns.py +1154 -0
  177. ccxt/async_support/bitcoincom.py +17 -0
  178. ccxt/async_support/bitfinex.py +1617 -0
  179. ccxt/async_support/bitfinex2.py +3552 -0
  180. ccxt/async_support/bitflyer.py +995 -0
  181. ccxt/async_support/bitget.py +8273 -0
  182. ccxt/async_support/bithumb.py +1061 -0
  183. ccxt/async_support/bitimen.py +401 -0
  184. ccxt/async_support/bitir.py +490 -0
  185. ccxt/async_support/bitmart.py +4415 -0
  186. ccxt/async_support/bitmex.py +2756 -0
  187. ccxt/async_support/bitopro.py +1630 -0
  188. ccxt/async_support/bitpanda.py +16 -0
  189. ccxt/async_support/bitpin.py +454 -0
  190. ccxt/async_support/bitrue.py +3027 -0
  191. ccxt/async_support/bitso.py +1670 -0
  192. ccxt/async_support/bitstamp.py +2203 -0
  193. ccxt/async_support/bitteam.py +2239 -0
  194. ccxt/async_support/bitvavo.py +1968 -0
  195. ccxt/async_support/bl3p.py +485 -0
  196. ccxt/async_support/blockchaincom.py +1104 -0
  197. ccxt/async_support/blofin.py +2066 -0
  198. ccxt/async_support/btcalpha.py +891 -0
  199. ccxt/async_support/btcbox.py +544 -0
  200. ccxt/async_support/btcmarkets.py +1221 -0
  201. ccxt/async_support/btcturk.py +911 -0
  202. ccxt/async_support/bybit.py +8159 -0
  203. ccxt/async_support/cex.py +1605 -0
  204. ccxt/async_support/coinbase.py +4475 -0
  205. ccxt/async_support/coinbaseadvanced.py +17 -0
  206. ccxt/async_support/coinbaseexchange.py +1734 -0
  207. ccxt/async_support/coinbaseinternational.py +1899 -0
  208. ccxt/async_support/coincatch.py +5069 -0
  209. ccxt/async_support/coincheck.py +815 -0
  210. ccxt/async_support/coinex.py +5526 -0
  211. ccxt/async_support/coinlist.py +2243 -0
  212. ccxt/async_support/coinmate.py +1067 -0
  213. ccxt/async_support/coinmetro.py +1797 -0
  214. ccxt/async_support/coinone.py +1127 -0
  215. ccxt/async_support/coinsph.py +1850 -0
  216. ccxt/async_support/coinspot.py +534 -0
  217. ccxt/async_support/cryptocom.py +2822 -0
  218. ccxt/async_support/currencycom.py +1950 -0
  219. ccxt/async_support/delta.py +3376 -0
  220. ccxt/async_support/deribit.py +3437 -0
  221. ccxt/async_support/digifinex.py +3960 -0
  222. ccxt/async_support/eterex.py +286 -0
  223. ccxt/async_support/excoino.py +399 -0
  224. ccxt/async_support/exir.py +375 -0
  225. ccxt/async_support/exmo.py +2462 -0
  226. ccxt/async_support/exnovin.py +360 -0
  227. ccxt/async_support/farhadexchange.py +266 -0
  228. ccxt/async_support/fmfwio.py +34 -0
  229. ccxt/async_support/gate.py +6976 -0
  230. ccxt/async_support/gateio.py +16 -0
  231. ccxt/async_support/gemini.py +1825 -0
  232. ccxt/async_support/hashkey.py +4150 -0
  233. ccxt/async_support/hitbtc.py +3423 -0
  234. ccxt/async_support/hitbtc3.py +16 -0
  235. ccxt/async_support/hitobit.py +391 -0
  236. ccxt/async_support/hollaex.py +1813 -0
  237. ccxt/async_support/htx.py +8506 -0
  238. ccxt/async_support/huobi.py +16 -0
  239. ccxt/async_support/huobijp.py +1801 -0
  240. ccxt/async_support/hyperliquid.py +2431 -0
  241. ccxt/async_support/idex.py +1766 -0
  242. ccxt/async_support/independentreserve.py +784 -0
  243. ccxt/async_support/indodax.py +1247 -0
  244. ccxt/async_support/jibitex.py +395 -0
  245. ccxt/async_support/kraken.py +2894 -0
  246. ccxt/async_support/krakenfutures.py +2601 -0
  247. ccxt/async_support/kucoin.py +4602 -0
  248. ccxt/async_support/kucoinfutures.py +2698 -0
  249. ccxt/async_support/kuna.py +1841 -0
  250. ccxt/async_support/latoken.py +1664 -0
  251. ccxt/async_support/lbank.py +2683 -0
  252. ccxt/async_support/luno.py +1067 -0
  253. ccxt/async_support/lykke.py +1270 -0
  254. ccxt/async_support/mercado.py +842 -0
  255. ccxt/async_support/mexc.py +5369 -0
  256. ccxt/async_support/ndax.py +2354 -0
  257. ccxt/async_support/nobitex.py +419 -0
  258. ccxt/async_support/novadax.py +1484 -0
  259. ccxt/async_support/oceanex.py +903 -0
  260. ccxt/async_support/okcoin.py +2936 -0
  261. ccxt/async_support/okexchange.py +349 -0
  262. ccxt/async_support/okx.py +7827 -0
  263. ccxt/async_support/ompfinex.py +472 -0
  264. ccxt/async_support/onetrading.py +1911 -0
  265. ccxt/async_support/oxfun.py +2773 -0
  266. ccxt/async_support/p2b.py +1194 -0
  267. ccxt/async_support/paradex.py +2015 -0
  268. ccxt/async_support/paymium.py +564 -0
  269. ccxt/async_support/phemex.py +4473 -0
  270. ccxt/async_support/poloniex.py +2232 -0
  271. ccxt/async_support/poloniexfutures.py +1717 -0
  272. ccxt/async_support/probit.py +1734 -0
  273. ccxt/async_support/ramzinex.py +476 -0
  274. ccxt/async_support/sarmayex.py +357 -0
  275. ccxt/async_support/sarrafex.py +478 -0
  276. ccxt/async_support/tabdeal.py +364 -0
  277. ccxt/async_support/tetherland.py +349 -0
  278. ccxt/async_support/timex.py +1593 -0
  279. ccxt/async_support/tokocrypto.py +2405 -0
  280. ccxt/async_support/tradeogre.py +608 -0
  281. ccxt/async_support/twox.py +326 -0
  282. ccxt/async_support/ubitex.py +409 -0
  283. ccxt/async_support/upbit.py +1833 -0
  284. ccxt/async_support/vertex.py +2922 -0
  285. ccxt/async_support/wallex.py +445 -0
  286. ccxt/async_support/wavesexchange.py +2473 -0
  287. ccxt/async_support/wazirx.py +1224 -0
  288. ccxt/async_support/whitebit.py +2469 -0
  289. ccxt/async_support/woo.py +3114 -0
  290. ccxt/async_support/woofipro.py +2533 -0
  291. ccxt/async_support/xt.py +4454 -0
  292. ccxt/async_support/yobit.py +1283 -0
  293. ccxt/async_support/zaif.py +725 -0
  294. ccxt/async_support/zonda.py +1828 -0
  295. ccxt/base/__init__.py +27 -0
  296. ccxt/base/decimal_to_precision.py +174 -0
  297. ccxt/base/errors.py +242 -0
  298. ccxt/base/exchange.py +5941 -0
  299. ccxt/base/precise.py +287 -0
  300. ccxt/base/types.py +502 -0
  301. ccxt/bequant.py +33 -0
  302. ccxt/bigone.py +2112 -0
  303. ccxt/binance.py +12233 -0
  304. ccxt/binancecoinm.py +45 -0
  305. ccxt/binanceus.py +211 -0
  306. ccxt/binanceusdm.py +58 -0
  307. ccxt/bingx.py +4324 -0
  308. ccxt/bit2c.py +866 -0
  309. ccxt/bitbank.py +1001 -0
  310. ccxt/bitbay.py +17 -0
  311. ccxt/bitbns.py +1154 -0
  312. ccxt/bitcoincom.py +17 -0
  313. ccxt/bitfinex.py +1617 -0
  314. ccxt/bitfinex2.py +3552 -0
  315. ccxt/bitflyer.py +995 -0
  316. ccxt/bitget.py +8272 -0
  317. ccxt/bithumb.py +1061 -0
  318. ccxt/bitimen.py +401 -0
  319. ccxt/bitir.py +490 -0
  320. ccxt/bitmart.py +4415 -0
  321. ccxt/bitmex.py +2756 -0
  322. ccxt/bitopro.py +1630 -0
  323. ccxt/bitpanda.py +16 -0
  324. ccxt/bitpin.py +454 -0
  325. ccxt/bitrue.py +3026 -0
  326. ccxt/bitso.py +1670 -0
  327. ccxt/bitstamp.py +2203 -0
  328. ccxt/bitteam.py +2239 -0
  329. ccxt/bitvavo.py +1968 -0
  330. ccxt/bl3p.py +485 -0
  331. ccxt/blockchaincom.py +1104 -0
  332. ccxt/blofin.py +2066 -0
  333. ccxt/btcalpha.py +891 -0
  334. ccxt/btcbox.py +544 -0
  335. ccxt/btcmarkets.py +1221 -0
  336. ccxt/btcturk.py +911 -0
  337. ccxt/bybit.py +8158 -0
  338. ccxt/cex.py +1605 -0
  339. ccxt/coinbase.py +4474 -0
  340. ccxt/coinbaseadvanced.py +17 -0
  341. ccxt/coinbaseexchange.py +1734 -0
  342. ccxt/coinbaseinternational.py +1899 -0
  343. ccxt/coincatch.py +5069 -0
  344. ccxt/coincheck.py +815 -0
  345. ccxt/coinex.py +5525 -0
  346. ccxt/coinlist.py +2243 -0
  347. ccxt/coinmate.py +1067 -0
  348. ccxt/coinmetro.py +1797 -0
  349. ccxt/coinone.py +1127 -0
  350. ccxt/coinsph.py +1850 -0
  351. ccxt/coinspot.py +534 -0
  352. ccxt/cryptocom.py +2822 -0
  353. ccxt/currencycom.py +1950 -0
  354. ccxt/delta.py +3376 -0
  355. ccxt/deribit.py +3437 -0
  356. ccxt/digifinex.py +3959 -0
  357. ccxt/eterex.py +286 -0
  358. ccxt/excoino.py +399 -0
  359. ccxt/exir.py +375 -0
  360. ccxt/exmo.py +2462 -0
  361. ccxt/exnovin.py +360 -0
  362. ccxt/farhadexchange.py +266 -0
  363. ccxt/fmfwio.py +34 -0
  364. ccxt/gate.py +6975 -0
  365. ccxt/gateio.py +16 -0
  366. ccxt/gemini.py +1824 -0
  367. ccxt/hashkey.py +4150 -0
  368. ccxt/hitbtc.py +3423 -0
  369. ccxt/hitbtc3.py +16 -0
  370. ccxt/hitobit.py +391 -0
  371. ccxt/hollaex.py +1813 -0
  372. ccxt/htx.py +8505 -0
  373. ccxt/huobi.py +16 -0
  374. ccxt/huobijp.py +1801 -0
  375. ccxt/hyperliquid.py +2430 -0
  376. ccxt/idex.py +1766 -0
  377. ccxt/independentreserve.py +784 -0
  378. ccxt/indodax.py +1247 -0
  379. ccxt/jibitex.py +395 -0
  380. ccxt/kraken.py +2894 -0
  381. ccxt/krakenfutures.py +2601 -0
  382. ccxt/kucoin.py +4601 -0
  383. ccxt/kucoinfutures.py +2698 -0
  384. ccxt/kuna.py +1841 -0
  385. ccxt/latoken.py +1664 -0
  386. ccxt/lbank.py +2682 -0
  387. ccxt/luno.py +1067 -0
  388. ccxt/lykke.py +1270 -0
  389. ccxt/mercado.py +842 -0
  390. ccxt/mexc.py +5369 -0
  391. ccxt/ndax.py +2354 -0
  392. ccxt/nobitex.py +419 -0
  393. ccxt/novadax.py +1484 -0
  394. ccxt/oceanex.py +903 -0
  395. ccxt/okcoin.py +2936 -0
  396. ccxt/okexchange.py +349 -0
  397. ccxt/okx.py +7826 -0
  398. ccxt/ompfinex.py +472 -0
  399. ccxt/onetrading.py +1911 -0
  400. ccxt/oxfun.py +2772 -0
  401. ccxt/p2b.py +1194 -0
  402. ccxt/paradex.py +2015 -0
  403. ccxt/paymium.py +564 -0
  404. ccxt/phemex.py +4473 -0
  405. ccxt/poloniex.py +2232 -0
  406. ccxt/poloniexfutures.py +1717 -0
  407. ccxt/pro/__init__.py +149 -0
  408. ccxt/pro/alpaca.py +685 -0
  409. ccxt/pro/ascendex.py +916 -0
  410. ccxt/pro/bequant.py +38 -0
  411. ccxt/pro/binance.py +3488 -0
  412. ccxt/pro/binancecoinm.py +28 -0
  413. ccxt/pro/binanceus.py +48 -0
  414. ccxt/pro/binanceusdm.py +31 -0
  415. ccxt/pro/bingx.py +1264 -0
  416. ccxt/pro/bitcoincom.py +34 -0
  417. ccxt/pro/bitfinex.py +621 -0
  418. ccxt/pro/bitfinex2.py +1083 -0
  419. ccxt/pro/bitget.py +1692 -0
  420. ccxt/pro/bithumb.py +368 -0
  421. ccxt/pro/bitmart.py +1449 -0
  422. ccxt/pro/bitmex.py +1656 -0
  423. ccxt/pro/bitopro.py +445 -0
  424. ccxt/pro/bitpanda.py +15 -0
  425. ccxt/pro/bitrue.py +447 -0
  426. ccxt/pro/bitstamp.py +522 -0
  427. ccxt/pro/bitvavo.py +1270 -0
  428. ccxt/pro/blockchaincom.py +738 -0
  429. ccxt/pro/blofin.py +692 -0
  430. ccxt/pro/bybit.py +2000 -0
  431. ccxt/pro/cex.py +1440 -0
  432. ccxt/pro/coinbase.py +678 -0
  433. ccxt/pro/coinbaseadvanced.py +16 -0
  434. ccxt/pro/coinbaseexchange.py +895 -0
  435. ccxt/pro/coinbaseinternational.py +620 -0
  436. ccxt/pro/coincatch.py +1464 -0
  437. ccxt/pro/coincheck.py +199 -0
  438. ccxt/pro/coinex.py +1061 -0
  439. ccxt/pro/coinone.py +395 -0
  440. ccxt/pro/cryptocom.py +947 -0
  441. ccxt/pro/currencycom.py +536 -0
  442. ccxt/pro/deribit.py +892 -0
  443. ccxt/pro/exmo.py +629 -0
  444. ccxt/pro/gate.py +1416 -0
  445. ccxt/pro/gateio.py +15 -0
  446. ccxt/pro/gemini.py +865 -0
  447. ccxt/pro/hashkey.py +802 -0
  448. ccxt/pro/hitbtc.py +1216 -0
  449. ccxt/pro/hollaex.py +563 -0
  450. ccxt/pro/htx.py +2215 -0
  451. ccxt/pro/huobi.py +15 -0
  452. ccxt/pro/huobijp.py +570 -0
  453. ccxt/pro/hyperliquid.py +525 -0
  454. ccxt/pro/idex.py +672 -0
  455. ccxt/pro/independentreserve.py +270 -0
  456. ccxt/pro/kraken.py +1356 -0
  457. ccxt/pro/krakenfutures.py +1492 -0
  458. ccxt/pro/kucoin.py +1133 -0
  459. ccxt/pro/kucoinfutures.py +1081 -0
  460. ccxt/pro/lbank.py +843 -0
  461. ccxt/pro/luno.py +303 -0
  462. ccxt/pro/mexc.py +1122 -0
  463. ccxt/pro/ndax.py +506 -0
  464. ccxt/pro/okcoin.py +698 -0
  465. ccxt/pro/okx.py +1851 -0
  466. ccxt/pro/onetrading.py +1275 -0
  467. ccxt/pro/oxfun.py +950 -0
  468. ccxt/pro/p2b.py +419 -0
  469. ccxt/pro/paradex.py +352 -0
  470. ccxt/pro/phemex.py +1441 -0
  471. ccxt/pro/poloniex.py +1166 -0
  472. ccxt/pro/poloniexfutures.py +990 -0
  473. ccxt/pro/probit.py +551 -0
  474. ccxt/pro/upbit.py +520 -0
  475. ccxt/pro/vertex.py +943 -0
  476. ccxt/pro/wazirx.py +749 -0
  477. ccxt/pro/whitebit.py +864 -0
  478. ccxt/pro/woo.py +1078 -0
  479. ccxt/pro/woofipro.py +1183 -0
  480. ccxt/pro/xt.py +1067 -0
  481. ccxt/probit.py +1734 -0
  482. ccxt/ramzinex.py +476 -0
  483. ccxt/sarmayex.py +357 -0
  484. ccxt/sarrafex.py +478 -0
  485. ccxt/static_dependencies/__init__.py +1 -0
  486. ccxt/static_dependencies/ecdsa/__init__.py +14 -0
  487. ccxt/static_dependencies/ecdsa/_version.py +520 -0
  488. ccxt/static_dependencies/ecdsa/curves.py +56 -0
  489. ccxt/static_dependencies/ecdsa/der.py +221 -0
  490. ccxt/static_dependencies/ecdsa/ecdsa.py +310 -0
  491. ccxt/static_dependencies/ecdsa/ellipticcurve.py +197 -0
  492. ccxt/static_dependencies/ecdsa/keys.py +332 -0
  493. ccxt/static_dependencies/ecdsa/numbertheory.py +531 -0
  494. ccxt/static_dependencies/ecdsa/rfc6979.py +100 -0
  495. ccxt/static_dependencies/ecdsa/util.py +266 -0
  496. ccxt/static_dependencies/ethereum/__init__.py +7 -0
  497. ccxt/static_dependencies/ethereum/abi/__init__.py +16 -0
  498. ccxt/static_dependencies/ethereum/abi/abi.py +19 -0
  499. ccxt/static_dependencies/ethereum/abi/base.py +152 -0
  500. ccxt/static_dependencies/ethereum/abi/codec.py +217 -0
  501. ccxt/static_dependencies/ethereum/abi/constants.py +3 -0
  502. ccxt/static_dependencies/ethereum/abi/decoding.py +565 -0
  503. ccxt/static_dependencies/ethereum/abi/encoding.py +720 -0
  504. ccxt/static_dependencies/ethereum/abi/exceptions.py +139 -0
  505. ccxt/static_dependencies/ethereum/abi/grammar.py +443 -0
  506. ccxt/static_dependencies/ethereum/abi/packed.py +13 -0
  507. ccxt/static_dependencies/ethereum/abi/py.typed +0 -0
  508. ccxt/static_dependencies/ethereum/abi/registry.py +643 -0
  509. ccxt/static_dependencies/ethereum/abi/tools/__init__.py +3 -0
  510. ccxt/static_dependencies/ethereum/abi/tools/_strategies.py +230 -0
  511. ccxt/static_dependencies/ethereum/abi/utils/__init__.py +0 -0
  512. ccxt/static_dependencies/ethereum/abi/utils/numeric.py +83 -0
  513. ccxt/static_dependencies/ethereum/abi/utils/padding.py +27 -0
  514. ccxt/static_dependencies/ethereum/abi/utils/string.py +19 -0
  515. ccxt/static_dependencies/ethereum/account/__init__.py +3 -0
  516. ccxt/static_dependencies/ethereum/account/encode_typed_data/__init__.py +4 -0
  517. ccxt/static_dependencies/ethereum/account/encode_typed_data/encoding_and_hashing.py +239 -0
  518. ccxt/static_dependencies/ethereum/account/encode_typed_data/helpers.py +40 -0
  519. ccxt/static_dependencies/ethereum/account/messages.py +263 -0
  520. ccxt/static_dependencies/ethereum/account/py.typed +0 -0
  521. ccxt/static_dependencies/ethereum/hexbytes/__init__.py +5 -0
  522. ccxt/static_dependencies/ethereum/hexbytes/_utils.py +54 -0
  523. ccxt/static_dependencies/ethereum/hexbytes/main.py +65 -0
  524. ccxt/static_dependencies/ethereum/hexbytes/py.typed +0 -0
  525. ccxt/static_dependencies/ethereum/typing/__init__.py +63 -0
  526. ccxt/static_dependencies/ethereum/typing/abi.py +6 -0
  527. ccxt/static_dependencies/ethereum/typing/bls.py +7 -0
  528. ccxt/static_dependencies/ethereum/typing/discovery.py +5 -0
  529. ccxt/static_dependencies/ethereum/typing/encoding.py +7 -0
  530. ccxt/static_dependencies/ethereum/typing/enums.py +17 -0
  531. ccxt/static_dependencies/ethereum/typing/ethpm.py +9 -0
  532. ccxt/static_dependencies/ethereum/typing/evm.py +20 -0
  533. ccxt/static_dependencies/ethereum/typing/networks.py +1122 -0
  534. ccxt/static_dependencies/ethereum/typing/py.typed +0 -0
  535. ccxt/static_dependencies/ethereum/utils/__init__.py +115 -0
  536. ccxt/static_dependencies/ethereum/utils/abi.py +72 -0
  537. ccxt/static_dependencies/ethereum/utils/address.py +171 -0
  538. ccxt/static_dependencies/ethereum/utils/applicators.py +151 -0
  539. ccxt/static_dependencies/ethereum/utils/conversions.py +190 -0
  540. ccxt/static_dependencies/ethereum/utils/currency.py +107 -0
  541. ccxt/static_dependencies/ethereum/utils/curried/__init__.py +269 -0
  542. ccxt/static_dependencies/ethereum/utils/debug.py +20 -0
  543. ccxt/static_dependencies/ethereum/utils/decorators.py +132 -0
  544. ccxt/static_dependencies/ethereum/utils/encoding.py +6 -0
  545. ccxt/static_dependencies/ethereum/utils/exceptions.py +4 -0
  546. ccxt/static_dependencies/ethereum/utils/functional.py +75 -0
  547. ccxt/static_dependencies/ethereum/utils/hexadecimal.py +74 -0
  548. ccxt/static_dependencies/ethereum/utils/humanize.py +188 -0
  549. ccxt/static_dependencies/ethereum/utils/logging.py +159 -0
  550. ccxt/static_dependencies/ethereum/utils/module_loading.py +31 -0
  551. ccxt/static_dependencies/ethereum/utils/numeric.py +43 -0
  552. ccxt/static_dependencies/ethereum/utils/py.typed +0 -0
  553. ccxt/static_dependencies/ethereum/utils/toolz.py +76 -0
  554. ccxt/static_dependencies/ethereum/utils/types.py +54 -0
  555. ccxt/static_dependencies/ethereum/utils/typing/__init__.py +18 -0
  556. ccxt/static_dependencies/ethereum/utils/typing/misc.py +14 -0
  557. ccxt/static_dependencies/ethereum/utils/units.py +31 -0
  558. ccxt/static_dependencies/keccak/__init__.py +3 -0
  559. ccxt/static_dependencies/keccak/keccak.py +197 -0
  560. ccxt/static_dependencies/lark/__init__.py +38 -0
  561. ccxt/static_dependencies/lark/__pyinstaller/__init__.py +6 -0
  562. ccxt/static_dependencies/lark/__pyinstaller/hook-lark.py +14 -0
  563. ccxt/static_dependencies/lark/ast_utils.py +59 -0
  564. ccxt/static_dependencies/lark/common.py +86 -0
  565. ccxt/static_dependencies/lark/exceptions.py +292 -0
  566. ccxt/static_dependencies/lark/grammar.py +130 -0
  567. ccxt/static_dependencies/lark/grammars/__init__.py +0 -0
  568. ccxt/static_dependencies/lark/indenter.py +143 -0
  569. ccxt/static_dependencies/lark/lark.py +658 -0
  570. ccxt/static_dependencies/lark/lexer.py +678 -0
  571. ccxt/static_dependencies/lark/load_grammar.py +1428 -0
  572. ccxt/static_dependencies/lark/parse_tree_builder.py +391 -0
  573. ccxt/static_dependencies/lark/parser_frontends.py +257 -0
  574. ccxt/static_dependencies/lark/parsers/__init__.py +0 -0
  575. ccxt/static_dependencies/lark/parsers/cyk.py +340 -0
  576. ccxt/static_dependencies/lark/parsers/earley.py +314 -0
  577. ccxt/static_dependencies/lark/parsers/earley_common.py +42 -0
  578. ccxt/static_dependencies/lark/parsers/earley_forest.py +801 -0
  579. ccxt/static_dependencies/lark/parsers/grammar_analysis.py +203 -0
  580. ccxt/static_dependencies/lark/parsers/lalr_analysis.py +332 -0
  581. ccxt/static_dependencies/lark/parsers/lalr_interactive_parser.py +158 -0
  582. ccxt/static_dependencies/lark/parsers/lalr_parser.py +122 -0
  583. ccxt/static_dependencies/lark/parsers/lalr_parser_state.py +110 -0
  584. ccxt/static_dependencies/lark/parsers/xearley.py +165 -0
  585. ccxt/static_dependencies/lark/reconstruct.py +107 -0
  586. ccxt/static_dependencies/lark/tools/__init__.py +70 -0
  587. ccxt/static_dependencies/lark/tools/nearley.py +202 -0
  588. ccxt/static_dependencies/lark/tools/serialize.py +32 -0
  589. ccxt/static_dependencies/lark/tools/standalone.py +196 -0
  590. ccxt/static_dependencies/lark/tree.py +267 -0
  591. ccxt/static_dependencies/lark/tree_matcher.py +186 -0
  592. ccxt/static_dependencies/lark/tree_templates.py +180 -0
  593. ccxt/static_dependencies/lark/utils.py +343 -0
  594. ccxt/static_dependencies/lark/visitors.py +596 -0
  595. ccxt/static_dependencies/marshmallow/__init__.py +81 -0
  596. ccxt/static_dependencies/marshmallow/base.py +65 -0
  597. ccxt/static_dependencies/marshmallow/class_registry.py +94 -0
  598. ccxt/static_dependencies/marshmallow/decorators.py +231 -0
  599. ccxt/static_dependencies/marshmallow/error_store.py +60 -0
  600. ccxt/static_dependencies/marshmallow/exceptions.py +71 -0
  601. ccxt/static_dependencies/marshmallow/fields.py +2114 -0
  602. ccxt/static_dependencies/marshmallow/orderedset.py +89 -0
  603. ccxt/static_dependencies/marshmallow/schema.py +1228 -0
  604. ccxt/static_dependencies/marshmallow/types.py +12 -0
  605. ccxt/static_dependencies/marshmallow/utils.py +378 -0
  606. ccxt/static_dependencies/marshmallow/validate.py +678 -0
  607. ccxt/static_dependencies/marshmallow/warnings.py +2 -0
  608. ccxt/static_dependencies/marshmallow_dataclass/__init__.py +1047 -0
  609. ccxt/static_dependencies/marshmallow_dataclass/collection_field.py +51 -0
  610. ccxt/static_dependencies/marshmallow_dataclass/lazy_class_attribute.py +45 -0
  611. ccxt/static_dependencies/marshmallow_dataclass/mypy.py +71 -0
  612. ccxt/static_dependencies/marshmallow_dataclass/typing.py +14 -0
  613. ccxt/static_dependencies/marshmallow_dataclass/union_field.py +82 -0
  614. ccxt/static_dependencies/marshmallow_oneofschema/__init__.py +1 -0
  615. ccxt/static_dependencies/marshmallow_oneofschema/one_of_schema.py +193 -0
  616. ccxt/static_dependencies/msgpack/__init__.py +55 -0
  617. ccxt/static_dependencies/msgpack/exceptions.py +48 -0
  618. ccxt/static_dependencies/msgpack/ext.py +168 -0
  619. ccxt/static_dependencies/msgpack/fallback.py +951 -0
  620. ccxt/static_dependencies/parsimonious/__init__.py +10 -0
  621. ccxt/static_dependencies/parsimonious/exceptions.py +105 -0
  622. ccxt/static_dependencies/parsimonious/expressions.py +479 -0
  623. ccxt/static_dependencies/parsimonious/grammar.py +487 -0
  624. ccxt/static_dependencies/parsimonious/nodes.py +325 -0
  625. ccxt/static_dependencies/parsimonious/utils.py +40 -0
  626. ccxt/static_dependencies/starknet/__init__.py +0 -0
  627. ccxt/static_dependencies/starknet/cairo/__init__.py +0 -0
  628. ccxt/static_dependencies/starknet/cairo/data_types.py +123 -0
  629. ccxt/static_dependencies/starknet/cairo/deprecated_parse/__init__.py +0 -0
  630. ccxt/static_dependencies/starknet/cairo/deprecated_parse/cairo_types.py +77 -0
  631. ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser.py +46 -0
  632. ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser_transformer.py +138 -0
  633. ccxt/static_dependencies/starknet/cairo/felt.py +64 -0
  634. ccxt/static_dependencies/starknet/cairo/type_parser.py +121 -0
  635. ccxt/static_dependencies/starknet/cairo/v1/__init__.py +0 -0
  636. ccxt/static_dependencies/starknet/cairo/v1/type_parser.py +59 -0
  637. ccxt/static_dependencies/starknet/cairo/v2/__init__.py +0 -0
  638. ccxt/static_dependencies/starknet/cairo/v2/type_parser.py +77 -0
  639. ccxt/static_dependencies/starknet/ccxt_utils.py +7 -0
  640. ccxt/static_dependencies/starknet/common.py +15 -0
  641. ccxt/static_dependencies/starknet/constants.py +39 -0
  642. ccxt/static_dependencies/starknet/hash/__init__.py +0 -0
  643. ccxt/static_dependencies/starknet/hash/address.py +79 -0
  644. ccxt/static_dependencies/starknet/hash/compiled_class_hash_objects.py +111 -0
  645. ccxt/static_dependencies/starknet/hash/selector.py +16 -0
  646. ccxt/static_dependencies/starknet/hash/storage.py +12 -0
  647. ccxt/static_dependencies/starknet/hash/utils.py +78 -0
  648. ccxt/static_dependencies/starknet/models/__init__.py +0 -0
  649. ccxt/static_dependencies/starknet/models/typed_data.py +45 -0
  650. ccxt/static_dependencies/starknet/serialization/__init__.py +24 -0
  651. ccxt/static_dependencies/starknet/serialization/_calldata_reader.py +40 -0
  652. ccxt/static_dependencies/starknet/serialization/_context.py +142 -0
  653. ccxt/static_dependencies/starknet/serialization/data_serializers/__init__.py +10 -0
  654. ccxt/static_dependencies/starknet/serialization/data_serializers/_common.py +82 -0
  655. ccxt/static_dependencies/starknet/serialization/data_serializers/array_serializer.py +43 -0
  656. ccxt/static_dependencies/starknet/serialization/data_serializers/bool_serializer.py +37 -0
  657. ccxt/static_dependencies/starknet/serialization/data_serializers/byte_array_serializer.py +66 -0
  658. ccxt/static_dependencies/starknet/serialization/data_serializers/cairo_data_serializer.py +71 -0
  659. ccxt/static_dependencies/starknet/serialization/data_serializers/enum_serializer.py +71 -0
  660. ccxt/static_dependencies/starknet/serialization/data_serializers/felt_serializer.py +50 -0
  661. ccxt/static_dependencies/starknet/serialization/data_serializers/named_tuple_serializer.py +58 -0
  662. ccxt/static_dependencies/starknet/serialization/data_serializers/option_serializer.py +43 -0
  663. ccxt/static_dependencies/starknet/serialization/data_serializers/output_serializer.py +40 -0
  664. ccxt/static_dependencies/starknet/serialization/data_serializers/payload_serializer.py +72 -0
  665. ccxt/static_dependencies/starknet/serialization/data_serializers/struct_serializer.py +36 -0
  666. ccxt/static_dependencies/starknet/serialization/data_serializers/tuple_serializer.py +36 -0
  667. ccxt/static_dependencies/starknet/serialization/data_serializers/uint256_serializer.py +76 -0
  668. ccxt/static_dependencies/starknet/serialization/data_serializers/uint_serializer.py +100 -0
  669. ccxt/static_dependencies/starknet/serialization/data_serializers/unit_serializer.py +32 -0
  670. ccxt/static_dependencies/starknet/serialization/errors.py +10 -0
  671. ccxt/static_dependencies/starknet/serialization/factory.py +229 -0
  672. ccxt/static_dependencies/starknet/serialization/function_serialization_adapter.py +110 -0
  673. ccxt/static_dependencies/starknet/serialization/tuple_dataclass.py +59 -0
  674. ccxt/static_dependencies/starknet/utils/__init__.py +0 -0
  675. ccxt/static_dependencies/starknet/utils/constructor_args_translator.py +86 -0
  676. ccxt/static_dependencies/starknet/utils/iterable.py +13 -0
  677. ccxt/static_dependencies/starknet/utils/schema.py +13 -0
  678. ccxt/static_dependencies/starknet/utils/typed_data.py +182 -0
  679. ccxt/static_dependencies/starkware/__init__.py +0 -0
  680. ccxt/static_dependencies/starkware/crypto/__init__.py +0 -0
  681. ccxt/static_dependencies/starkware/crypto/fast_pedersen_hash.py +50 -0
  682. ccxt/static_dependencies/starkware/crypto/math_utils.py +78 -0
  683. ccxt/static_dependencies/starkware/crypto/signature.py +2344 -0
  684. ccxt/static_dependencies/starkware/crypto/utils.py +63 -0
  685. ccxt/static_dependencies/sympy/__init__.py +0 -0
  686. ccxt/static_dependencies/sympy/core/__init__.py +0 -0
  687. ccxt/static_dependencies/sympy/core/intfunc.py +35 -0
  688. ccxt/static_dependencies/sympy/external/__init__.py +0 -0
  689. ccxt/static_dependencies/sympy/external/gmpy.py +345 -0
  690. ccxt/static_dependencies/sympy/external/importtools.py +187 -0
  691. ccxt/static_dependencies/sympy/external/ntheory.py +637 -0
  692. ccxt/static_dependencies/sympy/external/pythonmpq.py +341 -0
  693. ccxt/static_dependencies/toolz/__init__.py +26 -0
  694. ccxt/static_dependencies/toolz/_signatures.py +784 -0
  695. ccxt/static_dependencies/toolz/_version.py +520 -0
  696. ccxt/static_dependencies/toolz/compatibility.py +30 -0
  697. ccxt/static_dependencies/toolz/curried/__init__.py +101 -0
  698. ccxt/static_dependencies/toolz/curried/exceptions.py +22 -0
  699. ccxt/static_dependencies/toolz/curried/operator.py +22 -0
  700. ccxt/static_dependencies/toolz/dicttoolz.py +339 -0
  701. ccxt/static_dependencies/toolz/functoolz.py +1049 -0
  702. ccxt/static_dependencies/toolz/itertoolz.py +1057 -0
  703. ccxt/static_dependencies/toolz/recipes.py +46 -0
  704. ccxt/static_dependencies/toolz/utils.py +9 -0
  705. ccxt/static_dependencies/typing_inspect/__init__.py +0 -0
  706. ccxt/static_dependencies/typing_inspect/typing_inspect.py +851 -0
  707. ccxt/tabdeal.py +364 -0
  708. ccxt/test/__init__.py +3 -0
  709. ccxt/test/base/__init__.py +29 -0
  710. ccxt/test/base/test_account.py +26 -0
  711. ccxt/test/base/test_balance.py +56 -0
  712. ccxt/test/base/test_borrow_interest.py +35 -0
  713. ccxt/test/base/test_borrow_rate.py +32 -0
  714. ccxt/test/base/test_calculate_fee.py +51 -0
  715. ccxt/test/base/test_crypto.py +127 -0
  716. ccxt/test/base/test_currency.py +76 -0
  717. ccxt/test/base/test_datetime.py +109 -0
  718. ccxt/test/base/test_decimal_to_precision.py +392 -0
  719. ccxt/test/base/test_deep_extend.py +68 -0
  720. ccxt/test/base/test_deposit_withdrawal.py +50 -0
  721. ccxt/test/base/test_exchange_datetime_functions.py +76 -0
  722. ccxt/test/base/test_funding_rate_history.py +29 -0
  723. ccxt/test/base/test_last_price.py +31 -0
  724. ccxt/test/base/test_ledger_entry.py +45 -0
  725. ccxt/test/base/test_ledger_item.py +48 -0
  726. ccxt/test/base/test_leverage_tier.py +33 -0
  727. ccxt/test/base/test_liquidation.py +50 -0
  728. ccxt/test/base/test_margin_mode.py +24 -0
  729. ccxt/test/base/test_margin_modification.py +35 -0
  730. ccxt/test/base/test_market.py +193 -0
  731. ccxt/test/base/test_number.py +411 -0
  732. ccxt/test/base/test_ohlcv.py +33 -0
  733. ccxt/test/base/test_open_interest.py +32 -0
  734. ccxt/test/base/test_order.py +64 -0
  735. ccxt/test/base/test_order_book.py +69 -0
  736. ccxt/test/base/test_position.py +60 -0
  737. ccxt/test/base/test_shared_methods.py +353 -0
  738. ccxt/test/base/test_status.py +24 -0
  739. ccxt/test/base/test_throttle.py +126 -0
  740. ccxt/test/base/test_ticker.py +92 -0
  741. ccxt/test/base/test_trade.py +47 -0
  742. ccxt/test/base/test_trading_fee.py +26 -0
  743. ccxt/test/base/test_transaction.py +39 -0
  744. ccxt/test/test_async.py +1649 -0
  745. ccxt/test/test_sync.py +1648 -0
  746. ccxt/test/tests_async.py +1558 -0
  747. ccxt/test/tests_helpers.py +287 -0
  748. ccxt/test/tests_init.py +39 -0
  749. ccxt/test/tests_sync.py +1555 -0
  750. ccxt/tetherland.py +349 -0
  751. ccxt/timex.py +1593 -0
  752. ccxt/tokocrypto.py +2405 -0
  753. ccxt/tradeogre.py +608 -0
  754. ccxt/twox.py +326 -0
  755. ccxt/ubitex.py +409 -0
  756. ccxt/upbit.py +1833 -0
  757. ccxt/vertex.py +2922 -0
  758. ccxt/wallex.py +445 -0
  759. ccxt/wavesexchange.py +2472 -0
  760. ccxt/wazirx.py +1224 -0
  761. ccxt/whitebit.py +2469 -0
  762. ccxt/woo.py +3114 -0
  763. ccxt/woofipro.py +2533 -0
  764. ccxt/xt.py +4453 -0
  765. ccxt/yobit.py +1283 -0
  766. ccxt/zaif.py +725 -0
  767. ccxt/zonda.py +1828 -0
  768. ccxt_ir-4.3.46.0.1.dist-info/LICENSE.txt +21 -0
  769. ccxt_ir-4.3.46.0.1.dist-info/METADATA +655 -0
  770. ccxt_ir-4.3.46.0.1.dist-info/RECORD +772 -0
  771. ccxt_ir-4.3.46.0.1.dist-info/WHEEL +6 -0
  772. ccxt_ir-4.3.46.0.1.dist-info/top_level.txt +1 -0
ccxt/bitmex.py ADDED
@@ -0,0 +1,2756 @@
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.base.exchange import Exchange
7
+ from ccxt.abstract.bitmex import ImplicitAPI
8
+ import hashlib
9
+ from ccxt.base.types import Balances, Currencies, Currency, Int, Leverage, Leverages, Market, MarketType, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, Transaction
10
+ from typing import List
11
+ from ccxt.base.errors import ExchangeError
12
+ from ccxt.base.errors import AuthenticationError
13
+ from ccxt.base.errors import PermissionDenied
14
+ from ccxt.base.errors import ArgumentsRequired
15
+ from ccxt.base.errors import BadRequest
16
+ from ccxt.base.errors import BadSymbol
17
+ from ccxt.base.errors import InsufficientFunds
18
+ from ccxt.base.errors import InvalidOrder
19
+ from ccxt.base.errors import OrderNotFound
20
+ from ccxt.base.errors import DDoSProtection
21
+ from ccxt.base.errors import ExchangeNotAvailable
22
+ from ccxt.base.decimal_to_precision import TICK_SIZE
23
+ from ccxt.base.precise import Precise
24
+
25
+
26
+ class bitmex(Exchange, ImplicitAPI):
27
+
28
+ def describe(self):
29
+ return self.deep_extend(super(bitmex, self).describe(), {
30
+ 'id': 'bitmex',
31
+ 'name': 'BitMEX',
32
+ 'countries': ['SC'], # Seychelles
33
+ 'version': 'v1',
34
+ 'userAgent': None,
35
+ # cheapest endpoints are 10 requests per second(trading)
36
+ # 10 per second => rateLimit = 1000ms / 10 = 100ms
37
+ # 120 per minute => 2 per second => weight = 5(authenticated)
38
+ # 30 per minute => 0.5 per second => weight = 20(unauthenticated)
39
+ 'rateLimit': 100,
40
+ 'certified': True,
41
+ 'pro': True,
42
+ 'has': {
43
+ 'CORS': None,
44
+ 'spot': True,
45
+ 'margin': False,
46
+ 'swap': True,
47
+ 'future': True,
48
+ 'option': False,
49
+ 'addMargin': None,
50
+ 'cancelAllOrders': True,
51
+ 'cancelAllOrdersAfter': True,
52
+ 'cancelOrder': True,
53
+ 'cancelOrders': True,
54
+ 'closeAllPositions': False,
55
+ 'closePosition': True,
56
+ 'createOrder': True,
57
+ 'createReduceOnlyOrder': True,
58
+ 'createTrailingAmountOrder': True,
59
+ 'editOrder': True,
60
+ 'fetchBalance': True,
61
+ 'fetchClosedOrders': True,
62
+ 'fetchCurrencies': True,
63
+ 'fetchDepositAddress': True,
64
+ 'fetchDepositAddresses': False,
65
+ 'fetchDepositAddressesByNetwork': False,
66
+ 'fetchDepositsWithdrawals': 'emulated',
67
+ 'fetchDepositWithdrawFee': 'emulated',
68
+ 'fetchDepositWithdrawFees': True,
69
+ 'fetchFundingHistory': False,
70
+ 'fetchFundingRate': False,
71
+ 'fetchFundingRateHistory': True,
72
+ 'fetchFundingRates': True,
73
+ 'fetchIndexOHLCV': False,
74
+ 'fetchLedger': True,
75
+ 'fetchLeverage': 'emulated',
76
+ 'fetchLeverages': True,
77
+ 'fetchLeverageTiers': False,
78
+ 'fetchLiquidations': True,
79
+ 'fetchMarginAdjustmentHistory': False,
80
+ 'fetchMarketLeverageTiers': False,
81
+ 'fetchMarkets': True,
82
+ 'fetchMarkOHLCV': False,
83
+ 'fetchMyLiquidations': False,
84
+ 'fetchMyTrades': True,
85
+ 'fetchOHLCV': True,
86
+ 'fetchOpenOrders': True,
87
+ 'fetchOrder': True,
88
+ 'fetchOrderBook': True,
89
+ 'fetchOrders': True,
90
+ 'fetchPosition': False,
91
+ 'fetchPositionHistory': False,
92
+ 'fetchPositions': True,
93
+ 'fetchPositionsHistory': False,
94
+ 'fetchPositionsRisk': False,
95
+ 'fetchPremiumIndexOHLCV': False,
96
+ 'fetchTicker': True,
97
+ 'fetchTickers': True,
98
+ 'fetchTrades': True,
99
+ 'fetchTransactions': 'emulated',
100
+ 'fetchTransfer': False,
101
+ 'fetchTransfers': False,
102
+ 'reduceMargin': None,
103
+ 'sandbox': True,
104
+ 'setLeverage': True,
105
+ 'setMargin': None,
106
+ 'setMarginMode': True,
107
+ 'setPositionMode': False,
108
+ 'transfer': False,
109
+ 'withdraw': True,
110
+ },
111
+ 'timeframes': {
112
+ '1m': '1m',
113
+ '5m': '5m',
114
+ '1h': '1h',
115
+ '1d': '1d',
116
+ },
117
+ 'urls': {
118
+ 'test': {
119
+ 'public': 'https://testnet.bitmex.com',
120
+ 'private': 'https://testnet.bitmex.com',
121
+ },
122
+ 'logo': 'https://github.com/ccxt/ccxt/assets/43336371/cea9cfe5-c57e-4b84-b2ac-77b960b04445',
123
+ 'api': {
124
+ 'public': 'https://www.bitmex.com',
125
+ 'private': 'https://www.bitmex.com',
126
+ },
127
+ 'www': 'https://www.bitmex.com',
128
+ 'doc': [
129
+ 'https://www.bitmex.com/app/apiOverview',
130
+ 'https://github.com/BitMEX/api-connectors/tree/master/official-http',
131
+ ],
132
+ 'fees': 'https://www.bitmex.com/app/fees',
133
+ 'referral': {
134
+ 'url': 'https://www.bitmex.com/app/register/NZTR1q',
135
+ 'discount': 0.1,
136
+ },
137
+ },
138
+ 'api': {
139
+ 'public': {
140
+ 'get': {
141
+ 'announcement': 5,
142
+ 'announcement/urgent': 5,
143
+ 'chat': 5,
144
+ 'chat/channels': 5,
145
+ 'chat/connected': 5,
146
+ 'chat/pinned': 5,
147
+ 'funding': 5,
148
+ 'guild': 5,
149
+ 'instrument': 5,
150
+ 'instrument/active': 5,
151
+ 'instrument/activeAndIndices': 5,
152
+ 'instrument/activeIntervals': 5,
153
+ 'instrument/compositeIndex': 5,
154
+ 'instrument/indices': 5,
155
+ 'instrument/usdVolume': 5,
156
+ 'insurance': 5,
157
+ 'leaderboard': 5,
158
+ 'liquidation': 5,
159
+ 'orderBook/L2': 5,
160
+ 'porl/nonce': 5,
161
+ 'quote': 5,
162
+ 'quote/bucketed': 5,
163
+ 'schema': 5,
164
+ 'schema/websocketHelp': 5,
165
+ 'settlement': 5,
166
+ 'stats': 5,
167
+ 'stats/history': 5,
168
+ 'stats/historyUSD': 5,
169
+ 'trade': 5,
170
+ 'trade/bucketed': 5,
171
+ 'wallet/assets': 5,
172
+ 'wallet/networks': 5,
173
+ },
174
+ },
175
+ 'private': {
176
+ 'get': {
177
+ 'address': 5,
178
+ 'apiKey': 5,
179
+ 'execution': 5,
180
+ 'execution/tradeHistory': 5,
181
+ 'globalNotification': 5,
182
+ 'leaderboard/name': 5,
183
+ 'order': 5,
184
+ 'porl/snapshots': 5,
185
+ 'position': 5,
186
+ 'user': 5,
187
+ 'user/affiliateStatus': 5,
188
+ 'user/checkReferralCode': 5,
189
+ 'user/commission': 5,
190
+ 'user/csa': 5,
191
+ 'user/depositAddress': 5,
192
+ 'user/executionHistory': 5,
193
+ 'user/getWalletTransferAccounts': 5,
194
+ 'user/margin': 5,
195
+ 'user/quoteFillRatio': 5,
196
+ 'user/quoteValueRatio': 5,
197
+ 'user/staking': 5,
198
+ 'user/staking/instruments': 5,
199
+ 'user/staking/tiers': 5,
200
+ 'user/tradingVolume': 5,
201
+ 'user/unstakingRequests': 5,
202
+ 'user/wallet': 5,
203
+ 'user/walletHistory': 5,
204
+ 'user/walletSummary': 5,
205
+ 'userAffiliates': 5,
206
+ 'userEvent': 5,
207
+ },
208
+ 'post': {
209
+ 'address': 5,
210
+ 'chat': 5,
211
+ 'guild': 5,
212
+ 'guild/archive': 5,
213
+ 'guild/join': 5,
214
+ 'guild/kick': 5,
215
+ 'guild/leave': 5,
216
+ 'guild/sharesTrades': 5,
217
+ 'order': 1,
218
+ 'order/cancelAllAfter': 5,
219
+ 'order/closePosition': 5,
220
+ 'position/isolate': 1,
221
+ 'position/leverage': 1,
222
+ 'position/riskLimit': 5,
223
+ 'position/transferMargin': 1,
224
+ 'user/addSubaccount': 5,
225
+ 'user/cancelWithdrawal': 5,
226
+ 'user/communicationToken': 5,
227
+ 'user/confirmEmail': 5,
228
+ 'user/confirmWithdrawal': 5,
229
+ 'user/logout': 5,
230
+ 'user/preferences': 5,
231
+ 'user/requestWithdrawal': 5,
232
+ 'user/unstakingRequests': 5,
233
+ 'user/updateSubaccount': 5,
234
+ 'user/walletTransfer': 5,
235
+ },
236
+ 'put': {
237
+ 'guild': 5,
238
+ 'order': 1,
239
+ },
240
+ 'delete': {
241
+ 'order': 1,
242
+ 'order/all': 1,
243
+ 'user/unstakingRequests': 5,
244
+ },
245
+ },
246
+ },
247
+ 'exceptions': {
248
+ 'exact': {
249
+ 'Invalid API Key.': AuthenticationError,
250
+ 'This key is disabled.': PermissionDenied,
251
+ 'Access Denied': PermissionDenied,
252
+ 'Duplicate clOrdID': InvalidOrder,
253
+ 'orderQty is invalid': InvalidOrder,
254
+ 'Invalid price': InvalidOrder,
255
+ 'Invalid stopPx for ordType': InvalidOrder,
256
+ 'Account is restricted': PermissionDenied, # {"error":{"message":"Account is restricted","name":"HTTPError"}}
257
+ },
258
+ 'broad': {
259
+ 'Signature not valid': AuthenticationError,
260
+ 'overloaded': ExchangeNotAvailable,
261
+ 'Account has insufficient Available Balance': InsufficientFunds,
262
+ 'Service unavailable': ExchangeNotAvailable, # {"error":{"message":"Service unavailable","name":"HTTPError"}}
263
+ 'Server Error': ExchangeError, # {"error":{"message":"Server Error","name":"HTTPError"}}
264
+ 'Unable to cancel order due to existing state': InvalidOrder,
265
+ 'We require all new traders to verify': PermissionDenied, # {"message":"We require all new traders to verify their identity before their first deposit. Please visit bitmex.com/verify to complete the process.","name":"HTTPError"}
266
+ },
267
+ },
268
+ 'precisionMode': TICK_SIZE,
269
+ 'options': {
270
+ # https://blog.bitmex.com/api_announcement/deprecation-of-api-nonce-header/
271
+ # https://github.com/ccxt/ccxt/issues/4789
272
+ 'api-expires': 5, # in seconds
273
+ 'fetchOHLCVOpenTimestamp': True,
274
+ 'oldPrecision': False,
275
+ 'networks': {
276
+ 'BTC': 'btc',
277
+ 'ERC20': 'eth',
278
+ 'BEP20': 'bsc',
279
+ 'TRC20': 'tron',
280
+ 'AVAXC': 'avax',
281
+ 'NEAR': 'near',
282
+ 'XTZ': 'xtz',
283
+ 'DOT': 'dot',
284
+ 'SOL': 'sol',
285
+ 'ADA': 'ada',
286
+ },
287
+ },
288
+ 'commonCurrencies': {
289
+ 'USDt': 'USDT',
290
+ 'XBt': 'BTC',
291
+ 'XBT': 'BTC',
292
+ 'Gwei': 'ETH',
293
+ 'GWEI': 'ETH',
294
+ 'LAMP': 'SOL',
295
+ 'LAMp': 'SOL',
296
+ },
297
+ })
298
+
299
+ def fetch_currencies(self, params={}) -> Currencies:
300
+ """
301
+ fetches all available currencies on an exchange
302
+ :see: https://www.bitmex.com/api/explorer/#not /Wallet/Wallet_getAssetsConfig
303
+ :param dict [params]: extra parameters specific to the exchange API endpoint
304
+ :returns dict: an associative dictionary of currencies
305
+ """
306
+ response = self.publicGetWalletAssets(params)
307
+ #
308
+ # {
309
+ # "XBt": {
310
+ # "asset": "XBT",
311
+ # "currency": "XBt",
312
+ # "majorCurrency": "XBT",
313
+ # "name": "Bitcoin",
314
+ # "currencyType": "Crypto",
315
+ # "scale": "8",
316
+ # # "mediumPrecision": "8",
317
+ # # "shorterPrecision": "4",
318
+ # # "symbol": "₿",
319
+ # # "weight": "1",
320
+ # # "tickLog": "0",
321
+ # "enabled": True,
322
+ # "isMarginCurrency": True,
323
+ # "minDepositAmount": "10000",
324
+ # "minWithdrawalAmount": "1000",
325
+ # "maxWithdrawalAmount": "100000000000000",
326
+ # "networks": [
327
+ # {
328
+ # "asset": "btc",
329
+ # "tokenAddress": "",
330
+ # "depositEnabled": True,
331
+ # "withdrawalEnabled": True,
332
+ # "withdrawalFee": "20000",
333
+ # "minFee": "20000",
334
+ # "maxFee": "10000000"
335
+ # }
336
+ # ]
337
+ # },
338
+ # }
339
+ #
340
+ result: dict = {}
341
+ for i in range(0, len(response)):
342
+ currency = response[i]
343
+ asset = self.safe_string(currency, 'asset')
344
+ code = self.safe_currency_code(asset)
345
+ id = self.safe_string(currency, 'currency')
346
+ name = self.safe_string(currency, 'name')
347
+ chains = self.safe_value(currency, 'networks', [])
348
+ depositEnabled = False
349
+ withdrawEnabled = False
350
+ networks: dict = {}
351
+ scale = self.safe_string(currency, 'scale')
352
+ precisionString = self.parse_precision(scale)
353
+ precision = self.parse_number(precisionString)
354
+ for j in range(0, len(chains)):
355
+ chain = chains[j]
356
+ networkId = self.safe_string(chain, 'asset')
357
+ network = self.network_id_to_code(networkId)
358
+ withdrawalFeeRaw = self.safe_string(chain, 'withdrawalFee')
359
+ withdrawalFee = self.parse_number(Precise.string_mul(withdrawalFeeRaw, precisionString))
360
+ isDepositEnabled = self.safe_bool(chain, 'depositEnabled', False)
361
+ isWithdrawEnabled = self.safe_bool(chain, 'withdrawalEnabled', False)
362
+ active = (isDepositEnabled and isWithdrawEnabled)
363
+ if isDepositEnabled:
364
+ depositEnabled = True
365
+ if isWithdrawEnabled:
366
+ withdrawEnabled = True
367
+ networks[network] = {
368
+ 'info': chain,
369
+ 'id': networkId,
370
+ 'network': network,
371
+ 'active': active,
372
+ 'deposit': isDepositEnabled,
373
+ 'withdraw': isWithdrawEnabled,
374
+ 'fee': withdrawalFee,
375
+ 'precision': None,
376
+ 'limits': {
377
+ 'withdraw': {
378
+ 'min': None,
379
+ 'max': None,
380
+ },
381
+ 'deposit': {
382
+ 'min': None,
383
+ 'max': None,
384
+ },
385
+ },
386
+ }
387
+ currencyEnabled = self.safe_value(currency, 'enabled')
388
+ currencyActive = currencyEnabled or (depositEnabled or withdrawEnabled)
389
+ minWithdrawalString = self.safe_string(currency, 'minWithdrawalAmount')
390
+ minWithdrawal = self.parse_number(Precise.string_mul(minWithdrawalString, precisionString))
391
+ maxWithdrawalString = self.safe_string(currency, 'maxWithdrawalAmount')
392
+ maxWithdrawal = self.parse_number(Precise.string_mul(maxWithdrawalString, precisionString))
393
+ minDepositString = self.safe_string(currency, 'minDepositAmount')
394
+ minDeposit = self.parse_number(Precise.string_mul(minDepositString, precisionString))
395
+ result[code] = {
396
+ 'id': id,
397
+ 'code': code,
398
+ 'info': currency,
399
+ 'name': name,
400
+ 'active': currencyActive,
401
+ 'deposit': depositEnabled,
402
+ 'withdraw': withdrawEnabled,
403
+ 'fee': None,
404
+ 'precision': precision,
405
+ 'limits': {
406
+ 'amount': {
407
+ 'min': None,
408
+ 'max': None,
409
+ },
410
+ 'withdraw': {
411
+ 'min': minWithdrawal,
412
+ 'max': maxWithdrawal,
413
+ },
414
+ 'deposit': {
415
+ 'min': minDeposit,
416
+ 'max': None,
417
+ },
418
+ },
419
+ 'networks': networks,
420
+ }
421
+ return result
422
+
423
+ def convert_from_real_amount(self, code, amount):
424
+ currency = self.currency(code)
425
+ precision = self.safe_string(currency, 'precision')
426
+ amountString = self.number_to_string(amount)
427
+ finalAmount = Precise.string_div(amountString, precision)
428
+ return self.parse_number(finalAmount)
429
+
430
+ def convert_to_real_amount(self, code: Str, amount: Str):
431
+ if code is None:
432
+ return amount
433
+ elif amount is None:
434
+ return None
435
+ currency = self.currency(code)
436
+ precision = self.safe_string(currency, 'precision')
437
+ return Precise.string_mul(amount, precision)
438
+
439
+ def amount_to_precision(self, symbol, amount):
440
+ symbol = self.safe_symbol(symbol)
441
+ market = self.market(symbol)
442
+ oldPrecision = self.safe_value(self.options, 'oldPrecision')
443
+ if market['spot'] and not oldPrecision:
444
+ amount = self.convert_from_real_amount(market['base'], amount)
445
+ return super(bitmex, self).amount_to_precision(symbol, amount)
446
+
447
+ def convert_from_raw_quantity(self, symbol, rawQuantity, currencySide='base'):
448
+ if self.safe_value(self.options, 'oldPrecision'):
449
+ return self.parse_number(rawQuantity)
450
+ symbol = self.safe_symbol(symbol)
451
+ marketExists = self.in_array(symbol, self.symbols)
452
+ if not marketExists:
453
+ return self.parse_number(rawQuantity)
454
+ market = self.market(symbol)
455
+ if market['spot']:
456
+ return self.parse_number(self.convert_to_real_amount(market[currencySide], rawQuantity))
457
+ return self.parse_number(rawQuantity)
458
+
459
+ def convert_from_raw_cost(self, symbol, rawQuantity):
460
+ return self.convert_from_raw_quantity(symbol, rawQuantity, 'quote')
461
+
462
+ def fetch_markets(self, params={}) -> List[Market]:
463
+ """
464
+ retrieves data on all markets for bitmex
465
+ :see: https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_getActive
466
+ :param dict [params]: extra parameters specific to the exchange API endpoint
467
+ :returns dict[]: an array of objects representing market data
468
+ """
469
+ response = self.publicGetInstrumentActive(params)
470
+ #
471
+ # [
472
+ # {
473
+ # "symbol": "LTCUSDT",
474
+ # "rootSymbol": "LTC",
475
+ # "state": "Open",
476
+ # "typ": "FFWCSX",
477
+ # "listing": "2021-11-10T04:00:00.000Z",
478
+ # "front": "2021-11-10T04:00:00.000Z",
479
+ # "expiry": null,
480
+ # "settle": null,
481
+ # "listedSettle": null,
482
+ # "relistInterval": null,
483
+ # "inverseLeg": "",
484
+ # "sellLeg": "",
485
+ # "buyLeg": "",
486
+ # "optionStrikePcnt": null,
487
+ # "optionStrikeRound": null,
488
+ # "optionStrikePrice": null,
489
+ # "optionMultiplier": null,
490
+ # "positionCurrency": "LTC", # can be empty for spot markets
491
+ # "underlying": "LTC",
492
+ # "quoteCurrency": "USDT",
493
+ # "underlyingSymbol": "LTCT=", # can be empty for spot markets
494
+ # "reference": "BMEX",
495
+ # "referenceSymbol": ".BLTCT", # can be empty for spot markets
496
+ # "calcInterval": null,
497
+ # "publishInterval": null,
498
+ # "publishTime": null,
499
+ # "maxOrderQty": 1000000000,
500
+ # "maxPrice": 1000000,
501
+ # "lotSize": 1000,
502
+ # "tickSize": 0.01,
503
+ # "multiplier": 100,
504
+ # "settlCurrency": "USDt", # can be empty for spot markets
505
+ # "underlyingToPositionMultiplier": 10000,
506
+ # "underlyingToSettleMultiplier": null,
507
+ # "quoteToSettleMultiplier": 1000000,
508
+ # "isQuanto": False,
509
+ # "isInverse": False,
510
+ # "initMargin": 0.03,
511
+ # "maintMargin": 0.015,
512
+ # "riskLimit": 1000000000000, # can be null for spot markets
513
+ # "riskStep": 1000000000000, # can be null for spot markets
514
+ # "limit": null,
515
+ # "capped": False,
516
+ # "taxed": True,
517
+ # "deleverage": True,
518
+ # "makerFee": -0.0001,
519
+ # "takerFee": 0.0005,
520
+ # "settlementFee": 0,
521
+ # "insuranceFee": 0,
522
+ # "fundingBaseSymbol": ".LTCBON8H", # can be empty for spot markets
523
+ # "fundingQuoteSymbol": ".USDTBON8H", # can be empty for spot markets
524
+ # "fundingPremiumSymbol": ".LTCUSDTPI8H", # can be empty for spot markets
525
+ # "fundingTimestamp": "2022-01-14T20:00:00.000Z",
526
+ # "fundingInterval": "2000-01-01T08:00:00.000Z",
527
+ # "fundingRate": 0.0001,
528
+ # "indicativeFundingRate": 0.0001,
529
+ # "rebalanceTimestamp": null,
530
+ # "rebalanceInterval": null,
531
+ # "openingTimestamp": "2022-01-14T17:00:00.000Z",
532
+ # "closingTimestamp": "2022-01-14T18:00:00.000Z",
533
+ # "sessionInterval": "2000-01-01T01:00:00.000Z",
534
+ # "prevClosePrice": 138.511,
535
+ # "limitDownPrice": null,
536
+ # "limitUpPrice": null,
537
+ # "bankruptLimitDownPrice": null,
538
+ # "bankruptLimitUpPrice": null,
539
+ # "prevTotalVolume": 12699024000,
540
+ # "totalVolume": 12702160000,
541
+ # "volume": 3136000,
542
+ # "volume24h": 114251000,
543
+ # "prevTotalTurnover": 232418052349000,
544
+ # "totalTurnover": 232463353260000,
545
+ # "turnover": 45300911000,
546
+ # "turnover24h": 1604331340000,
547
+ # "homeNotional24h": 11425.1,
548
+ # "foreignNotional24h": 1604331.3400000003,
549
+ # "prevPrice24h": 135.48,
550
+ # "vwap": 140.42165,
551
+ # "highPrice": 146.42,
552
+ # "lowPrice": 135.08,
553
+ # "lastPrice": 144.36,
554
+ # "lastPriceProtected": 144.36,
555
+ # "lastTickDirection": "MinusTick",
556
+ # "lastChangePcnt": 0.0655,
557
+ # "bidPrice": 143.75,
558
+ # "midPrice": 143.855,
559
+ # "askPrice": 143.96,
560
+ # "impactBidPrice": 143.75,
561
+ # "impactMidPrice": 143.855,
562
+ # "impactAskPrice": 143.96,
563
+ # "hasLiquidity": True,
564
+ # "openInterest": 38103000,
565
+ # "openValue": 547963053300,
566
+ # "fairMethod": "FundingRate",
567
+ # "fairBasisRate": 0.1095,
568
+ # "fairBasis": 0.004,
569
+ # "fairPrice": 143.811,
570
+ # "markMethod": "FairPrice",
571
+ # "markPrice": 143.811,
572
+ # "indicativeTaxRate": null,
573
+ # "indicativeSettlePrice": 143.807,
574
+ # "optionUnderlyingPrice": null,
575
+ # "settledPriceAdjustmentRate": null,
576
+ # "settledPrice": null,
577
+ # "timestamp": "2022-01-14T17:49:55.000Z"
578
+ # }
579
+ # ]
580
+ #
581
+ return self.parse_markets(response)
582
+
583
+ def parse_market(self, market: dict) -> Market:
584
+ id = self.safe_string(market, 'symbol')
585
+ baseId = self.safe_string(market, 'underlying')
586
+ quoteId = self.safe_string(market, 'quoteCurrency')
587
+ settleId = self.safe_string(market, 'settlCurrency')
588
+ settle = self.safe_currency_code(settleId)
589
+ # 'positionCurrency' may be empty("", currently returns for ETHUSD)
590
+ # so let's take the settlCurrency first and then adjust if needed
591
+ typ = self.safe_string(market, 'typ') # type definitions at: https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_get
592
+ type: MarketType
593
+ swap = False
594
+ spot = False
595
+ future = False
596
+ if typ == 'FFWCSX':
597
+ type = 'swap'
598
+ swap = True
599
+ elif typ == 'IFXXXP':
600
+ type = 'spot'
601
+ spot = True
602
+ elif typ == 'FFCCSX':
603
+ type = 'future'
604
+ future = True
605
+ elif typ == 'FFICSX':
606
+ # prediction markets(without any volume)
607
+ quoteId = baseId
608
+ baseId = self.safe_string(market, 'rootSymbol')
609
+ type = 'future'
610
+ future = True
611
+ base = self.safe_currency_code(baseId)
612
+ quote = self.safe_currency_code(quoteId)
613
+ contract = swap or future
614
+ contractSize = None
615
+ isInverse = self.safe_value(market, 'isInverse') # self is True when BASE and SETTLE are same, i.e. BTC/XXX:BTC
616
+ isQuanto = self.safe_value(market, 'isQuanto') # self is True when BASE and SETTLE are different, i.e. AXS/XXX:BTC
617
+ linear = (not isInverse and not isQuanto) if contract else None
618
+ status = self.safe_string(market, 'state')
619
+ active = status != 'Unlisted'
620
+ expiry = None
621
+ expiryDatetime = None
622
+ symbol = None
623
+ if spot:
624
+ symbol = base + '/' + quote
625
+ elif contract:
626
+ symbol = base + '/' + quote + ':' + settle
627
+ if linear:
628
+ multiplierString = self.safe_string_2(market, 'underlyingToPositionMultiplier', 'underlyingToSettleMultiplier')
629
+ contractSize = self.parse_number(Precise.string_div('1', multiplierString))
630
+ else:
631
+ multiplierString = Precise.string_abs(self.safe_string(market, 'multiplier'))
632
+ contractSize = self.parse_number(multiplierString)
633
+ if future:
634
+ expiryDatetime = self.safe_string(market, 'expiry')
635
+ expiry = self.parse8601(expiryDatetime)
636
+ symbol = symbol + '-' + self.yymmdd(expiry)
637
+ else:
638
+ # for index/exotic markets, default to id
639
+ symbol = id
640
+ positionId = self.safe_string_2(market, 'positionCurrency', 'underlying')
641
+ position = self.safe_currency_code(positionId)
642
+ positionIsQuote = (position == quote)
643
+ maxOrderQty = self.safe_number(market, 'maxOrderQty')
644
+ initMargin = self.safe_string(market, 'initMargin', '1')
645
+ maxLeverage = self.parse_number(Precise.string_div('1', initMargin))
646
+ return {
647
+ 'id': id,
648
+ 'symbol': symbol,
649
+ 'base': base,
650
+ 'quote': quote,
651
+ 'settle': settle,
652
+ 'baseId': baseId,
653
+ 'quoteId': quoteId,
654
+ 'settleId': settleId,
655
+ 'type': type,
656
+ 'spot': spot,
657
+ 'margin': False,
658
+ 'swap': swap,
659
+ 'future': future,
660
+ 'option': False,
661
+ 'active': active,
662
+ 'contract': contract,
663
+ 'linear': linear,
664
+ 'inverse': isInverse,
665
+ 'quanto': isQuanto,
666
+ 'taker': self.safe_number(market, 'takerFee'),
667
+ 'maker': self.safe_number(market, 'makerFee'),
668
+ 'contractSize': contractSize,
669
+ 'expiry': expiry,
670
+ 'expiryDatetime': expiryDatetime,
671
+ 'strike': self.safe_number(market, 'optionStrikePrice'),
672
+ 'optionType': None,
673
+ 'precision': {
674
+ 'amount': self.safe_number(market, 'lotSize'),
675
+ 'price': self.safe_number(market, 'tickSize'),
676
+ },
677
+ 'limits': {
678
+ 'leverage': {
679
+ 'min': self.parse_number('1') if contract else None,
680
+ 'max': maxLeverage if contract else None,
681
+ },
682
+ 'amount': {
683
+ 'min': None,
684
+ 'max': None if positionIsQuote else maxOrderQty,
685
+ },
686
+ 'price': {
687
+ 'min': None,
688
+ 'max': self.safe_number(market, 'maxPrice'),
689
+ },
690
+ 'cost': {
691
+ 'min': None,
692
+ 'max': maxOrderQty if positionIsQuote else None,
693
+ },
694
+ },
695
+ 'created': self.parse8601(self.safe_string(market, 'listing')),
696
+ 'info': market,
697
+ }
698
+
699
+ def parse_balance(self, response) -> Balances:
700
+ #
701
+ # [
702
+ # {
703
+ # "account":1455728,
704
+ # "currency":"XBt",
705
+ # "riskLimit":1000000000000,
706
+ # "prevState":"",
707
+ # "state":"",
708
+ # "action":"",
709
+ # "amount":263542,
710
+ # "pendingCredit":0,
711
+ # "pendingDebit":0,
712
+ # "confirmedDebit":0,
713
+ # "prevRealisedPnl":0,
714
+ # "prevUnrealisedPnl":0,
715
+ # "grossComm":0,
716
+ # "grossOpenCost":0,
717
+ # "grossOpenPremium":0,
718
+ # "grossExecCost":0,
719
+ # "grossMarkValue":0,
720
+ # "riskValue":0,
721
+ # "taxableMargin":0,
722
+ # "initMargin":0,
723
+ # "maintMargin":0,
724
+ # "sessionMargin":0,
725
+ # "targetExcessMargin":0,
726
+ # "varMargin":0,
727
+ # "realisedPnl":0,
728
+ # "unrealisedPnl":0,
729
+ # "indicativeTax":0,
730
+ # "unrealisedProfit":0,
731
+ # "syntheticMargin":null,
732
+ # "walletBalance":263542,
733
+ # "marginBalance":263542,
734
+ # "marginBalancePcnt":1,
735
+ # "marginLeverage":0,
736
+ # "marginUsedPcnt":0,
737
+ # "excessMargin":263542,
738
+ # "excessMarginPcnt":1,
739
+ # "availableMargin":263542,
740
+ # "withdrawableMargin":263542,
741
+ # "timestamp":"2020-08-03T12:01:01.246Z",
742
+ # "grossLastValue":0,
743
+ # "commission":null
744
+ # }
745
+ # ]
746
+ #
747
+ result: dict = {'info': response}
748
+ for i in range(0, len(response)):
749
+ balance = response[i]
750
+ currencyId = self.safe_string(balance, 'currency')
751
+ code = self.safe_currency_code(currencyId)
752
+ account = self.account()
753
+ free = self.safe_string(balance, 'availableMargin')
754
+ total = self.safe_string(balance, 'marginBalance')
755
+ account['free'] = self.convert_to_real_amount(code, free)
756
+ account['total'] = self.convert_to_real_amount(code, total)
757
+ result[code] = account
758
+ return self.safe_balance(result)
759
+
760
+ def fetch_balance(self, params={}) -> Balances:
761
+ """
762
+ query for balance and get the amount of funds available for trading or funds locked in orders
763
+ :see: https://www.bitmex.com/api/explorer/#not /User/User_getMargin
764
+ :param dict [params]: extra parameters specific to the exchange API endpoint
765
+ :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
766
+ """
767
+ self.load_markets()
768
+ request: dict = {
769
+ 'currency': 'all',
770
+ }
771
+ response = self.privateGetUserMargin(self.extend(request, params))
772
+ #
773
+ # [
774
+ # {
775
+ # "account":1455728,
776
+ # "currency":"XBt",
777
+ # "riskLimit":1000000000000,
778
+ # "prevState":"",
779
+ # "state":"",
780
+ # "action":"",
781
+ # "amount":263542,
782
+ # "pendingCredit":0,
783
+ # "pendingDebit":0,
784
+ # "confirmedDebit":0,
785
+ # "prevRealisedPnl":0,
786
+ # "prevUnrealisedPnl":0,
787
+ # "grossComm":0,
788
+ # "grossOpenCost":0,
789
+ # "grossOpenPremium":0,
790
+ # "grossExecCost":0,
791
+ # "grossMarkValue":0,
792
+ # "riskValue":0,
793
+ # "taxableMargin":0,
794
+ # "initMargin":0,
795
+ # "maintMargin":0,
796
+ # "sessionMargin":0,
797
+ # "targetExcessMargin":0,
798
+ # "varMargin":0,
799
+ # "realisedPnl":0,
800
+ # "unrealisedPnl":0,
801
+ # "indicativeTax":0,
802
+ # "unrealisedProfit":0,
803
+ # "syntheticMargin":null,
804
+ # "walletBalance":263542,
805
+ # "marginBalance":263542,
806
+ # "marginBalancePcnt":1,
807
+ # "marginLeverage":0,
808
+ # "marginUsedPcnt":0,
809
+ # "excessMargin":263542,
810
+ # "excessMarginPcnt":1,
811
+ # "availableMargin":263542,
812
+ # "withdrawableMargin":263542,
813
+ # "timestamp":"2020-08-03T12:01:01.246Z",
814
+ # "grossLastValue":0,
815
+ # "commission":null
816
+ # }
817
+ # ]
818
+ #
819
+ return self.parse_balance(response)
820
+
821
+ def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
822
+ """
823
+ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
824
+ :see: https://www.bitmex.com/api/explorer/#not /OrderBook/OrderBook_getL2
825
+ :param str symbol: unified symbol of the market to fetch the order book for
826
+ :param int [limit]: the maximum amount of order book entries to return
827
+ :param dict [params]: extra parameters specific to the exchange API endpoint
828
+ :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
829
+ """
830
+ self.load_markets()
831
+ market = self.market(symbol)
832
+ request: dict = {
833
+ 'symbol': market['id'],
834
+ }
835
+ if limit is not None:
836
+ request['depth'] = limit
837
+ response = self.publicGetOrderBookL2(self.extend(request, params))
838
+ result: dict = {
839
+ 'symbol': symbol,
840
+ 'bids': [],
841
+ 'asks': [],
842
+ 'timestamp': None,
843
+ 'datetime': None,
844
+ 'nonce': None,
845
+ }
846
+ for i in range(0, len(response)):
847
+ order = response[i]
848
+ side = 'asks' if (order['side'] == 'Sell') else 'bids'
849
+ amount = self.convert_from_raw_quantity(symbol, self.safe_string(order, 'size'))
850
+ price = self.safe_number(order, 'price')
851
+ # https://github.com/ccxt/ccxt/issues/4926
852
+ # https://github.com/ccxt/ccxt/issues/4927
853
+ # the exchange sometimes returns null price in the orderbook
854
+ if price is not None:
855
+ result[side].append([price, amount])
856
+ result['bids'] = self.sort_by(result['bids'], 0, True)
857
+ result['asks'] = self.sort_by(result['asks'], 0)
858
+ return result
859
+
860
+ def fetch_order(self, id: str, symbol: Str = None, params={}):
861
+ """
862
+ fetches information on an order made by the user
863
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders
864
+ :param str symbol: unified symbol of the market the order was made in
865
+ :param dict [params]: extra parameters specific to the exchange API endpoint
866
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
867
+ """
868
+ filter: dict = {
869
+ 'filter': {
870
+ 'orderID': id,
871
+ },
872
+ }
873
+ response = self.fetch_orders(symbol, None, None, self.deep_extend(filter, params))
874
+ numResults = len(response)
875
+ if numResults == 1:
876
+ return response[0]
877
+ raise OrderNotFound(self.id + ': The order ' + id + ' not found.')
878
+
879
+ def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
880
+ """
881
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders
882
+ fetches information on multiple orders made by the user
883
+ :param str symbol: unified market symbol of the market orders were made in
884
+ :param int [since]: the earliest time in ms to fetch orders for
885
+ :param int [limit]: the maximum number of order structures to retrieve
886
+ :param dict [params]: extra parameters specific to the exchange API endpoint
887
+ :param int [params.until]: the earliest time in ms to fetch orders for
888
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
889
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
890
+ """
891
+ self.load_markets()
892
+ paginate = False
893
+ paginate, params = self.handle_option_and_params(params, 'fetchOrders', 'paginate')
894
+ if paginate:
895
+ return self.fetch_paginated_call_dynamic('fetchOrders', symbol, since, limit, params, 100)
896
+ market = None
897
+ request: dict = {}
898
+ if symbol is not None:
899
+ market = self.market(symbol)
900
+ request['symbol'] = market['id']
901
+ if since is not None:
902
+ request['startTime'] = self.iso8601(since)
903
+ if limit is not None:
904
+ request['count'] = limit
905
+ until = self.safe_integer_2(params, 'until', 'endTime')
906
+ if until is not None:
907
+ params = self.omit(params, ['until'])
908
+ request['endTime'] = self.iso8601(until)
909
+ request = self.deep_extend(request, params)
910
+ # why the hassle? urlencode in python is kinda broken for nested dicts.
911
+ # E.g. self.urlencode({"filter": {"open": True}}) will return "filter={'open':+True}"
912
+ # Bitmex doesn't like that. Hence resorting to self hack.
913
+ if 'filter' in request:
914
+ request['filter'] = self.json(request['filter'])
915
+ response = self.privateGetOrder(request)
916
+ return self.parse_orders(response, market, since, limit)
917
+
918
+ def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
919
+ """
920
+ fetch all unfilled currently open orders
921
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders
922
+ :param str symbol: unified market symbol
923
+ :param int [since]: the earliest time in ms to fetch open orders for
924
+ :param int [limit]: the maximum number of open orders structures to retrieve
925
+ :param dict [params]: extra parameters specific to the exchange API endpoint
926
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
927
+ """
928
+ request: dict = {
929
+ 'filter': {
930
+ 'open': True,
931
+ },
932
+ }
933
+ return self.fetch_orders(symbol, since, limit, self.deep_extend(request, params))
934
+
935
+ def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
936
+ """
937
+ fetches information on multiple closed orders made by the user
938
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_getOrders
939
+ :param str symbol: unified market symbol of the market orders were made in
940
+ :param int [since]: the earliest time in ms to fetch orders for
941
+ :param int [limit]: the maximum number of order structures to retrieve
942
+ :param dict [params]: extra parameters specific to the exchange API endpoint
943
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
944
+ """
945
+ # Bitmex barfs if you set 'open': False in the filter...
946
+ orders = self.fetch_orders(symbol, since, limit, params)
947
+ return self.filter_by_array(orders, 'status', ['closed', 'canceled'], False)
948
+
949
+ def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
950
+ """
951
+ fetch all trades made by the user
952
+ :see: https://www.bitmex.com/api/explorer/#not /Execution/Execution_getTradeHistory
953
+ :param str symbol: unified market symbol
954
+ :param int [since]: the earliest time in ms to fetch trades for
955
+ :param int [limit]: the maximum number of trades structures to retrieve
956
+ :param dict [params]: extra parameters specific to the exchange API endpoint
957
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
958
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
959
+ """
960
+ self.load_markets()
961
+ paginate = False
962
+ paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
963
+ if paginate:
964
+ return self.fetch_paginated_call_dynamic('fetchMyTrades', symbol, since, limit, params, 100)
965
+ market = None
966
+ request: dict = {}
967
+ if symbol is not None:
968
+ market = self.market(symbol)
969
+ request['symbol'] = market['id']
970
+ if since is not None:
971
+ request['startTime'] = self.iso8601(since)
972
+ if limit is not None:
973
+ request['count'] = limit
974
+ until = self.safe_integer_2(params, 'until', 'endTime')
975
+ if until is not None:
976
+ params = self.omit(params, ['until'])
977
+ request['endTime'] = self.iso8601(until)
978
+ request = self.deep_extend(request, params)
979
+ # why the hassle? urlencode in python is kinda broken for nested dicts.
980
+ # E.g. self.urlencode({"filter": {"open": True}}) will return "filter={'open':+True}"
981
+ # Bitmex doesn't like that. Hence resorting to self hack.
982
+ if 'filter' in request:
983
+ request['filter'] = self.json(request['filter'])
984
+ response = self.privateGetExecutionTradeHistory(request)
985
+ #
986
+ # [
987
+ # {
988
+ # "execID": "string",
989
+ # "orderID": "string",
990
+ # "clOrdID": "string",
991
+ # "clOrdLinkID": "string",
992
+ # "account": 0,
993
+ # "symbol": "string",
994
+ # "side": "string",
995
+ # "lastQty": 0,
996
+ # "lastPx": 0,
997
+ # "underlyingLastPx": 0,
998
+ # "lastMkt": "string",
999
+ # "lastLiquidityInd": "string",
1000
+ # "simpleOrderQty": 0,
1001
+ # "orderQty": 0,
1002
+ # "price": 0,
1003
+ # "displayQty": 0,
1004
+ # "stopPx": 0,
1005
+ # "pegOffsetValue": 0,
1006
+ # "pegPriceType": "string",
1007
+ # "currency": "string",
1008
+ # "settlCurrency": "string",
1009
+ # "execType": "string",
1010
+ # "ordType": "string",
1011
+ # "timeInForce": "string",
1012
+ # "execInst": "string",
1013
+ # "contingencyType": "string",
1014
+ # "exDestination": "string",
1015
+ # "ordStatus": "string",
1016
+ # "triggered": "string",
1017
+ # "workingIndicator": True,
1018
+ # "ordRejReason": "string",
1019
+ # "simpleLeavesQty": 0,
1020
+ # "leavesQty": 0,
1021
+ # "simpleCumQty": 0,
1022
+ # "cumQty": 0,
1023
+ # "avgPx": 0,
1024
+ # "commission": 0,
1025
+ # "tradePublishIndicator": "string",
1026
+ # "multiLegReportingType": "string",
1027
+ # "text": "string",
1028
+ # "trdMatchID": "string",
1029
+ # "execCost": 0,
1030
+ # "execComm": 0,
1031
+ # "homeNotional": 0,
1032
+ # "foreignNotional": 0,
1033
+ # "transactTime": "2019-03-05T12:47:02.762Z",
1034
+ # "timestamp": "2019-03-05T12:47:02.762Z"
1035
+ # }
1036
+ # ]
1037
+ #
1038
+ return self.parse_trades(response, market, since, limit)
1039
+
1040
+ def parse_ledger_entry_type(self, type):
1041
+ types: dict = {
1042
+ 'Withdrawal': 'transaction',
1043
+ 'RealisedPNL': 'margin',
1044
+ 'UnrealisedPNL': 'margin',
1045
+ 'Deposit': 'transaction',
1046
+ 'Transfer': 'transfer',
1047
+ 'AffiliatePayout': 'referral',
1048
+ 'SpotTrade': 'trade',
1049
+ }
1050
+ return self.safe_string(types, type, type)
1051
+
1052
+ def parse_ledger_entry(self, item: dict, currency: Currency = None):
1053
+ #
1054
+ # {
1055
+ # "transactID": "69573da3-7744-5467-3207-89fd6efe7a47",
1056
+ # "account": 24321,
1057
+ # "currency": "XBt",
1058
+ # "transactType": "Withdrawal", # "AffiliatePayout", "Transfer", "Deposit", "RealisedPNL", ...
1059
+ # "amount": -1000000,
1060
+ # "fee": 300000,
1061
+ # "transactStatus": "Completed", # "Canceled", ...
1062
+ # "address": "1Ex4fkF4NhQaQdRWNoYpqiPbDBbq18Kdd9",
1063
+ # "tx": "3BMEX91ZhhKoWtsH9QRb5dNXnmnGpiEetA",
1064
+ # "text": "",
1065
+ # "transactTime": "2017-03-21T20:05:14.388Z",
1066
+ # "walletBalance": 0, # balance after
1067
+ # "marginBalance": null,
1068
+ # "timestamp": "2017-03-22T13:09:23.514Z"
1069
+ # }
1070
+ #
1071
+ # ButMEX returns the unrealized pnl from the wallet history endpoint.
1072
+ # The unrealized pnl transaction has an empty timestamp.
1073
+ # It is not related to historical pnl it has status set to "Pending".
1074
+ # Therefore it's not a part of the history at all.
1075
+ # https://github.com/ccxt/ccxt/issues/6047
1076
+ #
1077
+ # {
1078
+ # "transactID":"00000000-0000-0000-0000-000000000000",
1079
+ # "account":121210,
1080
+ # "currency":"XBt",
1081
+ # "transactType":"UnrealisedPNL",
1082
+ # "amount":-5508,
1083
+ # "fee":0,
1084
+ # "transactStatus":"Pending",
1085
+ # "address":"XBTUSD",
1086
+ # "tx":"",
1087
+ # "text":"",
1088
+ # "transactTime":null, # ←---------------------------- null
1089
+ # "walletBalance":139198767,
1090
+ # "marginBalance":139193259,
1091
+ # "timestamp":null # ←---------------------------- null
1092
+ # }
1093
+ #
1094
+ id = self.safe_string(item, 'transactID')
1095
+ account = self.safe_string(item, 'account')
1096
+ referenceId = self.safe_string(item, 'tx')
1097
+ referenceAccount = None
1098
+ type = self.parse_ledger_entry_type(self.safe_string(item, 'transactType'))
1099
+ currencyId = self.safe_string(item, 'currency')
1100
+ code = self.safe_currency_code(currencyId, currency)
1101
+ amountString = self.safe_string(item, 'amount')
1102
+ amount = self.convert_to_real_amount(code, amountString)
1103
+ timestamp = self.parse8601(self.safe_string(item, 'transactTime'))
1104
+ if timestamp is None:
1105
+ # https://github.com/ccxt/ccxt/issues/6047
1106
+ # set the timestamp to zero, 1970 Jan 1 00:00:00
1107
+ # for unrealized pnl and other transactions without a timestamp
1108
+ timestamp = 0 # see comments above
1109
+ feeCost = self.safe_string(item, 'fee')
1110
+ if feeCost is not None:
1111
+ feeCost = self.convert_to_real_amount(code, feeCost)
1112
+ fee = {
1113
+ 'cost': self.parse_number(feeCost),
1114
+ 'currency': code,
1115
+ }
1116
+ after = self.safe_string(item, 'walletBalance')
1117
+ if after is not None:
1118
+ after = self.convert_to_real_amount(code, after)
1119
+ before = self.parse_number(Precise.string_sub(self.number_to_string(after), self.number_to_string(amount)))
1120
+ direction = None
1121
+ if Precise.string_lt(amountString, '0'):
1122
+ direction = 'out'
1123
+ amount = self.convert_to_real_amount(code, Precise.string_abs(amountString))
1124
+ else:
1125
+ direction = 'in'
1126
+ status = self.parse_transaction_status(self.safe_string(item, 'transactStatus'))
1127
+ return {
1128
+ 'id': id,
1129
+ 'info': item,
1130
+ 'timestamp': timestamp,
1131
+ 'datetime': self.iso8601(timestamp),
1132
+ 'direction': direction,
1133
+ 'account': account,
1134
+ 'referenceId': referenceId,
1135
+ 'referenceAccount': referenceAccount,
1136
+ 'type': type,
1137
+ 'currency': code,
1138
+ 'amount': amount,
1139
+ 'before': before,
1140
+ 'after': self.parse_number(after),
1141
+ 'status': status,
1142
+ 'fee': fee,
1143
+ }
1144
+
1145
+ def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
1146
+ """
1147
+ fetch the history of changes, actions done by the user or operations that altered balance of the user
1148
+ :see: https://www.bitmex.com/api/explorer/#not /User/User_getWalletHistory
1149
+ :param str code: unified currency code, default is None
1150
+ :param int [since]: timestamp in ms of the earliest ledger entry, default is None
1151
+ :param int [limit]: max number of ledger entrys to return, default is None
1152
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1153
+ :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger-structure>`
1154
+ """
1155
+ self.load_markets()
1156
+ request: dict = {
1157
+ # 'start': 123,
1158
+ }
1159
+ #
1160
+ # if since is not None:
1161
+ # # date-based pagination not supported
1162
+ # }
1163
+ #
1164
+ if limit is not None:
1165
+ request['count'] = limit
1166
+ currency = None
1167
+ if code is not None:
1168
+ currency = self.currency(code)
1169
+ request['currency'] = currency['id']
1170
+ response = self.privateGetUserWalletHistory(self.extend(request, params))
1171
+ #
1172
+ # [
1173
+ # {
1174
+ # "transactID": "69573da3-7744-5467-3207-89fd6efe7a47",
1175
+ # "account": 24321,
1176
+ # "currency": "XBt",
1177
+ # "transactType": "Withdrawal", # "AffiliatePayout", "Transfer", "Deposit", "RealisedPNL", ...
1178
+ # "amount": -1000000,
1179
+ # "fee": 300000,
1180
+ # "transactStatus": "Completed", # "Canceled", ...
1181
+ # "address": "1Ex4fkF4NhQaQdRWNoYpqiPbDBbq18Kdd9",
1182
+ # "tx": "3BMEX91ZhhKoWtsH9QRb5dNXnmnGpiEetA",
1183
+ # "text": "",
1184
+ # "transactTime": "2017-03-21T20:05:14.388Z",
1185
+ # "walletBalance": 0, # balance after
1186
+ # "marginBalance": null,
1187
+ # "timestamp": "2017-03-22T13:09:23.514Z"
1188
+ # }
1189
+ # ]
1190
+ #
1191
+ return self.parse_ledger(response, currency, since, limit)
1192
+
1193
+ def fetch_deposits_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
1194
+ """
1195
+ fetch history of deposits and withdrawals
1196
+ :see: https://www.bitmex.com/api/explorer/#not /User/User_getWalletHistory
1197
+ :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
1198
+ :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
1199
+ :param int [limit]: max number of deposit/withdrawals to return, default is None
1200
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1201
+ :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
1202
+ """
1203
+ self.load_markets()
1204
+ request: dict = {
1205
+ 'currency': 'all',
1206
+ # 'start': 123,
1207
+ }
1208
+ #
1209
+ # if since is not None:
1210
+ # # date-based pagination not supported
1211
+ # }
1212
+ #
1213
+ currency = None
1214
+ if code is not None:
1215
+ currency = self.currency(code)
1216
+ request['currency'] = currency['id']
1217
+ if limit is not None:
1218
+ request['count'] = limit
1219
+ response = self.privateGetUserWalletHistory(self.extend(request, params))
1220
+ transactions = self.filter_by_array(response, 'transactType', ['Withdrawal', 'Deposit'], False)
1221
+ return self.parse_transactions(transactions, currency, since, limit)
1222
+
1223
+ def parse_transaction_status(self, status: Str):
1224
+ statuses: dict = {
1225
+ 'Confirmed': 'pending',
1226
+ 'Canceled': 'canceled',
1227
+ 'Completed': 'ok',
1228
+ 'Pending': 'pending',
1229
+ }
1230
+ return self.safe_string(statuses, status, status)
1231
+
1232
+ def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
1233
+ #
1234
+ # {
1235
+ # "transactID": "ffe699c2-95ee-4c13-91f9-0faf41daec25",
1236
+ # "account": 123456,
1237
+ # "currency": "XBt",
1238
+ # "network":'', # "tron" for USDt, etc...
1239
+ # "transactType": "Withdrawal",
1240
+ # "amount": -100100000,
1241
+ # "fee": 100000,
1242
+ # "transactStatus": "Completed",
1243
+ # "address": "385cR5DM96n1HvBDMzLHPYcw89fZAXULJP",
1244
+ # "tx": "3BMEXabcdefghijklmnopqrstuvwxyz123",
1245
+ # "text": '',
1246
+ # "transactTime": "2019-01-02T01:00:00.000Z",
1247
+ # "walletBalance": 99900000, # self field might be inexistent
1248
+ # "marginBalance": None, # self field might be inexistent
1249
+ # "timestamp": "2019-01-02T13:00:00.000Z"
1250
+ # }
1251
+ #
1252
+ currencyId = self.safe_string(transaction, 'currency')
1253
+ currency = self.safe_currency(currencyId, currency)
1254
+ # For deposits, transactTime == timestamp
1255
+ # For withdrawals, transactTime is submission, timestamp is processed
1256
+ transactTime = self.parse8601(self.safe_string(transaction, 'transactTime'))
1257
+ timestamp = self.parse8601(self.safe_string(transaction, 'timestamp'))
1258
+ type = self.safe_string_lower(transaction, 'transactType')
1259
+ # Deposits have no from address or to address, withdrawals have both
1260
+ address = None
1261
+ addressFrom = None
1262
+ addressTo = None
1263
+ if type == 'withdrawal':
1264
+ address = self.safe_string(transaction, 'address')
1265
+ addressFrom = self.safe_string(transaction, 'tx')
1266
+ addressTo = address
1267
+ elif type == 'deposit':
1268
+ addressTo = self.safe_string(transaction, 'address')
1269
+ addressFrom = self.safe_string(transaction, 'tx')
1270
+ amountString = self.safe_string(transaction, 'amount')
1271
+ amountStringAbs = Precise.string_abs(amountString)
1272
+ amount = self.convert_to_real_amount(currency['code'], amountStringAbs)
1273
+ feeCostString = self.safe_string(transaction, 'fee')
1274
+ feeCost = self.convert_to_real_amount(currency['code'], feeCostString)
1275
+ status = self.safe_string(transaction, 'transactStatus')
1276
+ if status is not None:
1277
+ status = self.parse_transaction_status(status)
1278
+ return {
1279
+ 'info': transaction,
1280
+ 'id': self.safe_string(transaction, 'transactID'),
1281
+ 'txid': self.safe_string(transaction, 'tx'),
1282
+ 'type': type,
1283
+ 'currency': currency['code'],
1284
+ 'network': self.network_id_to_code(self.safe_string(transaction, 'network'), currency['code']),
1285
+ 'amount': self.parse_number(amount),
1286
+ 'status': status,
1287
+ 'timestamp': transactTime,
1288
+ 'datetime': self.iso8601(transactTime),
1289
+ 'address': address,
1290
+ 'addressFrom': addressFrom,
1291
+ 'addressTo': addressTo,
1292
+ 'tag': None,
1293
+ 'tagFrom': None,
1294
+ 'tagTo': None,
1295
+ 'updated': timestamp,
1296
+ 'internal': None,
1297
+ 'comment': None,
1298
+ 'fee': {
1299
+ 'currency': currency['code'],
1300
+ 'cost': self.parse_number(feeCost),
1301
+ 'rate': None,
1302
+ },
1303
+ }
1304
+
1305
+ def fetch_ticker(self, symbol: str, params={}) -> Ticker:
1306
+ """
1307
+ fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
1308
+ :see: https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_get
1309
+ :param str symbol: unified symbol of the market to fetch the ticker for
1310
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1311
+ :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
1312
+ """
1313
+ self.load_markets()
1314
+ market = self.market(symbol)
1315
+ request: dict = {
1316
+ 'symbol': market['id'],
1317
+ }
1318
+ response = self.publicGetInstrument(self.extend(request, params))
1319
+ ticker = self.safe_value(response, 0)
1320
+ if ticker is None:
1321
+ raise BadSymbol(self.id + ' fetchTicker() symbol ' + symbol + ' not found')
1322
+ return self.parse_ticker(ticker, market)
1323
+
1324
+ def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
1325
+ """
1326
+ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
1327
+ :see: https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_getActiveAndIndices
1328
+ :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
1329
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1330
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
1331
+ """
1332
+ self.load_markets()
1333
+ symbols = self.market_symbols(symbols)
1334
+ response = self.publicGetInstrumentActiveAndIndices(params)
1335
+ # same response "fetchMarkets"
1336
+ result: dict = {}
1337
+ for i in range(0, len(response)):
1338
+ ticker = self.parse_ticker(response[i])
1339
+ symbol = self.safe_string(ticker, 'symbol')
1340
+ if symbol is not None:
1341
+ result[symbol] = ticker
1342
+ return self.filter_by_array_tickers(result, 'symbol', symbols)
1343
+
1344
+ def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
1345
+ # see response sample under "fetchMarkets" because same endpoint is being used here
1346
+ marketId = self.safe_string(ticker, 'symbol')
1347
+ symbol = self.safe_symbol(marketId, market)
1348
+ timestamp = self.parse8601(self.safe_string(ticker, 'timestamp'))
1349
+ open = self.safe_string(ticker, 'prevPrice24h')
1350
+ last = self.safe_string(ticker, 'lastPrice')
1351
+ return self.safe_ticker({
1352
+ 'symbol': symbol,
1353
+ 'timestamp': timestamp,
1354
+ 'datetime': self.iso8601(timestamp),
1355
+ 'high': self.safe_string(ticker, 'highPrice'),
1356
+ 'low': self.safe_string(ticker, 'lowPrice'),
1357
+ 'bid': self.safe_string(ticker, 'bidPrice'),
1358
+ 'bidVolume': None,
1359
+ 'ask': self.safe_string(ticker, 'askPrice'),
1360
+ 'askVolume': None,
1361
+ 'vwap': self.safe_string(ticker, 'vwap'),
1362
+ 'open': open,
1363
+ 'close': last,
1364
+ 'last': last,
1365
+ 'previousClose': None,
1366
+ 'change': None,
1367
+ 'percentage': None,
1368
+ 'average': None,
1369
+ 'baseVolume': self.safe_string(ticker, 'homeNotional24h'),
1370
+ 'quoteVolume': self.safe_string(ticker, 'foreignNotional24h'),
1371
+ 'info': ticker,
1372
+ }, market)
1373
+
1374
+ def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
1375
+ #
1376
+ # {
1377
+ # "timestamp":"2015-09-25T13:38:00.000Z",
1378
+ # "symbol":"XBTUSD",
1379
+ # "open":237.45,
1380
+ # "high":237.45,
1381
+ # "low":237.45,
1382
+ # "close":237.45,
1383
+ # "trades":0,
1384
+ # "volume":0,
1385
+ # "vwap":null,
1386
+ # "lastSize":null,
1387
+ # "turnover":0,
1388
+ # "homeNotional":0,
1389
+ # "foreignNotional":0
1390
+ # }
1391
+ #
1392
+ marketId = self.safe_string(ohlcv, 'symbol')
1393
+ market = self.safe_market(marketId, market)
1394
+ volume = self.convert_from_raw_quantity(market['symbol'], self.safe_string(ohlcv, 'volume'))
1395
+ return [
1396
+ self.parse8601(self.safe_string(ohlcv, 'timestamp')),
1397
+ self.safe_number(ohlcv, 'open'),
1398
+ self.safe_number(ohlcv, 'high'),
1399
+ self.safe_number(ohlcv, 'low'),
1400
+ self.safe_number(ohlcv, 'close'),
1401
+ volume,
1402
+ ]
1403
+
1404
+ def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
1405
+ """
1406
+ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
1407
+ :see: https://www.bitmex.com/api/explorer/#not /Trade/Trade_getBucketed
1408
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
1409
+ :param str timeframe: the length of time each candle represents
1410
+ :param int [since]: timestamp in ms of the earliest candle to fetch
1411
+ :param int [limit]: the maximum amount of candles to fetch
1412
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1413
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
1414
+ :returns int[][]: A list of candles ordered, open, high, low, close, volume
1415
+ """
1416
+ self.load_markets()
1417
+ paginate = False
1418
+ paginate, params = self.handle_option_and_params(params, 'fetchOHLCV', 'paginate')
1419
+ if paginate:
1420
+ return self.fetch_paginated_call_deterministic('fetchOHLCV', symbol, since, limit, timeframe, params)
1421
+ # send JSON key/value pairs, such as {"key": "value"}
1422
+ # filter by individual fields and do advanced queries on timestamps
1423
+ # filter: Dict = {'key': 'value'}
1424
+ # send a bare series(e.g. XBU) to nearest expiring contract in that series
1425
+ # you can also send a timeframe, e.g. XBU:monthly
1426
+ # timeframes: daily, weekly, monthly, quarterly, and biquarterly
1427
+ market = self.market(symbol)
1428
+ request: dict = {
1429
+ 'symbol': market['id'],
1430
+ 'binSize': self.safe_string(self.timeframes, timeframe, timeframe),
1431
+ 'partial': True, # True == include yet-incomplete current bins
1432
+ # 'filter': filter, # filter by individual fields and do advanced queries
1433
+ # 'columns': [], # will return all columns if omitted
1434
+ # 'start': 0, # starting point for results(wtf?)
1435
+ # 'reverse': False, # True == newest first
1436
+ # 'endTime': '', # ending date filter for results
1437
+ }
1438
+ if limit is not None:
1439
+ request['count'] = limit # default 100, max 500
1440
+ until = self.safe_integer_2(params, 'until', 'endTime')
1441
+ if until is not None:
1442
+ params = self.omit(params, ['until'])
1443
+ request['endTime'] = self.iso8601(until)
1444
+ duration = self.parse_timeframe(timeframe) * 1000
1445
+ fetchOHLCVOpenTimestamp = self.safe_bool(self.options, 'fetchOHLCVOpenTimestamp', True)
1446
+ # if since is not set, they will return candles starting from 2017-01-01
1447
+ if since is not None:
1448
+ timestamp = since
1449
+ if fetchOHLCVOpenTimestamp:
1450
+ timestamp = self.sum(timestamp, duration)
1451
+ startTime = self.iso8601(timestamp)
1452
+ request['startTime'] = startTime # starting date filter for results
1453
+ else:
1454
+ request['reverse'] = True
1455
+ response = self.publicGetTradeBucketed(self.extend(request, params))
1456
+ #
1457
+ # [
1458
+ # {"timestamp":"2015-09-25T13:38:00.000Z","symbol":"XBTUSD","open":237.45,"high":237.45,"low":237.45,"close":237.45,"trades":0,"volume":0,"vwap":null,"lastSize":null,"turnover":0,"homeNotional":0,"foreignNotional":0},
1459
+ # {"timestamp":"2015-09-25T13:39:00.000Z","symbol":"XBTUSD","open":237.45,"high":237.45,"low":237.45,"close":237.45,"trades":0,"volume":0,"vwap":null,"lastSize":null,"turnover":0,"homeNotional":0,"foreignNotional":0},
1460
+ # {"timestamp":"2015-09-25T13:40:00.000Z","symbol":"XBTUSD","open":237.45,"high":237.45,"low":237.45,"close":237.45,"trades":0,"volume":0,"vwap":null,"lastSize":null,"turnover":0,"homeNotional":0,"foreignNotional":0}
1461
+ # ]
1462
+ #
1463
+ result = self.parse_ohlcvs(response, market, timeframe, since, limit)
1464
+ if fetchOHLCVOpenTimestamp:
1465
+ # bitmex returns the candle's close timestamp - https://github.com/ccxt/ccxt/issues/4446
1466
+ # we can emulate the open timestamp by shifting all the timestamps one place
1467
+ # so the previous close becomes the current open, and we drop the first candle
1468
+ for i in range(0, len(result)):
1469
+ result[i][0] = result[i][0] - duration
1470
+ return result
1471
+
1472
+ def parse_trade(self, trade: dict, market: Market = None) -> Trade:
1473
+ #
1474
+ # fetchTrades(public)
1475
+ #
1476
+ # {
1477
+ # "timestamp": "2018-08-28T00:00:02.735Z",
1478
+ # "symbol": "XBTUSD",
1479
+ # "side": "Buy",
1480
+ # "size": 2000,
1481
+ # "price": 6906.5,
1482
+ # "tickDirection": "PlusTick",
1483
+ # "trdMatchID": "b9a42432-0a46-6a2f-5ecc-c32e9ca4baf8",
1484
+ # "grossValue": 28958000,
1485
+ # "homeNotional": 0.28958,
1486
+ # "foreignNotional": 2000
1487
+ # }
1488
+ #
1489
+ # fetchMyTrades(private)
1490
+ #
1491
+ # {
1492
+ # "execID": "string",
1493
+ # "orderID": "string",
1494
+ # "clOrdID": "string",
1495
+ # "clOrdLinkID": "string",
1496
+ # "account": 0,
1497
+ # "symbol": "string",
1498
+ # "side": "string",
1499
+ # "lastQty": 0,
1500
+ # "lastPx": 0,
1501
+ # "underlyingLastPx": 0,
1502
+ # "lastMkt": "string",
1503
+ # "lastLiquidityInd": "string",
1504
+ # "simpleOrderQty": 0,
1505
+ # "orderQty": 0,
1506
+ # "price": 0,
1507
+ # "displayQty": 0,
1508
+ # "stopPx": 0,
1509
+ # "pegOffsetValue": 0,
1510
+ # "pegPriceType": "string",
1511
+ # "currency": "string",
1512
+ # "settlCurrency": "string",
1513
+ # "execType": "string",
1514
+ # "ordType": "string",
1515
+ # "timeInForce": "string",
1516
+ # "execInst": "string",
1517
+ # "contingencyType": "string",
1518
+ # "exDestination": "string",
1519
+ # "ordStatus": "string",
1520
+ # "triggered": "string",
1521
+ # "workingIndicator": True,
1522
+ # "ordRejReason": "string",
1523
+ # "simpleLeavesQty": 0,
1524
+ # "leavesQty": 0,
1525
+ # "simpleCumQty": 0,
1526
+ # "cumQty": 0,
1527
+ # "avgPx": 0,
1528
+ # "commission": 0,
1529
+ # "tradePublishIndicator": "string",
1530
+ # "multiLegReportingType": "string",
1531
+ # "text": "string",
1532
+ # "trdMatchID": "string",
1533
+ # "execCost": 0,
1534
+ # "execComm": 0,
1535
+ # "homeNotional": 0,
1536
+ # "foreignNotional": 0,
1537
+ # "transactTime": "2019-03-05T12:47:02.762Z",
1538
+ # "timestamp": "2019-03-05T12:47:02.762Z"
1539
+ # }
1540
+ #
1541
+ marketId = self.safe_string(trade, 'symbol')
1542
+ symbol = self.safe_symbol(marketId, market)
1543
+ timestamp = self.parse8601(self.safe_string(trade, 'timestamp'))
1544
+ priceString = self.safe_string_2(trade, 'avgPx', 'price')
1545
+ amountString = self.convert_from_raw_quantity(symbol, self.safe_string_2(trade, 'size', 'lastQty'))
1546
+ execCost = self.number_to_string(self.convert_from_raw_cost(symbol, self.safe_string(trade, 'execCost')))
1547
+ id = self.safe_string(trade, 'trdMatchID')
1548
+ order = self.safe_string(trade, 'orderID')
1549
+ side = self.safe_string_lower(trade, 'side')
1550
+ # price * amount doesn't work for all symbols(e.g. XBT, ETH)
1551
+ fee = None
1552
+ feeCostString = self.number_to_string(self.convert_from_raw_cost(symbol, self.safe_string(trade, 'execComm')))
1553
+ if feeCostString is not None:
1554
+ currencyId = self.safe_string_2(trade, 'settlCurrency', 'currency')
1555
+ fee = {
1556
+ 'cost': feeCostString,
1557
+ 'currency': self.safe_currency_code(currencyId),
1558
+ 'rate': self.safe_string(trade, 'commission'),
1559
+ }
1560
+ # Trade or Funding
1561
+ execType = self.safe_string(trade, 'execType')
1562
+ takerOrMaker = None
1563
+ if feeCostString is not None and execType == 'Trade':
1564
+ takerOrMaker = 'maker' if Precise.string_lt(feeCostString, '0') else 'taker'
1565
+ type = self.safe_string_lower(trade, 'ordType')
1566
+ return self.safe_trade({
1567
+ 'info': trade,
1568
+ 'timestamp': timestamp,
1569
+ 'datetime': self.iso8601(timestamp),
1570
+ 'symbol': symbol,
1571
+ 'id': id,
1572
+ 'order': order,
1573
+ 'type': type,
1574
+ 'takerOrMaker': takerOrMaker,
1575
+ 'side': side,
1576
+ 'price': priceString,
1577
+ 'cost': Precise.string_abs(execCost),
1578
+ 'amount': amountString,
1579
+ 'fee': fee,
1580
+ }, market)
1581
+
1582
+ def parse_order_status(self, status: Str):
1583
+ statuses: dict = {
1584
+ 'New': 'open',
1585
+ 'PartiallyFilled': 'open',
1586
+ 'Filled': 'closed',
1587
+ 'DoneForDay': 'open',
1588
+ 'Canceled': 'canceled',
1589
+ 'PendingCancel': 'open',
1590
+ 'PendingNew': 'open',
1591
+ 'Rejected': 'rejected',
1592
+ 'Expired': 'expired',
1593
+ 'Stopped': 'open',
1594
+ 'Untriggered': 'open',
1595
+ 'Triggered': 'open',
1596
+ }
1597
+ return self.safe_string(statuses, status, status)
1598
+
1599
+ def parse_time_in_force(self, timeInForce: Str):
1600
+ timeInForces: dict = {
1601
+ 'Day': 'Day',
1602
+ 'GoodTillCancel': 'GTC',
1603
+ 'ImmediateOrCancel': 'IOC',
1604
+ 'FillOrKill': 'FOK',
1605
+ }
1606
+ return self.safe_string(timeInForces, timeInForce, timeInForce)
1607
+
1608
+ def parse_order(self, order: dict, market: Market = None) -> Order:
1609
+ #
1610
+ # {
1611
+ # "orderID":"56222c7a-9956-413a-82cf-99f4812c214b",
1612
+ # "clOrdID":"",
1613
+ # "clOrdLinkID":"",
1614
+ # "account":1455728,
1615
+ # "symbol":"XBTUSD",
1616
+ # "side":"Sell",
1617
+ # "simpleOrderQty":null,
1618
+ # "orderQty":1,
1619
+ # "price":40000,
1620
+ # "displayQty":null,
1621
+ # "stopPx":null,
1622
+ # "pegOffsetValue":null,
1623
+ # "pegPriceType":"",
1624
+ # "currency":"USD",
1625
+ # "settlCurrency":"XBt",
1626
+ # "ordType":"Limit",
1627
+ # "timeInForce":"GoodTillCancel",
1628
+ # "execInst":"",
1629
+ # "contingencyType":"",
1630
+ # "exDestination":"XBME",
1631
+ # "ordStatus":"New",
1632
+ # "triggered":"",
1633
+ # "workingIndicator":true,
1634
+ # "ordRejReason":"",
1635
+ # "simpleLeavesQty":null,
1636
+ # "leavesQty":1,
1637
+ # "simpleCumQty":null,
1638
+ # "cumQty":0,
1639
+ # "avgPx":null,
1640
+ # "multiLegReportingType":"SingleSecurity",
1641
+ # "text":"Submitted via API.",
1642
+ # "transactTime":"2021-01-02T21:38:49.246Z",
1643
+ # "timestamp":"2021-01-02T21:38:49.246Z"
1644
+ # }
1645
+ #
1646
+ marketId = self.safe_string(order, 'symbol')
1647
+ market = self.safe_market(marketId, market)
1648
+ symbol = market['symbol']
1649
+ qty = self.safe_string(order, 'orderQty')
1650
+ cost = None
1651
+ amount = None
1652
+ isInverse = False
1653
+ if marketId is None:
1654
+ defaultSubType = self.safe_string(self.options, 'defaultSubType', 'linear')
1655
+ isInverse = (defaultSubType == 'inverse')
1656
+ else:
1657
+ isInverse = self.safe_bool(market, 'inverse', False)
1658
+ if isInverse:
1659
+ cost = self.convert_from_raw_quantity(symbol, qty)
1660
+ else:
1661
+ amount = self.convert_from_raw_quantity(symbol, qty)
1662
+ average = self.safe_string(order, 'avgPx')
1663
+ filled = None
1664
+ cumQty = self.number_to_string(self.convert_from_raw_quantity(symbol, self.safe_string(order, 'cumQty')))
1665
+ if isInverse:
1666
+ filled = Precise.string_div(cumQty, average)
1667
+ else:
1668
+ filled = cumQty
1669
+ execInst = self.safe_string(order, 'execInst')
1670
+ postOnly = None
1671
+ if execInst is not None:
1672
+ postOnly = (execInst == 'ParticipateDoNotInitiate')
1673
+ timestamp = self.parse8601(self.safe_string(order, 'timestamp'))
1674
+ stopPrice = self.safe_number(order, 'stopPx')
1675
+ remaining = self.safe_string(order, 'leavesQty')
1676
+ return self.safe_order({
1677
+ 'info': order,
1678
+ 'id': self.safe_string(order, 'orderID'),
1679
+ 'clientOrderId': self.safe_string(order, 'clOrdID'),
1680
+ 'timestamp': timestamp,
1681
+ 'datetime': self.iso8601(timestamp),
1682
+ 'lastTradeTimestamp': self.parse8601(self.safe_string(order, 'transactTime')),
1683
+ 'symbol': symbol,
1684
+ 'type': self.safe_string_lower(order, 'ordType'),
1685
+ 'timeInForce': self.parse_time_in_force(self.safe_string(order, 'timeInForce')),
1686
+ 'postOnly': postOnly,
1687
+ 'side': self.safe_string_lower(order, 'side'),
1688
+ 'price': self.safe_string(order, 'price'),
1689
+ 'stopPrice': stopPrice,
1690
+ 'triggerPrice': stopPrice,
1691
+ 'amount': amount,
1692
+ 'cost': cost,
1693
+ 'average': average,
1694
+ 'filled': filled,
1695
+ 'remaining': self.convert_from_raw_quantity(symbol, remaining),
1696
+ 'status': self.parse_order_status(self.safe_string(order, 'ordStatus')),
1697
+ 'fee': None,
1698
+ 'trades': None,
1699
+ }, market)
1700
+
1701
+ def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
1702
+ """
1703
+ get the list of most recent trades for a particular symbol
1704
+ :see: https://www.bitmex.com/api/explorer/#not /Trade/Trade_get
1705
+ :param str symbol: unified symbol of the market to fetch trades for
1706
+ :param int [since]: timestamp in ms of the earliest trade to fetch
1707
+ :param int [limit]: the maximum amount of trades to fetch
1708
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1709
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
1710
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
1711
+ """
1712
+ self.load_markets()
1713
+ paginate = False
1714
+ paginate, params = self.handle_option_and_params(params, 'fetchTrades', 'paginate')
1715
+ if paginate:
1716
+ return self.fetch_paginated_call_dynamic('fetchTrades', symbol, since, limit, params)
1717
+ market = self.market(symbol)
1718
+ request: dict = {
1719
+ 'symbol': market['id'],
1720
+ }
1721
+ if since is not None:
1722
+ request['startTime'] = self.iso8601(since)
1723
+ else:
1724
+ # by default reverse=false, i.e. trades are fetched since the time of market inception(year 2015 for XBTUSD)
1725
+ request['reverse'] = True
1726
+ if limit is not None:
1727
+ request['count'] = min(limit, 1000) # api maximum 1000
1728
+ until = self.safe_integer_2(params, 'until', 'endTime')
1729
+ if until is not None:
1730
+ params = self.omit(params, ['until'])
1731
+ request['endTime'] = self.iso8601(until)
1732
+ response = self.publicGetTrade(self.extend(request, params))
1733
+ #
1734
+ # [
1735
+ # {
1736
+ # "timestamp": "2018-08-28T00:00:02.735Z",
1737
+ # "symbol": "XBTUSD",
1738
+ # "side": "Buy",
1739
+ # "size": 2000,
1740
+ # "price": 6906.5,
1741
+ # "tickDirection": "PlusTick",
1742
+ # "trdMatchID": "b9a42432-0a46-6a2f-5ecc-c32e9ca4baf8",
1743
+ # "grossValue": 28958000,
1744
+ # "homeNotional": 0.28958,
1745
+ # "foreignNotional": 2000
1746
+ # },
1747
+ # {
1748
+ # "timestamp": "2018-08-28T00:00:03.778Z",
1749
+ # "symbol": "XBTUSD",
1750
+ # "side": "Sell",
1751
+ # "size": 1000,
1752
+ # "price": 6906,
1753
+ # "tickDirection": "MinusTick",
1754
+ # "trdMatchID": "0d4f1682-5270-a800-569b-4a0eb92db97c",
1755
+ # "grossValue": 14480000,
1756
+ # "homeNotional": 0.1448,
1757
+ # "foreignNotional": 1000
1758
+ # },
1759
+ # ]
1760
+ #
1761
+ return self.parse_trades(response, market, since, limit)
1762
+
1763
+ def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1764
+ """
1765
+ create a trade order
1766
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_new
1767
+ :param str symbol: unified symbol of the market to create an order in
1768
+ :param str type: 'market' or 'limit'
1769
+ :param str side: 'buy' or 'sell'
1770
+ :param float amount: how much of currency you want to trade in units of base currency
1771
+ :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
1772
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1773
+ :param dict [params.triggerPrice]: the price at which a trigger order is triggered at
1774
+ :param dict [params.triggerDirection]: the direction whenever the trigger happens with relation to price - 'above' or 'below'
1775
+ :param float [params.trailingAmount]: the quote amount to trail away from the current market price
1776
+ :returns dict: an `order structure <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
1777
+ """
1778
+ self.load_markets()
1779
+ market = self.market(symbol)
1780
+ orderType = self.capitalize(type)
1781
+ reduceOnly = self.safe_value(params, 'reduceOnly')
1782
+ if reduceOnly is not None:
1783
+ if (not market['swap']) and (not market['future']):
1784
+ raise InvalidOrder(self.id + ' createOrder() does not support reduceOnly for ' + market['type'] + ' orders, reduceOnly orders are supported for swap and future markets only')
1785
+ brokerId = self.safe_string(self.options, 'brokerId', 'CCXT')
1786
+ qty = self.parse_to_int(self.amount_to_precision(symbol, amount))
1787
+ request: dict = {
1788
+ 'symbol': market['id'],
1789
+ 'side': self.capitalize(side),
1790
+ 'orderQty': qty, # lot size multiplied by the number of contracts
1791
+ 'ordType': orderType,
1792
+ 'text': brokerId,
1793
+ }
1794
+ # support for unified trigger format
1795
+ triggerPrice = self.safe_number_n(params, ['triggerPrice', 'stopPx', 'stopPrice'])
1796
+ trailingAmount = self.safe_string_2(params, 'trailingAmount', 'pegOffsetValue')
1797
+ isTriggerOrder = triggerPrice is not None
1798
+ isTrailingAmountOrder = trailingAmount is not None
1799
+ if isTriggerOrder or isTrailingAmountOrder:
1800
+ triggerDirection = self.safe_string(params, 'triggerDirection')
1801
+ triggerAbove = (triggerDirection == 'above')
1802
+ if (type == 'limit') or (type == 'market'):
1803
+ self.check_required_argument('createOrder', triggerDirection, 'triggerDirection', ['above', 'below'])
1804
+ if type == 'limit':
1805
+ if side == 'buy':
1806
+ orderType = 'StopLimit' if triggerAbove else 'LimitIfTouched'
1807
+ else:
1808
+ orderType = 'LimitIfTouched' if triggerAbove else 'StopLimit'
1809
+ elif type == 'market':
1810
+ if side == 'buy':
1811
+ orderType = 'Stop' if triggerAbove else 'MarketIfTouched'
1812
+ else:
1813
+ orderType = 'MarketIfTouched' if triggerAbove else 'Stop'
1814
+ if isTrailingAmountOrder:
1815
+ isStopSellOrder = (side == 'sell') and ((orderType == 'Stop') or (orderType == 'StopLimit'))
1816
+ isBuyIfTouchedOrder = (side == 'buy') and ((orderType == 'MarketIfTouched') or (orderType == 'LimitIfTouched'))
1817
+ if isStopSellOrder or isBuyIfTouchedOrder:
1818
+ trailingAmount = '-' + trailingAmount
1819
+ request['pegOffsetValue'] = self.parse_to_numeric(trailingAmount)
1820
+ request['pegPriceType'] = 'TrailingStopPeg'
1821
+ else:
1822
+ if triggerPrice is None:
1823
+ # if exchange specific trigger types were provided
1824
+ raise ArgumentsRequired(self.id + ' createOrder() requires a triggerPrice(stopPx|stopPrice) parameter for the ' + orderType + ' order type')
1825
+ request['stopPx'] = self.parse_to_numeric(self.price_to_precision(symbol, triggerPrice))
1826
+ request['ordType'] = orderType
1827
+ params = self.omit(params, ['triggerPrice', 'stopPrice', 'stopPx', 'triggerDirection', 'trailingAmount'])
1828
+ if (orderType == 'Limit') or (orderType == 'StopLimit') or (orderType == 'LimitIfTouched'):
1829
+ request['price'] = self.parse_to_numeric(self.price_to_precision(symbol, price))
1830
+ clientOrderId = self.safe_string_2(params, 'clOrdID', 'clientOrderId')
1831
+ if clientOrderId is not None:
1832
+ request['clOrdID'] = clientOrderId
1833
+ params = self.omit(params, ['clOrdID', 'clientOrderId'])
1834
+ response = self.privatePostOrder(self.extend(request, params))
1835
+ return self.parse_order(response, market)
1836
+
1837
+ def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
1838
+ self.load_markets()
1839
+ request: dict = {}
1840
+ trailingAmount = self.safe_string_2(params, 'trailingAmount', 'pegOffsetValue')
1841
+ isTrailingAmountOrder = trailingAmount is not None
1842
+ if isTrailingAmountOrder:
1843
+ triggerDirection = self.safe_string(params, 'triggerDirection')
1844
+ triggerAbove = (triggerDirection == 'above')
1845
+ if (type == 'limit') or (type == 'market'):
1846
+ self.check_required_argument('createOrder', triggerDirection, 'triggerDirection', ['above', 'below'])
1847
+ orderType = None
1848
+ if type == 'limit':
1849
+ if side == 'buy':
1850
+ orderType = 'StopLimit' if triggerAbove else 'LimitIfTouched'
1851
+ else:
1852
+ orderType = 'LimitIfTouched' if triggerAbove else 'StopLimit'
1853
+ elif type == 'market':
1854
+ if side == 'buy':
1855
+ orderType = 'Stop' if triggerAbove else 'MarketIfTouched'
1856
+ else:
1857
+ orderType = 'MarketIfTouched' if triggerAbove else 'Stop'
1858
+ isStopSellOrder = (side == 'sell') and ((orderType == 'Stop') or (orderType == 'StopLimit'))
1859
+ isBuyIfTouchedOrder = (side == 'buy') and ((orderType == 'MarketIfTouched') or (orderType == 'LimitIfTouched'))
1860
+ if isStopSellOrder or isBuyIfTouchedOrder:
1861
+ trailingAmount = '-' + trailingAmount
1862
+ request['pegOffsetValue'] = self.parse_to_numeric(trailingAmount)
1863
+ params = self.omit(params, ['triggerDirection', 'trailingAmount'])
1864
+ origClOrdID = self.safe_string_2(params, 'origClOrdID', 'clientOrderId')
1865
+ if origClOrdID is not None:
1866
+ request['origClOrdID'] = origClOrdID
1867
+ clientOrderId = self.safe_string(params, 'clOrdID', 'clientOrderId')
1868
+ if clientOrderId is not None:
1869
+ request['clOrdID'] = clientOrderId
1870
+ params = self.omit(params, ['origClOrdID', 'clOrdID', 'clientOrderId'])
1871
+ else:
1872
+ request['orderID'] = id
1873
+ if amount is not None:
1874
+ qty = self.parse_to_int(self.amount_to_precision(symbol, amount))
1875
+ request['orderQty'] = qty
1876
+ if price is not None:
1877
+ request['price'] = price
1878
+ brokerId = self.safe_string(self.options, 'brokerId', 'CCXT')
1879
+ request['text'] = brokerId
1880
+ response = self.privatePutOrder(self.extend(request, params))
1881
+ return self.parse_order(response)
1882
+
1883
+ def cancel_order(self, id: str, symbol: Str = None, params={}):
1884
+ """
1885
+ cancels an open order
1886
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_cancel
1887
+ :param str id: order id
1888
+ :param str symbol: not used by bitmex cancelOrder()
1889
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1890
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1891
+ """
1892
+ self.load_markets()
1893
+ # https://github.com/ccxt/ccxt/issues/6507
1894
+ clientOrderId = self.safe_value_2(params, 'clOrdID', 'clientOrderId')
1895
+ request: dict = {}
1896
+ if clientOrderId is None:
1897
+ request['orderID'] = id
1898
+ else:
1899
+ request['clOrdID'] = clientOrderId
1900
+ params = self.omit(params, ['clOrdID', 'clientOrderId'])
1901
+ response = self.privateDeleteOrder(self.extend(request, params))
1902
+ order = self.safe_value(response, 0, {})
1903
+ error = self.safe_string(order, 'error')
1904
+ if error is not None:
1905
+ if error.find('Unable to cancel order due to existing state') >= 0:
1906
+ raise OrderNotFound(self.id + ' cancelOrder() failed: ' + error)
1907
+ return self.parse_order(order)
1908
+
1909
+ def cancel_orders(self, ids, symbol: Str = None, params={}):
1910
+ """
1911
+ cancel multiple orders
1912
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_cancel
1913
+ :param str[] ids: order ids
1914
+ :param str symbol: not used by bitmex cancelOrders()
1915
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1916
+ :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1917
+ """
1918
+ # return self.cancel_order(ids, symbol, params)
1919
+ self.load_markets()
1920
+ # https://github.com/ccxt/ccxt/issues/6507
1921
+ clientOrderId = self.safe_value_2(params, 'clOrdID', 'clientOrderId')
1922
+ request: dict = {}
1923
+ if clientOrderId is None:
1924
+ request['orderID'] = ids
1925
+ else:
1926
+ request['clOrdID'] = clientOrderId
1927
+ params = self.omit(params, ['clOrdID', 'clientOrderId'])
1928
+ response = self.privateDeleteOrder(self.extend(request, params))
1929
+ return self.parse_orders(response)
1930
+
1931
+ def cancel_all_orders(self, symbol: Str = None, params={}):
1932
+ """
1933
+ cancel all open orders
1934
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_cancelAll
1935
+ :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
1936
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1937
+ :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1938
+ """
1939
+ self.load_markets()
1940
+ request: dict = {}
1941
+ market = None
1942
+ if symbol is not None:
1943
+ market = self.market(symbol)
1944
+ request['symbol'] = market['id']
1945
+ response = self.privateDeleteOrderAll(self.extend(request, params))
1946
+ #
1947
+ # [
1948
+ # {
1949
+ # "orderID": "string",
1950
+ # "clOrdID": "string",
1951
+ # "clOrdLinkID": "string",
1952
+ # "account": 0,
1953
+ # "symbol": "string",
1954
+ # "side": "string",
1955
+ # "simpleOrderQty": 0,
1956
+ # "orderQty": 0,
1957
+ # "price": 0,
1958
+ # "displayQty": 0,
1959
+ # "stopPx": 0,
1960
+ # "pegOffsetValue": 0,
1961
+ # "pegPriceType": "string",
1962
+ # "currency": "string",
1963
+ # "settlCurrency": "string",
1964
+ # "ordType": "string",
1965
+ # "timeInForce": "string",
1966
+ # "execInst": "string",
1967
+ # "contingencyType": "string",
1968
+ # "exDestination": "string",
1969
+ # "ordStatus": "string",
1970
+ # "triggered": "string",
1971
+ # "workingIndicator": True,
1972
+ # "ordRejReason": "string",
1973
+ # "simpleLeavesQty": 0,
1974
+ # "leavesQty": 0,
1975
+ # "simpleCumQty": 0,
1976
+ # "cumQty": 0,
1977
+ # "avgPx": 0,
1978
+ # "multiLegReportingType": "string",
1979
+ # "text": "string",
1980
+ # "transactTime": "2020-06-01T09:36:35.290Z",
1981
+ # "timestamp": "2020-06-01T09:36:35.290Z"
1982
+ # }
1983
+ # ]
1984
+ #
1985
+ return self.parse_orders(response, market)
1986
+
1987
+ def cancel_all_orders_after(self, timeout: Int, params={}):
1988
+ """
1989
+ dead man's switch, cancel all orders after the given timeout
1990
+ :see: https://www.bitmex.com/api/explorer/#not /Order/Order_cancelAllAfter
1991
+ :param number timeout: time in milliseconds, 0 represents cancel the timer
1992
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1993
+ :returns dict: the api result
1994
+ """
1995
+ self.load_markets()
1996
+ request: dict = {
1997
+ 'timeout': self.parse_to_int(timeout / 1000) if (timeout > 0) else 0,
1998
+ }
1999
+ response = self.privatePostOrderCancelAllAfter(self.extend(request, params))
2000
+ #
2001
+ # {
2002
+ # now: '2024-04-09T09:01:56.560Z',
2003
+ # cancelTime: '2024-04-09T09:01:56.660Z'
2004
+ # }
2005
+ #
2006
+ return response
2007
+
2008
+ def fetch_leverages(self, symbols: Strings = None, params={}) -> Leverages:
2009
+ """
2010
+ fetch the set leverage for all contract markets
2011
+ :see: https://www.bitmex.com/api/explorer/#not /Position/Position_get
2012
+ :param str[] [symbols]: a list of unified market symbols
2013
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2014
+ :returns dict: a list of `leverage structures <https://docs.ccxt.com/#/?id=leverage-structure>`
2015
+ """
2016
+ self.load_markets()
2017
+ leverages = self.fetch_positions(symbols, params)
2018
+ return self.parse_leverages(leverages, symbols, 'symbol')
2019
+
2020
+ def parse_leverage(self, leverage: dict, market: Market = None) -> Leverage:
2021
+ marketId = self.safe_string(leverage, 'symbol')
2022
+ return {
2023
+ 'info': leverage,
2024
+ 'symbol': self.safe_symbol(marketId, market),
2025
+ 'marginMode': self.safe_string_lower(leverage, 'marginMode'),
2026
+ 'longLeverage': self.safe_integer(leverage, 'leverage'),
2027
+ 'shortLeverage': self.safe_integer(leverage, 'leverage'),
2028
+ }
2029
+
2030
+ def fetch_positions(self, symbols: Strings = None, params={}):
2031
+ """
2032
+ fetch all open positions
2033
+ :see: https://www.bitmex.com/api/explorer/#not /Position/Position_get
2034
+ :param str[]|None symbols: list of unified market symbols
2035
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2036
+ :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
2037
+ """
2038
+ self.load_markets()
2039
+ response = self.privateGetPosition(params)
2040
+ #
2041
+ # [
2042
+ # {
2043
+ # "account": 0,
2044
+ # "symbol": "string",
2045
+ # "currency": "string",
2046
+ # "underlying": "string",
2047
+ # "quoteCurrency": "string",
2048
+ # "commission": 0,
2049
+ # "initMarginReq": 0,
2050
+ # "maintMarginReq": 0,
2051
+ # "riskLimit": 0,
2052
+ # "leverage": 0,
2053
+ # "crossMargin": True,
2054
+ # "deleveragePercentile": 0,
2055
+ # "rebalancedPnl": 0,
2056
+ # "prevRealisedPnl": 0,
2057
+ # "prevUnrealisedPnl": 0,
2058
+ # "prevClosePrice": 0,
2059
+ # "openingTimestamp": "2020-11-09T06:53:59.892Z",
2060
+ # "openingQty": 0,
2061
+ # "openingCost": 0,
2062
+ # "openingComm": 0,
2063
+ # "openOrderBuyQty": 0,
2064
+ # "openOrderBuyCost": 0,
2065
+ # "openOrderBuyPremium": 0,
2066
+ # "openOrderSellQty": 0,
2067
+ # "openOrderSellCost": 0,
2068
+ # "openOrderSellPremium": 0,
2069
+ # "execBuyQty": 0,
2070
+ # "execBuyCost": 0,
2071
+ # "execSellQty": 0,
2072
+ # "execSellCost": 0,
2073
+ # "execQty": 0,
2074
+ # "execCost": 0,
2075
+ # "execComm": 0,
2076
+ # "currentTimestamp": "2020-11-09T06:53:59.893Z",
2077
+ # "currentQty": 0,
2078
+ # "currentCost": 0,
2079
+ # "currentComm": 0,
2080
+ # "realisedCost": 0,
2081
+ # "unrealisedCost": 0,
2082
+ # "grossOpenCost": 0,
2083
+ # "grossOpenPremium": 0,
2084
+ # "grossExecCost": 0,
2085
+ # "isOpen": True,
2086
+ # "markPrice": 0,
2087
+ # "markValue": 0,
2088
+ # "riskValue": 0,
2089
+ # "homeNotional": 0,
2090
+ # "foreignNotional": 0,
2091
+ # "posState": "string",
2092
+ # "posCost": 0,
2093
+ # "posCost2": 0,
2094
+ # "posCross": 0,
2095
+ # "posInit": 0,
2096
+ # "posComm": 0,
2097
+ # "posLoss": 0,
2098
+ # "posMargin": 0,
2099
+ # "posMaint": 0,
2100
+ # "posAllowance": 0,
2101
+ # "taxableMargin": 0,
2102
+ # "initMargin": 0,
2103
+ # "maintMargin": 0,
2104
+ # "sessionMargin": 0,
2105
+ # "targetExcessMargin": 0,
2106
+ # "varMargin": 0,
2107
+ # "realisedGrossPnl": 0,
2108
+ # "realisedTax": 0,
2109
+ # "realisedPnl": 0,
2110
+ # "unrealisedGrossPnl": 0,
2111
+ # "longBankrupt": 0,
2112
+ # "shortBankrupt": 0,
2113
+ # "taxBase": 0,
2114
+ # "indicativeTaxRate": 0,
2115
+ # "indicativeTax": 0,
2116
+ # "unrealisedTax": 0,
2117
+ # "unrealisedPnl": 0,
2118
+ # "unrealisedPnlPcnt": 0,
2119
+ # "unrealisedRoePcnt": 0,
2120
+ # "simpleQty": 0,
2121
+ # "simpleCost": 0,
2122
+ # "simpleValue": 0,
2123
+ # "simplePnl": 0,
2124
+ # "simplePnlPcnt": 0,
2125
+ # "avgCostPrice": 0,
2126
+ # "avgEntryPrice": 0,
2127
+ # "breakEvenPrice": 0,
2128
+ # "marginCallPrice": 0,
2129
+ # "liquidationPrice": 0,
2130
+ # "bankruptPrice": 0,
2131
+ # "timestamp": "2020-11-09T06:53:59.894Z",
2132
+ # "lastPrice": 0,
2133
+ # "lastValue": 0
2134
+ # }
2135
+ # ]
2136
+ #
2137
+ results = self.parse_positions(response, symbols)
2138
+ return self.filter_by_array_positions(results, 'symbol', symbols, False)
2139
+
2140
+ def parse_position(self, position: dict, market: Market = None):
2141
+ #
2142
+ # {
2143
+ # "account": 9371654,
2144
+ # "symbol": "ETHUSDT",
2145
+ # "currency": "USDt",
2146
+ # "underlying": "ETH",
2147
+ # "quoteCurrency": "USDT",
2148
+ # "commission": 0.00075,
2149
+ # "initMarginReq": 0.3333333333333333,
2150
+ # "maintMarginReq": 0.01,
2151
+ # "riskLimit": 1000000000000,
2152
+ # "leverage": 3,
2153
+ # "crossMargin": False,
2154
+ # "deleveragePercentile": 1,
2155
+ # "rebalancedPnl": 0,
2156
+ # "prevRealisedPnl": 0,
2157
+ # "prevUnrealisedPnl": 0,
2158
+ # "prevClosePrice": 2053.738,
2159
+ # "openingTimestamp": "2022-05-21T04:00:00.000Z",
2160
+ # "openingQty": 0,
2161
+ # "openingCost": 0,
2162
+ # "openingComm": 0,
2163
+ # "openOrderBuyQty": 0,
2164
+ # "openOrderBuyCost": 0,
2165
+ # "openOrderBuyPremium": 0,
2166
+ # "openOrderSellQty": 0,
2167
+ # "openOrderSellCost": 0,
2168
+ # "openOrderSellPremium": 0,
2169
+ # "execBuyQty": 2000,
2170
+ # "execBuyCost": 39260000,
2171
+ # "execSellQty": 0,
2172
+ # "execSellCost": 0,
2173
+ # "execQty": 2000,
2174
+ # "execCost": 39260000,
2175
+ # "execComm": 26500,
2176
+ # "currentTimestamp": "2022-05-21T04:35:16.397Z",
2177
+ # "currentQty": 2000,
2178
+ # "currentCost": 39260000,
2179
+ # "currentComm": 26500,
2180
+ # "realisedCost": 0,
2181
+ # "unrealisedCost": 39260000,
2182
+ # "grossOpenCost": 0,
2183
+ # "grossOpenPremium": 0,
2184
+ # "grossExecCost": 39260000,
2185
+ # "isOpen": True,
2186
+ # "markPrice": 1964.195,
2187
+ # "markValue": 39283900,
2188
+ # "riskValue": 39283900,
2189
+ # "homeNotional": 0.02,
2190
+ # "foreignNotional": -39.2839,
2191
+ # "posState": "",
2192
+ # "posCost": 39260000,
2193
+ # "posCost2": 39260000,
2194
+ # "posCross": 0,
2195
+ # "posInit": 13086667,
2196
+ # "posComm": 39261,
2197
+ # "posLoss": 0,
2198
+ # "posMargin": 13125928,
2199
+ # "posMaint": 435787,
2200
+ # "posAllowance": 0,
2201
+ # "taxableMargin": 0,
2202
+ # "initMargin": 0,
2203
+ # "maintMargin": 13149828,
2204
+ # "sessionMargin": 0,
2205
+ # "targetExcessMargin": 0,
2206
+ # "varMargin": 0,
2207
+ # "realisedGrossPnl": 0,
2208
+ # "realisedTax": 0,
2209
+ # "realisedPnl": -26500,
2210
+ # "unrealisedGrossPnl": 23900,
2211
+ # "longBankrupt": 0,
2212
+ # "shortBankrupt": 0,
2213
+ # "taxBase": 0,
2214
+ # "indicativeTaxRate": null,
2215
+ # "indicativeTax": 0,
2216
+ # "unrealisedTax": 0,
2217
+ # "unrealisedPnl": 23900,
2218
+ # "unrealisedPnlPcnt": 0.0006,
2219
+ # "unrealisedRoePcnt": 0.0018,
2220
+ # "simpleQty": null,
2221
+ # "simpleCost": null,
2222
+ # "simpleValue": null,
2223
+ # "simplePnl": null,
2224
+ # "simplePnlPcnt": null,
2225
+ # "avgCostPrice": 1963,
2226
+ # "avgEntryPrice": 1963,
2227
+ # "breakEvenPrice": 1964.35,
2228
+ # "marginCallPrice": 1328.5,
2229
+ # "liquidationPrice": 1328.5,
2230
+ # "bankruptPrice": 1308.7,
2231
+ # "timestamp": "2022-05-21T04:35:16.397Z",
2232
+ # "lastPrice": 1964.195,
2233
+ # "lastValue": 39283900
2234
+ # }
2235
+ #
2236
+ market = self.safe_market(self.safe_string(position, 'symbol'), market)
2237
+ symbol = market['symbol']
2238
+ datetime = self.safe_string(position, 'timestamp')
2239
+ crossMargin = self.safe_value(position, 'crossMargin')
2240
+ marginMode = 'cross' if (crossMargin is True) else 'isolated'
2241
+ notionalString = Precise.string_abs(self.safe_string_2(position, 'foreignNotional', 'homeNotional'))
2242
+ settleCurrencyCode = self.safe_string(market, 'settle')
2243
+ maintenanceMargin = self.convert_to_real_amount(settleCurrencyCode, self.safe_string(position, 'maintMargin'))
2244
+ unrealisedPnl = self.convert_to_real_amount(settleCurrencyCode, self.safe_string(position, 'unrealisedPnl'))
2245
+ contracts = self.parse_number(Precise.string_abs(self.safe_string(position, 'currentQty')))
2246
+ contractSize = self.safe_number(market, 'contractSize')
2247
+ side = None
2248
+ homeNotional = self.safe_string(position, 'homeNotional')
2249
+ if homeNotional is not None:
2250
+ if homeNotional[0] == '-':
2251
+ side = 'short'
2252
+ else:
2253
+ side = 'long'
2254
+ return self.safe_position({
2255
+ 'info': position,
2256
+ 'id': self.safe_string(position, 'account'),
2257
+ 'symbol': symbol,
2258
+ 'timestamp': self.parse8601(datetime),
2259
+ 'datetime': datetime,
2260
+ 'lastUpdateTimestamp': None,
2261
+ 'hedged': None,
2262
+ 'side': side,
2263
+ 'contracts': contracts,
2264
+ 'contractSize': contractSize,
2265
+ 'entryPrice': self.safe_number(position, 'avgEntryPrice'),
2266
+ 'markPrice': self.safe_number(position, 'markPrice'),
2267
+ 'lastPrice': None,
2268
+ 'notional': self.parse_number(notionalString),
2269
+ 'leverage': self.safe_number(position, 'leverage'),
2270
+ 'collateral': None,
2271
+ 'initialMargin': self.safe_number(position, 'initMargin'),
2272
+ 'initialMarginPercentage': self.safe_number(position, 'initMarginReq'),
2273
+ 'maintenanceMargin': maintenanceMargin,
2274
+ 'maintenanceMarginPercentage': self.safe_number(position, 'maintMarginReq'),
2275
+ 'unrealizedPnl': unrealisedPnl,
2276
+ 'liquidationPrice': self.safe_number(position, 'liquidationPrice'),
2277
+ 'marginMode': marginMode,
2278
+ 'marginRatio': None,
2279
+ 'percentage': self.safe_number(position, 'unrealisedPnlPcnt'),
2280
+ 'stopLossPrice': None,
2281
+ 'takeProfitPrice': None,
2282
+ })
2283
+
2284
+ def withdraw(self, code: str, amount: float, address: str, tag=None, params={}):
2285
+ """
2286
+ make a withdrawal
2287
+ :see: https://www.bitmex.com/api/explorer/#not /User/User_requestWithdrawal
2288
+ :param str code: unified currency code
2289
+ :param float amount: the amount to withdraw
2290
+ :param str address: the address to withdraw to
2291
+ :param str tag:
2292
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2293
+ :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
2294
+ """
2295
+ tag, params = self.handle_withdraw_tag_and_params(tag, params)
2296
+ self.check_address(address)
2297
+ self.load_markets()
2298
+ currency = self.currency(code)
2299
+ qty = self.convert_from_real_amount(code, amount)
2300
+ networkCode = None
2301
+ networkCode, params = self.handle_network_code_and_params(params)
2302
+ request: dict = {
2303
+ 'currency': currency['id'],
2304
+ 'amount': qty,
2305
+ 'address': address,
2306
+ 'network': self.network_code_to_id(networkCode, currency['code']),
2307
+ # 'otpToken': '123456', # requires if two-factor auth(OTP) is enabled
2308
+ # 'fee': 0.001, # bitcoin network fee
2309
+ }
2310
+ response = self.privatePostUserRequestWithdrawal(self.extend(request, params))
2311
+ #
2312
+ # {
2313
+ # "transactID": "3aece414-bb29-76c8-6c6d-16a477a51a1e",
2314
+ # "account": 1403035,
2315
+ # "currency": "USDt",
2316
+ # "network": "tron",
2317
+ # "transactType": "Withdrawal",
2318
+ # "amount": -11000000,
2319
+ # "fee": 1000000,
2320
+ # "transactStatus": "Pending",
2321
+ # "address": "TAf5JxcAQQsC2Nm2zu21XE2iDtnisxPo1x",
2322
+ # "tx": "",
2323
+ # "text": "",
2324
+ # "transactTime": "2022-12-16T07:37:06.500Z",
2325
+ # "timestamp": "2022-12-16T07:37:06.500Z",
2326
+ # }
2327
+ #
2328
+ return self.parse_transaction(response, currency)
2329
+
2330
+ def fetch_funding_rates(self, symbols: Strings = None, params={}):
2331
+ """
2332
+ fetch the funding rate for multiple markets
2333
+ :see: https://www.bitmex.com/api/explorer/#not /Instrument/Instrument_getActiveAndIndices
2334
+ :param str[]|None symbols: list of unified market symbols
2335
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2336
+ :returns dict: a dictionary of `funding rates structures <https://docs.ccxt.com/#/?id=funding-rates-structure>`, indexe by market symbols
2337
+ """
2338
+ self.load_markets()
2339
+ response = self.publicGetInstrumentActiveAndIndices(params)
2340
+ # same response "fetchMarkets"
2341
+ filteredResponse = []
2342
+ for i in range(0, len(response)):
2343
+ item = response[i]
2344
+ marketId = self.safe_string(item, 'symbol')
2345
+ market = self.safe_market(marketId)
2346
+ swap = self.safe_bool(market, 'swap', False)
2347
+ if swap:
2348
+ filteredResponse.append(item)
2349
+ symbols = self.market_symbols(symbols)
2350
+ result = self.parse_funding_rates(filteredResponse)
2351
+ return self.filter_by_array(result, 'symbol', symbols)
2352
+
2353
+ def parse_funding_rate(self, contract, market: Market = None):
2354
+ # see response sample under "fetchMarkets" because same endpoint is being used here
2355
+ datetime = self.safe_string(contract, 'timestamp')
2356
+ marketId = self.safe_string(contract, 'symbol')
2357
+ fundingDatetime = self.safe_string(contract, 'fundingTimestamp')
2358
+ return {
2359
+ 'info': contract,
2360
+ 'symbol': self.safe_symbol(marketId, market),
2361
+ 'markPrice': self.safe_number(contract, 'markPrice'),
2362
+ 'indexPrice': None,
2363
+ 'interestRate': None,
2364
+ 'estimatedSettlePrice': self.safe_number(contract, 'indicativeSettlePrice'),
2365
+ 'timestamp': self.parse8601(datetime),
2366
+ 'datetime': datetime,
2367
+ 'fundingRate': self.safe_number(contract, 'fundingRate'),
2368
+ 'fundingTimestamp': self.iso8601(fundingDatetime),
2369
+ 'fundingDatetime': fundingDatetime,
2370
+ 'nextFundingRate': self.safe_number(contract, 'indicativeFundingRate'),
2371
+ 'nextFundingTimestamp': None,
2372
+ 'nextFundingDatetime': None,
2373
+ 'previousFundingRate': None,
2374
+ 'previousFundingTimestamp': None,
2375
+ 'previousFundingDatetime': None,
2376
+ }
2377
+
2378
+ def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
2379
+ """
2380
+ Fetches the history of funding rates
2381
+ :see: https://www.bitmex.com/api/explorer/#not /Funding/Funding_get
2382
+ :param str symbol: unified symbol of the market to fetch the funding rate history for
2383
+ :param int [since]: timestamp in ms of the earliest funding rate to fetch
2384
+ :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
2385
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2386
+ :param int [params.until]: timestamp in ms for ending date filter
2387
+ :param bool [params.reverse]: if True, will sort results newest first
2388
+ :param int [params.start]: starting point for results
2389
+ :param str [params.columns]: array of column names to fetch in info, if omitted, will return all columns
2390
+ :param str [params.filter]: generic table filter, send json key/value pairs, such as {"key": "value"}, you can key on individual fields, and do more advanced querying on timestamps, see the `timestamp docs <https://www.bitmex.com/app/restAPI#Timestamp-Filters>` for more details
2391
+ :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
2392
+ """
2393
+ self.load_markets()
2394
+ request: dict = {}
2395
+ market = None
2396
+ if symbol in self.currencies:
2397
+ code = self.currency(symbol)
2398
+ request['symbol'] = code['id']
2399
+ elif symbol is not None:
2400
+ splitSymbol = symbol.split(':')
2401
+ splitSymbolLength = len(splitSymbol)
2402
+ timeframes = ['nearest', 'daily', 'weekly', 'monthly', 'quarterly', 'biquarterly', 'perpetual']
2403
+ if (splitSymbolLength > 1) and self.in_array(splitSymbol[1], timeframes):
2404
+ code = self.currency(splitSymbol[0])
2405
+ symbol = code['id'] + ':' + splitSymbol[1]
2406
+ request['symbol'] = symbol
2407
+ else:
2408
+ market = self.market(symbol)
2409
+ request['symbol'] = market['id']
2410
+ if since is not None:
2411
+ request['startTime'] = self.iso8601(since)
2412
+ if limit is not None:
2413
+ request['count'] = limit
2414
+ until = self.safe_integer(params, 'until')
2415
+ params = self.omit(params, ['until'])
2416
+ if until is not None:
2417
+ request['endTime'] = self.iso8601(until)
2418
+ if (since is None) and (until is None):
2419
+ request['reverse'] = True
2420
+ response = self.publicGetFunding(self.extend(request, params))
2421
+ #
2422
+ # [
2423
+ # {
2424
+ # "timestamp": "2016-05-07T12:00:00.000Z",
2425
+ # "symbol": "ETHXBT",
2426
+ # "fundingInterval": "2000-01-02T00:00:00.000Z",
2427
+ # "fundingRate": 0.0010890000000000001,
2428
+ # "fundingRateDaily": 0.0010890000000000001
2429
+ # }
2430
+ # ]
2431
+ #
2432
+ return self.parse_funding_rate_histories(response, market, since, limit)
2433
+
2434
+ def parse_funding_rate_history(self, info, market: Market = None):
2435
+ #
2436
+ # {
2437
+ # "timestamp": "2016-05-07T12:00:00.000Z",
2438
+ # "symbol": "ETHXBT",
2439
+ # "fundingInterval": "2000-01-02T00:00:00.000Z",
2440
+ # "fundingRate": 0.0010890000000000001,
2441
+ # "fundingRateDaily": 0.0010890000000000001
2442
+ # }
2443
+ #
2444
+ marketId = self.safe_string(info, 'symbol')
2445
+ datetime = self.safe_string(info, 'timestamp')
2446
+ return {
2447
+ 'info': info,
2448
+ 'symbol': self.safe_symbol(marketId, market),
2449
+ 'fundingRate': self.safe_number(info, 'fundingRate'),
2450
+ 'timestamp': self.parse8601(datetime),
2451
+ 'datetime': datetime,
2452
+ }
2453
+
2454
+ def set_leverage(self, leverage: Int, symbol: Str = None, params={}):
2455
+ """
2456
+ set the level of leverage for a market
2457
+ :see: https://www.bitmex.com/api/explorer/#not /Position/Position_updateLeverage
2458
+ :param float leverage: the rate of leverage
2459
+ :param str symbol: unified market symbol
2460
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2461
+ :returns dict: response from the exchange
2462
+ """
2463
+ if symbol is None:
2464
+ raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
2465
+ if (leverage < 0.01) or (leverage > 100):
2466
+ raise BadRequest(self.id + ' leverage should be between 0.01 and 100')
2467
+ self.load_markets()
2468
+ market = self.market(symbol)
2469
+ if market['type'] != 'swap' and market['type'] != 'future':
2470
+ raise BadSymbol(self.id + ' setLeverage() supports future and swap contracts only')
2471
+ request: dict = {
2472
+ 'symbol': market['id'],
2473
+ 'leverage': leverage,
2474
+ }
2475
+ return self.privatePostPositionLeverage(self.extend(request, params))
2476
+
2477
+ def set_margin_mode(self, marginMode: str, symbol: Str = None, params={}):
2478
+ """
2479
+ set margin mode to 'cross' or 'isolated'
2480
+ :see: https://www.bitmex.com/api/explorer/#not /Position/Position_isolateMargin
2481
+ :param str marginMode: 'cross' or 'isolated'
2482
+ :param str symbol: unified market symbol
2483
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2484
+ :returns dict: response from the exchange
2485
+ """
2486
+ if symbol is None:
2487
+ raise ArgumentsRequired(self.id + ' setMarginMode() requires a symbol argument')
2488
+ marginMode = marginMode.lower()
2489
+ if marginMode != 'isolated' and marginMode != 'cross':
2490
+ raise BadRequest(self.id + ' setMarginMode() marginMode argument should be isolated or cross')
2491
+ self.load_markets()
2492
+ market = self.market(symbol)
2493
+ if (market['type'] != 'swap') and (market['type'] != 'future'):
2494
+ raise BadSymbol(self.id + ' setMarginMode() supports swap and future contracts only')
2495
+ enabled = False if (marginMode == 'cross') else True
2496
+ request: dict = {
2497
+ 'symbol': market['id'],
2498
+ 'enabled': enabled,
2499
+ }
2500
+ return self.privatePostPositionIsolate(self.extend(request, params))
2501
+
2502
+ def fetch_deposit_address(self, code: str, params={}):
2503
+ """
2504
+ fetch the deposit address for a currency associated with self account
2505
+ :see: https://www.bitmex.com/api/explorer/#not /User/User_getDepositAddress
2506
+ :param str code: unified currency code
2507
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2508
+ :param str [params.network]: deposit chain, can view all chains via self.publicGetWalletAssets, default is eth, unless the currency has a default chain within self.options['networks']
2509
+ :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
2510
+ """
2511
+ self.load_markets()
2512
+ networkCode = None
2513
+ networkCode, params = self.handle_network_code_and_params(params)
2514
+ if networkCode is None:
2515
+ raise ArgumentsRequired(self.id + ' fetchDepositAddress requires params["network"]')
2516
+ currency = self.currency(code)
2517
+ params = self.omit(params, 'network')
2518
+ request: dict = {
2519
+ 'currency': currency['id'],
2520
+ 'network': self.network_code_to_id(networkCode, currency['code']),
2521
+ }
2522
+ response = self.privateGetUserDepositAddress(self.extend(request, params))
2523
+ #
2524
+ # '"bc1qmex3puyrzn2gduqcnlu70c2uscpyaa9nm2l2j9le2lt2wkgmw33sy7ndjg"'
2525
+ #
2526
+ return {
2527
+ 'currency': code,
2528
+ 'address': response.replace('"', '').replace('"', ''), # Done twice because some languages only replace the first instance
2529
+ 'tag': None,
2530
+ 'network': networkCode,
2531
+ 'info': response,
2532
+ }
2533
+
2534
+ def parse_deposit_withdraw_fee(self, fee, currency: Currency = None):
2535
+ #
2536
+ # {
2537
+ # "asset": "XBT",
2538
+ # "currency": "XBt",
2539
+ # "majorCurrency": "XBT",
2540
+ # "name": "Bitcoin",
2541
+ # "currencyType": "Crypto",
2542
+ # "scale": "8",
2543
+ # "enabled": True,
2544
+ # "isMarginCurrency": True,
2545
+ # "minDepositAmount": "10000",
2546
+ # "minWithdrawalAmount": "1000",
2547
+ # "maxWithdrawalAmount": "100000000000000",
2548
+ # "networks": [
2549
+ # {
2550
+ # "asset": "btc",
2551
+ # "tokenAddress": '',
2552
+ # "depositEnabled": True,
2553
+ # "withdrawalEnabled": True,
2554
+ # "withdrawalFee": "20000",
2555
+ # "minFee": "20000",
2556
+ # "maxFee": "10000000"
2557
+ # }
2558
+ # ]
2559
+ # }
2560
+ #
2561
+ networks = self.safe_value(fee, 'networks', [])
2562
+ networksLength = len(networks)
2563
+ result: dict = {
2564
+ 'info': fee,
2565
+ 'withdraw': {
2566
+ 'fee': None,
2567
+ 'percentage': None,
2568
+ },
2569
+ 'deposit': {
2570
+ 'fee': None,
2571
+ 'percentage': None,
2572
+ },
2573
+ 'networks': {},
2574
+ }
2575
+ if networksLength != 0:
2576
+ scale = self.safe_string(fee, 'scale')
2577
+ precision = self.parse_precision(scale)
2578
+ for i in range(0, networksLength):
2579
+ network = networks[i]
2580
+ networkId = self.safe_string(network, 'asset')
2581
+ currencyCode = self.safe_string(currency, 'code')
2582
+ networkCode = self.network_id_to_code(networkId, currencyCode)
2583
+ withdrawalFeeId = self.safe_string(network, 'withdrawalFee')
2584
+ withdrawalFee = self.parse_number(Precise.string_mul(withdrawalFeeId, precision))
2585
+ result['networks'][networkCode] = {
2586
+ 'deposit': {'fee': None, 'percentage': None},
2587
+ 'withdraw': {'fee': withdrawalFee, 'percentage': False},
2588
+ }
2589
+ if networksLength == 1:
2590
+ result['withdraw']['fee'] = withdrawalFee
2591
+ result['withdraw']['percentage'] = False
2592
+ return result
2593
+
2594
+ def fetch_deposit_withdraw_fees(self, codes: Strings = None, params={}):
2595
+ """
2596
+ fetch deposit and withdraw fees
2597
+ :see: https://www.bitmex.com/api/explorer/#not /Wallet/Wallet_getAssetsConfig
2598
+ :param str[]|None codes: list of unified currency codes
2599
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2600
+ :returns dict: a list of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>`
2601
+ """
2602
+ self.load_markets()
2603
+ assets = self.publicGetWalletAssets(params)
2604
+ #
2605
+ # [
2606
+ # {
2607
+ # "asset": "XBT",
2608
+ # "currency": "XBt",
2609
+ # "majorCurrency": "XBT",
2610
+ # "name": "Bitcoin",
2611
+ # "currencyType": "Crypto",
2612
+ # "scale": "8",
2613
+ # "enabled": True,
2614
+ # "isMarginCurrency": True,
2615
+ # "minDepositAmount": "10000",
2616
+ # "minWithdrawalAmount": "1000",
2617
+ # "maxWithdrawalAmount": "100000000000000",
2618
+ # "networks": [
2619
+ # {
2620
+ # "asset": "btc",
2621
+ # "tokenAddress": '',
2622
+ # "depositEnabled": True,
2623
+ # "withdrawalEnabled": True,
2624
+ # "withdrawalFee": "20000",
2625
+ # "minFee": "20000",
2626
+ # "maxFee": "10000000"
2627
+ # }
2628
+ # ]
2629
+ # },
2630
+ # ...
2631
+ # ]
2632
+ #
2633
+ return self.parse_deposit_withdraw_fees(assets, codes, 'asset')
2634
+
2635
+ def calculate_rate_limiter_cost(self, api, method, path, params, config={}):
2636
+ isAuthenticated = self.check_required_credentials(False)
2637
+ cost = self.safe_value(config, 'cost', 1)
2638
+ if cost != 1: # trading endpoints
2639
+ if isAuthenticated:
2640
+ return cost
2641
+ else:
2642
+ return 20
2643
+ return cost
2644
+
2645
+ def fetch_liquidations(self, symbol: str, since: Int = None, limit: Int = None, params={}):
2646
+ """
2647
+ retrieves the public liquidations of a trading pair
2648
+ :see: https://www.bitmex.com/api/explorer/#not /Liquidation/Liquidation_get
2649
+ :param str symbol: unified CCXT market symbol
2650
+ :param int [since]: the earliest time in ms to fetch liquidations for
2651
+ :param int [limit]: the maximum number of liquidation structures to retrieve
2652
+ :param dict [params]: exchange specific parameters for the bitmex api endpoint
2653
+ :param int [params.until]: timestamp in ms of the latest liquidation
2654
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
2655
+ :returns dict: an array of `liquidation structures <https://docs.ccxt.com/#/?id=liquidation-structure>`
2656
+ """
2657
+ self.load_markets()
2658
+ paginate = False
2659
+ paginate, params = self.handle_option_and_params(params, 'fetchLiquidations', 'paginate')
2660
+ if paginate:
2661
+ return self.fetch_paginated_call_dynamic('fetchLiquidations', symbol, since, limit, params)
2662
+ market = self.market(symbol)
2663
+ request: dict = {
2664
+ 'symbol': market['id'],
2665
+ }
2666
+ if since is not None:
2667
+ request['startTime'] = since
2668
+ if limit is not None:
2669
+ request['count'] = limit
2670
+ request, params = self.handle_until_option('endTime', request, params)
2671
+ response = self.publicGetLiquidation(self.extend(request, params))
2672
+ #
2673
+ # [
2674
+ # {
2675
+ # "orderID": "string",
2676
+ # "symbol": "string",
2677
+ # "side": "string",
2678
+ # "price": 0,
2679
+ # "leavesQty": 0
2680
+ # }
2681
+ # ]
2682
+ #
2683
+ return self.parse_liquidations(response, market, since, limit)
2684
+
2685
+ def parse_liquidation(self, liquidation, market: Market = None):
2686
+ #
2687
+ # {
2688
+ # "orderID": "string",
2689
+ # "symbol": "string",
2690
+ # "side": "string",
2691
+ # "price": 0,
2692
+ # "leavesQty": 0
2693
+ # }
2694
+ #
2695
+ marketId = self.safe_string(liquidation, 'symbol')
2696
+ return self.safe_liquidation({
2697
+ 'info': liquidation,
2698
+ 'symbol': self.safe_symbol(marketId, market),
2699
+ 'contracts': None,
2700
+ 'contractSize': self.safe_number(market, 'contractSize'),
2701
+ 'price': self.safe_number(liquidation, 'price'),
2702
+ 'baseValue': None,
2703
+ 'quoteValue': None,
2704
+ 'timestamp': None,
2705
+ 'datetime': None,
2706
+ })
2707
+
2708
+ def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
2709
+ if response is None:
2710
+ return None
2711
+ if code == 429:
2712
+ raise DDoSProtection(self.id + ' ' + body)
2713
+ if code >= 400:
2714
+ error = self.safe_value(response, 'error', {})
2715
+ message = self.safe_string(error, 'message')
2716
+ feedback = self.id + ' ' + body
2717
+ self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
2718
+ self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
2719
+ if code == 400:
2720
+ raise BadRequest(feedback)
2721
+ raise ExchangeError(feedback) # unknown message
2722
+ return None
2723
+
2724
+ def nonce(self):
2725
+ return self.milliseconds()
2726
+
2727
+ def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
2728
+ query = '/api/' + self.version + '/' + path
2729
+ if method == 'GET':
2730
+ if params:
2731
+ query += '?' + self.urlencode(params)
2732
+ else:
2733
+ format = self.safe_string(params, '_format')
2734
+ if format is not None:
2735
+ query += '?' + self.urlencode({'_format': format})
2736
+ params = self.omit(params, '_format')
2737
+ url = self.urls['api'][api] + query
2738
+ isAuthenticated = self.check_required_credentials(False)
2739
+ if api == 'private' or (api == 'public' and isAuthenticated):
2740
+ self.check_required_credentials()
2741
+ auth = method + query
2742
+ expires = self.safe_integer(self.options, 'api-expires')
2743
+ headers = {
2744
+ 'Content-Type': 'application/json',
2745
+ 'api-key': self.apiKey,
2746
+ }
2747
+ expires = self.sum(self.seconds(), expires)
2748
+ stringExpires = str(expires)
2749
+ auth += stringExpires
2750
+ headers['api-expires'] = stringExpires
2751
+ if method == 'POST' or method == 'PUT' or method == 'DELETE':
2752
+ if params:
2753
+ body = self.json(params)
2754
+ auth += body
2755
+ headers['api-signature'] = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256)
2756
+ return {'url': url, 'method': method, 'body': body, 'headers': headers}