Skip to content

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 resubsriptions 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())

Note that perpeutals 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:

hyp.get_accredited_name("JEFF/USDC")
hyp.get_canonical_name("@3")

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.

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()
We can get perpeutals contract specs:
specs = await hyp.contract_specifications(is_perpetuals=True)
or spot contract specs:
specs = await hyp.contract_specifications(is_perpetuals=False)
which gives:
{'@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}, ... }
The spot endpoints by default assume accredited_name as identifiers, but we can request:
specs = await hyp.contract_specifications(is_perpetuals=False,as_canonical=True)
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:

pos = await hyp.positions_get()
pos = await hyp.positions_get(is_perpetuals=False)
print(pos)
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')}, ... }
or force it to look like usdc-positions:
pos = await hyp.positions_get(is_perpetuals=False,as_usdc_pair=True)
{'PURR/USDC': {'ticker': 'PURR/USDC', 'amount': Decimal('dadas.gsdg'), 'entry': Decimal('0.dasdas'), 'value': Decimal('gdfsf.das'), 'unrealized_pnl': Decimal('sa.242113')}, 'HFUN/USDC': {'ticker': 'HFUN/USDC', 'amount': Decimal('3.1415926535'), 'entry': Decimal('dasd.dfasdf'), 'value': Decimal('DAD.ASF'), 'unrealized_pnl': Decimal('245.32242')}, ...}
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:
await hyp.positions_mirror()
await hyp.positions_mirror(on_update=print_handler)
the on_update is optional, and the alive, local copy of positions can be retrieved here:
pos = hyp.positions_peek()
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)
We also give options to submit parent-child orders involving tp-sl triggers, as in their web-interface:
ord = await hyp.limit_order(ticker="SOL",amount=-1,price=1000,tp=400,sl=1200)
And the market-order:
ord = await hyp.market_order(ticker="SOL",amount=-1)

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:

await hyp.order_updates_subscribe(handler=print_handler)

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)

Data

You can of course retrieve data. You can get all mids as snapshot or as subscription:

mids = await hyp.get_all_mids()
await hyp.all_mids_subscribe(handler=print_handler)
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', ... }
but again you can ask for canonical schema:
await hyp.all_mids_subscribe(handler=print_handler,as_canonical=True)
{'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):

await hyp.all_mids_unsubscribe()

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)
In hpl cases, the subscription actually returns a book snapshot rather than incremental updates, so the mirror states and subscription updates are similar. However, the 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
By specifying 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)
A host of other endpoints such as user-funding,transactions, funding rates, transfers, account leverage updates and so on are supported...refer to docs.

Documentation

Channel

Represents various socket subscription channels.

Attributes:

Name Type Description
ALL_MIDS str

The "allMids" channel.

NOTIFICATION str

The "notification" channel.

WEBDATA str

The "webData2" 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 "user" channel for user events.

USER_FILLS str

The "userFills" channel.

USER_FUNDINGS str

The "userFundings" channel.

USER_LEDGER_UPDATES str

The "userNonFundingLedgerUpdates" channel.

Hyperliquid

__init__(key='', secret='', **kwargs)

Initializes the Hyperliquid instance.

Parameters:

Name Type Description Default
key str

The public or vault address.

''
secret str

The secret key.

''

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, **kwargs) async

Subscribe to order fill events.

Parameters:

Name Type Description Default
handler coroutine

A coroutine handler for the message received.

required
**kwargs

Exchange wrapper specific keyword arguments.

{}

account_fill_unsubscribe(**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.

all_mids() 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, **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
**kwargs

Exchange wrapper specific keyword arguments.

{}

all_mids_unsubscribe(**kwargs) async

Unsubscribe from mid prices.

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 is_canonical is True, this should be the canonical name. Defaults to None, which means cancel all open orders.

None
is_canonical bool

If True, the ticker is treated as a canonical name and converted to the accredited name. Defaults to False.

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 ticker is treated as a canonical name and converted to the accredited name. Defaults to False.

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.

cleanup() async

Cleans up open sessions with HPL server

contract_specifications(is_perpetuals=True, as_canonical=False, **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
**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

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_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 ticker is provided.

dict

A dictionary with contract symbols as keys and their corresponding mid-prices (Decimal) as values if ticker is not provided.

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_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 ticker is treated as a canonical name. Defaults to False.

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 ticker is treated as a canonical name. Defaults to False.

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, which uses start time.

False
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description
DataFrame

DataFrame containing the trade bars data.

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.

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 as_dict is False.

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=1000, buffer_size=100, as_dict=True, on_update=None, 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 as_dict is False

1000
buffer_size int

Size of the order-book buffer, if as_dict is False

100
as_dict (bool, True)

If True, pass state as dictionary, otherwise as a quantpylib.hft.lob.LOB object into handlers.

True
on_update coroutine

A coroutine handler when order book state is updated.

None
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, return state as dictionary, otherwise as a quantpylib.hft.lob.LOB object.

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, **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 {ts,b,a}

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

l2_book_subscriptions(**kwargs)

Retrieve the list of open l2 book subscriptions.

l2_book_unsubscribe(ticker, **kwargs) async

Unsubscribe from L2 Order Book.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
**kwargs

Exchange wrapper specific keyword arguments.

{}

l2_snapshot(ticker, nsigfig=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

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, **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 ticker is treated as a canonical name and converted to the accredited name. Defaults to False.

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 ticker is treated as a canonical name and converted to the accredited name. Defaults to False.

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.

order_cancel(ticker, oid, 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
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 submit is True, otherwise the action dictionary.

order_cancel_cloid(ticker, cloid, 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
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 submit is True, otherwise the action dictionary.

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) 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

Returns:

Name Type Description
dict

The result of the order creation or the action object if submit is False.

order_fills() 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) 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.

required

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

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 submit is True, otherwise the action dictionary.

order_query(oid=None, cloid=None, as_dict=True, **kwargs) async

Get order details using order ID.

Parameters:

Name Type Description Default
id (str, int)

Order ID in exchange

required
**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) async

Cancel multiple orders.

Parameters:

Name Type Description Default
order_actions list

A list of dictionaries representing the orders to be canceled.

required

Returns:

Name Type Description
dict

The result of the orders cancellation request.

orders_cancel_cloid(order_actions) 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

Returns:

Name Type Description
dict

The result of the orders cancellation request.

orders_create(order_actions, grouping='na') 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'

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 (oid), with value dict: - markets.TICKER: The asset's ticker symbol, either in standard or canonical form. - markets.ORDER_ID: The unique identifier of the order. - markets.ORDER_CLOID: The client order ID. - markets.LIMIT_PRICE: The limit price of the order. - markets.ORDER_AMOUNT: The original size of the order. - markets.ORDER_FILLED_SIZE: The remaining size of the order yet to be filled. - markets.ORDER_STATUS: The status of the order. - markets.TIMESTAMP: The timestamp when the order was created.

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, pass state as list, otherwise as quantpylib.standards.Orders object into handlers.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

orders_modify(order_actions) async

Modify multiple existing orders.

Parameters:

Name Type Description Default
order_actions list

A list of dictionaries representing the orders to be modified.

required

Returns:

Name Type Description
dict

The result of the orders modification request.

orders_open() 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() 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, pass state as dictionary, otherwise as quantpylib.standards.Orders object.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

perpetuals_account() async

Retrieve account information related to perpetual contracts.

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_contexts() async

Retrieve context information for perpetual contracts.

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_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() async

Retrieve metadata for all perpetual contracts.

Returns:

Name Type Description
dict

A dictionary containing metadata for all perpetual contracts, including information about contract specifications and trading rules.

perpetuals_user_funding() async

Retrieve the user's funding payment history for perpetual contracts.

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.

positions_get(is_perpetuals=True, as_usdc_pair=False, **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
as_usdc_pair bool

If True, returns spot balances as USDC pairs, otherwise as token balances. Defaults to False.

False
**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 quantpylib.standards.Positions object. Defaults to True.

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 quantpylib.standards.Positions object. Defaults to True.

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 details related to the user's referral program, such as referral code, referral rewards, and the status of referred users.

request_l1_action(action, nonce, signature) 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

Returns:

Name Type Description
dict

The result of the action request.

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_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_perp_transfer(amount, spot_to_perp=True) async

Transfer funds between spot and perpetual accounts.

Parameters:

Name Type Description Default
amount float

The amount to transfer.

required
spot_to_perp bool

If True, transfer from spot to perpetual. Defaults to True.

True

Returns:

Name Type Description
dict

The result of the transfer request.

subaccount_transfer(subaccount, is_deposit, amount) 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

Returns:

Name Type Description
dict

The result of the subaccount transfer request.

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 is_canonical is True, this should be the canonical name.

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 ticker is treated as a canonical name and converted to the accredited name. Defaults to False.

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 is_canonical is True, this should be the canonical name.

required
is_canonical bool

If True, the ticker is treated as a canonical name and converted to the accredited name. Defaults to False.

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.

transfer_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.

update_iso_margin(ticker, amount) 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

Returns:

Name Type Description
dict

The result of the isolated margin update request.

update_leverage(ticker, leverage, is_cross=True) 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

Returns:

Name Type Description
dict

The result of the leverage update request.

vault_transfer(vault, is_deposit, amount) 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

Returns:

Name Type Description
dict

The result of the vault transfer 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.