Skip to content

Commit

Permalink
Version 0.1.20
Browse files Browse the repository at this point in the history
  • Loading branch information
traderben committed Feb 5, 2024
1 parent 5427ef5 commit 6cb8b1f
Show file tree
Hide file tree
Showing 17 changed files with 161 additions and 199 deletions.
19 changes: 7 additions & 12 deletions examples/basic_adding.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@
import threading
import time

import eth_account
import utils
from eth_account.signers.local import LocalAccount

from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
Expand All @@ -24,6 +20,7 @@
Union,
UserEventsMsg,
)
import example_utils

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


class BasicAdder:
def __init__(self, wallet: LocalAccount, api_url: str):
self.info = Info(api_url)
self.exchange = Exchange(wallet, api_url)
def __init__(self, address: str, info: Info, exchange: Exchange):
self.info = info
self.exchange = exchange
subscription: L2BookSubscription = {"type": "l2Book", "coin": COIN}
self.info.subscribe(subscription, self.on_book_update)
self.info.subscribe({"type": "userEvents", "user": wallet.address}, self.on_user_events)
self.info.subscribe({"type": "userEvents", "user": address}, self.on_user_events)
self.position: Optional[float] = None
self.provide_state: Dict[Side, ProvideState] = {
"A": {"type": "cancelled"},
Expand Down Expand Up @@ -175,10 +172,8 @@ def poll(self):
def main():
# Setting this to logging.DEBUG can be helpful for debugging websocket callback issues
logging.basicConfig(level=logging.ERROR)
config = utils.get_config()
account = eth_account.Account.from_key(config["secret_key"])
print("Running with account address:", account.address)
BasicAdder(account, constants.TESTNET_API_URL)
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL)
BasicAdder(address, info, exchange)


if __name__ == "__main__":
Expand Down
28 changes: 14 additions & 14 deletions examples/basic_agent.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
import eth_account
import utils
from eth_account.signers.local import LocalAccount

from hyperliquid.exchange import Exchange
from hyperliquid.utils import constants
import example_utils


def main():
config = utils.get_config()
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
print("Running with account address:", account.address)
exchange = Exchange(account, constants.TESTNET_API_URL)
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)

if exchange.account_address != exchange.wallet.address:
raise Exception("You should not create an agent using an agent")

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

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

# Cancel the order
if order_result["status"] == "ok":
status = order_result["response"]["data"]["statuses"][0]
if "resting" in status:
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
cancel_result = agent_exchange.cancel("ETH", status["resting"]["oid"])
print(cancel_result)

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

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

print("Placing order with original agent")
order_result = exchange.order("ETH", True, 0.2, 1000, {"limit": {"tif": "Gtc"}})
order_result = extra_agent_exchange.order("ETH", True, 0.2, 1000, {"limit": {"tif": "Gtc"}})
print(order_result)

if order_result["status"] == "ok":
status = order_result["response"]["data"]["statuses"][0]
if "resting" in status:
print("Canceling order with extra agent")
exchange = Exchange(extra_agent_account, constants.TESTNET_API_URL)
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
cancel_result = extra_agent_exchange.cancel("ETH", status["resting"]["oid"])
print(cancel_result)


Expand Down
27 changes: 10 additions & 17 deletions examples/basic_leverage_adjustment.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
import json

import eth_account
import utils
from eth_account.signers.local import LocalAccount

from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
import example_utils


def main():
config = utils.get_config()
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
print("Running with account address:", account.address)
info = Info(constants.TESTNET_API_URL, skip_ws=True)
exchange = Exchange(account, constants.TESTNET_API_URL)
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)

# Get the user state and print out leverage information for ETH
user_state = info.user_state(account.address)
print("Current leverage for ETH:")
print(json.dumps(user_state["assetPositions"][exchange.coin_to_asset["ETH"]]["position"]["leverage"], indent=2))
user_state = info.user_state(address)
for asset_position in user_state["assetPositions"]:
if asset_position["position"]["coin"] == "ETH":
print("Current leverage for ETH:", json.dumps(asset_position["position"]["leverage"], indent=2))

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

# Get the user state and print out the final leverage information after our changes
user_state = info.user_state(account.address)
print("Current leverage for ETH:")
print(json.dumps(user_state["assetPositions"][exchange.coin_to_asset["ETH"]]["position"]["leverage"], indent=2))
user_state = info.user_state(address)
for asset_position in user_state["assetPositions"]:
if asset_position["position"]["coin"] == "ETH":
print("Current leverage for ETH:", json.dumps(asset_position["position"]["leverage"], indent=2))


if __name__ == "__main__":
Expand Down
17 changes: 4 additions & 13 deletions examples/basic_market_order.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,19 @@
import time

import eth_account
import utils
from eth_account.signers.local import LocalAccount

from hyperliquid.exchange import Exchange
from hyperliquid.utils import constants
import example_utils


def main():

config = utils.get_config()
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
print("Running with account address:", account.address)

exchange = Exchange(account, constants.TESTNET_API_URL)
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)

coin = "ETH"
is_buy = True
is_buy = False
sz = 0.05

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

order_result = exchange.market_open("ETH", is_buy, sz, 2040, 0.01)
order_result = exchange.market_open("ETH", is_buy, sz, None, 0.01)
if order_result["status"] == "ok":
for status in order_result["response"]["data"]["statuses"]:
try:
Expand Down
20 changes: 5 additions & 15 deletions examples/basic_order.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,17 @@
import json

import eth_account
import utils
from eth_account.signers.local import LocalAccount

from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
import example_utils


def main():
config = utils.get_config()
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
print("Running with account address:", account.address)
info = Info(constants.TESTNET_API_URL, skip_ws=True)
address, info, exchange = example_utils.setup(base_url=constants.TESTNET_API_URL, skip_ws=True)

# Get the user state and print out position information
user_state = info.user_state(account.address)
user_state = info.user_state(address)
positions = []
for position in user_state["assetPositions"]:
if float(position["position"]["szi"]) != 0:
positions.append(position["position"])
positions.append(position["position"])
if len(positions) > 0:
print("positions:")
for position in positions:
Expand All @@ -29,15 +20,14 @@ def main():
print("no open positions")

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

# Query the order status by oid
if order_result["status"] == "ok":
status = order_result["response"]["data"]["statuses"][0]
if "resting" in status:
order_status = info.query_order_by_oid(account.address, status["resting"]["oid"])
order_status = info.query_order_by_oid(address, status["resting"]["oid"])
print("Order status by oid:", order_status)

# Cancel the order
Expand Down
30 changes: 3 additions & 27 deletions examples/basic_order_modify.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,11 @@
import json

import eth_account
import utils
from eth_account.signers.local import LocalAccount

from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
import example_utils


def main():
config = utils.get_config()
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
print("Running with account address:", account.address)
info = Info(constants.TESTNET_API_URL, skip_ws=True)

# Get the user state and print out position information
user_state = info.user_state(account.address)
positions = []
for position in user_state["assetPositions"]:
if float(position["position"]["szi"]) != 0:
positions.append(position["position"])
if len(positions) > 0:
print("positions:")
for position in positions:
print(json.dumps(position, indent=2))
else:
print("no open positions")
address, info, exchange = example_utils.setup(base_url=constants.TESTNET_API_URL, skip_ws=True)

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

Expand All @@ -38,7 +14,7 @@ def main():
status = order_result["response"]["data"]["statuses"][0]
if "resting" in status:
oid = status["resting"]["oid"]
order_status = info.query_order_by_oid(account.address, oid)
order_status = info.query_order_by_oid(address, oid)
print("Order status by oid:", order_status)

modify_result = exchange.modify_order(oid, "ETH", True, 0.1, 1105, {"limit": {"tif": "Gtc"}})
Expand Down
32 changes: 4 additions & 28 deletions examples/basic_order_with_cloid.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,25 @@
import json

import eth_account
import utils
from eth_account.signers.local import LocalAccount

from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
from hyperliquid.utils.types import Cloid
import example_utils


def main():
config = utils.get_config()
account: LocalAccount = eth_account.Account.from_key(config["secret_key"])
print("Running with account address:", account.address)
info = Info(constants.TESTNET_API_URL, skip_ws=True)

# Get the user state and print out position information
user_state = info.user_state(account.address)
positions = []
for position in user_state["assetPositions"]:
if float(position["position"]["szi"]) != 0:
positions.append(position["position"])
if len(positions) > 0:
print("positions:")
for position in positions:
print(json.dumps(position, indent=2))
else:
print("no open positions")
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)

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

# Query the order status by cloid
order_status = info.query_order_by_cloid(account.address, cloid)
order_status = info.query_order_by_cloid(address, cloid)
print("Order status by cloid:", order_status)

# Non-existent cloid example
invalid_cloid = Cloid.from_int(2)
order_status = info.query_order_by_cloid(account.address, invalid_cloid)
order_status = info.query_order_by_cloid(address, invalid_cloid)
print("Order status by cloid:", order_status)

# Cancel the order by cloid
Expand Down
45 changes: 45 additions & 0 deletions examples/basic_tpsl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import argparse

from hyperliquid.utils import constants
import example_utils


def main():
parser = argparse.ArgumentParser(description="basic_tpsl")
parser.add_argument("--is_buy", action="store_true")
args = parser.parse_args()

address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)

is_buy = args.is_buy
# Place an order that should execute by setting the price very aggressively
order_result = exchange.order("ETH", is_buy, 0.02, 2500 if is_buy else 1500, {"limit": {"tif": "Gtc"}})
print(order_result)

# Place a stop order
stop_order_type = {"trigger": {"triggerPx": 1600 if is_buy else 2400, "isMarket": True, "tpsl": "sl"}}
stop_result = exchange.order("ETH", not is_buy, 0.02, 1500 if is_buy else 2500, stop_order_type, reduce_only=True)
print(stop_result)

# Cancel the order
if stop_result["status"] == "ok":
status = stop_result["response"]["data"]["statuses"][0]
if "resting" in status:
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
print(cancel_result)

# Place a tp order
tp_order_type = {"trigger": {"triggerPx": 1600 if is_buy else 2400, "isMarket": True, "tpsl": "tp"}}
tp_result = exchange.order("ETH", not is_buy, 0.02, 2500 if is_buy else 1500, tp_order_type, reduce_only=True)
print(tp_result)

# Cancel the order
if tp_result["status"] == "ok":
status = tp_result["response"]["data"]["statuses"][0]
if "resting" in status:
cancel_result = exchange.cancel("ETH", status["resting"]["oid"])
print(cancel_result)


if __name__ == "__main__":
main()
Loading

0 comments on commit 6cb8b1f

Please sign in to comment.