### Install Dependencies (npm) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/l4orderbooksnapshots Installs necessary Node.js packages: axios for HTTP requests, @mongodb-js/zstd for Zstandard decompression, msgpack-lite for MessagePack encoding/decoding, and dotenv for environment variable management. ```bash npm install axios @mongodb-js/zstd msgpack-lite dotenv ``` -------------------------------- ### POST userNonFundingLedgerUpdates Request Examples Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data/usernonfundingledgerupdates Demonstrates how to make a POST request to the userNonFundingLedgerUpdates endpoint. Requires an API key for authentication and specifies the user's Ethereum address and a start time. The endpoint returns a list of ledger update objects. ```cURL curl -X POST https://api.hydromancer.xyz/info \ -H "Authorization: Bearer $HYDROMANCER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "userNonFundingLedgerUpdates", "user": "0x0000000000000000000000000000000000000000", "startTime": 0 }' ``` ```Python import requests import os response = requests.post( 'https://api.hydromancer.xyz/info', json={ 'type': 'userNonFundingLedgerUpdates', 'user': '0x0000000000000000000000000000000000000000' }, headers={ 'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}', 'Content-Type': 'application/json' } ) print(response.json()) ``` ```Javascript import axios from 'axios'; try { const response = await axios.post('https://api.hydromancer.xyz/info', { type: 'userNonFundingLedgerUpdates', 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); } ``` -------------------------------- ### Example Usage: Polling Snapshots in JavaScript Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Demonstrates how to instantiate the SpotSnapshotClient and continuously poll for snapshots of specified tokens. Includes basic error handling for the polling process. ```javascript // Example usage async function main() { const client = new SpotSnapshotClient(); while (true) { try { const snapshots = await client.pollSnapshots(['UBTC', "PUP"]); ``` -------------------------------- ### Connect and Subscribe to Fills (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 'allFills'. It utilizes the `websocket-client` library and includes functions to handle connection opening and incoming messages, including pings and fill data. ```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() ``` -------------------------------- ### API Error Response Examples Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api Examples of common error responses from the Hydromancer.xyz API, including status codes and corresponding JSON error messages. ```json { "error": "Invalid Ethereum address: 0xinvalid" } ``` ```json { "error": "Invalid API key" } ``` ```json { "error": "Timeout error" } ``` ```json { "error": "An internal error occurred" } ``` -------------------------------- ### Connect and Subscribe to Fills (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 also includes handling of incoming messages, including pings and fill 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: 'allFills' } })); } else if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } else if (msg.type === 'allFills') { console.log(`Received ${msg.fills.length} fills`); } }); ``` -------------------------------- ### Multiple Markets Response Binary Structure (Text) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot This example describes the custom binary format for multiple market snapshots. It begins with a 4-byte market count, followed by length-prefixed, zstd-compressed data for each market. ```text [market_count: 4 bytes][length1: 4 bytes][zstd_data1][length2: 4 bytes][zstd_data2]... ``` -------------------------------- ### Connect and Subscribe to Fills using Javascript Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/builderfills Example Javascript code using the 'ws' library to establish a WebSocket connection, authenticate with an API key, and subscribe to builder fills. It handles incoming messages, including connection status, pings, and fill 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: 'builderFills', builder: '0xb84168cf3be63c6b8dad05ff5d755e97432ff80b' } })); } else if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } else if (msg.type === 'builderFills') { console.log(`Received ${msg.fills.length} fills`); } }); ``` -------------------------------- ### Connect and Subscribe to Fills using Python Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/builderfills Example Python code using the 'websocket-client' library to connect via WebSocket, authenticate, and subscribe to builder fills. It includes handlers for various message types like connection, pings, fills, and errors. ```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": "builderFills", "builder": "0xb84168cf3be63c6b8dad05ff5d755e97432ff80b" } })) elif msg['type'] == 'ping': print("Received ping, sending pong") ws.send(json.dumps({'type': 'pong'})) elif msg['type'] == 'builderFills': 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() ``` -------------------------------- ### Connect and Subscribe to Order Updates (Javascript) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/builderorderupdates This Javascript example demonstrates connecting to the Hydromancer WebSocket API, authenticating, and subscribing to builder order updates. It uses the 'ws' library and expects the API key to be set in the HYDROMANCER_API_KEY environment variable. ```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}`); }); } }); ``` -------------------------------- ### POST User Funding Data (Python) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data/userfunding This Python script uses the requests library to send a POST request to the Hydromancer.xyz API for user funding data. It configures the request with the API endpoint, JSON payload, and authorization headers. The script retrieves the API key from environment variables and prints the JSON response. Note the 'type' is 'userFills' in this example, which might be a typo and should potentially be 'userFunding' based on the context. ```python import requests import os response = requests.post( 'https://api.hydromancer.xyz/info', json={ 'type': 'userFills', 'user': '0x0000000000000000000000000000000000000000' }, headers={ 'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}', 'Content-Type': 'application/json' } ) print(response.json()) ``` -------------------------------- ### Connect and Subscribe to Order Updates (Python) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/builderorderupdates This Python example shows how to establish a WebSocket connection to the Hydromancer API, authenticate using an environment variable (HYDROMANCER_API_KEY), and subscribe to builder order updates. It includes basic message handling for connection, pings, and order updates. ```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": "builderOrderUpdates", "builder": "0x123.." } })) elif msg['type'] == 'ping': print("Received ping, sending pong") ws.send(json.dumps({'type': 'pong'})) elif msg['type'] == 'builderOrderUpdates': print(f"Received {len(msg['updates'])} orders") 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): print("WebSocket connection opened") # Get API key from environment variable api_key = os.environ.get('HYDROMANCER_API_KEY') if not api_key: raise ValueError("HYDROMANCER_API_KEY environment variable not set") ``` -------------------------------- ### POST User Funding Data (Javascript) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data/userfunding This Javascript code snippet utilizes the axios library to perform a POST request to the Hydromancer.xyz API for user funding information. It sets up the request URL, the JSON body with user details, and authorization headers using environment variables. The code includes basic error handling for the API call and logs the response data. Similar to the Python example, 'type' is 'userFills', which may need adjustment. ```javascript import axios from 'axios'; try { const response = await axios.post('https://api.hydromancer.xyz/info', { type: 'userFills', 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); } ``` -------------------------------- ### Initialize SpotSnapshotClient Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Initializes the SpotSnapshotClient with API credentials and configuration. It retrieves the API URL and key from environment variables, raising an error if the API key is missing. It also sets up internal caching mechanisms and prepares for asynchronous operations. ```python import os import aiohttp import time from typing import Optional, Dict, Any, List 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" ``` -------------------------------- ### AccountValueSnapshotClient Initialization and Async Context Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/accountvaluesnapshot Initializes the AccountValueSnapshotClient, setting up the base URL and API key from environment variables. It also defines asynchronous context management methods (__aenter__ and __aexit__) for managing the aiohttp client session. ```python import os import aiohttp from typing import Dict, Any, Optional class AccountValueSnapshotClient: 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_snapshots: Dict[str, Any] = {} self.cached_timestamp: Optional[str] = None self.session: Optional[aiohttp.ClientSession] = None self.output_file = "account_value_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 Asset Context Information (cURL, Python, Javascript) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/asset-data/assetcontext This snippet demonstrates how to request asset context information for a given cryptocurrency using the Hydromancer API. It requires specifying the 'type' as 'assetContext' and the 'coin' symbol. The examples show how to construct the POST request with necessary headers and payload for cURL, Python (using requests library), and Javascript (using axios). The API returns pricing data and impact prices upon successful execution. ```bash curl -X POST https://api.hydromancer.xyz/info \ -H "Authorization: Bearer $HYDROMANCER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "assetContext", "coin": "BTC" }' ``` ```python import requests import os import json response = requests.post( 'https://api.hydromancer.xyz/info', json={ 'type': 'assetContext', 'coin': 'BTC' }, headers={ 'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}', 'Content-Type': 'application/json' } ) print(json.dumps(response.json(), indent=2)) ``` ```javascript import axios from 'axios'; const response = await axios.post('https://api.hydromancer.xyz/info', { type: 'assetContext', coin: 'BTC' }, { headers: { 'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`, 'Content-Type': 'application/json' } }); console.log(JSON.stringify(response.data, null, 2)); ``` -------------------------------- ### GET /user-position-data/spotclearinghousestate Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-position-data Retrieves a summary of a user's spot accounts. ```APIDOC ## GET /user-position-data/spotclearinghousestate ### Description Retrieves a summary of a user's spot accounts. ### Method GET ### Endpoint /user-position-data/spotclearinghousestate ### Parameters #### Query Parameters - **user** (string) - Required - The unique identifier for the user. ### Response #### Success Response (200) - **data** (object) - Contains the user's spot account summary. (Structure not detailed in provided text) #### Response Example { "example": "{\"data\": {}}" } ``` -------------------------------- ### GET /user-position-data/clearinghousestate Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-position-data Retrieves a summary of a user's perpetual accounts. ```APIDOC ## GET /user-position-data/clearinghousestate ### Description Retrieves a summary of a user's perpetual accounts. ### Method GET ### Endpoint /user-position-data/clearinghousestate ### Parameters #### Query Parameters - **user** (string) - Required - The unique identifier for the user. ### Response #### Success Response (200) - **data** (object) - Contains the user's account summary. (Structure not detailed in provided text) #### Response Example { "example": "{\"data\": {}}" } ``` -------------------------------- ### PerpSnapshotClient Initialization and Async Context Management (Python) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/perpsnapshot Initializes the PerpSnapshotClient, setting up the base API URL and retrieving the API key from environment variables. It also defines asynchronous context management methods (__aenter__ and __aexit__) for handling the aiohttp client session. An exception is raised if the API key is missing or invalid. ```python import os import aiohttp from typing import Optional, Dict, Any 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" 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() ``` -------------------------------- ### Python: Core Library Imports for Data Handling Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot This Python snippet showcases essential library imports for asynchronous operations, network requests, data serialization (struct, msgpack), compression (zstandard), environment variable loading, and general utilities. These are foundational for tasks involving data fetching and processing. ```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 /user-order-data/openorders Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-order-data Retrieves a list of a user's currently open orders. ```APIDOC ## GET /user-order-data/openorders ### Description Retrieves a list of a user's currently open orders. ### Method GET ### Endpoint /user-order-data/openorders ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **orders** (array) - A list of open order objects. #### Response Example ```json { "orders": [ { "order_id": "123e4567-e89b-12d3-a456-426614174000", "symbol": "BTC-PERPETUAL", "side": "BUY", "price": 50000.50, "quantity": 0.1, "timestamp": 1678886400 } ] } ``` ``` -------------------------------- ### Load Environment Variables Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Loads environment variables from a .env file. This is typically the first step in configuring the client, ensuring that sensitive information like API keys and base URLs are available. ```python from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() ``` -------------------------------- ### GET /user-position-data/batchclearinghousestates Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-position-data Retrieves a summary of multiple users' perpetual accounts in a batch request. ```APIDOC ## GET /user-position-data/batchclearinghousestates ### Description Retrieves a summary of multiple users' perpetual accounts in a batch request. ### Method GET ### Endpoint /user-position-data/batchclearinghousestates ### Parameters #### Query Parameters - **users** (array of strings) - Required - A list of unique user identifiers. ### Response #### Success Response (200) - **data** (object) - A mapping of user identifiers to their account summaries. (Structure not detailed in provided text) #### Response Example { "example": "{\"data\": {}}" } ``` -------------------------------- ### GET /perpsnapshot Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/builder-guides/copytrading-and-social-trading Retrieve a snapshot of perpetual positions on any market to identify high-signal traders. ```APIDOC ## GET /perpsnapshot ### Description This endpoint allows you to retrieve a snapshot of perpetual positions on various markets. It is useful for identifying traders with large positions, which can be presented to your users as potential high-signal traders. ### Method GET ### Endpoint /perpsnapshot ### Parameters #### Query Parameters - **market** (string) - Required - The market for which to retrieve the snapshot. ### Request Example ``` GET /perpsnapshot?market=ETH-PERPETUAL ``` ### Response #### Success Response (200) - **positions** (array) - An array of position objects, each containing details about a trader's position. - **traderId** (string) - The unique identifier of the trader. - **position** (object) - Details of the trader's position. - **entryPrice** (number) - The average entry price of the position. - **liquidationPrice** (number) - The liquidation price for the position. - **size** (number) - The size of the position. - **margin** (number) - The margin used for the position. #### Response Example ```json { "positions": [ { "traderId": "user123", "position": { "entryPrice": 3000.50, "liquidationPrice": 2800.00, "size": 10.5, "margin": 5000.00 } } ] } ``` ``` -------------------------------- ### GET /user-position-data/activeassetdata Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-position-data Retrieves a user's asset data, including available trade size, leverage on a given asset, and mark price. ```APIDOC ## GET /user-position-data/activeassetdata ### Description Retrieves a user's asset data, including available trade size, leverage on a given asset, and mark price. ### Method GET ### Endpoint /user-position-data/activeassetdata ### Parameters #### Query Parameters - **user** (string) - Required - The unique identifier for the user. ### Response #### Success Response (200) - **data** (object) - Contains the user's active asset data. (Structure not detailed in provided text) #### Response Example { "example": "{\"data\": {}}" } ``` -------------------------------- ### GET /user-order-data/frontendopenorders Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/user-order-data Retrieves a list of a user's open orders with additional frontend information, such as order trigger conditions and TP/SL status. ```APIDOC ## GET /user-order-data/frontendopenorders ### Description Retrieves a list of a user's open orders with additional frontend information, such as order trigger conditions and TP/SL status. ### Method GET ### Endpoint /user-order-data/frontendopenorders ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **orders** (array) - A list of open order objects with frontend details. #### Response Example ```json { "orders": [ { "order_id": "123e4567-e89b-12d3-a456-426614174001", "symbol": "ETH-PERPETUAL", "side": "SELL", "price": 3000.75, "quantity": 0.5, "timestamp": 1678886500, "trigger_condition": "GreaterThanOrEqual", "reduce_only": false, "is_tp_sl": true } ] } ``` ``` -------------------------------- ### L4 Snapshot Client Initialization (JavaScript) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/l4orderbooksnapshots Initializes the L4SnapshotClient, which polls L4 orderbook snapshots. It configures the base API URL and requires an API key via the HYDROMANCER_API_KEY environment variable for authentication. If the API key is missing, it logs an error and exits. ```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 } ``` -------------------------------- ### POST /batchclearinghousestates Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/builder-guides/copytrading-and-social-trading Get positioning updates for multiple followed accounts simultaneously. This is essential for tracking the live positions of traders your users are following. ```APIDOC ## POST /batchclearinghousestates ### Description This endpoint allows you to fetch the current state of multiple clearing house accounts in a single request. It is primarily used to track the live positioning of traders that your users have decided to follow. ### Method POST ### Endpoint /batchclearinghousestates ### Parameters #### Request Body - **userIds** (array) - Required - A list of user IDs for whom to fetch state information. - **userId** (string) - The ID of the user. ### Request Example ```json { "userIds": ["user123", "user456", "user789"] } ``` ### Response #### Success Response (200) - **states** (object) - An object where keys are user IDs and values are their corresponding clearing house states. - **userId** (string) - The user ID. - **state** (object) - The clearing house state for the user. - **position** (object) - The user's current position details. - **entryPrice** (number) - The average entry price. - **liquidationPrice** (number) - The liquidation price. - **size** (number) - The size of the position. - **margin** (number) - The margin of the position. - **balance** (number) - The user's account balance. #### Response Example ```json { "states": { "user123": { "position": { "entryPrice": 3050.00, "liquidationPrice": 2900.00, "size": 8.2, "margin": 4500.00 }, "balance": 10000.00 }, "user456": { "position": { "entryPrice": 3100.00, "liquidationPrice": 2950.00, "size": 12.0, "margin": 6000.00 }, "balance": 15000.00 } } } ``` ``` -------------------------------- ### Download Spot Snapshots Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Downloads spot market snapshots for specified tokens. This method makes a POST request to the API, retrieves binary data, and reports download size and payload format. It handles different payload formats, such as 'multi-zstd'. ```python async def download_snapshots(self, tokens: List[str]) -> Dict[str, Any]: """Download spot market snapshots""" if not self.session: raise RuntimeError("Client session not initialized") headers = { "Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}" } start_time = time.time() async with self.session.post( f'{self.base_url}/info', json={'type': 'spotSnapshots', 'tokens': tokens}, headers=headers ) as response: fetch_time = time.time() - start_time if not response.ok: text = await response.text() raise Exception(f'Spot snapshots request failed: {response.status} - {text}') payload_format = response.headers.get('x-payload-format') binary_data = await response.read() # Format file size in human readable format def format_bytes(bytes_size): for unit in ['B', 'KB', 'MB', 'GB']: if bytes_size < 1024.0: return f"{bytes_size:.2f} {unit}" bytes_size /= 1024.0 return f"{bytes_size:.2f} TB" readable_size = format_bytes(len(binary_data)) print(f"📦 Downloaded {readable_size} ({len(binary_data):,} bytes) in {fetch_time:.3f}s") print(f"🔧 Payload format: {payload_format}") if payload_format == 'multi-zstd': return self.parse_multiple_tokens(binary_data) else: ``` -------------------------------- ### GET /builderfillsbytime Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/builder-guides/copytrading-and-social-trading Query historical fill data within a specified time range. This API allows you to retrieve all trades executed through your builder code for a given period. ```APIDOC ## GET /builderfillsbytime ### Description This API endpoint allows you to retrieve historical trade fill data that occurred through your builder code within a specific time frame. It is useful for auditing, reporting, and analyzing past trading activity. ### Method GET ### Endpoint /builderfillsbytime ### Parameters #### Query Parameters - **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 (default: 100). - **offset** (integer) - Optional - The number of fills to skip (for pagination, default: 0). ### Request Example ``` GET /builderfillsbytime?startTime=1678838400&endTime=1678886400&limit=50 ``` ### Response #### Success Response (200) - **fills** (array) - An array of fill objects. - **fillId** (string) - The unique identifier for the fill. - **orderId** (string) - The ID of the order associated with this fill. - **userId** (string) - The ID of the user whose trade was filled. - **side** (string) - The side of the trade ('buy' or 'sell'). - **size** (number) - The size of the filled portion. - **price** (number) - The price at which the trade was filled. - **timestamp** (integer) - The Unix timestamp of the fill. #### Response Example ```json { "fills": [ { "fillId": "fill567", "orderId": "orderABC", "userId": "userXYZ", "side": "sell", "size": 2.5, "price": 3015.75, "timestamp": 1678880000 }, { "fillId": "fill568", "orderId": "orderABD", "userId": "userXYZ", "side": "buy", "size": 1.0, "price": 3016.00, "timestamp": 1678881000 } ] } ``` ``` -------------------------------- ### Python WebSocket Client for Hydromancer API Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/liquidationfills This Python script illustrates how to connect to the Hydromancer API via WebSocket, authenticate with an API key, and subscribe to liquidation fills. It utilizes the `websocket-client` library and defines callback functions for message handling, including connection opening, message processing (auth, pings, fills, errors), and running the WebSocket application. ```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() ``` -------------------------------- ### POST /info - Download Snapshots Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Downloads the actual spot market snapshot data for specified tokens. This endpoint is typically called after `check_for_updates` indicates that new data is available. ```APIDOC ## POST /info - Download Snapshots ### Description Downloads the actual spot market snapshot data for specified tokens. This endpoint is typically called after `check_for_updates` indicates that new data is available. The response format is indicated by the 'x-payload-format' header. ### Method POST ### Endpoint /info ### Parameters #### Request Body - **type** (string) - Required - Specifies the type of information to retrieve, should be 'spotSnapshots'. - **tokens** (array of strings) - Required - A list of tokens for which to download spot snapshots (e.g., ["UBTC", "PUP"]). ### Request Example ```json { "type": "spotSnapshots", "tokens": ["UBTC", "PUP"] } ``` ### Response #### Success Response (200) - The response body contains binary data representing the spot snapshots. - **x-payload-format** (string) - Header indicating the payload format (e.g., 'multi-zstd'). #### Response Example (Binary data, format depends on 'x-payload-format' header. Example if parsed from 'multi-zstd') ```json { "UBTC": { ... snapshot data ... }, "PUP": { ... snapshot data ... } } ``` ``` -------------------------------- ### GET /info - Account Value Snapshot Timestamp Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/accountvaluesnapshot Retrieves the timestamp or snapshot ID for the latest account value snapshot. This is used to check for updates before downloading new data. ```APIDOC ## GET /info - Account Value Snapshot Timestamp ### Description Checks if account value snapshots have been updated since the last poll by comparing timestamps. ### Method POST ### Endpoint /info ### Parameters #### Request Body - **type** (string) - Required - Specifies the type of information requested, should be 'accountValueSnapshotTimestamp'. ### Request Example ```json { "type": "accountValueSnapshotTimestamp" } ``` ### Response #### Success Response (200) - **timestamp** (string) - The timestamp of the latest snapshot, or **snapshot_id** (string) if timestamp is not available. #### Response Example ```json { "timestamp": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### POST /info Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/historical-data/usernonfundingledgerupdates This endpoint retrieves non-funding ledger updates for a specified user. You can filter the results by providing a start time and an optional end time. ```APIDOC ## POST /info ### Description Retrieves non-funding ledger updates for a specified user within a given time frame. ### Method POST ### Endpoint https://api.hydromancer.xyz/info ### Parameters #### Query Parameters None #### Request Body - **type** (string) - Required - Must be `"userNonFundingLedgerUpdates"` - **user** (string) - Required - Ethereum address (0x-prefixed, 42 characters) - **startTime** (int) - Required - Start time in ms (inclusive) - **endTime** (int) - Optional - End time in ms ### Request Example ```json { "type": "userNonFundingLedgerUpdates", "user": "0x0000000000000000000000000000000000000000", "startTime": 0 } ``` ### Response #### Success Response (200) - **time** (int) - Timestamp of the ledger update. - **hash** (string) - Transaction hash. - **delta** (object) - Details of the ledger change. - **type** (string) - Type of the delta (e.g., `"internalTransfer"`). - **usdc** (string) - Amount of USDC involved. - **user** (string) - The user's Ethereum address involved in the delta. - **destination** (string) - The destination address for the transfer. - **fee** (string) - Any transaction fee associated with the delta. #### Response Example ```json [ { "time": 1710245329284, "hash": "0x27bb0996075790365f590408011f7b0201fc004e9cf81a12ad03c4847b64c5cd", "delta": { "type": "internalTransfer", "usdc": "1.0", "user": "0xc272fa7d73e8ed66e65a6281570d3788bea5e7a4", "destination": "0x0000000000000000000000000000000000000000", "fee": "0.0" } } ] ``` ``` -------------------------------- ### Subscribe to User Fills via WebSocket Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/websocket/userfills This snippet demonstrates how to establish a WebSocket connection, authenticate with an API key, and subscribe to user fill events. It handles connected, ping, and userFills message types. Dependencies include the 'ws' library for Node.js and 'websocket' for Python. Outputs logged fill counts and handles pongs. ```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: 'userFills', addresses: ['0x010461c14e146ac35fe42271bdc1134ee31c703a'] } })); } else if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } else if (msg.type === 'userFills') { console.log(`Received ${msg.fills.length} fills`); } }); ``` ```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": "userFills", "addresses": ["0x010461c14e146ac35fe42271bdc1134ee31c703a"] } })) elif msg['type'] == 'ping': print("Received ping, sending pong") ws.send(json.dumps({'type': 'pong'})) elif msg['type'] == 'userFills': 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() ``` -------------------------------- ### Get L4 Snapshot Metadata (JSON Request) Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/l4orderbooksnapshots This JSON object is used to request the latest L4 orderbook snapshot metadata. It specifies the type of information requested. ```json { "type": "l4SnapshotTimestamp" } ``` -------------------------------- ### Manage Async Client Session Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/market-data/spotsnapshot Manages the asynchronous HTTP client session using context managers (__aenter__ and __aexit__). This ensures that the aiohttp.ClientSession is properly initialized before use and closed gracefully afterward, preventing resource leaks. ```python 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() ``` -------------------------------- ### POST /info - Get All Mids Source: https://docs.hydromancer.xyz/hydromancer-better-hyperliquid-apis/rest-api/asset-data/allmids Retrieves all mid prices for supported decentralized exchanges. This endpoint currently only returns perpetual futures mid prices. ```APIDOC ## POST /info ### Description Retrieves all mid prices for supported decentralized exchanges. This endpoint currently only returns perpetual futures mid prices. ### Method POST ### Endpoint https://api.hydromancer.xyz/info ### Parameters #### Request Body - **type** (string) - Required - Must be `"allMids"` - **dex** (string) - Optional - Defaults to the first dex. Can be set to `ALL_DEXS` for mids of all dexes. ### Request Example ```json { "type": "allMids", "dex": "" } ``` ### Response #### Success Response (200) - **BTC** (string) - Mid price for BTC. - **ETH** (string) - Mid price for ETH. - ... (other cryptocurrency mid prices) #### Response Example ```json { "BTC": "96500.50", "ETH": "3000.21" } ``` ```