### Install Dependencies with Make Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/README.md Use the make install command to set up project dependencies. This command is part of the Makefile for streamlined development workflows. ```bash make install ``` -------------------------------- ### Install hyperliquid-python-sdk Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/README.md Install the SDK using pip. Ensure you are using a compatible Python version. ```bash pip install hyperliquid-python-sdk ``` -------------------------------- ### Makefile Usage Examples Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/README.md A list of common CLI commands available through the Makefile for development tasks such as running checks, cleaning, installing, linting, and testing. ```bash check-safety Run safety checks on dependencies cleanup Cleanup project install Install dependencies from poetry.lock install-types Find and install additional types for mypy lint Alias for the pre-commit target lockfile-update Update poetry.lock lockfile-update-full Fully regenerate poetry.lock poetry-download Download and install poetry pre-commit Run linters + formatters via pre-commit, run "make pre-commit hook=black" to run only black test Run tests with pytest update-dev-deps Update development dependencies to latest versions ``` -------------------------------- ### Minimal Info Setup Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Initialize an Info client with default settings, connecting to the mainnet API. ```python from hyperliquid.info import Info info = Info() ``` -------------------------------- ### Wallet Setup from Private Key Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Demonstrates how to set up a wallet for the Exchange client using a private key string. Ensure the private key is kept secure. ```python from eth_account import Account from hyperliquid.exchange import Exchange from hyperliquid.utils.constants import TESTNET_API_URL # Load from key string wallet = Account.from_key("0x...") exchange = Exchange(wallet, TESTNET_API_URL) ``` -------------------------------- ### Wallet Setup from Keystore File Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Shows how to load a wallet from a keystore JSON file using a password. This method is suitable for securely storing private keys. ```python from eth_account import Account from hyperliquid.exchange import Exchange # Load from encrypted keystore with open("keystore.json") as f: wallet = Account.from_key(Account.decrypt("keystore.json", "password")) exchange = Exchange(wallet) ``` -------------------------------- ### Info Setup with Pre-cached Metadata Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Initialize an Info client using pre-cached metadata to avoid redundant API calls for market information. ```python from hyperliquid.info import Info # First call caches metadata info1 = Info(skip_ws=True) meta = info1.meta() spot_meta = info1.spot_meta() # Second instance reuses metadata (saves API calls) info2 = Info(meta=meta, spot_meta=spot_meta) ``` -------------------------------- ### Testnet Setup with Exchange Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initializes a new test account and sets up the Exchange object for interacting with the Hyperliquid testnet. Ensure to fund the account via the testnet faucet. ```python from eth_account import Account from hyperliquid.exchange import Exchange from hyperliquid.utils.constants import TESTNET_API_URL # New test account wallet = Account.create() exchange = Exchange(wallet, TESTNET_API_URL) # Fund and test # (Testnet faucet at https://app.hyperliquid-testnet.xyz) ``` -------------------------------- ### Agent Account Setup and Usage Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Demonstrates how to approve an agent and then use it to perform trades. This involves approving the agent first, then creating a new `Exchange` instance associated with the agent's wallet. ```APIDOC ## Agent Account ### Description Demonstrates how to approve an agent and then use it to perform trades. This involves approving the agent first, then creating a new `Exchange` instance associated with the agent's wallet. ### Methods 1. **Approve Agent** ```python exchange.approve_agent(name="my-agent") ``` - **name** (string): The name for the agent. - **Returns**: A tuple containing the response and the agent's private key. 2. **Trade with Agent** ```python agent_wallet = Account.from_key(agent_key) agent_exchange = Exchange(agent_wallet, account_address=wallet.address) ``` - **agent_key**: The private key obtained from `approve_agent`. - **account_address**: The address of the main account to associate the agent with. ``` -------------------------------- ### Info Setup with Custom Timeout Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Initialize an Info client with a custom request timeout to control how long API calls will wait for a response. ```python from hyperliquid.info import Info # 5 second timeout for all API calls info = Info(timeout=5.0) ``` -------------------------------- ### Get Spot and Perpetual Balances Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve balances for both spot and perpetual wallets. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') balances = exchange.get_balances() print(balances) ``` -------------------------------- ### Info Setup for Multiple Perpetual DEXs Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Configure an Info client to load multiple perpetual DEXs, including the default and custom builder-deployed DEXs. ```python from hyperliquid.info import Info from hyperliquid.utils.constants import MAINNET_API_URL # Load default DEX and builder-deployed DEXs info = Info( MAINNET_API_URL, perp_dexs=["", "myperpdex1", "myperpdex2"] ) ``` -------------------------------- ### Get Metadata Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve metadata for all available assets on the exchange. ```python from hyperliquid.info import Info info = Info() metadata = info.get_metadata() print(metadata) ``` -------------------------------- ### Initialize Info Module Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/modules-overview.md The Info module is initialized by calling `Info.__init__()`. This process involves setting up the API connection, starting the WebSocket manager if enabled, fetching metadata, and building internal mapping dictionaries. ```python Info.__init__() ├── API.__init__() # Set base_url, session ├── WebsocketManager.__init__() & start() # If not skip_ws ├── spot_meta() # Fetch if not provided ├── set_perp_meta() # For each perp DEX └── Build mapping dicts ├── coin_to_asset ├── name_to_coin └── asset_to_sz_decimals ``` -------------------------------- ### Get Prices Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve current market prices for specified assets. ```python from hyperliquid.info import Info info = Info() # Get prices for USDC and SOL prices = info.get_prices(assets=['USDC', 'SOL']) print(prices) ``` -------------------------------- ### Get All Mid Prices Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Fetch the current mid-prices for all available trading pairs. ```python mids = info.all_mids() btc_price = float(mids["BTC"]) ``` -------------------------------- ### Minimal Imports for Hyperliquid SDK Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/README.md Use these imports for basic functionality. Ensure you have the necessary libraries installed. ```python from hyperliquid.info import Info from hyperliquid.exchange import Exchange from eth_account import Account ``` -------------------------------- ### spot_deploy_register_hyperliquidity Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-exchange.md Initializes automated market making (hyperliquidity) for a registered spot pair. This method sets up the parameters for automated liquidity provision, including the starting price, order size, and the number of orders and price levels to seed. ```APIDOC ## spot_deploy_register_hyperliquidity ### Description Initializes automated market making (hyperliquidity) for a spot pair. ### Method Signature ```python def spot_deploy_register_hyperliquidity( self, spot: int, start_px: float, order_sz: float, n_orders: int, n_seeded_levels: Optional[int] ) -> Any ``` ### Parameters #### Path Parameters - **spot** (int) - Required - Spot pair ID. - **start_px** (float) - Required - Starting price for orders. - **order_sz** (float) - Required - Size per order. - **n_orders** (int) - Required - Number of orders to seed. - **n_seeded_levels** (Optional[int]) - Optional - Number of price levels to seed. ### Returns Response confirming hyperliquidity setup. ``` -------------------------------- ### Get User Fees Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Retrieve the fee schedule, referral discount, and volume tiers for a given user address. ```json { "type": "userFees", "user": "0x..." } ``` -------------------------------- ### Example Limit and Trigger Order Creation Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/types.md Illustrates how to create instances of limit and trigger orders using the defined TypedDicts. 'Gtc' is a valid Time In Force (TIF) for limit orders, and 'tp' is a valid value for take profit/stop loss in trigger orders. ```python limit_order = {"limit": {"tif": "Gtc"}} trigger_order = {"trigger": {"triggerPx": 50000.0, "isMarket": True, "tpsl": "tp"}} ``` -------------------------------- ### Get Historical Funding Rates Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical funding rates for perpetual swap contracts. ```python from hyperliquid.info import Info info = Info() funding_rates = info.get_funding_rates(asset='BTC') print(funding_rates) ``` -------------------------------- ### Get Candlesticks Snapshot Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Fetch historical candlestick data for an asset. Requires asset symbol, interval, start time, and end time. ```python candles = info.candles_snapshot( "BTC", interval="1h", startTime=1234567890000, endTime=1234567900000 ) ``` -------------------------------- ### Get Funding History Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieve the funding history for a specified asset within a given time range. Requires asset symbol, start time, and end time. ```python history = info.funding_history( "BTC", startTime=1234567890000, endTime=1234567900000 ) ``` -------------------------------- ### Get Funding History Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-info.md Retrieves funding rate history for a perpetual coin. Requires coin name and start time in Unix milliseconds. End time is optional. ```python def funding_history(self, name: str, startTime: int, endTime: Optional[int] = None) -> Any: ``` -------------------------------- ### Get Funding History Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Fetch historical funding rates and premiums for a given coin within a specified time range. Requires start and end timestamps in milliseconds. ```json { "type": "fundingHistory", "coin": "BTC", "startTime": 1234567890000, "endTime": 1234567900000 } ``` -------------------------------- ### Get Candle Snapshot Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Retrieve historical OHLCV (Open, High, Low, Close, Volume) data for a specified coin and interval. Requires start and end timestamps in milliseconds. ```json { "type": "candleSnapshot", "req": { "coin": "BTC", "interval": "1h", "startTime": 1234567890000, "endTime": 1234567900000 } } ``` -------------------------------- ### Handle Specific Error Codes with Hyperliquid SDK Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md This example demonstrates how to catch a ClientError and check for specific error codes like 'INVALID_LEVERAGE' or 'INSUFFICIENT_MARGIN' to provide tailored user feedback. ```python try: exchange.update_leverage(100, "BTC") except ClientError as e: if e.error_code == "INVALID_LEVERAGE": print("Leverage too high") elif e.error_code == "INSUFFICIENT_MARGIN": print("Not enough margin") else: raise ``` -------------------------------- ### Get User Funding History Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-info.md Retrieves funding payments received or paid by a user. Requires the user's onchain address and start time in Unix milliseconds. End time is optional. ```python def user_funding_history(self, user: str, startTime: int, endTime: Optional[int] = None) -> Any: ``` -------------------------------- ### Modify Bulk Orders with Hyperliquid SDK Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md This example shows how to modify multiple existing orders in a single request. Each modification requires the order ID and the updated order details. ```python modifies = [ { "oid": 12345, "order": { "coin": "BTC", "is_buy": True, "sz": 0.2, "limit_px": 41000.0, "order_type": {"limit": {"tif": "Gtc"}}, "reduce_only": False, }, }, ] response = exchange.bulk_modify_orders_new(modifies) ``` -------------------------------- ### Initialize Info Module Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Instantiate the Info module for interacting with Hyperliquid's data endpoints. This is a minimal configuration. ```python from hyperliquid.info import Info info = Info() ``` -------------------------------- ### Example WebSocket Client Error Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md An example of a client error response, specifically indicating insufficient margin for an order. ```json { "code": "INSUFFICIENT_MARGIN", "msg": "Not enough collateral for order", "data": {} } ``` -------------------------------- ### Initialize Info Instance with Metadata Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Fetches metadata upon initialization. Use this single instance for all subsequent queries to avoid redundant fetches. ```python from hyperliquid.info import Info from hyperliquid.utils.constants import MAINNET_API_URL info = Info(MAINNET_API_URL) # Fetches meta on init # Use info for all queries ``` -------------------------------- ### Get Prices Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieves the mid-prices for all available assets. ```APIDOC ## Get Prices ### Description Retrieves the mid-prices for all available assets. ### Code ```python mids = info.all_mids() btc_price = float(mids["BTC"]) ``` ``` -------------------------------- ### Configure Testnet Connection Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Set up the SDK for testnet trading. Loads a private key from a .env file and initializes Info and Exchange objects for the testnet API. ```python from eth_account import Account from hyperliquid.info import Info from hyperliquid.exchange import Exchange from hyperliquid.utils.constants import TESTNET_API_URL # Load wallet with open(".env") as f: key = f.read().strip() wallet = Account.from_key(key) # Info for queries info = Info(TESTNET_API_URL, timeout=5.0) # Exchange for trading exchange = Exchange(wallet, TESTNET_API_URL, timeout=5.0) # Check configuration print(f"Address: {wallet.address}") print(f"Network: Testnet") ``` -------------------------------- ### Configure Production Connection Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Set up the SDK for production trading. Loads a private key and vault address from environment variables. Initializes Info and Exchange objects with cached metadata for the mainnet API. ```python from eth_account import Account from hyperliquid.info import Info from hyperliquid.exchange import Exchange from hyperliquid.utils.constants import MAINNET_API_URL import os # Load wallet securely private_key = os.getenv("HYPERLIQUID_KEY") if not private_key: raise ValueError("HYPERLIQUID_KEY not set") wallet = Account.from_key(private_key) # Cache metadata meta = Info(skip_ws=True).meta() spot_meta = Info(skip_ws=True).spot_meta() # Info with WebSocket info = Info( MAINNET_API_URL, meta=meta, spot_meta=spot_meta, timeout=10.0 ) # Exchange with vault vault = os.getenv("VAULT_ADDRESS") exchange = Exchange( wallet, MAINNET_API_URL, meta=meta, spot_meta=spot_meta, vault_address=vault, timeout=10.0 ) ``` -------------------------------- ### Get Historical Fees Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical fee data for the account. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') historical_fees = exchange.get_historical_fees() print(historical_fees) ``` -------------------------------- ### Initialize Exchange Instance Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-exchange.md Instantiate the Exchange class with a wallet and optional parameters like base URL. The wallet is used for signing all actions. ```python from eth_account import Account from hyperliquid.exchange import Exchange from hyperliquid.utils import constants wallet = Account.from_key("0x...") exchange = Exchange(wallet, constants.TESTNET_API_URL) ``` -------------------------------- ### Get Fills Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve a list of historical trade fills for the account. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') fills = exchange.get_fills() print(fills) ``` -------------------------------- ### Get Fills Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieves a list of all executed trades (fills) for a given account. ```APIDOC ## Get Fills ### Description Retrieves a list of all executed trades (fills) for a given account. ### Code ```python fills = info.user_fills("0x...") ``` ``` -------------------------------- ### Get Open Orders Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieves a list of all open orders for a given account. ```APIDOC ## Get Open Orders ### Description Retrieves a list of all open orders for a given account. ### Code ```python orders = info.open_orders("0x...") ``` ``` -------------------------------- ### Initialize Exchange Object Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Set up the Exchange object for trading operations. Requires an Ethereum account private key. ```python from eth_account import Account from hyperliquid.exchange import Exchange wallet = Account.from_key("0x...") exchange = Exchange(wallet) ``` -------------------------------- ### Initialize Info Class Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-info.md Initializes an Info instance for querying market and account data. Automatically loads metadata and sets up WebSocket if not skipped. The WebSocket manager runs in a background thread. ```python Info( base_url: Optional[str] = None, skip_ws: Optional[bool] = False, meta: Optional[Meta] = None, spot_meta: Optional[SpotMeta] = None, perp_dexs: Optional[List[str]] = None, timeout: Optional[float] = None ) ``` -------------------------------- ### Configure Info Client with Custom Endpoint Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initialize the Info client to connect to a custom API endpoint. ```python info = Info("https://my-proxy.example.com") ``` -------------------------------- ### Get Metadata for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve metadata for a single, specified asset. ```python from hyperliquid.info import Info info = Info() metadata = info.get_metadata_for_asset('ETH') print(metadata) ``` -------------------------------- ### Basic Info Initialization Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/modules-overview.md Initializes the Info object for accessing market data. Use `skip_ws=True` if real-time WebSocket updates are not needed. ```python from hyperliquid.info import Info from hyperliquid.utils.constants import MAINNET_API_URL info = Info(MAINNET_API_URL, skip_ws=True) ``` -------------------------------- ### Info Constructor Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-info.md Initializes an Info instance for querying market and account data. Automatically loads metadata for coin-to-asset mapping and sets up WebSocket if not skipped. The WebSocket manager runs in a background thread. ```APIDOC ## Info Class ### Constructor ```python Info( base_url: Optional[str] = None, skip_ws: Optional[bool] = False, meta: Optional[Meta] = None, spot_meta: Optional[SpotMeta] = None, perp_dexs: Optional[List[str]] = None, timeout: Optional[float] = None ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | base_url | Optional[str] | MAINNET_API_URL | HTTP API endpoint URL. Use constants.TESTNET_API_URL for testnet. | | skip_ws | Optional[bool] | False | If True, disables WebSocket connection and subscriptions. | | meta | Optional[Meta] | None | Pre-cached perpetual market metadata. If None, fetches automatically. | | spot_meta | Optional[SpotMeta] | None | Pre-cached spot market metadata. If None, fetches automatically. | | perp_dexs | Optional[List[str]] | None | List of perpetual DEX names to initialize. If None, uses default (" "). | | timeout | Optional[float] | None | Request timeout in seconds. | ### Returns Info instance ``` -------------------------------- ### Get Open Orders Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve a list of all currently open orders for the account. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') open_orders = exchange.get_open_orders() print(open_orders) ``` -------------------------------- ### Get Account Value Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieves the current account value from the user's state. ```APIDOC ## Get Account Value ### Description Retrieves the current account value from the user's state. ### Code ```python info = Info() state = info.user_state("0x...") account_value = state["crossMarginSummary"]["accountValue"] ``` ``` -------------------------------- ### Query Sub-Accounts Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Get a list of sub-account addresses associated with a primary user address. ```json { "type": "subAccounts", "user": "0x..." } ``` -------------------------------- ### Initialize Info Module Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/modules-overview.md Create an instance of the Info module for read-only queries. It can optionally skip WebSocket initialization. ```python from hyperliquid.info import Info info = Info() mids = info.all_mids() state = info.user_state("0x...") sub_id = info.subscribe({"type": "l2Book", "coin": "BTC"}, callback) ``` -------------------------------- ### Initialize and Use Info Class Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/README.md Instantiate the Info class to interact with read-only market data and user states. WebSocket is enabled by default for live updates. Remember to disconnect the WebSocket when done. ```python from hyperliquid.info import Info info = Info() # WebSocket enabled by default # Query user positions state = info.user_state("0x...") # Get market data mids = info.all_mids() l2 = info.l2_snapshot("BTC") # Subscribe to live updates sub_id = info.subscribe({"type": "l2Book", "coin": "BTC"}, callback) # Clean up info.disconnect_websocket() ``` -------------------------------- ### Get Account Type Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Determine the type of account (e.g., vault, agent, sub-account). ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') account_type = exchange.get_account_type() print(account_type) ``` -------------------------------- ### Configuration: Testnet Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initialize the SDK client to connect to the Hyperliquid testnet environment. ```APIDOC ### Testnet ```python from hyperliquid.utils.constants import TESTNET_API_URL info = Info(TESTNET_API_URL) exchange = Exchange(wallet, TESTNET_API_URL) ``` ``` -------------------------------- ### Get Leverage for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve the current leverage setting for a specific asset. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') leverage = exchange.get_leverage(asset='ETH') print(leverage) ``` -------------------------------- ### Configure Info and Exchange Clients with API URLs Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Instantiate Info and Exchange clients using predefined constants or custom endpoints for different Hyperliquid networks. ```python from hyperliquid.info import Info from hyperliquid.exchange import Exchange from hyperliquid.utils.constants import TESTNET_API_URL, MAINNET_API_URL # Testnet info_testnet = Info(TESTNET_API_URL) # Mainnet exchange_mainnet = Exchange(wallet, MAINNET_API_URL) # Custom endpoint info_custom = Info("https://my-proxy.example.com") ``` -------------------------------- ### Get Fees for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical fee data for a particular asset. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') historical_fees = exchange.get_historical_fees(asset='BTC') print(historical_fees) ``` -------------------------------- ### Get Current Time in Milliseconds Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Obtain the current timestamp in milliseconds since the Unix epoch. ```python from hyperliquid.utils.signing import get_timestamp_ms now = get_timestamp_ms() ``` -------------------------------- ### Initialize and Use Exchange Class for Trading Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/README.md Set up the Exchange class using an Ethereum account for executing trades. This class allows placing orders, canceling them, and closing positions. ```python from eth_account import Account from hyperliquid.exchange import Exchange wallet = Account.from_key("0x...") exchange = Exchange(wallet) # Place order response = exchange.order( "BTC", is_buy=True, sz=0.1, limit_px=40000.0, order_type={"limit": {"tif": "Gtc"}} ) # Cancel order exchange.cancel("BTC", oid=12345) # Close position exchange.market_close("BTC", slippage=0.02) ``` -------------------------------- ### Multi-DEX Initialization and Usage Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Allows initializing the SDK to interact with specific Decentralized Exchanges (DEXs) and performing operations on them. ```APIDOC ## Multiple DEXs ### Description Allows initializing the SDK to interact with specific Decentralized Exchanges (DEXs) and performing operations on them. ### Methods 1. **Initialize with DEXs** ```python info = Info(perp_dexs=["", "dex1", "dex2"]) exchange = Exchange(wallet, perp_dexs=["", "dex1", "dex2"]) ``` - **perp_dexs** (list of strings): A list of DEX names to initialize with. An empty string `""` typically refers to the default or main DEX. 2. **Query DEX-Specific Data** ```python state = info.user_state("0x...", dex="dex1") mids = info.all_mids(dex="dex1") ``` - **dex** (string): The name of the DEX to query data from. 3. **Trade on Specific DEX** ```python response = exchange.order("dex1:BTC", is_buy=True, sz=0.1, limit_px=40000.0, order_type={"limit": {"tif": "Gtc"}}) ``` - **Order Format**: Use "dexname:coin" format for specifying the asset (e.g., "dex1:BTC"). ``` -------------------------------- ### Get L2 Book Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieves the Level 2 order book snapshot for a specified asset. ```APIDOC ## Get L2 Book ### Description Retrieves the Level 2 order book snapshot for a specified asset. ### Code ```python l2 = info.l2_snapshot("BTC") bids = l2["levels"][0] asks = l2["levels"][1] ``` ``` -------------------------------- ### Initialize API Client Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/modules-overview.md Instantiate the base API client for interacting with Hyperliquid servers. Requires the base URL and an optional timeout value. ```python from hyperliquid.api import API api = API("https://api.hyperliquid.xyz", timeout=5.0) response = api.post("/info", {"type": "meta"}) ``` -------------------------------- ### Get Positions for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve current open position details for a specific asset. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') positions = exchange.get_positions(asset='BTC') print(positions) ``` -------------------------------- ### Get Fills for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical trade fill data for a specific asset. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') fills = exchange.get_fills(asset='SOL') print(fills) ``` -------------------------------- ### Timestamp Utility Function Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Get the current Unix timestamp in milliseconds, useful for time-sensitive operations. ```python from hyperliquid.utils import current_time timestamp_ms = current_time() print(timestamp_ms) ``` -------------------------------- ### Connect to Testnet Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initialize Info and Exchange clients to connect to the Hyperliquid testnet using a predefined URL. Requires a wallet object for the Exchange client. ```python from hyperliquid.utils.constants import TESTNET_API_URL info = Info(TESTNET_API_URL) exchange = Exchange(wallet, TESTNET_API_URL) ``` -------------------------------- ### List Available Assets and Decimals Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Fetch the market metadata using `info.meta()` and iterate through the 'universe' to print each asset's name and its decimal places. ```python meta = info.meta() for asset_info in meta["universe"]: print(f"{asset_info['name']}: {asset_info['szDecimals']} decimals") ``` -------------------------------- ### Initialize Info Object Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Instantiate the Info object for read-only queries. Supports mainnet, testnet, and disabling WebSocket. ```python from hyperliquid.info import Info from hyperliquid.utils.constants import MAINNET_API_URL, TESTNET_API_URL # Mainnet info = Info() # Testnet info = Info(TESTNET_API_URL) # No WebSocket info = Info(skip_ws=True) ``` -------------------------------- ### Approve and Trade with Agent Account Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md First, approve the agent using `approve_agent`. Then, create an agent wallet from the returned key and initialize a new Exchange object for trading with the agent. ```python # First approve agent response, agent_key = exchange.approve_agent(name="my-agent") # Trade with agent agent_wallet = Account.from_key(agent_key) agent_exchange = Exchange( agent_wallet, account_address=wallet.address ) ``` -------------------------------- ### Utility: Current Time in Milliseconds Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Get the current timestamp in milliseconds, formatted for use with the Hyperliquid API. ```APIDOC ## Utility Functions ### Current Time in Milliseconds ```python from hyperliquid.utils.signing import get_timestamp_ms now = get_timestamp_ms() ``` ``` -------------------------------- ### Configure Info Client Timeout Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initialize the Info client with a custom request timeout in seconds. ```python info = Info(timeout=5.0) ``` -------------------------------- ### Fetch Market Metadata Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initialize an `Info` object to retrieve market metadata. Use `meta()` for general metadata and `spot_meta()` for spot market-specific data. ```python info = Info() meta = info.meta() spot_meta = info.spot_meta() ``` -------------------------------- ### User Fees Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Get the fee schedule for a user's account, including maker and taker rates. ```APIDOC ## User Fees ```python fees = info.user_fees("0x...") print(f"Maker rate: {fees['feeSchedule']['add']}") print(f"Taker rate: {fees['feeSchedule']['cross']}") ``` ``` -------------------------------- ### Place Order with Exchange Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/modules-overview.md Placing an order involves calling `Exchange.order()`. The request is prepared, signed with the L1 action, and sent to the `/exchange` endpoint via a POST request. The response contains the order confirmation. ```python Exchange.order() → order_request_to_order_wire() # Prepare → order_wires_to_order_action() # Build action → sign_l1_action() # Sign with wallet → API.post("/exchange", signed_payload) → Response parsed ← Order confirmation ``` -------------------------------- ### Get Open Orders for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve a list of currently open orders for a specific asset. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') open_orders = exchange.get_open_orders(asset='ETH') print(open_orders) ``` -------------------------------- ### Get Response Details Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Access detailed information about the API response, including status codes and headers. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') # The place_order method returns response details response = exchange.place_order(asset='USDC', side='BUY', quantity=1, price=1.0) print(f"Status Code: {response['status_code']}") print(f"Response Body: {response['body']}") ``` -------------------------------- ### Initialize Exchange Module Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Instantiate the Exchange module for trading operations. Requires API keys and network configuration. ```python from hyperliquid.exchange import Exchange # For testnet: exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') # For mainnet: # exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='mainnet') ``` -------------------------------- ### Get Historical Fills Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical trade fill data for the account, optionally filtered by asset. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') historical_fills = exchange.get_historical_fills(asset='ETH') print(historical_fills) ``` -------------------------------- ### Initialize Multiple Instances with Shared Metadata Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Fetch metadata once and reuse it across multiple Info and Exchange instances. This is useful when you need to initialize several components that rely on the same metadata. ```python from hyperliquid.info import Info from hyperliquid.exchange import Exchange from hyperliquid.utils.constants import MAINNET_API_URL # Fetch metadata once info = Info(skip_ws=True) meta = info.meta() spot_meta = info.spot_meta() # Reuse in other instances info2 = Info(MAINNET_API_URL, meta=meta, spot_meta=spot_meta) exchange = Exchange(wallet, MAINNET_API_URL, meta=meta, spot_meta=spot_meta) ``` -------------------------------- ### Get Candlesticks for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical OHLCV candle data for a single asset and specified interval. ```python from hyperliquid.info import Info info = Info() candles = info.get_candlesticks(asset='SOL', interval='15m') print(candles) ``` -------------------------------- ### Initialize Hyperliquid Info for Testnet Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/README.md Initializes the Info class for interacting with the Hyperliquid testnet. Set skip_ws to True to disable WebSocket subscriptions if not needed. ```python from hyperliquid.info import Info from hyperliquid.utils.constants import TESTNET_API_URL info = Info(TESTNET_API_URL, skip_ws=True) ``` -------------------------------- ### Get Funding Rate for Specific Asset Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve the current funding rate for a particular perpetual swap asset. ```python from hyperliquid.info import Info info = Info() funding_rate = info.get_funding_rate(asset='ETH') print(funding_rate) ``` -------------------------------- ### Project File Structure Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/README.md This outlines the directory structure of the Hyperliquid Python SDK documentation, indicating the location of various reference files. ```bash output/ ├── README.md ← You are here ├── api-reference-info.md ├── api-reference-exchange.md ├── types.md ├── endpoints.md ├── errors.md ├── configuration.md ├── modules-overview.md └── quick-reference.md ``` -------------------------------- ### Get Historical Candles for Multiple Assets Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical OHLCV candle data for multiple assets simultaneously. ```python from hyperliquid.info import Info info = Info() candles = info.get_candlesticks(assets=['BTC', 'ETH'], interval='1d') print(candles) ``` -------------------------------- ### Import from Top Level and Modules Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/modules-overview.md Demonstrates how to import core components like Info, Exchange, and Cloid either from the top level of the SDK or directly from their respective modules. ```python # Import from top level from hyperliquid import Info, Exchange, Cloid # Or from modules from hyperliquid.info import Info from hyperliquid.exchange import Exchange from hyperliquid.utils.types import Cloid ``` -------------------------------- ### Get Historical Funding Rates for Multiple Assets Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical funding rates for a list of specified assets. ```python from hyperliquid.info import Info info = Info() funding_rates = info.get_funding_rates(assets=['BTC', 'ETH']) print(funding_rates) ``` -------------------------------- ### Configure Multi-DEX Trading Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Initialize the SDK to trade across multiple DEXs. Discovers available DEXs and initializes the Exchange object to interact with all of them. ```python from hyperliquid.info import Info from hyperliquid.exchange import Exchange # Discover available DEXs info = Info(skip_ws=True) dex_list = info.perp_dexs() dex_names = [dex["name"] for dex in dex_list] # Initialize with all DEXs exchange = Exchange( wallet, perp_dexs=dex_names ) # Query specific DEX for dex_name in dex_names: state = info.user_state(wallet.address, dex=dex_name) print(f"{dex_name}: {state['crossMarginSummary']['accountValue']}") ``` -------------------------------- ### Testnet Initialization Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Configure the Exchange module to connect to the Hyperliquid testnet environment. ```python from hyperliquid.exchange import Exchange # Initialize for testnet exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') ``` -------------------------------- ### Get Account Value Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve the total value of the user's account, including margin and unrealized PNL. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_PRIVATE_KEY', network='testnet') account_value = exchange.get_account_value() print(account_value) ``` -------------------------------- ### Create and Transfer to Sub-Account Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Use `create_sub_account` to create a new sub-account. Use `sub_account_transfer` to deposit funds into a sub-account, specifying the sub-account user address and the USD amount. ```python # Create response = exchange.create_sub_account("trading-bot") # Transfer to exchange.sub_account_transfer( sub_account_user="0x...", is_deposit=True, usd=1000 ) ``` -------------------------------- ### Get Delegator History Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Fetch a comprehensive history of a user's staking activities, including timestamps and transaction details. ```json { "type": "delegatorHistory", "user": "0x..." } ``` -------------------------------- ### Place Bulk Orders with Hyperliquid SDK Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Use this snippet to submit multiple orders simultaneously. Each order in the list can have different parameters, including coin, side, size, price, and order type. ```python orders = [ { "coin": "BTC", "is_buy": True, "sz": 0.1, "limit_px": 40000.0, "order_type": {"limit": {"tif": "Gtc"}}, "reduce_only": False, }, { "coin": "ETH", "is_buy": False, "sz": 1.0, "limit_px": 2500.0, "order_type": {"limit": {"tif": "Ioc"}}, "reduce_only": True, }, ] response = exchange.bulk_orders(orders) ``` -------------------------------- ### Get Delegations Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Retrieve details of a user's current staking delegations, including the validator, amount, and lock-up period. ```json { "type": "delegations", "user": "0x..." } ``` -------------------------------- ### Get Extra Agents Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Retrieve information about extra agents associated with a user, including their name, address, and validity period. ```json { "type": "extraAgents", "user": "0x..." } ``` -------------------------------- ### Initialize Exchange with Agent and Vault Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Configure the Exchange module for an agent account that uses a vault for key management. ```python from hyperliquid.exchange import Exchange exchange = Exchange(private_key='YOUR_AGENT_PRIVATE_KEY', network='testnet', agent_address='0x...', vault_path='/path/to/vault.json') ``` -------------------------------- ### Get Account Value Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieve the current account value from the user's state. Requires an initialized Info object. ```python info = Info() state = info.user_state("0x...") account_value = state["crossMarginSummary"]["accountValue"] ``` -------------------------------- ### Exchange Constructor Parameters Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/configuration.md Defines the parameters available for initializing the Exchange client, including wallet, API endpoint, and account-specific configurations. ```python Exchange( wallet: LocalAccount, base_url: Optional[str] = None, meta: Optional[Meta] = None, vault_address: Optional[str] = None, account_address: Optional[str] = None, spot_meta: Optional[SpotMeta] = None, perp_dexs: Optional[List[str]] = None, timeout: Optional[float] = None, ) ``` -------------------------------- ### Get User Fees Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieve fee information for a user, including maker and taker rates. Requires a user's address. ```python fees = info.user_fees("0x...") print(f"Maker rate: {fees['feeSchedule']['add']}") print(f"Taker rate: {fees['feeSchedule']['cross']}") ``` -------------------------------- ### Initialize Exchange with Agent Wallet Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Initialize the Exchange module for an agent account, typically used for automated trading. ```python from hyperliquid.exchange import Exchange # Initialize with agent configuration exchange = Exchange(private_key='YOUR_AGENT_PRIVATE_KEY', network='testnet', agent_address='0x...') ``` -------------------------------- ### Get User Fills Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieve all fills for a user or fills within a specific time range. Requires a user's address. ```python # All fills fills = info.user_fills("0x...") ``` ```python # Fills in time range fills = info.user_fills_by_time( address="0x...", start_time=1234567890000, end_time=1234567900000 ) ``` -------------------------------- ### Configure Exchange Client with Custom Endpoint Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initialize the Exchange client to connect to a custom API endpoint. Requires a wallet object. ```python exchange = Exchange(wallet, "https://my-proxy.example.com") ``` -------------------------------- ### Get Historical Candles Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/MANIFEST.md Retrieve historical OHLCV (Open, High, Low, Close, Volume) candle data for an asset and timeframe. ```python from hyperliquid.info import Info info = Info() candles = info.get_candlesticks(asset='SOL', interval='1h') # interval can be '1m', '5m', '1h', '1d', etc. print(candles) ``` -------------------------------- ### Initialize Info and Exchange with Multiple DEXs Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Initialize `Info` and `Exchange` objects to target specific perpetual decentralized exchanges (DEXs) by passing a list of DEX names to the `perp_dexs` parameter. An empty string represents the default DEX. ```python info = Info(perp_dexs=["", "dex1", "dex2"]) exchange = Exchange(wallet, perp_dexs=["", "dex1", "dex2"]) ``` -------------------------------- ### Type-Safe Imports for Hyperliquid SDK Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/README.md Import additional types for more robust and type-checked interactions with the SDK. This setup is recommended for larger projects. ```python from hyperliquid import Info, Exchange, Cloid from hyperliquid.utils.types import OrderType, Subscription from hyperliquid.utils.error import ClientError from eth_account import Account ``` -------------------------------- ### Get User Fees Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-info.md Retrieves a user's fee tier and trading volume information. Requires the user's onchain address. ```python def user_fees(self, address: str) -> Any: ``` -------------------------------- ### Exchange Constructor Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/api-reference-exchange.md Initializes an Exchange instance for trading on the Hyperliquid platform. This involves setting up the necessary connection details and wallet for signing transactions. ```APIDOC ## Exchange Constructor ### Description Initializes an Exchange instance for trading. Creates an internal Info instance (with skip_ws=True) for metadata and price queries. The wallet is stored for signing all actions. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **wallet** (LocalAccount) - Required - eth_account LocalAccount object with private key. - **base_url** (Optional[str]) - Optional - API endpoint URL. Defaults to MAINNET_API_URL. - **meta** (Optional[Meta]) - Optional - Pre-cached perpetual metadata. - **vault_address** (Optional[str]) - Optional - Vault address for vault-based actions. - **account_address** (Optional[str]) - Optional - Account address for agent-based actions. - **spot_meta** (Optional[SpotMeta]) - Optional - Pre-cached spot metadata. - **perp_dexs** (Optional[List[str]]) - Optional - List of perpetual DEX names. - **timeout** (Optional[float]) - Optional - Request timeout in seconds. ### Request Example ```python from eth_account import Account from hyperliquid.exchange import Exchange from hyperliquid.utils import constants wallet = Account.from_key("0x...") exchange = Exchange(wallet, constants.TESTNET_API_URL) ``` ### Response #### Success Response (200) Exchange instance ``` -------------------------------- ### Get L2 Order Book Snapshot Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/quick-reference.md Retrieve a Level 2 snapshot of the order book for a specific asset, showing bids and asks. ```python l2 = info.l2_snapshot("BTC") bids = l2["levels"][0] asks = l2["levels"][1] ``` -------------------------------- ### Get L2 Book Snapshot Source: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/_autodocs/endpoints.md Retrieve the Level 2 order book for a specific coin. This is useful for understanding market depth and liquidity. ```json { "type": "l2Book", "coin": "BTC" } ```