hyperliquid.api
Documentation for eth_defi.hyperliquid.api Python module.
Hyperliquid info API client.
Typed wrappers for the Hyperliquid info endpoint.
Uses create_hyperliquid_session() for
HTTP connections with rate limiting and retry logic.
Example:
from eth_defi.hyperliquid.api import fetch_user_vault_equities
from eth_defi.hyperliquid.session import create_hyperliquid_session
session = create_hyperliquid_session()
equities = fetch_user_vault_equities(session, user="0xAbc...")
for eq in equities:
print(f"Vault {eq.vault_address}: {eq.equity} USDC")
Functions
|
Fetch up to 5,000 OHLCV candles for a single coin. |
|
Fetch up to 500 funding-rate observations for a single coin. |
|
Fetch the full Hyperliquid trader leaderboard. |
|
Fetch a user's perpetual account state on HyperCore. |
|
Fetch the perpetual universe metadata ( |
|
Fetch all-time PnL and volume for any Hyperliquid address. |
|
Fetch a user's spot account state on HyperCore. |
|
Read the Hyperliquid account abstraction mode for a user. |
|
Fetch a user's equity positions across all Hypercore vaults. |
|
Fetch a user's equity in a single Hypercore vault, with caching. |
|
Fetch a user's vault position and check whether the lock-up has expired. |
|
Fetch the display name of a Hyperliquid vault. |
|
Wait for a vault deposit to be confirmed on HyperCore. |
Classes
A single perpetual position. |
|
USDC bridged to HyperCore but held in EVM escrow. |
|
A single OHLCV candle from the |
|
A single funding-rate observation from the |
|
A single trader from the Hyperliquid public leaderboard. |
|
Margin summary for a perpetual account. |
|
Perpetual account state for a HyperCore user. |
|
All-time PnL and trading volume for a Hyperliquid address. |
|
A single spot token balance on HyperCore. |
|
Spot account state for a HyperCore user. |
|
A user's equity position in a single Hypercore vault. |
Exceptions
Raised when a Hypercore vault deposit cannot be verified on HyperCore. |
- class AssetPosition
Bases:
objectA single perpetual position.
Returned inside
PerpClearinghouseState.- __init__(coin, size, entry_price, unrealised_pnl, margin_used, position_value, liquidation_price)
- Parameters
coin (str) –
size (decimal.Decimal) –
entry_price (Optional[decimal.Decimal]) –
unrealised_pnl (decimal.Decimal) –
margin_used (decimal.Decimal) –
position_value (decimal.Decimal) –
liquidation_price (Optional[decimal.Decimal]) –
- Return type
None
- class EvmEscrow
Bases:
objectUSDC bridged to HyperCore but held in EVM escrow.
When USDC is deposited via
CoreDepositWallet.deposit(), it appears in theevmEscrowsfield of the spot clearinghouse state until the HyperCore action is processed.Returned inside
SpotClearinghouseState.- __init__(coin, token, total)
- Parameters
coin (str) –
token (int) –
total (decimal.Decimal) –
- Return type
None
- exception HypercoreDepositVerificationError
Bases:
ExceptionRaised when a Hypercore vault deposit cannot be verified on HyperCore.
CoreWriter actions (
transferUsdClass+vaultTransfer) can succeed on HyperEVM but be silently rejected by HyperCore. This exception is raised bywait_for_vault_deposit_confirmation()when the expected vault equity never appears within the timeout.- __init__(*args, **kwargs)
- __new__(**kwargs)
- add_note(note, /)
Add a note to the exception
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- class HyperliquidCandle
Bases:
objectA single OHLCV candle from the
candleSnapshotInfo endpoint.Prices and volume are stored as
floatfor direct pandas/numpy compatibility in backtesting notebooks. Callers needing arbitrage-level precision should consume the raw API response instead.- __init__(open_time, close_time, coin, interval, open, high, low, close, volume, trades)
- Parameters
open_time (datetime.datetime) –
close_time (datetime.datetime) –
coin (str) –
interval (str) –
open (float) –
high (float) –
low (float) –
close (float) –
volume (float) –
trades (int) –
- Return type
None
- class HyperliquidFundingRate
Bases:
objectA single funding-rate observation from the
fundingHistoryendpoint.Hyperliquid pays funding every hour at 1/8 of the computed 8-hour funding rate, so one of these dataclasses represents the funding charge/payment for a single 1-hour window. Authoritative reference for the cadence and formula: https://hyperliquid.gitbook.io/hyperliquid-docs/trading/funding
Funding rate and premium are stored as
floatfor direct pandas/numpy compatibility.- __init__(timestamp, coin, funding_rate, premium)
- Parameters
timestamp (datetime.datetime) –
coin (str) –
funding_rate (float) –
premium (float) –
- Return type
None
- class LeaderboardEntry
Bases:
objectA single trader from the Hyperliquid public leaderboard.
The leaderboard contains 32K+ traders who have opted in. Fetched in bulk by
fetch_leaderboard().- __init__(address, display_name, account_value, all_time_pnl, all_time_roi, all_time_volume)
- Parameters
address (eth_typing.evm.HexAddress) –
account_value (decimal.Decimal) –
all_time_pnl (decimal.Decimal) –
all_time_roi (decimal.Decimal) –
all_time_volume (decimal.Decimal) –
- Return type
None
- class MarginSummary
Bases:
objectMargin summary for a perpetual account.
Returned inside
PerpClearinghouseState.- __init__(account_value, total_ntl_pos, total_raw_usd, total_margin_used)
- Parameters
account_value (decimal.Decimal) –
total_ntl_pos (decimal.Decimal) –
total_raw_usd (decimal.Decimal) –
total_margin_used (decimal.Decimal) –
- Return type
None
- class PerpClearinghouseState
Bases:
objectPerpetual account state for a HyperCore user.
Returned by
fetch_perp_clearinghouse_state().- __init__(margin_summary, withdrawable, asset_positions)
- Parameters
margin_summary (eth_defi.hyperliquid.api.MarginSummary) –
withdrawable (decimal.Decimal) –
asset_positions (list[eth_defi.hyperliquid.api.AssetPosition]) –
- Return type
None
- class PortfolioAllTimeData
Bases:
objectAll-time PnL and trading volume for a Hyperliquid address.
Fetched from the
portfolioinfo endpoint, which works for any address — not just leaderboard participants.The
pnlHistoryarray in the API response is aggregated data that covers the account’s full lifetime, unlike fills which are capped at ~10K entries per account. The first entry’s timestamp therefore gives a reliable account creation / first activity date.Returned by
fetch_portfolio().- __init__(all_time_pnl, all_time_volume, first_activity_at)
- Parameters
all_time_pnl (Optional[decimal.Decimal]) –
all_time_volume (Optional[decimal.Decimal]) –
first_activity_at (Optional[datetime.datetime]) –
- Return type
None
- class SpotBalance
Bases:
objectA single spot token balance on HyperCore.
Returned inside
SpotClearinghouseState.- __init__(coin, token, total, hold)
- Parameters
coin (str) –
token (int) –
total (decimal.Decimal) –
hold (decimal.Decimal) –
- Return type
None
- class SpotClearinghouseState
Bases:
objectSpot account state for a HyperCore user.
Returned by
fetch_spot_clearinghouse_state().- __init__(balances, evm_escrows)
- Parameters
balances (list[eth_defi.hyperliquid.api.SpotBalance]) –
evm_escrows (list[eth_defi.hyperliquid.api.EvmEscrow]) –
- Return type
None
- class UserVaultEquity
Bases:
objectA user’s equity position in a single Hypercore vault.
Returned by
fetch_user_vault_equities().Example — check whether a vault deposit can be withdrawn:
from eth_defi.hyperliquid.api import fetch_user_vault_equity from eth_defi.hyperliquid.session import create_hyperliquid_session session = create_hyperliquid_session() eq = fetch_user_vault_equity(session, user="0xAbc...", vault_address="0xDef...") if eq is not None: if eq.is_lockup_expired: print(f"Withdrawal ready — {eq.equity} USDC available") else: print(f"Locked for another {eq.lockup_remaining}")- __init__(vault_address, equity, locked_until)
- Parameters
vault_address (eth_typing.evm.HexAddress) –
equity (decimal.Decimal) –
locked_until (datetime.datetime) –
- Return type
None
- property is_lockup_expired: bool
Whether the lock-up period has passed and withdrawal is allowed.
Compares
locked_untilagainst the current UTC time.- Returns
Trueif the current time is at or past the lock-up deadline.
- property lockup_remaining: datetime.timedelta
Time remaining until the lock-up expires.
Returns
timedelta(0)if the lock-up has already expired.- Returns
Remaining lock-up duration (never negative).
- fetch_candle_snapshot(session, *, coin, interval, start_time, end_time, timeout=30.0)
Fetch up to 5,000 OHLCV candles for a single coin.
Calls the
candleSnapshotInfo endpoint. The response is capped atHYPERLIQUID_CANDLE_SNAPSHOT_LIMITcandles regardless of window width, so callers needing longer histories must paginate.Pre-launch candles (before ~April 2023) are returned but have zero volume — these are backfilled price data, not authentic Hyperliquid trades. Filter by
volume > 0for real bars only.Uses
HyperliquidSession.post_info()for automatic proxy rotation on rate-limit or connectivity failures.Example:
from datetime import datetime from eth_defi.hyperliquid.api import fetch_candle_snapshot from eth_defi.hyperliquid.session import create_hyperliquid_session session = create_hyperliquid_session() candles = fetch_candle_snapshot( session, coin="BTC", interval="4h", start_time=datetime(2023, 5, 1), end_time=datetime(2023, 6, 1), ) print(f"{len(candles)} candles, first close={candles[0].close}")- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().coin (str) – Base symbol only (e.g.
"BTC"), not a CCXT-style pair.interval (str) – One of
"1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d","3d","1w","1M".start_time (datetime.datetime) – Earliest candle, naive UTC datetime.
end_time (datetime.datetime) – Latest candle, naive UTC datetime.
timeout (float) – HTTP request timeout in seconds.
- Returns
Candles in ascending time order. Empty list if no data.
- Return type
- fetch_funding_history(session, *, coin, start_time, end_time=None, timeout=30.0)
Fetch up to 500 funding-rate observations for a single coin.
Calls the
fundingHistoryInfo endpoint. Hyperliquid pays funding every hour at 1/8 of the computed 8-hour rate, soHYPERLIQUID_FUNDING_HISTORY_LIMITrecords ≈ 20 days per call. A 3-year history per symbol needs roughly 55 paginated requests. Callers needing long histories should use the higher-levelstrategycore.hyperliquid.fetch_funding_rate_history()wrapper, which handles pagination and parquet caching.Uses
HyperliquidSession.post_info()for automatic proxy rotation on rate-limit or connectivity failures.Funding cadence and formula: Hyperliquid Docs › Trading › Funding.
API endpoint: Info endpoint › fundingHistory.
- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().coin (str) – Base symbol only, e.g.
"BTC".start_time (datetime.datetime) – Earliest funding observation, naive UTC datetime.
end_time (Optional[datetime.datetime]) – Optional latest observation, naive UTC datetime. If
None, the API returns up to 500 records starting atstart_time.timeout (float) – HTTP request timeout in seconds.
- Returns
Funding-rate observations in ascending time order.
- Return type
- fetch_leaderboard(timeout=60.0)
Fetch the full Hyperliquid trader leaderboard.
Calls the public
stats-data.hyperliquid.xyz/Mainnet/leaderboardendpoint which returns 32K+ traders who have opted in, indexed by lowercased address for easy lookup.Does not require a
HyperliquidSession— this is a plain GET to a stats endpoint with no rate limiting.Example:
from eth_defi.hyperliquid.api import fetch_leaderboard leaderboard = fetch_leaderboard() print(f"Leaderboard has {len(leaderboard)} traders") # Look up a specific address entry = leaderboard.get("0x1234abcd...") if entry: print(f"{entry.display_name}: PnL={entry.all_time_pnl}, ROI={entry.all_time_roi}") # Example output: # HyperTrader42: PnL=1234567.89, ROI=0.4523The raw API response:
{"leaderboardRows": [{"ethAddress": "0x...", "accountValue": "123456.78", "displayName": "HyperTrader42", "windowPerformances": [["allTime", {"pnl": "1234567.89", "roi": "0.4523", "vlm": "98765432.10"}], ...]}, ...]}- Parameters
timeout (float) – HTTP request timeout in seconds.
- Returns
Dict mapping lowercased address to
LeaderboardEntry.- Return type
- fetch_perp_clearinghouse_state(session, user, timeout=10.0)
Fetch a user’s perpetual account state on HyperCore.
Calls the
clearinghouseStateinfo endpoint to retrieve margin summary, withdrawable balance, and open positions.- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().user (Union[eth_typing.evm.HexAddress, str]) – On-chain address.
timeout (float) – HTTP request timeout in seconds.
- Returns
Perpetual clearinghouse state with margin info and positions.
- Return type
- fetch_perp_meta(session, timeout=10.0)
Fetch the perpetual universe metadata (
{"type": "meta"}).Used primarily for symbol discovery. Returns the raw dict with keys such as
universe(list of per-coin metadata entries).Uses
HyperliquidSession.post_info()for automatic proxy rotation on rate-limit or connectivity failures.- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().timeout (float) – HTTP request timeout in seconds.
- Returns
Raw metadata dict.
- Return type
- fetch_portfolio(session, address, timeout=15.0)
Fetch all-time PnL and volume for any Hyperliquid address.
Calls the
portfolioinfo endpoint which returns account value history, PnL history, and volume across multiple time windows (day, week, month, allTime).Unlike the leaderboard, this works for any address — including those that have not opted in to the public leaderboard.
Example:
from eth_defi.hyperliquid.api import fetch_portfolio from eth_defi.hyperliquid.session import create_hyperliquid_session session = create_hyperliquid_session() portfolio = fetch_portfolio(session, "0x1234...") if portfolio is not None: print(f"All-time PnL: {portfolio.all_time_pnl}") print(f"All-time volume: {portfolio.all_time_volume}") # Example output: # All-time PnL: -58459.412942 # All-time volume: 1893425014.9738The raw API response is an array of
[period, data]pairs:[["day", {"accountValueHistory": [...], "pnlHistory": [...], "vlm": "..."}], ["allTime", {"accountValueHistory": [...], "pnlHistory": [[ts, pnl], ...], "vlm": "1893425014.9738"}]]- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().address (Union[eth_typing.evm.HexAddress, str]) – Hyperliquid user address.
timeout (float) – HTTP request timeout in seconds.
- Returns
All-time PnL, volume, and first activity timestamp, or
Noneon network/API error.- Return type
- fetch_spot_clearinghouse_state(session, user, timeout=10.0)
Fetch a user’s spot account state on HyperCore.
Calls the
spotClearinghouseStateinfo endpoint to retrieve spot token balances and EVM escrow amounts.- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().user (Union[eth_typing.evm.HexAddress, str]) – On-chain address.
timeout (float) – HTTP request timeout in seconds.
- Returns
Spot clearinghouse state with balances and EVM escrows.
- Return type
- fetch_user_abstraction_mode(session, user, timeout=10.0)
Read the Hyperliquid account abstraction mode for a user.
Example:
from eth_defi.hyperliquid.api import fetch_user_abstraction_mode from eth_defi.hyperliquid.session import create_hyperliquid_session session = create_hyperliquid_session() mode = fetch_user_abstraction_mode(session, user="0xAbc...") print(f"Account mode: {mode}")- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().user (Union[eth_typing.evm.HexAddress, str]) – On-chain address to query.
timeout (float) – HTTP request timeout in seconds.
- Returns
Hyperliquid account abstraction mode such as
"standard"or"unifiedAccount".- Return type
- fetch_user_vault_equities(session, user, timeout=10.0)
Fetch a user’s equity positions across all Hypercore vaults.
Calls the
userVaultEquitiesinfo endpoint to retrieve the user’s current vault deposits with equity and lock-up status.This is the recommended way to verify that a CoreWriter deposit landed on HyperCore — no EVM precompile needed.
Example:
from eth_defi.hyperliquid.api import fetch_user_vault_equities from eth_defi.hyperliquid.session import create_hyperliquid_session, HYPERLIQUID_TESTNET_API_URL # Mainnet session = create_hyperliquid_session() equities = fetch_user_vault_equities(session, user="0xAbc...") # Testnet session = create_hyperliquid_session(api_url=HYPERLIQUID_TESTNET_API_URL) equities = fetch_user_vault_equities(session, user="0xAbc...")
- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().user (Union[eth_typing.evm.HexAddress, str]) – On-chain address (the Safe address for Lagoon vaults).
timeout (float) – HTTP request timeout in seconds.
- Returns
List of vault equity positions. Empty list if the user has no vault deposits.
- Return type
- fetch_user_vault_equity(session, user, vault_address, cache_timeout=900, timeout=10.0, bypass_cache=False)
Fetch a user’s equity in a single Hypercore vault, with caching.
Convenience wrapper around
fetch_user_vault_equities()that fetches all vault positions, caches the result, and returns the one matching vault_address.The cache is keyed by
(api_url, user)and entries expire after cache_timeout seconds (default 15 minutes).Example:
from eth_defi.hyperliquid.api import fetch_user_vault_equity from eth_defi.hyperliquid.session import create_hyperliquid_session session = create_hyperliquid_session() eq = fetch_user_vault_equity(session, user="0xAbc...", vault_address="0xDef...") if eq is not None: print(f"Equity: {eq.equity} USDC")- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().user (Union[eth_typing.evm.HexAddress, str]) – On-chain address (the Safe address for Lagoon vaults).
vault_address (Union[eth_typing.evm.HexAddress, str]) – Hypercore vault address to look up.
cache_timeout (float) – How long cached results stay valid, in seconds. Defaults to
DEFAULT_VAULT_EQUITY_CACHE_TIMEOUT(15 minutes).timeout (float) – HTTP request timeout in seconds (passed to the underlying API call).
bypass_cache (bool) – If
True, skip the cache and always fetch fresh data from the API. The fresh result is still stored in the cache for subsequent calls.
- Returns
The user’s equity in the vault, or
Noneif the user has no position in the given vault.- Return type
- fetch_vault_lockup_status(session, user, vault_address, cache_timeout=900, timeout=10.0)
Fetch a user’s vault position and check whether the lock-up has expired.
Convenience wrapper around
fetch_user_vault_equity()that fetches the position (with caching) and returns it with lock-up status available viaUserVaultEquity.is_lockup_expiredandUserVaultEquity.lockup_remaining.Returns
Noneif the user has no position in the vault.Example:
from eth_defi.hyperliquid.api import fetch_vault_lockup_status from eth_defi.hyperliquid.session import create_hyperliquid_session session = create_hyperliquid_session() eq = fetch_vault_lockup_status(session, user="0xAbc...", vault_address="0xDef...") if eq is not None: if eq.is_lockup_expired: print("Withdrawal ready") else: print(f"Locked for another {eq.lockup_remaining}") else: print("No position in this vault")- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().user (Union[eth_typing.evm.HexAddress, str]) – On-chain address (the Safe address for Lagoon vaults).
vault_address (Union[eth_typing.evm.HexAddress, str]) – Hypercore vault address.
cache_timeout (float) – Cache timeout in seconds.
timeout (float) – HTTP request timeout in seconds.
- Returns
The user’s vault equity with lock-up properties, or
Noneif no position.- Return type
- fetch_vault_name(session, vault_address, timeout=10.0)
Fetch the display name of a Hyperliquid vault.
Makes a lightweight
vaultDetailsAPI call and extracts only the vault name. ReturnsNoneif the vault is not found or the request fails.Example:
from eth_defi.hyperliquid.api import fetch_vault_name from eth_defi.hyperliquid.session import create_hyperliquid_session session = create_hyperliquid_session() name = fetch_vault_name(session, "0x15be61aef0ea4e4dc93c79b668f26b3f1be75a66") print(name) # e.g. "Growi HF"
- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().vault_address (Union[eth_typing.evm.HexAddress, str]) – Vault address to look up.
timeout (float) – HTTP request timeout in seconds.
- Returns
Vault display name, or
Noneif not found.- Return type
- wait_for_vault_deposit_confirmation(session, user, vault_address, expected_deposit, existing_equity=None, timeout=60.0, poll_interval=2.0, tolerance=Decimal('0.01'), relative_tolerance=Decimal('0.01'))
Wait for a vault deposit to be confirmed on HyperCore.
After a CoreWriter
vaultTransferaction succeeds on HyperEVM, HyperCore may take several seconds to process the deposit. This function pollsuserVaultEquitiesuntil the expected equity appears or increases.Handles two cases:
New position: existing_equity is
None. Waits for any equity > 0 to appear for the vault.Existing position: existing_equity is provided. Waits for equity to increase by at least
expected_deposit - max(tolerance, expected_deposit * relative_tolerance).
- Parameters
session (eth_defi.hyperliquid.session.HyperliquidSession) – Session from
create_hyperliquid_session().user (Union[eth_typing.evm.HexAddress, str]) – On-chain address (the Safe address for Lagoon vaults).
vault_address (Union[eth_typing.evm.HexAddress, str]) – Hypercore vault address.
expected_deposit (decimal.Decimal) – Expected deposit amount in USDC (human-readable, not raw).
existing_equity (Optional[decimal.Decimal]) – User’s vault equity before the deposit, or
Noneif this is the first deposit (no existing position).timeout (float) – Maximum seconds to wait before raising
HypercoreDepositVerificationError.poll_interval (float) – Seconds between API polls.
tolerance (decimal.Decimal) – Acceptable difference between expected and actual equity increase (to account for rounding, fees, vault PnL during the wait). Defaults to 0.01 USDC.
relative_tolerance (decimal.Decimal) – Acceptable relative difference for existing vault deposits. The larger of
toleranceandexpected_deposit * relative_toleranceis used, because live vault equity can drift during confirmation. Defaults to 1%.
- Returns
The confirmed
UserVaultEquityafter the deposit.- Raises
HypercoreDepositVerificationError – If the deposit cannot be verified within the timeout.
- Return type