hyperliquid-python-sdk-async 0.24.6__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.
- hyperliquid/__init__.py +0 -0
- hyperliquid/api.py +69 -0
- hyperliquid/exchange.py +888 -0
- hyperliquid/info.py +288 -0
- hyperliquid/utils/__init__.py +0 -0
- hyperliquid/utils/constants.py +3 -0
- hyperliquid/utils/error.py +17 -0
- hyperliquid/utils/signing.py +527 -0
- hyperliquid/utils/types.py +220 -0
- hyperliquid/websocket_manager.py +197 -0
- hyperliquid_python_sdk_async-0.24.6.dist-info/LICENSE.md +21 -0
- hyperliquid_python_sdk_async-0.24.6.dist-info/METADATA +162 -0
- hyperliquid_python_sdk_async-0.24.6.dist-info/RECORD +15 -0
- hyperliquid_python_sdk_async-0.24.6.dist-info/WHEEL +4 -0
- hyperliquid_python_sdk_async-0.24.6.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Callable, Dict, List, Literal, NamedTuple, Optional, Tuple, TypedDict, Union, cast
|
|
4
|
+
from typing_extensions import NotRequired
|
|
5
|
+
|
|
6
|
+
Any = Any
|
|
7
|
+
Option = Optional
|
|
8
|
+
cast = cast
|
|
9
|
+
Callable = Callable
|
|
10
|
+
NamedTuple = NamedTuple
|
|
11
|
+
NotRequired = NotRequired
|
|
12
|
+
|
|
13
|
+
AssetInfo = TypedDict("AssetInfo", {"name": str, "szDecimals": int})
|
|
14
|
+
Meta = TypedDict("Meta", {"universe": List[AssetInfo]})
|
|
15
|
+
Side = Union[Literal["A"], Literal["B"]]
|
|
16
|
+
SIDES: List[Side] = ["A", "B"]
|
|
17
|
+
|
|
18
|
+
SpotAssetInfo = TypedDict("SpotAssetInfo", {"name": str, "tokens": List[int], "index": int, "isCanonical": bool})
|
|
19
|
+
SpotTokenInfo = TypedDict(
|
|
20
|
+
"SpotTokenInfo",
|
|
21
|
+
{
|
|
22
|
+
"name": str,
|
|
23
|
+
"szDecimals": int,
|
|
24
|
+
"weiDecimals": int,
|
|
25
|
+
"index": int,
|
|
26
|
+
"tokenId": str,
|
|
27
|
+
"isCanonical": bool,
|
|
28
|
+
"evmContract": Optional[str],
|
|
29
|
+
"fullName": Optional[str],
|
|
30
|
+
},
|
|
31
|
+
)
|
|
32
|
+
SpotMeta = TypedDict("SpotMeta", {"universe": List[SpotAssetInfo], "tokens": List[SpotTokenInfo]})
|
|
33
|
+
SpotAssetCtx = TypedDict(
|
|
34
|
+
"SpotAssetCtx",
|
|
35
|
+
{"dayNtlVlm": str, "markPx": str, "midPx": Optional[str], "prevDayPx": str, "circulatingSupply": str, "coin": str},
|
|
36
|
+
)
|
|
37
|
+
SpotMetaAndAssetCtxs = Tuple[SpotMeta, List[SpotAssetCtx]]
|
|
38
|
+
|
|
39
|
+
AllMidsSubscription = TypedDict("AllMidsSubscription", {"type": Literal["allMids"]})
|
|
40
|
+
BboSubscription = TypedDict("BboSubscription", {"type": Literal["bbo"], "coin": str})
|
|
41
|
+
L2BookSubscription = TypedDict("L2BookSubscription", {"type": Literal["l2Book"], "coin": str})
|
|
42
|
+
TradesSubscription = TypedDict("TradesSubscription", {"type": Literal["trades"], "coin": str})
|
|
43
|
+
UserEventsSubscription = TypedDict("UserEventsSubscription", {"type": Literal["userEvents"], "user": str})
|
|
44
|
+
UserFillsSubscription = TypedDict("UserFillsSubscription", {"type": Literal["userFills"], "user": str})
|
|
45
|
+
CandleSubscription = TypedDict("CandleSubscription", {"type": Literal["candle"], "coin": str, "interval": str})
|
|
46
|
+
OrderUpdatesSubscription = TypedDict("OrderUpdatesSubscription", {"type": Literal["orderUpdates"], "user": str})
|
|
47
|
+
UserFundingsSubscription = TypedDict("UserFundingsSubscription", {"type": Literal["userFundings"], "user": str})
|
|
48
|
+
UserNonFundingLedgerUpdatesSubscription = TypedDict(
|
|
49
|
+
"UserNonFundingLedgerUpdatesSubscription", {"type": Literal["userNonFundingLedgerUpdates"], "user": str}
|
|
50
|
+
)
|
|
51
|
+
WebData2Subscription = TypedDict("WebData2Subscription", {"type": Literal["webData2"], "user": str})
|
|
52
|
+
ActiveAssetCtxSubscription = TypedDict("ActiveAssetCtxSubscription", {"type": Literal["activeAssetCtx"], "coin": str})
|
|
53
|
+
ActiveAssetDataSubscription = TypedDict(
|
|
54
|
+
"ActiveAssetDataSubscription", {"type": Literal["activeAssetData"], "user": str, "coin": str}
|
|
55
|
+
)
|
|
56
|
+
# If adding new subscription types that contain coin's don't forget to handle automatically rewrite name to coin in info.subscribe
|
|
57
|
+
Subscription = Union[
|
|
58
|
+
AllMidsSubscription,
|
|
59
|
+
BboSubscription,
|
|
60
|
+
L2BookSubscription,
|
|
61
|
+
TradesSubscription,
|
|
62
|
+
UserEventsSubscription,
|
|
63
|
+
UserFillsSubscription,
|
|
64
|
+
CandleSubscription,
|
|
65
|
+
OrderUpdatesSubscription,
|
|
66
|
+
UserFundingsSubscription,
|
|
67
|
+
UserNonFundingLedgerUpdatesSubscription,
|
|
68
|
+
WebData2Subscription,
|
|
69
|
+
ActiveAssetCtxSubscription,
|
|
70
|
+
ActiveAssetDataSubscription,
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
AllMidsData = TypedDict("AllMidsData", {"mids": Dict[str, str]})
|
|
74
|
+
AllMidsMsg = TypedDict("AllMidsMsg", {"channel": Literal["allMids"], "data": AllMidsData})
|
|
75
|
+
L2Level = TypedDict("L2Level", {"px": str, "sz": str, "n": int})
|
|
76
|
+
L2BookData = TypedDict("L2BookData", {"coin": str, "levels": Tuple[List[L2Level], List[L2Level]], "time": int})
|
|
77
|
+
L2BookMsg = TypedDict("L2BookMsg", {"channel": Literal["l2Book"], "data": L2BookData})
|
|
78
|
+
BboData = TypedDict("BboData", {"coin": str, "time": int, "bbo": Tuple[Optional[L2Level], Optional[L2Level]]})
|
|
79
|
+
BboMsg = TypedDict("BboMsg", {"channel": Literal["bbo"], "data": BboData})
|
|
80
|
+
PongMsg = TypedDict("PongMsg", {"channel": Literal["pong"]})
|
|
81
|
+
Trade = TypedDict("Trade", {"coin": str, "side": Side, "px": str, "sz": int, "hash": str, "time": int})
|
|
82
|
+
CrossLeverage = TypedDict(
|
|
83
|
+
"CrossLeverage",
|
|
84
|
+
{
|
|
85
|
+
"type": Literal["cross"],
|
|
86
|
+
"value": int,
|
|
87
|
+
},
|
|
88
|
+
)
|
|
89
|
+
IsolatedLeverage = TypedDict(
|
|
90
|
+
"IsolatedLeverage",
|
|
91
|
+
{
|
|
92
|
+
"type": Literal["isolated"],
|
|
93
|
+
"value": int,
|
|
94
|
+
"rawUsd": str,
|
|
95
|
+
},
|
|
96
|
+
)
|
|
97
|
+
Leverage = Union[CrossLeverage, IsolatedLeverage]
|
|
98
|
+
TradesMsg = TypedDict("TradesMsg", {"channel": Literal["trades"], "data": List[Trade]})
|
|
99
|
+
PerpAssetCtx = TypedDict(
|
|
100
|
+
"PerpAssetCtx",
|
|
101
|
+
{
|
|
102
|
+
"funding": str,
|
|
103
|
+
"openInterest": str,
|
|
104
|
+
"prevDayPx": str,
|
|
105
|
+
"dayNtlVlm": str,
|
|
106
|
+
"premium": str,
|
|
107
|
+
"oraclePx": str,
|
|
108
|
+
"markPx": str,
|
|
109
|
+
"midPx": Optional[str],
|
|
110
|
+
"impactPxs": Optional[Tuple[str, str]],
|
|
111
|
+
"dayBaseVlm": str,
|
|
112
|
+
},
|
|
113
|
+
)
|
|
114
|
+
ActiveAssetCtx = TypedDict("ActiveAssetCtx", {"coin": str, "ctx": PerpAssetCtx})
|
|
115
|
+
ActiveSpotAssetCtx = TypedDict("ActiveSpotAssetCtx", {"coin": str, "ctx": SpotAssetCtx})
|
|
116
|
+
ActiveAssetCtxMsg = TypedDict("ActiveAssetCtxMsg", {"channel": Literal["activeAssetCtx"], "data": ActiveAssetCtx})
|
|
117
|
+
ActiveSpotAssetCtxMsg = TypedDict(
|
|
118
|
+
"ActiveSpotAssetCtxMsg", {"channel": Literal["activeSpotAssetCtx"], "data": ActiveSpotAssetCtx}
|
|
119
|
+
)
|
|
120
|
+
ActiveAssetData = TypedDict(
|
|
121
|
+
"ActiveAssetData",
|
|
122
|
+
{
|
|
123
|
+
"user": str,
|
|
124
|
+
"coin": str,
|
|
125
|
+
"leverage": Leverage,
|
|
126
|
+
"maxTradeSzs": Tuple[str, str],
|
|
127
|
+
"availableToTrade": Tuple[str, str],
|
|
128
|
+
"markPx": str,
|
|
129
|
+
},
|
|
130
|
+
)
|
|
131
|
+
ActiveAssetDataMsg = TypedDict("ActiveAssetDataMsg", {"channel": Literal["activeAssetData"], "data": ActiveAssetData})
|
|
132
|
+
Fill = TypedDict(
|
|
133
|
+
"Fill",
|
|
134
|
+
{
|
|
135
|
+
"coin": str,
|
|
136
|
+
"px": str,
|
|
137
|
+
"sz": str,
|
|
138
|
+
"side": Side,
|
|
139
|
+
"time": int,
|
|
140
|
+
"startPosition": str,
|
|
141
|
+
"dir": str,
|
|
142
|
+
"closedPnl": str,
|
|
143
|
+
"hash": str,
|
|
144
|
+
"oid": int,
|
|
145
|
+
"crossed": bool,
|
|
146
|
+
"fee": str,
|
|
147
|
+
"tid": int,
|
|
148
|
+
"feeToken": str,
|
|
149
|
+
},
|
|
150
|
+
)
|
|
151
|
+
# TODO: handle other types of user events
|
|
152
|
+
UserEventsData = TypedDict("UserEventsData", {"fills": List[Fill]}, total=False)
|
|
153
|
+
UserEventsMsg = TypedDict("UserEventsMsg", {"channel": Literal["user"], "data": UserEventsData})
|
|
154
|
+
UserFillsData = TypedDict("UserFillsData", {"user": str, "isSnapshot": bool, "fills": List[Fill]})
|
|
155
|
+
UserFillsMsg = TypedDict("UserFillsMsg", {"channel": Literal["userFills"], "data": UserFillsData})
|
|
156
|
+
OtherWsMsg = TypedDict(
|
|
157
|
+
"OtherWsMsg",
|
|
158
|
+
{
|
|
159
|
+
"channel": Union[
|
|
160
|
+
Literal["candle"],
|
|
161
|
+
Literal["orderUpdates"],
|
|
162
|
+
Literal["userFundings"],
|
|
163
|
+
Literal["userNonFundingLedgerUpdates"],
|
|
164
|
+
Literal["webData2"],
|
|
165
|
+
],
|
|
166
|
+
"data": Any,
|
|
167
|
+
},
|
|
168
|
+
total=False,
|
|
169
|
+
)
|
|
170
|
+
WsMsg = Union[
|
|
171
|
+
AllMidsMsg,
|
|
172
|
+
BboMsg,
|
|
173
|
+
L2BookMsg,
|
|
174
|
+
TradesMsg,
|
|
175
|
+
UserEventsMsg,
|
|
176
|
+
PongMsg,
|
|
177
|
+
UserFillsMsg,
|
|
178
|
+
OtherWsMsg,
|
|
179
|
+
ActiveAssetCtxMsg,
|
|
180
|
+
ActiveSpotAssetCtxMsg,
|
|
181
|
+
ActiveAssetDataMsg,
|
|
182
|
+
]
|
|
183
|
+
|
|
184
|
+
# b is the public address of the builder, f is the amount of the fee in tenths of basis points. e.g. 10 means 1 basis point
|
|
185
|
+
BuilderInfo = TypedDict("BuilderInfo", {"b": str, "f": int})
|
|
186
|
+
Abstraction = Literal["unifiedAccount", "portfolioMargin", "disabled"]
|
|
187
|
+
AgentAbstraction = Literal["u", "p", "i"]
|
|
188
|
+
|
|
189
|
+
PerpDexSchemaInput = TypedDict(
|
|
190
|
+
"PerpDexSchemaInput", {"fullName": str, "collateralToken": int, "oracleUpdater": Optional[str]}
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class Cloid:
|
|
195
|
+
def __init__(self, raw_cloid: str):
|
|
196
|
+
self._raw_cloid: str = raw_cloid
|
|
197
|
+
self._validate()
|
|
198
|
+
|
|
199
|
+
def _validate(self):
|
|
200
|
+
if not self._raw_cloid[:2] == "0x":
|
|
201
|
+
raise TypeError("cloid is not a hex string")
|
|
202
|
+
if not len(self._raw_cloid[2:]) == 32:
|
|
203
|
+
raise TypeError("cloid is not 16 bytes")
|
|
204
|
+
|
|
205
|
+
def __str__(self):
|
|
206
|
+
return str(self._raw_cloid)
|
|
207
|
+
|
|
208
|
+
def __repr__(self):
|
|
209
|
+
return str(self._raw_cloid)
|
|
210
|
+
|
|
211
|
+
@staticmethod
|
|
212
|
+
def from_int(cloid: int) -> Cloid:
|
|
213
|
+
return Cloid(f"{cloid:#034x}")
|
|
214
|
+
|
|
215
|
+
@staticmethod
|
|
216
|
+
def from_str(cloid: str) -> Cloid:
|
|
217
|
+
return Cloid(cloid)
|
|
218
|
+
|
|
219
|
+
def to_raw(self):
|
|
220
|
+
return self._raw_cloid
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
|
|
7
|
+
import websockets
|
|
8
|
+
|
|
9
|
+
from hyperliquid.utils.types import Any, Callable, Dict, List, NamedTuple, Optional, Subscription, Tuple, WsMsg
|
|
10
|
+
|
|
11
|
+
ActiveSubscription = NamedTuple("ActiveSubscription", [("callback", Callable[[Any], None]), ("subscription_id", int)])
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def subscription_to_identifier(subscription: Subscription) -> str:
|
|
15
|
+
if subscription["type"] == "allMids":
|
|
16
|
+
return "allMids"
|
|
17
|
+
elif subscription["type"] == "l2Book":
|
|
18
|
+
return f'l2Book:{subscription["coin"].lower()}'
|
|
19
|
+
elif subscription["type"] == "trades":
|
|
20
|
+
return f'trades:{subscription["coin"].lower()}'
|
|
21
|
+
elif subscription["type"] == "userEvents":
|
|
22
|
+
return "userEvents"
|
|
23
|
+
elif subscription["type"] == "userFills":
|
|
24
|
+
return f'userFills:{subscription["user"].lower()}'
|
|
25
|
+
elif subscription["type"] == "candle":
|
|
26
|
+
return f'candle:{subscription["coin"].lower()},{subscription["interval"]}'
|
|
27
|
+
elif subscription["type"] == "orderUpdates":
|
|
28
|
+
return "orderUpdates"
|
|
29
|
+
elif subscription["type"] == "userFundings":
|
|
30
|
+
return f'userFundings:{subscription["user"].lower()}'
|
|
31
|
+
elif subscription["type"] == "userNonFundingLedgerUpdates":
|
|
32
|
+
return f'userNonFundingLedgerUpdates:{subscription["user"].lower()}'
|
|
33
|
+
elif subscription["type"] == "webData2":
|
|
34
|
+
return f'webData2:{subscription["user"].lower()}'
|
|
35
|
+
elif subscription["type"] == "bbo":
|
|
36
|
+
return f'bbo:{subscription["coin"].lower()}'
|
|
37
|
+
elif subscription["type"] == "activeAssetCtx":
|
|
38
|
+
return f'activeAssetCtx:{subscription["coin"].lower()}'
|
|
39
|
+
elif subscription["type"] == "activeAssetData":
|
|
40
|
+
return f'activeAssetData:{subscription["coin"].lower()},{subscription["user"].lower()}'
|
|
41
|
+
raise ValueError(f"Unsupported subscription type: {subscription['type']}")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def ws_msg_to_identifier(ws_msg: WsMsg) -> Optional[str]:
|
|
45
|
+
if ws_msg["channel"] == "pong":
|
|
46
|
+
return "pong"
|
|
47
|
+
elif ws_msg["channel"] == "allMids":
|
|
48
|
+
return "allMids"
|
|
49
|
+
elif ws_msg["channel"] == "l2Book":
|
|
50
|
+
return f'l2Book:{ws_msg["data"]["coin"].lower()}'
|
|
51
|
+
elif ws_msg["channel"] == "trades":
|
|
52
|
+
trades = ws_msg["data"]
|
|
53
|
+
if len(trades) == 0:
|
|
54
|
+
return None
|
|
55
|
+
return f'trades:{trades[0]["coin"].lower()}'
|
|
56
|
+
elif ws_msg["channel"] == "user":
|
|
57
|
+
return "userEvents"
|
|
58
|
+
elif ws_msg["channel"] == "userFills":
|
|
59
|
+
return f'userFills:{ws_msg["data"]["user"].lower()}'
|
|
60
|
+
elif ws_msg["channel"] == "candle":
|
|
61
|
+
return f'candle:{ws_msg["data"]["s"].lower()},{ws_msg["data"]["i"]}'
|
|
62
|
+
elif ws_msg["channel"] == "orderUpdates":
|
|
63
|
+
return "orderUpdates"
|
|
64
|
+
elif ws_msg["channel"] == "userFundings":
|
|
65
|
+
return f'userFundings:{ws_msg["data"]["user"].lower()}'
|
|
66
|
+
elif ws_msg["channel"] == "userNonFundingLedgerUpdates":
|
|
67
|
+
return f'userNonFundingLedgerUpdates:{ws_msg["data"]["user"].lower()}'
|
|
68
|
+
elif ws_msg["channel"] == "webData2":
|
|
69
|
+
return f'webData2:{ws_msg["data"]["user"].lower()}'
|
|
70
|
+
elif ws_msg["channel"] == "bbo":
|
|
71
|
+
return f'bbo:{ws_msg["data"]["coin"].lower()}'
|
|
72
|
+
elif ws_msg["channel"] == "activeAssetCtx" or ws_msg["channel"] == "activeSpotAssetCtx":
|
|
73
|
+
return f'activeAssetCtx:{ws_msg["data"]["coin"].lower()}'
|
|
74
|
+
elif ws_msg["channel"] == "activeAssetData":
|
|
75
|
+
return f'activeAssetData:{ws_msg["data"]["coin"].lower()},{ws_msg["data"]["user"].lower()}'
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class WebsocketManager:
|
|
80
|
+
def __init__(self, base_url: str):
|
|
81
|
+
self.subscription_id_counter = 0
|
|
82
|
+
self.queued_subscriptions: List[Tuple[Subscription, ActiveSubscription]] = []
|
|
83
|
+
self.active_subscriptions: Dict[str, List[ActiveSubscription]] = defaultdict(list)
|
|
84
|
+
self.ws_url = "ws" + base_url[len("http") :] + "/ws"
|
|
85
|
+
self.ws = None
|
|
86
|
+
self._runner_task: Optional[asyncio.Task] = None
|
|
87
|
+
self._ping_task: Optional[asyncio.Task] = None
|
|
88
|
+
self._ready_event = asyncio.Event()
|
|
89
|
+
self._stop_event = asyncio.Event()
|
|
90
|
+
|
|
91
|
+
async def start(self) -> None:
|
|
92
|
+
if self._runner_task is not None and not self._runner_task.done():
|
|
93
|
+
return
|
|
94
|
+
self._stop_event.clear()
|
|
95
|
+
self._runner_task = asyncio.create_task(self._run())
|
|
96
|
+
|
|
97
|
+
async def stop(self) -> None:
|
|
98
|
+
self._stop_event.set()
|
|
99
|
+
if self.ws is not None:
|
|
100
|
+
await self.ws.close()
|
|
101
|
+
if self._runner_task is not None:
|
|
102
|
+
await self._runner_task
|
|
103
|
+
self._ready_event.clear()
|
|
104
|
+
|
|
105
|
+
async def _run(self) -> None:
|
|
106
|
+
try:
|
|
107
|
+
async with websockets.connect(self.ws_url, ping_interval=None) as websocket:
|
|
108
|
+
self.ws = websocket
|
|
109
|
+
self._ready_event.set()
|
|
110
|
+
for subscription, active_subscription in list(self.queued_subscriptions):
|
|
111
|
+
await self.subscribe(subscription, active_subscription.callback, active_subscription.subscription_id)
|
|
112
|
+
self.queued_subscriptions.clear()
|
|
113
|
+
self._ping_task = asyncio.create_task(self._send_ping())
|
|
114
|
+
await self._consume_messages()
|
|
115
|
+
finally:
|
|
116
|
+
self.ws = None
|
|
117
|
+
self._ready_event.clear()
|
|
118
|
+
if self._ping_task is not None:
|
|
119
|
+
self._ping_task.cancel()
|
|
120
|
+
try:
|
|
121
|
+
await self._ping_task
|
|
122
|
+
except asyncio.CancelledError:
|
|
123
|
+
pass
|
|
124
|
+
self._ping_task = None
|
|
125
|
+
|
|
126
|
+
async def _send_ping(self) -> None:
|
|
127
|
+
try:
|
|
128
|
+
while not self._stop_event.is_set():
|
|
129
|
+
await asyncio.sleep(50)
|
|
130
|
+
if self.ws is None:
|
|
131
|
+
break
|
|
132
|
+
logging.debug("Websocket sending ping")
|
|
133
|
+
await self.ws.send(json.dumps({"method": "ping"}))
|
|
134
|
+
except asyncio.CancelledError:
|
|
135
|
+
raise
|
|
136
|
+
finally:
|
|
137
|
+
logging.debug("Websocket ping sender stopped")
|
|
138
|
+
|
|
139
|
+
async def _consume_messages(self) -> None:
|
|
140
|
+
assert self.ws is not None
|
|
141
|
+
async for message in self.ws:
|
|
142
|
+
if message == "Websocket connection established.":
|
|
143
|
+
logging.debug(message)
|
|
144
|
+
continue
|
|
145
|
+
logging.debug("on_message %s", message)
|
|
146
|
+
ws_msg: WsMsg = json.loads(message)
|
|
147
|
+
identifier = ws_msg_to_identifier(ws_msg)
|
|
148
|
+
if identifier == "pong":
|
|
149
|
+
logging.debug("Websocket received pong")
|
|
150
|
+
continue
|
|
151
|
+
if identifier is None:
|
|
152
|
+
logging.debug("Websocket not handling empty message")
|
|
153
|
+
continue
|
|
154
|
+
active_subscriptions = self.active_subscriptions[identifier]
|
|
155
|
+
if len(active_subscriptions) == 0:
|
|
156
|
+
print("Websocket message from an unexpected subscription:", message, identifier)
|
|
157
|
+
continue
|
|
158
|
+
for active_subscription in active_subscriptions:
|
|
159
|
+
result = active_subscription.callback(ws_msg)
|
|
160
|
+
if inspect.isawaitable(result):
|
|
161
|
+
asyncio.create_task(result)
|
|
162
|
+
|
|
163
|
+
async def subscribe(
|
|
164
|
+
self, subscription: Subscription, callback: Callable[[Any], None], subscription_id: Optional[int] = None
|
|
165
|
+
) -> int:
|
|
166
|
+
if subscription_id is None:
|
|
167
|
+
self.subscription_id_counter += 1
|
|
168
|
+
subscription_id = self.subscription_id_counter
|
|
169
|
+
if not self._ready_event.is_set():
|
|
170
|
+
logging.debug("enqueueing subscription")
|
|
171
|
+
self.queued_subscriptions.append((subscription, ActiveSubscription(callback, subscription_id)))
|
|
172
|
+
return subscription_id
|
|
173
|
+
|
|
174
|
+
logging.debug("subscribing")
|
|
175
|
+
identifier = subscription_to_identifier(subscription)
|
|
176
|
+
if identifier == "userEvents" or identifier == "orderUpdates":
|
|
177
|
+
# TODO: ideally the userEvent and orderUpdates messages would include the user so that we can multiplex
|
|
178
|
+
if len(self.active_subscriptions[identifier]) != 0:
|
|
179
|
+
raise NotImplementedError(f"Cannot subscribe to {identifier} multiple times")
|
|
180
|
+
|
|
181
|
+
self.active_subscriptions[identifier].append(ActiveSubscription(callback, subscription_id))
|
|
182
|
+
assert self.ws is not None
|
|
183
|
+
await self.ws.send(json.dumps({"method": "subscribe", "subscription": subscription}))
|
|
184
|
+
return subscription_id
|
|
185
|
+
|
|
186
|
+
async def unsubscribe(self, subscription: Subscription, subscription_id: int) -> bool:
|
|
187
|
+
if not self._ready_event.is_set():
|
|
188
|
+
raise NotImplementedError("Can't unsubscribe before websocket connected")
|
|
189
|
+
|
|
190
|
+
identifier = subscription_to_identifier(subscription)
|
|
191
|
+
active_subscriptions = self.active_subscriptions[identifier]
|
|
192
|
+
new_active_subscriptions = [x for x in active_subscriptions if x.subscription_id != subscription_id]
|
|
193
|
+
if len(new_active_subscriptions) == 0:
|
|
194
|
+
assert self.ws is not None
|
|
195
|
+
await self.ws.send(json.dumps({"method": "unsubscribe", "subscription": subscription}))
|
|
196
|
+
self.active_subscriptions[identifier] = new_active_subscriptions
|
|
197
|
+
return len(active_subscriptions) != len(new_active_subscriptions)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Hyperliquid Labs Pte. Ltd.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
16
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
17
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
18
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
19
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
20
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
|
21
|
+
OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: hyperliquid-python-sdk-async
|
|
3
|
+
Version: 0.24.6
|
|
4
|
+
Summary: SDK for Hyperliquid API trading with Python.
|
|
5
|
+
Home-page: https://github.com/hyperliquid-dex/hyperliquid-python-sdk
|
|
6
|
+
License: MIT
|
|
7
|
+
Author: Hyperliquid
|
|
8
|
+
Author-email: hello@hyperliquid.xyz
|
|
9
|
+
Requires-Python: >=3.9,<4.0
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Requires-Dist: aiohttp (>=3.10,<4.0)
|
|
26
|
+
Requires-Dist: eth-account (>=0.13.5,<0.14.0)
|
|
27
|
+
Requires-Dist: eth-utils (>=5.2.0,<6.0.0)
|
|
28
|
+
Requires-Dist: msgpack (>=1.0.5,<2.0.0)
|
|
29
|
+
Requires-Dist: websockets (>=15.0.1,<16.0.0)
|
|
30
|
+
Project-URL: Repository, https://github.com/hyperliquid-dex/hyperliquid-python-sdk
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# hyperliquid-python-sdk
|
|
34
|
+
|
|
35
|
+
<div align="center">
|
|
36
|
+
|
|
37
|
+
[](https://github.com/hyperliquid-dex/hyperliquid-python-sdk/pulls?utf8=%E2%9C%93&q=is%3Apr%20author%3Aapp%2Fdependabot)
|
|
38
|
+
|
|
39
|
+
[](https://github.com/psf/black)
|
|
40
|
+
[](https://github.com/PyCQA/bandit)
|
|
41
|
+
[](https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/.pre-commit-config.yaml)
|
|
42
|
+
[](https://github.com/hyperliquid-dex/hyperliquid-python-sdk/releases)
|
|
43
|
+
[](https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/LICENSE.md)
|
|
44
|
+
|
|
45
|
+
SDK for Hyperliquid API trading with Python.
|
|
46
|
+
|
|
47
|
+
</div>
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
```bash
|
|
51
|
+
pip install hyperliquid-python-sdk
|
|
52
|
+
```
|
|
53
|
+
## Configuration
|
|
54
|
+
|
|
55
|
+
- Set the public key as the `account_address` in examples/config.json.
|
|
56
|
+
- Set your private key as the `secret_key` in examples/config.json.
|
|
57
|
+
- See the example of loading the config in examples/example_utils.py
|
|
58
|
+
|
|
59
|
+
### [Optional] Generate a new API key for an API Wallet
|
|
60
|
+
Generate and authorize a new API private key on https://app.hyperliquid.xyz/API, and set the API wallet's private key as the `secret_key` in examples/config.json. Note that you must still set the public key of the main wallet *not* the API wallet as the `account_address` in examples/config.json
|
|
61
|
+
|
|
62
|
+
## Usage Examples
|
|
63
|
+
```python
|
|
64
|
+
import asyncio
|
|
65
|
+
|
|
66
|
+
from hyperliquid.info import Info
|
|
67
|
+
from hyperliquid.utils import constants
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def main():
|
|
71
|
+
async with Info(constants.TESTNET_API_URL, skip_ws=True) as info:
|
|
72
|
+
user_state = await info.user_state("0xcd5051944f780a621ee62e39e493c489668acf4d")
|
|
73
|
+
print(user_state)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
asyncio.run(main())
|
|
77
|
+
```
|
|
78
|
+
See [examples](examples) for more complete examples. You can also checkout the repo and run any of the examples after configuring your private key e.g.
|
|
79
|
+
```bash
|
|
80
|
+
cp examples/config.json.example examples/config.json
|
|
81
|
+
vim examples/config.json
|
|
82
|
+
python examples/basic_order.py
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Getting started with contributing to this repo
|
|
86
|
+
|
|
87
|
+
1. Download `Poetry`: https://python-poetry.org/.
|
|
88
|
+
- Note that in the install script you might have to set `symlinks=True` in `venv.EnvBuilder`.
|
|
89
|
+
- Note that Poetry v2 is not supported, so you'll need to specify a specific version e.g. curl -sSL https://install.python-poetry.org | POETRY_VERSION=1.4.1 python3 -
|
|
90
|
+
|
|
91
|
+
2. Point poetry to correct version of python. For development we require python 3.10 exactly. Some dependencies have issues on 3.11, while older versions don't have correct typing support.
|
|
92
|
+
`brew install python@3.10 && poetry env use /opt/homebrew/Cellar/python@3.10/3.10.16/bin/python3.10`
|
|
93
|
+
|
|
94
|
+
3. Install dependencies:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
make install
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Makefile usage
|
|
101
|
+
|
|
102
|
+
CLI commands for faster development. See `make help` for more details.
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
check-safety Run safety checks on dependencies
|
|
106
|
+
cleanup Cleanup project
|
|
107
|
+
install Install dependencies from poetry.lock
|
|
108
|
+
install-types Find and install additional types for mypy
|
|
109
|
+
lint Alias for the pre-commit target
|
|
110
|
+
lockfile-update Update poetry.lock
|
|
111
|
+
lockfile-update-full Fully regenerate poetry.lock
|
|
112
|
+
poetry-download Download and install poetry
|
|
113
|
+
pre-commit Run linters + formatters via pre-commit, run "make pre-commit hook=black" to run only black
|
|
114
|
+
test Run tests with pytest
|
|
115
|
+
update-dev-deps Update development dependencies to latest versions
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Releases
|
|
119
|
+
|
|
120
|
+
You can see the list of available releases on the [GitHub Releases](https://github.com/hyperliquid-dex/hyperliquid-python-sdk/releases) page.
|
|
121
|
+
|
|
122
|
+
We follow the [Semantic Versions](https://semver.org/) specification and use [`Release Drafter`](https://github.com/marketplace/actions/release-drafter). As pull requests are merged, a draft release is kept up-to-date listing the changes, ready to publish when you’re ready. With the categories option, you can categorize pull requests in release notes using labels.
|
|
123
|
+
|
|
124
|
+
### List of labels and corresponding titles
|
|
125
|
+
|
|
126
|
+
| **Label** | **Title in Releases** |
|
|
127
|
+
| :-----------------------------------: | :---------------------: |
|
|
128
|
+
| `enhancement`, `feature` | Features |
|
|
129
|
+
| `bug`, `refactoring`, `bugfix`, `fix` | Fixes & Refactoring |
|
|
130
|
+
| `build`, `ci`, `testing` | Build System & CI/CD |
|
|
131
|
+
| `breaking` | Breaking Changes |
|
|
132
|
+
| `documentation` | Documentation |
|
|
133
|
+
| `dependencies` | Dependencies updates |
|
|
134
|
+
|
|
135
|
+
### Building and releasing
|
|
136
|
+
|
|
137
|
+
Building a new version of the application contains steps:
|
|
138
|
+
|
|
139
|
+
- Bump the version of your package with `poetry version <version>`. You can pass the new version explicitly, or a rule such as `major`, `minor`, or `patch`. For more details, refer to the [Semantic Versions](https://semver.org/) standard.
|
|
140
|
+
- Make a commit to `GitHub`
|
|
141
|
+
- Create a `GitHub release`
|
|
142
|
+
- `poetry publish --build`
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
This project is licensed under the terms of the `MIT` license. See [LICENSE](LICENSE.md) for more details.
|
|
147
|
+
|
|
148
|
+
```bibtex
|
|
149
|
+
@misc{hyperliquid-python-sdk,
|
|
150
|
+
author = {Hyperliquid},
|
|
151
|
+
title = {SDK for Hyperliquid API trading with Python.},
|
|
152
|
+
year = {2024},
|
|
153
|
+
publisher = {GitHub},
|
|
154
|
+
journal = {GitHub repository},
|
|
155
|
+
howpublished = {\url{https://github.com/hyperliquid-dex/hyperliquid-python-sdk}}
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Credits
|
|
160
|
+
|
|
161
|
+
This project was generated with [`python-package-template`](https://github.com/TezRomacH/python-package-template).
|
|
162
|
+
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
hyperliquid/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
hyperliquid/api.py,sha256=5te2RzF6IrBm0avQQkgKc__nJf-__9RkFDZWfzO4gy4,2698
|
|
3
|
+
hyperliquid/exchange.py,sha256=CDF6Kp68JTQqrrRKNEdVmecTiRWUNUYtUhpgPkfb14k,34604
|
|
4
|
+
hyperliquid/info.py,sha256=eCpFr7d6v5Dd5HFypYwI-zgQoA6e4ynJNYKJKE_2mr4,12299
|
|
5
|
+
hyperliquid/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
hyperliquid/utils/constants.py,sha256=waLKEHF26qm-eyIZ2mpqg_rz5NuobN4VxKiH-mD1Tbg,144
|
|
7
|
+
hyperliquid/utils/error.py,sha256=reXFISI7tHtv-ZLBkN-IP37LAHVvvxDUrSIOW7hXXMI,479
|
|
8
|
+
hyperliquid/utils/signing.py,sha256=k47AoflhGHS0I8qUZpbhmnHTLRRwn1IepdUm9DmMC4U,16099
|
|
9
|
+
hyperliquid/utils/types.py,sha256=UWHfz8XqOfFUDU5o_9eVILn1q3r_nOiKhEDW5tq7iLo,7944
|
|
10
|
+
hyperliquid/websocket_manager.py,sha256=THqWiNqq_HUX9XO0o82amxvJ_usl6oVH529ddFHYq7Q,9022
|
|
11
|
+
hyperliquid_python_sdk_async-0.24.6.dist-info/LICENSE.md,sha256=6lWTEWwNp94-WEWUHIzn8sBpLuRnH3s-OqmKiHJrkTw,1092
|
|
12
|
+
hyperliquid_python_sdk_async-0.24.6.dist-info/METADATA,sha256=C5XxqffzScoKUyKRTqcxaRwYxnUF-zLgCxTn8GWAvYY,7264
|
|
13
|
+
hyperliquid_python_sdk_async-0.24.6.dist-info/WHEEL,sha256=7Z8_27uaHI_UZAc4Uox4PpBhQ9Y5_modZXWMxtUi4NU,88
|
|
14
|
+
hyperliquid_python_sdk_async-0.24.6.dist-info/entry_points.txt,sha256=2rSUHnXv0f5Qg5I5sFZs954V2TrG2SzLQezTh1U6iq0,67
|
|
15
|
+
hyperliquid_python_sdk_async-0.24.6.dist-info/RECORD,,
|