### Python Hyperliquid API Setup Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/accountvaluesnapshot This Python code snippet sets up the necessary imports for interacting with Hyperliquid APIs. It includes libraries for asynchronous operations, HTTP requests, data structuring, time handling, compression, serialization, and environment variable management. This is a foundational setup for building Hyperliquid-related applications in Python. ```python import asyncio import aiohttp import struct from typing import Optional, Dict, List, Any import time import json import zstandard as zstd import msgpack import os from dotenv import load_dotenv ``` -------------------------------- ### JavaScript L4SnapshotClient Setup and Initialization Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/l4orderbooksnapshots Initializes the L4SnapshotClient, setting up the base URL and API key from environment variables. It validates the presence of the API key and prepares for subsequent API interactions. ```javascript const axios = require('axios'); const { decompress } = require('@mongodb-js/zstd'); const msgpack = require('msgpack-lite'); const fs = require('fs').promises; require('dotenv').config(); class L4SnapshotClient { /** * Client for polling L4 orderbook snapshots with trigger orders from the API. * * Configuration via environment variables: * - HYDROMANCER_URL: Base URL of the API (default: https://api.hydromancer.xyz) * - HYDROMANCER_API_KEY: API key for authentication (required) */ constructor() { this.baseUrl = process.env.HYDROMANCER_URL || 'https://api.hydromancer.xyz'; this.apiKey = process.env.HYDROMANCER_API_KEY; if (!this.apiKey) { console.error('Error: HYDROMANCER_API_KEY environment variable is required'); process.exit(1); } this.cachedTimestamp = null; this.cachedSnapshot = null; } // ... other methods ... } ``` -------------------------------- ### Connect and Subscribe to allTwapStatusUpdates using Python Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/alltwapstatusupdates Python example demonstrating WebSocket connection, authentication, and subscription to allTwapStatusUpdates using the 'websocket-client' library. ```python import websocket import json import os def on_message(ws, message): msg = json.loads(message) if msg['type'] == 'connected': ws.send(json.dumps({ "type": "subscribe", "subscription": { "type": "allTwapStatusUpdates" } })) elif msg['type'] == 'ping': print("Received ping, sending pong") ws.send(json.dumps({'type': 'pong'})) elif msg['type'] == 'allTwapStatusUpdates': print(f"Received {msg}") elif msg['type'] == 'subscriptionUpdate': print(f"Subscription update: {msg}") elif msg['type'] == 'error': print(f"Error: {msg}") else: print(f"Unknown message type: {msg}") def on_open(ws): ws.send(json.dumps({ 'type': 'auth', 'apiKey': os.environ.get('HYDROMANCER_API_KEY') })) ws = websocket.WebSocketApp('wss://api.hydromancer.xyz/ws', on_open=on_open, on_message=on_message) ws.run_forever() ``` -------------------------------- ### Getting Live Liquidation Alerts Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/builder-guides/data-and-information-tooling Subscribe to websockets to receive real-time liquidation events occurring on Hyperliquid. Allows filtering for specific thresholds, assets, or DEXs. ```APIDOC ## WebSocket Endpoint: /liquidationfills ### Description Establishes a WebSocket connection to receive real-time liquidation events as they happen on Hyperliquid. ### Method WebSocket ### Endpoint /liquidationfills ### Parameters #### Query Parameters - **threshold** (string) - Optional - Minimum liquidation amount to receive. - **asset** (string) - Optional - Filter liquidations for a specific asset. - **dex** (string) - Optional - Filter liquidations for a specific HIP-3 DEX. ### Request Example (No request body for WebSocket connections) ### Response #### Success Response (on message) - **liquidation** (object) - Details of a liquidation event. - **account** (string) - The address of the liquidated account. - **asset** (string) - The asset being liquidated. - **amount** (string) - The amount of the asset being liquidated. - **price** (string) - The price at which the liquidation occurred. - **timestamp** (string) - The timestamp of the liquidation. #### Response Example { "liquidation": { "account": "0x456...", "asset": "BTC", "amount": "0.1", "price": "29500000000000000000", "timestamp": "1678886400000" } } ``` -------------------------------- ### Connect and Subscribe to allFills using JavaScript Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/allfills This JavaScript example demonstrates how to establish a WebSocket connection to the Hydromancer API, authenticate using an API key, and subscribe to the 'allFills' stream. It includes handling 'connected', 'ping', and 'allFills' messages. The 'ws' library is required. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://api.hydromancer.xyz/ws'); ws.on('open', () => { // Authenticate using environment variable ws.send(JSON.stringify({ type: 'auth', apiKey: process.env.HYDROMANCER_API_KEY })); }); ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.type === 'connected') { // Subscribe to fills ws.send(JSON.stringify({ type: 'subscribe', subscription: { type: 'allFills' } })); } else if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } else if (msg.type === 'allFills') { console.log(`Received ${msg.fills.length} fills`); } }); ``` -------------------------------- ### Connect and Subscribe to allTwapStatusUpdates using Javascript Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/alltwapstatusupdates Example of connecting to the Hydromancer WebSocket API, authenticating, and subscribing to allTwapStatusUpdates using Node.js. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://api.hydromancer.xyz/ws'); ws.on('open', () => { // Authenticate using environment variable ws.send(JSON.stringify({ type: 'auth', apiKey: process.env.HYDROMANCER_API_KEY })); }); ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.type === 'connected') { // Subscribe to fills ws.send(JSON.stringify({ type: 'subscribe', subscription: { type: 'allTwapStatusUpdates' } })); } else if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } else if (msg.type === 'allTwapStatusUpdates') { console.log(`Received ${msg}`); } }); ``` -------------------------------- ### Account Value Snapshots Request - Multiple Query Examples Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/accountvaluesnapshot Demonstrates various ways to query account value snapshots, including fetching all data for a specific collateral token across DEXes, targeting a single DEX:token pair, or combining both approaches for comprehensive analysis. ```json // Get all DEXes using USDC as collateral {"type": "accountValueSnapshots", "collateral_tokens": ["USDC"]} // Might return: hyperliquid:USDC, xyz:USDC, vntls:USDC (multiple snapshots) // Get only Hyperliquid's USDC accounts {"type": "accountValueSnapshots", "collateral_tokens": ["hyperliquid:USDC"]} // Returns: Only hyperliquid:USDC (single snapshot) // Get USDC from all DEXes + specific USDE from xyz only {"type": "accountValueSnapshots", "collateral_tokens": ["USDC", "xyz:USDE"]} // Returns: All *:USDC snapshots + xyz:USDE snapshot (multiple snapshots) ``` -------------------------------- ### Connect and Subscribe to Liquidation Fills using Python WebSocket Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/liquidationfills Provides a Python example for connecting to the Hydromancer WebSocket API, authenticating with an API key, and subscribing to 'liquidationFills'. It includes message handling for various types like 'connected', 'ping', 'liquidationFills', 'subscriptionUpdate', and 'error'. ```python import websocket import json import os def on_message(ws, message): msg = json.loads(message) if msg['type'] == 'connected': ws.send(json.dumps({ "type": "subscribe", "subscription": { "type": "liquidationFills" } })) elif msg['type'] == 'ping': print("Received ping, sending pong") ws.send(json.dumps({'type': 'pong'})) elif msg['type'] == 'liquidationFills': print(f"Received {len(msg['fills'])} liquidations") elif msg['type'] == 'subscriptionUpdate': print(f"Subscription update: {msg}") elif msg['type'] == 'error': print(f"Error: {msg}") else: print(f"Unknown message type: {msg}") def on_open(ws): ws.send(json.dumps({ 'type': 'auth', 'apiKey': os.environ.get('HYDROMANCER_API_KEY') })) ws = websocket.WebSocketApp('wss://api.hydromancer.xyz/ws', on_open=on_open, on_message=on_message) ws.run_forever() ``` -------------------------------- ### Connect and Subscribe to allFills using Python Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/allfills This Python example shows how to connect to the Hydromancer WebSocket API, authenticate, and subscribe to the 'allFills' stream. It handles various message types including 'connected', 'ping', and 'allFills', providing a basic framework for processing real-time fill data. The 'websocket-client' library is required. ```python import websocket import json import os def on_message(ws, message): msg = json.loads(message) if msg['type'] == 'connected': ws.send(json.dumps({ "type": "subscribe", "subscription": { "type": "allFills" } })) elif msg['type'] == 'ping': print("Received ping, sending pong") ws.send(json.dumps({'type': 'pong'})) elif msg['type'] == 'allFills': print(f"Received {len(msg['fills'])} fills") elif msg['type'] == 'subscriptionUpdate': print(f"Subscription update: {msg}") elif msg['type'] == 'error': print(f"Error: {msg}") else: print(f"Unknown message type: {msg}") def on_open(ws): ws.send(json.dumps({ 'type': 'auth', 'apiKey': os.environ.get('HYDROMANCER_API_KEY') })) ws = websocket.WebSocketApp('wss://api.hydromancer.xyz/ws', on_open=on_open, on_message=on_message) ws.run_forever() ``` -------------------------------- ### Python WebSocket Client for Active Asset Context Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/activeassetctx A Python example demonstrating how to connect to the Hydromancer WebSocket API, subscribe to activeAssetCtx, and process received messages. It uses the 'websocket-client' library and requires an API key. ```python import websocket import json import os # Get API key from environment variable api_key = os.environ.get('HYDROMANCER_API_KEY') url = f'wss://api-testnet.hydromancer.xyz/ws?token={api_key}' # url = 'wss://api.hyperliquid-testnet.xyz/ws' def on_open(ws): print('WebSocket connection opened') print('Subscribing to oracleUpdates...') ws.send(json.dumps({ "method": "subscribe", "subscription": { "type": "activeAssetCtx", "coin": "ETH" } })) def on_error(ws, error): print(f'WebSocket error: {error}') def on_close(ws, close_status_code, close_msg): print('WebSocket connection closed') def on_message(ws, message): msg = json.loads(message) if msg.get('channel') == 'activeAssetCtx': print(msg.get('data')) # Create WebSocket connection ws = websocket.WebSocketApp(url, on_open=on_open, on_error=on_error, on_close=on_close, on_message=on_message) # Run the WebSocket connection ws.run_forever() ``` -------------------------------- ### Javascript WebSocket Client for Active Asset Context Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/activeassetctx A Javascript example demonstrating how to connect to the Hydromancer WebSocket API, subscribe to activeAssetCtx, and log received messages. It uses the 'ws' library and requires an API key. ```javascript const WebSocket = require('ws'); const ws = new WebSocket(`wss://api-testnet.hydromancer.xyz/ws?token=${process.env.HYDROMANCER_API_KEY}`); // const ws = new WebSocket(`wss://api.hyperliquid-testnet.xyz/ws`); ws.on('open', () => { console.log('WebSocket connection opened'); console.log('Subscribing to oracleUpdates...'); ws.send(JSON.stringify({ "method": "subscribe", "subscription": { "type": "activeAssetCtx", "coin": "ETH" } })); }); ws.on('error', (error) => { console.error('WebSocket error:', error); }); ws.on('close', () => { console.log('WebSocket connection closed'); }); ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.channel === 'activeAssetCtx') { console.log(msg.data) } }); ``` -------------------------------- ### WebSocket Connection and Subscription Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/allusernonfundingledgerevents Connect to the Hydromancer XYZ WebSocket API, authenticate with an API key, and subscribe to 'allUserNonFundingLedgerEvents'. Includes examples in Javascript and Python. ```APIDOC ## WebSocket Connection and Subscription ### Description Establishes a WebSocket connection to the Hydromancer XYZ API, authenticates the client using an API key, and subscribes to receive real-time non-funding ledger events for the user. The endpoint `wss://api.hydromancer.xyz/ws` is used for this purpose. ### Method WebSocket ### Endpoint `wss://api.hydromancer.xyz/ws` ### Parameters #### Request Body (Authentication) - **type** (string) - Required - Must be 'auth'. - **apiKey** (string) - Required - Your Hydromancer API key. #### Request Body (Subscription) - **type** (string) - Required - Must be 'subscribe'. - **subscription** (object) - Required - Subscription details. - **type** (string) - Required - The type of subscription, e.g., 'allUserNonFundingLedgerEvents'. ### Request Example (Javascript Authentication) ```javascript ws.send(JSON.stringify({ type: 'auth', apiKey: process.env.HYDROMANCER_API_KEY })); ``` ### Request Example (Javascript Subscription) ```javascript ws.send(JSON.stringify({ type: 'subscribe', subscription: { type: 'allUserNonFundingLedgerEvents' } })); ``` ### Request Example (Python Authentication) ```python ws.send(json.dumps({ 'type': 'auth', 'apiKey': os.environ.get('HYDROMANCER_API_KEY') })) ``` ### Request Example (Python Subscription) ```python ws.send(json.dumps({ "type": "subscribe", "subscription": { "type": "allUserNonFundingLedgerEvents" } })) ``` ### Response #### Success Response (Connection) - **type** (string) - 'connected' #### Success Response (Pong) - **type** (string) - 'pong' #### Success Response (Ledger Events) - **type** (string) - 'allUserNonFundingLedgerEvents' - [Event specific fields based on the delta type] #### Error Handling - **type** (string) - 'error' - Indicates an error occurred. - **message** (string) - Error message. ``` -------------------------------- ### Fetch User Fills by Time with Javascript (Axios) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data/userfillsbytime This Javascript example uses the 'axios' library to perform the POST request to the userFillsByTime API. It demonstrates asynchronous handling with async/await and includes error handling for network or API issues. The API key is accessed from environment variables, making it suitable for Node.js applications. ```javascript import axios from 'axios'; try { const response = await axios.post('https://api.hydromancer.xyz/info', { type: 'userFillsByTime', user: '0x0000000000000000000000000000000000000000', startTime: 1234567890000, endTime: 1234567900000, cursor: '1234567890000_12' }, { headers: { 'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`, 'Content-Type': 'application/json' } }); console.log(response.data); } catch (error) { console.error('Error:', error.message); } ``` -------------------------------- ### Javascript WebSocket Client for Order Updates Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/builderorderupdates Example Javascript code using the 'ws' library to connect to the Hydromancer API, authenticate, subscribe to 'builderOrderUpdates', and process incoming messages. Handles connection, authentication, subscription, and order update events. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://api.hydromancer.xyz/ws'); ws.on('open', () => { // Authenticate using environment variable ws.send(JSON.stringify({ type: 'auth', apiKey: process.env.HYDROMANCER_API_KEY })); }); ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.type === 'connected') { // Subscribe to order updates for specific users ws.send(JSON.stringify({ type: 'subscribe', subscription: { type: 'builderOrderupdates', builder: '0x742d35cc6634c0532925a3b844bc9e7595f7f2e2' } })); } else if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } else if (msg.type === 'builderOrderupdates') { console.log(`Received ${msg.updates.length} order updates`); msg.updates.forEach(update => { console.log(`Order ${update.order.oid} for ${update.user}: ${update.status}`); }); } }); ``` -------------------------------- ### Get Clearinghouse State (Javascript) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-position-data/clearinghousestate This Javascript example utilizes the axios library to make a POST request to the Hydromancer API for clearinghouse state data. It handles potential errors and logs the response data to the console. ```javascript import axios from 'axios'; try { const response = await axios.post('https://api.hydromancer.xyz/info', { type: 'clearinghouseState', user: '0x0000000000000000000000000000000000000000' }, { headers: { 'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`, 'Content-Type': 'application/json' } }); console.log(response.data); } catch (error) { console.error('Error:', error.message); } ``` -------------------------------- ### Hydromancer Ledger Event Type Examples (JSON) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/usernonfundingledgerevents This section provides JSON examples for various ledger event types available through the Hydromancer API. These examples illustrate the structure and fields for events such as SpotTransfer, AccountClassTransfer, Withdraw, Deposit, VaultCreate, VaultDeposit, VaultWithdraw, VaultDistribution, and VaultLeaderCommission. ```json { "time": "1704067200000", "hash": "0xabc123...", "eventType": "SpotTransfer", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "counterparty": "0x123456...", "role": "sender", "amount": "1000.0", "token": "USDC", "usdcValue": "1000.0", "fee": "1.5", "feeToken": "USDC", "nativeTokenFee": "0.1", "nonce": 12345 } ``` ```json { "time": "1704067200000", "hash": "0xdddeeef...", "eventType": "AccountClassTransfer", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "userDex": "hyperliquid", "role": "user", "amount": "1500.0", "toPerp": true } ``` ```json { "time": "1704067200000", "hash": "0xbbbccc...", "eventType": "Withdraw", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "userDex": "hyperliquid", "role": "user", "amount": "2000.0", "fee": "5.0", "nonce": 12347 } ``` ```json { "time": "1704067200000", "hash": "0x999aaa...", "eventType": "Deposit", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "userDex": "hyperliquid", "role": "user", "amount": "5000.0", "isDeposit": true } ``` ```json { "time": "1704067200000", "hash": "0xfff111...", "eventType": "VaultCreate", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "counterparty": "0xvault123...", "role": "sender", "vault": "0xvault123...", "amount": "10000.0", "fee": "10.0" } ``` ```json { "time": "1704067200000", "hash": "0x222333...", "eventType": "VaultDeposit", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "counterparty": "0xvault123...", "role": "sender", "vault": "0xvault123...", "amount": "5000.0" } ``` ```json { "time": "1704067200000", "hash": "0x444555...", "eventType": "VaultWithdraw", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "counterparty": "0xvault123...", "role": "receiver", "vault": "0xvault123...", "requestedUsd": "3000.0", "commission": "50.0", "closingCost": "100.0", "basis": "2900.0", "netWithdrawnUsd": "2850.0" } ``` ```json { "time": "1704067200000", "hash": "0x666777...", "eventType": "VaultDistribution", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "counterparty": "0xvault123...", "role": "receiver", "vault": "0xvault123...", "amount": "500.0" } ``` ```json { "time": "1704067200000", "hash": "0x888999...", "eventType": "VaultLeaderCommission", "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", "role": "user" } ``` -------------------------------- ### Initialize PerpSnapshotClient and manage API key Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/perpsnapshot Initializes the PerpSnapshotClient, loading API credentials from environment variables. It raises a ValueError if the API key is missing or not properly configured, ensuring secure access to the Hydromancer API. ```python import os import aiohttp import msgpack from typing import Optional, Dict, Any, List from dotenv import load_dotenv load_dotenv() class PerpSnapshotClient: def __init__(self): self.base_url = os.getenv('HYDROMANCER_API_URL', 'https://api.hydromancer.xyz') self.api_key = os.getenv('HYDROMANCER_API_KEY') if not self.api_key or self.api_key == 'INSERT_API_KEY_HERE': raise ValueError("API key not found. Please set HYDROMANCER_API_KEY in .env file") self.cached_timestamp: Optional[str] = None self.cached_snapshots: Dict[str, Any] = {} self.session: Optional[aiohttp.ClientSession] = None self.output_file = "perp_snapshot.json" ``` -------------------------------- ### GET /user-order-data/openorders Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-order-data Retrieves a list of the user's currently open orders. ```APIDOC ## GET /user-order-data/openorders ### Description Retrieves a list of the user's currently open orders. ### Method GET ### Endpoint /user-order-data/openorders ### Parameters #### Query Parameters - **user** (string) - Required - The identifier for the user. ### Request Example ``` GET /user-order-data/openorders?user=someUserId ``` ### Response #### Success Response (200) - **orders** (array) - A list of open order objects. - **orderId** (string) - The unique identifier for the order. - **symbol** (string) - The trading symbol for the order. - **side** (string) - The side of the order (e.g., 'buy', 'sell'). - **price** (number) - The price at which the order is placed. - **amount** (number) - The quantity of the asset for the order. - **timestamp** (integer) - The Unix timestamp when the order was created. #### Response Example ```json { "orders": [ { "orderId": "12345", "symbol": "BTC-PERPETUAL", "side": "buy", "price": 30000.50, "amount": 0.1, "timestamp": 1678886400 } ] } ``` ``` -------------------------------- ### SpotSnapshotClient Initialization and Session Management (Python) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Initializes the SpotSnapshotClient with API credentials and manages the aiohttp client session using asynchronous context managers. It raises an error if the API key is missing and ensures the session is closed properly. ```python import os import aiohttp import time from typing import Optional, Dict, Any, List # Load environment variables from .env file # from dotenv import load_dotenv # load_dotenv() class SpotSnapshotClient: def __init__(self): # Use environment variables with fallbacks self.base_url = os.getenv('HYDROMANCER_API_URL', 'https://api.hydromancer.xyz') self.api_key = os.getenv('HYDROMANCER_API_KEY') if not self.api_key: raise ValueError("API key not found. Please set HYDROMANCER_API_KEY in .env file") self.cached_timestamp: Optional[str] = None self.cached_snapshots: Dict[str, Any] = {} self.session: Optional[aiohttp.ClientSession] = None self.output_file = "spot_snapshot.json" async def __aenter__(self): self.session = aiohttp.ClientSession() return self async def __aexit__(self, exc_type, exc_val, exc_tb): if self.session: await self.session.close() ``` -------------------------------- ### GET /user-order-data/frontendopenorders Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-order-data Retrieves a list of the user's open orders, including additional frontend-specific information. ```APIDOC ## GET /user-order-data/frontendopenorders ### Description Retrieves a list of the user's open orders, including additional frontend-specific information such as order trigger conditions, reduceOnly toggles, and TP/SL status. ### Method GET ### Endpoint /user-order-data/frontendopenorders ### Parameters #### Query Parameters - **user** (string) - Required - The identifier for the user. ### Request Example ``` GET /user-order-data/frontendopenorders?user=someUserId ``` ### Response #### Success Response (200) - **orders** (array) - A list of open order objects with frontend details. - **orderId** (string) - The unique identifier for the order. - **symbol** (string) - The trading symbol for the order. - **side** (string) - The side of the order (e.g., 'buy', 'sell'). - **price** (number) - The price at which the order is placed. - **amount** (number) - The quantity of the asset for the order. - **timestamp** (integer) - The Unix timestamp when the order was created. - **triggerCondition** (string, optional) - The condition under which the order was triggered. - **reduceOnly** (boolean, optional) - Indicates if the order is a reduce-only order. - **isTP** (boolean, optional) - Indicates if the order is a Take Profit order. - **isSL** (boolean, optional) - Indicates if the order is a Stop Loss order. #### Response Example ```json { "orders": [ { "orderId": "67890", "symbol": "ETH-PERPETUAL", "side": "sell", "price": 2000.00, "amount": 0.5, "timestamp": 1678886400, "triggerCondition": ">= 2050", "reduceOnly": true, "isTP": false, "isSL": true } ] } ``` ``` -------------------------------- ### Perpetual Futures Snapshot Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data Retrieves the unique endpoint allowing to get entire perps positioning of all Hyperliquid traders. ```APIDOC ## GET /hydromancer-better-hyperliquid-apis/rest-api/market-data/perpsnapshot.md ### Description Retrieves the entire perpetual futures positioning of all Hyperliquid traders. ### Method GET ### Endpoint /hydromancer-better-hyperliquid-apis/rest-api/market-data/perpsnapshot.md ### Parameters #### Query Parameters - **collateral_type** (string) - Optional - Filter by a specific type of collateral. - **dex_type** (string) - Optional - Filter by a specific DEX type (e.g., HIP-3). ### Request Example ``` GET /hydromancer-better-hyperliquid-apis/rest-api/market-data/perpsnapshot.md?collateral_type=USDC&dex_type=HIP-3 ``` ### Response #### Success Response (200) - **trader_positions** (array) - An array of objects, where each object represents a trader's perpetual futures position. - **account** (string) - The trader's account identifier. - **position** (object) - Details of the trader's position. - **symbol** (string) - The trading symbol. - **side** (string) - The side of the position (e.g., 'long', 'short'). - **size** (number) - The size of the position. - **margin** (number) - The margin used for the position. #### Response Example ```json { "trader_positions": [ { "account": "0x123abc...", "position": { "symbol": "ETH-PERP", "side": "long", "size": 10.5, "margin": 1000.0 } } ] } ``` ``` -------------------------------- ### GET /historical-data/userfunding Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data Retrieves a user's historical funding payments and receipts. This endpoint is essential for understanding funding costs and income. ```APIDOC ## GET /historical-data/userfunding ### Description Retrieves a user's historical funding payments and receipts. This endpoint is essential for understanding funding costs and income. ### Method GET ### Endpoint /historical-data/userfunding ### Parameters #### Query Parameters - **userAddress** (string) - Required - The address of the user whose funding history is to be retrieved. - **limit** (integer) - Optional - The maximum number of funding records to return. - **offset** (integer) - Optional - The number of funding records to skip before returning results. ### Response #### Success Response (200) - **fundingHistory** (array) - An array of funding records. - **timestamp** (integer) - The Unix timestamp of the funding period. - **amount** (string) - The amount of funding paid or received. - **instrumentId** (string) - The ID of the instrument for which funding was applied. - **isPaid** (boolean) - True if the user paid funding, false if they received funding. #### Response Example ```json { "fundingHistory": [ { "timestamp": 1678886400, "amount": "0.5", "instrumentId": "ETH-PERPETUAL", "isPaid": true } ] } ``` ``` -------------------------------- ### Liquidation Fills WebSocket Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/builder-guides/quant-funds Provides real-time data on liquidation fills. This, combined with other endpoints, offers a powerful and granular overview of markets on Hyperliquid. ```APIDOC ## WebSocket /liquidationfills ### Description Provides real-time data stream of liquidation fills on Hyperliquid. Combined with other Hydromancer endpoints, this enables a powerful, granular overview of markets. ### Method WebSocket ### Endpoint /liquidationfills ### Parameters No specific parameters required for initial connection, but subscriptions may be available. ### Request Example (WebSocket connection setup) ### Response #### Success Response (on message) - **liquidation** (object) - Details of a liquidation fill. - **orderHash** (string) - Hash of the liquidated order. - **maker** (string) - Address of the maker. - **taker** (string) - Address of the taker. - **asset** (string) - The asset involved. - **size** (string) - The size of the liquidation. - **price** (string) - The price at which the liquidation occurred. - **timestamp** (integer) - The Unix timestamp of the liquidation. #### Response Example { "liquidation": { "orderHash": "0xabc...", "maker": "0xmaker...", "taker": "0xtaker...", "asset": "BTC", "size": "500000", "price": "30500000000000000000", "timestamp": 1678886402 } } ``` -------------------------------- ### GET /historical-data/userfills Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data Retrieves a user's historical trade fills. This endpoint provides a list of all trades executed by a specific user. ```APIDOC ## GET /historical-data/userfills ### Description Retrieves a user's historical trade fills. This endpoint provides a list of all trades executed by a specific user. ### Method GET ### Endpoint /historical-data/userfills ### Parameters #### Query Parameters - **userAddress** (string) - Required - The address of the user whose fills are to be retrieved. - **limit** (integer) - Optional - The maximum number of fills to return. - **offset** (integer) - Optional - The number of fills to skip before returning results. ### Response #### Success Response (200) - **fills** (array) - An array of fill objects, each containing details of a trade. - **timestamp** (integer) - The Unix timestamp of the fill. - **price** (string) - The execution price of the trade. - **amount** (string) - The amount traded. - **side** (string) - The side of the trade ('buy' or 'sell'). - **instrumentId** (string) - The ID of the instrument traded. - **orderId** (string) - The ID of the order associated with the fill. #### Response Example ```json { "fills": [ { "timestamp": 1678886400, "price": "1.2345", "amount": "100", "side": "buy", "instrumentId": "ETH-PERPETUAL", "orderId": "order123" } ] } ``` ``` -------------------------------- ### GET /historical-data/builderfills Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data Retrieves fills executed by builders. This endpoint is useful for analyzing the trading activity of market makers or automated trading strategies. ```APIDOC ## GET /historical-data/builderfills ### Description Retrieves fills executed by builders. This endpoint is useful for analyzing the trading activity of market makers or automated trading strategies. ### Method GET ### Endpoint /historical-data/builderfills ### Parameters #### Query Parameters - **builderAddress** (string) - Required - The address of the builder whose fills are to be retrieved. - **limit** (integer) - Optional - The maximum number of fills to return. - **offset** (integer) - Optional - The number of fills to skip before returning results. ### Response #### Success Response (200) - **fills** (array) - An array of fill objects executed by the builder. - **timestamp** (integer) - The Unix timestamp of the fill. - **price** (string) - The execution price of the trade. - **amount** (string) - The amount traded. - **side** (string) - The side of the trade ('buy' or 'sell'). - **instrumentId** (string) - The ID of the instrument traded. - **orderId** (string) - The ID of the order associated with the fill. #### Response Example ```json { "fills": [ { "timestamp": 1678886400, "price": "1.2345", "amount": "100", "side": "sell", "instrumentId": "ETH-PERPETUAL", "orderId": "builderOrder456" } ] } ``` ``` -------------------------------- ### Python: Import Necessary Libraries for Hyperliquid API Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Imports essential Python libraries for asynchronous operations, HTTP requests, data serialization, and environment variable management, necessary for interacting with the Hyperliquid API. ```python import asyncio import aiohttp import struct from typing import Optional, Dict, List, Any import time import json import zstandard as zstd import msgpack import os from dotenv import load_dotenv ``` -------------------------------- ### GET /historical-data/usernonfundingledgerupdates Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data Retrieves a user's non-funding ledger updates. This includes changes to positions, margin, and other account balances not related to funding. ```APIDOC ## GET /historical-data/usernonfundingledgerupdates ### Description Retrieves a user's non-funding ledger updates. This includes changes to positions, margin, and other account balances not related to funding. ### Method GET ### Endpoint /historical-data/usernonfundingledgerupdates ### Parameters #### Query Parameters - **userAddress** (string) - Required - The address of the user whose ledger updates are to be retrieved. - **limit** (integer) - Optional - The maximum number of updates to return. - **offset** (integer) - Optional - The number of updates to skip before returning results. ### Response #### Success Response (200) - **ledgerUpdates** (array) - An array of ledger update records. - **timestamp** (integer) - The Unix timestamp of the ledger update. - **type** (string) - The type of ledger update (e.g., 'POSITION_CHANGED', 'MARGIN_CHANGED'). - **details** (object) - Specific details about the ledger update. #### Response Example ```json { "ledgerUpdates": [ { "timestamp": 1678886400, "type": "POSITION_CHANGED", "details": { "instrumentId": "BTC-PERPETUAL", "newPositionSize": "5.0" } } ] } ``` ``` -------------------------------- ### GET /historical-data/builderfillsbytime Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data Retrieves builder fills within a specified time range. This allows for detailed analysis of builder activity during specific market conditions. ```APIDOC ## GET /historical-data/builderfillsbytime ### Description Retrieves builder fills within a specified time range. This allows for detailed analysis of builder activity during specific market conditions. ### Method GET ### Endpoint /historical-data/builderfillsbytime ### Parameters #### Query Parameters - **builderAddress** (string) - Required - The address of the builder whose fills are to be retrieved. - **startTime** (integer) - Required - The start of the time range in Unix timestamp format. - **endTime** (integer) - Required - The end of the time range in Unix timestamp format. - **limit** (integer) - Optional - The maximum number of fills to return. - **offset** (integer) - Optional - The number of fills to skip before returning results. ### Response #### Success Response (200) - **fills** (array) - An array of fill objects executed by the builder within the specified time range. - **timestamp** (integer) - The Unix timestamp of the fill. - **price** (string) - The execution price of the trade. - **amount** (string) - The amount traded. - **side** (string) - The side of the trade ('buy' or 'sell'). - **instrumentId** (string) - The ID of the instrument traded. - **orderId** (string) - The ID of the order associated with the fill. #### Response Example ```json { "fills": [ { "timestamp": 1678886400, "price": "1.2345", "amount": "100", "side": "sell", "instrumentId": "ETH-PERPETUAL", "orderId": "builderOrder456" } ] } ``` ``` -------------------------------- ### Finding Biggest Positions on Any Market Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/builder-guides/data-and-information-tooling Get all positions across all markets on Hyperliquid. You can filter by specific markets to retrieve positioning data for chosen assets. ```APIDOC ## GET /perpsnapshot ### Description Retrieves a snapshot of all open positions across specified markets on Hyperliquid. ### Method GET ### Endpoint /perpsnapshot ### Parameters #### Query Parameters - **markets** (string) - Optional - A comma-separated list of market identifiers (e.g., 'HYPE', 'BTC') to filter results. If omitted, all markets are included. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **snapshots** (array) - An array of position snapshots. - **market** (string) - The identifier of the market. - **side** (string) - The side of the position ('long' or 'short'). - **size** (string) - The size of the position. - **margin** (string) - The margin used for the position. - **liquidation_price** (string) - The liquidation price for the position. - **entry_price** (string) - The entry price of the position. #### Response Example { "snapshots": [ { "market": "BTC", "side": "long", "size": "0.5", "margin": "5000000000000000000", "liquidation_price": "28000000000000000000", "entry_price": "30000000000000000000" } ] } ``` -------------------------------- ### Connect and Subscribe to Liquidation Fills using Javascript WebSocket Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/liquidationfills Demonstrates how to establish a WebSocket connection to the Hydromancer API, authenticate using an API key, and subscribe to the 'liquidationFills' stream. It also shows how to handle incoming messages, including 'connected', 'ping', and 'liquidationFills' data. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://api.hydromancer.xyz/ws'); ws.on('open', () => { // Authenticate using environment variable ws.send(JSON.stringify({ type: 'auth', apiKey: process.env.HYDROMANCER_API_KEY })); }); ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.type === 'connected') { // Subscribe to fills ws.send(JSON.stringify({ type: 'subscribe', subscription: { type: 'liquidationFills' } })); } else if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } else if (msg.type === 'liquidationFills') { console.log(`Received ${msg.fills.length} liquidations`); } }); ```