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,3445 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
4
+ # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
5
+
6
+ from ccxt.base.exchange import Exchange
7
+ from ccxt.abstract.hyperliquid import ImplicitAPI
8
+ import math
9
+ from ccxt.base.types import Any, Balances, Currencies, Currency, Int, LedgerEntry, MarginModification, Market, Num, Order, OrderBook, OrderRequest, CancellationRequest, OrderSide, OrderType, Str, Strings, Ticker, Tickers, FundingRate, FundingRates, Trade, TradingFeeInterface, Transaction, TransferEntry
10
+ from typing import List
11
+ from ccxt.base.errors import ExchangeError
12
+ from ccxt.base.errors import ArgumentsRequired
13
+ from ccxt.base.errors import BadRequest
14
+ from ccxt.base.errors import InsufficientFunds
15
+ from ccxt.base.errors import InvalidOrder
16
+ from ccxt.base.errors import OrderNotFound
17
+ from ccxt.base.errors import NotSupported
18
+ from ccxt.base.decimal_to_precision import ROUND
19
+ from ccxt.base.decimal_to_precision import DECIMAL_PLACES
20
+ from ccxt.base.decimal_to_precision import SIGNIFICANT_DIGITS
21
+ from ccxt.base.decimal_to_precision import TICK_SIZE
22
+ from ccxt.base.precise import Precise
23
+
24
+
25
+ class hyperliquid(Exchange, ImplicitAPI):
26
+
27
+ def describe(self) -> Any:
28
+ return self.deep_extend(super(hyperliquid, self).describe(), {
29
+ 'id': 'hyperliquid',
30
+ 'name': 'Hyperliquid',
31
+ 'countries': [],
32
+ 'version': 'v1',
33
+ 'rateLimit': 50, # 1200 requests per minute, 20 request per second
34
+ 'certified': True,
35
+ 'pro': True,
36
+ 'dex': True,
37
+ 'has': {
38
+ 'CORS': None,
39
+ 'spot': True,
40
+ 'margin': False,
41
+ 'swap': True,
42
+ 'future': True,
43
+ 'option': False,
44
+ 'addMargin': True,
45
+ 'borrowCrossMargin': False,
46
+ 'borrowIsolatedMargin': False,
47
+ 'cancelAllOrders': False,
48
+ 'cancelAllOrdersAfter': True,
49
+ 'cancelOrder': True,
50
+ 'cancelOrders': True,
51
+ 'cancelOrdersForSymbols': True,
52
+ 'closeAllPositions': False,
53
+ 'closePosition': False,
54
+ 'createMarketBuyOrderWithCost': False,
55
+ 'createMarketOrderWithCost': False,
56
+ 'createMarketSellOrderWithCost': False,
57
+ 'createOrder': True,
58
+ 'createOrders': True,
59
+ 'createReduceOnlyOrder': True,
60
+ 'createStopOrder': True,
61
+ 'createTriggerOrder': True,
62
+ 'editOrder': True,
63
+ 'editOrders': True,
64
+ 'fetchAccounts': False,
65
+ 'fetchBalance': True,
66
+ 'fetchBorrowInterest': False,
67
+ 'fetchBorrowRateHistories': False,
68
+ 'fetchBorrowRateHistory': False,
69
+ 'fetchCanceledAndClosedOrders': True,
70
+ 'fetchCanceledOrders': True,
71
+ 'fetchClosedOrders': True,
72
+ 'fetchCrossBorrowRate': False,
73
+ 'fetchCrossBorrowRates': False,
74
+ 'fetchCurrencies': True,
75
+ 'fetchDepositAddress': False,
76
+ 'fetchDepositAddresses': False,
77
+ 'fetchDeposits': True,
78
+ 'fetchDepositWithdrawFee': 'emulated',
79
+ 'fetchDepositWithdrawFees': False,
80
+ 'fetchFundingHistory': True,
81
+ 'fetchFundingRate': False,
82
+ 'fetchFundingRateHistory': True,
83
+ 'fetchFundingRates': True,
84
+ 'fetchIndexOHLCV': False,
85
+ 'fetchIsolatedBorrowRate': False,
86
+ 'fetchIsolatedBorrowRates': False,
87
+ 'fetchLedger': True,
88
+ 'fetchLeverage': False,
89
+ 'fetchLeverageTiers': False,
90
+ 'fetchLiquidations': False,
91
+ 'fetchMarginMode': None,
92
+ 'fetchMarketLeverageTiers': False,
93
+ 'fetchMarkets': True,
94
+ 'fetchMarkOHLCV': False,
95
+ 'fetchMyLiquidations': False,
96
+ 'fetchMyTrades': True,
97
+ 'fetchOHLCV': True,
98
+ 'fetchOpenInterest': True,
99
+ 'fetchOpenInterestHistory': False,
100
+ 'fetchOpenInterests': True,
101
+ 'fetchOpenOrders': True,
102
+ 'fetchOrder': True,
103
+ 'fetchOrderBook': True,
104
+ 'fetchOrders': True,
105
+ 'fetchOrderTrades': False,
106
+ 'fetchPosition': True,
107
+ 'fetchPositionMode': False,
108
+ 'fetchPositions': True,
109
+ 'fetchPositionsRisk': False,
110
+ 'fetchPremiumIndexOHLCV': False,
111
+ 'fetchTicker': 'emulated',
112
+ 'fetchTickers': True,
113
+ 'fetchTime': False,
114
+ 'fetchTrades': True,
115
+ 'fetchTradingFee': True,
116
+ 'fetchTradingFees': False,
117
+ 'fetchTransfer': False,
118
+ 'fetchTransfers': False,
119
+ 'fetchWithdrawal': False,
120
+ 'fetchWithdrawals': True,
121
+ 'reduceMargin': True,
122
+ 'repayCrossMargin': False,
123
+ 'repayIsolatedMargin': False,
124
+ 'sandbox': True,
125
+ 'setLeverage': True,
126
+ 'setMarginMode': True,
127
+ 'setPositionMode': False,
128
+ 'transfer': True,
129
+ 'withdraw': True,
130
+ },
131
+ 'timeframes': {
132
+ '1m': '1m',
133
+ '3m': '3m',
134
+ '5m': '5m',
135
+ '15m': '15m',
136
+ '30m': '30m',
137
+ '1h': '1h',
138
+ '2h': '2h',
139
+ '4h': '4h',
140
+ '8h': '8h',
141
+ '12h': '12h',
142
+ '1d': '1d',
143
+ '3d': '3d',
144
+ '1w': '1w',
145
+ '1M': '1M',
146
+ },
147
+ 'hostname': 'hyperliquid.xyz',
148
+ 'urls': {
149
+ 'logo': 'https://github.com/ccxt/ccxt/assets/43336371/b371bc6c-4a8c-489f-87f4-20a913dd8d4b',
150
+ 'api': {
151
+ 'public': 'https://api.{hostname}',
152
+ 'private': 'https://api.{hostname}',
153
+ },
154
+ 'test': {
155
+ 'public': 'https://api.hyperliquid-testnet.xyz',
156
+ 'private': 'https://api.hyperliquid-testnet.xyz',
157
+ },
158
+ 'www': 'https://hyperliquid.xyz',
159
+ 'doc': 'https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api',
160
+ 'fees': 'https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees',
161
+ 'referral': 'https://app.hyperliquid.xyz/',
162
+ },
163
+ 'api': {
164
+ 'public': {
165
+ 'post': {
166
+ 'info': {
167
+ 'cost': 20,
168
+ 'byType': {
169
+ 'l2Book': 2,
170
+ 'allMids': 2,
171
+ 'clearinghouseState': 2,
172
+ 'orderStatus': 2,
173
+ 'spotClearinghouseState': 2,
174
+ 'exchangeStatus': 2,
175
+ },
176
+ },
177
+ },
178
+ },
179
+ 'private': {
180
+ 'post': {
181
+ 'exchange': 1,
182
+ },
183
+ },
184
+ },
185
+ 'fees': {
186
+ 'swap': {
187
+ 'taker': self.parse_number('0.00035'),
188
+ 'maker': self.parse_number('0.0001'),
189
+ },
190
+ 'spot': {
191
+ 'taker': self.parse_number('0.00035'),
192
+ 'maker': self.parse_number('0.0001'),
193
+ },
194
+ },
195
+ 'requiredCredentials': {
196
+ 'apiKey': False,
197
+ 'secret': False,
198
+ 'walletAddress': True,
199
+ 'privateKey': True,
200
+ },
201
+ 'exceptions': {
202
+ 'exact': {
203
+ },
204
+ 'broad': {
205
+ 'Price must be divisible by tick size.': InvalidOrder,
206
+ 'Order must have minimum value of $10': InvalidOrder,
207
+ 'Insufficient margin to place order.': InsufficientFunds,
208
+ 'Reduce only order would increase position.': InvalidOrder,
209
+ 'Post only order would have immediately matched,': InvalidOrder,
210
+ 'Order could not immediately match against any resting orders.': InvalidOrder,
211
+ 'Invalid TP/SL price.': InvalidOrder,
212
+ 'No liquidity available for market order.': InvalidOrder,
213
+ 'Order was never placed, already canceled, or filled.': OrderNotFound,
214
+ 'User or API Wallet ': InvalidOrder,
215
+ 'Order has invalid size': InvalidOrder,
216
+ 'Order price cannot be more than 80% away from the reference price': InvalidOrder,
217
+ 'Order has zero size.': InvalidOrder,
218
+ 'Insufficient spot balance asset': InsufficientFunds,
219
+ 'Insufficient balance for withdrawal': InsufficientFunds,
220
+ 'Insufficient balance for token transfer': InsufficientFunds,
221
+ },
222
+ },
223
+ 'precisionMode': TICK_SIZE,
224
+ 'commonCurrencies': {
225
+ },
226
+ 'options': {
227
+ 'defaultType': 'swap',
228
+ 'sandboxMode': False,
229
+ 'defaultSlippage': 0.05,
230
+ 'zeroAddress': '0x0000000000000000000000000000000000000000',
231
+ },
232
+ 'features': {
233
+ 'default': {
234
+ 'sandbox': True,
235
+ 'createOrder': {
236
+ 'marginMode': False,
237
+ 'triggerPrice': False,
238
+ 'triggerPriceType': None,
239
+ 'triggerDirection': False,
240
+ 'stopLossPrice': False,
241
+ 'takeProfitPrice': False,
242
+ 'attachedStopLossTakeProfit': None,
243
+ 'timeInForce': {
244
+ 'IOC': True,
245
+ 'FOK': False,
246
+ 'PO': True,
247
+ 'GTD': False,
248
+ },
249
+ 'hedged': False,
250
+ 'trailing': False,
251
+ 'leverage': False,
252
+ 'marketBuyByCost': False,
253
+ 'marketBuyRequiresPrice': False,
254
+ 'selfTradePrevention': False,
255
+ 'iceberg': False,
256
+ },
257
+ 'createOrders': {
258
+ 'max': 1000,
259
+ },
260
+ 'fetchMyTrades': {
261
+ 'marginMode': False,
262
+ 'limit': 2000,
263
+ 'daysBack': None,
264
+ 'untilDays': None,
265
+ 'symbolRequired': True,
266
+ },
267
+ 'fetchOrder': {
268
+ 'marginMode': False,
269
+ 'trigger': False,
270
+ 'trailing': False,
271
+ 'symbolRequired': True,
272
+ },
273
+ 'fetchOpenOrders': {
274
+ 'marginMode': False,
275
+ 'limit': 2000,
276
+ 'trigger': False,
277
+ 'trailing': False,
278
+ 'symbolRequired': True,
279
+ },
280
+ 'fetchOrders': {
281
+ 'marginMode': False,
282
+ 'limit': 2000,
283
+ 'daysBack': None,
284
+ 'untilDays': None,
285
+ 'trigger': False,
286
+ 'trailing': False,
287
+ 'symbolRequired': True,
288
+ },
289
+ 'fetchClosedOrders': {
290
+ 'marginMode': False,
291
+ 'limit': 2000,
292
+ 'daysBack': None,
293
+ 'daysBackCanceled': None,
294
+ 'untilDays': None,
295
+ 'trigger': False,
296
+ 'trailing': False,
297
+ 'symbolRequired': True,
298
+ },
299
+ 'fetchOHLCV': {
300
+ 'limit': 5000,
301
+ },
302
+ },
303
+ 'spot': {
304
+ 'extends': 'default',
305
+ },
306
+ 'forPerps': {
307
+ 'extends': 'default',
308
+ 'createOrder': {
309
+ 'stopLossPrice': True,
310
+ 'takeProfitPrice': True,
311
+ 'attachedStopLossTakeProfit': None, # todo, in two orders
312
+ },
313
+ },
314
+ 'swap': {
315
+ 'linear': {
316
+ 'extends': 'forPerps',
317
+ },
318
+ 'inverse': {
319
+ 'extends': 'forPerps',
320
+ },
321
+ },
322
+ 'future': {
323
+ 'linear': {
324
+ 'extends': 'forPerps',
325
+ },
326
+ 'inverse': {
327
+ 'extends': 'forPerps',
328
+ },
329
+ },
330
+ },
331
+ })
332
+
333
+ def set_sandbox_mode(self, enabled):
334
+ super(hyperliquid, self).set_sandbox_mode(enabled)
335
+ self.options['sandboxMode'] = enabled
336
+
337
+ def fetch_currencies(self, params={}) -> Currencies:
338
+ """
339
+ fetches all available currencies on an exchange
340
+
341
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-metadata
342
+
343
+ :param dict [params]: extra parameters specific to the exchange API endpoint
344
+ :returns dict: an associative dictionary of currencies
345
+ """
346
+ request: dict = {
347
+ 'type': 'meta',
348
+ }
349
+ response = self.publicPostInfo(self.extend(request, params))
350
+ #
351
+ # [
352
+ # {
353
+ # "universe": [
354
+ # {
355
+ # "maxLeverage": 50,
356
+ # "name": "SOL",
357
+ # "onlyIsolated": False,
358
+ # "szDecimals": 2
359
+ # }
360
+ # ]
361
+ # }
362
+ # ]
363
+ #
364
+ meta = self.safe_list(response, 'universe', [])
365
+ result: dict = {}
366
+ for i in range(0, len(meta)):
367
+ data = self.safe_dict(meta, i, {})
368
+ id = i
369
+ name = self.safe_string(data, 'name')
370
+ code = self.safe_currency_code(name)
371
+ result[code] = {
372
+ 'id': id,
373
+ 'name': name,
374
+ 'code': code,
375
+ 'precision': None,
376
+ 'info': data,
377
+ 'active': None,
378
+ 'deposit': None,
379
+ 'withdraw': None,
380
+ 'networks': None,
381
+ 'fee': None,
382
+ 'limits': {
383
+ 'amount': {
384
+ 'min': None,
385
+ 'max': None,
386
+ },
387
+ 'withdraw': {
388
+ 'min': None,
389
+ 'max': None,
390
+ },
391
+ },
392
+ }
393
+ return result
394
+
395
+ def fetch_markets(self, params={}) -> List[Market]:
396
+ """
397
+ retrieves data on all markets for hyperliquid
398
+
399
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
400
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts
401
+
402
+ :param dict [params]: extra parameters specific to the exchange API endpoint
403
+ :returns dict[]: an array of objects representing market data
404
+ """
405
+ rawPromises = [
406
+ self.fetch_swap_markets(params),
407
+ self.fetch_spot_markets(params),
408
+ ]
409
+ promises = rawPromises
410
+ swapMarkets = promises[0]
411
+ spotMarkets = promises[1]
412
+ return self.array_concat(swapMarkets, spotMarkets)
413
+
414
+ def fetch_swap_markets(self, params={}) -> List[Market]:
415
+ """
416
+ retrieves data on all swap markets for hyperliquid
417
+
418
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
419
+
420
+ :param dict [params]: extra parameters specific to the exchange API endpoint
421
+ :returns dict[]: an array of objects representing market data
422
+ """
423
+ request: dict = {
424
+ 'type': 'metaAndAssetCtxs',
425
+ }
426
+ response = self.publicPostInfo(self.extend(request, params))
427
+ #
428
+ # [
429
+ # {
430
+ # "universe": [
431
+ # {
432
+ # "maxLeverage": 50,
433
+ # "name": "SOL",
434
+ # "onlyIsolated": False,
435
+ # "szDecimals": 2
436
+ # }
437
+ # ]
438
+ # },
439
+ # [
440
+ # {
441
+ # "dayNtlVlm": "9450588.2273",
442
+ # "funding": "0.0000198",
443
+ # "impactPxs": [
444
+ # "108.04",
445
+ # "108.06"
446
+ # ],
447
+ # "markPx": "108.04",
448
+ # "midPx": "108.05",
449
+ # "openInterest": "10764.48",
450
+ # "oraclePx": "107.99",
451
+ # "premium": "0.00055561",
452
+ # "prevDayPx": "111.81"
453
+ # }
454
+ # ]
455
+ # ]
456
+ #
457
+ #
458
+ meta = self.safe_dict(response, 0, {})
459
+ universe = self.safe_list(meta, 'universe', [])
460
+ assetCtxs = self.safe_list(response, 1, [])
461
+ result = []
462
+ for i in range(0, len(universe)):
463
+ data = self.extend(
464
+ self.safe_dict(universe, i, {}),
465
+ self.safe_dict(assetCtxs, i, {})
466
+ )
467
+ data['baseId'] = i
468
+ result.append(data)
469
+ return self.parse_markets(result)
470
+
471
+ def calculate_price_precision(self, price: float, amountPrecision: float, maxDecimals: float):
472
+ """
473
+ Helper function to calculate the Hyperliquid DECIMAL_PLACES price precision
474
+ :param float price: the price to use in the calculation
475
+ :param int amountPrecision: the amountPrecision to use in the calculation
476
+ :param int maxDecimals: the maxDecimals to use in the calculation
477
+ :returns int: The calculated price precision
478
+ """
479
+ pricePrecision = 0
480
+ priceStr = self.number_to_string(price)
481
+ if priceStr is None:
482
+ return 0
483
+ priceSplitted = priceStr.split('.')
484
+ if Precise.string_eq(priceStr, '0'):
485
+ # Significant digits is always hasattr(self, 5) case
486
+ significantDigits = 5
487
+ # Integer digits is always hasattr(self, 0) case(0 doesn't count)
488
+ integerDigits = 0
489
+ # Calculate the price precision
490
+ pricePrecision = min(maxDecimals - amountPrecision, significantDigits - integerDigits)
491
+ elif Precise.string_gt(priceStr, '0') and Precise.string_lt(priceStr, '1'):
492
+ # Significant digits, always hasattr(self, 5) case
493
+ significantDigits = 5
494
+ # Get the part after the decimal separator
495
+ decimalPart = self.safe_string(priceSplitted, 1, '')
496
+ # Count the number of leading zeros in the decimal part
497
+ leadingZeros = 0
498
+ while((leadingZeros <= len(decimalPart)) and (decimalPart[leadingZeros] == '0')):
499
+ leadingZeros = leadingZeros + 1
500
+ # Calculate price precision based on leading zeros and significant digits
501
+ pricePrecision = leadingZeros + significantDigits
502
+ # Calculate the price precision based on maxDecimals - szDecimals and the calculated price precision from the previous step
503
+ pricePrecision = min(maxDecimals - amountPrecision, pricePrecision)
504
+ else:
505
+ # Count the numbers before the decimal separator
506
+ integerPart = self.safe_string(priceSplitted, 0, '')
507
+ # Get significant digits, take the max() of 5 and the integer digits count
508
+ significantDigits = max(5, len(integerPart))
509
+ # Calculate price precision based on maxDecimals - szDecimals and significantDigits - len(integerPart)
510
+ pricePrecision = min(maxDecimals - amountPrecision, significantDigits - len(integerPart))
511
+ return self.parse_to_int(pricePrecision)
512
+
513
+ def fetch_spot_markets(self, params={}) -> List[Market]:
514
+ """
515
+ retrieves data on all spot markets for hyperliquid
516
+
517
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts
518
+
519
+ :param dict [params]: extra parameters specific to the exchange API endpoint
520
+ :returns dict[]: an array of objects representing market data
521
+ """
522
+ request: dict = {
523
+ 'type': 'spotMetaAndAssetCtxs',
524
+ }
525
+ response = self.publicPostInfo(self.extend(request, params))
526
+ #
527
+ # [
528
+ # {
529
+ # "tokens": [
530
+ # {
531
+ # "name": "USDC",
532
+ # "szDecimals": 8,
533
+ # "weiDecimals" 8,
534
+ # "index": 0,
535
+ # "tokenId": "0x6d1e7cde53ba9467b783cb7c530ce054",
536
+ # "isCanonical": True,
537
+ # "evmContract":null,
538
+ # "fullName":null
539
+ # },
540
+ # {
541
+ # "name": "PURR",
542
+ # "szDecimals": 0,
543
+ # "weiDecimals": 5,
544
+ # "index": 1,
545
+ # "tokenId": "0xc1fb593aeffbeb02f85e0308e9956a90",
546
+ # "isCanonical": True,
547
+ # "evmContract":null,
548
+ # "fullName":null
549
+ # }
550
+ # ],
551
+ # "universe": [
552
+ # {
553
+ # "name": "PURR/USDC",
554
+ # "tokens": [1, 0],
555
+ # "index": 0,
556
+ # "isCanonical": True
557
+ # }
558
+ # ]
559
+ # },
560
+ # [
561
+ # {
562
+ # "dayNtlVlm":"8906.0",
563
+ # "markPx":"0.14",
564
+ # "midPx":"0.209265",
565
+ # "prevDayPx":"0.20432"
566
+ # }
567
+ # ]
568
+ # ]
569
+ #
570
+ first = self.safe_dict(response, 0, {})
571
+ second = self.safe_list(response, 1, [])
572
+ meta = self.safe_list(first, 'universe', [])
573
+ tokens = self.safe_list(first, 'tokens', [])
574
+ markets = []
575
+ for i in range(0, len(meta)):
576
+ market = self.safe_dict(meta, i, {})
577
+ index = self.safe_integer(market, 'index')
578
+ extraData = self.safe_dict(second, index, {})
579
+ marketName = self.safe_string(market, 'name')
580
+ # if marketName.find('/') < 0:
581
+ # # there are some weird spot markets in testnet, eg @2
582
+ # continue
583
+ # }
584
+ # marketParts = marketName.split('/')
585
+ # baseName = self.safe_string(marketParts, 0)
586
+ # quoteId = self.safe_string(marketParts, 1)
587
+ fees = self.safe_dict(self.fees, 'spot', {})
588
+ taker = self.safe_number(fees, 'taker')
589
+ maker = self.safe_number(fees, 'maker')
590
+ tokensPos = self.safe_list(market, 'tokens', [])
591
+ baseTokenPos = self.safe_integer(tokensPos, 0)
592
+ quoteTokenPos = self.safe_integer(tokensPos, 1)
593
+ baseTokenInfo = self.safe_dict(tokens, baseTokenPos, {})
594
+ quoteTokenInfo = self.safe_dict(tokens, quoteTokenPos, {})
595
+ baseName = self.safe_string(baseTokenInfo, 'name')
596
+ quoteId = self.safe_string(quoteTokenInfo, 'name')
597
+ base = self.safe_currency_code(baseName)
598
+ quote = self.safe_currency_code(quoteId)
599
+ symbol = base + '/' + quote
600
+ innerBaseTokenInfo = self.safe_dict(baseTokenInfo, 'spec', baseTokenInfo)
601
+ # innerQuoteTokenInfo = self.safe_dict(quoteTokenInfo, 'spec', quoteTokenInfo)
602
+ amountPrecisionStr = self.safe_string(innerBaseTokenInfo, 'szDecimals')
603
+ amountPrecision = int(amountPrecisionStr)
604
+ price = self.safe_number(extraData, 'midPx')
605
+ pricePrecision = 0
606
+ if price is not None:
607
+ pricePrecision = self.calculate_price_precision(price, amountPrecision, 8)
608
+ pricePrecisionStr = self.number_to_string(pricePrecision)
609
+ # quotePrecision = self.parse_number(self.parse_precision(self.safe_string(innerQuoteTokenInfo, 'szDecimals')))
610
+ baseId = self.number_to_string(index + 10000)
611
+ markets.append(self.safe_market_structure({
612
+ 'id': marketName,
613
+ 'symbol': symbol,
614
+ 'base': base,
615
+ 'quote': quote,
616
+ 'settle': None,
617
+ 'baseId': baseId,
618
+ 'quoteId': quoteId,
619
+ 'settleId': None,
620
+ 'type': 'spot',
621
+ 'spot': True,
622
+ 'subType': None,
623
+ 'margin': None,
624
+ 'swap': False,
625
+ 'future': False,
626
+ 'option': False,
627
+ 'active': True,
628
+ 'contract': False,
629
+ 'linear': None,
630
+ 'inverse': None,
631
+ 'taker': taker,
632
+ 'maker': maker,
633
+ 'contractSize': None,
634
+ 'expiry': None,
635
+ 'expiryDatetime': None,
636
+ 'strike': None,
637
+ 'optionType': None,
638
+ 'precision': {
639
+ 'amount': self.parse_number(self.parse_precision(amountPrecisionStr)),
640
+ 'price': self.parse_number(self.parse_precision(pricePrecisionStr)),
641
+ },
642
+ 'limits': {
643
+ 'leverage': {
644
+ 'min': None,
645
+ 'max': None,
646
+ },
647
+ 'amount': {
648
+ 'min': None,
649
+ 'max': None,
650
+ },
651
+ 'price': {
652
+ 'min': None,
653
+ 'max': None,
654
+ },
655
+ 'cost': {
656
+ 'min': self.parse_number('10'),
657
+ 'max': None,
658
+ },
659
+ },
660
+ 'created': None,
661
+ 'info': self.extend(extraData, market),
662
+ }))
663
+ return markets
664
+
665
+ def parse_market(self, market: dict) -> Market:
666
+ #
667
+ # {
668
+ # "maxLeverage": "50",
669
+ # "name": "ETH",
670
+ # "onlyIsolated": False,
671
+ # "szDecimals": "4",
672
+ # "dayNtlVlm": "1709813.11535",
673
+ # "funding": "0.00004807",
674
+ # "impactPxs": [
675
+ # "2369.3",
676
+ # "2369.6"
677
+ # ],
678
+ # "markPx": "2369.6",
679
+ # "midPx": "2369.45",
680
+ # "openInterest": "1815.4712",
681
+ # "oraclePx": "2367.3",
682
+ # "premium": "0.00090821",
683
+ # "prevDayPx": "2381.5"
684
+ # }
685
+ #
686
+ quoteId = 'USDC'
687
+ base = self.safe_string(market, 'name')
688
+ quote = self.safe_currency_code(quoteId)
689
+ baseId = self.safe_string(market, 'baseId')
690
+ settleId = 'USDC'
691
+ settle = self.safe_currency_code(settleId)
692
+ symbol = base + '/' + quote
693
+ contract = True
694
+ swap = True
695
+ if contract:
696
+ if swap:
697
+ symbol = symbol + ':' + settle
698
+ fees = self.safe_dict(self.fees, 'swap', {})
699
+ taker = self.safe_number(fees, 'taker')
700
+ maker = self.safe_number(fees, 'maker')
701
+ amountPrecisionStr = self.safe_string(market, 'szDecimals')
702
+ amountPrecision = int(amountPrecisionStr)
703
+ price = self.safe_number(market, 'markPx', 0)
704
+ pricePrecision = 0
705
+ if price is not None:
706
+ pricePrecision = self.calculate_price_precision(price, amountPrecision, 6)
707
+ pricePrecisionStr = self.number_to_string(pricePrecision)
708
+ isDelisted = self.safe_bool(market, 'isDelisted')
709
+ active = True
710
+ if isDelisted is not None:
711
+ active = not isDelisted
712
+ return self.safe_market_structure({
713
+ 'id': baseId,
714
+ 'symbol': symbol,
715
+ 'base': base,
716
+ 'quote': quote,
717
+ 'settle': settle,
718
+ 'baseId': baseId,
719
+ 'quoteId': quoteId,
720
+ 'settleId': settleId,
721
+ 'type': 'swap',
722
+ 'spot': False,
723
+ 'margin': None,
724
+ 'swap': swap,
725
+ 'future': False,
726
+ 'option': False,
727
+ 'active': active,
728
+ 'contract': contract,
729
+ 'linear': True,
730
+ 'inverse': False,
731
+ 'taker': taker,
732
+ 'maker': maker,
733
+ 'contractSize': self.parse_number('1'),
734
+ 'expiry': None,
735
+ 'expiryDatetime': None,
736
+ 'strike': None,
737
+ 'optionType': None,
738
+ 'precision': {
739
+ 'amount': self.parse_number(self.parse_precision(amountPrecisionStr)),
740
+ 'price': self.parse_number(self.parse_precision(pricePrecisionStr)),
741
+ },
742
+ 'limits': {
743
+ 'leverage': {
744
+ 'min': None,
745
+ 'max': self.safe_integer(market, 'maxLeverage'),
746
+ },
747
+ 'amount': {
748
+ 'min': None,
749
+ 'max': None,
750
+ },
751
+ 'price': {
752
+ 'min': None,
753
+ 'max': None,
754
+ },
755
+ 'cost': {
756
+ 'min': self.parse_number('10'),
757
+ 'max': None,
758
+ },
759
+ },
760
+ 'created': None,
761
+ 'info': market,
762
+ })
763
+
764
+ def fetch_balance(self, params={}) -> Balances:
765
+ """
766
+ query for balance and get the amount of funds available for trading or funds locked in orders
767
+
768
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-a-users-token-balances
769
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary
770
+
771
+ :param dict [params]: extra parameters specific to the exchange API endpoint
772
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
773
+ :param str [params.type]: wallet type, ['spot', 'swap'], defaults to swap
774
+ :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
775
+ """
776
+ userAddress = None
777
+ userAddress, params = self.handle_public_address('fetchBalance', params)
778
+ type = None
779
+ type, params = self.handle_market_type_and_params('fetchBalance', None, params)
780
+ isSpot = (type == 'spot')
781
+ reqType = 'spotClearinghouseState' if (isSpot) else 'clearinghouseState'
782
+ request: dict = {
783
+ 'type': reqType,
784
+ 'user': userAddress,
785
+ }
786
+ response = self.publicPostInfo(self.extend(request, params))
787
+ #
788
+ # {
789
+ # "assetPositions": [],
790
+ # "crossMaintenanceMarginUsed": "0.0",
791
+ # "crossMarginSummary": {
792
+ # "accountValue": "100.0",
793
+ # "totalMarginUsed": "0.0",
794
+ # "totalNtlPos": "0.0",
795
+ # "totalRawUsd": "100.0"
796
+ # },
797
+ # "marginSummary": {
798
+ # "accountValue": "100.0",
799
+ # "totalMarginUsed": "0.0",
800
+ # "totalNtlPos": "0.0",
801
+ # "totalRawUsd": "100.0"
802
+ # },
803
+ # "time": "1704261007014",
804
+ # "withdrawable": "100.0"
805
+ # }
806
+ # spot
807
+ #
808
+ # {
809
+ # "balances":[
810
+ # {
811
+ # "coin":"USDC",
812
+ # "hold":"0.0",
813
+ # "total":"1481.844"
814
+ # },
815
+ # {
816
+ # "coin":"PURR",
817
+ # "hold":"0.0",
818
+ # "total":"999.65004"
819
+ # }
820
+ # }
821
+ #
822
+ balances = self.safe_list(response, 'balances')
823
+ if balances is not None:
824
+ spotBalances: dict = {'info': response}
825
+ for i in range(0, len(balances)):
826
+ balance = balances[i]
827
+ code = self.safe_currency_code(self.safe_string(balance, 'coin'))
828
+ account = self.account()
829
+ total = self.safe_string(balance, 'total')
830
+ used = self.safe_string(balance, 'hold')
831
+ account['total'] = total
832
+ account['used'] = used
833
+ spotBalances[code] = account
834
+ return self.safe_balance(spotBalances)
835
+ data = self.safe_dict(response, 'marginSummary', {})
836
+ result: dict = {
837
+ 'info': response,
838
+ 'USDC': {
839
+ 'total': self.safe_number(data, 'accountValue'),
840
+ 'free': self.safe_number(response, 'withdrawable'),
841
+ },
842
+ }
843
+ timestamp = self.safe_integer(response, 'time')
844
+ result['timestamp'] = timestamp
845
+ result['datetime'] = self.iso8601(timestamp)
846
+ return self.safe_balance(result)
847
+
848
+ def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
849
+ """
850
+ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
851
+
852
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#l2-book-snapshot
853
+
854
+ :param str symbol: unified symbol of the market to fetch the order book for
855
+ :param int [limit]: the maximum amount of order book entries to return
856
+ :param dict [params]: extra parameters specific to the exchange API endpoint
857
+ :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
858
+ """
859
+ self.load_markets()
860
+ market = self.market(symbol)
861
+ request: dict = {
862
+ 'type': 'l2Book',
863
+ 'coin': market['base'] if market['swap'] else market['id'],
864
+ }
865
+ response = self.publicPostInfo(self.extend(request, params))
866
+ #
867
+ # {
868
+ # "coin": "ETH",
869
+ # "levels": [
870
+ # [
871
+ # {
872
+ # "n": "2",
873
+ # "px": "2216.2",
874
+ # "sz": "74.0637"
875
+ # }
876
+ # ],
877
+ # [
878
+ # {
879
+ # "n": "2",
880
+ # "px": "2216.5",
881
+ # "sz": "70.5893"
882
+ # }
883
+ # ]
884
+ # ],
885
+ # "time": "1704290104840"
886
+ # }
887
+ #
888
+ data = self.safe_list(response, 'levels', [])
889
+ result: dict = {
890
+ 'bids': self.safe_list(data, 0, []),
891
+ 'asks': self.safe_list(data, 1, []),
892
+ }
893
+ timestamp = self.safe_integer(response, 'time')
894
+ return self.parse_order_book(result, market['symbol'], timestamp, 'bids', 'asks', 'px', 'sz')
895
+
896
+ def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
897
+ """
898
+ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
899
+
900
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
901
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts
902
+
903
+ :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
904
+ :param dict [params]: extra parameters specific to the exchange API endpoint
905
+ :param str [params.type]: 'spot' or 'swap', by default fetches both
906
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
907
+ """
908
+ self.load_markets()
909
+ symbols = self.market_symbols(symbols)
910
+ # at self stage, to get tickers data, we use fetchMarkets endpoints
911
+ response = []
912
+ type = self.safe_string(params, 'type')
913
+ params = self.omit(params, 'type')
914
+ if type == 'spot':
915
+ response = self.fetch_spot_markets(params)
916
+ elif type == 'swap':
917
+ response = self.fetch_swap_markets(params)
918
+ else:
919
+ response = self.fetch_markets(params)
920
+ # same response "fetchMarkets"
921
+ result: dict = {}
922
+ for i in range(0, len(response)):
923
+ market = response[i]
924
+ info = market['info']
925
+ ticker = self.parse_ticker(info, market)
926
+ symbol = self.safe_string(ticker, 'symbol')
927
+ result[symbol] = ticker
928
+ return self.filter_by_array_tickers(result, 'symbol', symbols)
929
+
930
+ def fetch_funding_rates(self, symbols: Strings = None, params={}) -> FundingRates:
931
+ """
932
+ retrieves data on all swap markets for hyperliquid
933
+
934
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
935
+
936
+ :param str[] [symbols]: list of unified market symbols
937
+ :param dict [params]: extra parameters specific to the exchange API endpoint
938
+ :returns dict[]: an array of objects representing market data
939
+ """
940
+ request: dict = {
941
+ 'type': 'metaAndAssetCtxs',
942
+ }
943
+ response = self.publicPostInfo(self.extend(request, params))
944
+ #
945
+ # [
946
+ # {
947
+ # "universe": [
948
+ # {
949
+ # "maxLeverage": 50,
950
+ # "name": "SOL",
951
+ # "onlyIsolated": False,
952
+ # "szDecimals": 2
953
+ # }
954
+ # ]
955
+ # },
956
+ # [
957
+ # {
958
+ # "dayNtlVlm": "9450588.2273",
959
+ # "funding": "0.0000198",
960
+ # "impactPxs": [
961
+ # "108.04",
962
+ # "108.06"
963
+ # ],
964
+ # "markPx": "108.04",
965
+ # "midPx": "108.05",
966
+ # "openInterest": "10764.48",
967
+ # "oraclePx": "107.99",
968
+ # "premium": "0.00055561",
969
+ # "prevDayPx": "111.81"
970
+ # }
971
+ # ]
972
+ # ]
973
+ #
974
+ #
975
+ meta = self.safe_dict(response, 0, {})
976
+ universe = self.safe_list(meta, 'universe', [])
977
+ assetCtxs = self.safe_list(response, 1, [])
978
+ result = []
979
+ for i in range(0, len(universe)):
980
+ data = self.extend(
981
+ self.safe_dict(universe, i, {}),
982
+ self.safe_dict(assetCtxs, i, {})
983
+ )
984
+ result.append(data)
985
+ return self.parse_funding_rates(result, symbols)
986
+
987
+ def parse_funding_rate(self, info, market: Market = None) -> FundingRate:
988
+ #
989
+ # {
990
+ # "maxLeverage": "50",
991
+ # "name": "ETH",
992
+ # "onlyIsolated": False,
993
+ # "szDecimals": "4",
994
+ # "dayNtlVlm": "1709813.11535",
995
+ # "funding": "0.00004807",
996
+ # "impactPxs": [
997
+ # "2369.3",
998
+ # "2369.6"
999
+ # ],
1000
+ # "markPx": "2369.6",
1001
+ # "midPx": "2369.45",
1002
+ # "openInterest": "1815.4712",
1003
+ # "oraclePx": "2367.3",
1004
+ # "premium": "0.00090821",
1005
+ # "prevDayPx": "2381.5"
1006
+ # }
1007
+ #
1008
+ base = self.safe_string(info, 'name')
1009
+ marketId = self.coin_to_market_id(base)
1010
+ symbol = self.safe_symbol(marketId, market)
1011
+ funding = self.safe_number(info, 'funding')
1012
+ markPx = self.safe_number(info, 'markPx')
1013
+ oraclePx = self.safe_number(info, 'oraclePx')
1014
+ fundingTimestamp = (int(math.floor(self.milliseconds()) / 60 / 60 / 1000) + 1) * 60 * 60 * 1000
1015
+ return {
1016
+ 'info': info,
1017
+ 'symbol': symbol,
1018
+ 'markPrice': markPx,
1019
+ 'indexPrice': oraclePx,
1020
+ 'interestRate': None,
1021
+ 'estimatedSettlePrice': None,
1022
+ 'timestamp': None,
1023
+ 'datetime': None,
1024
+ 'fundingRate': funding,
1025
+ 'fundingTimestamp': fundingTimestamp,
1026
+ 'fundingDatetime': self.iso8601(fundingTimestamp),
1027
+ 'nextFundingRate': None,
1028
+ 'nextFundingTimestamp': None,
1029
+ 'nextFundingDatetime': None,
1030
+ 'previousFundingRate': None,
1031
+ 'previousFundingTimestamp': None,
1032
+ 'previousFundingDatetime': None,
1033
+ 'interval': '1h',
1034
+ }
1035
+
1036
+ def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
1037
+ #
1038
+ # {
1039
+ # "prevDayPx": "3400.5",
1040
+ # "dayNtlVlm": "511297257.47936022",
1041
+ # "markPx": "3464.7",
1042
+ # "midPx": "3465.05",
1043
+ # "oraclePx": "3460.1", # only in swap
1044
+ # "openInterest": "64638.1108", # only in swap
1045
+ # "premium": "0.00141614", # only in swap
1046
+ # "funding": "0.00008727", # only in swap
1047
+ # "impactPxs": ["3465.0", "3465.1"], # only in swap
1048
+ # "coin": "PURR", # only in spot
1049
+ # "circulatingSupply": "998949190.03400207", # only in spot
1050
+ # },
1051
+ #
1052
+ bidAsk = self.safe_list(ticker, 'impactPxs')
1053
+ return self.safe_ticker({
1054
+ 'symbol': market['symbol'],
1055
+ 'timestamp': None,
1056
+ 'datetime': None,
1057
+ 'previousClose': self.safe_number(ticker, 'prevDayPx'),
1058
+ 'close': self.safe_number(ticker, 'midPx'),
1059
+ 'bid': self.safe_number(bidAsk, 0),
1060
+ 'ask': self.safe_number(bidAsk, 1),
1061
+ 'quoteVolume': self.safe_number(ticker, 'dayNtlVlm'),
1062
+ 'info': ticker,
1063
+ }, market)
1064
+
1065
+ def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
1066
+ """
1067
+ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
1068
+
1069
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candle-snapshot
1070
+
1071
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
1072
+ :param str timeframe: the length of time each candle represents, support '1m', '15m', '1h', '1d'
1073
+ :param int [since]: timestamp in ms of the earliest candle to fetch
1074
+ :param int [limit]: the maximum amount of candles to fetch
1075
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1076
+ :param int [params.until]: timestamp in ms of the latest candle to fetch
1077
+ :returns int[][]: A list of candles ordered, open, high, low, close, volume
1078
+ """
1079
+ self.load_markets()
1080
+ market = self.market(symbol)
1081
+ until = self.safe_integer(params, 'until', self.milliseconds())
1082
+ useTail = since is None
1083
+ originalSince = since
1084
+ if since is None:
1085
+ if limit is not None:
1086
+ # optimization if limit is provided
1087
+ timeframeInMilliseconds = self.parse_timeframe(timeframe) * 1000
1088
+ since = self.sum(until, timeframeInMilliseconds * limit * -1)
1089
+ useTail = False
1090
+ else:
1091
+ since = 0
1092
+ params = self.omit(params, ['until'])
1093
+ request: dict = {
1094
+ 'type': 'candleSnapshot',
1095
+ 'req': {
1096
+ 'coin': market['base'] if market['swap'] else market['id'],
1097
+ 'interval': self.safe_string(self.timeframes, timeframe, timeframe),
1098
+ 'startTime': since,
1099
+ 'endTime': until,
1100
+ },
1101
+ }
1102
+ response = self.publicPostInfo(self.extend(request, params))
1103
+ #
1104
+ # [
1105
+ # {
1106
+ # "T": 1704287699999,
1107
+ # "c": "2226.4",
1108
+ # "h": "2247.9",
1109
+ # "i": "15m",
1110
+ # "l": "2224.6",
1111
+ # "n": 46,
1112
+ # "o": "2247.9",
1113
+ # "s": "ETH",
1114
+ # "t": 1704286800000,
1115
+ # "v": "591.6427"
1116
+ # }
1117
+ # ]
1118
+ #
1119
+ return self.parse_ohlcvs(response, market, timeframe, originalSince, limit, useTail)
1120
+
1121
+ def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
1122
+ #
1123
+ # {
1124
+ # "T": 1704287699999,
1125
+ # "c": "2226.4",
1126
+ # "h": "2247.9",
1127
+ # "i": "15m",
1128
+ # "l": "2224.6",
1129
+ # "n": 46,
1130
+ # "o": "2247.9",
1131
+ # "s": "ETH",
1132
+ # "t": 1704286800000,
1133
+ # "v": "591.6427"
1134
+ # }
1135
+ #
1136
+ return [
1137
+ self.safe_integer(ohlcv, 't'),
1138
+ self.safe_number(ohlcv, 'o'),
1139
+ self.safe_number(ohlcv, 'h'),
1140
+ self.safe_number(ohlcv, 'l'),
1141
+ self.safe_number(ohlcv, 'c'),
1142
+ self.safe_number(ohlcv, 'v'),
1143
+ ]
1144
+
1145
+ def fetch_trades(self, symbol: Str, since: Int = None, limit: Int = None, params={}):
1146
+ """
1147
+ get the list of most recent trades for a particular symbol
1148
+
1149
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
1150
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time
1151
+
1152
+ :param str symbol: unified market symbol
1153
+ :param int [since]: the earliest time in ms to fetch trades for
1154
+ :param int [limit]: the maximum number of trades structures to retrieve
1155
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1156
+ :param int [params.until]: timestamp in ms of the latest trade
1157
+ :param str [params.address]: wallet address that made trades
1158
+ :param str [params.user]: wallet address that made trades
1159
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
1160
+ """
1161
+ userAddress = None
1162
+ userAddress, params = self.handle_public_address('fetchTrades', params)
1163
+ self.load_markets()
1164
+ market = self.safe_market(symbol)
1165
+ request: dict = {
1166
+ 'user': userAddress,
1167
+ }
1168
+ if since is not None:
1169
+ request['type'] = 'userFillsByTime'
1170
+ request['startTime'] = since
1171
+ else:
1172
+ request['type'] = 'userFills'
1173
+ until = self.safe_integer(params, 'until')
1174
+ params = self.omit(params, 'until')
1175
+ if until is not None:
1176
+ request['endTime'] = until
1177
+ response = self.publicPostInfo(self.extend(request, params))
1178
+ #
1179
+ # [
1180
+ # {
1181
+ # "closedPnl": "0.19343",
1182
+ # "coin": "ETH",
1183
+ # "crossed": True,
1184
+ # "dir": "Close Long",
1185
+ # "fee": "0.050062",
1186
+ # "hash": "0x09d77c96791e98b5775a04092584ab010d009445119c71e4005c0d634ea322bc",
1187
+ # "liquidationMarkPx": null,
1188
+ # "oid": 3929354691,
1189
+ # "px": "2381.1",
1190
+ # "side": "A",
1191
+ # "startPosition": "0.0841",
1192
+ # "sz": "0.0841",
1193
+ # "tid": 128423918764978,
1194
+ # "time": 1704262888911
1195
+ # }
1196
+ # ]
1197
+ #
1198
+ return self.parse_trades(response, market, since, limit)
1199
+
1200
+ def amount_to_precision(self, symbol, amount):
1201
+ market = self.market(symbol)
1202
+ return self.decimal_to_precision(amount, ROUND, market['precision']['amount'], self.precisionMode, self.paddingMode)
1203
+
1204
+ def price_to_precision(self, symbol: str, price) -> str:
1205
+ market = self.market(symbol)
1206
+ priceStr = self.number_to_string(price)
1207
+ integerPart = priceStr.split('.')[0]
1208
+ significantDigits = max(5, len(integerPart))
1209
+ result = self.decimal_to_precision(price, ROUND, significantDigits, SIGNIFICANT_DIGITS, self.paddingMode)
1210
+ maxDecimals = 8 if market['spot'] else 6
1211
+ subtractedValue = maxDecimals - self.precision_from_string(self.safe_string(market['precision'], 'amount'))
1212
+ return self.decimal_to_precision(result, ROUND, subtractedValue, DECIMAL_PLACES, self.paddingMode)
1213
+
1214
+ def hash_message(self, message):
1215
+ return '0x' + self.hash(message, 'keccak', 'hex')
1216
+
1217
+ def sign_hash(self, hash, privateKey):
1218
+ signature = self.ecdsa(hash[-64:], privateKey[-64:], 'secp256k1', None)
1219
+ return {
1220
+ 'r': '0x' + signature['r'],
1221
+ 's': '0x' + signature['s'],
1222
+ 'v': self.sum(27, signature['v']),
1223
+ }
1224
+
1225
+ def sign_message(self, message, privateKey):
1226
+ return self.sign_hash(self.hash_message(message), privateKey[-64:])
1227
+
1228
+ def construct_phantom_agent(self, hash, isTestnet=True):
1229
+ source = 'b' if (isTestnet) else 'a'
1230
+ return {
1231
+ 'source': source,
1232
+ 'connectionId': hash,
1233
+ }
1234
+
1235
+ def action_hash(self, action, vaultAddress, nonce):
1236
+ dataBinary = self.packb(action)
1237
+ dataHex = self.binary_to_base16(dataBinary)
1238
+ data = dataHex
1239
+ data += '00000' + self.int_to_base16(nonce)
1240
+ if vaultAddress is None:
1241
+ data += '00'
1242
+ else:
1243
+ data += '01'
1244
+ data += vaultAddress
1245
+ return self.hash(self.base16_to_binary(data), 'keccak', 'binary')
1246
+
1247
+ def sign_l1_action(self, action, nonce, vaultAdress=None) -> object:
1248
+ hash = self.action_hash(action, vaultAdress, nonce)
1249
+ isTestnet = self.safe_bool(self.options, 'sandboxMode', False)
1250
+ phantomAgent = self.construct_phantom_agent(hash, isTestnet)
1251
+ # data: Dict = {
1252
+ # 'domain': {
1253
+ # 'chainId': 1337,
1254
+ # 'name': 'Exchange',
1255
+ # 'verifyingContract': '0x0000000000000000000000000000000000000000',
1256
+ # 'version': '1',
1257
+ # },
1258
+ # 'types': {
1259
+ # 'Agent': [
1260
+ # {'name': 'source', 'type': 'string'},
1261
+ # {'name': 'connectionId', 'type': 'bytes32'},
1262
+ # ],
1263
+ # 'EIP712Domain': [
1264
+ # {'name': 'name', 'type': 'string'},
1265
+ # {'name': 'version', 'type': 'string'},
1266
+ # {'name': 'chainId', 'type': 'uint256'},
1267
+ # {'name': 'verifyingContract', 'type': 'address'},
1268
+ # ],
1269
+ # },
1270
+ # 'primaryType': 'Agent',
1271
+ # 'message': phantomAgent,
1272
+ # }
1273
+ zeroAddress = self.safe_string(self.options, 'zeroAddress')
1274
+ chainId = 1337 # check self out
1275
+ domain: dict = {
1276
+ 'chainId': chainId,
1277
+ 'name': 'Exchange',
1278
+ 'verifyingContract': zeroAddress,
1279
+ 'version': '1',
1280
+ }
1281
+ messageTypes: dict = {
1282
+ 'Agent': [
1283
+ {'name': 'source', 'type': 'string'},
1284
+ {'name': 'connectionId', 'type': 'bytes32'},
1285
+ ],
1286
+ }
1287
+ msg = self.eth_encode_structured_data(domain, messageTypes, phantomAgent)
1288
+ signature = self.sign_message(msg, self.privateKey)
1289
+ return signature
1290
+
1291
+ def sign_user_signed_action(self, messageTypes, message):
1292
+ zeroAddress = self.safe_string(self.options, 'zeroAddress')
1293
+ chainId = 421614 # check self out
1294
+ domain: dict = {
1295
+ 'chainId': chainId,
1296
+ 'name': 'HyperliquidSignTransaction',
1297
+ 'verifyingContract': zeroAddress,
1298
+ 'version': '1',
1299
+ }
1300
+ msg = self.eth_encode_structured_data(domain, messageTypes, message)
1301
+ signature = self.sign_message(msg, self.privateKey)
1302
+ return signature
1303
+
1304
+ def build_usd_send_sig(self, message):
1305
+ messageTypes: dict = {
1306
+ 'HyperliquidTransaction:UsdSend': [
1307
+ {'name': 'hyperliquidChain', 'type': 'string'},
1308
+ {'name': 'destination', 'type': 'string'},
1309
+ {'name': 'amount', 'type': 'string'},
1310
+ {'name': 'time', 'type': 'uint64'},
1311
+ ],
1312
+ }
1313
+ return self.sign_user_signed_action(messageTypes, message)
1314
+
1315
+ def build_usd_class_send_sig(self, message):
1316
+ messageTypes: dict = {
1317
+ 'HyperliquidTransaction:UsdClassTransfer': [
1318
+ {'name': 'hyperliquidChain', 'type': 'string'},
1319
+ {'name': 'amount', 'type': 'string'},
1320
+ {'name': 'toPerp', 'type': 'bool'},
1321
+ {'name': 'nonce', 'type': 'uint64'},
1322
+ ],
1323
+ }
1324
+ return self.sign_user_signed_action(messageTypes, message)
1325
+
1326
+ def build_withdraw_sig(self, message):
1327
+ messageTypes: dict = {
1328
+ 'HyperliquidTransaction:Withdraw': [
1329
+ {'name': 'hyperliquidChain', 'type': 'string'},
1330
+ {'name': 'destination', 'type': 'string'},
1331
+ {'name': 'amount', 'type': 'string'},
1332
+ {'name': 'time', 'type': 'uint64'},
1333
+ ],
1334
+ }
1335
+ return self.sign_user_signed_action(messageTypes, message)
1336
+
1337
+ def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1338
+ """
1339
+ create a trade order
1340
+
1341
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
1342
+
1343
+ :param str symbol: unified symbol of the market to create an order in
1344
+ :param str type: 'market' or 'limit'
1345
+ :param str side: 'buy' or 'sell'
1346
+ :param float amount: how much of currency you want to trade in units of base currency
1347
+ :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1348
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1349
+ :param str [params.timeInForce]: 'Gtc', 'Ioc', 'Alo'
1350
+ :param bool [params.postOnly]: True or False whether the order is post-only
1351
+ :param bool [params.reduceOnly]: True or False whether the order is reduce-only
1352
+ :param float [params.triggerPrice]: The price at which a trigger order is triggered at
1353
+ :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
1354
+ :param str [params.slippage]: the slippage for market order
1355
+ :param str [params.vaultAddress]: the vault address for order
1356
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1357
+ """
1358
+ self.load_markets()
1359
+ order, globalParams = self.parse_create_edit_order_args(None, symbol, type, side, amount, price, params)
1360
+ orders = self.create_orders([order], globalParams)
1361
+ return orders[0]
1362
+
1363
+ def create_orders(self, orders: List[OrderRequest], params={}):
1364
+ """
1365
+ create a list of trade orders
1366
+
1367
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
1368
+
1369
+ :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
1370
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1371
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1372
+ """
1373
+ self.load_markets()
1374
+ request = self.create_orders_request(orders, params)
1375
+ response = self.privatePostExchange(request)
1376
+ #
1377
+ # {
1378
+ # "status": "ok",
1379
+ # "response": {
1380
+ # "type": "order",
1381
+ # "data": {
1382
+ # "statuses": [
1383
+ # {
1384
+ # "resting": {
1385
+ # "oid": 5063830287
1386
+ # }
1387
+ # }
1388
+ # ]
1389
+ # }
1390
+ # }
1391
+ # }
1392
+ #
1393
+ responseObj = self.safe_dict(response, 'response', {})
1394
+ data = self.safe_dict(responseObj, 'data', {})
1395
+ statuses = self.safe_list(data, 'statuses', [])
1396
+ return self.parse_orders(statuses, None)
1397
+
1398
+ def create_orders_request(self, orders, params={}) -> dict:
1399
+ """
1400
+ create a list of trade orders
1401
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
1402
+ :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
1403
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1404
+ """
1405
+ self.check_required_credentials()
1406
+ defaultSlippage = self.safe_string(self.options, 'defaultSlippage')
1407
+ defaultSlippage = self.safe_string(params, 'slippage', defaultSlippage)
1408
+ hasClientOrderId = False
1409
+ for i in range(0, len(orders)):
1410
+ rawOrder = orders[i]
1411
+ orderParams = self.safe_dict(rawOrder, 'params', {})
1412
+ clientOrderId = self.safe_string_2(orderParams, 'clientOrderId', 'client_id')
1413
+ if clientOrderId is not None:
1414
+ hasClientOrderId = True
1415
+ if hasClientOrderId:
1416
+ for i in range(0, len(orders)):
1417
+ rawOrder = orders[i]
1418
+ orderParams = self.safe_dict(rawOrder, 'params', {})
1419
+ clientOrderId = self.safe_string_2(orderParams, 'clientOrderId', 'client_id')
1420
+ if clientOrderId is None:
1421
+ raise ArgumentsRequired(self.id + ' createOrders() all orders must have clientOrderId if at least one has a clientOrderId')
1422
+ params = self.omit(params, ['slippage', 'clientOrderId', 'client_id', 'slippage', 'triggerPrice', 'stopPrice', 'stopLossPrice', 'takeProfitPrice', 'timeInForce'])
1423
+ nonce = self.milliseconds()
1424
+ orderReq = []
1425
+ for i in range(0, len(orders)):
1426
+ rawOrder = orders[i]
1427
+ marketId = self.safe_string(rawOrder, 'symbol')
1428
+ market = self.market(marketId)
1429
+ symbol = market['symbol']
1430
+ type = self.safe_string_upper(rawOrder, 'type')
1431
+ isMarket = (type == 'MARKET')
1432
+ side = self.safe_string_upper(rawOrder, 'side')
1433
+ isBuy = (side == 'BUY')
1434
+ amount = self.safe_string(rawOrder, 'amount')
1435
+ price = self.safe_string(rawOrder, 'price')
1436
+ orderParams = self.safe_dict(rawOrder, 'params', {})
1437
+ clientOrderId = self.safe_string_2(orderParams, 'clientOrderId', 'client_id')
1438
+ slippage = self.safe_string(orderParams, 'slippage', defaultSlippage)
1439
+ defaultTimeInForce = 'ioc' if (isMarket) else 'gtc'
1440
+ postOnly = self.safe_bool(orderParams, 'postOnly', False)
1441
+ if postOnly:
1442
+ defaultTimeInForce = 'alo'
1443
+ timeInForce = self.safe_string_lower(orderParams, 'timeInForce', defaultTimeInForce)
1444
+ timeInForce = self.capitalize(timeInForce)
1445
+ triggerPrice = self.safe_string_2(orderParams, 'triggerPrice', 'stopPrice')
1446
+ stopLossPrice = self.safe_string(orderParams, 'stopLossPrice', triggerPrice)
1447
+ takeProfitPrice = self.safe_string(orderParams, 'takeProfitPrice')
1448
+ isTrigger = (stopLossPrice or takeProfitPrice)
1449
+ px = None
1450
+ if isMarket:
1451
+ if price is None:
1452
+ raise ArgumentsRequired(self.id + ' market orders require price to calculate the max slippage price. Default slippage can be set in options(default is 5%).')
1453
+ px = Precise.string_mul(price, Precise.string_add('1', slippage)) if (isBuy) else Precise.string_mul(price, Precise.string_sub('1', slippage))
1454
+ px = self.price_to_precision(symbol, px) # round after adding slippage
1455
+ else:
1456
+ px = self.price_to_precision(symbol, price)
1457
+ sz = self.amount_to_precision(symbol, amount)
1458
+ reduceOnly = self.safe_bool(orderParams, 'reduceOnly', False)
1459
+ orderType: dict = {}
1460
+ if isTrigger:
1461
+ isTp = False
1462
+ if takeProfitPrice is not None:
1463
+ triggerPrice = self.price_to_precision(symbol, takeProfitPrice)
1464
+ isTp = True
1465
+ else:
1466
+ triggerPrice = self.price_to_precision(symbol, stopLossPrice)
1467
+ orderType['trigger'] = {
1468
+ 'isMarket': isMarket,
1469
+ 'triggerPx': triggerPrice,
1470
+ 'tpsl': 'tp' if (isTp) else 'sl',
1471
+ }
1472
+ else:
1473
+ orderType['limit'] = {
1474
+ 'tif': timeInForce,
1475
+ }
1476
+ orderParams = self.omit(orderParams, ['clientOrderId', 'slippage', 'triggerPrice', 'stopPrice', 'stopLossPrice', 'takeProfitPrice', 'timeInForce', 'client_id', 'reduceOnly', 'postOnly'])
1477
+ orderObj: dict = {
1478
+ 'a': self.parse_to_int(market['baseId']),
1479
+ 'b': isBuy,
1480
+ 'p': px,
1481
+ 's': sz,
1482
+ 'r': reduceOnly,
1483
+ 't': orderType,
1484
+ # 'c': clientOrderId,
1485
+ }
1486
+ if clientOrderId is not None:
1487
+ orderObj['c'] = clientOrderId
1488
+ orderReq.append(orderObj)
1489
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
1490
+ orderAction: dict = {
1491
+ 'type': 'order',
1492
+ 'orders': orderReq,
1493
+ 'grouping': 'na',
1494
+ # 'brokerCode': 1, # cant
1495
+ }
1496
+ if vaultAddress is None:
1497
+ orderAction['brokerCode'] = 1
1498
+ signature = self.sign_l1_action(orderAction, nonce, vaultAddress)
1499
+ request: dict = {
1500
+ 'action': orderAction,
1501
+ 'nonce': nonce,
1502
+ 'signature': signature,
1503
+ # 'vaultAddress': vaultAddress,
1504
+ }
1505
+ if vaultAddress is not None:
1506
+ params = self.omit(params, 'vaultAddress')
1507
+ request['vaultAddress'] = vaultAddress
1508
+ return request
1509
+
1510
+ def cancel_order(self, id: str, symbol: Str = None, params={}):
1511
+ """
1512
+ cancels an open order
1513
+
1514
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
1515
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
1516
+
1517
+ :param str id: order id
1518
+ :param str symbol: unified symbol of the market the order was made in
1519
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1520
+ :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
1521
+ :param str [params.vaultAddress]: the vault address for order
1522
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1523
+ """
1524
+ orders = self.cancel_orders([id], symbol, params)
1525
+ return self.safe_dict(orders, 0)
1526
+
1527
+ def cancel_orders(self, ids: List[str], symbol: Str = None, params={}):
1528
+ """
1529
+ cancel multiple orders
1530
+
1531
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
1532
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
1533
+
1534
+ :param str[] ids: order ids
1535
+ :param str [symbol]: unified market symbol
1536
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1537
+ :param string|str[] [params.clientOrderId]: client order ids,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
1538
+ :param str [params.vaultAddress]: the vault address
1539
+ :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1540
+ """
1541
+ self.check_required_credentials()
1542
+ if symbol is None:
1543
+ raise ArgumentsRequired(self.id + ' cancelOrders() requires a symbol argument')
1544
+ self.load_markets()
1545
+ market = self.market(symbol)
1546
+ clientOrderId = self.safe_value_2(params, 'clientOrderId', 'client_id')
1547
+ params = self.omit(params, ['clientOrderId', 'client_id'])
1548
+ nonce = self.milliseconds()
1549
+ request: dict = {
1550
+ 'nonce': nonce,
1551
+ # 'vaultAddress': vaultAddress,
1552
+ }
1553
+ cancelReq = []
1554
+ cancelAction: dict = {
1555
+ 'type': '',
1556
+ 'cancels': [],
1557
+ }
1558
+ baseId = self.parse_to_numeric(market['baseId'])
1559
+ if clientOrderId is not None:
1560
+ if not isinstance(clientOrderId, list):
1561
+ clientOrderId = [clientOrderId]
1562
+ cancelAction['type'] = 'cancelByCloid'
1563
+ for i in range(0, len(clientOrderId)):
1564
+ cancelReq.append({
1565
+ 'asset': baseId,
1566
+ 'cloid': clientOrderId[i],
1567
+ })
1568
+ else:
1569
+ cancelAction['type'] = 'cancel'
1570
+ for i in range(0, len(ids)):
1571
+ cancelReq.append({
1572
+ 'a': baseId,
1573
+ 'o': self.parse_to_numeric(ids[i]),
1574
+ })
1575
+ cancelAction['cancels'] = cancelReq
1576
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
1577
+ signature = self.sign_l1_action(cancelAction, nonce, vaultAddress)
1578
+ request['action'] = cancelAction
1579
+ request['signature'] = signature
1580
+ if vaultAddress is not None:
1581
+ params = self.omit(params, 'vaultAddress')
1582
+ request['vaultAddress'] = vaultAddress
1583
+ response = self.privatePostExchange(request)
1584
+ #
1585
+ # {
1586
+ # "status":"ok",
1587
+ # "response":{
1588
+ # "type":"cancel",
1589
+ # "data":{
1590
+ # "statuses":[
1591
+ # "success"
1592
+ # ]
1593
+ # }
1594
+ # }
1595
+ # }
1596
+ #
1597
+ innerResponse = self.safe_dict(response, 'response')
1598
+ data = self.safe_dict(innerResponse, 'data')
1599
+ statuses = self.safe_list(data, 'statuses')
1600
+ orders = []
1601
+ for i in range(0, len(statuses)):
1602
+ status = statuses[i]
1603
+ orders.append(self.safe_order({
1604
+ 'info': status,
1605
+ 'status': status,
1606
+ }))
1607
+ return orders
1608
+
1609
+ def cancel_orders_for_symbols(self, orders: List[CancellationRequest], params={}):
1610
+ """
1611
+ cancel multiple orders for multiple symbols
1612
+
1613
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
1614
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
1615
+
1616
+ :param CancellationRequest[] orders: each order should contain the parameters required by cancelOrder namely id and symbol, example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}]
1617
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1618
+ :param str [params.vaultAddress]: the vault address
1619
+ :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1620
+ """
1621
+ self.check_required_credentials()
1622
+ self.load_markets()
1623
+ nonce = self.milliseconds()
1624
+ request: dict = {
1625
+ 'nonce': nonce,
1626
+ # 'vaultAddress': vaultAddress,
1627
+ }
1628
+ cancelReq = []
1629
+ cancelAction: dict = {
1630
+ 'type': '',
1631
+ 'cancels': [],
1632
+ }
1633
+ cancelByCloid = False
1634
+ for i in range(0, len(orders)):
1635
+ order = orders[i]
1636
+ clientOrderId = self.safe_string(order, 'clientOrderId')
1637
+ if clientOrderId is not None:
1638
+ cancelByCloid = True
1639
+ id = self.safe_string(order, 'id')
1640
+ symbol = self.safe_string(order, 'symbol')
1641
+ if symbol is None:
1642
+ raise ArgumentsRequired(self.id + ' cancelOrdersForSymbols() requires a symbol argument in each order')
1643
+ if id is not None and cancelByCloid:
1644
+ raise BadRequest(self.id + ' cancelOrdersForSymbols() all orders must have either id or clientOrderId')
1645
+ assetKey = 'asset' if cancelByCloid else 'a'
1646
+ idKey = 'cloid' if cancelByCloid else 'o'
1647
+ market = self.market(symbol)
1648
+ cancelObj: dict = {}
1649
+ cancelObj[assetKey] = self.parse_to_numeric(market['baseId'])
1650
+ cancelObj[idKey] = clientOrderId if cancelByCloid else self.parse_to_numeric(id)
1651
+ cancelReq.append(cancelObj)
1652
+ cancelAction['type'] = 'cancelByCloid' if cancelByCloid else 'cancel'
1653
+ cancelAction['cancels'] = cancelReq
1654
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
1655
+ signature = self.sign_l1_action(cancelAction, nonce, vaultAddress)
1656
+ request['action'] = cancelAction
1657
+ request['signature'] = signature
1658
+ if vaultAddress is not None:
1659
+ params = self.omit(params, 'vaultAddress')
1660
+ request['vaultAddress'] = vaultAddress
1661
+ response = self.privatePostExchange(request)
1662
+ #
1663
+ # {
1664
+ # "status":"ok",
1665
+ # "response":{
1666
+ # "type":"cancel",
1667
+ # "data":{
1668
+ # "statuses":[
1669
+ # "success"
1670
+ # ]
1671
+ # }
1672
+ # }
1673
+ # }
1674
+ #
1675
+ return response
1676
+
1677
+ def cancel_all_orders_after(self, timeout: Int, params={}):
1678
+ """
1679
+ dead man's switch, cancel all orders after the given timeout
1680
+ :param number timeout: time in milliseconds, 0 represents cancel the timer
1681
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1682
+ :param str [params.vaultAddress]: the vault address
1683
+ :returns dict: the api result
1684
+ """
1685
+ self.check_required_credentials()
1686
+ self.load_markets()
1687
+ params = self.omit(params, ['clientOrderId', 'client_id'])
1688
+ nonce = self.milliseconds()
1689
+ request: dict = {
1690
+ 'nonce': nonce,
1691
+ # 'vaultAddress': vaultAddress,
1692
+ }
1693
+ cancelAction: dict = {
1694
+ 'type': 'scheduleCancel',
1695
+ 'time': nonce + timeout,
1696
+ }
1697
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
1698
+ signature = self.sign_l1_action(cancelAction, nonce, vaultAddress)
1699
+ request['action'] = cancelAction
1700
+ request['signature'] = signature
1701
+ if vaultAddress is not None:
1702
+ params = self.omit(params, 'vaultAddress')
1703
+ request['vaultAddress'] = vaultAddress
1704
+ response = self.privatePostExchange(request)
1705
+ #
1706
+ # {
1707
+ # "status":"err",
1708
+ # "response":"Cannot set scheduled cancel time until enough volume traded. Required: $1000000. Traded: $373.47205."
1709
+ # }
1710
+ #
1711
+ return response
1712
+
1713
+ def edit_orders_request(self, orders, params={}):
1714
+ self.check_required_credentials()
1715
+ hasClientOrderId = False
1716
+ for i in range(0, len(orders)):
1717
+ rawOrder = orders[i]
1718
+ orderParams = self.safe_dict(rawOrder, 'params', {})
1719
+ clientOrderId = self.safe_string_2(orderParams, 'clientOrderId', 'client_id')
1720
+ if clientOrderId is not None:
1721
+ hasClientOrderId = True
1722
+ if hasClientOrderId:
1723
+ for i in range(0, len(orders)):
1724
+ rawOrder = orders[i]
1725
+ orderParams = self.safe_dict(rawOrder, 'params', {})
1726
+ clientOrderId = self.safe_string_2(orderParams, 'clientOrderId', 'client_id')
1727
+ if clientOrderId is None:
1728
+ raise ArgumentsRequired(self.id + ' editOrders() all orders must have clientOrderId if at least one has a clientOrderId')
1729
+ params = self.omit(params, ['slippage', 'clientOrderId', 'client_id', 'slippage', 'triggerPrice', 'stopPrice', 'stopLossPrice', 'takeProfitPrice', 'timeInForce'])
1730
+ modifies = []
1731
+ for i in range(0, len(orders)):
1732
+ rawOrder = orders[i]
1733
+ id = self.safe_string(rawOrder, 'id')
1734
+ marketId = self.safe_string(rawOrder, 'symbol')
1735
+ market = self.market(marketId)
1736
+ symbol = market['symbol']
1737
+ type = self.safe_string_upper(rawOrder, 'type')
1738
+ isMarket = (type == 'MARKET')
1739
+ side = self.safe_string_upper(rawOrder, 'side')
1740
+ isBuy = (side == 'BUY')
1741
+ amount = self.safe_string(rawOrder, 'amount')
1742
+ price = self.safe_string(rawOrder, 'price')
1743
+ orderParams = self.safe_dict(rawOrder, 'params', {})
1744
+ defaultSlippage = self.safe_string(self.options, 'defaultSlippage')
1745
+ slippage = self.safe_string(orderParams, 'slippage', defaultSlippage)
1746
+ defaultTimeInForce = 'ioc' if (isMarket) else 'gtc'
1747
+ postOnly = self.safe_bool(orderParams, 'postOnly', False)
1748
+ if postOnly:
1749
+ defaultTimeInForce = 'alo'
1750
+ timeInForce = self.safe_string_lower(orderParams, 'timeInForce', defaultTimeInForce)
1751
+ timeInForce = self.capitalize(timeInForce)
1752
+ clientOrderId = self.safe_string_2(orderParams, 'clientOrderId', 'client_id')
1753
+ triggerPrice = self.safe_string_2(orderParams, 'triggerPrice', 'stopPrice')
1754
+ stopLossPrice = self.safe_string(orderParams, 'stopLossPrice', triggerPrice)
1755
+ takeProfitPrice = self.safe_string(orderParams, 'takeProfitPrice')
1756
+ isTrigger = (stopLossPrice or takeProfitPrice)
1757
+ reduceOnly = self.safe_bool(orderParams, 'reduceOnly', False)
1758
+ orderParams = self.omit(orderParams, ['slippage', 'timeInForce', 'triggerPrice', 'stopLossPrice', 'takeProfitPrice', 'clientOrderId', 'client_id', 'postOnly', 'reduceOnly'])
1759
+ px = str(price)
1760
+ if isMarket:
1761
+ px = str(Precise.string_mul(price), Precise.string_add('1', slippage)) if (isBuy) else str(Precise.string_mul(price), Precise.string_sub('1', slippage))
1762
+ else:
1763
+ px = self.price_to_precision(symbol, str(price))
1764
+ sz = self.amount_to_precision(symbol, amount)
1765
+ orderType: dict = {}
1766
+ if isTrigger:
1767
+ isTp = False
1768
+ if takeProfitPrice is not None:
1769
+ triggerPrice = self.price_to_precision(symbol, takeProfitPrice)
1770
+ isTp = True
1771
+ else:
1772
+ triggerPrice = self.price_to_precision(symbol, stopLossPrice)
1773
+ orderType['trigger'] = {
1774
+ 'isMarket': isMarket,
1775
+ 'triggerPx': triggerPrice,
1776
+ 'tpsl': 'tp' if (isTp) else 'sl',
1777
+ }
1778
+ else:
1779
+ orderType['limit'] = {
1780
+ 'tif': timeInForce,
1781
+ }
1782
+ if triggerPrice is None:
1783
+ triggerPrice = '0'
1784
+ orderReq: dict = {
1785
+ 'a': self.parse_to_int(market['baseId']),
1786
+ 'b': isBuy,
1787
+ 'p': px,
1788
+ 's': sz,
1789
+ 'r': reduceOnly,
1790
+ 't': orderType,
1791
+ # 'c': clientOrderId,
1792
+ }
1793
+ if clientOrderId is not None:
1794
+ orderReq['c'] = clientOrderId
1795
+ modifyReq: dict = {
1796
+ 'oid': self.parse_to_int(id),
1797
+ 'order': orderReq,
1798
+ }
1799
+ modifies.append(modifyReq)
1800
+ nonce = self.milliseconds()
1801
+ modifyAction: dict = {
1802
+ 'type': 'batchModify',
1803
+ 'modifies': modifies,
1804
+ }
1805
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
1806
+ signature = self.sign_l1_action(modifyAction, nonce, vaultAddress)
1807
+ request: dict = {
1808
+ 'action': modifyAction,
1809
+ 'nonce': nonce,
1810
+ 'signature': signature,
1811
+ # 'vaultAddress': vaultAddress,
1812
+ }
1813
+ if vaultAddress is not None:
1814
+ params = self.omit(params, 'vaultAddress')
1815
+ request['vaultAddress'] = vaultAddress
1816
+ return request
1817
+
1818
+ def edit_order(self, id: str, symbol: str, type: str, side: str, amount: Num = None, price: Num = None, params={}):
1819
+ """
1820
+ edit a trade order
1821
+
1822
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#modify-multiple-orders
1823
+
1824
+ :param str id: cancel order id
1825
+ :param str symbol: unified symbol of the market to create an order in
1826
+ :param str type: 'market' or 'limit'
1827
+ :param str side: 'buy' or 'sell'
1828
+ :param float amount: how much of currency you want to trade in units of base currency
1829
+ :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1830
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1831
+ :param str [params.timeInForce]: 'Gtc', 'Ioc', 'Alo'
1832
+ :param bool [params.postOnly]: True or False whether the order is post-only
1833
+ :param bool [params.reduceOnly]: True or False whether the order is reduce-only
1834
+ :param float [params.triggerPrice]: The price at which a trigger order is triggered at
1835
+ :param str [params.clientOrderId]: client order id,(optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
1836
+ :param str [params.vaultAddress]: the vault address for order
1837
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1838
+ """
1839
+ self.load_markets()
1840
+ if id is None:
1841
+ raise ArgumentsRequired(self.id + ' editOrder() requires an id argument')
1842
+ order, globalParams = self.parse_create_edit_order_args(id, symbol, type, side, amount, price, params)
1843
+ orders = self.edit_orders([order], globalParams)
1844
+ return orders[0]
1845
+
1846
+ def edit_orders(self, orders: List[OrderRequest], params={}):
1847
+ """
1848
+ edit a list of trade orders
1849
+
1850
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#modify-multiple-orders
1851
+
1852
+ :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
1853
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1854
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1855
+ """
1856
+ self.load_markets()
1857
+ request = self.edit_orders_request(orders, params)
1858
+ response = self.privatePostExchange(request)
1859
+ #
1860
+ # {
1861
+ # "status": "ok",
1862
+ # "response": {
1863
+ # "type": "order",
1864
+ # "data": {
1865
+ # "statuses": [
1866
+ # {
1867
+ # "resting": {
1868
+ # "oid": 5063830287
1869
+ # }
1870
+ # }
1871
+ # ]
1872
+ # }
1873
+ # }
1874
+ # }
1875
+ # when the order is filled immediately
1876
+ # {
1877
+ # "status":"ok",
1878
+ # "response":{
1879
+ # "type":"order",
1880
+ # "data":{
1881
+ # "statuses":[
1882
+ # {
1883
+ # "filled":{
1884
+ # "totalSz":"0.1",
1885
+ # "avgPx":"100.84",
1886
+ # "oid":6195281425
1887
+ # }
1888
+ # }
1889
+ # ]
1890
+ # }
1891
+ # }
1892
+ # }
1893
+ #
1894
+ responseObject = self.safe_dict(response, 'response', {})
1895
+ dataObject = self.safe_dict(responseObject, 'data', {})
1896
+ statuses = self.safe_list(dataObject, 'statuses', [])
1897
+ return self.parse_orders(statuses)
1898
+
1899
+ def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1900
+ """
1901
+ fetches historical funding rate prices
1902
+
1903
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-historical-funding-rates
1904
+
1905
+ :param str symbol: unified symbol of the market to fetch the funding rate history for
1906
+ :param int [since]: timestamp in ms of the earliest funding rate to fetch
1907
+ :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
1908
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1909
+ :param int [params.until]: timestamp in ms of the latest funding rate
1910
+ :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
1911
+ """
1912
+ self.load_markets()
1913
+ if symbol is None:
1914
+ raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
1915
+ market = self.market(symbol)
1916
+ request: dict = {
1917
+ 'type': 'fundingHistory',
1918
+ 'coin': market['base'],
1919
+ }
1920
+ if since is not None:
1921
+ request['startTime'] = since
1922
+ else:
1923
+ maxLimit = 500 if (limit is None) else limit
1924
+ request['startTime'] = self.milliseconds() - maxLimit * 60 * 60 * 1000
1925
+ until = self.safe_integer(params, 'until')
1926
+ params = self.omit(params, 'until')
1927
+ if until is not None:
1928
+ request['endTime'] = until
1929
+ response = self.publicPostInfo(self.extend(request, params))
1930
+ #
1931
+ # [
1932
+ # {
1933
+ # "coin": "ETH",
1934
+ # "fundingRate": "0.0000125",
1935
+ # "premium": "0.00057962",
1936
+ # "time": 1704290400031
1937
+ # }
1938
+ # ]
1939
+ #
1940
+ result = []
1941
+ for i in range(0, len(response)):
1942
+ entry = response[i]
1943
+ timestamp = self.safe_integer(entry, 'time')
1944
+ result.append({
1945
+ 'info': entry,
1946
+ 'symbol': self.safe_symbol(None, market),
1947
+ 'fundingRate': self.safe_number(entry, 'fundingRate'),
1948
+ 'timestamp': timestamp,
1949
+ 'datetime': self.iso8601(timestamp),
1950
+ })
1951
+ sorted = self.sort_by(result, 'timestamp')
1952
+ return self.filter_by_symbol_since_limit(sorted, symbol, since, limit)
1953
+
1954
+ def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1955
+ """
1956
+ fetch all unfilled currently open orders
1957
+
1958
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-open-orders
1959
+
1960
+ :param str symbol: unified market symbol
1961
+ :param int [since]: the earliest time in ms to fetch open orders for
1962
+ :param int [limit]: the maximum number of open orders structures to retrieve
1963
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1964
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
1965
+ :param str [params.method]: 'openOrders' or 'frontendOpenOrders' default is 'frontendOpenOrders'
1966
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1967
+ """
1968
+ userAddress = None
1969
+ userAddress, params = self.handle_public_address('fetchOpenOrders', params)
1970
+ method = None
1971
+ method, params = self.handle_option_and_params(params, 'fetchOpenOrders', 'method', 'frontendOpenOrders')
1972
+ self.load_markets()
1973
+ market = self.safe_market(symbol)
1974
+ request: dict = {
1975
+ 'type': method,
1976
+ 'user': userAddress,
1977
+ }
1978
+ response = self.publicPostInfo(self.extend(request, params))
1979
+ #
1980
+ # [
1981
+ # {
1982
+ # "coin": "ETH",
1983
+ # "limitPx": "2000.0",
1984
+ # "oid": 3991946565,
1985
+ # "origSz": "0.1",
1986
+ # "side": "B",
1987
+ # "sz": "0.1",
1988
+ # "timestamp": 1704346468838
1989
+ # }
1990
+ # ]
1991
+ #
1992
+ orderWithStatus = []
1993
+ for i in range(0, len(response)):
1994
+ order = response[i]
1995
+ extendOrder = {}
1996
+ if self.safe_string(order, 'status') is None:
1997
+ extendOrder['ccxtStatus'] = 'open'
1998
+ orderWithStatus.append(self.extend(order, extendOrder))
1999
+ return self.parse_orders(orderWithStatus, market, since, limit)
2000
+
2001
+ def fetch_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
2002
+ """
2003
+ fetch all unfilled currently closed orders
2004
+ :param str symbol: unified market symbol
2005
+ :param int [since]: the earliest time in ms to fetch open orders for
2006
+ :param int [limit]: the maximum number of open orders structures to retrieve
2007
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2008
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2009
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
2010
+ """
2011
+ self.load_markets()
2012
+ orders = self.fetch_orders(symbol, None, None, params) # don't filter here because we don't want to catch open orders
2013
+ closedOrders = self.filter_by_array(orders, 'status', ['closed'], False)
2014
+ return self.filter_by_symbol_since_limit(closedOrders, symbol, since, limit)
2015
+
2016
+ def fetch_canceled_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
2017
+ """
2018
+ fetch all canceled orders
2019
+ :param str symbol: unified market symbol
2020
+ :param int [since]: the earliest time in ms to fetch open orders for
2021
+ :param int [limit]: the maximum number of open orders structures to retrieve
2022
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2023
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2024
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
2025
+ """
2026
+ self.load_markets()
2027
+ orders = self.fetch_orders(symbol, None, None, params) # don't filter here because we don't want to catch open orders
2028
+ closedOrders = self.filter_by_array(orders, 'status', ['canceled'], False)
2029
+ return self.filter_by_symbol_since_limit(closedOrders, symbol, since, limit)
2030
+
2031
+ def fetch_canceled_and_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
2032
+ """
2033
+ fetch all closed and canceled orders
2034
+ :param str symbol: unified market symbol
2035
+ :param int [since]: the earliest time in ms to fetch open orders for
2036
+ :param int [limit]: the maximum number of open orders structures to retrieve
2037
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2038
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2039
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
2040
+ """
2041
+ self.load_markets()
2042
+ orders = self.fetch_orders(symbol, None, None, params) # don't filter here because we don't want to catch open orders
2043
+ closedOrders = self.filter_by_array(orders, 'status', ['canceled', 'closed', 'rejected'], False)
2044
+ return self.filter_by_symbol_since_limit(closedOrders, symbol, since, limit)
2045
+
2046
+ def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
2047
+ """
2048
+ fetch all orders
2049
+ :param str symbol: unified market symbol
2050
+ :param int [since]: the earliest time in ms to fetch open orders for
2051
+ :param int [limit]: the maximum number of open orders structures to retrieve
2052
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2053
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2054
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
2055
+ """
2056
+ userAddress = None
2057
+ userAddress, params = self.handle_public_address('fetchOrders', params)
2058
+ self.load_markets()
2059
+ market = self.safe_market(symbol)
2060
+ request: dict = {
2061
+ 'type': 'historicalOrders',
2062
+ 'user': userAddress,
2063
+ }
2064
+ response = self.publicPostInfo(self.extend(request, params))
2065
+ #
2066
+ # [
2067
+ # {
2068
+ # "coin": "ETH",
2069
+ # "limitPx": "2000.0",
2070
+ # "oid": 3991946565,
2071
+ # "origSz": "0.1",
2072
+ # "side": "B",
2073
+ # "sz": "0.1",
2074
+ # "timestamp": 1704346468838
2075
+ # }
2076
+ # ]
2077
+ #
2078
+ return self.parse_orders(response, market, since, limit)
2079
+
2080
+ def fetch_order(self, id: str, symbol: Str = None, params={}):
2081
+ """
2082
+ fetches information on an order made by the user
2083
+
2084
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-order-status-by-oid-or-cloid
2085
+
2086
+ :param str id: order id
2087
+ :param str symbol: unified symbol of the market the order was made in
2088
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2089
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2090
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
2091
+ """
2092
+ userAddress = None
2093
+ userAddress, params = self.handle_public_address('fetchOrder', params)
2094
+ self.load_markets()
2095
+ market = self.safe_market(symbol)
2096
+ isClientOrderId = len(id) >= 34
2097
+ request: dict = {
2098
+ 'type': 'orderStatus',
2099
+ 'oid': id if isClientOrderId else self.parse_to_numeric(id),
2100
+ 'user': userAddress,
2101
+ }
2102
+ response = self.publicPostInfo(self.extend(request, params))
2103
+ #
2104
+ # {
2105
+ # "order": {
2106
+ # "order": {
2107
+ # "children": [],
2108
+ # "cloid": null,
2109
+ # "coin": "ETH",
2110
+ # "isPositionTpsl": False,
2111
+ # "isTrigger": False,
2112
+ # "limitPx": "2000.0",
2113
+ # "oid": "3991946565",
2114
+ # "orderType": "Limit",
2115
+ # "origSz": "0.1",
2116
+ # "reduceOnly": False,
2117
+ # "side": "B",
2118
+ # "sz": "0.1",
2119
+ # "tif": "Gtc",
2120
+ # "timestamp": "1704346468838",
2121
+ # "triggerCondition": "N/A",
2122
+ # "triggerPx": "0.0"
2123
+ # },
2124
+ # "status": "open",
2125
+ # "statusTimestamp": "1704346468838"
2126
+ # },
2127
+ # "status": "order"
2128
+ # }
2129
+ #
2130
+ data = self.safe_dict(response, 'order')
2131
+ return self.parse_order(data, market)
2132
+
2133
+ def parse_order(self, order: dict, market: Market = None) -> Order:
2134
+ #
2135
+ # fetchOpenOrders
2136
+ #
2137
+ # {
2138
+ # "coin": "ETH",
2139
+ # "limitPx": "2000.0",
2140
+ # "oid": 3991946565,
2141
+ # "origSz": "0.1",
2142
+ # "side": "B",
2143
+ # "sz": "0.1",
2144
+ # "timestamp": 1704346468838
2145
+ # }
2146
+ # fetchClosedorders
2147
+ # {
2148
+ # "cloid": null,
2149
+ # "closedPnl": "0.0",
2150
+ # "coin": "SOL",
2151
+ # "crossed": True,
2152
+ # "dir": "Open Long",
2153
+ # "fee": "0.003879",
2154
+ # "hash": "0x4a2647998682b7f07bc5040ab531e1011400f9a51bfa0346a0b41ebe510e8875",
2155
+ # "liquidationMarkPx": null,
2156
+ # "oid": "6463280784",
2157
+ # "px": "110.83",
2158
+ # "side": "B",
2159
+ # "startPosition": "1.64",
2160
+ # "sz": "0.1",
2161
+ # "tid": "232174667018988",
2162
+ # "time": "1709142268394"
2163
+ # }
2164
+ #
2165
+ # fetchOrder
2166
+ #
2167
+ # {
2168
+ # "order": {
2169
+ # "children": [],
2170
+ # "cloid": null,
2171
+ # "coin": "ETH",
2172
+ # "isPositionTpsl": False,
2173
+ # "isTrigger": False,
2174
+ # "limitPx": "2000.0",
2175
+ # "oid": "3991946565",
2176
+ # "orderType": "Limit",
2177
+ # "origSz": "0.1",
2178
+ # "reduceOnly": False,
2179
+ # "side": "B",
2180
+ # "sz": "0.1",
2181
+ # "tif": "Gtc",
2182
+ # "timestamp": "1704346468838",
2183
+ # "triggerCondition": "N/A",
2184
+ # "triggerPx": "0.0"
2185
+ # },
2186
+ # "status": "open",
2187
+ # "statusTimestamp": "1704346468838"
2188
+ # }
2189
+ #
2190
+ # createOrder
2191
+ #
2192
+ # {
2193
+ # "resting": {
2194
+ # "oid": 5063830287
2195
+ # }
2196
+ # }
2197
+ #
2198
+ # {
2199
+ # "filled":{
2200
+ # "totalSz":"0.1",
2201
+ # "avgPx":"100.84",
2202
+ # "oid":6195281425
2203
+ # }
2204
+ # }
2205
+ # frontendOrder
2206
+ # {
2207
+ # "children": [],
2208
+ # "cloid": null,
2209
+ # "coin": "BLUR",
2210
+ # "isPositionTpsl": False,
2211
+ # "isTrigger": True,
2212
+ # "limitPx": "0.5",
2213
+ # "oid": 8670487141,
2214
+ # "orderType": "Stop Limit",
2215
+ # "origSz": "20.0",
2216
+ # "reduceOnly": False,
2217
+ # "side": "B",
2218
+ # "sz": "20.0",
2219
+ # "tif": null,
2220
+ # "timestamp": 1715523663687,
2221
+ # "triggerCondition": "Price above 0.6",
2222
+ # "triggerPx": "0.6"
2223
+ # }
2224
+ #
2225
+ entry = self.safe_dict_n(order, ['order', 'resting', 'filled'])
2226
+ if entry is None:
2227
+ entry = order
2228
+ coin = self.safe_string(entry, 'coin')
2229
+ marketId = None
2230
+ if coin is not None:
2231
+ marketId = self.coin_to_market_id(coin)
2232
+ if self.safe_string(entry, 'id') is None:
2233
+ market = self.safe_market(marketId, None)
2234
+ else:
2235
+ market = self.safe_market(marketId, market)
2236
+ symbol = market['symbol']
2237
+ timestamp = self.safe_integer(entry, 'timestamp')
2238
+ status = self.safe_string_2(order, 'status', 'ccxtStatus')
2239
+ order = self.omit(order, ['ccxtStatus'])
2240
+ side = self.safe_string(entry, 'side')
2241
+ if side is not None:
2242
+ side = 'sell' if (side == 'A') else 'buy'
2243
+ totalAmount = self.safe_string_2(entry, 'origSz', 'totalSz')
2244
+ remaining = self.safe_string(entry, 'sz')
2245
+ return self.safe_order({
2246
+ 'info': order,
2247
+ 'id': self.safe_string(entry, 'oid'),
2248
+ 'clientOrderId': self.safe_string(entry, 'cloid'),
2249
+ 'timestamp': timestamp,
2250
+ 'datetime': self.iso8601(timestamp),
2251
+ 'lastTradeTimestamp': None,
2252
+ 'lastUpdateTimestamp': self.safe_integer(order, 'statusTimestamp'),
2253
+ 'symbol': symbol,
2254
+ 'type': self.parse_order_type(self.safe_string_lower(entry, 'orderType')),
2255
+ 'timeInForce': self.safe_string_upper(entry, 'tif'),
2256
+ 'postOnly': None,
2257
+ 'reduceOnly': self.safe_bool(entry, 'reduceOnly'),
2258
+ 'side': side,
2259
+ 'price': self.safe_string(entry, 'limitPx'),
2260
+ 'triggerPrice': self.safe_number(entry, 'triggerPx') if self.safe_bool(entry, 'isTrigger') else None,
2261
+ 'amount': totalAmount,
2262
+ 'cost': None,
2263
+ 'average': self.safe_string(entry, 'avgPx'),
2264
+ 'filled': Precise.string_sub(totalAmount, remaining),
2265
+ 'remaining': remaining,
2266
+ 'status': self.parse_order_status(status),
2267
+ 'fee': None,
2268
+ 'trades': None,
2269
+ }, market)
2270
+
2271
+ def parse_order_status(self, status: Str):
2272
+ statuses: dict = {
2273
+ 'triggered': 'open',
2274
+ 'filled': 'closed',
2275
+ 'open': 'open',
2276
+ 'canceled': 'canceled',
2277
+ 'rejected': 'rejected',
2278
+ 'marginCanceled': 'canceled',
2279
+ }
2280
+ return self.safe_string(statuses, status, status)
2281
+
2282
+ def parse_order_type(self, status):
2283
+ statuses: dict = {
2284
+ 'stop limit': 'limit',
2285
+ 'stop market': 'market',
2286
+ }
2287
+ return self.safe_string(statuses, status, status)
2288
+
2289
+ def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
2290
+ """
2291
+ fetch all trades made by the user
2292
+
2293
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
2294
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time
2295
+
2296
+ :param str symbol: unified market symbol
2297
+ :param int [since]: the earliest time in ms to fetch trades for
2298
+ :param int [limit]: the maximum number of trades structures to retrieve
2299
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2300
+ :param int [params.until]: timestamp in ms of the latest trade
2301
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
2302
+ """
2303
+ userAddress = None
2304
+ userAddress, params = self.handle_public_address('fetchMyTrades', params)
2305
+ self.load_markets()
2306
+ market = self.safe_market(symbol)
2307
+ request: dict = {
2308
+ 'user': userAddress,
2309
+ }
2310
+ if since is not None:
2311
+ request['type'] = 'userFillsByTime'
2312
+ request['startTime'] = since
2313
+ else:
2314
+ request['type'] = 'userFills'
2315
+ until = self.safe_integer(params, 'until')
2316
+ params = self.omit(params, 'until')
2317
+ if until is not None:
2318
+ request['endTime'] = until
2319
+ response = self.publicPostInfo(self.extend(request, params))
2320
+ #
2321
+ # [
2322
+ # {
2323
+ # "closedPnl": "0.19343",
2324
+ # "coin": "ETH",
2325
+ # "crossed": True,
2326
+ # "dir": "Close Long",
2327
+ # "fee": "0.050062",
2328
+ # "feeToken": "USDC",
2329
+ # "hash": "0x09d77c96791e98b5775a04092584ab010d009445119c71e4005c0d634ea322bc",
2330
+ # "liquidationMarkPx": null,
2331
+ # "oid": 3929354691,
2332
+ # "px": "2381.1",
2333
+ # "side": "A",
2334
+ # "startPosition": "0.0841",
2335
+ # "sz": "0.0841",
2336
+ # "tid": 128423918764978,
2337
+ # "time": 1704262888911
2338
+ # }
2339
+ # ]
2340
+ #
2341
+ return self.parse_trades(response, market, since, limit)
2342
+
2343
+ def parse_trade(self, trade: dict, market: Market = None) -> Trade:
2344
+ #
2345
+ # {
2346
+ # "closedPnl": "0.19343",
2347
+ # "coin": "ETH",
2348
+ # "crossed": True,
2349
+ # "dir": "Close Long",
2350
+ # "fee": "0.050062",
2351
+ # "hash": "0x09d77c96791e98b5775a04092584ab010d009445119c71e4005c0d634ea322bc",
2352
+ # "liquidationMarkPx": null,
2353
+ # "oid": 3929354691,
2354
+ # "px": "2381.1",
2355
+ # "side": "A",
2356
+ # "startPosition": "0.0841",
2357
+ # "sz": "0.0841",
2358
+ # "tid": 128423918764978,
2359
+ # "time": 1704262888911
2360
+ # }
2361
+ #
2362
+ timestamp = self.safe_integer(trade, 'time')
2363
+ price = self.safe_string(trade, 'px')
2364
+ amount = self.safe_string(trade, 'sz')
2365
+ coin = self.safe_string(trade, 'coin')
2366
+ marketId = self.coin_to_market_id(coin)
2367
+ market = self.safe_market(marketId, None)
2368
+ symbol = market['symbol']
2369
+ id = self.safe_string(trade, 'tid')
2370
+ side = self.safe_string(trade, 'side')
2371
+ if side is not None:
2372
+ side = 'sell' if (side == 'A') else 'buy'
2373
+ fee = self.safe_string(trade, 'fee')
2374
+ return self.safe_trade({
2375
+ 'info': trade,
2376
+ 'timestamp': timestamp,
2377
+ 'datetime': self.iso8601(timestamp),
2378
+ 'symbol': symbol,
2379
+ 'id': id,
2380
+ 'order': self.safe_string(trade, 'oid'),
2381
+ 'type': None,
2382
+ 'side': side,
2383
+ 'takerOrMaker': None,
2384
+ 'price': price,
2385
+ 'amount': amount,
2386
+ 'cost': None,
2387
+ 'fee': {
2388
+ 'cost': fee,
2389
+ 'currency': self.safe_string(trade, 'feeToken'),
2390
+ 'rate': None,
2391
+ },
2392
+ }, market)
2393
+
2394
+ def fetch_position(self, symbol: str, params={}):
2395
+ """
2396
+ fetch data on an open position
2397
+
2398
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary
2399
+
2400
+ :param str symbol: unified market symbol of the market the position is held in
2401
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2402
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2403
+ :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
2404
+ """
2405
+ positions = self.fetch_positions([symbol], params)
2406
+ return self.safe_dict(positions, 0, {})
2407
+
2408
+ def fetch_positions(self, symbols: Strings = None, params={}):
2409
+ """
2410
+ fetch all open positions
2411
+
2412
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary
2413
+
2414
+ :param str[] [symbols]: list of unified market symbols
2415
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2416
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2417
+ :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
2418
+ """
2419
+ self.load_markets()
2420
+ userAddress = None
2421
+ userAddress, params = self.handle_public_address('fetchPositions', params)
2422
+ symbols = self.market_symbols(symbols)
2423
+ request: dict = {
2424
+ 'type': 'clearinghouseState',
2425
+ 'user': userAddress,
2426
+ }
2427
+ response = self.publicPostInfo(self.extend(request, params))
2428
+ #
2429
+ # {
2430
+ # "assetPositions": [
2431
+ # {
2432
+ # "position": {
2433
+ # "coin": "ETH",
2434
+ # "cumFunding": {
2435
+ # "allTime": "0.0",
2436
+ # "sinceChange": "0.0",
2437
+ # "sinceOpen": "0.0"
2438
+ # },
2439
+ # "entryPx": "2213.9",
2440
+ # "leverage": {
2441
+ # "rawUsd": "-475.23904",
2442
+ # "type": "isolated",
2443
+ # "value": "20"
2444
+ # },
2445
+ # "liquidationPx": "2125.00856238",
2446
+ # "marginUsed": "24.88097",
2447
+ # "maxLeverage": "50",
2448
+ # "positionValue": "500.12001",
2449
+ # "returnOnEquity": "0.0",
2450
+ # "szi": "0.2259",
2451
+ # "unrealizedPnl": "0.0"
2452
+ # },
2453
+ # "type": "oneWay"
2454
+ # }
2455
+ # ],
2456
+ # "crossMaintenanceMarginUsed": "0.0",
2457
+ # "crossMarginSummary": {
2458
+ # "accountValue": "100.0",
2459
+ # "totalMarginUsed": "0.0",
2460
+ # "totalNtlPos": "0.0",
2461
+ # "totalRawUsd": "100.0"
2462
+ # },
2463
+ # "marginSummary": {
2464
+ # "accountValue": "100.0",
2465
+ # "totalMarginUsed": "0.0",
2466
+ # "totalNtlPos": "0.0",
2467
+ # "totalRawUsd": "100.0"
2468
+ # },
2469
+ # "time": "1704261007014",
2470
+ # "withdrawable": "100.0"
2471
+ # }
2472
+ #
2473
+ data = self.safe_list(response, 'assetPositions', [])
2474
+ result = []
2475
+ for i in range(0, len(data)):
2476
+ result.append(self.parse_position(data[i], None))
2477
+ return self.filter_by_array_positions(result, 'symbol', symbols, False)
2478
+
2479
+ def parse_position(self, position: dict, market: Market = None):
2480
+ #
2481
+ # {
2482
+ # "position": {
2483
+ # "coin": "ETH",
2484
+ # "cumFunding": {
2485
+ # "allTime": "0.0",
2486
+ # "sinceChange": "0.0",
2487
+ # "sinceOpen": "0.0"
2488
+ # },
2489
+ # "entryPx": "2213.9",
2490
+ # "leverage": {
2491
+ # "rawUsd": "-475.23904",
2492
+ # "type": "isolated",
2493
+ # "value": "20"
2494
+ # },
2495
+ # "liquidationPx": "2125.00856238",
2496
+ # "marginUsed": "24.88097",
2497
+ # "maxLeverage": "50",
2498
+ # "positionValue": "500.12001",
2499
+ # "returnOnEquity": "0.0",
2500
+ # "szi": "0.2259",
2501
+ # "unrealizedPnl": "0.0"
2502
+ # },
2503
+ # "type": "oneWay"
2504
+ # }
2505
+ #
2506
+ entry = self.safe_dict(position, 'position', {})
2507
+ coin = self.safe_string(entry, 'coin')
2508
+ marketId = self.coin_to_market_id(coin)
2509
+ market = self.safe_market(marketId, None)
2510
+ symbol = market['symbol']
2511
+ leverage = self.safe_dict(entry, 'leverage', {})
2512
+ marginMode = self.safe_string(leverage, 'type')
2513
+ isIsolated = (marginMode == 'isolated')
2514
+ rawSize = self.safe_string(entry, 'szi')
2515
+ size = rawSize
2516
+ side = None
2517
+ if size is not None:
2518
+ side = 'long' if Precise.string_gt(rawSize, '0') else 'short'
2519
+ size = Precise.string_abs(size)
2520
+ rawUnrealizedPnl = self.safe_string(entry, 'unrealizedPnl')
2521
+ absRawUnrealizedPnl = Precise.string_abs(rawUnrealizedPnl)
2522
+ initialMargin = self.safe_string(entry, 'marginUsed')
2523
+ percentage = Precise.string_mul(Precise.string_div(absRawUnrealizedPnl, initialMargin), '100')
2524
+ return self.safe_position({
2525
+ 'info': position,
2526
+ 'id': None,
2527
+ 'symbol': symbol,
2528
+ 'timestamp': None,
2529
+ 'datetime': None,
2530
+ 'isolated': isIsolated,
2531
+ 'hedged': None,
2532
+ 'side': side,
2533
+ 'contracts': self.parse_number(size),
2534
+ 'contractSize': None,
2535
+ 'entryPrice': self.safe_number(entry, 'entryPx'),
2536
+ 'markPrice': None,
2537
+ 'notional': self.safe_number(entry, 'positionValue'),
2538
+ 'leverage': self.safe_number(leverage, 'value'),
2539
+ 'collateral': self.safe_number(entry, 'marginUsed'),
2540
+ 'initialMargin': self.parse_number(initialMargin),
2541
+ 'maintenanceMargin': None,
2542
+ 'initialMarginPercentage': None,
2543
+ 'maintenanceMarginPercentage': None,
2544
+ 'unrealizedPnl': self.parse_number(rawUnrealizedPnl),
2545
+ 'liquidationPrice': self.safe_number(entry, 'liquidationPx'),
2546
+ 'marginMode': marginMode,
2547
+ 'percentage': self.parse_number(percentage),
2548
+ })
2549
+
2550
+ def set_margin_mode(self, marginMode: str, symbol: Str = None, params={}):
2551
+ """
2552
+ set margin mode(symbol)
2553
+ :param str marginMode: margin mode must be either [isolated, cross]
2554
+ :param str symbol: unified market symbol of the market the position is held in, default is None
2555
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2556
+ :param str [params.leverage]: the rate of leverage, is required if setting trade mode(symbol)
2557
+ :returns dict: response from the exchange
2558
+ """
2559
+ if symbol is None:
2560
+ raise ArgumentsRequired(self.id + ' setMarginMode() requires a symbol argument')
2561
+ self.load_markets()
2562
+ market = self.market(symbol)
2563
+ leverage = self.safe_integer(params, 'leverage')
2564
+ if leverage is None:
2565
+ raise ArgumentsRequired(self.id + ' setMarginMode() requires a leverage parameter')
2566
+ asset = self.parse_to_int(market['baseId'])
2567
+ isCross = (marginMode == 'cross')
2568
+ nonce = self.milliseconds()
2569
+ params = self.omit(params, ['leverage'])
2570
+ updateAction: dict = {
2571
+ 'type': 'updateLeverage',
2572
+ 'asset': asset,
2573
+ 'isCross': isCross,
2574
+ 'leverage': leverage,
2575
+ }
2576
+ vaultAddress = self.safe_string(params, 'vaultAddress')
2577
+ if vaultAddress is not None:
2578
+ params = self.omit(params, 'vaultAddress')
2579
+ if vaultAddress.startswith('0x'):
2580
+ vaultAddress = vaultAddress.replace('0x', '')
2581
+ signature = self.sign_l1_action(updateAction, nonce, vaultAddress)
2582
+ request: dict = {
2583
+ 'action': updateAction,
2584
+ 'nonce': nonce,
2585
+ 'signature': signature,
2586
+ # 'vaultAddress': vaultAddress,
2587
+ }
2588
+ if vaultAddress is not None:
2589
+ request['vaultAddress'] = vaultAddress
2590
+ response = self.privatePostExchange(request)
2591
+ #
2592
+ # {
2593
+ # 'response': {
2594
+ # 'type': 'default'
2595
+ # },
2596
+ # 'status': 'ok'
2597
+ # }
2598
+ #
2599
+ return response
2600
+
2601
+ def set_leverage(self, leverage: Int, symbol: Str = None, params={}):
2602
+ """
2603
+ set the level of leverage for a market
2604
+ :param float leverage: the rate of leverage
2605
+ :param str symbol: unified market symbol
2606
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2607
+ :param str [params.marginMode]: margin mode must be either [isolated, cross], default is cross
2608
+ :returns dict: response from the exchange
2609
+ """
2610
+ if symbol is None:
2611
+ raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
2612
+ self.load_markets()
2613
+ market = self.market(symbol)
2614
+ marginMode = self.safe_string(params, 'marginMode', 'cross')
2615
+ isCross = (marginMode == 'cross')
2616
+ asset = self.parse_to_int(market['baseId'])
2617
+ nonce = self.milliseconds()
2618
+ params = self.omit(params, 'marginMode')
2619
+ updateAction: dict = {
2620
+ 'type': 'updateLeverage',
2621
+ 'asset': asset,
2622
+ 'isCross': isCross,
2623
+ 'leverage': leverage,
2624
+ }
2625
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
2626
+ signature = self.sign_l1_action(updateAction, nonce, vaultAddress)
2627
+ request: dict = {
2628
+ 'action': updateAction,
2629
+ 'nonce': nonce,
2630
+ 'signature': signature,
2631
+ # 'vaultAddress': vaultAddress,
2632
+ }
2633
+ if vaultAddress is not None:
2634
+ params = self.omit(params, 'vaultAddress')
2635
+ request['vaultAddress'] = vaultAddress
2636
+ response = self.privatePostExchange(request)
2637
+ #
2638
+ # {
2639
+ # 'response': {
2640
+ # 'type': 'default'
2641
+ # },
2642
+ # 'status': 'ok'
2643
+ # }
2644
+ #
2645
+ return response
2646
+
2647
+ def add_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
2648
+ """
2649
+ add margin
2650
+
2651
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin
2652
+
2653
+ :param str symbol: unified market symbol
2654
+ :param float amount: amount of margin to add
2655
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2656
+ :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
2657
+ """
2658
+ return self.modify_margin_helper(symbol, amount, 'add', params)
2659
+
2660
+ def reduce_margin(self, symbol: str, amount: float, params={}) -> MarginModification:
2661
+ """
2662
+
2663
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin
2664
+
2665
+ remove margin from a position
2666
+ :param str symbol: unified market symbol
2667
+ :param float amount: the amount of margin to remove
2668
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2669
+ :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
2670
+ """
2671
+ return self.modify_margin_helper(symbol, amount, 'reduce', params)
2672
+
2673
+ def modify_margin_helper(self, symbol: str, amount, type, params={}) -> MarginModification:
2674
+ self.load_markets()
2675
+ market = self.market(symbol)
2676
+ asset = self.parse_to_int(market['baseId'])
2677
+ sz = self.parse_to_int(Precise.string_mul(self.amount_to_precision(symbol, amount), '1000000'))
2678
+ if type == 'reduce':
2679
+ sz = -sz
2680
+ nonce = self.milliseconds()
2681
+ updateAction: dict = {
2682
+ 'type': 'updateIsolatedMargin',
2683
+ 'asset': asset,
2684
+ 'isBuy': True,
2685
+ 'ntli': sz,
2686
+ }
2687
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
2688
+ signature = self.sign_l1_action(updateAction, nonce, vaultAddress)
2689
+ request: dict = {
2690
+ 'action': updateAction,
2691
+ 'nonce': nonce,
2692
+ 'signature': signature,
2693
+ # 'vaultAddress': vaultAddress,
2694
+ }
2695
+ if vaultAddress is not None:
2696
+ params = self.omit(params, 'vaultAddress')
2697
+ request['vaultAddress'] = vaultAddress
2698
+ response = self.privatePostExchange(request)
2699
+ #
2700
+ # {
2701
+ # 'response': {
2702
+ # 'type': 'default'
2703
+ # },
2704
+ # 'status': 'ok'
2705
+ # }
2706
+ #
2707
+ return self.extend(self.parse_margin_modification(response, market), {
2708
+ 'code': self.safe_string(response, 'status'),
2709
+ })
2710
+
2711
+ def parse_margin_modification(self, data: dict, market: Market = None) -> MarginModification:
2712
+ #
2713
+ # {
2714
+ # 'type': 'default'
2715
+ # }
2716
+ #
2717
+ return {
2718
+ 'info': data,
2719
+ 'symbol': self.safe_symbol(None, market),
2720
+ 'type': None,
2721
+ 'marginMode': 'isolated',
2722
+ 'amount': None,
2723
+ 'total': None,
2724
+ 'code': self.safe_string(market, 'settle'),
2725
+ 'status': None,
2726
+ 'timestamp': None,
2727
+ 'datetime': None,
2728
+ }
2729
+
2730
+ def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry:
2731
+ """
2732
+ transfer currency internally between wallets on the same account
2733
+
2734
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#l1-usdc-transfer
2735
+
2736
+ :param str code: unified currency code
2737
+ :param float amount: amount to transfer
2738
+ :param str fromAccount: account to transfer from *spot, swap*
2739
+ :param str toAccount: account to transfer to *swap, spot or address*
2740
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2741
+ :param str [params.vaultAddress]: the vault address for order
2742
+ :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
2743
+ """
2744
+ self.check_required_credentials()
2745
+ self.load_markets()
2746
+ isSandboxMode = self.safe_bool(self.options, 'sandboxMode')
2747
+ nonce = self.milliseconds()
2748
+ if self.in_array(fromAccount, ['spot', 'swap', 'perp']):
2749
+ # handle swap <> spot account transfer
2750
+ if not self.in_array(toAccount, ['spot', 'swap', 'perp']):
2751
+ raise NotSupported(self.id + ' transfer() only support spot <> swap transfer')
2752
+ strAmount = self.number_to_string(amount)
2753
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
2754
+ params = self.omit(params, 'vaultAddress')
2755
+ if vaultAddress is not None:
2756
+ strAmount = strAmount + ' subaccount:' + vaultAddress
2757
+ toPerp = (toAccount == 'perp') or (toAccount == 'swap')
2758
+ transferPayload: dict = {
2759
+ 'hyperliquidChain': 'Testnet' if isSandboxMode else 'Mainnet',
2760
+ 'amount': strAmount,
2761
+ 'toPerp': toPerp,
2762
+ 'nonce': nonce,
2763
+ }
2764
+ transferSig = self.build_usd_class_send_sig(transferPayload)
2765
+ transferRequest: dict = {
2766
+ 'action': {
2767
+ 'hyperliquidChain': transferPayload['hyperliquidChain'],
2768
+ 'signatureChainId': '0x66eee',
2769
+ 'type': 'usdClassTransfer',
2770
+ 'amount': strAmount,
2771
+ 'toPerp': toPerp,
2772
+ 'nonce': nonce,
2773
+ },
2774
+ 'nonce': nonce,
2775
+ 'signature': transferSig,
2776
+ }
2777
+ if vaultAddress is not None:
2778
+ transferRequest['vaultAddress'] = vaultAddress
2779
+ transferResponse = self.privatePostExchange(transferRequest)
2780
+ return transferResponse
2781
+ # handle sub-account/different account transfer
2782
+ self.check_address(toAccount)
2783
+ if code is not None:
2784
+ code = code.upper()
2785
+ if code != 'USDC':
2786
+ raise NotSupported(self.id + ' transfer() only support USDC')
2787
+ payload: dict = {
2788
+ 'hyperliquidChain': 'Testnet' if isSandboxMode else 'Mainnet',
2789
+ 'destination': toAccount,
2790
+ 'amount': self.number_to_string(amount),
2791
+ 'time': nonce,
2792
+ }
2793
+ sig = self.build_usd_send_sig(payload)
2794
+ request: dict = {
2795
+ 'action': {
2796
+ 'hyperliquidChain': payload['hyperliquidChain'],
2797
+ 'signatureChainId': '0x66eee', # check self out
2798
+ 'destination': toAccount,
2799
+ 'amount': str(amount),
2800
+ 'time': nonce,
2801
+ 'type': 'usdSend',
2802
+ },
2803
+ 'nonce': nonce,
2804
+ 'signature': sig,
2805
+ }
2806
+ response = self.privatePostExchange(request)
2807
+ #
2808
+ # {'response': {'type': 'default'}, 'status': 'ok'}
2809
+ #
2810
+ return self.parse_transfer(response)
2811
+
2812
+ def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry:
2813
+ #
2814
+ # {'response': {'type': 'default'}, 'status': 'ok'}
2815
+ #
2816
+ return {
2817
+ 'info': transfer,
2818
+ 'id': None,
2819
+ 'timestamp': None,
2820
+ 'datetime': None,
2821
+ 'currency': None,
2822
+ 'amount': None,
2823
+ 'fromAccount': None,
2824
+ 'toAccount': None,
2825
+ 'status': 'ok',
2826
+ }
2827
+
2828
+ def withdraw(self, code: str, amount: float, address: str, tag=None, params={}) -> Transaction:
2829
+ """
2830
+ make a withdrawal(only support USDC)
2831
+
2832
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#initiate-a-withdrawal-request
2833
+ https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#deposit-or-withdraw-from-a-vault
2834
+
2835
+ :param str code: unified currency code
2836
+ :param float amount: the amount to withdraw
2837
+ :param str address: the address to withdraw to
2838
+ :param str tag:
2839
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2840
+ :param str [params.vaultAddress]: vault address withdraw from
2841
+ :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
2842
+ """
2843
+ self.check_required_credentials()
2844
+ self.load_markets()
2845
+ self.check_address(address)
2846
+ if code is not None:
2847
+ code = code.upper()
2848
+ if code != 'USDC':
2849
+ raise NotSupported(self.id + ' withdraw() only support USDC')
2850
+ vaultAddress = self.format_vault_address(self.safe_string(params, 'vaultAddress'))
2851
+ params = self.omit(params, 'vaultAddress')
2852
+ nonce = self.milliseconds()
2853
+ action: dict = {}
2854
+ sig = None
2855
+ if vaultAddress is not None:
2856
+ action = {
2857
+ 'type': 'vaultTransfer',
2858
+ 'vaultAddress': '0x' + vaultAddress,
2859
+ 'isDeposit': False,
2860
+ 'usd': amount,
2861
+ }
2862
+ sig = self.sign_l1_action(action, nonce)
2863
+ else:
2864
+ isSandboxMode = self.safe_bool(self.options, 'sandboxMode', False)
2865
+ payload: dict = {
2866
+ 'hyperliquidChain': 'Testnet' if isSandboxMode else 'Mainnet',
2867
+ 'destination': address,
2868
+ 'amount': str(amount),
2869
+ 'time': nonce,
2870
+ }
2871
+ sig = self.build_withdraw_sig(payload)
2872
+ action = {
2873
+ 'hyperliquidChain': payload['hyperliquidChain'],
2874
+ 'signatureChainId': '0x66eee', # check self out
2875
+ 'destination': address,
2876
+ 'amount': str(amount),
2877
+ 'time': nonce,
2878
+ 'type': 'withdraw3',
2879
+ }
2880
+ request: dict = {
2881
+ 'action': action,
2882
+ 'nonce': nonce,
2883
+ 'signature': sig,
2884
+ }
2885
+ response = self.privatePostExchange(request)
2886
+ return self.parse_transaction(response)
2887
+
2888
+ def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
2889
+ #
2890
+ # {status: 'ok', response: {type: 'default'}}
2891
+ #
2892
+ # fetchDeposits / fetchWithdrawals
2893
+ # {
2894
+ # "time":1724762307531,
2895
+ # "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
2896
+ # "delta":{
2897
+ # "type":"accountClassTransfer",
2898
+ # "usdc":"50.0",
2899
+ # "toPerp":false
2900
+ # }
2901
+ # }
2902
+ #
2903
+ timestamp = self.safe_integer(transaction, 'time')
2904
+ delta = self.safe_dict(transaction, 'delta', {})
2905
+ fee = None
2906
+ feeCost = self.safe_integer(delta, 'fee')
2907
+ if feeCost is not None:
2908
+ fee = {
2909
+ 'currency': 'USDC',
2910
+ 'cost': feeCost,
2911
+ }
2912
+ internal = None
2913
+ type = self.safe_string(delta, 'type')
2914
+ if type is not None:
2915
+ internal = (type == 'internalTransfer')
2916
+ return {
2917
+ 'info': transaction,
2918
+ 'id': None,
2919
+ 'txid': self.safe_string(transaction, 'hash'),
2920
+ 'timestamp': timestamp,
2921
+ 'datetime': self.iso8601(timestamp),
2922
+ 'network': None,
2923
+ 'address': None,
2924
+ 'addressTo': self.safe_string(delta, 'destination'),
2925
+ 'addressFrom': self.safe_string(delta, 'user'),
2926
+ 'tag': None,
2927
+ 'tagTo': None,
2928
+ 'tagFrom': None,
2929
+ 'type': None,
2930
+ 'amount': self.safe_integer(delta, 'usdc'),
2931
+ 'currency': None,
2932
+ 'status': self.safe_string(transaction, 'status'),
2933
+ 'updated': None,
2934
+ 'comment': None,
2935
+ 'internal': internal,
2936
+ 'fee': fee,
2937
+ }
2938
+
2939
+ def fetch_trading_fee(self, symbol: str, params={}) -> TradingFeeInterface:
2940
+ """
2941
+ fetch the trading fees for a market
2942
+ :param str symbol: unified market symbol
2943
+ :param dict [params]: extra parameters specific to the exchange API endpoint
2944
+ :param str [params.user]: user address, will default to self.walletAddress if not provided
2945
+ :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
2946
+ """
2947
+ self.load_markets()
2948
+ userAddress = None
2949
+ userAddress, params = self.handle_public_address('fetchTradingFee', params)
2950
+ market = self.market(symbol)
2951
+ request: dict = {
2952
+ 'type': 'userFees',
2953
+ 'user': userAddress,
2954
+ }
2955
+ response = self.publicPostInfo(self.extend(request, params))
2956
+ #
2957
+ # {
2958
+ # "dailyUserVlm": [
2959
+ # {
2960
+ # "date": "2024-07-08",
2961
+ # "userCross": "0.0",
2962
+ # "userAdd": "0.0",
2963
+ # "exchange": "90597185.23639999"
2964
+ # }
2965
+ # ],
2966
+ # "feeSchedule": {
2967
+ # "cross": "0.00035",
2968
+ # "add": "0.0001",
2969
+ # "tiers": {
2970
+ # "vip": [
2971
+ # {
2972
+ # "ntlCutoff": "5000000.0",
2973
+ # "cross": "0.0003",
2974
+ # "add": "0.00005"
2975
+ # }
2976
+ # ],
2977
+ # "mm": [
2978
+ # {
2979
+ # "makerFractionCutoff": "0.005",
2980
+ # "add": "-0.00001"
2981
+ # }
2982
+ # ]
2983
+ # },
2984
+ # "referralDiscount": "0.04"
2985
+ # },
2986
+ # "userCrossRate": "0.00035",
2987
+ # "userAddRate": "0.0001",
2988
+ # "activeReferralDiscount": "0.0"
2989
+ # }
2990
+ #
2991
+ data: dict = {
2992
+ 'userCrossRate': self.safe_string(response, 'userCrossRate'),
2993
+ 'userAddRate': self.safe_string(response, 'userAddRate'),
2994
+ }
2995
+ return self.parse_trading_fee(data, market)
2996
+
2997
+ def parse_trading_fee(self, fee: dict, market: Market = None) -> TradingFeeInterface:
2998
+ #
2999
+ # {
3000
+ # "dailyUserVlm": [
3001
+ # {
3002
+ # "date": "2024-07-08",
3003
+ # "userCross": "0.0",
3004
+ # "userAdd": "0.0",
3005
+ # "exchange": "90597185.23639999"
3006
+ # }
3007
+ # ],
3008
+ # "feeSchedule": {
3009
+ # "cross": "0.00035",
3010
+ # "add": "0.0001",
3011
+ # "tiers": {
3012
+ # "vip": [
3013
+ # {
3014
+ # "ntlCutoff": "5000000.0",
3015
+ # "cross": "0.0003",
3016
+ # "add": "0.00005"
3017
+ # }
3018
+ # ],
3019
+ # "mm": [
3020
+ # {
3021
+ # "makerFractionCutoff": "0.005",
3022
+ # "add": "-0.00001"
3023
+ # }
3024
+ # ]
3025
+ # },
3026
+ # "referralDiscount": "0.04"
3027
+ # },
3028
+ # "userCrossRate": "0.00035",
3029
+ # "userAddRate": "0.0001",
3030
+ # "activeReferralDiscount": "0.0"
3031
+ # }
3032
+ #
3033
+ symbol = self.safe_symbol(None, market)
3034
+ return {
3035
+ 'info': fee,
3036
+ 'symbol': symbol,
3037
+ 'maker': self.safe_number(fee, 'userAddRate'),
3038
+ 'taker': self.safe_number(fee, 'userCrossRate'),
3039
+ 'percentage': None,
3040
+ 'tierBased': None,
3041
+ }
3042
+
3043
+ def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[LedgerEntry]:
3044
+ """
3045
+ fetch the history of changes, actions done by the user or operations that altered the balance of the user
3046
+ :param str [code]: unified currency code
3047
+ :param int [since]: timestamp in ms of the earliest ledger entry
3048
+ :param int [limit]: max number of ledger entries to return
3049
+ :param dict [params]: extra parameters specific to the exchange API endpoint
3050
+ :param int [params.until]: timestamp in ms of the latest ledger entry
3051
+ :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
3052
+ """
3053
+ self.load_markets()
3054
+ userAddress = None
3055
+ userAddress, params = self.handle_public_address('fetchLedger', params)
3056
+ request: dict = {
3057
+ 'type': 'userNonFundingLedgerUpdates',
3058
+ 'user': userAddress,
3059
+ }
3060
+ if since is not None:
3061
+ request['startTime'] = since
3062
+ until = self.safe_integer(params, 'until')
3063
+ if until is not None:
3064
+ request['endTime'] = until
3065
+ params = self.omit(params, ['until'])
3066
+ response = self.publicPostInfo(self.extend(request, params))
3067
+ #
3068
+ # [
3069
+ # {
3070
+ # "time":1724762307531,
3071
+ # "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
3072
+ # "delta":{
3073
+ # "type":"accountClassTransfer",
3074
+ # "usdc":"50.0",
3075
+ # "toPerp":false
3076
+ # }
3077
+ # }
3078
+ # ]
3079
+ #
3080
+ return self.parse_ledger(response, None, since, limit)
3081
+
3082
+ def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry:
3083
+ #
3084
+ # {
3085
+ # "time":1724762307531,
3086
+ # "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
3087
+ # "delta":{
3088
+ # "type":"accountClassTransfer",
3089
+ # "usdc":"50.0",
3090
+ # "toPerp":false
3091
+ # }
3092
+ # }
3093
+ #
3094
+ timestamp = self.safe_integer(item, 'time')
3095
+ delta = self.safe_dict(item, 'delta', {})
3096
+ fee = None
3097
+ feeCost = self.safe_integer(delta, 'fee')
3098
+ if feeCost is not None:
3099
+ fee = {
3100
+ 'currency': 'USDC',
3101
+ 'cost': feeCost,
3102
+ }
3103
+ type = self.safe_string(delta, 'type')
3104
+ amount = self.safe_string(delta, 'usdc')
3105
+ return self.safe_ledger_entry({
3106
+ 'info': item,
3107
+ 'id': self.safe_string(item, 'hash'),
3108
+ 'direction': None,
3109
+ 'account': None,
3110
+ 'referenceAccount': self.safe_string(delta, 'user'),
3111
+ 'referenceId': self.safe_string(item, 'hash'),
3112
+ 'type': self.parse_ledger_entry_type(type),
3113
+ 'currency': None,
3114
+ 'amount': self.parse_number(amount),
3115
+ 'timestamp': timestamp,
3116
+ 'datetime': self.iso8601(timestamp),
3117
+ 'before': None,
3118
+ 'after': None,
3119
+ 'status': None,
3120
+ 'fee': fee,
3121
+ }, currency)
3122
+
3123
+ def parse_ledger_entry_type(self, type):
3124
+ ledgerType: dict = {
3125
+ 'internalTransfer': 'transfer',
3126
+ 'accountClassTransfer': 'transfer',
3127
+ }
3128
+ return self.safe_string(ledgerType, type, type)
3129
+
3130
+ def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}):
3131
+ """
3132
+ fetch all deposits made to an account
3133
+ :param str code: unified currency code
3134
+ :param int [since]: the earliest time in ms to fetch deposits for
3135
+ :param int [limit]: the maximum number of deposits structures to retrieve
3136
+ :param dict [params]: extra parameters specific to the exchange API endpoint
3137
+ :param int [params.until]: the latest time in ms to fetch withdrawals for
3138
+ :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
3139
+ """
3140
+ self.load_markets()
3141
+ userAddress = None
3142
+ userAddress, params = self.handle_public_address('fetchDepositsWithdrawals', params)
3143
+ request: dict = {
3144
+ 'type': 'userNonFundingLedgerUpdates',
3145
+ 'user': userAddress,
3146
+ }
3147
+ if since is not None:
3148
+ request['startTime'] = since
3149
+ until = self.safe_integer(params, 'until')
3150
+ if until is not None:
3151
+ request['endTime'] = until
3152
+ params = self.omit(params, ['until'])
3153
+ response = self.publicPostInfo(self.extend(request, params))
3154
+ #
3155
+ # [
3156
+ # {
3157
+ # "time":1724762307531,
3158
+ # "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
3159
+ # "delta":{
3160
+ # "type":"accountClassTransfer",
3161
+ # "usdc":"50.0",
3162
+ # "toPerp":false
3163
+ # }
3164
+ # }
3165
+ # ]
3166
+ #
3167
+ records = self.extract_type_from_delta(response)
3168
+ deposits = self.filter_by_array(records, 'type', ['deposit'], False)
3169
+ return self.parse_transactions(deposits, None, since, limit)
3170
+
3171
+ def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
3172
+ """
3173
+ fetch all withdrawals made from an account
3174
+ :param str code: unified currency code
3175
+ :param int [since]: the earliest time in ms to fetch withdrawals for
3176
+ :param int [limit]: the maximum number of withdrawals structures to retrieve
3177
+ :param dict [params]: extra parameters specific to the exchange API endpoint
3178
+ :param int [params.until]: the latest time in ms to fetch withdrawals for
3179
+ :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
3180
+ """
3181
+ self.load_markets()
3182
+ userAddress = None
3183
+ userAddress, params = self.handle_public_address('fetchDepositsWithdrawals', params)
3184
+ request: dict = {
3185
+ 'type': 'userNonFundingLedgerUpdates',
3186
+ 'user': userAddress,
3187
+ }
3188
+ if since is not None:
3189
+ request['startTime'] = since
3190
+ until = self.safe_integer(params, 'until')
3191
+ if until is not None:
3192
+ request['endTime'] = until
3193
+ params = self.omit(params, ['until'])
3194
+ response = self.publicPostInfo(self.extend(request, params))
3195
+ #
3196
+ # [
3197
+ # {
3198
+ # "time":1724762307531,
3199
+ # "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
3200
+ # "delta":{
3201
+ # "type":"accountClassTransfer",
3202
+ # "usdc":"50.0",
3203
+ # "toPerp":false
3204
+ # }
3205
+ # }
3206
+ # ]
3207
+ #
3208
+ records = self.extract_type_from_delta(response)
3209
+ withdrawals = self.filter_by_array(records, 'type', ['withdraw'], False)
3210
+ return self.parse_transactions(withdrawals, None, since, limit)
3211
+
3212
+ def fetch_open_interests(self, symbols: Strings = None, params={}):
3213
+ """
3214
+ Retrieves the open interest for a list of symbols
3215
+ :param str[] [symbols]: Unified CCXT market symbol
3216
+ :param dict [params]: exchange specific parameters
3217
+ :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
3218
+ """
3219
+ self.load_markets()
3220
+ symbols = self.market_symbols(symbols)
3221
+ swapMarkets = self.fetch_swap_markets()
3222
+ return self.parse_open_interests(swapMarkets, symbols)
3223
+
3224
+ def fetch_open_interest(self, symbol: str, params={}):
3225
+ """
3226
+ retrieves the open interest of a contract trading pair
3227
+ :param str symbol: unified CCXT market symbol
3228
+ :param dict [params]: exchange specific parameters
3229
+ :returns dict: an `open interest structure <https://docs.ccxt.com/#/?id=open-interest-structure>`
3230
+ """
3231
+ symbol = self.symbol(symbol)
3232
+ self.load_markets()
3233
+ ois = self.fetch_open_interests([symbol], params)
3234
+ return ois[symbol]
3235
+
3236
+ def parse_open_interest(self, interest, market: Market = None):
3237
+ #
3238
+ # {
3239
+ # szDecimals: '2',
3240
+ # name: 'HYPE',
3241
+ # maxLeverage: '3',
3242
+ # funding: '0.00014735',
3243
+ # openInterest: '14677900.74',
3244
+ # prevDayPx: '26.145',
3245
+ # dayNtlVlm: '299643445.12560016',
3246
+ # premium: '0.00081613',
3247
+ # oraclePx: '27.569',
3248
+ # markPx: '27.63',
3249
+ # midPx: '27.599',
3250
+ # impactPxs: ['27.5915', '27.6319'],
3251
+ # dayBaseVlm: '10790652.83',
3252
+ # baseId: 159
3253
+ # }
3254
+ #
3255
+ interest = self.safe_dict(interest, 'info', {})
3256
+ coin = self.safe_string(interest, 'name')
3257
+ marketId = None
3258
+ if coin is not None:
3259
+ marketId = self.coin_to_market_id(coin)
3260
+ return self.safe_open_interest({
3261
+ 'symbol': self.safe_symbol(marketId),
3262
+ 'openInterestAmount': self.safe_number(interest, 'openInterest'),
3263
+ 'openInterestValue': None,
3264
+ 'timestamp': None,
3265
+ 'datetime': None,
3266
+ 'info': interest,
3267
+ }, market)
3268
+
3269
+ def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
3270
+ """
3271
+ fetch the history of funding payments paid and received on self account
3272
+ :param str [symbol]: unified market symbol
3273
+ :param int [since]: the earliest time in ms to fetch funding history for
3274
+ :param int [limit]: the maximum number of funding history structures to retrieve
3275
+ :param dict [params]: extra parameters specific to the exchange API endpoint
3276
+ :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
3277
+ """
3278
+ self.load_markets()
3279
+ market = None
3280
+ if symbol is not None:
3281
+ market = self.market(symbol)
3282
+ userAddress = None
3283
+ userAddress, params = self.handle_public_address('fetchFundingHistory', params)
3284
+ request: dict = {
3285
+ 'user': userAddress,
3286
+ 'type': 'userFunding',
3287
+ }
3288
+ if since is not None:
3289
+ request['startTime'] = since
3290
+ until = self.safe_integer(params, 'until')
3291
+ params = self.omit(params, 'until')
3292
+ if until is not None:
3293
+ request['endTime'] = until
3294
+ response = self.publicPostInfo(self.extend(request, params))
3295
+ #
3296
+ # [
3297
+ # {
3298
+ # "time": 1734026400057,
3299
+ # "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
3300
+ # "delta": {
3301
+ # "type": "funding",
3302
+ # "coin": "SOL",
3303
+ # "usdc": "75.635093",
3304
+ # "szi": "-7375.9",
3305
+ # "fundingRate": "0.00004381",
3306
+ # "nSamples": null
3307
+ # }
3308
+ # }
3309
+ # ]
3310
+ #
3311
+ return self.parse_incomes(response, market, since, limit)
3312
+
3313
+ def parse_income(self, income, market: Market = None):
3314
+ #
3315
+ # {
3316
+ # "time": 1734026400057,
3317
+ # "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
3318
+ # "delta": {
3319
+ # "type": "funding",
3320
+ # "coin": "SOL",
3321
+ # "usdc": "75.635093",
3322
+ # "szi": "-7375.9",
3323
+ # "fundingRate": "0.00004381",
3324
+ # "nSamples": null
3325
+ # }
3326
+ # }
3327
+ #
3328
+ id = self.safe_string(income, 'hash')
3329
+ timestamp = self.safe_integer(income, 'time')
3330
+ delta = self.safe_dict(income, 'delta')
3331
+ baseId = self.safe_string(delta, 'coin')
3332
+ marketSymbol = baseId + '/USDC:USDC'
3333
+ market = self.safe_market(marketSymbol)
3334
+ symbol = market['symbol']
3335
+ amount = self.safe_string(delta, 'usdc')
3336
+ code = self.safe_currency_code('USDC')
3337
+ rate = self.safe_number(delta, 'fundingRate')
3338
+ return {
3339
+ 'info': income,
3340
+ 'symbol': symbol,
3341
+ 'code': code,
3342
+ 'timestamp': timestamp,
3343
+ 'datetime': self.iso8601(timestamp),
3344
+ 'id': id,
3345
+ 'amount': self.parse_number(amount),
3346
+ 'rate': rate,
3347
+ }
3348
+
3349
+ def extract_type_from_delta(self, data=[]):
3350
+ records = []
3351
+ for i in range(0, len(data)):
3352
+ record = data[i]
3353
+ record['type'] = record['delta']['type']
3354
+ records.append(record)
3355
+ return records
3356
+
3357
+ def format_vault_address(self, address: Str = None):
3358
+ if address is None:
3359
+ return None
3360
+ if address.startswith('0x'):
3361
+ return address.replace('0x', '')
3362
+ return address
3363
+
3364
+ def handle_public_address(self, methodName: str, params: dict):
3365
+ userAux = None
3366
+ userAux, params = self.handle_option_and_params(params, methodName, 'user')
3367
+ user = userAux
3368
+ user, params = self.handle_option_and_params(params, methodName, 'address', userAux)
3369
+ if (user is not None) and (user != ''):
3370
+ return [user, params]
3371
+ if (self.walletAddress is not None) and (self.walletAddress != ''):
3372
+ return [self.walletAddress, params]
3373
+ raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a user parameter inside \'params\' or the wallet address set')
3374
+
3375
+ def coin_to_market_id(self, coin: Str):
3376
+ if coin.find('/') > -1 or coin.find('@') > -1:
3377
+ return coin # spot
3378
+ return coin + '/USDC:USDC'
3379
+
3380
+ def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
3381
+ if not response:
3382
+ return None # fallback to default error handler
3383
+ # {"status":"err","response":"User or API Wallet 0xb8a6f8b26223de27c31938d56e470a5b832703a5 does not exist."}
3384
+ #
3385
+ # {
3386
+ # status: 'ok',
3387
+ # response: {type: 'order', data: {statuses: [{error: 'Insufficient margin to place order. asset=4'}]}}
3388
+ # }
3389
+ # {"status":"ok","response":{"type":"order","data":{"statuses":[{"error":"Insufficient margin to place order. asset=84"}]}}}
3390
+ #
3391
+ status = self.safe_string(response, 'status', '')
3392
+ message = None
3393
+ if status == 'err':
3394
+ message = self.safe_string(response, 'response')
3395
+ else:
3396
+ responsePayload = self.safe_dict(response, 'response', {})
3397
+ data = self.safe_dict(responsePayload, 'data', {})
3398
+ statuses = self.safe_list(data, 'statuses', [])
3399
+ firstStatus = self.safe_dict(statuses, 0)
3400
+ message = self.safe_string(firstStatus, 'error')
3401
+ feedback = self.id + ' ' + body
3402
+ nonEmptyMessage = ((message is not None) and (message != ''))
3403
+ if nonEmptyMessage:
3404
+ self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
3405
+ self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
3406
+ if nonEmptyMessage:
3407
+ raise ExchangeError(feedback) # unknown message
3408
+ return None
3409
+
3410
+ def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
3411
+ url = self.implode_hostname(self.urls['api'][api]) + '/' + path
3412
+ if method == 'POST':
3413
+ headers = {
3414
+ 'Content-Type': 'application/json',
3415
+ }
3416
+ body = self.json(params)
3417
+ return {'url': url, 'method': method, 'body': body, 'headers': headers}
3418
+
3419
+ def calculate_rate_limiter_cost(self, api, method, path, params, config={}):
3420
+ if ('byType' in config) and ('type' in params):
3421
+ type = params['type']
3422
+ byType = config['byType']
3423
+ if type in byType:
3424
+ return byType[type]
3425
+ return self.safe_value(config, 'cost', 1)
3426
+
3427
+ def parse_create_edit_order_args(self, id: Str, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
3428
+ market = self.market(symbol)
3429
+ vaultAddress = self.safe_string(params, 'vaultAddress')
3430
+ params = self.omit(params, 'vaultAddress')
3431
+ symbol = market['symbol']
3432
+ order = {
3433
+ 'symbol': symbol,
3434
+ 'type': type,
3435
+ 'side': side,
3436
+ 'amount': amount,
3437
+ 'price': price,
3438
+ 'params': params,
3439
+ }
3440
+ globalParams = {}
3441
+ if vaultAddress is not None:
3442
+ globalParams['vaultAddress'] = vaultAddress
3443
+ if id is not None:
3444
+ order['id'] = id
3445
+ return [order, globalParams]