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")
Module Attributes
Hyperliquid stats-data leaderboard endpoint (public GET, no auth, 32K+ entries) |
|
Default cache timeout for |
Functions
|
Fetch the full Hyperliquid trader leaderboard. |
|
Fetch a user's perpetual account state on HyperCore. |
|
Fetch all-time PnL and volume for any Hyperliquid address. |
|
Fetch a user's spot account state on HyperCore. |
|
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 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. |
- LEADERBOARD_URL = 'https://stats-data.hyperliquid.xyz/Mainnet/leaderboard'
Hyperliquid stats-data leaderboard endpoint (public GET, no auth, 32K+ entries)
- DEFAULT_VAULT_EQUITY_CACHE_TIMEOUT = 900
Default cache timeout for
fetch_user_vault_equity()in seconds (15 minutes).
- 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()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- 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}")- vault_address: eth_typing.evm.HexAddress
Hypercore vault address
- equity: decimal.Decimal
USDC equity in the vault
- locked_until: datetime.datetime
UTC datetime until which withdrawals are locked.
User-created vaults have a 1 day lock-up, protocol vaults (HLP) have 4 days.
- 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).
- __init__(vault_address, equity, locked_until)
- Parameters
vault_address (eth_typing.evm.HexAddress) –
equity (decimal.Decimal) –
locked_until (datetime.datetime) –
- Return type
None
- class SpotBalance
Bases:
objectA single spot token balance on HyperCore.
Returned inside
SpotClearinghouseState.- total: decimal.Decimal
Total balance (decimal string parsed to
Decimal)
- hold: decimal.Decimal
Amount on hold (reserved for orders)
- __init__(coin, token, total, hold)
- Parameters
coin (str) –
token (int) –
total (decimal.Decimal) –
hold (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.- total: decimal.Decimal
Escrowed amount
- __init__(coin, token, total)
- Parameters
coin (str) –
token (int) –
total (decimal.Decimal) –
- Return type
None
- class SpotClearinghouseState
Bases:
objectSpot account state for a HyperCore user.
Returned by
fetch_spot_clearinghouse_state().- balances: list[eth_defi.hyperliquid.api.SpotBalance]
Spot token balances
- evm_escrows: list[eth_defi.hyperliquid.api.EvmEscrow]
USDC in EVM escrow (bridged but not yet processed by HyperCore)
- __init__(balances, evm_escrows)
- Parameters
balances (list[eth_defi.hyperliquid.api.SpotBalance]) –
evm_escrows (list[eth_defi.hyperliquid.api.EvmEscrow]) –
- Return type
None
- class MarginSummary
Bases:
objectMargin summary for a perpetual account.
Returned inside
PerpClearinghouseState.- account_value: decimal.Decimal
Total account value in USD
- total_ntl_pos: decimal.Decimal
Total notional position size
- total_raw_usd: decimal.Decimal
Total raw USD balance
- total_margin_used: decimal.Decimal
Total margin used
- __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 AssetPosition
Bases:
objectA single perpetual position.
Returned inside
PerpClearinghouseState.- size: decimal.Decimal
Position size (negative = short)
- entry_price: decimal.Decimal | None
Entry price
- unrealised_pnl: decimal.Decimal
Unrealised PnL
- margin_used: decimal.Decimal
Margin used for this position
- position_value: decimal.Decimal
Position value in USD
- liquidation_price: decimal.Decimal | None
Liquidation price (
Noneif no position)
- __init__(coin, size, entry_price, unrealised_pnl, margin_used, position_value, liquidation_price)
- Parameters
coin (str) –
size (decimal.Decimal) –
entry_price (decimal.Decimal | None) –
unrealised_pnl (decimal.Decimal) –
margin_used (decimal.Decimal) –
position_value (decimal.Decimal) –
liquidation_price (decimal.Decimal | None) –
- Return type
None
- class PerpClearinghouseState
Bases:
objectPerpetual account state for a HyperCore user.
Returned by
fetch_perp_clearinghouse_state().- margin_summary: eth_defi.hyperliquid.api.MarginSummary
Cross-margin summary
- withdrawable: decimal.Decimal
Withdrawable balance
- asset_positions: list[eth_defi.hyperliquid.api.AssetPosition]
Active perpetual positions
- __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().- all_time_pnl: decimal.Decimal | None
Latest cumulative PnL in USD (from the last entry in
pnlHistory)
- all_time_volume: decimal.Decimal | None
All-time trading volume in USD
- first_activity_at: datetime.datetime | None
Timestamp of the first
pnlHistoryentry — the account’s first recorded activity. Derived from aggregated data that covers the full account lifetime (not subject to the ~10K fill API cap).
- __init__(all_time_pnl, all_time_volume, first_activity_at)
- Parameters
all_time_pnl (decimal.Decimal | None) –
all_time_volume (decimal.Decimal | None) –
first_activity_at (datetime.datetime | None) –
- 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().- address: eth_typing.evm.HexAddress
Ethereum address (lowercased)
- account_value: decimal.Decimal
Account value in USD at time of leaderboard snapshot
- all_time_pnl: decimal.Decimal
All-time PnL in USD
- all_time_roi: decimal.Decimal
All-time ROI as a ratio (e.g.
0.25= 25%)
- all_time_volume: decimal.Decimal
All-time trading volume in USD
- __init__(address, display_name, account_value, all_time_pnl, all_time_roi, all_time_volume)
- Parameters
address (eth_typing.evm.HexAddress) –
display_name (str | None) –
account_value (decimal.Decimal) –
all_time_pnl (decimal.Decimal) –
all_time_roi (decimal.Decimal) –
all_time_volume (decimal.Decimal) –
- Return type
None
- 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
- 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'))
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 - 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 (decimal.Decimal | None) – 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.
- Returns
The confirmed
UserVaultEquityafter the deposit.- Raises
HypercoreDepositVerificationError – If the deposit cannot be verified within the timeout.
- 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_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_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_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
str | None
- 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