quantpylib.wrappers.hyperliquid
quantpylib.wrappers.hyperliquid module is our official Hyperliquid wrapper SDK implementing the endpoints for perpetuals and spot trading. The library supports a fully asynchronous endpoint for efficiency and lightweight
concurrency. The websocket manager handles reconnections and resubscriptions under network errors and upgrades.
We will demonstrate usage of the library. On top of the endpoints exposed by the exchange, we have added a variety of utility functions.
Examples
We would demonstrate some endpoints. Refer to full documentation for details. For demonstrations, let us first make some imports we would like to use
import os
import time
import asyncio
from pprint import pprint
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
from quantpylib.standards import Period
from quantpylib.wrappers.hyperliquid import Hyperliquid
async def print_handler(msg): print(msg)
async def main():
hyp = Hyperliquid(
key=os.getenv("HYP_DEMO"), #should be your vault address, if trading for a vault
secret=os.getenv("HYP_KEY"), #secret key
)
await hyp.init_client()
#...examples go here
if __name__ == "__main__":
import asyncio
asyncio.run(main())
HIP3 / Multi-DEX Support
Hyperliquid supports deploying perpetual markets on third-party DEXs (HIP3). To interact with these markets, pass the DEX names at initialization:
hyp = Hyperliquid(
key=os.getenv("HYP_DEMO"),
secret=os.getenv("HYP_KEY"),
perp_dexs=["xyz", "km"],
)
get_all_mids, get_all_marks, positions_get, orders_get, contract_specifications, get_funding_info automatically aggregate across the main DEX and the specified HIP3 DEXs.
If you only want HIP3 DEX data (excluding the main perp DEX), use hip3_only=True.
For the raw info endpoints, the dex parameter is available directly:
await hyp.perpetuals_metadata(dex="xyz")
await hyp.perpetuals_contexts(dex="xyz")
await hyp.perpetuals_account(dex="xyz")
await hyp.all_mids(dex="xyz")
HIP3 tickers are prefixed with their DEX name (e.g. "xyz:SP500"). You can use them directly in order and data endpoints:
await hyp.limit_order(ticker="xyz:SP500", amount=0.01, price=1000, round_size=True)
await hyp.market_order(ticker="xyz:SP500", amount=0.01, round_size=True)
Navigating Assets
Note that perpetuals and their asset identifiers are the same. That is, SOL has the identifier SOL - this is not
true of spot pairs. In most of the endpoints, the canonical name is not recognised, and their recognised identifier
shall be given the moniker accredited_name. We may convert between the two:
Most of our endpoints that may benefit from this conversion automatically allows this with the flag is_canonical
and as_canonical to interact and parse hpl server requests and responses respectively.
Precision helpers are also available:
Account
We may get account balances, subscribe to fill events, get rate limits easily
bal = await hyp.account_balance()
await hyp.account_fill_subscribe(handler=print_handler)
limits = await hyp.account_rate_limits()
{'@1': {'price_precision': 6, 'quote_precision': 8, 'quantity_precision': 2, 'min_notional': 10.0}, '@2': {'price_precision': 8, 'quote_precision': 8, 'quantity_precision': 0, 'min_notional': 10.0}, ... }
accredited_name as identifiers, but we can request:
and get instead:
{'HFUN/USDC': {'price_precision': 6, 'quote_precision': 8, 'quantity_precision': 2, 'min_notional': 10.0}, 'LICK/USDC': {'price_precision': 8, 'quote_precision': 8, 'quantity_precision': 0, 'min_notional': 10.0}, ... }
Positions
We can get account perp-positions or spot-positions/balances:
which gives something like:{'USDC': {'ticker': 'USDC', 'amount': Decimal('12412.04185909'), 'entry': 1, 'value': Decimal('12412.04185909'), 'unrealized_pnl': 0}, 'PURR': {'ticker': 'PURR', 'amount': Decimal('12345.24577'), 'entry': Decimal('0.123456'), 'value': Decimal('7890.1234'), 'unrealized_pnl': Decimal('347.25542313685')}, ... }
This gives us a snapshot of our positions from a HTTP-request, but we can also keep a local copy of the position state using:
theon_update is optional, and the alive, local copy of positions can be retrieved here:
This is handled internally by the websocket subscriptions made available. All get-mirror-peek trio's work similarly. get is the HTTP request-response,
mirror is the mirror-copy maintained using socket subscriptions and peek requires a mirror request and just echoes the internal copy.
Orders
Of course you can make orders:
ord = await hyp.limit_order(ticker="SOL",amount=-1,price=1000)
ord = await hyp.limit_order(ticker="@1",amount=10,price=5)
ord = await hyp.limit_order(ticker="HFUN/USDC",is_canonical=True,amount=10,price=5)
Order states can be get-mirror-peek-ed:
print(await hyp.orders_get(as_canonical=False))
await hyp.orders_mirror(as_canonical=False, on_update=print_handler)
await asyncio.sleep(10)
hyp.orders_peek()
or simply subscribed to for custom handling:
Of course you can cancel the orders (by ticker and id, all for some ticker, or all tickers):
await hyp.cancel_open_orders(ticker="SOL",is_canonical=False)
await hyp.cancel_order("JEFF/USDC", oid=1234, is_canonical=True)
Exchange Endpoints
The exchange SDK exposes the full set of /exchange action endpoints. These are the lower-level building blocks for the gateway endpoints above,
but is made available in case you want to use them directly.
Single and batch order operations with submit=False for deferred batching:
res = await hyp.order_create(ticker="HYPE", amount=0.3, price=10, round_size=True)
oid = res['response']['data']['statuses'][0]['resting']['oid']
await hyp.order_modify(ticker="HYPE", amount=0.3, price=10.1, oid=oid, round_size=True)
action = await hyp.order_create(ticker="HYPE", amount=0.3, price=10, submit=False, round_size=True)
await hyp.orders_create(order_actions=[action])
cancel_action = await hyp.order_cancel(ticker="HYPE", oid=oid, submit=False)
await hyp.orders_cancel(order_actions=[cancel_action])
Schedule a cancel-all:
Leverage and margin:
await hyp.update_leverage(ticker="HYPE", leverage=5)
await hyp.update_leverage(ticker="HYPE", leverage=5, is_cross=False) # isolated
await hyp.update_iso_margin(ticker="HYPE", amount=1)
TWAP orders:
await hyp.twap_order_create(ticker="HYPE", amount=5, minutes=5, round_size=True)
await hyp.twap_order_cancel(ticker="HYPE", twap_id=0)
Transfers and staking:
await hyp.transfers_core_l1(amount=1, dest="0x...")
await hyp.withdrawal_request(amount=5, dest="0x...")
await hyp.spot_perp_transfer(amount=5, spot_to_perp=True)
await hyp.vault_transfer(vault="0x...", is_deposit=True, amount=10)
await hyp.subaccount_transfer(subaccount="0x...", is_deposit=True, amount=1)
await hyp.deposit_staking(amount=5)
await hyp.withdraw_staking(amount=1)
await hyp.claim_rewards()
Agent and builder:
Other actions:
await hyp.reserve_request_weight(weight=10)
await hyp.set_referrer(code="hangukquant")
await hyp.set_user_abstraction(abstraction="portfolioMargin")
await hyp.set_user_abstraction_agent(abstraction="portfolioMargin")
await hyp.validator_vote_on_risk_free(risk_free_rate="0.04")
Data
You can of course retrieve data. You can get all mids as snapshot or as subscription:
The subscriptions give response like this:{'@1': '22.253', '@10': '0.00043966', '@11': '0.00054', '@12': '0.00060734', '@13': '0.012098', '@14': '0.00057891', '@15': '0. ...
'ARK': '0.361', 'ATOM': '5.7538', 'AVAX': '25.343', 'BADGER': '3.1786', 'BANANA': '48.7905', 'BCH': '419.195', 'BIGTIME': '0.094512', 'BLAST': '0.013506', 'BLUR': '0.17726', 'BLZ': '0.164115', 'BNB': '569.025', ... }
{'HFUN/USDC': '22.236', 'GMEOW/USDC': '0.00043966', 'PEPE/USDC': '0.00054', 'XULIAN/USDC': '0.00060734', ... }
You can unsubscribe (you can do this for all websocket subscriptions):
The l2-book also has a get-mirror-peek functionality, as well as the subscribe functionality. You probably get the hang of it:
await hyp.l2_book_get(ticker="BTC")
await hyp.l2_book_mirror(ticker="BTC",on_update=print_handler)
hyp.l2_book_peek()
await hyp.l2_book_subscribe("SOL",handler=print_handler)
l2_book_mirror has powerful add-ons:
ob = await hyp.l2_book_mirror("SOL",depth=20,buffer_size=1000,as_dict=False)
await asyncio.sleep(15)
print(ob.buffer_len()) #26
as_dict=False, we get a instance of the quantpylib.hft.lob.LOB object. This object is 'live', in that
it is collecting a buffer of orderbook states in the background. There are utility functions we can call on LOB object instances, such as
get_spread, get_vol, get_vamp that are useful for market modelling.
We have other endpoints, of course:
candles = await hyp.candle_historical( #candles for `BTC` on `15m` intervals for the past hour
"BTC",
interval="15m",
start=int(time.time()) * 1000 - 60 * 60 * 1000,
end=int(time.time()) * 1000
)
df = await hyp.get_trade_bars( #OHLCV DF
ticker="BTC",
start=datetime(2022,12,14),
end=datetime.now(),
granularity=Period.DAILY,
granularity_multiplier=1
)
print(df)
Info Endpoints
The info endpoints expose the raw /info API. HIP3 endpoints accepts an optional dex parameter.
'''info: all'''
await hyp.all_mids()
await hyp.orders_open()
await hyp.orders_open_frontend()
await hyp.order_fills()
await hyp.order_fills_by_time(start=int(time.time() * 1000) - 1000 * 60 * 60 * 24 * 30)
await hyp.account_rate_limits()
await hyp.order_status(id=1)
await hyp.l2_snapshot("HYPE")
await hyp.candle_historical("HYPE", interval="15m", start=..., end=...)
await hyp.max_builder_fee(builder="0x...")
await hyp.historical_orders()
await hyp.twap_slice_fills()
await hyp.subaccounts()
await hyp.vault_details(vault_address="0x...")
await hyp.user_vault_equities()
await hyp.user_role()
await hyp.portfolio()
await hyp.referral()
await hyp.user_fees()
await hyp.delegations()
await hyp.delegator_summary()
await hyp.delegator_history()
await hyp.delegator_rewards()
await hyp.user_dex_abstraction()
await hyp.user_abstraction()
await hyp.aligned_quote_token_info(token=0)
await hyp.borrow_lend_user_state()
await hyp.borrow_lend_reserve_state(token=0)
await hyp.all_borrow_lend_reserve_states()
await hyp.approved_builders()
'''info: perpetuals'''
await hyp.perpetuals_dexs()
await hyp.perpetuals_metadata()
await hyp.perpetuals_contexts()
await hyp.perpetuals_account()
await hyp.perpetuals_user_funding(start=...)
await hyp.perpetuals_non_funding_ledger(start=...)
await hyp.perpetuals_funding_historical(ticker="HYPE")
await hyp.perpetuals_predicted_fundings()
await hyp.perpetuals_at_open_interest_cap()
await hyp.perpetuals_deploy_auction_status()
await hyp.perpetuals_active_asset_data(ticker="HYPE")
await hyp.perpetuals_dex_limits(dex="xyz")
await hyp.perpetuals_dex_status(dex="xyz")
await hyp.perpetuals_metadata_all()
await hyp.perpetuals_annotation(ticker="HYPE")
await hyp.perpetuals_categories()
await hyp.perpetuals_concise_annotations()
'''info: spot'''
await hyp.spot_metadata()
await hyp.spot_contexts()
await hyp.spot_balances()
await hyp.spot_deploy_state()
await hyp.spot_pair_deploy_auction_status()
await hyp.token_details(token_id="0xc1fb593aeffbeb02f85e0308e9956a90")
Websockets
The websocket manager supports 22 subscription channels. You can use the gateway-level
subscribe/unsubscribe methods on the Hyperliquid instance, or access the aws_manager member object
directly for the full channel set.
Gateway-level websocket methods (with optional schema standardization):
await hyp.all_mids_subscribe(handler=print_handler, dex="xyz")
await hyp.all_mids_unsubscribe(dex="xyz")
await hyp.l2_book_subscribe("BTC", handler=print_handler, nSigFigs=5, mantissa=2)
await hyp.l2_book_unsubscribe("BTC", nSigFigs=5, mantissa=2)
await hyp.trades_subscribe("HYPE", handler=print_handler)
await hyp.trades_unsubscribe("HYPE")
await hyp.order_updates_subscribe(handler=print_handler)
await hyp.order_updates_unsubscribe()
await hyp.account_fill_subscribe(handler=print_handler, aggregateByTime=True)
await hyp.account_fill_unsubscribe(aggregateByTime=True)
For the full set of channels, use aws_manager directly:
aws = hyp.aws_manager
await aws.all_mids_subscribe(handler=print_handler, dex="xyz")
await aws.notification_subscribe(handler=print_handler)
await aws.webdata_subscribe(handler=print_handler)
await aws.twap_states_subscribe(handler=print_handler, dex="xyz")
await aws.clearinghouse_state_subscribe(handler=print_handler, dex="xyz")
await aws.open_orders_subscribe(handler=print_handler, dex="xyz")
await aws.candle_subscribe(coin="HYPE", interval="1m", handler=print_handler)
await aws.l2_book_subscribe(ticker="HYPE", handler=print_handler, nSigFigs=5, mantissa=2)
await aws.trades_subscribe(ticker="HYPE", handler=print_handler)
await aws.order_updates_subscribe(handler=print_handler)
await aws.user_events_subscribe(handler=print_handler)
await aws.account_fill_subscribe(handler=print_handler, aggregateByTime=True)
await aws.user_fundings_subscribe(handler=print_handler)
await aws.user_ledger_updates_subscribe(handler=print_handler)
await aws.active_asset_ctx_subscribe(coin="HYPE", handler=print_handler)
await aws.active_asset_data_subscribe(coin="HYPE", handler=print_handler)
await aws.user_twap_slice_fills_subscribe(handler=print_handler)
await aws.user_twap_history_subscribe(handler=print_handler)
await aws.bbo_subscribe(coin="HYPE", handler=print_handler)
await aws.spot_state_subscribe(handler=print_handler, isPortfolioMargin=True)
await aws.all_dexs_clearinghouse_state_subscribe(handler=print_handler)
await aws.all_dexs_asset_ctxs_subscribe(handler=print_handler)
A host of other endpoints such as user-funding, transactions, funding rates, transfers, account leverage updates and so on are supported...refer to docs.
More Examples
examples/example_hyperliquid.py:
import os
import time
import asyncio
import logging
from pprint import pprint
from functools import partial
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
from quantpylib.standards import Period
from quantpylib.wrappers.hyperliquid import Hyperliquid
async def print_handler(msg):
print(msg)
def get_resting_oid_from_resp(resp):
try:
return resp['response']['data']['statuses'][0]['resting']['oid']
except Exception as e:
logging.exception("Error extracting resting oid from response: %s", e)
dexs = ["xyz", "km"]
hyp = Hyperliquid(
key=os.getenv("HPL_KEY"),
secret=os.getenv("HPL_SECRET"),
perp_dexs=dexs
)
protocol_vault = "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303"
async def exchange_sdk_examnples():
ticker = "HYPE"
amount = 0.3
resting_price = 10
'''market order'''
# pprint(await hyp.order_market(
# ticker=ticker, amount=amount, round_size=True
# ))
'''single order_create + modify'''
# res = await hyp.order_create(
# ticker=ticker, amount=amount, price=resting_price, round_size=True
# )
# pprint(res)
# oid = get_resting_oid_from_resp(res)
# pprint(await hyp.order_modify(
# ticker=ticker, amount=amount, price=resting_price + 0.1,
# oid=oid, round_size=True
# ))
'''batch: create 4 resting orders via orders_create'''
# cloids = [hyp.rand_cloid() for _ in range(4)]
# order_actions = []
# for i in range(4):
# action = await hyp.order_create(
# ticker=ticker, amount=amount, price=resting_price,
# cloid=cloids[i], round_size=True, submit=False
# )
# order_actions.append(action)
# pprint(await hyp.orders_create(order_actions=order_actions))
'''retrieve open orders'''
# open_orders = await hyp.orders_get()
# pprint(open_orders)
# oids = list(open_orders.keys())
'''order_cancel: cancel 1st order by oid'''
# pprint(await hyp.order_cancel(ticker=ticker, oid=oids[0]))
'''orders_cancel: cancel 2nd order (batch cancel)'''
# cancel_action = await hyp.order_cancel(ticker=ticker, oid=oids[1], submit=False)
# pprint(await hyp.orders_cancel(order_actions=[cancel_action]))
'''order_cancel_cloid: cancel 3rd order by cloid (use cloid from open_orders)'''
# remaining = await hyp.orders_get()
# remaining_cloids = [v["cloid"] for v in remaining.values()]
# pprint(await hyp.order_cancel_cloid(ticker=ticker, cloid=remaining_cloids[0]))
'''orders_cancel_cloid: cancel 4th order (batch cancel by cloid)'''
# remaining = await hyp.orders_get()
# remaining_cloids = [v["cloid"] for v in remaining.values()]
# cancel_cloid_action = await hyp.order_cancel_cloid(ticker=ticker, cloid=remaining_cloids[0], submit=False)
# pprint(await hyp.orders_cancel_cloid(order_actions=[cancel_cloid_action]))
'''schedule cancel: create 2 orders then schedule cancel-all 5s later'''
# for _ in range(2):
# await hyp.order_create(
# ticker=ticker, amount=amount, price=resting_price, round_size=True
# )
# cancel_time = int(time.time() * 1000) + 7000
# pprint(await hyp.orders_schedule_cancel(time=cancel_time))
# print("Scheduled cancel-all at", cancel_time, "— waiting 6s...")
# await asyncio.sleep(10)
# open_orders = await hyp.orders_get()
# print(f"Open orders after schedule cancel: {len(open_orders)}")
# pprint(open_orders)
'''modify see above'''
'''update_leverage'''
# pprint(await hyp.update_leverage(ticker=ticker, leverage=5))
# pprint(await hyp.update_leverage(ticker=ticker, leverage=10))
'''update_iso_margin: switch to isolated, add margin, remove margin, switch back to cross'''
# pprint(await hyp.update_leverage(ticker=ticker, leverage=5, is_cross=False))
# pprint(await hyp.update_iso_margin(ticker=ticker, amount=1))
# pprint(await hyp.update_iso_margin(ticker=ticker, amount=-1))
# pprint(await hyp.update_leverage(ticker=ticker, leverage=10, is_cross=True))
dest = ""
'''transfers_core_l1'''
# pprint(await hyp.transfers_core_l1(amount=1, dest=dest))
'''withdrawal_request'''
# pprint(await hyp.withdrawal_request(amount=5, dest=dest))
'''spot_perp_transfer: perp to spot then back'''
# pprint(await hyp.spot_perp_transfer(amount=5, spot_to_perp=False))
# pprint(await hyp.spot_perp_transfer(amount=5, spot_to_perp=True))
'''send asset'''
'''send to evm'''
'''deposit_staking: 5 HYPE'''
# pprint(await hyp.deposit_staking(amount=5))
'''withdraw_staking: unstake 5 HYPE'''
# pprint(await hyp.withdraw_staking(amount=1))
'''vault_transfer: deposit 5 then withdraw 5'''
# pprint(await hyp.vault_transfer(vault=protocol_vault, is_deposit=True, amount=10))
# pprint(await hyp.vault_transfer(vault=protocol_vault, is_deposit=False, amount=10))
'''approve_agent'''
# pprint(await hyp.approve_agent())
'''approve_builder_fee'''
# pprint(await hyp.approve_builder_fee(builder=os.getenv("HPL_KEY"), max_fee_rate="0.1%"))
'''twap_order_create/cancel'''
# pprint(await hyp.twap_order_create(ticker=ticker, amount=5, minutes=5, round_size=True))
# twap_id = 0
# pprint(await hyp.twap_order_cancel(ticker=ticker, twap_id=twap_id))
'''reserve_request_weight'''
# pprint(await hyp.reserve_request_weight(weight=10))
'''create order then invalidate pending nonce'''
# nonce = hyp.get_nonce()
# pprint(await hyp.invalidate_pending_nonces(nonce=nonce))
# pprint(await hyp.order_create(ticker=ticker, amount=amount, price=resting_price, round_size=True, submit=True, nonce=nonce))
'''set_user_abstraction'''
# pprint(await hyp.set_user_abstraction(abstraction="portfolioMargin"))
'''set_user_abstraction_agent'''
# pprint(await hyp.set_user_abstraction_agent(abstraction="portfolioMargin"))
'''validator_vote_on_risk_free'''
# pprint(await hyp.validator_vote_on_risk_free(risk_free_rate="0.04"))
'''claim_rewards'''
# pprint(await hyp.claim_rewards())
'''set_referrer'''
# pprint(await hyp.set_referrer(code="hangukquant"))
'''subaccount_transfer: deposit 1 USDC to subaccount then withdraw'''
# pprint(await hyp.subaccount_transfer(subaccount="", is_deposit=True, amount=1))
# pprint(await hyp.subaccount_transfer(subaccount="", is_deposit=False, amount=1))
async def info_sdk_examples():
ticker = "HYPE"
dex = "xyz"
'''info all'''
pprint(await hyp.all_mids())
pprint(await hyp.all_mids(dex=dex))
pprint(await hyp.orders_open())
pprint(await hyp.orders_open(dex=dex))
pprint(await hyp.orders_open_frontend())
pprint(await hyp.orders_open_frontend(dex=dex))
pprint(await hyp.order_fills())
pprint(await hyp.order_fills_by_time(start=int(time.time() * 1000) - 1000 * 60 * 60 * 24 * 30))
id = 1
pprint(await hyp.account_rate_limits())
pprint(await hyp.order_status(id=id))
pprint(await hyp.l2_snapshot(ticker))
pprint(await hyp.candle_historical(
ticker, interval="15m",
start=int(time.time()) * 1000 - 60 * 60 * 1000,
end=int(time.time()) * 1000
))
pprint(await hyp.max_builder_fee(builder=os.getenv("HPL_KEY")))
pprint(await hyp.historical_orders())
pprint(await hyp.twap_slice_fills())
pprint(await hyp.subaccounts())
pprint(await hyp.vault_details(vault_address=protocol_vault))
pprint(await hyp.user_vault_equities())
pprint(await hyp.user_role())
pprint(await hyp.portfolio())
pprint(await hyp.referral())
pprint(await hyp.user_fees())
pprint(await hyp.delegations())
pprint(await hyp.delegator_summary())
pprint(await hyp.delegator_history())
pprint(await hyp.delegator_rewards())
pprint(await hyp.user_dex_abstraction())
pprint(await hyp.user_abstraction())
pprint(await hyp.aligned_quote_token_info(token=0))
pprint(await hyp.borrow_lend_user_state())
pprint(await hyp.borrow_lend_reserve_state(token=0))
pprint(await hyp.all_borrow_lend_reserve_states())
pprint(await hyp.approved_builders())
'''info perps'''
pprint(await hyp.perpetuals_dexs())
pprint(await hyp.perpetuals_metadata())
pprint(await hyp.perpetuals_metadata(dex=dex))
pprint(await hyp.perpetuals_contexts())
pprint(await hyp.perpetuals_contexts(dex=dex))
pprint(await hyp.perpetuals_account())
pprint(await hyp.perpetuals_account(dex=dex))
pprint(await hyp.perpetuals_user_funding(start=int(time.time() * 1000) - 1000 * 60 * 60 * 24 * 30))
pprint(await hyp.perpetuals_non_funding_ledger(start=int(time.time() * 1000) - 1000 * 60 * 60 * 24 * 30))
pprint(await hyp.perpetuals_funding_historical(ticker=ticker))
pprint(await hyp.perpetuals_predicted_fundings())
pprint(await hyp.perpetuals_at_open_interest_cap())
pprint(await hyp.perpetuals_at_open_interest_cap(dex=dex))
pprint(await hyp.perpetuals_deploy_auction_status())
pprint(await hyp.perpetuals_active_asset_data(ticker=ticker))
pprint(await hyp.perpetuals_dex_limits(dex=dex))
pprint(await hyp.perpetuals_dex_status(dex=dex))
pprint(await hyp.perpetuals_metadata_all())
pprint(await hyp.perpetuals_annotation(ticker=ticker))
pprint(await hyp.perpetuals_categories())
pprint(await hyp.perpetuals_concise_annotations())
'''info spot'''
pprint(await hyp.spot_metadata())
pprint(await hyp.spot_contexts())
pprint(await hyp.spot_balances())
pprint(await hyp.spot_deploy_state())
pprint(await hyp.spot_pair_deploy_auction_status())
pprint(await hyp.token_details(token_id="0xc1fb593aeffbeb02f85e0308e9956a90"))
pprint(await hyp.outcome_metadata()) # testnet only
async def gateway_examples():
'''utilities'''
ticker = "HYPE"
ticker_dex = "xyz:SP500"
spot_ticker = "HFUN/USDC"
spot_name = "@1"
pprint(hyp.get_nonce())
pprint(hyp.get_canonical_name(spot_name))
pprint(hyp.get_accredited_name(spot_ticker))
pprint(hyp.get_price_precision(ticker))
pprint(hyp.get_lot_precision(ticker_dex))
'''account'''
pprint(await hyp.account_balance())
await hyp.account_fill_subscribe(handler=print_handler)
await hyp.account_fill_unsubscribe()
'''exchange'''
# pprint(await hyp.contract_specifications(is_perpetuals=True))
# pprint(await hyp.contract_specifications(is_perpetuals=True,include_dexs=False))
# pprint(await hyp.contract_specifications(is_perpetuals=False,as_canonical=True))
# pprint(await hyp.get_funding_info()) #includes, dexs that were intialized
'''executor'''
# pprint(hyp.rand_cloid())
# pprint(await hyp.get_all_mids()) #includes dexs initialized
# pprint(await hyp.get_all_marks()) #includes dexs initialized
# pprint(await hyp.limit_order(ticker="HYPE",amount=-1,price=500))
# pprint(await hyp.limit_order(ticker="HYPE",amount=-1,price=500,tp=400,sl=600))
# pprint(await hyp.limit_order(ticker="xyz:SP500", amount=0.01, price=1000, round_size=True))
# pprint(await hyp.limit_order(ticker="@1",amount=10,price=1))
# pprint(await hyp.limit_order(ticker="HFUN/USDC",is_canonical=True,amount=10,price=1))
# pprint(await hyp.cancel_open_orders()) #optional: ticker
# pprint(await hyp.cancel_order("HYPE", oid=1234))
# pprint(await hyp.market_order(ticker="xyz:SP500", amount=0.01, round_size=True))
# pprint(await hyp.l2_book_get(ticker=ticker))
# pprint(await hyp.l2_book_get(ticker=ticker, depth=5))
# ob = await hyp.l2_book_mirror(ticker=ticker, as_dict=False)
# for _ in range(4):
# await asyncio.sleep(1)
# print(f"mid: {ob.get_mid()}")
# await hyp.l2_book_subscribe(ticker=ticker, handler=print_handler)
# await asyncio.sleep(4)
# await hyp.l2_book_unsubscribe(ticker=ticker)
# await hyp.trades_subscribe(ticker=ticker, handler=print_handler)
# await asyncio.sleep(4)
# await hyp.trades_unsubscribe(ticker=ticker)
# await hyp.all_mids_subscribe(handler=print_handler)
# await asyncio.sleep(4)
# await hyp.all_mids_unsubscribe()
'''orders'''
# pprint(await hyp.order_query(oid=1234))
# pprint(await hyp.orders_get())
# orders = await hyp.orders_mirror(on_update=print_handler)
# pprint(hyp.orders_peek())
# await hyp.order_updates_subscribe(handler=print_handler)
# await asyncio.sleep(4)
# await hyp.order_updates_unsubscribe()
'''positions'''
# pprint(await hyp.positions_get())
# pprint(await hyp.positions_get(is_perpetuals=False))
# pos = await hyp.positions_mirror(as_dict=False, on_update=print_handler)
# print(pos)
# pos = hyp.positions_peek()
'''datapoller'''
# df = await hyp.get_trade_bars(
# ticker="BTC",
# start=datetime(2025,12,14),
# end=datetime.now(),
# granularity=Period.DAILY,
# granularity_multiplier=1
# )
# print(df)
async def socket_examples():
aws = hyp.aws_manager
ticker = "HYPE"
dex = "xyz"
interval = "1m"
async def stream_for(sub,unsub,duration=10):
await sub
await asyncio.sleep(duration)
await unsub
await stream_for(
aws.all_mids_subscribe(handler=print_handler),
aws.all_mids_unsubscribe()
)
# await stream_for(
# aws.all_mids_subscribe(handler=print_handler,dex=dex),
# aws.all_mids_unsubscribe(dex=dex)
# )
# await stream_for(
# aws.notification_subscribe(handler=print_handler),
# aws.notification_unsubscribe()
# )
# await stream_for(
# aws.webdata_subscribe(handler=print_handler),
# aws.webdata_unsubscribe()
# )
# await stream_for(
# aws.twap_states_subscribe(handler=print_handler,dex=dex),
# aws.twap_states_unsubscribe(dex=dex)
# )
# await stream_for(
# aws.clearinghouse_state_subscribe(handler=print_handler,dex=dex),
# aws.clearinghouse_state_unsubscribe(dex=dex)
# )
# await stream_for(
# aws.open_orders_subscribe(handler=print_handler,dex=dex),
# aws.open_orders_unsubscribe(dex=dex)
# )
# await stream_for(
# aws.candle_subscribe(coin=ticker,interval=interval,handler=print_handler),
# aws.candle_unsubscribe(coin=ticker,interval=interval)
# )
# await stream_for(
# aws.l2_book_subscribe(ticker=ticker,handler=print_handler),
# aws.l2_book_unsubscribe(ticker=ticker)
# )
# await stream_for(
# aws.l2_book_subscribe(ticker=ticker,handler=print_handler,nSigFigs=5,mantissa=2),
# aws.l2_book_unsubscribe(ticker=ticker,nSigFigs=5,mantissa=2)
# )
# await stream_for(
# aws.trades_subscribe(ticker=ticker,handler=print_handler),
# aws.trades_unsubscribe(ticker=ticker)
# )
# await stream_for(
# aws.order_updates_subscribe(handler=print_handler),
# aws.order_updates_unsubscribe()
# )
# await stream_for(
# aws.user_events_subscribe(handler=print_handler),
# aws.user_events_unsubscribe()
# )
# await stream_for(
# aws.account_fill_subscribe(handler=print_handler),
# aws.account_fill_unsubscribe()
# )
# await stream_for(
# aws.account_fill_subscribe(handler=print_handler,aggregateByTime=True),
# aws.account_fill_unsubscribe(aggregateByTime=True)
# )
# await stream_for(
# aws.user_fundings_subscribe(handler=print_handler),
# aws.user_fundings_unsubscribe()
# )
# await stream_for(
# aws.user_ledger_updates_subscribe(handler=print_handler),
# aws.user_ledger_updates_unsubscribe()
# )
# await stream_for(
# aws.active_asset_ctx_subscribe(coin=ticker,handler=print_handler),
# aws.active_asset_ctx_unsubscribe(coin=ticker)
# )
# await stream_for(
# aws.active_asset_data_subscribe(coin=ticker,handler=print_handler),
# aws.active_asset_data_unsubscribe(coin=ticker)
# )
# await stream_for(
# aws.user_twap_slice_fills_subscribe(handler=print_handler),
# aws.user_twap_slice_fills_unsubscribe()
# )
# await stream_for(
# aws.user_twap_history_subscribe(handler=print_handler),
# aws.user_twap_history_unsubscribe()
# )
# await stream_for(
# aws.bbo_subscribe(coin=ticker,handler=print_handler),
# aws.bbo_unsubscribe(coin=ticker)
# )
# await stream_for(
# aws.spot_state_subscribe(handler=print_handler),
# aws.spot_state_unsubscribe()
# )
# await stream_for(
# aws.spot_state_subscribe(handler=print_handler,isPortfolioMargin=True),
# aws.spot_state_unsubscribe(isPortfolioMargin=True)
# )
# await stream_for(
# aws.all_dexs_clearinghouse_state_subscribe(handler=print_handler),
# aws.all_dexs_clearinghouse_state_unsubscribe()
# )
# await stream_for(
# aws.all_dexs_asset_ctxs_subscribe(handler=print_handler),
# aws.all_dexs_asset_ctxs_unsubscribe()
# )
async def main():
await hyp.init_client()
try:
'''uncomment examples to run
NOTE: that some code may trigger exchange actions such as live orders
'''
#await exchange_sdk_examnples()
#await info_sdk_examples()
#await gateway_examples()
await socket_examples()
except Exception as e:
logging.exception("Error in SDK examples: %s", e)
await hyp.cleanup()
if __name__ == "__main__":
import asyncio
asyncio.run(main())
Documentation
AsyncWebsocketManager
account_fill_subscribe(handler, aggregateByTime=None)
async
Subscribe to userFills channel.
account_fill_unsubscribe(aggregateByTime=None)
async
Unsubscribe from userFills channel.
active_asset_ctx_subscribe(coin, handler)
async
Subscribe to activeAssetCtx channel.
active_asset_ctx_unsubscribe(coin)
async
Unsubscribe from activeAssetCtx channel.
active_asset_data_subscribe(coin, handler)
async
Subscribe to activeAssetData channel.
active_asset_data_unsubscribe(coin)
async
Unsubscribe from activeAssetData channel.
all_dexs_asset_ctxs_subscribe(handler)
async
Subscribe to allDexsAssetCtxs channel.
all_dexs_asset_ctxs_unsubscribe()
async
Unsubscribe from allDexsAssetCtxs channel.
all_dexs_clearinghouse_state_subscribe(handler)
async
Subscribe to allDexsClearinghouseState channel.
all_dexs_clearinghouse_state_unsubscribe()
async
Unsubscribe from allDexsClearinghouseState channel.
all_mids_subscribe(handler, dex=None)
async
Subscribe to allMids channel.
all_mids_unsubscribe(dex=None)
async
Unsubscribe from allMids channel.
bbo_subscribe(coin, handler)
async
Subscribe to bbo channel.
bbo_unsubscribe(coin)
async
Unsubscribe from bbo channel.
candle_subscribe(coin, interval, handler)
async
Subscribe to candle channel.
candle_unsubscribe(coin, interval)
async
Unsubscribe from candle channel.
clearinghouse_state_subscribe(handler, dex)
async
Subscribe to clearinghouseState channel.
clearinghouse_state_unsubscribe(dex)
async
Unsubscribe from clearinghouseState channel.
l2_book_subscribe(ticker, handler, nSigFigs=None, mantissa=None)
async
Subscribe to l2Book channel.
l2_book_subscriptions()
Return active l2Book subscriptions.
l2_book_unsubscribe(ticker, nSigFigs=None, mantissa=None)
async
Unsubscribe from l2Book channel.
notification_subscribe(handler)
async
Subscribe to notification channel.
notification_unsubscribe()
async
Unsubscribe from notification channel.
open_orders_subscribe(handler, dex)
async
Subscribe to openOrders channel.
open_orders_unsubscribe(dex)
async
Unsubscribe from openOrders channel.
order_updates_subscribe(handler)
async
Subscribe to orderUpdates channel.
order_updates_unsubscribe()
async
Unsubscribe from orderUpdates channel.
spot_state_subscribe(handler, isPortfolioMargin=None)
async
Subscribe to spotState channel.
spot_state_unsubscribe(isPortfolioMargin=None)
async
Unsubscribe from spotState channel.
trades_subscribe(ticker, handler)
async
Subscribe to trades channel.
trades_unsubscribe(ticker)
async
Unsubscribe from trades channel.
twap_states_subscribe(handler, dex)
async
Subscribe to twapStates channel.
twap_states_unsubscribe(dex)
async
Unsubscribe from twapStates channel.
user_events_subscribe(handler)
async
Subscribe to userEvents channel.
user_events_unsubscribe()
async
Unsubscribe from userEvents channel.
user_fundings_subscribe(handler)
async
Subscribe to userFundings channel.
user_fundings_unsubscribe()
async
Unsubscribe from userFundings channel.
user_ledger_updates_subscribe(handler)
async
Subscribe to userNonFundingLedgerUpdates channel.
user_ledger_updates_unsubscribe()
async
Unsubscribe from userNonFundingLedgerUpdates channel.
user_twap_history_subscribe(handler)
async
Subscribe to userTwapHistory channel.
user_twap_history_unsubscribe()
async
Unsubscribe from userTwapHistory channel.
user_twap_slice_fills_subscribe(handler)
async
Subscribe to userTwapSliceFills channel.
user_twap_slice_fills_unsubscribe()
async
Unsubscribe from userTwapSliceFills channel.
webdata_subscribe(handler)
async
Subscribe to webData3 channel.
webdata_unsubscribe()
async
Unsubscribe from webData3 channel.
Channel
Represents various socket subscription channels.
Attributes:
| Name | Type | Description |
|---|---|---|
ALL_MIDS |
str
|
The "allMids" channel. |
NOTIFICATION |
str
|
The "notification" channel. |
WEBDATA |
str
|
The "webData3" channel. |
TWAP_STATES |
str
|
The "twapStates" channel. |
CLEARINGHOUSE_STATE |
str
|
The "clearinghouseState" channel. |
OPEN_ORDERS |
str
|
The "openOrders" channel. |
CANDLE |
str
|
The "candle" channel. |
L2BOOK |
str
|
The "l2Book" channel. |
TRADES |
str
|
The "trades" channel. |
ORDER_UPDATES |
str
|
The "orderUpdates" channel. |
USER_EVENTS |
str
|
The "userEvents" channel. |
USER_FILLS |
str
|
The "userFills" channel. |
USER_FUNDINGS |
str
|
The "userFundings" channel. |
USER_LEDGER_UPDATES |
str
|
The "userNonFundingLedgerUpdates" channel. |
ACTIVE_ASSET_CTX |
str
|
The "activeAssetCtx" channel. |
ACTIVE_ASSET_DATA |
str
|
The "activeAssetData" channel. |
USER_TWAP_SLICE_FILLS |
str
|
The "userTwapSliceFills" channel. |
USER_TWAP_HISTORY |
str
|
The "userTwapHistory" channel. |
BBO |
str
|
The "bbo" channel. |
SPOT_STATE |
str
|
The "spotState" channel. |
ALL_DEXS_CLEARINGHOUSE_STATE |
str
|
The "allDexsClearinghouseState" channel. |
ALL_DEXS_ASSET_CTXS |
str
|
The "allDexsAssetCtxs" channel. |
Hyperliquid
__init__(key='', secret='', vault_address=None, mode=ExchangeModes.LIVE, builder=None, perp_dexs=None, hip3_only=False, **kwargs)
Initializes the Hyperliquid instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The public or vault address. |
''
|
secret
|
str
|
The secret key. |
''
|
mode
|
ExchangeModes
|
The exchange mode. Defaults to ExchangeModes.LIVE. |
LIVE
|
builder
|
str
|
Builder address for order fee routing. |
None
|
perp_dexs
|
list
|
List of HIP3 perp DEX names to include (e.g. ["xyz", "km"]). |
None
|
hip3_only
|
bool
|
If True, excludes the main perp DEX from aggregated queries. Defaults to False. |
False
|
vault_address
|
str
|
Vault address |
None
|
account_balance(**kwargs)
async
Retrieve balance details of the user, such as equity, margin (total, maintenance) and pnl.
Returns:
| Type | Description |
|---|---|
dict
|
Balance details. |
account_fill_subscribe(handler, aggregateByTime=None, **kwargs)
async
Subscribe to order fill events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
aggregateByTime
|
optional
|
Aggregate fills by time. |
None
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
account_fill_unsubscribe(aggregateByTime=None, **kwargs)
async
Unsubscribe from order fill events.
account_rate_limits()
async
Get the rate limits for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the current rate limits and usage statistics for the user's account. |
aligned_quote_token_info(token)
async
Retrieve aligned quote token information for a given token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
int
|
The token index. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing alignment status, first alignment timestamp, minted supply, daily amounts owed, and predicted rate. |
all_borrow_lend_reserve_states()
async
Retrieve all borrow/lend reserve states.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of all reserve states indexed by token with complete reserve information. |
all_mids(dex='')
async
Retrieve the mid-prices of all assets.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the mid-prices of all assets available on the exchange. |
all_mids_subscribe(handler, standardize_schema=True, as_canonical=False, dex=None, **kwargs)
async
Subscribe to mid prices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
standardize_schema
|
(bool, True)
|
Processes the incoming message to standard schema. |
True
|
as_canonical
|
(bool, False)
|
If True, the mid prices are returned with canonical names. |
False
|
dex
|
str
|
The dex to subscribe to. |
None
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
all_mids_unsubscribe(dex=None, **kwargs)
async
Unsubscribe from mid prices.
approve_agent(name=None)
async
Approve a new agent key for trading on behalf of the account.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A human-readable name for the agent. |
None
|
approve_builder_fee(builder, max_fee_rate)
async
Approve a builder fee rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
builder
|
str
|
The builder address. |
required |
max_fee_rate
|
str
|
Maximum fee rate (e.g. "0.1%"). |
required |
approved_builders()
async
Retrieve approved builder addresses for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of approved builder addresses. |
borrow_lend_reserve_state(token)
async
Retrieve borrow/lend reserve state for a given token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
int
|
The token index. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing reserve parameters including borrowing/supply rates, balance, utilization, LTV, and totals. |
borrow_lend_user_state()
async
Retrieve borrow/lend state for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing token-indexed state showing borrow/supply basis and values, health status, and health factor. |
cancel_open_orders(ticker=None, is_canonical=False, **kwargs)
async
Cancel open orders on the exchange.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The coin symbol. If |
None
|
is_canonical
|
bool
|
If True, the |
False
|
**kwargs
|
Additional keyword arguments for further customization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The result of the cancellation request. Returns None if no open orders are found or no orders are canceled. |
cancel_order(ticker, oid=None, cloid=None, is_canonical=False, **kwargs)
async
Cancel an order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
oid
|
int
|
Order ID to cancel. |
None
|
cloid
|
str
|
Client Order ID to cancel. |
None
|
is_canonical
|
bool
|
If True, the |
False
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
candle_historical(ticker, interval, start, end)
async
Retrieve historical candlestick data for a specified ticker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
interval
|
str
|
The time interval for each candlestick (e.g., '1m', '1h'). |
required |
start
|
int
|
The start time for the data range in UNIX ms timestamp format. |
required |
end
|
int
|
The end time for the data range in UNIX ms timestamp format. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the historical candlestick data for the specified ticker. |
claim_rewards()
async
Claim accumulated staking rewards.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the claim rewards request. |
cleanup()
async
Cleans up open sessions with Hyperliquid server
contract_specifications(is_perpetuals=True, as_canonical=False, include_dexs=True, **kwargs)
async
Retrieve the contract's trading rules from the exchange.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
is_perpetuals
|
bool
|
Specifies whether to fetch perpetual contracts. Defaults to True. |
True
|
as_canonical
|
bool
|
If True, returns the contract specifications using canonical names. Defaults to False. |
False
|
include_dexs
|
bool
|
If True, includes HIP3 DEX contracts. Defaults to True. |
True
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing contract specifications for each asset with key-values: - SYMBOL_PRICE_PRECISION. - SYMBOL_QUANTITY_PRECISION. - SYMBOL_MIN_NOTIONAL - SYMBOL_BASE_ASSET - SYMBOL_QUOTE_ASSET |
delegations()
async
Retrieve staking delegations for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of delegation objects containing validator address, delegated amount, and lock-up timestamp. |
delegator_history()
async
Retrieve historical delegation transactions for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of historical records with timestamps, transaction hashes, and delta changes. |
delegator_rewards()
async
Retrieve delegation rewards for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of reward records detailing time, source type, and total amounts earned. |
delegator_summary()
async
Retrieve delegator summary for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing total delegated amount, undelegated balance, pending withdrawals, and withdrawal count. |
deposit_staking(amount)
async
Deposit native tokens into staking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
float
|
The amount of tokens to stake (converted to wei internally). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the staking deposit request. |
get_accredited_name(canonical)
Retrieves the accredited name for a given canonical name. For perpetuals, this is an identity mapping. For spot, (for instance) JEFF/USDC maps to @4.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
canonical
|
str
|
The canonical name. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
The accredited name associated with the canonical name. |
get_all_marks(**kwargs)
async
Retrieve mark prices for all perpetuals across configured DEXs.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary of ticker to mark price (Decimal). |
get_all_mids(ticker=None, **kwargs)
async
Retrieve the mid-price for a specific ticker or all available tickers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The symbol of the specific contract for which to retrieve the mid-price. If not provided, mid-prices for all contracts will be returned. Defaults to None. |
None
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Decimal |
The mid-price of the specified ticker if |
|
dict |
A dictionary with contract symbols as keys and their corresponding mid-prices (Decimal) as values
if |
get_canonical_name(name, return_unmapped=False)
Retrieves the canonical name for a given ticker. For perpetuals, this is an identity mapping. For spot, (for instance) @4 maps to JEFF/USDC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The ticker name. |
required |
return_unmapped
|
bool
|
If True, returns the name back to the caller if no mapping is found. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
The canonical name associated with the ticker. |
get_funding_info(ticker=None, **kwargs)
async
Retrieve funding rate information across all configured DEXs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
If provided, returns funding info for this ticker only. |
None
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Funding info keyed by ticker, or a single ticker's funding info if |
get_funding_rates(ticker, start, end, **kwargs)
async
Retrieve funding rates data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol for the asset. |
required |
start
|
datetime
|
Start datetime for the data retrieval. |
required |
end
|
datetime
|
End datetime for the data retrieval. |
required |
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing the funding rates data. |
get_lot_precision(ticker, is_canonical=False)
Get the lot precision for a specified asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
is_canonical
|
bool
|
If True, the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
The number of decimal places used for the asset's lot size precision. |
get_nonce()
Get a unique nonce value using a nonce buffer to ensure no overlaps between exchange requests.
Returns:
| Name | Type | Description |
|---|---|---|
int |
A unique nonce value. |
get_price_precision(ticker, is_canonical=False)
Get the price precision for a specified asset. Note that prices quoted are less of price precision and 5 significant figures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
is_canonical
|
bool
|
If True, the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
The number of decimal places used for the asset's price precision. |
get_trade_bars(ticker, start, end, granularity, granularity_multiplier, kline_close=False, **kwargs)
async
Retrieve trade bars data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol for the asset. |
required |
start
|
datetime
|
Start datetime for the data retrieval. |
required |
end
|
datetime
|
End datetime for the data retrieval. |
required |
granularity
|
Period
|
Granularity of the data. |
required |
granularity_multiplier
|
int
|
Multiplier for the granularity. |
required |
kline_close
|
bool
|
Timestamp candle by the candles' start or end timestamp. Defaults to |
False
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing the trade bars data. |
historical_orders()
async
Retrieve historical orders for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of up to 2000 most recent orders with status, timestamp, and order details. |
init_client()
async
Initializes the exchange client with important metadata for mapping tickers to asset ids, contract precision and mapping. Should be called upon object initialization.
invalidate_pending_nonces(nonce, expires_after=None)
async
Invalidate pending nonces by submitting a no-op action, preventing replay of actions signed with the given nonce. Can be used to cancel pending actions that have not yet been processed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nonce
|
int
|
The nonce to invalidate. |
required |
expires_after
|
int
|
Expiration time in milliseconds. |
None
|
l2_book_get(ticker, nsigfig=None, depth=None, depth_cum=True)
async
Retrieve L2 snapshot for a given coin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The coin symbol. |
required |
nsigfig
|
int
|
Number of significant figures requested. Defaults to None. |
None
|
depth
|
int
|
Depth of the order-book representation, if |
None
|
depth_cum
|
bool
|
Flag indicating whether to return cumulative depth or not. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the L2 snapshot information. |
l2_book_mirror(ticker, depth=100, buffer_size=100, as_dict=True, on_update=None, apply_shadow_depth=False, is_canonical=False, **kwargs)
async
Keep a live, internal L2 Order Book representation using a l2-book subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
depth
|
int
|
Depth of the order-book representation, if |
100
|
buffer_size
|
int
|
Size of the order-book buffer, if |
100
|
as_dict
|
(bool, True)
|
If |
True
|
on_update
|
coroutine
|
A coroutine handler when order book state is updated. |
None
|
apply_shadow_depth
|
(bool, False)
|
If True, applies shadow depth to the LOB. |
False
|
is_canonical
|
(bool, False)
|
If the ticker passed in is a canonical name for the spot pairs. |
False
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
l2_book_peek(ticker, as_dict=True, is_canonical=False, **kwargs)
Retrieve the mirrored, local internal L2 Order Book representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
as_dict
|
(bool, True)
|
If |
True
|
is_canonical
|
(bool, False)
|
If the ticker passed in is a canonical name for the spot pairs. |
False
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
l2_book_subscribe(ticker, handler, standardize_schema=True, nSigFigs=None, mantissa=None, **kwargs)
async
Subscribe to L2 Order Book stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
standardize_schema
|
(bool, True)
|
Processes the incoming message to |
True
|
nSigFigs
|
int
|
Number of significant figures for price grouping. |
None
|
mantissa
|
int
|
Mantissa for price grouping. |
None
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
l2_book_subscriptions(**kwargs)
Retrieve the list of open l2 book subscriptions.
l2_book_unsubscribe(ticker, nSigFigs=None, mantissa=None, **kwargs)
async
Unsubscribe from L2 Order Book.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol. |
required |
nSigFigs
|
int
|
Number of significant figures for price grouping. |
None
|
mantissa
|
int
|
Mantissa for price grouping. |
None
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
l2_snapshot(ticker, nsigfig=None, mantissa=None)
async
Get a Level 2 snapshot for a specified ticker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
nsigfig
|
int
|
Number of significant figures for the data. Defaults to None. |
None
|
mantissa
|
int
|
Mantissa for price grouping. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the L2 order book snapshot for the specified ticker. |
limit_order(ticker, amount, price, tif='Gtc', reduce_only=False, cloid=None, tp=None, sl=None, trigger_market=True, round_price=False, round_size=False, is_canonical=False, submit=True, **kwargs)
async
Submit a limit order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The coin symbol. |
required |
amount
|
float or Decimal
|
The signed quantity of contracts to long or short. |
required |
price
|
float
|
The price at which to execute the order. |
required |
tif
|
str
|
The time in force for the order. Defaults to "Gtc". Allowed values are: - "Gtc" (Good 'til canceled) - "Alo" (Add liquidity only) - "Ioc" (Immediate or cancel) |
'Gtc'
|
reduce_only
|
bool
|
Whether the order should only reduce an existing position. Defaults to False. |
False
|
cloid
|
str
|
Client order ID for order tracking. Defaults to None. |
None
|
tp
|
float
|
Take profit price. Defaults to None. |
None
|
sl
|
float
|
Stop loss price. Defaults to None. |
None
|
trigger_market
|
bool
|
Whether the tpsl trigger (if not None) is a market order. Defaults to True. |
True
|
round_price
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
round_size
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
is_canonical
|
bool
|
If True, the |
False
|
**kwargs
|
Additional keyword arguments for order customization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The result of the order placement. |
market_order(ticker, amount, reduce_only=False, cloid=None, is_canonical=False, slippage_tolerance=0.05, round_size=False, **kwargs)
async
Submit a market order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol for the asset. |
required |
amount
|
float or Decimal
|
The signed quantity of contracts to long or short. |
required |
reduce_only
|
bool
|
Whether the order should only reduce an existing position. Defaults to False. |
False
|
slippage_tolerance
|
float
|
The maximum acceptable slippage, expressed as a percentage. Defaults to 0.05 (5%). |
0.05
|
cloid
|
str
|
Client order ID for custom tracking. Defaults to None. |
None
|
is_canonical
|
bool
|
If True, the |
False
|
round_size
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
The result of the order placement. |
max_builder_fee(builder)
async
Retrieve the maximum builder fee for a given builder address.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
builder
|
str
|
The builder address (42-character hex address). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
The maximum approved fee in tenths of basis points. |
order_cancel(ticker, oid, expires_after=None, submit=True)
async
Cancel a specific order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
oid
|
int
|
The order ID of the order to be canceled. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
submit
|
bool
|
If True, the cancel action is submitted. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the order cancellation request if |
order_cancel_cloid(ticker, cloid, expires_after=None, submit=True)
async
Cancel an order using client order ID (Cloid).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
cloid
|
str
|
The client order ID of the order to be canceled. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
submit
|
bool
|
If True, the cancel action is submitted. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the order cancellation request if |
order_create(ticker, amount, price, tif='Gtc', reduce_only=False, cloid=None, tp=None, sl=None, trigger_market=True, grouping='na', round_price=False, round_size=False, submit=True, is_canonical=False, nonce=None)
async
Create a new order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
amount
|
float
|
The quantity of the asset to trade. Positive for buy (long), negative for sell (short). |
required |
price
|
float or Decimal
|
The limit price for the order. |
required |
tif
|
str
|
Time in force for the order. Defaults to "Gtc" (Good 'til canceled). |
'Gtc'
|
reduce_only
|
bool
|
If True, the order can only reduce an existing position. Defaults to False. |
False
|
cloid
|
str
|
Client order ID for tracking. Defaults to None. |
None
|
tp
|
float
|
Take profit price. Defaults to None. |
None
|
sl
|
float
|
Stop loss price. Defaults to None. |
None
|
trigger_market
|
bool
|
Whether the tpsl trigger (if not None) is a market order. Defaults to True. |
True
|
grouping
|
str
|
Order grouping type. Defaults to "na". |
'na'
|
round_price
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
round_size
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
submit
|
bool
|
If True, the order is submitted immediately, otherwise the order schema is returned. Defaults to True. |
True
|
is_canonical
|
bool
|
If True, the ticker is treated as a canonical name. Defaults to False. |
False
|
nonce
|
int
|
A specific nonce to use. Defaults to None (auto-generated). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the order creation or the action object if |
order_fills(aggregate_by_time=False)
async
Get all filled orders.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of dictionaries containing details of all filled orders for the user's account. |
order_fills_by_time(start, end=None, aggregate_by_time=False)
async
Get filled orders within a specific time range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
The start time for the data range in UNIX timestamp format. |
required |
end
|
int
|
The end time for the data range in UNIX timestamp format. |
None
|
aggregate_by_time
|
bool
|
If True, aggregates fills by time. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of dictionaries containing details of all filled orders within the specified time range. |
order_market(ticker, amount, reduce_only=False, slippage_tolerance=0.05, cloid=None, is_canonical=False, round_size=False)
async
Submit a market order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
amount
|
float
|
The quantity of the asset to trade. Positive for buy (long), negative for sell (short). |
required |
reduce_only
|
bool
|
If True, the order can only reduce an existing position. Defaults to False. |
False
|
slippage_tolerance
|
float
|
The acceptable slippage percentage. Defaults to 0.05. |
0.05
|
cloid
|
str
|
Client order ID for tracking. Defaults to None. |
None
|
is_canonical
|
bool
|
If True, the ticker is treated as a canonical name. Defaults to False. |
False
|
round_size
|
bool
|
Whether to round the size to a valid order specification. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the market order submission. |
order_modify(ticker, amount, price, oid=None, cloid=None, tif='Gtc', reduce_only=False, tp=None, sl=None, trigger_market=True, round_price=False, round_size=False, submit=True)
async
Modify an existing order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
amount
|
float or Decimal
|
The positive or negative quantity of contracts to long or short. |
required |
price
|
float
|
The new price for the order. |
required |
oid
|
int
|
The order ID of the order to modify. Defaults to None. |
None
|
cloid
|
str
|
The client order ID of the order to modify. Defaults to None. |
None
|
tif
|
str
|
The time in force for the order. Defaults to "Gtc". Allowed values are: - "Gtc" (Good 'til canceled) - "Alo" (Add liquidity only) - "Ioc" (Immediate or cancel) |
'Gtc'
|
reduce_only
|
bool
|
Whether the order should only reduce an existing position. Defaults to False. |
False
|
tp
|
float
|
Take profit price. Defaults to None. |
None
|
sl
|
float
|
Stop loss price. Defaults to None. |
None
|
trigger_market
|
bool
|
Whether the tpsl trigger (if not None) is a market order. Defaults to True. |
True
|
round_price
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
round_size
|
bool
|
Whether to round the price to a valid order specification. Defaults to False. |
False
|
submit
|
bool
|
If True, the modification is submitted immediately, otherwise the order schema is returned. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the order modification request if |
order_query(oid=None, cloid=None, as_dict=True, **kwargs)
async
Get order details using order ID or client order ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
oid
|
int
|
The order ID in exchange. |
None
|
cloid
|
str
|
The client order ID. |
None
|
as_dict
|
bool
|
If True, returns as dictionary. Defaults to True. |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
order_status(id)
async
Get the status of a specific order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Unique identifier as order ID or client order ID. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the status and details of the specified order. |
order_updates_subscribe(handler, **kwargs)
async
Subscribe to creation, updation and deletion of account's orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
coroutine
|
A coroutine handler for the message received. |
required |
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
order_updates_unsubscribe(**kwargs)
async
Unsubscribe from order events.
orders_cancel(order_actions, expires_after=None)
async
Cancel multiple orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order_actions
|
list
|
A list of dictionaries representing the orders to be canceled. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the orders cancellation request. |
orders_cancel_cloid(order_actions, expires_after=None)
async
Cancel multiple orders using client order IDs (Cloids).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order_actions
|
list
|
A list of dictionaries representing the orders to be canceled using Cloids. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the orders cancellation request. |
orders_create(order_actions, grouping='na', expires_after=None, nonce=None)
async
Create new orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order_actions
|
list
|
A list of dictionaries representing the actions for creating orders. |
required |
grouping
|
str
|
The grouping type for the orders. Defaults to "na". |
'na'
|
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
nonce
|
int
|
A specific nonce to use. Defaults to None (auto-generated). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the orders creation request. |
orders_get(as_canonical=False, **kwargs)
async
Get all open order details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_canonical
|
bool
|
If True, the method returns tickers in their canonical form. Defaults to False. |
False
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing details of all open orders. Each key is the order ID ( |
Notes
See the Hyperliquid documentation for more details: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-open-orders
orders_mirror(as_canonical=False, on_update=None, as_list=True, **kwargs)
async
Keeps a local mirror copy of the account open orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_canonical
|
bool
|
If True, the method returns tickers in their canonical form. Defaults to False. |
False
|
on_update
|
coroutine
|
A coroutine handler for orders dictionary on order event. |
None
|
as_list
|
bool
|
If |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
orders_modify(order_actions, expires_after=None)
async
Modify multiple existing orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order_actions
|
list
|
A list of dictionaries representing the orders to be modified. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the orders modification request. |
orders_open(dex='')
async
Get all open orders.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of dictionaries containing details of all open orders for the user's account. |
orders_open_frontend(dex='')
async
Get all open orders with additional frontend-specific information.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of dictionaries containing details of all open orders for the user's account, with extra information for frontend use. |
orders_peek(as_dict=True, **kwargs)
Retrieves the local mirror copy of the account open orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_dict
|
bool
|
If |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
orders_schedule_cancel(time=None, expires_after=None)
async
Schedule a cancel-all operation (dead man's switch).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time
|
int
|
Timestamp in milliseconds for when to cancel all open orders. Must be at least 5 seconds in the future. Omit to remove a previously scheduled cancel. |
None
|
expires_after
|
int
|
Expiration time for the action in milliseconds. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the schedule cancel request. |
outcome_metadata()
async
Retrieve outcome metadata (testnet only).
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing prediction outcome definitions with binary side specifications. |
perpetuals_account(dex='')
async
Retrieve account information related to perpetual contracts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dex
|
str
|
The dex identifier. Defaults to "". |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing information about the user's account in relation to perpetual contracts, including positions, balances, and other relevant data. |
perpetuals_active_asset_data(ticker)
async
Retrieve active asset data for a specific perpetual.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing leverage settings, max tradeable sizes, available balance, and mark price. |
perpetuals_annotation(ticker)
async
Retrieve annotation for a specific perpetual asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with asset category classification and descriptive text. |
perpetuals_at_open_interest_cap(dex='')
async
Retrieve perpetuals currently at their open interest capacity limits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dex
|
str
|
The dex identifier. Defaults to "". |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of coin symbols at open interest capacity limits. |
perpetuals_categories()
async
Retrieve category mappings for all perpetual assets.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of coin-to-category mappings. |
perpetuals_concise_annotations()
async
Retrieve concise annotations for all perpetual assets.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Key-value pairs mapping coins to category and optional keywords. |
perpetuals_contexts(dex='')
async
Retrieve context information for perpetual contracts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dex
|
str
|
The dex identifier. Defaults to "". |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing context information for perpetual contracts, which may include details about market conditions and other relevant data. |
perpetuals_deploy_auction_status()
async
Retrieve the current perpetual deploy auction status.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with auction timing and gas parameters. |
perpetuals_dex_limits(dex)
async
Retrieve dex limits for a specific perpetuals dex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dex
|
str
|
The dex identifier. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary with total OI caps, per-perp size caps, max transfer notional, and per-coin limits. |
perpetuals_dex_status(dex)
async
Retrieve status for a specific perpetuals dex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dex
|
str
|
The dex identifier. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing total net deposit for the dex. |
perpetuals_dexs()
async
Retrieve information about all perpetual dexes.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of perpetual dex objects containing dex name, deployer address, oracle updater, fee recipient, and asset configurations. |
perpetuals_funding_historical(ticker, start=int(datetime.now(pytz.utc) - timedelta(days=14).timestamp() * 1000), end=None)
async
Retrieve funding history for a given coin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the coin. |
required |
start
|
int
|
The start time for the data range in milliseconds. Defaults to 14 days ago from the current time. |
int(timestamp() * 1000)
|
end
|
int
|
The end time for the data range in milliseconds. Defaults to None. |
None
|
Notes
For more details, refer to the Hyperliquid API documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-historical-funding-rates
perpetuals_metadata(dex='')
async
Retrieve metadata for all perpetual contracts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dex
|
str
|
The dex identifier. Defaults to "". |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing metadata for all perpetual contracts, including information about contract specifications and trading rules. |
perpetuals_metadata_all()
async
Retrieve metadata for all perpetuals across all dexes.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A nested array with universe definitions, margin tables, and asset contexts for all dexes. |
perpetuals_non_funding_ledger(start, end=None)
async
Retrieve non-funding ledger updates for the user's account.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
The start time in UNIX ms timestamp format. |
required |
end
|
int
|
The end time in UNIX ms timestamp format. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of ledger entries including deposits, transfers, and withdrawals. |
perpetuals_predicted_fundings()
async
Retrieve predicted funding rates for all perpetual assets.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A nested array mapping assets to venue-specific funding rates and next funding times. |
perpetuals_user_funding(start, end=None)
async
Retrieve the user's funding payment history for perpetual contracts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
The start time for the data range in UNIX ms timestamp format. |
required |
end
|
int
|
The end time for the data range in UNIX ms timestamp format. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the user's funding payment history, detailing the amounts paid or received as funding fees over time. |
portfolio()
async
Retrieve portfolio information for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing account value and PnL histories across multiple timeframes. |
positions_get(is_perpetuals=True, **kwargs)
async
Get all open position details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
is_perpetuals
|
bool
|
If True, retrieves positions for perpetual contracts. If False, retrieves spot balances. Defaults to True. |
True
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing details of the open positions. |
positions_mirror(is_perpetuals=True, on_update=None, as_dict=True, **kwargs)
async
Keeps a local mirror copy of the account open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
is_perpetuals
|
bool
|
If True, retrieves positions for perpetual contracts. If False, retrieves spot balances. Defaults to True. |
True
|
on_update
|
coroutine
|
A coroutine handler for positions dictionary on fill. |
None
|
as_dict
|
bool
|
If True, the method returns positions as a dictionary, otherwise as a |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
positions_peek(as_dict=True, **kwargs)
Retrieves the local mirror copy of the account open positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_dict
|
bool
|
If True, the method returns positions as a dictionary, otherwise as a |
True
|
**kwargs
|
Exchange wrapper specific keyword arguments. |
{}
|
rand_cloid(start='', end='', include_prefix=True, **kwargs)
Generate a random string (cloid) consisting of hexadecimal characters, optionally with a prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
str
|
A string to prepend to the generated random string. Defaults to ''. |
''
|
end
|
str
|
A string to append to the generated random string. Defaults to ''. |
''
|
include_prefix
|
bool
|
If True, includes the '0x' prefix at the beginning of the string. Defaults to True. |
True
|
**kwargs
|
Additional keyword arguments for future extensibility. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
A random hexadecimal string with a total length of 32 characters, including the optional 'start' and 'end' strings, and an optional '0x' prefix. |
referral()
async
Retrieve referral information for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing referral details including cumulative volume, rewards, referrer information, and referral state. |
request_l1_action(action, nonce, signature, expires_after=None)
async
Submit a Level 1 (L1) action to the exchange.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
str
|
The action to be performed. |
required |
nonce
|
int
|
A unique nonce for the action to prevent replay attacks. |
required |
signature
|
str
|
The signature validating the action. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the action request. |
reserve_request_weight(weight, expires_after=None)
async
Purchase additional rate limit capacity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
int
|
The amount of additional rate limit weight to reserve. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the reserve request. |
send_asset(amount, dest, src_dex, dest_dex, asset)
async
Send an asset between DEXs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
float
|
The amount to send. |
required |
dest
|
str
|
The destination address. |
required |
src_dex
|
str
|
Source DEX name. |
required |
dest_dex
|
str
|
Destination DEX name. |
required |
asset
|
str
|
The token to send. |
required |
send_to_evm(token, amount, source_dex, destination_recipient, address_encoding, destination_chain_id, gas_limit, data)
async
Send tokens to EVM with additional payload data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
Token identifier (e.g. "PURR:0xc4bf3f870c0e9465323c0b6ed28096c2"). |
required |
amount
|
float
|
The amount to send. |
required |
source_dex
|
str
|
Name of the source perp dex. |
required |
destination_recipient
|
str
|
Recipient address in the specified encoding. |
required |
address_encoding
|
str
|
Address encoding format ("hex" or "base58"). |
required |
destination_chain_id
|
int
|
Destination chain identifier. |
required |
gas_limit
|
int
|
Gas limit for the transaction. |
required |
data
|
bytes
|
Payload bytes. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the send request. |
set_referrer(code, expires_after=None)
async
Set a referral code for the account.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
The referral code. |
required |
expires_after
|
int
|
Expiration time in milliseconds. |
None
|
set_user_abstraction(abstraction)
async
Set the user's account abstraction mode (e.g. "portfolioMargin").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
abstraction
|
str
|
The abstraction mode to set. |
required |
set_user_abstraction_agent(abstraction)
async
Set account abstraction mode via agent key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
abstraction
|
str
|
The abstraction mode to set. |
required |
spot_balances()
async
Retrieve the user's spot balances.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the user's spot balances for various assets, detailing the amount held and other relevant account information. |
spot_contexts()
async
Retrieve context information for spot markets.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing context information for spot markets. |
spot_deploy_state()
async
Retrieve spot deploy auction info for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing token deployment states with genesis balances, max supply, gas auction timing and values. |
spot_metadata()
async
Retrieve metadata for all spot markets.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing metadata for all spot markets, including information such as trading pairs, asset details, and other relevant market specifications. |
spot_pair_deploy_auction_status()
async
Retrieve spot pair deploy auction status.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing dutch auction details for pair deployments including start time, duration, and gas pricing. |
spot_perp_transfer(amount, spot_to_perp=True)
async
Transfer funds between spot and perp accounts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
float
|
The amount to transfer. |
required |
spot_to_perp
|
bool
|
If True, transfer from spot to perp. If False, perp to spot. Defaults to True. |
True
|
subaccount_transfer(subaccount, is_deposit, amount, expires_after=None)
async
Transfer funds to or from a subaccount.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subaccount
|
str
|
The identifier for the subaccount. |
required |
is_deposit
|
bool
|
If True, the transfer is a deposit. If False, it is a withdrawal. |
required |
amount
|
float
|
The amount to transfer. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the subaccount transfer request. |
subaccounts()
async
Retrieve subaccounts for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list containing subaccount name, address, margin summary, and spot balances. |
token_delegate_undelegate(validator, wei, is_undelegate)
async
Delegate or undelegate tokens to a validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validator
|
str
|
The validator address. |
required |
wei
|
int
|
The amount in wei. |
required |
is_undelegate
|
bool
|
If True, undelegate. If False, delegate. |
required |
token_details(token_id)
async
Retrieve token information for a given token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_id
|
str
|
The 34-character hex token identifier. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing token supply data, pricing, genesis allocations, deployer info, and deployment timestamp. |
trades_subscribe(ticker, handler, standardize_schema=True, is_canonical=False, **kwargs)
async
Subscribe to ticker trades.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol for the asset. If |
required |
handler
|
coroutine
|
A coroutine handler for processing the received trade messages. |
required |
standardize_schema
|
bool
|
If True, processes the incoming message to a standardized format. Defaults to True. |
True
|
is_canonical
|
bool
|
If True, the |
False
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
trades_unsubscribe(ticker, is_canonical=False, **kwargs)
async
Unsubscribe from trade data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Ticker symbol for the asset. If |
required |
is_canonical
|
bool
|
If True, the |
False
|
**kwargs
|
Additional keyword arguments specific to the exchange wrapper. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Coroutine |
A coroutine that can be awaited to complete the unsubscription process. |
transfers_core_l1(amount, dest, asset='usdc')
async
Transfer l1 funds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
float
|
The amount to transfer. |
required |
dest
|
str
|
The destination address. |
required |
asset
|
str
|
The asset to transfer (default is "usdc"). |
'usdc'
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the transfer request. |
twap_order_cancel(ticker, twap_id, is_canonical=False, expires_after=None)
async
Cancel an active TWAP order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
twap_id
|
int
|
The TWAP order ID. |
required |
is_canonical
|
bool
|
If True, the ticker is treated as a canonical name. Defaults to False. |
False
|
expires_after
|
int
|
Expiration time for the action in milliseconds. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the TWAP cancel request. |
twap_order_create(ticker, amount, minutes, reduce_only=False, randomize=False, round_size=False, is_canonical=False, expires_after=None)
async
Create a TWAP (time-weighted average price) order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
amount
|
float
|
The signed quantity. Positive for buy (long), negative for sell (short). |
required |
minutes
|
int
|
The duration of the TWAP in minutes. |
required |
reduce_only
|
bool
|
Whether the order should only reduce an existing position. Defaults to False. |
False
|
randomize
|
bool
|
Whether to randomize the execution timing. Defaults to False. |
False
|
round_size
|
bool
|
Whether to round the size to a valid order specification. Defaults to False. |
False
|
is_canonical
|
bool
|
If True, the ticker is treated as a canonical name. Defaults to False. |
False
|
expires_after
|
int
|
Expiration time for the action in milliseconds. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the TWAP order request. |
twap_slice_fills()
async
Retrieve TWAP slice fills for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list of up to 2000 most recent TWAP fills with fill details and TWAP IDs. |
update_iso_margin(ticker, amount, expires_after=None)
async
Update the isolated margin for a specified asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
amount
|
float
|
The amount to adjust the isolated margin. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the isolated margin update request. |
update_leverage(ticker, leverage, is_cross=True, expires_after=None)
async
Update the leverage for a specified asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The ticker symbol of the asset. |
required |
leverage
|
float
|
The leverage multiplier to set. |
required |
is_cross
|
bool
|
If True, sets cross-margin mode. Defaults to True. |
True
|
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the leverage update request. |
user_abstraction()
async
Retrieve abstraction mode for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
str |
The abstraction mode - one of 'unifiedAccount', 'portfolioMargin', 'disabled', 'default', or 'dexAbstraction'. |
user_dex_abstraction()
async
Retrieve DEX abstraction enablement status for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
Whether DEX abstraction is enabled for the user. |
user_fees()
async
Retrieve fee schedule details for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing fee schedule details including daily volume, tier rates, referral discounts, staking discounts, and active user rates. |
user_role()
async
Retrieve the role designation for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the role designation and optional data. |
user_vault_equities()
async
Retrieve vault equities for the user's account.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list with vault address and equity amount for each vault. |
validator_vote_on_risk_free(risk_free_rate)
async
Validator vote on risk-free rate for quote asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_free_rate
|
str
|
The risk-free rate as a string (e.g. "0.04" for 4%). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the validator vote request. |
vault_details(vault_address, user=None)
async
Retrieve details for a specific vault.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vault_address
|
str
|
The vault address (42-character hex address). |
required |
user
|
str
|
User address for additional context. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing vault information including portfolio history, APR, followers, and relationship data. |
vault_transfer(vault, is_deposit, amount, expires_after=None)
async
Transfer funds to or from a vault.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vault
|
str
|
The address of the vault. |
required |
is_deposit
|
bool
|
If True, the transfer is a deposit. If False, it is a withdrawal. |
required |
amount
|
float
|
The amount to transfer. |
required |
expires_after
|
int
|
Expiration time for the action in milliseconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the vault transfer request. |
withdraw_staking(amount)
async
Withdraw staked tokens (7-day unstaking queue).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
float
|
The amount of tokens to unstake (converted to wei internally). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the staking withdrawal request. |
withdrawal_request(amount, dest)
async
Request a withdrawal from the bridge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
float
|
The amount to withdraw. |
required |
dest
|
str
|
The destination address. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
The result of the withdrawal request. |