hyperliquid 0.4.66__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 (274) hide show
  1. hyperliquid/__init__.py +7 -0
  2. hyperliquid/ccxt/__init__.py +101 -0
  3. hyperliquid/ccxt/abstract/hyperliquid.py +6 -0
  4. hyperliquid/ccxt/async_support/__init__.py +80 -0
  5. hyperliquid/ccxt/async_support/base/__init__.py +1 -0
  6. hyperliquid/ccxt/async_support/base/exchange.py +2095 -0
  7. hyperliquid/ccxt/async_support/base/throttler.py +50 -0
  8. hyperliquid/ccxt/async_support/base/ws/__init__.py +38 -0
  9. hyperliquid/ccxt/async_support/base/ws/aiohttp_client.py +147 -0
  10. hyperliquid/ccxt/async_support/base/ws/cache.py +213 -0
  11. hyperliquid/ccxt/async_support/base/ws/client.py +214 -0
  12. hyperliquid/ccxt/async_support/base/ws/fast_client.py +97 -0
  13. hyperliquid/ccxt/async_support/base/ws/functions.py +59 -0
  14. hyperliquid/ccxt/async_support/base/ws/future.py +69 -0
  15. hyperliquid/ccxt/async_support/base/ws/order_book.py +78 -0
  16. hyperliquid/ccxt/async_support/base/ws/order_book_side.py +174 -0
  17. hyperliquid/ccxt/async_support/hyperliquid.py +3446 -0
  18. hyperliquid/ccxt/base/__init__.py +27 -0
  19. hyperliquid/ccxt/base/decimal_to_precision.py +174 -0
  20. hyperliquid/ccxt/base/errors.py +267 -0
  21. hyperliquid/ccxt/base/exchange.py +6767 -0
  22. hyperliquid/ccxt/base/precise.py +297 -0
  23. hyperliquid/ccxt/base/types.py +577 -0
  24. hyperliquid/ccxt/hyperliquid.py +3445 -0
  25. hyperliquid/ccxt/pro/__init__.py +21 -0
  26. hyperliquid/ccxt/pro/hyperliquid.py +997 -0
  27. hyperliquid/ccxt/static_dependencies/__init__.py +1 -0
  28. hyperliquid/ccxt/static_dependencies/ecdsa/__init__.py +14 -0
  29. hyperliquid/ccxt/static_dependencies/ecdsa/_version.py +520 -0
  30. hyperliquid/ccxt/static_dependencies/ecdsa/curves.py +56 -0
  31. hyperliquid/ccxt/static_dependencies/ecdsa/der.py +221 -0
  32. hyperliquid/ccxt/static_dependencies/ecdsa/ecdsa.py +310 -0
  33. hyperliquid/ccxt/static_dependencies/ecdsa/ellipticcurve.py +197 -0
  34. hyperliquid/ccxt/static_dependencies/ecdsa/keys.py +332 -0
  35. hyperliquid/ccxt/static_dependencies/ecdsa/numbertheory.py +531 -0
  36. hyperliquid/ccxt/static_dependencies/ecdsa/rfc6979.py +100 -0
  37. hyperliquid/ccxt/static_dependencies/ecdsa/util.py +266 -0
  38. hyperliquid/ccxt/static_dependencies/ethereum/__init__.py +7 -0
  39. hyperliquid/ccxt/static_dependencies/ethereum/abi/__init__.py +16 -0
  40. hyperliquid/ccxt/static_dependencies/ethereum/abi/abi.py +19 -0
  41. hyperliquid/ccxt/static_dependencies/ethereum/abi/base.py +152 -0
  42. hyperliquid/ccxt/static_dependencies/ethereum/abi/codec.py +217 -0
  43. hyperliquid/ccxt/static_dependencies/ethereum/abi/constants.py +3 -0
  44. hyperliquid/ccxt/static_dependencies/ethereum/abi/decoding.py +565 -0
  45. hyperliquid/ccxt/static_dependencies/ethereum/abi/encoding.py +720 -0
  46. hyperliquid/ccxt/static_dependencies/ethereum/abi/exceptions.py +139 -0
  47. hyperliquid/ccxt/static_dependencies/ethereum/abi/grammar.py +443 -0
  48. hyperliquid/ccxt/static_dependencies/ethereum/abi/packed.py +13 -0
  49. hyperliquid/ccxt/static_dependencies/ethereum/abi/py.typed +0 -0
  50. hyperliquid/ccxt/static_dependencies/ethereum/abi/registry.py +643 -0
  51. hyperliquid/ccxt/static_dependencies/ethereum/abi/tools/__init__.py +3 -0
  52. hyperliquid/ccxt/static_dependencies/ethereum/abi/tools/_strategies.py +230 -0
  53. hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/__init__.py +0 -0
  54. hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/numeric.py +83 -0
  55. hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/padding.py +27 -0
  56. hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/string.py +19 -0
  57. hyperliquid/ccxt/static_dependencies/ethereum/account/__init__.py +3 -0
  58. hyperliquid/ccxt/static_dependencies/ethereum/account/encode_typed_data/__init__.py +4 -0
  59. hyperliquid/ccxt/static_dependencies/ethereum/account/encode_typed_data/encoding_and_hashing.py +239 -0
  60. hyperliquid/ccxt/static_dependencies/ethereum/account/encode_typed_data/helpers.py +40 -0
  61. hyperliquid/ccxt/static_dependencies/ethereum/account/messages.py +263 -0
  62. hyperliquid/ccxt/static_dependencies/ethereum/account/py.typed +0 -0
  63. hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/__init__.py +5 -0
  64. hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/_utils.py +54 -0
  65. hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/main.py +65 -0
  66. hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/py.typed +0 -0
  67. hyperliquid/ccxt/static_dependencies/ethereum/typing/__init__.py +63 -0
  68. hyperliquid/ccxt/static_dependencies/ethereum/typing/abi.py +6 -0
  69. hyperliquid/ccxt/static_dependencies/ethereum/typing/bls.py +7 -0
  70. hyperliquid/ccxt/static_dependencies/ethereum/typing/discovery.py +5 -0
  71. hyperliquid/ccxt/static_dependencies/ethereum/typing/encoding.py +7 -0
  72. hyperliquid/ccxt/static_dependencies/ethereum/typing/enums.py +17 -0
  73. hyperliquid/ccxt/static_dependencies/ethereum/typing/ethpm.py +9 -0
  74. hyperliquid/ccxt/static_dependencies/ethereum/typing/evm.py +20 -0
  75. hyperliquid/ccxt/static_dependencies/ethereum/typing/networks.py +1122 -0
  76. hyperliquid/ccxt/static_dependencies/ethereum/typing/py.typed +0 -0
  77. hyperliquid/ccxt/static_dependencies/ethereum/utils/__init__.py +115 -0
  78. hyperliquid/ccxt/static_dependencies/ethereum/utils/abi.py +72 -0
  79. hyperliquid/ccxt/static_dependencies/ethereum/utils/address.py +171 -0
  80. hyperliquid/ccxt/static_dependencies/ethereum/utils/applicators.py +151 -0
  81. hyperliquid/ccxt/static_dependencies/ethereum/utils/conversions.py +190 -0
  82. hyperliquid/ccxt/static_dependencies/ethereum/utils/currency.py +107 -0
  83. hyperliquid/ccxt/static_dependencies/ethereum/utils/curried/__init__.py +269 -0
  84. hyperliquid/ccxt/static_dependencies/ethereum/utils/debug.py +20 -0
  85. hyperliquid/ccxt/static_dependencies/ethereum/utils/decorators.py +132 -0
  86. hyperliquid/ccxt/static_dependencies/ethereum/utils/encoding.py +6 -0
  87. hyperliquid/ccxt/static_dependencies/ethereum/utils/exceptions.py +4 -0
  88. hyperliquid/ccxt/static_dependencies/ethereum/utils/functional.py +75 -0
  89. hyperliquid/ccxt/static_dependencies/ethereum/utils/hexadecimal.py +74 -0
  90. hyperliquid/ccxt/static_dependencies/ethereum/utils/humanize.py +188 -0
  91. hyperliquid/ccxt/static_dependencies/ethereum/utils/logging.py +159 -0
  92. hyperliquid/ccxt/static_dependencies/ethereum/utils/module_loading.py +31 -0
  93. hyperliquid/ccxt/static_dependencies/ethereum/utils/numeric.py +43 -0
  94. hyperliquid/ccxt/static_dependencies/ethereum/utils/py.typed +0 -0
  95. hyperliquid/ccxt/static_dependencies/ethereum/utils/toolz.py +76 -0
  96. hyperliquid/ccxt/static_dependencies/ethereum/utils/types.py +54 -0
  97. hyperliquid/ccxt/static_dependencies/ethereum/utils/typing/__init__.py +18 -0
  98. hyperliquid/ccxt/static_dependencies/ethereum/utils/typing/misc.py +14 -0
  99. hyperliquid/ccxt/static_dependencies/ethereum/utils/units.py +31 -0
  100. hyperliquid/ccxt/static_dependencies/keccak/__init__.py +3 -0
  101. hyperliquid/ccxt/static_dependencies/keccak/keccak.py +197 -0
  102. hyperliquid/ccxt/static_dependencies/lark/__init__.py +38 -0
  103. hyperliquid/ccxt/static_dependencies/lark/__pyinstaller/__init__.py +6 -0
  104. hyperliquid/ccxt/static_dependencies/lark/__pyinstaller/hook-lark.py +14 -0
  105. hyperliquid/ccxt/static_dependencies/lark/ast_utils.py +59 -0
  106. hyperliquid/ccxt/static_dependencies/lark/common.py +86 -0
  107. hyperliquid/ccxt/static_dependencies/lark/exceptions.py +292 -0
  108. hyperliquid/ccxt/static_dependencies/lark/grammar.py +130 -0
  109. hyperliquid/ccxt/static_dependencies/lark/grammars/__init__.py +0 -0
  110. hyperliquid/ccxt/static_dependencies/lark/indenter.py +143 -0
  111. hyperliquid/ccxt/static_dependencies/lark/lark.py +658 -0
  112. hyperliquid/ccxt/static_dependencies/lark/lexer.py +678 -0
  113. hyperliquid/ccxt/static_dependencies/lark/load_grammar.py +1428 -0
  114. hyperliquid/ccxt/static_dependencies/lark/parse_tree_builder.py +391 -0
  115. hyperliquid/ccxt/static_dependencies/lark/parser_frontends.py +257 -0
  116. hyperliquid/ccxt/static_dependencies/lark/parsers/__init__.py +0 -0
  117. hyperliquid/ccxt/static_dependencies/lark/parsers/cyk.py +340 -0
  118. hyperliquid/ccxt/static_dependencies/lark/parsers/earley.py +314 -0
  119. hyperliquid/ccxt/static_dependencies/lark/parsers/earley_common.py +42 -0
  120. hyperliquid/ccxt/static_dependencies/lark/parsers/earley_forest.py +801 -0
  121. hyperliquid/ccxt/static_dependencies/lark/parsers/grammar_analysis.py +203 -0
  122. hyperliquid/ccxt/static_dependencies/lark/parsers/lalr_analysis.py +332 -0
  123. hyperliquid/ccxt/static_dependencies/lark/parsers/lalr_interactive_parser.py +158 -0
  124. hyperliquid/ccxt/static_dependencies/lark/parsers/lalr_parser.py +122 -0
  125. hyperliquid/ccxt/static_dependencies/lark/parsers/lalr_parser_state.py +110 -0
  126. hyperliquid/ccxt/static_dependencies/lark/parsers/xearley.py +165 -0
  127. hyperliquid/ccxt/static_dependencies/lark/py.typed +0 -0
  128. hyperliquid/ccxt/static_dependencies/lark/reconstruct.py +107 -0
  129. hyperliquid/ccxt/static_dependencies/lark/tools/__init__.py +70 -0
  130. hyperliquid/ccxt/static_dependencies/lark/tools/nearley.py +202 -0
  131. hyperliquid/ccxt/static_dependencies/lark/tools/serialize.py +32 -0
  132. hyperliquid/ccxt/static_dependencies/lark/tools/standalone.py +196 -0
  133. hyperliquid/ccxt/static_dependencies/lark/tree.py +267 -0
  134. hyperliquid/ccxt/static_dependencies/lark/tree_matcher.py +186 -0
  135. hyperliquid/ccxt/static_dependencies/lark/tree_templates.py +180 -0
  136. hyperliquid/ccxt/static_dependencies/lark/utils.py +343 -0
  137. hyperliquid/ccxt/static_dependencies/lark/visitors.py +596 -0
  138. hyperliquid/ccxt/static_dependencies/marshmallow/__init__.py +81 -0
  139. hyperliquid/ccxt/static_dependencies/marshmallow/base.py +65 -0
  140. hyperliquid/ccxt/static_dependencies/marshmallow/class_registry.py +94 -0
  141. hyperliquid/ccxt/static_dependencies/marshmallow/decorators.py +231 -0
  142. hyperliquid/ccxt/static_dependencies/marshmallow/error_store.py +60 -0
  143. hyperliquid/ccxt/static_dependencies/marshmallow/exceptions.py +71 -0
  144. hyperliquid/ccxt/static_dependencies/marshmallow/fields.py +2114 -0
  145. hyperliquid/ccxt/static_dependencies/marshmallow/orderedset.py +89 -0
  146. hyperliquid/ccxt/static_dependencies/marshmallow/py.typed +0 -0
  147. hyperliquid/ccxt/static_dependencies/marshmallow/schema.py +1228 -0
  148. hyperliquid/ccxt/static_dependencies/marshmallow/types.py +12 -0
  149. hyperliquid/ccxt/static_dependencies/marshmallow/utils.py +378 -0
  150. hyperliquid/ccxt/static_dependencies/marshmallow/validate.py +678 -0
  151. hyperliquid/ccxt/static_dependencies/marshmallow/warnings.py +2 -0
  152. hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/__init__.py +1047 -0
  153. hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/collection_field.py +51 -0
  154. hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/lazy_class_attribute.py +45 -0
  155. hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/mypy.py +71 -0
  156. hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/py.typed +0 -0
  157. hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/typing.py +14 -0
  158. hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/union_field.py +82 -0
  159. hyperliquid/ccxt/static_dependencies/marshmallow_oneofschema/__init__.py +1 -0
  160. hyperliquid/ccxt/static_dependencies/marshmallow_oneofschema/one_of_schema.py +193 -0
  161. hyperliquid/ccxt/static_dependencies/marshmallow_oneofschema/py.typed +0 -0
  162. hyperliquid/ccxt/static_dependencies/msgpack/__init__.py +55 -0
  163. hyperliquid/ccxt/static_dependencies/msgpack/exceptions.py +48 -0
  164. hyperliquid/ccxt/static_dependencies/msgpack/ext.py +168 -0
  165. hyperliquid/ccxt/static_dependencies/msgpack/fallback.py +951 -0
  166. hyperliquid/ccxt/static_dependencies/parsimonious/__init__.py +10 -0
  167. hyperliquid/ccxt/static_dependencies/parsimonious/exceptions.py +105 -0
  168. hyperliquid/ccxt/static_dependencies/parsimonious/expressions.py +479 -0
  169. hyperliquid/ccxt/static_dependencies/parsimonious/grammar.py +487 -0
  170. hyperliquid/ccxt/static_dependencies/parsimonious/nodes.py +325 -0
  171. hyperliquid/ccxt/static_dependencies/parsimonious/utils.py +40 -0
  172. hyperliquid/ccxt/static_dependencies/starknet/__init__.py +0 -0
  173. hyperliquid/ccxt/static_dependencies/starknet/abi/v0/__init__.py +2 -0
  174. hyperliquid/ccxt/static_dependencies/starknet/abi/v0/model.py +44 -0
  175. hyperliquid/ccxt/static_dependencies/starknet/abi/v0/parser.py +216 -0
  176. hyperliquid/ccxt/static_dependencies/starknet/abi/v0/schemas.py +72 -0
  177. hyperliquid/ccxt/static_dependencies/starknet/abi/v0/shape.py +63 -0
  178. hyperliquid/ccxt/static_dependencies/starknet/abi/v1/__init__.py +2 -0
  179. hyperliquid/ccxt/static_dependencies/starknet/abi/v1/model.py +39 -0
  180. hyperliquid/ccxt/static_dependencies/starknet/abi/v1/parser.py +220 -0
  181. hyperliquid/ccxt/static_dependencies/starknet/abi/v1/parser_transformer.py +179 -0
  182. hyperliquid/ccxt/static_dependencies/starknet/abi/v1/schemas.py +66 -0
  183. hyperliquid/ccxt/static_dependencies/starknet/abi/v1/shape.py +47 -0
  184. hyperliquid/ccxt/static_dependencies/starknet/abi/v2/__init__.py +2 -0
  185. hyperliquid/ccxt/static_dependencies/starknet/abi/v2/model.py +89 -0
  186. hyperliquid/ccxt/static_dependencies/starknet/abi/v2/parser.py +293 -0
  187. hyperliquid/ccxt/static_dependencies/starknet/abi/v2/parser_transformer.py +192 -0
  188. hyperliquid/ccxt/static_dependencies/starknet/abi/v2/schemas.py +132 -0
  189. hyperliquid/ccxt/static_dependencies/starknet/abi/v2/shape.py +107 -0
  190. hyperliquid/ccxt/static_dependencies/starknet/cairo/__init__.py +0 -0
  191. hyperliquid/ccxt/static_dependencies/starknet/cairo/data_types.py +123 -0
  192. hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/__init__.py +0 -0
  193. hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/cairo_types.py +77 -0
  194. hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser.py +46 -0
  195. hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser_transformer.py +138 -0
  196. hyperliquid/ccxt/static_dependencies/starknet/cairo/felt.py +64 -0
  197. hyperliquid/ccxt/static_dependencies/starknet/cairo/type_parser.py +121 -0
  198. hyperliquid/ccxt/static_dependencies/starknet/cairo/v1/__init__.py +0 -0
  199. hyperliquid/ccxt/static_dependencies/starknet/cairo/v1/type_parser.py +59 -0
  200. hyperliquid/ccxt/static_dependencies/starknet/cairo/v2/__init__.py +0 -0
  201. hyperliquid/ccxt/static_dependencies/starknet/cairo/v2/type_parser.py +77 -0
  202. hyperliquid/ccxt/static_dependencies/starknet/ccxt_utils.py +7 -0
  203. hyperliquid/ccxt/static_dependencies/starknet/common.py +15 -0
  204. hyperliquid/ccxt/static_dependencies/starknet/constants.py +39 -0
  205. hyperliquid/ccxt/static_dependencies/starknet/hash/__init__.py +0 -0
  206. hyperliquid/ccxt/static_dependencies/starknet/hash/address.py +79 -0
  207. hyperliquid/ccxt/static_dependencies/starknet/hash/compiled_class_hash_objects.py +111 -0
  208. hyperliquid/ccxt/static_dependencies/starknet/hash/selector.py +16 -0
  209. hyperliquid/ccxt/static_dependencies/starknet/hash/storage.py +12 -0
  210. hyperliquid/ccxt/static_dependencies/starknet/hash/utils.py +78 -0
  211. hyperliquid/ccxt/static_dependencies/starknet/models/__init__.py +0 -0
  212. hyperliquid/ccxt/static_dependencies/starknet/models/typed_data.py +45 -0
  213. hyperliquid/ccxt/static_dependencies/starknet/serialization/__init__.py +24 -0
  214. hyperliquid/ccxt/static_dependencies/starknet/serialization/_calldata_reader.py +40 -0
  215. hyperliquid/ccxt/static_dependencies/starknet/serialization/_context.py +142 -0
  216. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/__init__.py +10 -0
  217. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/_common.py +82 -0
  218. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/array_serializer.py +43 -0
  219. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/bool_serializer.py +37 -0
  220. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/byte_array_serializer.py +66 -0
  221. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/cairo_data_serializer.py +71 -0
  222. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/enum_serializer.py +71 -0
  223. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/felt_serializer.py +50 -0
  224. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/named_tuple_serializer.py +58 -0
  225. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/option_serializer.py +43 -0
  226. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/output_serializer.py +40 -0
  227. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/payload_serializer.py +72 -0
  228. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/struct_serializer.py +36 -0
  229. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/tuple_serializer.py +36 -0
  230. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/uint256_serializer.py +76 -0
  231. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/uint_serializer.py +100 -0
  232. hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/unit_serializer.py +32 -0
  233. hyperliquid/ccxt/static_dependencies/starknet/serialization/errors.py +10 -0
  234. hyperliquid/ccxt/static_dependencies/starknet/serialization/factory.py +229 -0
  235. hyperliquid/ccxt/static_dependencies/starknet/serialization/function_serialization_adapter.py +110 -0
  236. hyperliquid/ccxt/static_dependencies/starknet/serialization/tuple_dataclass.py +59 -0
  237. hyperliquid/ccxt/static_dependencies/starknet/utils/__init__.py +0 -0
  238. hyperliquid/ccxt/static_dependencies/starknet/utils/constructor_args_translator.py +86 -0
  239. hyperliquid/ccxt/static_dependencies/starknet/utils/iterable.py +13 -0
  240. hyperliquid/ccxt/static_dependencies/starknet/utils/schema.py +13 -0
  241. hyperliquid/ccxt/static_dependencies/starknet/utils/typed_data.py +182 -0
  242. hyperliquid/ccxt/static_dependencies/starkware/__init__.py +0 -0
  243. hyperliquid/ccxt/static_dependencies/starkware/crypto/__init__.py +0 -0
  244. hyperliquid/ccxt/static_dependencies/starkware/crypto/fast_pedersen_hash.py +50 -0
  245. hyperliquid/ccxt/static_dependencies/starkware/crypto/math_utils.py +78 -0
  246. hyperliquid/ccxt/static_dependencies/starkware/crypto/signature.py +2344 -0
  247. hyperliquid/ccxt/static_dependencies/starkware/crypto/utils.py +63 -0
  248. hyperliquid/ccxt/static_dependencies/sympy/__init__.py +0 -0
  249. hyperliquid/ccxt/static_dependencies/sympy/core/__init__.py +0 -0
  250. hyperliquid/ccxt/static_dependencies/sympy/core/intfunc.py +35 -0
  251. hyperliquid/ccxt/static_dependencies/sympy/external/__init__.py +0 -0
  252. hyperliquid/ccxt/static_dependencies/sympy/external/gmpy.py +345 -0
  253. hyperliquid/ccxt/static_dependencies/sympy/external/importtools.py +187 -0
  254. hyperliquid/ccxt/static_dependencies/sympy/external/ntheory.py +637 -0
  255. hyperliquid/ccxt/static_dependencies/sympy/external/pythonmpq.py +341 -0
  256. hyperliquid/ccxt/static_dependencies/toolz/__init__.py +26 -0
  257. hyperliquid/ccxt/static_dependencies/toolz/_signatures.py +784 -0
  258. hyperliquid/ccxt/static_dependencies/toolz/_version.py +520 -0
  259. hyperliquid/ccxt/static_dependencies/toolz/compatibility.py +30 -0
  260. hyperliquid/ccxt/static_dependencies/toolz/curried/__init__.py +101 -0
  261. hyperliquid/ccxt/static_dependencies/toolz/curried/exceptions.py +22 -0
  262. hyperliquid/ccxt/static_dependencies/toolz/curried/operator.py +22 -0
  263. hyperliquid/ccxt/static_dependencies/toolz/dicttoolz.py +339 -0
  264. hyperliquid/ccxt/static_dependencies/toolz/functoolz.py +1049 -0
  265. hyperliquid/ccxt/static_dependencies/toolz/itertoolz.py +1057 -0
  266. hyperliquid/ccxt/static_dependencies/toolz/recipes.py +46 -0
  267. hyperliquid/ccxt/static_dependencies/toolz/utils.py +9 -0
  268. hyperliquid/ccxt/static_dependencies/typing_inspect/__init__.py +0 -0
  269. hyperliquid/ccxt/static_dependencies/typing_inspect/typing_inspect.py +851 -0
  270. hyperliquid-0.4.66.dist-info/LICENSE +21 -0
  271. hyperliquid-0.4.66.dist-info/METADATA +219 -0
  272. hyperliquid-0.4.66.dist-info/RECORD +274 -0
  273. hyperliquid-0.4.66.dist-info/WHEEL +5 -0
  274. hyperliquid-0.4.66.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2095 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # -----------------------------------------------------------------------------
4
+
5
+ __version__ = '4.4.66'
6
+
7
+ # -----------------------------------------------------------------------------
8
+
9
+ import asyncio
10
+ import concurrent.futures
11
+ import socket
12
+ import certifi
13
+ import aiohttp
14
+ import ssl
15
+ import sys
16
+ import yarl
17
+ import math
18
+ from typing import Any, List
19
+ from ccxt.base.types import Int, Str, Num, Strings
20
+
21
+ # -----------------------------------------------------------------------------
22
+
23
+ from ccxt.async_support.base.throttler import Throttler
24
+
25
+ # -----------------------------------------------------------------------------
26
+
27
+ from ccxt.base.errors import BaseError, NetworkError, BadSymbol, BadRequest, BadResponse, ExchangeError, ExchangeNotAvailable, RequestTimeout, NotSupported, NullResponse, InvalidAddress, RateLimitExceeded
28
+ from ccxt.base.types import OrderType, OrderSide, OrderRequest, CancellationRequest
29
+
30
+ # -----------------------------------------------------------------------------
31
+
32
+ from ccxt.base.exchange import Exchange as BaseExchange, ArgumentsRequired
33
+
34
+ # -----------------------------------------------------------------------------
35
+
36
+ from ccxt.async_support.base.ws.functions import inflate, inflate64, gunzip
37
+ from ccxt.async_support.base.ws.fast_client import FastClient
38
+ from ccxt.async_support.base.ws.future import Future
39
+ from ccxt.async_support.base.ws.order_book import OrderBook, IndexedOrderBook, CountedOrderBook
40
+
41
+
42
+ # -----------------------------------------------------------------------------
43
+
44
+ try:
45
+ from aiohttp_socks import ProxyConnector
46
+ except ImportError:
47
+ ProxyConnector = None
48
+
49
+ # -----------------------------------------------------------------------------
50
+
51
+ __all__ = [
52
+ 'BaseExchange',
53
+ 'Exchange',
54
+ ]
55
+
56
+ # -----------------------------------------------------------------------------
57
+
58
+
59
+ class Exchange(BaseExchange):
60
+ synchronous = False
61
+ streaming = {
62
+ 'maxPingPongMisses': 2,
63
+ 'keepAlive': 30000
64
+ }
65
+ ping = None
66
+ newUpdates = True
67
+ clients = {}
68
+ timeout_on_exit = 250 # needed for: https://github.com/ccxt/ccxt/pull/23470
69
+
70
+ def __init__(self, config={}):
71
+ if 'asyncio_loop' in config:
72
+ self.asyncio_loop = config['asyncio_loop']
73
+ self.aiohttp_trust_env = config.get('aiohttp_trust_env', self.aiohttp_trust_env)
74
+ self.verify = config.get('verify', self.verify)
75
+ self.own_session = 'session' not in config
76
+ self.cafile = config.get('cafile', certifi.where())
77
+ self.throttler = None
78
+ super(Exchange, self).__init__(config)
79
+ self.markets_loading = None
80
+ self.reloading_markets = False
81
+
82
+ def get_event_loop(self):
83
+ return self.asyncio_loop
84
+
85
+ def init_throttler(self, cost=None):
86
+ self.throttler = Throttler(self.tokenBucket, self.asyncio_loop)
87
+
88
+ async def throttle(self, cost=None):
89
+ return await self.throttler(cost)
90
+
91
+ def get_session(self):
92
+ return self.session
93
+
94
+ def __del__(self):
95
+ if self.session is not None or self.socks_proxy_sessions is not None:
96
+ self.logger.warning(self.id + " requires to release all resources with an explicit call to the .close() coroutine. If you are using the exchange instance with async coroutines, add `await exchange.close()` to your code into a place when you're done with the exchange and don't need the exchange instance anymore (at the end of your async coroutine).")
97
+
98
+ if sys.version_info >= (3, 5):
99
+ async def __aenter__(self):
100
+ self.open()
101
+ return self
102
+
103
+ async def __aexit__(self, exc_type, exc, tb):
104
+ await self.close()
105
+
106
+ def open(self):
107
+ if self.asyncio_loop is None:
108
+ if sys.version_info >= (3, 7):
109
+ self.asyncio_loop = asyncio.get_running_loop()
110
+ else:
111
+ self.asyncio_loop = asyncio.get_event_loop()
112
+ self.throttler.loop = self.asyncio_loop
113
+
114
+ if self.ssl_context is None:
115
+ # Create our SSL context object with our CA cert file
116
+ self.ssl_context = ssl.create_default_context(cafile=self.cafile) if self.verify else self.verify
117
+
118
+ if self.own_session and self.session is None:
119
+ # Pass this SSL context to aiohttp and create a TCPConnector
120
+ self.tcp_connector = aiohttp.TCPConnector(ssl=self.ssl_context, loop=self.asyncio_loop, enable_cleanup_closed=True)
121
+ self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=self.tcp_connector, trust_env=self.aiohttp_trust_env)
122
+
123
+ async def close(self):
124
+ await self.ws_close()
125
+ if self.session is not None:
126
+ if self.own_session:
127
+ await self.session.close()
128
+ self.session = None
129
+ await self.close_connector()
130
+ await self.close_proxy_sessions()
131
+ await self.sleep(self.timeout_on_exit)
132
+
133
+ async def close_connector(self):
134
+ if self.tcp_connector is not None:
135
+ await self.tcp_connector.close()
136
+ self.tcp_connector = None
137
+ if self.aiohttp_socks_connector is not None:
138
+ await self.aiohttp_socks_connector.close()
139
+ self.aiohttp_socks_connector = None
140
+
141
+ async def close_proxy_sessions(self):
142
+ if self.socks_proxy_sessions is not None:
143
+ for url in self.socks_proxy_sessions:
144
+ await self.socks_proxy_sessions[url].close()
145
+ self.socks_proxy_sessions = None
146
+
147
+ async def fetch(self, url, method='GET', headers=None, body=None):
148
+ """Perform a HTTP request and return decoded JSON data"""
149
+
150
+ # ##### PROXY & HEADERS #####
151
+ request_headers = self.prepare_request_headers(headers)
152
+ self.last_request_headers = request_headers
153
+ # proxy-url
154
+ proxyUrl = self.check_proxy_url_settings(url, method, headers, body)
155
+ if proxyUrl is not None:
156
+ request_headers.update({'Origin': self.origin})
157
+ url = proxyUrl + url
158
+ # proxy agents
159
+ final_proxy = None # set default
160
+ proxy_session = None
161
+ httpProxy, httpsProxy, socksProxy = self.check_proxy_settings(url, method, headers, body)
162
+ if httpProxy:
163
+ final_proxy = httpProxy
164
+ elif httpsProxy:
165
+ final_proxy = httpsProxy
166
+ elif socksProxy:
167
+ if ProxyConnector is None:
168
+ raise NotSupported(self.id + ' - to use SOCKS proxy with ccxt, you need "aiohttp_socks" module that can be installed by "pip install aiohttp_socks"')
169
+ # override session
170
+ if (self.socks_proxy_sessions is None):
171
+ self.socks_proxy_sessions = {}
172
+ if (socksProxy not in self.socks_proxy_sessions):
173
+ # Create our SSL context object with our CA cert file
174
+ self.open() # ensure `asyncio_loop` is set
175
+ self.aiohttp_socks_connector = ProxyConnector.from_url(
176
+ socksProxy,
177
+ # extra args copied from self.open()
178
+ ssl=self.ssl_context,
179
+ loop=self.asyncio_loop,
180
+ enable_cleanup_closed=True
181
+ )
182
+ self.socks_proxy_sessions[socksProxy] = aiohttp.ClientSession(loop=self.asyncio_loop, connector=self.aiohttp_socks_connector, trust_env=self.aiohttp_trust_env)
183
+ proxy_session = self.socks_proxy_sessions[socksProxy]
184
+ # add aiohttp_proxy for python as exclusion
185
+ elif self.aiohttp_proxy:
186
+ final_proxy = self.aiohttp_proxy
187
+
188
+ proxyAgentSet = final_proxy is not None or socksProxy is not None
189
+ self.checkConflictingProxies(proxyAgentSet, proxyUrl)
190
+
191
+ # avoid old proxies mixing
192
+ if (self.aiohttp_proxy is not None) and (proxyUrl is not None or httpProxy is not None or httpsProxy is not None or socksProxy is not None):
193
+ raise NotSupported(self.id + ' you have set multiple proxies, please use one or another')
194
+
195
+ # log
196
+ if self.verbose:
197
+ self.log("\nfetch Request:", self.id, method, url, "RequestHeaders:", request_headers, "RequestBody:", body)
198
+ self.logger.debug("%s %s, Request: %s %s", method, url, headers, body)
199
+ # end of proxies & headers
200
+
201
+ request_body = body
202
+ encoded_body = body.encode() if body else None
203
+ self.open()
204
+ final_session = proxy_session if proxy_session is not None else self.session
205
+ session_method = getattr(final_session, method.lower())
206
+
207
+ http_response = None
208
+ http_status_code = None
209
+ http_status_text = None
210
+ json_response = None
211
+ try:
212
+ async with session_method(yarl.URL(url, encoded=True),
213
+ data=encoded_body,
214
+ headers=request_headers,
215
+ timeout=(self.timeout / 1000),
216
+ proxy=final_proxy) as response:
217
+ http_response = await response.text(errors='replace')
218
+ # CIMultiDictProxy
219
+ raw_headers = response.headers
220
+ headers = {}
221
+ for header in raw_headers:
222
+ if header in headers:
223
+ headers[header] = headers[header] + ', ' + raw_headers[header]
224
+ else:
225
+ headers[header] = raw_headers[header]
226
+ http_status_code = response.status
227
+ http_status_text = response.reason
228
+ http_response = self.on_rest_response(http_status_code, http_status_text, url, method, headers, http_response, request_headers, request_body)
229
+ json_response = self.parse_json(http_response)
230
+ if self.enableLastHttpResponse:
231
+ self.last_http_response = http_response
232
+ if self.enableLastResponseHeaders:
233
+ self.last_response_headers = headers
234
+ if self.enableLastJsonResponse:
235
+ self.last_json_response = json_response
236
+ if self.verbose:
237
+ self.log("\nfetch Response:", self.id, method, url, http_status_code, "ResponseHeaders:", headers, "ResponseBody:", http_response)
238
+ self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response)
239
+
240
+ except socket.gaierror as e:
241
+ details = ' '.join([self.id, method, url])
242
+ raise ExchangeNotAvailable(details) from e
243
+
244
+ except (concurrent.futures.TimeoutError, asyncio.TimeoutError) as e:
245
+ details = ' '.join([self.id, method, url])
246
+ raise RequestTimeout(details) from e
247
+
248
+ except aiohttp.ClientConnectionError as e:
249
+ details = ' '.join([self.id, method, url])
250
+ raise ExchangeNotAvailable(details) from e
251
+
252
+ except aiohttp.ClientError as e: # base exception class
253
+ details = ' '.join([self.id, method, url])
254
+ raise ExchangeError(details) from e
255
+
256
+ self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
257
+ self.handle_http_status_code(http_status_code, http_status_text, url, method, http_response)
258
+ if json_response is not None:
259
+ return json_response
260
+ if self.is_text_response(headers):
261
+ return http_response
262
+ if http_response == '' or http_response is None:
263
+ return http_response
264
+ return response.content
265
+
266
+ async def load_markets_helper(self, reload=False, params={}):
267
+ if not reload:
268
+ if self.markets:
269
+ if not self.markets_by_id:
270
+ return self.set_markets(self.markets)
271
+ return self.markets
272
+ currencies = None
273
+ if self.has['fetchCurrencies'] is True:
274
+ currencies = await self.fetch_currencies()
275
+ markets = await self.fetch_markets(params)
276
+ return self.set_markets(markets, currencies)
277
+
278
+ async def load_markets(self, reload=False, params={}):
279
+ if (reload and not self.reloading_markets) or not self.markets_loading:
280
+ self.reloading_markets = True
281
+ coroutine = self.load_markets_helper(reload, params)
282
+ # coroutines can only be awaited once so we wrap it in a task
283
+ self.markets_loading = asyncio.ensure_future(coroutine)
284
+ try:
285
+ result = await self.markets_loading
286
+ except Exception as e:
287
+ self.reloading_markets = False
288
+ self.markets_loading = None
289
+ raise e
290
+ self.reloading_markets = False
291
+ return result
292
+
293
+ async def load_fees(self, reload=False):
294
+ if not reload:
295
+ if self.loaded_fees != Exchange.loaded_fees:
296
+ return self.loaded_fees
297
+ self.loaded_fees = self.deep_extend(self.loaded_fees, await self.fetch_fees())
298
+ return self.loaded_fees
299
+
300
+ async def fetch_markets(self, params={}):
301
+ # markets are returned as a list
302
+ # currencies are returned as a dict
303
+ # this is for historical reasons
304
+ # and may be changed for consistency later
305
+ return self.to_array(self.markets)
306
+
307
+ async def fetch_currencies(self, params={}):
308
+ # markets are returned as a list
309
+ # currencies are returned as a dict
310
+ # this is for historical reasons
311
+ # and may be changed for consistency later
312
+ return self.currencies
313
+
314
+ async def fetchOHLCVC(self, symbol, timeframe='1m', since=None, limit=None, params={}):
315
+ return await self.fetch_ohlcvc(symbol, timeframe, since, limit, params)
316
+
317
+ async def fetch_full_tickers(self, symbols=None, params={}):
318
+ return await self.fetch_tickers(symbols, params)
319
+
320
+ async def sleep(self, milliseconds):
321
+ return await asyncio.sleep(milliseconds / 1000)
322
+
323
+ async def spawn_async(self, method, *args):
324
+ try:
325
+ await method(*args)
326
+ except Exception:
327
+ # todo: handle spawned errors
328
+ pass
329
+
330
+ def spawn(self, method, *args):
331
+ def callback(asyncio_future):
332
+ exception = asyncio_future.exception()
333
+ if exception is None:
334
+ future.resolve(asyncio_future.result())
335
+ else:
336
+ future.reject(exception)
337
+ future = Future()
338
+ task = self.asyncio_loop.create_task(method(*args))
339
+ task.add_done_callback(callback)
340
+ return future
341
+
342
+ # -----------------------------------------------------------------------
343
+ # WS/PRO code
344
+
345
+ @staticmethod
346
+ def inflate(data):
347
+ return inflate(data)
348
+
349
+ @staticmethod
350
+ def inflate64(data):
351
+ return inflate64(data)
352
+
353
+ @staticmethod
354
+ def gunzip(data):
355
+ return gunzip(data)
356
+
357
+ def order_book(self, snapshot={}, depth=None):
358
+ return OrderBook(snapshot, depth)
359
+
360
+ def indexed_order_book(self, snapshot={}, depth=None):
361
+ return IndexedOrderBook(snapshot, depth)
362
+
363
+ def counted_order_book(self, snapshot={}, depth=None):
364
+ return CountedOrderBook(snapshot, depth)
365
+
366
+ def client(self, url):
367
+ self.clients = self.clients or {}
368
+ if url not in self.clients:
369
+ on_message = self.handle_message
370
+ on_error = self.on_error
371
+ on_close = self.on_close
372
+ on_connected = self.on_connected
373
+ # decide client type here: aiohttp ws / websockets / signalr / socketio
374
+ ws_options = self.safe_value(self.options, 'ws', {})
375
+ options = self.extend(self.streaming, {
376
+ 'log': getattr(self, 'log'),
377
+ 'ping': getattr(self, 'ping', None),
378
+ 'verbose': self.verbose,
379
+ 'throttle': Throttler(self.tokenBucket, self.asyncio_loop),
380
+ 'asyncio_loop': self.asyncio_loop,
381
+ }, ws_options)
382
+ self.clients[url] = FastClient(url, on_message, on_error, on_close, on_connected, options)
383
+ self.clients[url].proxy = self.get_ws_proxy()
384
+ return self.clients[url]
385
+
386
+ def get_ws_proxy(self):
387
+ httpProxy, httpsProxy, socksProxy = self.check_ws_proxy_settings()
388
+ if httpProxy:
389
+ return httpProxy
390
+ elif httpsProxy:
391
+ return httpsProxy
392
+ elif socksProxy:
393
+ return socksProxy
394
+ return None
395
+
396
+ def delay(self, timeout, method, *args):
397
+ return self.asyncio_loop.call_later(timeout / 1000, self.spawn, method, *args)
398
+
399
+ def handle_message(self, client, message):
400
+ always = True
401
+ if always:
402
+ raise NotSupported(self.id + '.handle_message() not implemented yet')
403
+ return {}
404
+
405
+ def watch_multiple(self, url, message_hashes, message=None, subscribe_hashes=None, subscription=None):
406
+ # base exchange self.open starts the aiohttp Session in an async context
407
+ self.open()
408
+ backoff_delay = 0
409
+ client = self.client(url)
410
+
411
+ future = Future.race([client.future(message_hash) for message_hash in message_hashes])
412
+
413
+ missing_subscriptions = []
414
+ if subscribe_hashes is not None:
415
+ for subscribe_hash in subscribe_hashes:
416
+ if subscribe_hash not in client.subscriptions:
417
+ missing_subscriptions.append(subscribe_hash)
418
+ client.subscriptions[subscribe_hash] = subscription or True
419
+
420
+ connected = client.connected if client.connected.done() \
421
+ else asyncio.ensure_future(client.connect(self.session, backoff_delay))
422
+
423
+ def after(fut):
424
+ # todo: decouple signing from subscriptions
425
+ options = self.safe_value(self.options, 'ws')
426
+ cost = self.safe_value(options, 'cost', 1)
427
+ if message:
428
+ async def send_message():
429
+ if self.enableRateLimit:
430
+ await client.throttle(cost)
431
+ try:
432
+ await client.send(message)
433
+ except ConnectionError as e:
434
+ client.on_error(e)
435
+ except Exception as e:
436
+ client.on_error(e)
437
+ asyncio.ensure_future(send_message())
438
+
439
+ if missing_subscriptions:
440
+ connected.add_done_callback(after)
441
+
442
+ return future
443
+
444
+ def watch(self, url, message_hash, message=None, subscribe_hash=None, subscription=None):
445
+ # base exchange self.open starts the aiohttp Session in an async context
446
+ self.open()
447
+ backoff_delay = 0
448
+ client = self.client(url)
449
+ if subscribe_hash is None and message_hash in client.futures:
450
+ return client.futures[message_hash]
451
+ future = client.future(message_hash)
452
+
453
+ subscribed = client.subscriptions.get(subscribe_hash)
454
+
455
+ if not subscribed:
456
+ client.subscriptions[subscribe_hash] = subscription or True
457
+
458
+ connected = client.connected if client.connected.done() \
459
+ else asyncio.ensure_future(client.connect(self.session, backoff_delay))
460
+
461
+ def after(fut):
462
+ # todo: decouple signing from subscriptions
463
+ options = self.safe_value(self.options, 'ws')
464
+ cost = self.safe_value(options, 'cost', 1)
465
+ if message:
466
+ async def send_message():
467
+ if self.enableRateLimit:
468
+ await client.throttle(cost)
469
+ try:
470
+ await client.send(message)
471
+ except ConnectionError as e:
472
+ client.on_error(e)
473
+ except Exception as e:
474
+ client.on_error(e)
475
+ asyncio.ensure_future(send_message())
476
+
477
+ if not subscribed:
478
+ connected.add_done_callback(after)
479
+
480
+ return future
481
+
482
+ def on_connected(self, client, message=None):
483
+ # for user hooks
484
+ # print('Connected to', client.url)
485
+ pass
486
+
487
+ def on_error(self, client, error):
488
+ if client.url in self.clients and self.clients[client.url].error:
489
+ del self.clients[client.url]
490
+
491
+ def on_close(self, client, error):
492
+ if client.error:
493
+ # connection closed by the user or due to an error
494
+ pass
495
+ else:
496
+ # server disconnected a working connection
497
+ if client.url in self.clients:
498
+ del self.clients[client.url]
499
+
500
+ async def ws_close(self):
501
+ if self.clients:
502
+ await asyncio.wait([asyncio.create_task(client.close()) for client in self.clients.values()], return_when=asyncio.ALL_COMPLETED)
503
+ for url in self.clients.copy():
504
+ del self.clients[url]
505
+
506
+ async def load_order_book(self, client, messageHash, symbol, limit=None, params={}):
507
+ if symbol not in self.orderbooks:
508
+ client.reject(ExchangeError(self.id + ' loadOrderBook() orderbook is not initiated'), messageHash)
509
+ return
510
+ try:
511
+ maxRetries = self.handle_option('watchOrderBook', 'maxRetries', 3)
512
+ tries = 0
513
+ stored = self.orderbooks[symbol]
514
+ while tries < maxRetries:
515
+ cache = stored.cache
516
+ order_book = await self.fetch_order_book(symbol, limit, params)
517
+ index = self.get_cache_index(order_book, cache)
518
+ if index >= 0:
519
+ stored.reset(order_book)
520
+ self.handle_deltas(stored, cache[index:])
521
+ cache.clear()
522
+ client.resolve(stored, messageHash)
523
+ return
524
+ tries += 1
525
+ client.reject(ExchangeError(self.id + ' nonce is behind cache after ' + str(maxRetries) + ' tries.'), messageHash)
526
+ del self.clients[client.url]
527
+ except BaseError as e:
528
+ client.reject(e, messageHash)
529
+ await self.load_order_book(client, messageHash, symbol, limit, params)
530
+
531
+ def format_scientific_notation_ftx(self, n):
532
+ if n == 0:
533
+ return '0e-00'
534
+ return format(n, 'g')
535
+
536
+ # ########################################################################
537
+ # ########################################################################
538
+ # ########################################################################
539
+ # ########################################################################
540
+ # ######## ######## ########
541
+ # ######## ######## ########
542
+ # ######## ######## ########
543
+ # ######## ######## ########
544
+ # ######## ######################## ########################
545
+ # ######## ######################## ########################
546
+ # ######## ######################## ########################
547
+ # ######## ######################## ########################
548
+ # ######## ######## ########
549
+ # ######## ######## ########
550
+ # ######## ######## ########
551
+ # ######## ######## ########
552
+ # ########################################################################
553
+ # ########################################################################
554
+ # ########################################################################
555
+ # ########################################################################
556
+ # ######## ######## ######## ########
557
+ # ######## ######## ######## ########
558
+ # ######## ######## ######## ########
559
+ # ######## ######## ######## ########
560
+ # ################ ######################## ################
561
+ # ################ ######################## ################
562
+ # ################ ######################## ################
563
+ # ################ ######################## ################
564
+ # ######## ######## ################ ################
565
+ # ######## ######## ################ ################
566
+ # ######## ######## ################ ################
567
+ # ######## ######## ################ ################
568
+ # ########################################################################
569
+ # ########################################################################
570
+ # ########################################################################
571
+ # ########################################################################
572
+
573
+ # METHODS BELOW THIS LINE ARE TRANSPILED FROM JAVASCRIPT TO PYTHON AND PHP
574
+
575
+ async def fetch_accounts(self, params={}):
576
+ raise NotSupported(self.id + ' fetchAccounts() is not supported yet')
577
+
578
+ async def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}):
579
+ raise NotSupported(self.id + ' fetchTrades() is not supported yet')
580
+
581
+ async def fetch_trades_ws(self, symbol: str, since: Int = None, limit: Int = None, params={}):
582
+ raise NotSupported(self.id + ' fetchTradesWs() is not supported yet')
583
+
584
+ async def watch_liquidations(self, symbol: str, since: Int = None, limit: Int = None, params={}):
585
+ if self.has['watchLiquidationsForSymbols']:
586
+ return await self.watch_liquidations_for_symbols([symbol], since, limit, params)
587
+ raise NotSupported(self.id + ' watchLiquidations() is not supported yet')
588
+
589
+ async def watch_liquidations_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}):
590
+ raise NotSupported(self.id + ' watchLiquidationsForSymbols() is not supported yet')
591
+
592
+ async def watch_my_liquidations(self, symbol: str, since: Int = None, limit: Int = None, params={}):
593
+ if self.has['watchMyLiquidationsForSymbols']:
594
+ return self.watch_my_liquidations_for_symbols([symbol], since, limit, params)
595
+ raise NotSupported(self.id + ' watchMyLiquidations() is not supported yet')
596
+
597
+ async def watch_my_liquidations_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}):
598
+ raise NotSupported(self.id + ' watchMyLiquidationsForSymbols() is not supported yet')
599
+
600
+ async def watch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}):
601
+ raise NotSupported(self.id + ' watchTrades() is not supported yet')
602
+
603
+ async def un_watch_trades(self, symbol: str, params={}):
604
+ raise NotSupported(self.id + ' unWatchTrades() is not supported yet')
605
+
606
+ async def watch_trades_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}):
607
+ raise NotSupported(self.id + ' watchTradesForSymbols() is not supported yet')
608
+
609
+ async def un_watch_trades_for_symbols(self, symbols: List[str], params={}):
610
+ raise NotSupported(self.id + ' unWatchTradesForSymbols() is not supported yet')
611
+
612
+ async def watch_my_trades_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}):
613
+ raise NotSupported(self.id + ' watchMyTradesForSymbols() is not supported yet')
614
+
615
+ async def watch_orders_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}):
616
+ raise NotSupported(self.id + ' watchOrdersForSymbols() is not supported yet')
617
+
618
+ async def watch_ohlcv_for_symbols(self, symbolsAndTimeframes: List[List[str]], since: Int = None, limit: Int = None, params={}):
619
+ raise NotSupported(self.id + ' watchOHLCVForSymbols() is not supported yet')
620
+
621
+ async def un_watch_ohlcv_for_symbols(self, symbolsAndTimeframes: List[List[str]], params={}):
622
+ raise NotSupported(self.id + ' unWatchOHLCVForSymbols() is not supported yet')
623
+
624
+ async def watch_order_book_for_symbols(self, symbols: List[str], limit: Int = None, params={}):
625
+ raise NotSupported(self.id + ' watchOrderBookForSymbols() is not supported yet')
626
+
627
+ async def un_watch_order_book_for_symbols(self, symbols: List[str], params={}):
628
+ raise NotSupported(self.id + ' unWatchOrderBookForSymbols() is not supported yet')
629
+
630
+ async def fetch_deposit_addresses(self, codes: Strings = None, params={}):
631
+ raise NotSupported(self.id + ' fetchDepositAddresses() is not supported yet')
632
+
633
+ async def fetch_order_book(self, symbol: str, limit: Int = None, params={}):
634
+ raise NotSupported(self.id + ' fetchOrderBook() is not supported yet')
635
+
636
+ async def fetch_order_book_ws(self, symbol: str, limit: Int = None, params={}):
637
+ raise NotSupported(self.id + ' fetchOrderBookWs() is not supported yet')
638
+
639
+ async def fetch_margin_mode(self, symbol: str, params={}):
640
+ if self.has['fetchMarginModes']:
641
+ marginModes = await self.fetch_margin_modes([symbol], params)
642
+ return self.safe_dict(marginModes, symbol)
643
+ else:
644
+ raise NotSupported(self.id + ' fetchMarginMode() is not supported yet')
645
+
646
+ async def fetch_margin_modes(self, symbols: Strings = None, params={}):
647
+ raise NotSupported(self.id + ' fetchMarginModes() is not supported yet')
648
+
649
+ async def fetch_rest_order_book_safe(self, symbol, limit=None, params={}):
650
+ fetchSnapshotMaxRetries = self.handle_option('watchOrderBook', 'maxRetries', 3)
651
+ for i in range(0, fetchSnapshotMaxRetries):
652
+ try:
653
+ orderBook = await self.fetch_order_book(symbol, limit, params)
654
+ return orderBook
655
+ except Exception as e:
656
+ if (i + 1) == fetchSnapshotMaxRetries:
657
+ raise e
658
+ return None
659
+
660
+ async def watch_order_book(self, symbol: str, limit: Int = None, params={}):
661
+ raise NotSupported(self.id + ' watchOrderBook() is not supported yet')
662
+
663
+ async def un_watch_order_book(self, symbol: str, params={}):
664
+ raise NotSupported(self.id + ' unWatchOrderBook() is not supported yet')
665
+
666
+ async def fetch_time(self, params={}):
667
+ raise NotSupported(self.id + ' fetchTime() is not supported yet')
668
+
669
+ async def fetch_trading_limits(self, symbols: Strings = None, params={}):
670
+ raise NotSupported(self.id + ' fetchTradingLimits() is not supported yet')
671
+
672
+ async def fetch_cross_borrow_rates(self, params={}):
673
+ raise NotSupported(self.id + ' fetchCrossBorrowRates() is not supported yet')
674
+
675
+ async def fetch_isolated_borrow_rates(self, params={}):
676
+ raise NotSupported(self.id + ' fetchIsolatedBorrowRates() is not supported yet')
677
+
678
+ async def fetch_leverage_tiers(self, symbols: Strings = None, params={}):
679
+ raise NotSupported(self.id + ' fetchLeverageTiers() is not supported yet')
680
+
681
+ async def fetch_funding_rates(self, symbols: Strings = None, params={}):
682
+ raise NotSupported(self.id + ' fetchFundingRates() is not supported yet')
683
+
684
+ async def fetch_funding_intervals(self, symbols: Strings = None, params={}):
685
+ raise NotSupported(self.id + ' fetchFundingIntervals() is not supported yet')
686
+
687
+ async def watch_funding_rate(self, symbol: str, params={}):
688
+ raise NotSupported(self.id + ' watchFundingRate() is not supported yet')
689
+
690
+ async def watch_funding_rates(self, symbols: List[str], params={}):
691
+ raise NotSupported(self.id + ' watchFundingRates() is not supported yet')
692
+
693
+ async def watch_funding_rates_for_symbols(self, symbols: List[str], params={}):
694
+ return await self.watch_funding_rates(symbols, params)
695
+
696
+ async def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}):
697
+ raise NotSupported(self.id + ' transfer() is not supported yet')
698
+
699
+ async def withdraw(self, code: str, amount: float, address: str, tag=None, params={}):
700
+ raise NotSupported(self.id + ' withdraw() is not supported yet')
701
+
702
+ async def create_deposit_address(self, code: str, params={}):
703
+ raise NotSupported(self.id + ' createDepositAddress() is not supported yet')
704
+
705
+ async def set_leverage(self, leverage: Int, symbol: Str = None, params={}):
706
+ raise NotSupported(self.id + ' setLeverage() is not supported yet')
707
+
708
+ async def fetch_leverage(self, symbol: str, params={}):
709
+ if self.has['fetchLeverages']:
710
+ leverages = await self.fetch_leverages([symbol], params)
711
+ return self.safe_dict(leverages, symbol)
712
+ else:
713
+ raise NotSupported(self.id + ' fetchLeverage() is not supported yet')
714
+
715
+ async def fetch_leverages(self, symbols: Strings = None, params={}):
716
+ raise NotSupported(self.id + ' fetchLeverages() is not supported yet')
717
+
718
+ async def set_position_mode(self, hedged: bool, symbol: Str = None, params={}):
719
+ raise NotSupported(self.id + ' setPositionMode() is not supported yet')
720
+
721
+ async def add_margin(self, symbol: str, amount: float, params={}):
722
+ raise NotSupported(self.id + ' addMargin() is not supported yet')
723
+
724
+ async def reduce_margin(self, symbol: str, amount: float, params={}):
725
+ raise NotSupported(self.id + ' reduceMargin() is not supported yet')
726
+
727
+ async def set_margin(self, symbol: str, amount: float, params={}):
728
+ raise NotSupported(self.id + ' setMargin() is not supported yet')
729
+
730
+ async def fetch_long_short_ratio(self, symbol: str, timeframe: Str = None, params={}):
731
+ raise NotSupported(self.id + ' fetchLongShortRatio() is not supported yet')
732
+
733
+ async def fetch_long_short_ratio_history(self, symbol: Str = None, timeframe: Str = None, since: Int = None, limit: Int = None, params={}):
734
+ raise NotSupported(self.id + ' fetchLongShortRatioHistory() is not supported yet')
735
+
736
+ async def fetch_margin_adjustment_history(self, symbol: Str = None, type: Str = None, since: Num = None, limit: Num = None, params={}):
737
+ """
738
+ fetches the history of margin added or reduced from contract isolated positions
739
+ :param str [symbol]: unified market symbol
740
+ :param str [type]: "add" or "reduce"
741
+ :param int [since]: timestamp in ms of the earliest change to fetch
742
+ :param int [limit]: the maximum amount of changes to fetch
743
+ :param dict params: extra parameters specific to the exchange api endpoint
744
+ :returns dict[]: a list of `margin structures <https://docs.ccxt.com/#/?id=margin-loan-structure>`
745
+ """
746
+ raise NotSupported(self.id + ' fetchMarginAdjustmentHistory() is not supported yet')
747
+
748
+ async def set_margin_mode(self, marginMode: str, symbol: Str = None, params={}):
749
+ raise NotSupported(self.id + ' setMarginMode() is not supported yet')
750
+
751
+ async def fetch_deposit_addresses_by_network(self, code: str, params={}):
752
+ raise NotSupported(self.id + ' fetchDepositAddressesByNetwork() is not supported yet')
753
+
754
+ async def fetch_open_interest_history(self, symbol: str, timeframe='1h', since: Int = None, limit: Int = None, params={}):
755
+ raise NotSupported(self.id + ' fetchOpenInterestHistory() is not supported yet')
756
+
757
+ async def fetch_open_interest(self, symbol: str, params={}):
758
+ raise NotSupported(self.id + ' fetchOpenInterest() is not supported yet')
759
+
760
+ async def fetch_open_interests(self, symbols: Strings = None, params={}):
761
+ raise NotSupported(self.id + ' fetchOpenInterests() is not supported yet')
762
+
763
+ async def sign_in(self, params={}):
764
+ raise NotSupported(self.id + ' signIn() is not supported yet')
765
+
766
+ async def fetch_payment_methods(self, params={}):
767
+ raise NotSupported(self.id + ' fetchPaymentMethods() is not supported yet')
768
+
769
+ async def fetch_borrow_rate(self, code: str, amount: float, params={}):
770
+ raise NotSupported(self.id + ' fetchBorrowRate is deprecated, please use fetchCrossBorrowRate or fetchIsolatedBorrowRate instead')
771
+
772
+ async def repay_cross_margin(self, code: str, amount: float, params={}):
773
+ raise NotSupported(self.id + ' repayCrossMargin is not support yet')
774
+
775
+ async def repay_isolated_margin(self, symbol: str, code: str, amount: float, params={}):
776
+ raise NotSupported(self.id + ' repayIsolatedMargin is not support yet')
777
+
778
+ async def borrow_cross_margin(self, code: str, amount: float, params={}):
779
+ raise NotSupported(self.id + ' borrowCrossMargin is not support yet')
780
+
781
+ async def borrow_isolated_margin(self, symbol: str, code: str, amount: float, params={}):
782
+ raise NotSupported(self.id + ' borrowIsolatedMargin is not support yet')
783
+
784
+ async def borrow_margin(self, code: str, amount: float, symbol: Str = None, params={}):
785
+ raise NotSupported(self.id + ' borrowMargin is deprecated, please use borrowCrossMargin or borrowIsolatedMargin instead')
786
+
787
+ async def repay_margin(self, code: str, amount: float, symbol: Str = None, params={}):
788
+ raise NotSupported(self.id + ' repayMargin is deprecated, please use repayCrossMargin or repayIsolatedMargin instead')
789
+
790
+ async def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}):
791
+ message = ''
792
+ if self.has['fetchTrades']:
793
+ message = '. If you want to build OHLCV candles from trade executions data, visit https://github.com/ccxt/ccxt/tree/master/examples/ and see "build-ohlcv-bars" file'
794
+ raise NotSupported(self.id + ' fetchOHLCV() is not supported yet' + message)
795
+
796
+ async def fetch_ohlcv_ws(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}):
797
+ message = ''
798
+ if self.has['fetchTradesWs']:
799
+ message = '. If you want to build OHLCV candles from trade executions data, visit https://github.com/ccxt/ccxt/tree/master/examples/ and see "build-ohlcv-bars" file'
800
+ raise NotSupported(self.id + ' fetchOHLCVWs() is not supported yet. Try using fetchOHLCV instead.' + message)
801
+
802
+ async def watch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}):
803
+ raise NotSupported(self.id + ' watchOHLCV() is not supported yet')
804
+
805
+ async def fetch_web_endpoint(self, method, endpointMethod, returnAsJson, startRegex=None, endRegex=None):
806
+ errorMessage = ''
807
+ options = self.safe_value(self.options, method, {})
808
+ muteOnFailure = self.safe_bool(options, 'webApiMuteFailure', True)
809
+ try:
810
+ # if it was not explicitly disabled, then don't fetch
811
+ if self.safe_bool(options, 'webApiEnable', True) is not True:
812
+ return None
813
+ maxRetries = self.safe_value(options, 'webApiRetries', 10)
814
+ response = None
815
+ retry = 0
816
+ shouldBreak = False
817
+ while(retry < maxRetries):
818
+ try:
819
+ response = await getattr(self, endpointMethod)({})
820
+ shouldBreak = True
821
+ break
822
+ except Exception as e:
823
+ retry = retry + 1
824
+ if retry == maxRetries:
825
+ raise e
826
+ if shouldBreak:
827
+ break # self is needed because of GO
828
+ content = response
829
+ if startRegex is not None:
830
+ splitted_by_start = content.split(startRegex)
831
+ content = splitted_by_start[1] # we need second part after start
832
+ if endRegex is not None:
833
+ splitted_by_end = content.split(endRegex)
834
+ content = splitted_by_end[0] # we need first part after start
835
+ if returnAsJson and (isinstance(content, str)):
836
+ jsoned = self.parse_json(content.strip()) # content should be trimmed before json parsing
837
+ if jsoned:
838
+ return jsoned # if parsing was not successfull, exception should be thrown
839
+ else:
840
+ raise BadResponse('could not parse the response into json')
841
+ else:
842
+ return content
843
+ except Exception as e:
844
+ errorMessage = self.id + ' ' + method + '() failed to fetch correct data from website. Probably webpage markup has been changed, breaking the page custom parser.'
845
+ if muteOnFailure:
846
+ return None
847
+ else:
848
+ raise BadResponse(errorMessage)
849
+
850
+ async def fetch_l2_order_book(self, symbol: str, limit: Int = None, params={}):
851
+ orderbook = await self.fetch_order_book(symbol, limit, params)
852
+ return self.extend(orderbook, {
853
+ 'asks': self.sort_by(self.aggregate(orderbook['asks']), 0),
854
+ 'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True),
855
+ })
856
+
857
+ async def load_trading_limits(self, symbols: Strings = None, reload=False, params={}):
858
+ if self.has['fetchTradingLimits']:
859
+ if reload or not ('limitsLoaded' in self.options):
860
+ response = await self.fetch_trading_limits(symbols)
861
+ for i in range(0, len(symbols)):
862
+ symbol = symbols[i]
863
+ self.markets[symbol] = self.deep_extend(self.markets[symbol], response[symbol])
864
+ self.options['limitsLoaded'] = self.milliseconds()
865
+ return self.markets
866
+
867
+ async def fetch2(self, path, api: Any = 'public', method='GET', params={}, headers: Any = None, body: Any = None, config={}):
868
+ if self.enableRateLimit:
869
+ cost = self.calculate_rate_limiter_cost(api, method, path, params, config)
870
+ await self.throttle(cost)
871
+ self.lastRestRequestTimestamp = self.milliseconds()
872
+ request = self.sign(path, api, method, params, headers, body)
873
+ self.last_request_headers = request['headers']
874
+ self.last_request_body = request['body']
875
+ self.last_request_url = request['url']
876
+ retries = None
877
+ retries, params = self.handle_option_and_params(params, path, 'maxRetriesOnFailure', 0)
878
+ retryDelay = None
879
+ retryDelay, params = self.handle_option_and_params(params, path, 'maxRetriesOnFailureDelay', 0)
880
+ for i in range(0, retries + 1):
881
+ try:
882
+ return await self.fetch(request['url'], request['method'], request['headers'], request['body'])
883
+ except Exception as e:
884
+ if isinstance(e, NetworkError):
885
+ if i < retries:
886
+ if self.verbose:
887
+ self.log('Request failed with the error: ' + str(e) + ', retrying ' + (i + str(1)) + ' of ' + str(retries) + '...')
888
+ if (retryDelay is not None) and (retryDelay != 0):
889
+ await self.sleep(retryDelay)
890
+ # continue #check self
891
+ if i >= retries:
892
+ raise e
893
+ return None # self line is never reached, but exists for c# value return requirement
894
+
895
+ async def request(self, path, api: Any = 'public', method='GET', params={}, headers: Any = None, body: Any = None, config={}):
896
+ return await self.fetch2(path, api, method, params, headers, body, config)
897
+
898
+ async def load_accounts(self, reload=False, params={}):
899
+ if reload:
900
+ self.accounts = await self.fetch_accounts(params)
901
+ else:
902
+ if self.accounts:
903
+ return self.accounts
904
+ else:
905
+ self.accounts = await self.fetch_accounts(params)
906
+ self.accountsById = self.index_by(self.accounts, 'id')
907
+ return self.accounts
908
+
909
+ async def edit_limit_buy_order(self, id: str, symbol: str, amount: float, price: Num = None, params={}):
910
+ return await self.edit_limit_order(id, symbol, 'buy', amount, price, params)
911
+
912
+ async def edit_limit_sell_order(self, id: str, symbol: str, amount: float, price: Num = None, params={}):
913
+ return await self.edit_limit_order(id, symbol, 'sell', amount, price, params)
914
+
915
+ async def edit_limit_order(self, id: str, symbol: str, side: OrderSide, amount: float, price: Num = None, params={}):
916
+ return await self.edit_order(id, symbol, 'limit', side, amount, price, params)
917
+
918
+ async def edit_order(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
919
+ await self.cancel_order(id, symbol)
920
+ return await self.create_order(symbol, type, side, amount, price, params)
921
+
922
+ async def edit_order_ws(self, id: str, symbol: str, type: OrderType, side: OrderSide, amount: Num = None, price: Num = None, params={}):
923
+ await self.cancel_order_ws(id, symbol)
924
+ return await self.create_order_ws(symbol, type, side, amount, price, params)
925
+
926
+ async def fetch_position(self, symbol: str, params={}):
927
+ raise NotSupported(self.id + ' fetchPosition() is not supported yet')
928
+
929
+ async def fetch_position_ws(self, symbol: str, params={}):
930
+ raise NotSupported(self.id + ' fetchPositionWs() is not supported yet')
931
+
932
+ async def watch_position(self, symbol: Str = None, params={}):
933
+ raise NotSupported(self.id + ' watchPosition() is not supported yet')
934
+
935
+ async def watch_positions(self, symbols: Strings = None, since: Int = None, limit: Int = None, params={}):
936
+ raise NotSupported(self.id + ' watchPositions() is not supported yet')
937
+
938
+ async def watch_position_for_symbols(self, symbols: Strings = None, since: Int = None, limit: Int = None, params={}):
939
+ return await self.watch_positions(symbols, since, limit, params)
940
+
941
+ async def fetch_positions_for_symbol(self, symbol: str, params={}):
942
+ """
943
+ fetches all open positions for specific symbol, unlike fetchPositions(which is designed to work with multiple symbols) so self method might be preffered for one-market position, because of less rate-limit consumption and speed
944
+ :param str symbol: unified market symbol
945
+ :param dict params: extra parameters specific to the endpoint
946
+ :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>` with maximum 3 items - possible one position for "one-way" mode, and possible two positions(long & short) for "two-way"(a.k.a. hedge) mode
947
+ """
948
+ raise NotSupported(self.id + ' fetchPositionsForSymbol() is not supported yet')
949
+
950
+ async def fetch_positions_for_symbol_ws(self, symbol: str, params={}):
951
+ """
952
+ fetches all open positions for specific symbol, unlike fetchPositions(which is designed to work with multiple symbols) so self method might be preffered for one-market position, because of less rate-limit consumption and speed
953
+ :param str symbol: unified market symbol
954
+ :param dict params: extra parameters specific to the endpoint
955
+ :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>` with maximum 3 items - possible one position for "one-way" mode, and possible two positions(long & short) for "two-way"(a.k.a. hedge) mode
956
+ """
957
+ raise NotSupported(self.id + ' fetchPositionsForSymbol() is not supported yet')
958
+
959
+ async def fetch_positions(self, symbols: Strings = None, params={}):
960
+ raise NotSupported(self.id + ' fetchPositions() is not supported yet')
961
+
962
+ async def fetch_positions_ws(self, symbols: Strings = None, params={}):
963
+ raise NotSupported(self.id + ' fetchPositions() is not supported yet')
964
+
965
+ async def fetch_positions_risk(self, symbols: Strings = None, params={}):
966
+ raise NotSupported(self.id + ' fetchPositionsRisk() is not supported yet')
967
+
968
+ async def fetch_bids_asks(self, symbols: Strings = None, params={}):
969
+ raise NotSupported(self.id + ' fetchBidsAsks() is not supported yet')
970
+
971
+ async def fetch_borrow_interest(self, code: Str = None, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
972
+ raise NotSupported(self.id + ' fetchBorrowInterest() is not supported yet')
973
+
974
+ async def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
975
+ raise NotSupported(self.id + ' fetchLedger() is not supported yet')
976
+
977
+ async def fetch_ledger_entry(self, id: str, code: Str = None, params={}):
978
+ raise NotSupported(self.id + ' fetchLedgerEntry() is not supported yet')
979
+
980
+ async def fetch_balance(self, params={}):
981
+ raise NotSupported(self.id + ' fetchBalance() is not supported yet')
982
+
983
+ async def fetch_balance_ws(self, params={}):
984
+ raise NotSupported(self.id + ' fetchBalanceWs() is not supported yet')
985
+
986
+ async def watch_balance(self, params={}):
987
+ raise NotSupported(self.id + ' watchBalance() is not supported yet')
988
+
989
+ async def fetch_partial_balance(self, part, params={}):
990
+ balance = await self.fetch_balance(params)
991
+ return balance[part]
992
+
993
+ async def fetch_free_balance(self, params={}):
994
+ return await self.fetch_partial_balance('free', params)
995
+
996
+ async def fetch_used_balance(self, params={}):
997
+ return await self.fetch_partial_balance('used', params)
998
+
999
+ async def fetch_total_balance(self, params={}):
1000
+ return await self.fetch_partial_balance('total', params)
1001
+
1002
+ async def fetch_status(self, params={}):
1003
+ raise NotSupported(self.id + ' fetchStatus() is not supported yet')
1004
+
1005
+ async def fetch_transaction_fee(self, code: str, params={}):
1006
+ if not self.has['fetchTransactionFees']:
1007
+ raise NotSupported(self.id + ' fetchTransactionFee() is not supported yet')
1008
+ return await self.fetch_transaction_fees([code], params)
1009
+
1010
+ async def fetch_transaction_fees(self, codes: Strings = None, params={}):
1011
+ raise NotSupported(self.id + ' fetchTransactionFees() is not supported yet')
1012
+
1013
+ async def fetch_deposit_withdraw_fees(self, codes: Strings = None, params={}):
1014
+ raise NotSupported(self.id + ' fetchDepositWithdrawFees() is not supported yet')
1015
+
1016
+ async def fetch_deposit_withdraw_fee(self, code: str, params={}):
1017
+ if not self.has['fetchDepositWithdrawFees']:
1018
+ raise NotSupported(self.id + ' fetchDepositWithdrawFee() is not supported yet')
1019
+ fees = await self.fetch_deposit_withdraw_fees([code], params)
1020
+ return self.safe_value(fees, code)
1021
+
1022
+ async def fetch_cross_borrow_rate(self, code: str, params={}):
1023
+ await self.load_markets()
1024
+ if not self.has['fetchBorrowRates']:
1025
+ raise NotSupported(self.id + ' fetchCrossBorrowRate() is not supported yet')
1026
+ borrowRates = await self.fetch_cross_borrow_rates(params)
1027
+ rate = self.safe_value(borrowRates, code)
1028
+ if rate is None:
1029
+ raise ExchangeError(self.id + ' fetchCrossBorrowRate() could not find the borrow rate for currency code ' + code)
1030
+ return rate
1031
+
1032
+ async def fetch_isolated_borrow_rate(self, symbol: str, params={}):
1033
+ await self.load_markets()
1034
+ if not self.has['fetchBorrowRates']:
1035
+ raise NotSupported(self.id + ' fetchIsolatedBorrowRate() is not supported yet')
1036
+ borrowRates = await self.fetch_isolated_borrow_rates(params)
1037
+ rate = self.safe_dict(borrowRates, symbol)
1038
+ if rate is None:
1039
+ raise ExchangeError(self.id + ' fetchIsolatedBorrowRate() could not find the borrow rate for market symbol ' + symbol)
1040
+ return rate
1041
+
1042
+ async def fetch_ticker(self, symbol: str, params={}):
1043
+ if self.has['fetchTickers']:
1044
+ await self.load_markets()
1045
+ market = self.market(symbol)
1046
+ symbol = market['symbol']
1047
+ tickers = await self.fetch_tickers([symbol], params)
1048
+ ticker = self.safe_dict(tickers, symbol)
1049
+ if ticker is None:
1050
+ raise NullResponse(self.id + ' fetchTickers() could not find a ticker for ' + symbol)
1051
+ else:
1052
+ return ticker
1053
+ else:
1054
+ raise NotSupported(self.id + ' fetchTicker() is not supported yet')
1055
+
1056
+ async def fetch_mark_price(self, symbol: str, params={}):
1057
+ if self.has['fetchMarkPrices']:
1058
+ await self.load_markets()
1059
+ market = self.market(symbol)
1060
+ symbol = market['symbol']
1061
+ tickers = await self.fetch_mark_prices([symbol], params)
1062
+ ticker = self.safe_dict(tickers, symbol)
1063
+ if ticker is None:
1064
+ raise NullResponse(self.id + ' fetchMarkPrices() could not find a ticker for ' + symbol)
1065
+ else:
1066
+ return ticker
1067
+ else:
1068
+ raise NotSupported(self.id + ' fetchMarkPrices() is not supported yet')
1069
+
1070
+ async def fetch_ticker_ws(self, symbol: str, params={}):
1071
+ if self.has['fetchTickersWs']:
1072
+ await self.load_markets()
1073
+ market = self.market(symbol)
1074
+ symbol = market['symbol']
1075
+ tickers = await self.fetch_tickers_ws([symbol], params)
1076
+ ticker = self.safe_dict(tickers, symbol)
1077
+ if ticker is None:
1078
+ raise NullResponse(self.id + ' fetchTickerWs() could not find a ticker for ' + symbol)
1079
+ else:
1080
+ return ticker
1081
+ else:
1082
+ raise NotSupported(self.id + ' fetchTickerWs() is not supported yet')
1083
+
1084
+ async def watch_ticker(self, symbol: str, params={}):
1085
+ raise NotSupported(self.id + ' watchTicker() is not supported yet')
1086
+
1087
+ async def fetch_tickers(self, symbols: Strings = None, params={}):
1088
+ raise NotSupported(self.id + ' fetchTickers() is not supported yet')
1089
+
1090
+ async def fetch_mark_prices(self, symbols: Strings = None, params={}):
1091
+ raise NotSupported(self.id + ' fetchMarkPrices() is not supported yet')
1092
+
1093
+ async def fetch_tickers_ws(self, symbols: Strings = None, params={}):
1094
+ raise NotSupported(self.id + ' fetchTickers() is not supported yet')
1095
+
1096
+ async def fetch_order_books(self, symbols: Strings = None, limit: Int = None, params={}):
1097
+ raise NotSupported(self.id + ' fetchOrderBooks() is not supported yet')
1098
+
1099
+ async def watch_bids_asks(self, symbols: Strings = None, params={}):
1100
+ raise NotSupported(self.id + ' watchBidsAsks() is not supported yet')
1101
+
1102
+ async def watch_tickers(self, symbols: Strings = None, params={}):
1103
+ raise NotSupported(self.id + ' watchTickers() is not supported yet')
1104
+
1105
+ async def un_watch_tickers(self, symbols: Strings = None, params={}):
1106
+ raise NotSupported(self.id + ' unWatchTickers() is not supported yet')
1107
+
1108
+ async def fetch_order(self, id: str, symbol: Str = None, params={}):
1109
+ raise NotSupported(self.id + ' fetchOrder() is not supported yet')
1110
+
1111
+ async def fetch_order_ws(self, id: str, symbol: Str = None, params={}):
1112
+ raise NotSupported(self.id + ' fetchOrderWs() is not supported yet')
1113
+
1114
+ async def fetch_order_status(self, id: str, symbol: Str = None, params={}):
1115
+ # TODO: TypeScript: change method signature by replacing
1116
+ # Promise<string> with Promise<Order['status']>.
1117
+ order = await self.fetch_order(id, symbol, params)
1118
+ return order['status']
1119
+
1120
+ async def fetch_unified_order(self, order, params={}):
1121
+ return await self.fetch_order(self.safe_string(order, 'id'), self.safe_string(order, 'symbol'), params)
1122
+
1123
+ async def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1124
+ raise NotSupported(self.id + ' createOrder() is not supported yet')
1125
+
1126
+ async def create_convert_trade(self, id: str, fromCode: str, toCode: str, amount: Num = None, params={}):
1127
+ raise NotSupported(self.id + ' createConvertTrade() is not supported yet')
1128
+
1129
+ async def fetch_convert_trade(self, id: str, code: Str = None, params={}):
1130
+ raise NotSupported(self.id + ' fetchConvertTrade() is not supported yet')
1131
+
1132
+ async def fetch_convert_trade_history(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
1133
+ raise NotSupported(self.id + ' fetchConvertTradeHistory() is not supported yet')
1134
+
1135
+ async def fetch_position_mode(self, symbol: Str = None, params={}):
1136
+ raise NotSupported(self.id + ' fetchPositionMode() is not supported yet')
1137
+
1138
+ async def create_trailing_amount_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingAmount=None, trailingTriggerPrice=None, params={}):
1139
+ """
1140
+ create a trailing order by providing the symbol, type, side, amount, price and trailingAmount
1141
+ :param str symbol: unified symbol of the market to create an order in
1142
+ :param str type: 'market' or 'limit'
1143
+ :param str side: 'buy' or 'sell'
1144
+ :param float amount: how much you want to trade in units of the base currency, or number of contracts
1145
+ :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
1146
+ :param float trailingAmount: the quote amount to trail away from the current market price
1147
+ :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument
1148
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1149
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1150
+ """
1151
+ if trailingAmount is None:
1152
+ raise ArgumentsRequired(self.id + ' createTrailingAmountOrder() requires a trailingAmount argument')
1153
+ params['trailingAmount'] = trailingAmount
1154
+ if trailingTriggerPrice is not None:
1155
+ params['trailingTriggerPrice'] = trailingTriggerPrice
1156
+ if self.has['createTrailingAmountOrder']:
1157
+ return await self.create_order(symbol, type, side, amount, price, params)
1158
+ raise NotSupported(self.id + ' createTrailingAmountOrder() is not supported yet')
1159
+
1160
+ async def create_trailing_amount_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingAmount=None, trailingTriggerPrice=None, params={}):
1161
+ """
1162
+ create a trailing order by providing the symbol, type, side, amount, price and trailingAmount
1163
+ :param str symbol: unified symbol of the market to create an order in
1164
+ :param str type: 'market' or 'limit'
1165
+ :param str side: 'buy' or 'sell'
1166
+ :param float amount: how much you want to trade in units of the base currency, or number of contracts
1167
+ :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
1168
+ :param float trailingAmount: the quote amount to trail away from the current market price
1169
+ :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument
1170
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1171
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1172
+ """
1173
+ if trailingAmount is None:
1174
+ raise ArgumentsRequired(self.id + ' createTrailingAmountOrderWs() requires a trailingAmount argument')
1175
+ params['trailingAmount'] = trailingAmount
1176
+ if trailingTriggerPrice is not None:
1177
+ params['trailingTriggerPrice'] = trailingTriggerPrice
1178
+ if self.has['createTrailingAmountOrderWs']:
1179
+ return await self.create_order_ws(symbol, type, side, amount, price, params)
1180
+ raise NotSupported(self.id + ' createTrailingAmountOrderWs() is not supported yet')
1181
+
1182
+ async def create_trailing_percent_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingPercent=None, trailingTriggerPrice=None, params={}):
1183
+ """
1184
+ create a trailing order by providing the symbol, type, side, amount, price and trailingPercent
1185
+ :param str symbol: unified symbol of the market to create an order in
1186
+ :param str type: 'market' or 'limit'
1187
+ :param str side: 'buy' or 'sell'
1188
+ :param float amount: how much you want to trade in units of the base currency, or number of contracts
1189
+ :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
1190
+ :param float trailingPercent: the percent to trail away from the current market price
1191
+ :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument
1192
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1193
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1194
+ """
1195
+ if trailingPercent is None:
1196
+ raise ArgumentsRequired(self.id + ' createTrailingPercentOrder() requires a trailingPercent argument')
1197
+ params['trailingPercent'] = trailingPercent
1198
+ if trailingTriggerPrice is not None:
1199
+ params['trailingTriggerPrice'] = trailingTriggerPrice
1200
+ if self.has['createTrailingPercentOrder']:
1201
+ return await self.create_order(symbol, type, side, amount, price, params)
1202
+ raise NotSupported(self.id + ' createTrailingPercentOrder() is not supported yet')
1203
+
1204
+ async def create_trailing_percent_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, trailingPercent=None, trailingTriggerPrice=None, params={}):
1205
+ """
1206
+ create a trailing order by providing the symbol, type, side, amount, price and trailingPercent
1207
+ :param str symbol: unified symbol of the market to create an order in
1208
+ :param str type: 'market' or 'limit'
1209
+ :param str side: 'buy' or 'sell'
1210
+ :param float amount: how much you want to trade in units of the base currency, or number of contracts
1211
+ :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders
1212
+ :param float trailingPercent: the percent to trail away from the current market price
1213
+ :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument
1214
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1215
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1216
+ """
1217
+ if trailingPercent is None:
1218
+ raise ArgumentsRequired(self.id + ' createTrailingPercentOrderWs() requires a trailingPercent argument')
1219
+ params['trailingPercent'] = trailingPercent
1220
+ if trailingTriggerPrice is not None:
1221
+ params['trailingTriggerPrice'] = trailingTriggerPrice
1222
+ if self.has['createTrailingPercentOrderWs']:
1223
+ return await self.create_order_ws(symbol, type, side, amount, price, params)
1224
+ raise NotSupported(self.id + ' createTrailingPercentOrderWs() is not supported yet')
1225
+
1226
+ async def create_market_order_with_cost(self, symbol: str, side: OrderSide, cost: float, params={}):
1227
+ """
1228
+ create a market order by providing the symbol, side and cost
1229
+ :param str symbol: unified symbol of the market to create an order in
1230
+ :param str side: 'buy' or 'sell'
1231
+ :param float cost: how much you want to trade in units of the quote currency
1232
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1233
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1234
+ """
1235
+ if self.has['createMarketOrderWithCost'] or (self.has['createMarketBuyOrderWithCost'] and self.has['createMarketSellOrderWithCost']):
1236
+ return await self.create_order(symbol, 'market', side, cost, 1, params)
1237
+ raise NotSupported(self.id + ' createMarketOrderWithCost() is not supported yet')
1238
+
1239
+ async def create_market_buy_order_with_cost(self, symbol: str, cost: float, params={}):
1240
+ """
1241
+ create a market buy order by providing the symbol and cost
1242
+ :param str symbol: unified symbol of the market to create an order in
1243
+ :param float cost: how much you want to trade in units of the quote currency
1244
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1245
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1246
+ """
1247
+ if self.options['createMarketBuyOrderRequiresPrice'] or self.has['createMarketBuyOrderWithCost']:
1248
+ return await self.create_order(symbol, 'market', 'buy', cost, 1, params)
1249
+ raise NotSupported(self.id + ' createMarketBuyOrderWithCost() is not supported yet')
1250
+
1251
+ async def create_market_sell_order_with_cost(self, symbol: str, cost: float, params={}):
1252
+ """
1253
+ create a market sell order by providing the symbol and cost
1254
+ :param str symbol: unified symbol of the market to create an order in
1255
+ :param float cost: how much you want to trade in units of the quote currency
1256
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1257
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1258
+ """
1259
+ if self.options['createMarketSellOrderRequiresPrice'] or self.has['createMarketSellOrderWithCost']:
1260
+ return await self.create_order(symbol, 'market', 'sell', cost, 1, params)
1261
+ raise NotSupported(self.id + ' createMarketSellOrderWithCost() is not supported yet')
1262
+
1263
+ async def create_market_order_with_cost_ws(self, symbol: str, side: OrderSide, cost: float, params={}):
1264
+ """
1265
+ create a market order by providing the symbol, side and cost
1266
+ :param str symbol: unified symbol of the market to create an order in
1267
+ :param str side: 'buy' or 'sell'
1268
+ :param float cost: how much you want to trade in units of the quote currency
1269
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1270
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1271
+ """
1272
+ if self.has['createMarketOrderWithCostWs'] or (self.has['createMarketBuyOrderWithCostWs'] and self.has['createMarketSellOrderWithCostWs']):
1273
+ return await self.create_order_ws(symbol, 'market', side, cost, 1, params)
1274
+ raise NotSupported(self.id + ' createMarketOrderWithCostWs() is not supported yet')
1275
+
1276
+ async def create_trigger_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, triggerPrice: Num = None, params={}):
1277
+ """
1278
+ create a trigger stop order(type 1)
1279
+ :param str symbol: unified symbol of the market to create an order in
1280
+ :param str type: 'market' or 'limit'
1281
+ :param str side: 'buy' or 'sell'
1282
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1283
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1284
+ :param float triggerPrice: the price to trigger the stop order, in units of the quote currency
1285
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1286
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1287
+ """
1288
+ if triggerPrice is None:
1289
+ raise ArgumentsRequired(self.id + ' createTriggerOrder() requires a triggerPrice argument')
1290
+ params['triggerPrice'] = triggerPrice
1291
+ if self.has['createTriggerOrder']:
1292
+ return await self.create_order(symbol, type, side, amount, price, params)
1293
+ raise NotSupported(self.id + ' createTriggerOrder() is not supported yet')
1294
+
1295
+ async def create_trigger_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, triggerPrice: Num = None, params={}):
1296
+ """
1297
+ create a trigger stop order(type 1)
1298
+ :param str symbol: unified symbol of the market to create an order in
1299
+ :param str type: 'market' or 'limit'
1300
+ :param str side: 'buy' or 'sell'
1301
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1302
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1303
+ :param float triggerPrice: the price to trigger the stop order, in units of the quote currency
1304
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1305
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1306
+ """
1307
+ if triggerPrice is None:
1308
+ raise ArgumentsRequired(self.id + ' createTriggerOrderWs() requires a triggerPrice argument')
1309
+ params['triggerPrice'] = triggerPrice
1310
+ if self.has['createTriggerOrderWs']:
1311
+ return await self.create_order_ws(symbol, type, side, amount, price, params)
1312
+ raise NotSupported(self.id + ' createTriggerOrderWs() is not supported yet')
1313
+
1314
+ async def create_stop_loss_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, stopLossPrice: Num = None, params={}):
1315
+ """
1316
+ create a trigger stop loss order(type 2)
1317
+ :param str symbol: unified symbol of the market to create an order in
1318
+ :param str type: 'market' or 'limit'
1319
+ :param str side: 'buy' or 'sell'
1320
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1321
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1322
+ :param float stopLossPrice: the price to trigger the stop loss order, in units of the quote currency
1323
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1324
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1325
+ """
1326
+ if stopLossPrice is None:
1327
+ raise ArgumentsRequired(self.id + ' createStopLossOrder() requires a stopLossPrice argument')
1328
+ params['stopLossPrice'] = stopLossPrice
1329
+ if self.has['createStopLossOrder']:
1330
+ return await self.create_order(symbol, type, side, amount, price, params)
1331
+ raise NotSupported(self.id + ' createStopLossOrder() is not supported yet')
1332
+
1333
+ async def create_stop_loss_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, stopLossPrice: Num = None, params={}):
1334
+ """
1335
+ create a trigger stop loss order(type 2)
1336
+ :param str symbol: unified symbol of the market to create an order in
1337
+ :param str type: 'market' or 'limit'
1338
+ :param str side: 'buy' or 'sell'
1339
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1340
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1341
+ :param float stopLossPrice: the price to trigger the stop loss order, in units of the quote currency
1342
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1343
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1344
+ """
1345
+ if stopLossPrice is None:
1346
+ raise ArgumentsRequired(self.id + ' createStopLossOrderWs() requires a stopLossPrice argument')
1347
+ params['stopLossPrice'] = stopLossPrice
1348
+ if self.has['createStopLossOrderWs']:
1349
+ return await self.create_order_ws(symbol, type, side, amount, price, params)
1350
+ raise NotSupported(self.id + ' createStopLossOrderWs() is not supported yet')
1351
+
1352
+ async def create_take_profit_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, takeProfitPrice: Num = None, params={}):
1353
+ """
1354
+ create a trigger take profit order(type 2)
1355
+ :param str symbol: unified symbol of the market to create an order in
1356
+ :param str type: 'market' or 'limit'
1357
+ :param str side: 'buy' or 'sell'
1358
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1359
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1360
+ :param float takeProfitPrice: the price to trigger the take profit order, in units of the quote currency
1361
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1362
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1363
+ """
1364
+ if takeProfitPrice is None:
1365
+ raise ArgumentsRequired(self.id + ' createTakeProfitOrder() requires a takeProfitPrice argument')
1366
+ params['takeProfitPrice'] = takeProfitPrice
1367
+ if self.has['createTakeProfitOrder']:
1368
+ return await self.create_order(symbol, type, side, amount, price, params)
1369
+ raise NotSupported(self.id + ' createTakeProfitOrder() is not supported yet')
1370
+
1371
+ async def create_take_profit_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, takeProfitPrice: Num = None, params={}):
1372
+ """
1373
+ create a trigger take profit order(type 2)
1374
+ :param str symbol: unified symbol of the market to create an order in
1375
+ :param str type: 'market' or 'limit'
1376
+ :param str side: 'buy' or 'sell'
1377
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1378
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1379
+ :param float takeProfitPrice: the price to trigger the take profit order, in units of the quote currency
1380
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1381
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1382
+ """
1383
+ if takeProfitPrice is None:
1384
+ raise ArgumentsRequired(self.id + ' createTakeProfitOrderWs() requires a takeProfitPrice argument')
1385
+ params['takeProfitPrice'] = takeProfitPrice
1386
+ if self.has['createTakeProfitOrderWs']:
1387
+ return await self.create_order_ws(symbol, type, side, amount, price, params)
1388
+ raise NotSupported(self.id + ' createTakeProfitOrderWs() is not supported yet')
1389
+
1390
+ async def create_order_with_take_profit_and_stop_loss(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, takeProfit: Num = None, stopLoss: Num = None, params={}):
1391
+ """
1392
+ create an order with a stop loss or take profit attached(type 3)
1393
+ :param str symbol: unified symbol of the market to create an order in
1394
+ :param str type: 'market' or 'limit'
1395
+ :param str side: 'buy' or 'sell'
1396
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1397
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1398
+ :param float [takeProfit]: the take profit price, in units of the quote currency
1399
+ :param float [stopLoss]: the stop loss price, in units of the quote currency
1400
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1401
+ :param str [params.takeProfitType]: *not available on all exchanges* 'limit' or 'market'
1402
+ :param str [params.stopLossType]: *not available on all exchanges* 'limit' or 'market'
1403
+ :param str [params.takeProfitPriceType]: *not available on all exchanges* 'last', 'mark' or 'index'
1404
+ :param str [params.stopLossPriceType]: *not available on all exchanges* 'last', 'mark' or 'index'
1405
+ :param float [params.takeProfitLimitPrice]: *not available on all exchanges* limit price for a limit take profit order
1406
+ :param float [params.stopLossLimitPrice]: *not available on all exchanges* stop loss for a limit stop loss order
1407
+ :param float [params.takeProfitAmount]: *not available on all exchanges* the amount for a take profit
1408
+ :param float [params.stopLossAmount]: *not available on all exchanges* the amount for a stop loss
1409
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1410
+ """
1411
+ params = self.set_take_profit_and_stop_loss_params(symbol, type, side, amount, price, takeProfit, stopLoss, params)
1412
+ if self.has['createOrderWithTakeProfitAndStopLoss']:
1413
+ return await self.create_order(symbol, type, side, amount, price, params)
1414
+ raise NotSupported(self.id + ' createOrderWithTakeProfitAndStopLoss() is not supported yet')
1415
+
1416
+ async def create_order_with_take_profit_and_stop_loss_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, takeProfit: Num = None, stopLoss: Num = None, params={}):
1417
+ """
1418
+ create an order with a stop loss or take profit attached(type 3)
1419
+ :param str symbol: unified symbol of the market to create an order in
1420
+ :param str type: 'market' or 'limit'
1421
+ :param str side: 'buy' or 'sell'
1422
+ :param float amount: how much you want to trade in units of the base currency or the number of contracts
1423
+ :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders
1424
+ :param float [takeProfit]: the take profit price, in units of the quote currency
1425
+ :param float [stopLoss]: the stop loss price, in units of the quote currency
1426
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1427
+ :param str [params.takeProfitType]: *not available on all exchanges* 'limit' or 'market'
1428
+ :param str [params.stopLossType]: *not available on all exchanges* 'limit' or 'market'
1429
+ :param str [params.takeProfitPriceType]: *not available on all exchanges* 'last', 'mark' or 'index'
1430
+ :param str [params.stopLossPriceType]: *not available on all exchanges* 'last', 'mark' or 'index'
1431
+ :param float [params.takeProfitLimitPrice]: *not available on all exchanges* limit price for a limit take profit order
1432
+ :param float [params.stopLossLimitPrice]: *not available on all exchanges* stop loss for a limit stop loss order
1433
+ :param float [params.takeProfitAmount]: *not available on all exchanges* the amount for a take profit
1434
+ :param float [params.stopLossAmount]: *not available on all exchanges* the amount for a stop loss
1435
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1436
+ """
1437
+ params = self.set_take_profit_and_stop_loss_params(symbol, type, side, amount, price, takeProfit, stopLoss, params)
1438
+ if self.has['createOrderWithTakeProfitAndStopLossWs']:
1439
+ return await self.create_order_ws(symbol, type, side, amount, price, params)
1440
+ raise NotSupported(self.id + ' createOrderWithTakeProfitAndStopLossWs() is not supported yet')
1441
+
1442
+ async def create_orders(self, orders: List[OrderRequest], params={}):
1443
+ raise NotSupported(self.id + ' createOrders() is not supported yet')
1444
+
1445
+ async def edit_orders(self, orders: List[OrderRequest], params={}):
1446
+ raise NotSupported(self.id + ' editOrders() is not supported yet')
1447
+
1448
+ async def create_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1449
+ raise NotSupported(self.id + ' createOrderWs() is not supported yet')
1450
+
1451
+ async def cancel_order(self, id: str, symbol: Str = None, params={}):
1452
+ raise NotSupported(self.id + ' cancelOrder() is not supported yet')
1453
+
1454
+ async def cancel_order_ws(self, id: str, symbol: Str = None, params={}):
1455
+ raise NotSupported(self.id + ' cancelOrderWs() is not supported yet')
1456
+
1457
+ async def cancel_orders_ws(self, ids: List[str], symbol: Str = None, params={}):
1458
+ raise NotSupported(self.id + ' cancelOrdersWs() is not supported yet')
1459
+
1460
+ async def cancel_all_orders(self, symbol: Str = None, params={}):
1461
+ raise NotSupported(self.id + ' cancelAllOrders() is not supported yet')
1462
+
1463
+ async def cancel_all_orders_after(self, timeout: Int, params={}):
1464
+ raise NotSupported(self.id + ' cancelAllOrdersAfter() is not supported yet')
1465
+
1466
+ async def cancel_orders_for_symbols(self, orders: List[CancellationRequest], params={}):
1467
+ raise NotSupported(self.id + ' cancelOrdersForSymbols() is not supported yet')
1468
+
1469
+ async def cancel_all_orders_ws(self, symbol: Str = None, params={}):
1470
+ raise NotSupported(self.id + ' cancelAllOrdersWs() is not supported yet')
1471
+
1472
+ async def cancel_unified_order(self, order, params={}):
1473
+ return self.cancel_order(self.safe_string(order, 'id'), self.safe_string(order, 'symbol'), params)
1474
+
1475
+ async def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1476
+ if self.has['fetchOpenOrders'] and self.has['fetchClosedOrders']:
1477
+ raise NotSupported(self.id + ' fetchOrders() is not supported yet, consider using fetchOpenOrders() and fetchClosedOrders() instead')
1478
+ raise NotSupported(self.id + ' fetchOrders() is not supported yet')
1479
+
1480
+ async def fetch_orders_ws(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1481
+ raise NotSupported(self.id + ' fetchOrdersWs() is not supported yet')
1482
+
1483
+ async def fetch_order_trades(self, id: str, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1484
+ raise NotSupported(self.id + ' fetchOrderTrades() is not supported yet')
1485
+
1486
+ async def watch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1487
+ raise NotSupported(self.id + ' watchOrders() is not supported yet')
1488
+
1489
+ async def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1490
+ if self.has['fetchOrders']:
1491
+ orders = await self.fetch_orders(symbol, since, limit, params)
1492
+ return self.filter_by(orders, 'status', 'open')
1493
+ raise NotSupported(self.id + ' fetchOpenOrders() is not supported yet')
1494
+
1495
+ async def fetch_open_orders_ws(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1496
+ if self.has['fetchOrdersWs']:
1497
+ orders = await self.fetch_orders_ws(symbol, since, limit, params)
1498
+ return self.filter_by(orders, 'status', 'open')
1499
+ raise NotSupported(self.id + ' fetchOpenOrdersWs() is not supported yet')
1500
+
1501
+ async def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1502
+ if self.has['fetchOrders']:
1503
+ orders = await self.fetch_orders(symbol, since, limit, params)
1504
+ return self.filter_by(orders, 'status', 'closed')
1505
+ raise NotSupported(self.id + ' fetchClosedOrders() is not supported yet')
1506
+
1507
+ async def fetch_canceled_and_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1508
+ raise NotSupported(self.id + ' fetchCanceledAndClosedOrders() is not supported yet')
1509
+
1510
+ async def fetch_closed_orders_ws(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1511
+ if self.has['fetchOrdersWs']:
1512
+ orders = await self.fetch_orders_ws(symbol, since, limit, params)
1513
+ return self.filter_by(orders, 'status', 'closed')
1514
+ raise NotSupported(self.id + ' fetchClosedOrdersWs() is not supported yet')
1515
+
1516
+ async def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1517
+ raise NotSupported(self.id + ' fetchMyTrades() is not supported yet')
1518
+
1519
+ async def fetch_my_liquidations(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1520
+ raise NotSupported(self.id + ' fetchMyLiquidations() is not supported yet')
1521
+
1522
+ async def fetch_liquidations(self, symbol: str, since: Int = None, limit: Int = None, params={}):
1523
+ raise NotSupported(self.id + ' fetchLiquidations() is not supported yet')
1524
+
1525
+ async def fetch_my_trades_ws(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1526
+ raise NotSupported(self.id + ' fetchMyTradesWs() is not supported yet')
1527
+
1528
+ async def watch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1529
+ raise NotSupported(self.id + ' watchMyTrades() is not supported yet')
1530
+
1531
+ async def fetch_greeks(self, symbol: str, params={}):
1532
+ raise NotSupported(self.id + ' fetchGreeks() is not supported yet')
1533
+
1534
+ async def fetch_option_chain(self, code: str, params={}):
1535
+ raise NotSupported(self.id + ' fetchOptionChain() is not supported yet')
1536
+
1537
+ async def fetch_option(self, symbol: str, params={}):
1538
+ raise NotSupported(self.id + ' fetchOption() is not supported yet')
1539
+
1540
+ async def fetch_convert_quote(self, fromCode: str, toCode: str, amount: Num = None, params={}):
1541
+ raise NotSupported(self.id + ' fetchConvertQuote() is not supported yet')
1542
+
1543
+ async def fetch_deposits_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
1544
+ """
1545
+ fetch history of deposits and withdrawals
1546
+ :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
1547
+ :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
1548
+ :param int [limit]: max number of deposit/withdrawals to return, default is None
1549
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1550
+ :returns dict: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
1551
+ """
1552
+ raise NotSupported(self.id + ' fetchDepositsWithdrawals() is not supported yet')
1553
+
1554
+ async def fetch_deposits(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1555
+ raise NotSupported(self.id + ' fetchDeposits() is not supported yet')
1556
+
1557
+ async def fetch_withdrawals(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1558
+ raise NotSupported(self.id + ' fetchWithdrawals() is not supported yet')
1559
+
1560
+ async def fetch_deposits_ws(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
1561
+ raise NotSupported(self.id + ' fetchDepositsWs() is not supported yet')
1562
+
1563
+ async def fetch_withdrawals_ws(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
1564
+ raise NotSupported(self.id + ' fetchWithdrawalsWs() is not supported yet')
1565
+
1566
+ async def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1567
+ raise NotSupported(self.id + ' fetchFundingRateHistory() is not supported yet')
1568
+
1569
+ async def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1570
+ raise NotSupported(self.id + ' fetchFundingHistory() is not supported yet')
1571
+
1572
+ async def close_position(self, symbol: str, side: OrderSide = None, params={}):
1573
+ raise NotSupported(self.id + ' closePosition() is not supported yet')
1574
+
1575
+ async def close_all_positions(self, params={}):
1576
+ raise NotSupported(self.id + ' closeAllPositions() is not supported yet')
1577
+
1578
+ async def fetch_l3_order_book(self, symbol: str, limit: Int = None, params={}):
1579
+ raise BadRequest(self.id + ' fetchL3OrderBook() is not supported yet')
1580
+
1581
+ async def fetch_deposit_address(self, code: str, params={}):
1582
+ if self.has['fetchDepositAddresses']:
1583
+ depositAddresses = await self.fetch_deposit_addresses([code], params)
1584
+ depositAddress = self.safe_value(depositAddresses, code)
1585
+ if depositAddress is None:
1586
+ raise InvalidAddress(self.id + ' fetchDepositAddress() could not find a deposit address for ' + code + ', make sure you have created a corresponding deposit address in your wallet on the exchange website')
1587
+ else:
1588
+ return depositAddress
1589
+ elif self.has['fetchDepositAddressesByNetwork']:
1590
+ network = self.safe_string(params, 'network')
1591
+ params = self.omit(params, 'network')
1592
+ addressStructures = await self.fetch_deposit_addresses_by_network(code, params)
1593
+ if network is not None:
1594
+ return self.safe_dict(addressStructures, network)
1595
+ else:
1596
+ keys = list(addressStructures.keys())
1597
+ key = self.safe_string(keys, 0)
1598
+ return self.safe_dict(addressStructures, key)
1599
+ else:
1600
+ raise NotSupported(self.id + ' fetchDepositAddress() is not supported yet')
1601
+
1602
+ async def create_limit_order(self, symbol: str, side: OrderSide, amount: float, price: float, params={}):
1603
+ return await self.create_order(symbol, 'limit', side, amount, price, params)
1604
+
1605
+ async def create_limit_order_ws(self, symbol: str, side: OrderSide, amount: float, price: float, params={}):
1606
+ return await self.create_order_ws(symbol, 'limit', side, amount, price, params)
1607
+
1608
+ async def create_market_order(self, symbol: str, side: OrderSide, amount: float, price: Num = None, params={}):
1609
+ return await self.create_order(symbol, 'market', side, amount, price, params)
1610
+
1611
+ async def create_market_order_ws(self, symbol: str, side: OrderSide, amount: float, price: Num = None, params={}):
1612
+ return await self.create_order_ws(symbol, 'market', side, amount, price, params)
1613
+
1614
+ async def create_limit_buy_order(self, symbol: str, amount: float, price: float, params={}):
1615
+ return await self.create_order(symbol, 'limit', 'buy', amount, price, params)
1616
+
1617
+ async def create_limit_buy_order_ws(self, symbol: str, amount: float, price: float, params={}):
1618
+ return await self.create_order_ws(symbol, 'limit', 'buy', amount, price, params)
1619
+
1620
+ async def create_limit_sell_order(self, symbol: str, amount: float, price: float, params={}):
1621
+ return await self.create_order(symbol, 'limit', 'sell', amount, price, params)
1622
+
1623
+ async def create_limit_sell_order_ws(self, symbol: str, amount: float, price: float, params={}):
1624
+ return await self.create_order_ws(symbol, 'limit', 'sell', amount, price, params)
1625
+
1626
+ async def create_market_buy_order(self, symbol: str, amount: float, params={}):
1627
+ return await self.create_order(symbol, 'market', 'buy', amount, None, params)
1628
+
1629
+ async def create_market_buy_order_ws(self, symbol: str, amount: float, params={}):
1630
+ return await self.create_order_ws(symbol, 'market', 'buy', amount, None, params)
1631
+
1632
+ async def create_market_sell_order(self, symbol: str, amount: float, params={}):
1633
+ return await self.create_order(symbol, 'market', 'sell', amount, None, params)
1634
+
1635
+ async def create_market_sell_order_ws(self, symbol: str, amount: float, params={}):
1636
+ return await self.create_order_ws(symbol, 'market', 'sell', amount, None, params)
1637
+
1638
+ async def load_time_difference(self, params={}):
1639
+ serverTime = await self.fetch_time(params)
1640
+ after = self.milliseconds()
1641
+ self.options['timeDifference'] = after - serverTime
1642
+ return self.options['timeDifference']
1643
+
1644
+ async def fetch_market_leverage_tiers(self, symbol: str, params={}):
1645
+ if self.has['fetchLeverageTiers']:
1646
+ market = self.market(symbol)
1647
+ if not market['contract']:
1648
+ raise BadSymbol(self.id + ' fetchMarketLeverageTiers() supports contract markets only')
1649
+ tiers = await self.fetch_leverage_tiers([symbol])
1650
+ return self.safe_value(tiers, symbol)
1651
+ else:
1652
+ raise NotSupported(self.id + ' fetchMarketLeverageTiers() is not supported yet')
1653
+
1654
+ async def create_post_only_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1655
+ if not self.has['createPostOnlyOrder']:
1656
+ raise NotSupported(self.id + ' createPostOnlyOrder() is not supported yet')
1657
+ query = self.extend(params, {'postOnly': True})
1658
+ return await self.create_order(symbol, type, side, amount, price, query)
1659
+
1660
+ async def create_post_only_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1661
+ if not self.has['createPostOnlyOrderWs']:
1662
+ raise NotSupported(self.id + ' createPostOnlyOrderWs() is not supported yet')
1663
+ query = self.extend(params, {'postOnly': True})
1664
+ return await self.create_order_ws(symbol, type, side, amount, price, query)
1665
+
1666
+ async def create_reduce_only_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1667
+ if not self.has['createReduceOnlyOrder']:
1668
+ raise NotSupported(self.id + ' createReduceOnlyOrder() is not supported yet')
1669
+ query = self.extend(params, {'reduceOnly': True})
1670
+ return await self.create_order(symbol, type, side, amount, price, query)
1671
+
1672
+ async def create_reduce_only_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1673
+ if not self.has['createReduceOnlyOrderWs']:
1674
+ raise NotSupported(self.id + ' createReduceOnlyOrderWs() is not supported yet')
1675
+ query = self.extend(params, {'reduceOnly': True})
1676
+ return await self.create_order_ws(symbol, type, side, amount, price, query)
1677
+
1678
+ async def create_stop_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, triggerPrice: Num = None, params={}):
1679
+ if not self.has['createStopOrder']:
1680
+ raise NotSupported(self.id + ' createStopOrder() is not supported yet')
1681
+ if triggerPrice is None:
1682
+ raise ArgumentsRequired(self.id + ' create_stop_order() requires a stopPrice argument')
1683
+ query = self.extend(params, {'stopPrice': triggerPrice})
1684
+ return await self.create_order(symbol, type, side, amount, price, query)
1685
+
1686
+ async def create_stop_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, triggerPrice: Num = None, params={}):
1687
+ if not self.has['createStopOrderWs']:
1688
+ raise NotSupported(self.id + ' createStopOrderWs() is not supported yet')
1689
+ if triggerPrice is None:
1690
+ raise ArgumentsRequired(self.id + ' createStopOrderWs() requires a stopPrice argument')
1691
+ query = self.extend(params, {'stopPrice': triggerPrice})
1692
+ return await self.create_order_ws(symbol, type, side, amount, price, query)
1693
+
1694
+ async def create_stop_limit_order(self, symbol: str, side: OrderSide, amount: float, price: float, triggerPrice: float, params={}):
1695
+ if not self.has['createStopLimitOrder']:
1696
+ raise NotSupported(self.id + ' createStopLimitOrder() is not supported yet')
1697
+ query = self.extend(params, {'stopPrice': triggerPrice})
1698
+ return await self.create_order(symbol, 'limit', side, amount, price, query)
1699
+
1700
+ async def create_stop_limit_order_ws(self, symbol: str, side: OrderSide, amount: float, price: float, triggerPrice: float, params={}):
1701
+ if not self.has['createStopLimitOrderWs']:
1702
+ raise NotSupported(self.id + ' createStopLimitOrderWs() is not supported yet')
1703
+ query = self.extend(params, {'stopPrice': triggerPrice})
1704
+ return await self.create_order_ws(symbol, 'limit', side, amount, price, query)
1705
+
1706
+ async def create_stop_market_order(self, symbol: str, side: OrderSide, amount: float, triggerPrice: float, params={}):
1707
+ if not self.has['createStopMarketOrder']:
1708
+ raise NotSupported(self.id + ' createStopMarketOrder() is not supported yet')
1709
+ query = self.extend(params, {'stopPrice': triggerPrice})
1710
+ return await self.create_order(symbol, 'market', side, amount, None, query)
1711
+
1712
+ async def create_stop_market_order_ws(self, symbol: str, side: OrderSide, amount: float, triggerPrice: float, params={}):
1713
+ if not self.has['createStopMarketOrderWs']:
1714
+ raise NotSupported(self.id + ' createStopMarketOrderWs() is not supported yet')
1715
+ query = self.extend(params, {'stopPrice': triggerPrice})
1716
+ return await self.create_order_ws(symbol, 'market', side, amount, None, query)
1717
+
1718
+ async def fetch_last_prices(self, symbols: Strings = None, params={}):
1719
+ raise NotSupported(self.id + ' fetchLastPrices() is not supported yet')
1720
+
1721
+ async def fetch_trading_fees(self, params={}):
1722
+ raise NotSupported(self.id + ' fetchTradingFees() is not supported yet')
1723
+
1724
+ async def fetch_trading_fees_ws(self, params={}):
1725
+ raise NotSupported(self.id + ' fetchTradingFeesWs() is not supported yet')
1726
+
1727
+ async def fetch_trading_fee(self, symbol: str, params={}):
1728
+ if not self.has['fetchTradingFees']:
1729
+ raise NotSupported(self.id + ' fetchTradingFee() is not supported yet')
1730
+ fees = await self.fetch_trading_fees(params)
1731
+ return self.safe_dict(fees, symbol)
1732
+
1733
+ async def fetch_convert_currencies(self, params={}):
1734
+ raise NotSupported(self.id + ' fetchConvertCurrencies() is not supported yet')
1735
+
1736
+ async def fetch_funding_rate(self, symbol: str, params={}):
1737
+ if self.has['fetchFundingRates']:
1738
+ await self.load_markets()
1739
+ market = self.market(symbol)
1740
+ symbol = market['symbol']
1741
+ if not market['contract']:
1742
+ raise BadSymbol(self.id + ' fetchFundingRate() supports contract markets only')
1743
+ rates = await self.fetch_funding_rates([symbol], params)
1744
+ rate = self.safe_value(rates, symbol)
1745
+ if rate is None:
1746
+ raise NullResponse(self.id + ' fetchFundingRate() returned no data for ' + symbol)
1747
+ else:
1748
+ return rate
1749
+ else:
1750
+ raise NotSupported(self.id + ' fetchFundingRate() is not supported yet')
1751
+
1752
+ async def fetch_funding_interval(self, symbol: str, params={}):
1753
+ if self.has['fetchFundingIntervals']:
1754
+ await self.load_markets()
1755
+ market = self.market(symbol)
1756
+ symbol = market['symbol']
1757
+ if not market['contract']:
1758
+ raise BadSymbol(self.id + ' fetchFundingInterval() supports contract markets only')
1759
+ rates = await self.fetch_funding_intervals([symbol], params)
1760
+ rate = self.safe_value(rates, symbol)
1761
+ if rate is None:
1762
+ raise NullResponse(self.id + ' fetchFundingInterval() returned no data for ' + symbol)
1763
+ else:
1764
+ return rate
1765
+ else:
1766
+ raise NotSupported(self.id + ' fetchFundingInterval() is not supported yet')
1767
+
1768
+ async def fetch_mark_ohlcv(self, symbol, timeframe='1m', since: Int = None, limit: Int = None, params={}):
1769
+ """
1770
+ fetches historical mark price candlestick data containing the open, high, low, and close price of a market
1771
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
1772
+ :param str timeframe: the length of time each candle represents
1773
+ :param int [since]: timestamp in ms of the earliest candle to fetch
1774
+ :param int [limit]: the maximum amount of candles to fetch
1775
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1776
+ :returns float[][]: A list of candles ordered, open, high, low, close, None
1777
+ """
1778
+ if self.has['fetchMarkOHLCV']:
1779
+ request: dict = {
1780
+ 'price': 'mark',
1781
+ }
1782
+ return await self.fetch_ohlcv(symbol, timeframe, since, limit, self.extend(request, params))
1783
+ else:
1784
+ raise NotSupported(self.id + ' fetchMarkOHLCV() is not supported yet')
1785
+
1786
+ async def fetch_index_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}):
1787
+ """
1788
+ fetches historical index price candlestick data containing the open, high, low, and close price of a market
1789
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
1790
+ :param str timeframe: the length of time each candle represents
1791
+ :param int [since]: timestamp in ms of the earliest candle to fetch
1792
+ :param int [limit]: the maximum amount of candles to fetch
1793
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1794
+ @returns {} A list of candles ordered, open, high, low, close, None
1795
+ """
1796
+ if self.has['fetchIndexOHLCV']:
1797
+ request: dict = {
1798
+ 'price': 'index',
1799
+ }
1800
+ return await self.fetch_ohlcv(symbol, timeframe, since, limit, self.extend(request, params))
1801
+ else:
1802
+ raise NotSupported(self.id + ' fetchIndexOHLCV() is not supported yet')
1803
+
1804
+ async def fetch_premium_index_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}):
1805
+ """
1806
+ fetches historical premium index price candlestick data containing the open, high, low, and close price of a market
1807
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
1808
+ :param str timeframe: the length of time each candle represents
1809
+ :param int [since]: timestamp in ms of the earliest candle to fetch
1810
+ :param int [limit]: the maximum amount of candles to fetch
1811
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1812
+ :returns float[][]: A list of candles ordered, open, high, low, close, None
1813
+ """
1814
+ if self.has['fetchPremiumIndexOHLCV']:
1815
+ request: dict = {
1816
+ 'price': 'premiumIndex',
1817
+ }
1818
+ return await self.fetch_ohlcv(symbol, timeframe, since, limit, self.extend(request, params))
1819
+ else:
1820
+ raise NotSupported(self.id + ' fetchPremiumIndexOHLCV() is not supported yet')
1821
+
1822
+ async def fetch_transactions(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
1823
+ """
1824
+ @deprecated
1825
+ *DEPRECATED* use fetchDepositsWithdrawals instead
1826
+ :param str code: unified currency code for the currency of the deposit/withdrawals, default is None
1827
+ :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
1828
+ :param int [limit]: max number of deposit/withdrawals to return, default is None
1829
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1830
+ :returns dict: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
1831
+ """
1832
+ if self.has['fetchDepositsWithdrawals']:
1833
+ return await self.fetch_deposits_withdrawals(code, since, limit, params)
1834
+ else:
1835
+ raise NotSupported(self.id + ' fetchTransactions() is not supported yet')
1836
+
1837
+ async def fetch_paginated_call_dynamic(self, method: str, symbol: Str = None, since: Int = None, limit: Int = None, params={}, maxEntriesPerRequest: Int = None, removeRepeated=True):
1838
+ maxCalls = None
1839
+ maxCalls, params = self.handle_option_and_params(params, method, 'paginationCalls', 10)
1840
+ maxRetries = None
1841
+ maxRetries, params = self.handle_option_and_params(params, method, 'maxRetries', 3)
1842
+ paginationDirection = None
1843
+ paginationDirection, params = self.handle_option_and_params(params, method, 'paginationDirection', 'backward')
1844
+ paginationTimestamp = None
1845
+ removeRepeatedOption = removeRepeated
1846
+ removeRepeatedOption, params = self.handle_option_and_params(params, method, 'removeRepeated', removeRepeated)
1847
+ calls = 0
1848
+ result = []
1849
+ errors = 0
1850
+ until = self.safe_integer_2(params, 'untill', 'till') # do not omit it from params here
1851
+ maxEntriesPerRequest, params = self.handle_max_entries_per_request_and_params(method, maxEntriesPerRequest, params)
1852
+ if (paginationDirection == 'forward'):
1853
+ if since is None:
1854
+ raise ArgumentsRequired(self.id + ' pagination requires a since argument when paginationDirection set to forward')
1855
+ paginationTimestamp = since
1856
+ while((calls < maxCalls)):
1857
+ calls += 1
1858
+ try:
1859
+ if paginationDirection == 'backward':
1860
+ # do it backwards, starting from the last
1861
+ # UNTIL filtering is required in order to work
1862
+ if paginationTimestamp is not None:
1863
+ params['until'] = paginationTimestamp - 1
1864
+ response = await getattr(self, method)(symbol, None, maxEntriesPerRequest, params)
1865
+ responseLength = len(response)
1866
+ if self.verbose:
1867
+ backwardMessage = 'Dynamic pagination call ' + self.number_to_string(calls) + ' method ' + method + ' response length ' + self.number_to_string(responseLength)
1868
+ if paginationTimestamp is not None:
1869
+ backwardMessage += ' timestamp ' + self.number_to_string(paginationTimestamp)
1870
+ self.log(backwardMessage)
1871
+ if responseLength == 0:
1872
+ break
1873
+ errors = 0
1874
+ result = self.array_concat(result, response)
1875
+ firstElement = self.safe_value(response, 0)
1876
+ paginationTimestamp = self.safe_integer_2(firstElement, 'timestamp', 0)
1877
+ if (since is not None) and (paginationTimestamp <= since):
1878
+ break
1879
+ else:
1880
+ # do it forwards, starting from the since
1881
+ response = await getattr(self, method)(symbol, paginationTimestamp, maxEntriesPerRequest, params)
1882
+ responseLength = len(response)
1883
+ if self.verbose:
1884
+ forwardMessage = 'Dynamic pagination call ' + self.number_to_string(calls) + ' method ' + method + ' response length ' + self.number_to_string(responseLength)
1885
+ if paginationTimestamp is not None:
1886
+ forwardMessage += ' timestamp ' + self.number_to_string(paginationTimestamp)
1887
+ self.log(forwardMessage)
1888
+ if responseLength == 0:
1889
+ break
1890
+ errors = 0
1891
+ result = self.array_concat(result, response)
1892
+ last = self.safe_value(response, responseLength - 1)
1893
+ paginationTimestamp = self.safe_integer(last, 'timestamp') + 1
1894
+ if (until is not None) and (paginationTimestamp >= until):
1895
+ break
1896
+ except Exception as e:
1897
+ errors += 1
1898
+ if errors > maxRetries:
1899
+ raise e
1900
+ uniqueResults = result
1901
+ if removeRepeatedOption:
1902
+ uniqueResults = self.remove_repeated_elements_from_array(result)
1903
+ key = 0 if (method == 'fetchOHLCV') else 'timestamp'
1904
+ return self.filter_by_since_limit(uniqueResults, since, limit, key)
1905
+
1906
+ async def safe_deterministic_call(self, method: str, symbol: Str = None, since: Int = None, limit: Int = None, timeframe: Str = None, params={}):
1907
+ maxRetries = None
1908
+ maxRetries, params = self.handle_option_and_params(params, method, 'maxRetries', 3)
1909
+ errors = 0
1910
+ while(errors <= maxRetries):
1911
+ try:
1912
+ if timeframe and method != 'fetchFundingRateHistory':
1913
+ return await getattr(self, method)(symbol, timeframe, since, limit, params)
1914
+ else:
1915
+ return await getattr(self, method)(symbol, since, limit, params)
1916
+ except Exception as e:
1917
+ if isinstance(e, RateLimitExceeded):
1918
+ raise e # if we are rate limited, we should not retry and fail fast
1919
+ errors += 1
1920
+ if errors > maxRetries:
1921
+ raise e
1922
+ return []
1923
+
1924
+ async def fetch_paginated_call_deterministic(self, method: str, symbol: Str = None, since: Int = None, limit: Int = None, timeframe: Str = None, params={}, maxEntriesPerRequest=None):
1925
+ maxCalls = None
1926
+ maxCalls, params = self.handle_option_and_params(params, method, 'paginationCalls', 10)
1927
+ maxEntriesPerRequest, params = self.handle_max_entries_per_request_and_params(method, maxEntriesPerRequest, params)
1928
+ current = self.milliseconds()
1929
+ tasks = []
1930
+ time = self.parse_timeframe(timeframe) * 1000
1931
+ step = time * maxEntriesPerRequest
1932
+ currentSince = current - (maxCalls * step) - 1
1933
+ if since is not None:
1934
+ currentSince = max(currentSince, since)
1935
+ else:
1936
+ currentSince = max(currentSince, 1241440531000) # avoid timestamps older than 2009
1937
+ until = self.safe_integer_2(params, 'until', 'till') # do not omit it here
1938
+ if until is not None:
1939
+ requiredCalls = int(math.ceil((until - since)) / step)
1940
+ if requiredCalls > maxCalls:
1941
+ raise BadRequest(self.id + ' the number of required calls is greater than the max number of calls allowed, either increase the paginationCalls or decrease the since-until gap. Current paginationCalls limit is ' + str(maxCalls) + ' required calls is ' + str(requiredCalls))
1942
+ for i in range(0, maxCalls):
1943
+ if (until is not None) and (currentSince >= until):
1944
+ break
1945
+ if currentSince >= current:
1946
+ break
1947
+ tasks.append(self.safe_deterministic_call(method, symbol, currentSince, maxEntriesPerRequest, timeframe, params))
1948
+ currentSince = self.sum(currentSince, step) - 1
1949
+ results = await asyncio.gather(*tasks)
1950
+ result = []
1951
+ for i in range(0, len(results)):
1952
+ result = self.array_concat(result, results[i])
1953
+ uniqueResults = self.remove_repeated_elements_from_array(result)
1954
+ key = 0 if (method == 'fetchOHLCV') else 'timestamp'
1955
+ return self.filter_by_since_limit(uniqueResults, since, limit, key)
1956
+
1957
+ async def fetch_paginated_call_cursor(self, method: str, symbol: Str = None, since=None, limit=None, params={}, cursorReceived=None, cursorSent=None, cursorIncrement=None, maxEntriesPerRequest=None):
1958
+ maxCalls = None
1959
+ maxCalls, params = self.handle_option_and_params(params, method, 'paginationCalls', 10)
1960
+ maxRetries = None
1961
+ maxRetries, params = self.handle_option_and_params(params, method, 'maxRetries', 3)
1962
+ maxEntriesPerRequest, params = self.handle_max_entries_per_request_and_params(method, maxEntriesPerRequest, params)
1963
+ cursorValue = None
1964
+ i = 0
1965
+ errors = 0
1966
+ result = []
1967
+ timeframe = self.safe_string(params, 'timeframe')
1968
+ params = self.omit(params, 'timeframe') # reading the timeframe from the method arguments to avoid changing the signature
1969
+ while(i < maxCalls):
1970
+ try:
1971
+ if cursorValue is not None:
1972
+ if cursorIncrement is not None:
1973
+ cursorValue = self.parse_to_int(cursorValue) + cursorIncrement
1974
+ params[cursorSent] = cursorValue
1975
+ response = None
1976
+ if method == 'fetchAccounts':
1977
+ response = await getattr(self, method)(params)
1978
+ elif method == 'getLeverageTiersPaginated' or method == 'fetchPositions':
1979
+ response = await getattr(self, method)(symbol, params)
1980
+ elif method == 'fetchOpenInterestHistory':
1981
+ response = await getattr(self, method)(symbol, timeframe, since, maxEntriesPerRequest, params)
1982
+ else:
1983
+ response = await getattr(self, method)(symbol, since, maxEntriesPerRequest, params)
1984
+ errors = 0
1985
+ responseLength = len(response)
1986
+ if self.verbose:
1987
+ cursorString = '' if (cursorValue is None) else cursorValue
1988
+ iteration = (i + 1)
1989
+ cursorMessage = 'Cursor pagination call ' + str(iteration) + ' method ' + method + ' response length ' + str(responseLength) + ' cursor ' + cursorString
1990
+ self.log(cursorMessage)
1991
+ if responseLength == 0:
1992
+ break
1993
+ result = self.array_concat(result, response)
1994
+ last = self.safe_dict(response, responseLength - 1)
1995
+ # cursorValue = self.safe_value(last['info'], cursorReceived)
1996
+ cursorValue = None # search for the cursor
1997
+ for j in range(0, responseLength):
1998
+ index = responseLength - j - 1
1999
+ entry = self.safe_dict(response, index)
2000
+ info = self.safe_dict(entry, 'info')
2001
+ cursor = self.safe_value(info, cursorReceived)
2002
+ if cursor is not None:
2003
+ cursorValue = cursor
2004
+ break
2005
+ if cursorValue is None:
2006
+ break
2007
+ lastTimestamp = self.safe_integer(last, 'timestamp')
2008
+ if lastTimestamp is not None and lastTimestamp < since:
2009
+ break
2010
+ except Exception as e:
2011
+ errors += 1
2012
+ if errors > maxRetries:
2013
+ raise e
2014
+ i += 1
2015
+ sorted = self.sort_cursor_paginated_result(result)
2016
+ key = 0 if (method == 'fetchOHLCV') else 'timestamp'
2017
+ return self.filter_by_since_limit(sorted, since, limit, key)
2018
+
2019
+ async def fetch_paginated_call_incremental(self, method: str, symbol: Str = None, since=None, limit=None, params={}, pageKey=None, maxEntriesPerRequest=None):
2020
+ maxCalls = None
2021
+ maxCalls, params = self.handle_option_and_params(params, method, 'paginationCalls', 10)
2022
+ maxRetries = None
2023
+ maxRetries, params = self.handle_option_and_params(params, method, 'maxRetries', 3)
2024
+ maxEntriesPerRequest, params = self.handle_max_entries_per_request_and_params(method, maxEntriesPerRequest, params)
2025
+ i = 0
2026
+ errors = 0
2027
+ result = []
2028
+ while(i < maxCalls):
2029
+ try:
2030
+ params[pageKey] = i + 1
2031
+ response = await getattr(self, method)(symbol, since, maxEntriesPerRequest, params)
2032
+ errors = 0
2033
+ responseLength = len(response)
2034
+ if self.verbose:
2035
+ iteration = (i + str(1))
2036
+ incrementalMessage = 'Incremental pagination call ' + iteration + ' method ' + method + ' response length ' + str(responseLength)
2037
+ self.log(incrementalMessage)
2038
+ if responseLength == 0:
2039
+ break
2040
+ result = self.array_concat(result, response)
2041
+ except Exception as e:
2042
+ errors += 1
2043
+ if errors > maxRetries:
2044
+ raise e
2045
+ i += 1
2046
+ sorted = self.sort_cursor_paginated_result(result)
2047
+ key = 0 if (method == 'fetchOHLCV') else 'timestamp'
2048
+ return self.filter_by_since_limit(sorted, since, limit, key)
2049
+
2050
+ async def fetch_position_history(self, symbol: str, since: Int = None, limit: Int = None, params={}):
2051
+ """
2052
+ fetches the history of margin added or reduced from contract isolated positions
2053
+ :param str [symbol]: unified market symbol
2054
+ :param int [since]: timestamp in ms of the position
2055
+ :param int [limit]: the maximum amount of candles to fetch, default=1000
2056
+ :param dict params: extra parameters specific to the exchange api endpoint
2057
+ :returns dict[]: a list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
2058
+ """
2059
+ if self.has['fetchPositionsHistory']:
2060
+ positions = await self.fetch_positions_history([symbol], since, limit, params)
2061
+ return positions
2062
+ else:
2063
+ raise NotSupported(self.id + ' fetchPositionHistory() is not supported yet')
2064
+
2065
+ async def fetch_positions_history(self, symbols: Strings = None, since: Int = None, limit: Int = None, params={}):
2066
+ """
2067
+ fetches the history of margin added or reduced from contract isolated positions
2068
+ :param str [symbol]: unified market symbol
2069
+ :param int [since]: timestamp in ms of the position
2070
+ :param int [limit]: the maximum amount of candles to fetch, default=1000
2071
+ :param dict params: extra parameters specific to the exchange api endpoint
2072
+ :returns dict[]: a list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
2073
+ """
2074
+ raise NotSupported(self.id + ' fetchPositionsHistory() is not supported yet')
2075
+
2076
+ async def fetch_transfer(self, id: str, code: Str = None, params={}):
2077
+ """
2078
+ fetches a transfer
2079
+ :param str id: transfer id
2080
+ :param [str] code: unified currency code
2081
+ :param dict params: extra parameters specific to the exchange api endpoint
2082
+ :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
2083
+ """
2084
+ raise NotSupported(self.id + ' fetchTransfer() is not supported yet')
2085
+
2086
+ async def fetch_transfers(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
2087
+ """
2088
+ fetches a transfer
2089
+ :param str id: transfer id
2090
+ :param int [since]: timestamp in ms of the earliest transfer to fetch
2091
+ :param int [limit]: the maximum amount of transfers to fetch
2092
+ :param dict params: extra parameters specific to the exchange api endpoint
2093
+ :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
2094
+ """
2095
+ raise NotSupported(self.id + ' fetchTransfers() is not supported yet')