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_candle_snapshot(session, *, coin, ...)

Fetch up to 5,000 OHLCV candles for a single coin.

fetch_funding_history(session, *, coin, ...)

Fetch up to 500 funding-rate observations for a single coin.

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_perp_meta(session[, timeout])

Fetch the perpetual universe metadata ({"type": "meta"}).

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_abstraction_mode(session, user[, ...])

Read the Hyperliquid account abstraction mode for a user.

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.

HyperliquidCandle

A single OHLCV candle from the candleSnapshot Info endpoint.

HyperliquidFundingRate

A single funding-rate observation from the fundingHistory endpoint.

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.

class AssetPosition

Bases: object

A single perpetual position.

Returned inside PerpClearinghouseState.

__init__(coin, size, entry_price, unrealised_pnl, margin_used, position_value, liquidation_price)
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.

__init__(coin, token, total)
Parameters
Return type

None

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(note, /)

Add a note to the exception

with_traceback(tb, /)

Set self.__traceback__ to tb and return self.

class HyperliquidCandle

Bases: object

A single OHLCV candle from the candleSnapshot Info endpoint.

Prices and volume are stored as float for 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
Return type

None

class HyperliquidFundingRate

Bases: object

A single funding-rate observation from the fundingHistory endpoint.

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 float for direct pandas/numpy compatibility.

__init__(timestamp, coin, funding_rate, premium)
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().

__init__(address, display_name, account_value, all_time_pnl, all_time_roi, all_time_volume)
Parameters
Return type

None

class MarginSummary

Bases: object

Margin summary for a perpetual account.

Returned inside PerpClearinghouseState.

__init__(account_value, total_ntl_pos, total_raw_usd, total_margin_used)
Parameters
Return type

None

class PerpClearinghouseState

Bases: object

Perpetual account state for a HyperCore user.

Returned by fetch_perp_clearinghouse_state().

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

__init__(all_time_pnl, all_time_volume, first_activity_at)
Parameters
Return type

None

class SpotBalance

Bases: object

A single spot token balance on HyperCore.

Returned inside SpotClearinghouseState.

__init__(coin, token, total, hold)
Parameters
Return type

None

class SpotClearinghouseState

Bases: object

Spot account state for a HyperCore user.

Returned by fetch_spot_clearinghouse_state().

__init__(balances, evm_escrows)
Parameters
Return type

None

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}")
__init__(vault_address, equity, locked_until)
Parameters
Return type

None

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

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 candleSnapshot Info endpoint. The response is capped at HYPERLIQUID_CANDLE_SNAPSHOT_LIMIT candles 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 > 0 for 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
Returns

Candles in ascending time order. Empty list if no data.

Return type

list[eth_defi.hyperliquid.api.HyperliquidCandle]

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 fundingHistory Info endpoint. Hyperliquid pays funding every hour at 1/8 of the computed 8-hour rate, so HYPERLIQUID_FUNDING_HISTORY_LIMIT records ≈ 20 days per call. A 3-year history per symbol needs roughly 55 paginated requests. Callers needing long histories should use the higher-level strategycore.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.

Parameters
Returns

Funding-rate observations in ascending time order.

Return type

list[eth_defi.hyperliquid.api.HyperliquidFundingRate]

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]

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_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
Returns

Raw metadata dict.

Return type

dict

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

Optional[eth_defi.hyperliquid.api.PortfolioAllTimeData]

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_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
Returns

Hyperliquid account abstraction mode such as "standard" or "unifiedAccount".

Return type

str

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

Optional[eth_defi.hyperliquid.api.UserVaultEquity]

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

Optional[eth_defi.hyperliquid.api.UserVaultEquity]

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

Optional[str]

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 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 - max(tolerance, expected_deposit * relative_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