HyperliquidSession

Documentation for eth_defi.hyperliquid.session.HyperliquidSession Python class.

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.

Attributes summary

active_proxy_url

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

proxy_count

Number of configured proxies.

proxy_enabled

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

proxy_failures

Rotation generation count (increases with each rotation).

proxy_urls

All configured proxy URLs.

request_count

Total HTTP requests made via post_info().

rotation_count

Total proxy rotations triggered by failures in post_info().

rotator

The configured ProxyRotator, or None if proxies are disabled.

Methods summary

__init__([api_url])

clone_for_worker([proxy_start_index])

Create a lightweight clone for a worker thread.

close()

Closes all adapters and as such the session

configure_rotator(rotator)

Configure proxy rotation using a ProxyRotator.

delete(url, **kwargs)

Sends a DELETE request.

get(url, **kwargs)

Sends a GET request.

get_adapter(url)

Returns the appropriate connection adapter for the given URL.

get_redirect_target(resp)

Receives a Response.

head(url, **kwargs)

Sends a HEAD request.

merge_environment_settings(url, proxies, ...)

Check the environment and merge it with some settings.

mount(prefix, adapter)

Registers a connection adapter to a prefix.

options(url, **kwargs)

Sends a OPTIONS request.

patch(url[, data])

Sends a PATCH request.

post(url[, data, json])

Sends a POST request.

post_info(payload[, timeout])

POST to the Hyperliquid /info endpoint with graceful proxy rotation.

prepare_request(request)

Constructs a PreparedRequest for transmission and returns it.

put(url[, data])

Sends a PUT request.

rebuild_auth(prepared_request, response)

When being redirected we may want to strip authentication from the request to avoid leaking credentials.

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.

request(method, url[, params, data, ...])

Constructs a Request, prepares it and sends it.

resolve_redirects(resp, req[, stream, ...])

Receives a Response.

send(request, **kwargs)

Send a given PreparedRequest.

should_strip_auth(old_url, new_url)

Decide whether Authorization header should be removed when redirecting

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

api_url (str) –

property active_proxy_url: Optional[str]

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

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

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

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

post_info(payload, timeout=30.0)

POST to the Hyperliquid /info endpoint with graceful proxy rotation.

Uses the session’s configured proxy (if any). Rotation policy:

  • Rate-limit / backend overload responses (HTTP 429, 500, 502, 503, 504): rotate to the next proxy but do NOT record the current proxy as dead — it is only throttled, and will recover within minutes. This avoids shrinking the working pool across runs via the ProxyStateManager 14-day grace period.

  • Connection errors (requests.ConnectionError, requests.Timeout, OSError): rotate AND record the current proxy as dead via the state manager, because the proxy itself is unreachable.

After MAX_PROXY_ROTATIONS consecutive rotations in a single call, returns whatever response comes back (or re-raises the last exception) rather than continuing to rotate.

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

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

property proxy_count: int

Number of configured proxies.

property proxy_enabled: bool

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

property proxy_failures: int

Rotation generation count (increases with each rotation).

property proxy_urls: list[str]

All configured proxy URLs.

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

property request_count: int

Total HTTP requests made via post_info().

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.

property rotation_count: int

Total proxy rotations triggered by failures in post_info().

property rotator: Optional[eth_defi.event_reader.webshare.ProxyRotator]

The configured ProxyRotator, or None if proxies are disabled.

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