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

LEADERBOARD_URL

Hyperliquid stats-data leaderboard endpoint (public GET, no auth, 32K+ entries)

DEFAULT_VAULT_EQUITY_CACHE_TIMEOUT

Default cache timeout for fetch_user_vault_equity() in seconds (15 minutes).

Functions

fetch_leaderboard([timeout])

Fetch the full Hyperliquid trader leaderboard.

fetch_perp_clearinghouse_state(session, user)

Fetch a user's perpetual account state on HyperCore.

fetch_portfolio(session, address[, timeout])

Fetch all-time PnL and volume for any Hyperliquid address.

fetch_spot_clearinghouse_state(session, user)

Fetch a user's spot account state on HyperCore.

fetch_user_vault_equities(session, user[, ...])

Fetch a user's equity positions across all Hypercore vaults.

fetch_user_vault_equity(session, user, ...)

Fetch a user's equity in a single Hypercore vault, with caching.

fetch_vault_lockup_status(session, user, ...)

Fetch a user's vault position and check whether the lock-up has expired.

fetch_vault_name(session, vault_address[, ...])

Fetch the display name of a Hyperliquid vault.

wait_for_vault_deposit_confirmation(session, ...)

Wait for a vault deposit to be confirmed on HyperCore.

Classes

AssetPosition

A single perpetual position.

EvmEscrow

USDC bridged to HyperCore but held in EVM escrow.

LeaderboardEntry

A single trader from the Hyperliquid public leaderboard.

MarginSummary

Margin summary for a perpetual account.

PerpClearinghouseState

Perpetual account state for a HyperCore user.

PortfolioAllTimeData

All-time PnL and trading volume for a Hyperliquid address.

SpotBalance

A single spot token balance on HyperCore.

SpotClearinghouseState

Spot account state for a HyperCore user.

UserVaultEquity

A user's equity position in a single Hypercore vault.

Exceptions

HypercoreDepositVerificationError

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: Exception

Raised 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 by wait_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: object

A 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_until against the current UTC time.

Returns

True if 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
Return type

None

class SpotBalance

Bases: object

A single spot token balance on HyperCore.

Returned inside SpotClearinghouseState.

coin: str

Token symbol (e.g. "USDC", "HYPE")

token: int

Token index on HyperCore

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
Return type

None

class EvmEscrow

Bases: object

USDC bridged to HyperCore but held in EVM escrow.

When USDC is deposited via CoreDepositWallet.deposit(), it appears in the evmEscrows field of the spot clearinghouse state until the HyperCore action is processed.

Returned inside SpotClearinghouseState.

coin: str

Token symbol

token: int

Token index

total: decimal.Decimal

Escrowed amount

__init__(coin, token, total)
Parameters
Return type

None

class SpotClearinghouseState

Bases: object

Spot 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
Return type

None

class MarginSummary

Bases: object

Margin 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
Return type

None

class AssetPosition

Bases: object

A single perpetual position.

Returned inside PerpClearinghouseState.

coin: str

Perpetual market symbol (e.g. "BTC", "ETH")

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 (None if no position)

__init__(coin, size, entry_price, unrealised_pnl, margin_used, position_value, liquidation_price)
Parameters
Return type

None

class PerpClearinghouseState

Bases: object

Perpetual 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
Return type

None

class PortfolioAllTimeData

Bases: object

All-time PnL and trading volume for a Hyperliquid address.

Fetched from the portfolio info endpoint, which works for any address — not just leaderboard participants.

The pnlHistory array 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 pnlHistory entry — 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
Return type

None

class LeaderboardEntry

Bases: object

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

display_name: str | None

Display name chosen by the trader (None if not set)

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
Return type

None

fetch_user_vault_equities(session, user, timeout=10.0)

Fetch a user’s equity positions across all Hypercore vaults.

Calls the userVaultEquities info 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
Returns

List of vault equity positions. Empty list if the user has no vault deposits.

Return type

list[eth_defi.hyperliquid.api.UserVaultEquity]

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
Returns

The user’s equity in the vault, or None if the user has no position in the given vault.

Return type

eth_defi.hyperliquid.api.UserVaultEquity | None

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 via UserVaultEquity.is_lockup_expired and UserVaultEquity.lockup_remaining.

Returns None if 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
Returns

The user’s vault equity with lock-up properties, or None if no position.

Return type

eth_defi.hyperliquid.api.UserVaultEquity | None

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 vaultTransfer action succeeds on HyperEVM, HyperCore may take several seconds to process the deposit. This function polls userVaultEquities until 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
Returns

The confirmed UserVaultEquity after the deposit.

Raises

HypercoreDepositVerificationError – If the deposit cannot be verified within the timeout.

Return type

eth_defi.hyperliquid.api.UserVaultEquity

fetch_spot_clearinghouse_state(session, user, timeout=10.0)

Fetch a user’s spot account state on HyperCore.

Calls the spotClearinghouseState info endpoint to retrieve spot token balances and EVM escrow amounts.

Parameters
Returns

Spot clearinghouse state with balances and EVM escrows.

Return type

eth_defi.hyperliquid.api.SpotClearinghouseState

fetch_perp_clearinghouse_state(session, user, timeout=10.0)

Fetch a user’s perpetual account state on HyperCore.

Calls the clearinghouseState info endpoint to retrieve margin summary, withdrawable balance, and open positions.

Parameters
Returns

Perpetual clearinghouse state with margin info and positions.

Return type

eth_defi.hyperliquid.api.PerpClearinghouseState

fetch_portfolio(session, address, timeout=15.0)

Fetch all-time PnL and volume for any Hyperliquid address.

Calls the portfolio info 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.9738

The raw API response is an array of [period, data] pairs:

[["day", {"accountValueHistory": [...], "pnlHistory": [...], "vlm": "..."}], ["allTime", {"accountValueHistory": [...], "pnlHistory": [[ts, pnl], ...], "vlm": "1893425014.9738"}]]
Parameters
Returns

All-time PnL, volume, and first activity timestamp, or None on network/API error.

Return type

eth_defi.hyperliquid.api.PortfolioAllTimeData | None

fetch_vault_name(session, vault_address, timeout=10.0)

Fetch the display name of a Hyperliquid vault.

Makes a lightweight vaultDetails API call and extracts only the vault name. Returns None if 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
Returns

Vault display name, or None if 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/leaderboard endpoint 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.4523

The 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

dict[str, eth_defi.hyperliquid.api.LeaderboardEntry]