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