trading_agent_v2 / hype_accounts.py
samsonleegh's picture
Update hype_accounts.py
25afdc8 verified
# uv pip install hyperliquid-python-sdk pandas numpy python-dotenv
import os
import json
import eth_account
import numpy as np
import pandas as pd
from eth_account.signers.local import LocalAccount
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
from datetime import datetime, timezone
# https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/examples/example_utils.py
def setup(base_url=constants.MAINNET_API_URL, skip_ws=False, perp_dexs=None):
account: LocalAccount = eth_account.Account.from_key(os.getenv("HYPERLIQUID_PRIVATE_KEY"))
address = os.getenv("HYPERLIQUID_ACCOUNT_ADDRESS") # config["account_address"]
if address == "":
address = account.address
print("Running with account address:", address)
if address != account.address:
print("Running with agent address:", account.address)
info = Info(base_url, skip_ws, perp_dexs=perp_dexs)
user_state = info.user_state(address)
spot_user_state = info.spot_user_state(address)
margin_summary = user_state["marginSummary"]
if float(margin_summary["accountValue"]) == 0 and len(spot_user_state["balances"]) == 0:
print("Not running the example because the provided account has no equity.")
url = info.base_url.split(".", 1)[1]
error_string = f"No accountValue:\nIf you think this is a mistake, make sure that {address} has a balance on {url}.\nIf address shown is your API wallet address, update the config to specify the address of your account, not the address of the API wallet."
raise Exception(error_string)
exchange = Exchange(account, base_url, account_address=address, perp_dexs=perp_dexs)
return address, info, exchange
def long_short_shares_mkt_price(symbol, value, leverage, is_buy, stop_loss_price, take_profit_price) -> str:
address, info, exchange = setup()
end_time = int(datetime.now(timezone.utc).timestamp() * 1000) # Current time in ms
start_time = int(datetime.now(timezone.utc).timestamp() * 1000) # Current time in ms
close_price = float(info.candles_snapshot(symbol, "1m", start_time, end_time)[0]['c'])
coins_metadata_df = pd.DataFrame(info.meta()['universe'])
rounding_decimals = coins_metadata_df[coins_metadata_df['name']==symbol]['szDecimals'].values[0]
quantity = np.round(float(value)/float(close_price),rounding_decimals)
print(quantity)
mkt_order_result = exchange.market_open(
name=symbol,
is_buy=is_buy,
sz=quantity,
px=None,
slippage=0.01
)
is_cross = True
user_state = info.user_state(address)
for asset_position in user_state["assetPositions"]:
if asset_position["position"]["coin"] == symbol:
print(f"Current leverage for {symbol}:", json.dumps(asset_position["position"]["leverage"], indent=2))
leverage_position = exchange.update_leverage(leverage, symbol, is_cross)
if is_buy and stop_loss_price < close_price:
stop_order_type = {"trigger": {"triggerPx": stop_loss_price, "isMarket": True, "tpsl": "sl"}}
stop_loss_result = exchange.order(symbol, not is_buy, quantity, stop_loss_price, stop_order_type, reduce_only=True)
if is_buy and take_profit_price > close_price:
take_profit_order_type = {"trigger": {"triggerPx": take_profit_price, "isMarket": True, "tpsl": "tp"}}
take_profit_result = exchange.order(symbol, not is_buy, quantity, take_profit_price, take_profit_order_type, reduce_only=True)
if not is_buy and stop_loss_price > close_price:
stop_order_type = {"trigger": {"triggerPx": stop_loss_price, "isMarket": True, "tpsl": "sl"}}
stop_loss_result = exchange.order(symbol, not is_buy, quantity, stop_loss_price, stop_order_type, reduce_only=True)
if not is_buy and take_profit_price < close_price:
take_profit_order_type = {"trigger": {"triggerPx": take_profit_price, "isMarket": True, "tpsl": "tp"}}
take_profit_result = exchange.order(symbol, not is_buy, quantity, take_profit_price, take_profit_order_type, reduce_only=True)
return {'mkt_order_result': mkt_order_result, 'leverage_position': leverage_position}