Skip to content

Commit 6cb8b1f

Browse files
committed
Version 0.1.20
1 parent 5427ef5 commit 6cb8b1f

17 files changed

+161
-199
lines changed

examples/basic_adding.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,6 @@
44
import threading
55
import time
66

7-
import eth_account
8-
import utils
9-
from eth_account.signers.local import LocalAccount
10-
117
from hyperliquid.exchange import Exchange
128
from hyperliquid.info import Info
139
from hyperliquid.utils import constants
@@ -24,6 +20,7 @@
2420
Union,
2521
UserEventsMsg,
2622
)
23+
import example_utils
2724

2825
# How far from the best bid and offer this strategy ideally places orders. Currently set to .3%
2926
# i.e. if the best bid is $1000, this strategy will place a resting bid at $997
@@ -56,12 +53,12 @@ def side_to_uint(side: Side) -> int:
5653

5754

5855
class BasicAdder:
59-
def __init__(self, wallet: LocalAccount, api_url: str):
60-
self.info = Info(api_url)
61-
self.exchange = Exchange(wallet, api_url)
56+
def __init__(self, address: str, info: Info, exchange: Exchange):
57+
self.info = info
58+
self.exchange = exchange
6259
subscription: L2BookSubscription = {"type": "l2Book", "coin": COIN}
6360
self.info.subscribe(subscription, self.on_book_update)
64-
self.info.subscribe({"type": "userEvents", "user": wallet.address}, self.on_user_events)
61+
self.info.subscribe({"type": "userEvents", "user": address}, self.on_user_events)
6562
self.position: Optional[float] = None
6663
self.provide_state: Dict[Side, ProvideState] = {
6764
"A": {"type": "cancelled"},
@@ -175,10 +172,8 @@ def poll(self):
175172
def main():
176173
# Setting this to logging.DEBUG can be helpful for debugging websocket callback issues
177174
logging.basicConfig(level=logging.ERROR)
178-
config = utils.get_config()
179-
account = eth_account.Account.from_key(config["secret_key"])
180-
print("Running with account address:", account.address)
181-
BasicAdder(account, constants.TESTNET_API_URL)
175+
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL)
176+
BasicAdder(address, info, exchange)
182177

183178

184179
if __name__ == "__main__":

examples/basic_agent.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,60 @@
11
import eth_account
2-
import utils
32
from eth_account.signers.local import LocalAccount
43

54
from hyperliquid.exchange import Exchange
65
from hyperliquid.utils import constants
6+
import example_utils
77

88

99
def main():
10-
config = utils.get_config()
11-
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
12-
print("Running with account address:", account.address)
13-
exchange = Exchange(account, constants.TESTNET_API_URL)
10+
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)
11+
12+
if exchange.account_address != exchange.wallet.address:
13+
raise Exception("You should not create an agent using an agent")
1414

1515
# Create an agent that can place trades on behalf of the account. The agent does not have permission to transfer
1616
# or withdraw funds.
1717
# You can run this part on a separate machine or change the code to connect the agent via a wallet app instead of
18-
# using your private key directly in python
18+
# using your private key directly in python.
19+
# You can also create a named agent using the frontend, which persists the authorization under an agent name.
1920
approve_result, agent_key = exchange.approve_agent()
2021
if approve_result["status"] != "ok":
2122
print("approving agent failed", approve_result)
2223
return
2324

24-
# Place an order that should rest by setting the price very low
2525
agent_account: LocalAccount = eth_account.Account.from_key(agent_key)
2626
print("Running with agent address:", agent_account.address)
27-
exchange = Exchange(agent_account, constants.TESTNET_API_URL)
28-
order_result = exchange.order("ETH", True, 0.2, 1000, {"limit": {"tif": "Gtc"}})
27+
agent_exchange = Exchange(agent_account, constants.TESTNET_API_URL, account_address=address)
28+
# Place an order that should rest by setting the price very low
29+
order_result = agent_exchange.order("ETH", True, 0.2, 1000, {"limit": {"tif": "Gtc"}})
2930
print(order_result)
3031

3132
# Cancel the order
3233
if order_result["status"] == "ok":
3334
status = order_result["response"]["data"]["statuses"][0]
3435
if "resting" in status:
35-
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
36+
cancel_result = agent_exchange.cancel("ETH", status["resting"]["oid"])
3637
print(cancel_result)
3738

3839
# Create an extra named agent
39-
exchange = Exchange(account, constants.TESTNET_API_URL)
4040
approve_result, extra_agent_key = exchange.approve_agent("persist")
4141
if approve_result["status"] != "ok":
4242
print("approving extra agent failed", approve_result)
4343
return
4444

4545
extra_agent_account: LocalAccount = eth_account.Account.from_key(extra_agent_key)
46+
extra_agent_exchange = Exchange(extra_agent_account, constants.TESTNET_API_URL, account_address=address)
4647
print("Running with extra agent address:", extra_agent_account.address)
4748

4849
print("Placing order with original agent")
49-
order_result = exchange.order("ETH", True, 0.2, 1000, {"limit": {"tif": "Gtc"}})
50+
order_result = extra_agent_exchange.order("ETH", True, 0.2, 1000, {"limit": {"tif": "Gtc"}})
5051
print(order_result)
5152

5253
if order_result["status"] == "ok":
5354
status = order_result["response"]["data"]["statuses"][0]
5455
if "resting" in status:
5556
print("Canceling order with extra agent")
56-
exchange = Exchange(extra_agent_account, constants.TESTNET_API_URL)
57-
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
57+
cancel_result = extra_agent_exchange.cancel("ETH", status["resting"]["oid"])
5858
print(cancel_result)
5959

6060

examples/basic_leverage_adjustment.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,17 @@
11
import json
22

3-
import eth_account
4-
import utils
5-
from eth_account.signers.local import LocalAccount
6-
7-
from hyperliquid.exchange import Exchange
8-
from hyperliquid.info import Info
93
from hyperliquid.utils import constants
4+
import example_utils
105

116

127
def main():
13-
config = utils.get_config()
14-
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
15-
print("Running with account address:", account.address)
16-
info = Info(constants.TESTNET_API_URL, skip_ws=True)
17-
exchange = Exchange(account, constants.TESTNET_API_URL)
8+
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)
189

1910
# Get the user state and print out leverage information for ETH
20-
user_state = info.user_state(account.address)
21-
print("Current leverage for ETH:")
22-
print(json.dumps(user_state["assetPositions"][exchange.coin_to_asset["ETH"]]["position"]["leverage"], indent=2))
11+
user_state = info.user_state(address)
12+
for asset_position in user_state["assetPositions"]:
13+
if asset_position["position"]["coin"] == "ETH":
14+
print("Current leverage for ETH:", json.dumps(asset_position["position"]["leverage"], indent=2))
2315

2416
# Set the ETH leverage to 21x (cross margin)
2517
print(exchange.update_leverage(21, "ETH"))
@@ -31,9 +23,10 @@ def main():
3123
print(exchange.update_isolated_margin(1, "ETH"))
3224

3325
# Get the user state and print out the final leverage information after our changes
34-
user_state = info.user_state(account.address)
35-
print("Current leverage for ETH:")
36-
print(json.dumps(user_state["assetPositions"][exchange.coin_to_asset["ETH"]]["position"]["leverage"], indent=2))
26+
user_state = info.user_state(address)
27+
for asset_position in user_state["assetPositions"]:
28+
if asset_position["position"]["coin"] == "ETH":
29+
print("Current leverage for ETH:", json.dumps(asset_position["position"]["leverage"], indent=2))
3730

3831

3932
if __name__ == "__main__":

examples/basic_market_order.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,19 @@
11
import time
22

3-
import eth_account
4-
import utils
5-
from eth_account.signers.local import LocalAccount
6-
7-
from hyperliquid.exchange import Exchange
83
from hyperliquid.utils import constants
4+
import example_utils
95

106

117
def main():
12-
13-
config = utils.get_config()
14-
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
15-
print("Running with account address:", account.address)
16-
17-
exchange = Exchange(account, constants.TESTNET_API_URL)
8+
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)
189

1910
coin = "ETH"
20-
is_buy = True
11+
is_buy = False
2112
sz = 0.05
2213

2314
print(f"We try to Market {'Buy' if is_buy else 'Sell'} {sz} {coin}.")
2415

25-
order_result = exchange.market_open("ETH", is_buy, sz, 2040, 0.01)
16+
order_result = exchange.market_open("ETH", is_buy, sz, None, 0.01)
2617
if order_result["status"] == "ok":
2718
for status in order_result["response"]["data"]["statuses"]:
2819
try:

examples/basic_order.py

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,17 @@
11
import json
22

3-
import eth_account
4-
import utils
5-
from eth_account.signers.local import LocalAccount
6-
7-
from hyperliquid.exchange import Exchange
8-
from hyperliquid.info import Info
93
from hyperliquid.utils import constants
4+
import example_utils
105

116

127
def main():
13-
config = utils.get_config()
14-
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
15-
print("Running with account address:", account.address)
16-
info = Info(constants.TESTNET_API_URL, skip_ws=True)
8+
address, info, exchange = example_utils.setup(base_url=constants.TESTNET_API_URL, skip_ws=True)
179

1810
# Get the user state and print out position information
19-
user_state = info.user_state(account.address)
11+
user_state = info.user_state(address)
2012
positions = []
2113
for position in user_state["assetPositions"]:
22-
if float(position["position"]["szi"]) != 0:
23-
positions.append(position["position"])
14+
positions.append(position["position"])
2415
if len(positions) > 0:
2516
print("positions:")
2617
for position in positions:
@@ -29,15 +20,14 @@ def main():
2920
print("no open positions")
3021

3122
# Place an order that should rest by setting the price very low
32-
exchange = Exchange(account, constants.TESTNET_API_URL)
3323
order_result = exchange.order("ETH", True, 0.2, 1100, {"limit": {"tif": "Gtc"}})
3424
print(order_result)
3525

3626
# Query the order status by oid
3727
if order_result["status"] == "ok":
3828
status = order_result["response"]["data"]["statuses"][0]
3929
if "resting" in status:
40-
order_status = info.query_order_by_oid(account.address, status["resting"]["oid"])
30+
order_status = info.query_order_by_oid(address, status["resting"]["oid"])
4131
print("Order status by oid:", order_status)
4232

4333
# Cancel the order

examples/basic_order_modify.py

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,11 @@
1-
import json
2-
3-
import eth_account
4-
import utils
5-
from eth_account.signers.local import LocalAccount
6-
7-
from hyperliquid.exchange import Exchange
8-
from hyperliquid.info import Info
91
from hyperliquid.utils import constants
2+
import example_utils
103

114

125
def main():
13-
config = utils.get_config()
14-
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
15-
print("Running with account address:", account.address)
16-
info = Info(constants.TESTNET_API_URL, skip_ws=True)
17-
18-
# Get the user state and print out position information
19-
user_state = info.user_state(account.address)
20-
positions = []
21-
for position in user_state["assetPositions"]:
22-
if float(position["position"]["szi"]) != 0:
23-
positions.append(position["position"])
24-
if len(positions) > 0:
25-
print("positions:")
26-
for position in positions:
27-
print(json.dumps(position, indent=2))
28-
else:
29-
print("no open positions")
6+
address, info, exchange = example_utils.setup(base_url=constants.TESTNET_API_URL, skip_ws=True)
307

318
# Place an order that should rest by setting the price very low
32-
exchange = Exchange(account, constants.TESTNET_API_URL)
339
order_result = exchange.order("ETH", True, 0.2, 1100, {"limit": {"tif": "Gtc"}})
3410
print(order_result)
3511

@@ -38,7 +14,7 @@ def main():
3814
status = order_result["response"]["data"]["statuses"][0]
3915
if "resting" in status:
4016
oid = status["resting"]["oid"]
41-
order_status = info.query_order_by_oid(account.address, oid)
17+
order_status = info.query_order_by_oid(address, oid)
4218
print("Order status by oid:", order_status)
4319

4420
modify_result = exchange.modify_order(oid, "ETH", True, 0.1, 1105, {"limit": {"tif": "Gtc"}})

examples/basic_order_with_cloid.py

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,25 @@
1-
import json
2-
3-
import eth_account
4-
import utils
5-
from eth_account.signers.local import LocalAccount
6-
7-
from hyperliquid.exchange import Exchange
8-
from hyperliquid.info import Info
91
from hyperliquid.utils import constants
102
from hyperliquid.utils.types import Cloid
3+
import example_utils
114

125

136
def main():
14-
config = utils.get_config()
15-
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
16-
print("Running with account address:", account.address)
17-
info = Info(constants.TESTNET_API_URL, skip_ws=True)
18-
19-
# Get the user state and print out position information
20-
user_state = info.user_state(account.address)
21-
positions = []
22-
for position in user_state["assetPositions"]:
23-
if float(position["position"]["szi"]) != 0:
24-
positions.append(position["position"])
25-
if len(positions) > 0:
26-
print("positions:")
27-
for position in positions:
28-
print(json.dumps(position, indent=2))
29-
else:
30-
print("no open positions")
7+
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)
318

329
cloid = Cloid.from_str("0x00000000000000000000000000000001")
3310
# Users can also generate a cloid from an int
3411
# cloid = Cloid.from_int(1)
3512
# Place an order that should rest by setting the price very low
36-
exchange = Exchange(account, constants.TESTNET_API_URL)
3713
order_result = exchange.order("ETH", True, 0.2, 1100, {"limit": {"tif": "Gtc"}}, cloid=cloid)
3814
print(order_result)
3915

4016
# Query the order status by cloid
41-
order_status = info.query_order_by_cloid(account.address, cloid)
17+
order_status = info.query_order_by_cloid(address, cloid)
4218
print("Order status by cloid:", order_status)
4319

4420
# Non-existent cloid example
4521
invalid_cloid = Cloid.from_int(2)
46-
order_status = info.query_order_by_cloid(account.address, invalid_cloid)
22+
order_status = info.query_order_by_cloid(address, invalid_cloid)
4723
print("Order status by cloid:", order_status)
4824

4925
# Cancel the order by cloid

examples/basic_tpsl.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import argparse
2+
3+
from hyperliquid.utils import constants
4+
import example_utils
5+
6+
7+
def main():
8+
parser = argparse.ArgumentParser(description="basic_tpsl")
9+
parser.add_argument("--is_buy", action="store_true")
10+
args = parser.parse_args()
11+
12+
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)
13+
14+
is_buy = args.is_buy
15+
# Place an order that should execute by setting the price very aggressively
16+
order_result = exchange.order("ETH", is_buy, 0.02, 2500 if is_buy else 1500, {"limit": {"tif": "Gtc"}})
17+
print(order_result)
18+
19+
# Place a stop order
20+
stop_order_type = {"trigger": {"triggerPx": 1600 if is_buy else 2400, "isMarket": True, "tpsl": "sl"}}
21+
stop_result = exchange.order("ETH", not is_buy, 0.02, 1500 if is_buy else 2500, stop_order_type, reduce_only=True)
22+
print(stop_result)
23+
24+
# Cancel the order
25+
if stop_result["status"] == "ok":
26+
status = stop_result["response"]["data"]["statuses"][0]
27+
if "resting" in status:
28+
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
29+
print(cancel_result)
30+
31+
# Place a tp order
32+
tp_order_type = {"trigger": {"triggerPx": 1600 if is_buy else 2400, "isMarket": True, "tpsl": "tp"}}
33+
tp_result = exchange.order("ETH", not is_buy, 0.02, 2500 if is_buy else 1500, tp_order_type, reduce_only=True)
34+
print(tp_result)
35+
36+
# Cancel the order
37+
if tp_result["status"] == "ok":
38+
status = tp_result["response"]["data"]["statuses"][0]
39+
if "resting" in status:
40+
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
41+
print(cancel_result)
42+
43+
44+
if __name__ == "__main__":
45+
main()

0 commit comments

Comments
 (0)