hyperliquid.session

Documentation for eth_defi.hyperliquid.session Python module.

HTTP session management for Hyperliquid API.

This module provides session creation with retry logic and rate limiting for Hyperliquid API requests.

Rate limiting is thread-safe using SQLite backend, so the session can be shared across multiple threads when using joblib.Parallel or similar.

The HyperliquidSession carries the API URL so that downstream functions do not need a separate server_url argument.

Proxy support

When a ProxyRotator is configured (via HyperliquidSession.configure_rotator() or the rotator parameter to create_hyperliquid_session()), the session automatically routes API requests through proxies. post_info() rotates to the next proxy on connection failures or rate-limit responses, and records failures via the rotator’s ProxyStateManager so that persistently bad proxies are skipped in future runs.

Rate limiting with proxies

Hyperliquid rate limits are per IP. When proxies are used, each worker thread gets its own session clone (via HyperliquidSession.clone_for_worker()) with an independent rate limiter so that each proxy IP can use its full rate allowance independently.

Module Attributes

HYPERLIQUID_API_URL

Hyperliquid mainnet API URL.

HYPERLIQUID_TESTNET_API_URL

Hyperliquid testnet API URL.

DEFAULT_RETRIES

Default number of retries for API requests

DEFAULT_BACKOFF_FACTOR

Default backoff factor for retries (seconds)

DEFAULT_REQUESTS_PER_SECOND

Default rate limit for Hyperliquid API requests per second.

MAX_PROXY_ROTATIONS

Maximum proxy rotation attempts in a single post_info() call before falling back to direct connection

Functions

create_hyperliquid_session([api_url, ...])

Create a HyperliquidSession configured for Hyperliquid API.

Classes

HyperliquidSession

A requests.Session subclass that carries the Hyperliquid API URL.

HYPERLIQUID_API_URL: str = 'https://api.hyperliquid.xyz'

Hyperliquid mainnet API URL.

HYPERLIQUID_TESTNET_API_URL: str = 'https://api.hyperliquid-testnet.xyz'

Hyperliquid testnet API URL.

HYPERLIQUID_RATE_LIMIT_SQLITE_DATABASE = PosixPath('/home/runner/.tradingstrategy/hyperliquid/rate-limit.sqlite')

Default SQLite database path for rate limiting state.

Using SQLite ensures thread-safe rate limiting across multiple threads when using joblib.Parallel or similar parallel processing.

DEFAULT_RETRIES = 5

Default number of retries for API requests

DEFAULT_BACKOFF_FACTOR = 0.5

Default backoff factor for retries (seconds)

DEFAULT_REQUESTS_PER_SECOND = 1.0

Default rate limit for Hyperliquid API requests per second.

Hyperliquid has a limit of 1200 weight per minute per IP. Most info endpoints have weight 20, so: 1200 / 20 = 60 requests/minute = 1 request/second.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits

MAX_PROXY_ROTATIONS = 3

Maximum proxy rotation attempts in a single post_info() call before falling back to direct connection

class HyperliquidSession

Bases: requests.sessions.Session

A requests.Session subclass that carries the Hyperliquid API URL.

All Hyperliquid API functions accept a HyperliquidSession and read api_url from it, removing the need for a separate server_url argument on every call.

The session optionally manages a ProxyRotator for automatic proxy rotation on failure. Use configure_rotator() or pass rotator to create_hyperliquid_session().

Use create_hyperliquid_session() to create instances.

__init__(api_url='https://api.hyperliquid.xyz')
Parameters

api_url (str) –

api_url: str

Hyperliquid API base URL (e.g. https://api.hyperliquid.xyz).

max_proxy_rotations: int

Maximum proxy rotations per post_info() call before giving up

configure_rotator(rotator)

Configure proxy rotation using a ProxyRotator.

The rotator provides thread-safe proxy selection and persistent failure tracking via its optional ProxyStateManager.

Parameters

rotator (eth_defi.event_reader.webshare.ProxyRotator) – A ProxyRotator (typically from load_proxy_rotator()).

Return type

None

property rotator: eth_defi.event_reader.webshare.ProxyRotator | None

The configured ProxyRotator, or None if proxies are disabled.

property proxy_urls: list[str]

All configured proxy URLs.

property proxy_count: int

Number of configured proxies.

property proxy_enabled: bool

Whether proxy support is enabled (at least one proxy configured).

property active_proxy_url: str | None

Currently active proxy URL, or None if proxies are disabled.

property proxy_failures: int

Rotation generation count (increases with each rotation).

property request_count: int

Total HTTP requests made via post_info().

property rotation_count: int

Total proxy rotations triggered by failures in post_info().

post_info(payload, timeout=30.0)

POST to the Hyperliquid /info endpoint with proxy rotation.

Uses the session’s configured proxy (if any). On connection errors or HTTP 429/5xx responses, rotates to the next proxy and retries. After MAX_PROXY_ROTATIONS consecutive failures in a single call, falls back to a direct (no-proxy) connection for the remainder of this request.

Failures are recorded via the rotator’s ProxyStateManager so that persistently bad proxies are skipped in future runs.

Parameters
  • payload (dict) – JSON request body for the /info endpoint.

  • timeout (float) – HTTP request timeout in seconds.

Returns

The requests.Response object.

Raises
  • requests.ConnectionError – If the request fails and no proxy rotation is available.

  • requests.Timeout – If the request times out and no proxy rotation is available.

Return type

requests.models.Response

clone_for_worker(proxy_start_index=0)

Create a lightweight clone for a worker thread.

The clone shares the same API URL. When proxies are configured, the clone gets its own ProxyRotator starting at proxy_start_index so that each worker hits a different proxy. The underlying ProxyStateManager is shared, so failures recorded by any worker are persisted globally.

Each clone gets its own independent rate limiter because Hyperliquid rate limits are per IP. When workers use different proxies, each proxy IP gets its full rate allowance.

Parameters

proxy_start_index (int) – Starting proxy index for this worker (typically the worker ordinal: 0, 1, 2, …).

Returns

A new HyperliquidSession with its own proxy rotation state and rate limiter.

Return type

eth_defi.hyperliquid.session.HyperliquidSession

close()

Closes all adapters and as such the session

delete(url, **kwargs)

Sends a DELETE request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

get(url, **kwargs)

Sends a GET request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

get_adapter(url)

Returns the appropriate connection adapter for the given URL.

Return type

requests.adapters.BaseAdapter

get_redirect_target(resp)

Receives a Response. Returns a redirect URI or None

head(url, **kwargs)

Sends a HEAD request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

merge_environment_settings(url, proxies, stream, verify, cert)

Check the environment and merge it with some settings.

Return type

dict

mount(prefix, adapter)

Registers a connection adapter to a prefix.

Adapters are sorted in descending order by prefix length.

options(url, **kwargs)

Sends a OPTIONS request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

patch(url, data=None, **kwargs)

Sends a PATCH request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

post(url, data=None, json=None, **kwargs)

Sends a POST request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

prepare_request(request)

Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session.

Parameters

requestRequest instance to prepare with this session’s settings.

Return type

requests.PreparedRequest

put(url, data=None, **kwargs)

Sends a PUT request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

rebuild_auth(prepared_request, response)

When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.

rebuild_method(prepared_request, response)

When being redirected we may want to change the method of the request based on certain specs or browser behavior.

rebuild_proxies(prepared_request, proxies)

This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).

This method also replaces the Proxy-Authorization header where necessary.

Return type

dict

request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)

Constructs a Request, prepares it and sends it. Returns Response object.

Parameters
  • method – method for the new Request object.

  • url – URL for the new Request object.

  • params – (optional) Dictionary or bytes to be sent in the query string for the Request.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • headers – (optional) Dictionary of HTTP Headers to send with the Request.

  • cookies – (optional) Dict or CookieJar object to send with the Request.

  • files – (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.

  • auth – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.

  • timeout (float or tuple) – (optional) How many seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.

  • allow_redirects (bool) – (optional) Set to True by default.

  • proxies – (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy.

  • hooks – (optional) Dictionary mapping hook name to one event or list of events, event must be callable.

  • stream – (optional) whether to immediately download the response content. Defaults to False.

  • verify – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True. When set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to False may be useful during local development or testing.

  • cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Return type

requests.Response

resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)

Receives a Response. Returns a generator of Responses or Requests.

send(request, **kwargs)

Send a given PreparedRequest.

Return type

requests.Response

should_strip_auth(old_url, new_url)

Decide whether Authorization header should be removed when redirecting

headers

A case-insensitive dictionary of headers to be sent on each Request sent from this Session.

auth

Default Authentication tuple or object to attach to Request.

proxies

Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each Request.

hooks

Event-handling hooks.

params

Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.

stream

Stream response content default.

verify

SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing.

cert

SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

max_redirects

Maximum number of redirects allowed. If the request exceeds this limit, a TooManyRedirects exception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30.

trust_env

Trust environment settings for proxy configuration, default authentication and similar.

cookies

A CookieJar containing all currently outstanding cookies set on this session. By default it is a RequestsCookieJar, but may be any other cookielib.CookieJar compatible object.

create_hyperliquid_session(api_url='https://api.hyperliquid.xyz', retries=5, backoff_factor=0.5, requests_per_second=1.0, pool_maxsize=32, rate_limit_db_path=PosixPath('/home/runner/.tradingstrategy/hyperliquid/rate-limit.sqlite'), rotator=None, verbose_throttling=None, proxy_failure_log_level=None)

Create a HyperliquidSession configured for Hyperliquid API.

The session is configured with:

  • The API URL stored in HyperliquidSession.api_url

  • Rate limiting to respect Hyperliquid API throttling (thread-safe via SQLite)

  • Retry logic for handling transient errors using exponential backoff

  • Optional proxy support with automatic rotation on failure

The rate limiter uses SQLite backend for thread-safe coordination across multiple threads (e.g., when using joblib.Parallel with threading backend).

When proxies are configured and workers are cloned via HyperliquidSession.clone_for_worker(), each worker gets its own rate limiter because Hyperliquid rate limits are per IP.

Example:

from eth_defi.hyperliquid.session import create_hyperliquid_session, HYPERLIQUID_TESTNET_API_URL

# Mainnet (default)
session = create_hyperliquid_session()

# Testnet
session = create_hyperliquid_session(api_url=HYPERLIQUID_TESTNET_API_URL)

# With Webshare rotator (persistent failure tracking via ProxyStateManager)
from eth_defi.event_reader.webshare import load_proxy_rotator

rotator = load_proxy_rotator()
session = create_hyperliquid_session(rotator=rotator)
Parameters
  • api_url (str) – Hyperliquid API base URL. Defaults to mainnet (HYPERLIQUID_API_URL). Pass HYPERLIQUID_TESTNET_API_URL for testnet.

  • retries (int) – Maximum number of retry attempts for failed requests

  • backoff_factor (float) – Backoff factor for exponential retry delays

  • requests_per_second (float) – Maximum requests per second to avoid rate limiting. Defaults to 1.0 based on Hyperliquid’s 1200 weight/minute limit with most info endpoints having weight 20.

  • pool_maxsize (int) – Maximum number of connections to keep in the connection pool. Should be at least as large as max_workers when using parallel requests. Defaults to 32.

  • rate_limit_db_path (pathlib.Path) – Path to SQLite database for storing rate limit state. Using SQLite ensures thread-safe rate limiting across multiple threads. Defaults to ~/.tradingstrategy/hyperliquid/rate-limit.sqlite.

  • rotator (eth_defi.event_reader.webshare.ProxyRotator | None) – Optional ProxyRotator (typically from load_proxy_rotator()). Provides proxy rotation with persistent failure tracking via ProxyStateManager.

  • verbose_throttling (bool | None) –

    Control rate-limit / throttling log messages.

    • None (default): off when proxies are used, on otherwise. With proxies, every worker thread hits the rate limiter independently and the resulting log spam is not useful.

    • True: always log throttling messages.

    • False: always suppress throttling messages.

  • proxy_failure_log_level (int | None) –

    Log level for proxy failure/rotation messages (from ProxyRotator, ProxyStateManager, and LoggingRetry).

    • None (default): logging.DEBUG when proxies are used, logging.WARNING otherwise.

    • Pass e.g. logging.DEBUG to suppress or logging.WARNING to always show.

Returns

Configured HyperliquidSession with rate limiting and retry logic

Return type

eth_defi.hyperliquid.session.HyperliquidSession