Hyperliquid SDK

repository·main·Indexed 43 days ago

https://github.com/nomeida/hyperliquid

A TypeScript SDK for the Hyperliquid API (v1.7.7) providing complete coverage for REST and WebSocket endpoints. It supports order placement, fund transfers, and real-time market data subscriptions for both Perpetual and Spot markets. Features include automatic trailing zero handling for prices and sizes, low-latency WebSocket POST execution, and support for Node.js (v22+), browser UMD, and ESM environments.

Tokens
15.6K
Snippets
57
Records
68
Agent score
54%

What's inside Hyperliquid

  1. Supported features in browser environments

    main

    The Hyperliquid SDK provides the following capabilities when running in a browser:

    • REST API calls: Standard request/response interactions.
    • WebSocket real-time updates: Real-time data streaming.
    • Wallet integration: Via ethers.js.
    • Asset management: Asset conversion and management.
    • Market data: Real-time market data subscriptions.
  2. Manage Asset Map refreshes

    main

    The SDK automatically refreshes asset maps (used for symbol conversion) every 60 seconds. To prevent rate limiting or reduce overhead when running multiple instances, you can disable or control this behavior.

    When to disable:

    • Running multiple SDK instances from the same IP.
    • Only performing order placement/cancellation without needing symbol conversion.
    • Experiencing HTTP 429 (rate limit) errors.
    • Using external price oracles.

    Configuration and Runtime Methods:

    • disableAssetMapRefresh: true: Disables automatic refresh in the constructor.
    • assetMapRefreshIntervalMs: <number>: Sets the interval (e.g., 300000 for 5 minutes).
    • sdk.isAssetMapRefreshEnabled(): Checks current status.
    • sdk.disableAssetMapRefresh(): Disables at runtime.
    • sdk.enableAssetMapRefresh(): Enables at runtime.
    • sdk.setAssetMapRefreshInterval(ms): Updates interval at runtime.
    • await sdk.refreshAssetMapsNow(): Triggers a manual refresh.
    const sdk = new Hyperliquid({
      privateKey: 'your-private-key',
      testnet: false,
      enableWs: false,
      disableAssetMapRefresh: true,
    });
    
    // Manual refresh if needed
    await sdk.refreshAssetMapsNow();
  3. Execute low-latency trades via WebSocket POST

    main

    For high-frequency trading, the SDK allows executing exchange methods over WebSocket instead of HTTP using sdk.wsPayloads. This provides lower latency and handles signing/nonces automatically.

    Requirements:

    • enableWs: true must be set in the constructor.
    • privateKey must be provided for authenticated exchange methods.
    • You must call await sdk.connect() and ensure the connection is established before sending requests.

    Core Method Groups:

    • Order Management: placeOrder, cancelOrder, cancelAllOrders, modifyOrder, batchModifyOrders.
    • TWAP: placeTwapOrder, cancelTwapOrder.
    • Account/Leverage: updateLeverage, updateIsolatedMargin.
    • Transfers: transferBetweenSpotAndPerp, usdTransfer, spotTransfer, initiateWithdrawal, vaultTransfer.
    • Advanced: approveAgent, approveBuilderFee, scheduleCancel, setReferrer.
    const { Hyperliquid } = require('hyperliquid');
    
    async function testWebSocketPostRequests() {
      const sdk = new Hyperliquid({
        enableWs: true,
        privateKey: 'your_private_key',
        testnet: false,
      });
    
      try {
        await sdk.connect();
        await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for connection
    
        // Example: Place Order
        const orderResponse = await sdk.wsPayloads.placeOrder({
          coin: 'BTC-PERP',
          is_buy: true,
          sz: '0.001',
          limit_px: '50000',
          order_type: { limit: { tif: 'Gtc' } },
          reduce_only: false,
        });
        console.log('Place Order Response:', orderResponse);
    
        // Example: Cancel All Orders
        const cancelAllResponse = await sdk.wsPayloads.cancelAllOrders();
        console.log('Cancel All Orders Response:', cancelAllResponse);
    
      } catch (error) {
        console.error('Error:', error);
      } finally {
        sdk.disconnect();
      }
    }
  4. Manage WebSocket subscription limits

    main

    The Hyperliquid API limits WebSocket subscriptions to 1000 per IP address.

    To avoid errors:

    • Monitor your current count using sdk.ws.getSubscriptionCount().
    • Unsubscribe from feeds that are no longer needed.
    • Reuse existing subscriptions where possible.

    If you attempt to exceed 1000 subscriptions, the SDK will throw an error.

  5. Automatic handling of trailing zeros in prices and sizes

    main

    The Hyperliquid API requires that price (p) and size (s) fields do not contain trailing zeros (e.g., 12345.0 must be 12345).

    This SDK automatically handles this requirement for you. When using methods like placeOrder, modifyOrder, or batchModifyOrders, the SDK will strip trailing zeros from numeric or string values. You can safely pass values as strings or numbers.

    // Both of these will work correctly as the SDK strips trailing zeros
    await sdk.exchange.placeOrder({
      coin: 'BTC-PERP',
      is_buy: true,
      sz: '1.0000', // Becomes "1"
      limit_px: '50000.00', // Becomes "50000"
      reduce_only: false,
      order_type: { limit: { tif: 'Gtc' } },
    });
    
    await sdk.exchange.placeOrder({
      coin: 'BTC-PERP',
      is_buy: true,
      sz: 1, 
      limit_px: 50000,
      reduce_only: false,
      order_type: { limit: { tif: 'Gtc' } },
    });
  6. Format spot token parameters for transfers

    main

    When performing spot token operations (like sdk.exchange.spotTransfer), the token parameter must follow a specific string format: "TOKEN_NAME:TOKEN_ADDRESS".

    To ensure correctness, you can retrieve the required metadata using sdk.info.spot.getSpotMeta(). Each token object in the returned array contains a tokenId field which serves as the address.

    Correct Format Example: "PURR:0xeb62eee3685fc4c43992febcd9e75443"

    // Transfer spot tokens to another address
    // IMPORTANT: Token format must be "TOKEN_NAME:TOKEN_ADDRESS"
    sdk.exchange
      .spotTransfer(
        '0x1234567890123456789012345678901234567890', // destination address
        'PURR:0xeb62eee3685fc4c43992febcd9e75443', // token format: "NAME:ADDRESS"
        '1.0' // amount as string
      )
      .then(transferResult => {
        console.log(transferResult);
      })
      .catch(error => {
        console.error('Error transferring spot tokens:', error);
      });
  7. Install the Hyperliquid SDK

    main

    You can install the Hyperliquid SDK using any of the following package managers:

    # npm
    npm i --save hyperliquid
    
    # yarn
    yarn add hyperliquid
    
    # pnpm
    pnpm add hyperliquid
    
    # bun
    bun i hyperliquid
    npm i --save hyperliquid
  8. Use the Hyperliquid SDK in a browser via ES Module Import

    main

    If you are using a modern build tool or an environment that supports ES modules, you can import the Hyperliquid class directly from the hyperliquid package.

    import { Hyperliquid } from 'hyperliquid';
    
    const sdk = new Hyperliquid({
        testnet: true,
        enableWs: true
    });
  9. Browser security and best practices

    main

    When using the SDK in a browser, follow these security and operational guidelines:

    Security

    • Private Key Handling: Never store private keys in browser storage (e.g., localStorage). Use Web3 wallet providers for key management.
    • CORS: All API endpoints support CORS, so no additional configuration is required for browser-based requests.

    Operations

    • Connection Lifecycle: Always call connect() before usage and disconnect() when the session is complete.
    • WebSocket Management: The SDK manages WebSocket connections with automatic reconnection, but you should still implement logic to handle reconnection events.
    • Rate Limiting: Rate limiting is handled automatically by the SDK.
  10. Use the Hyperliquid SDK in the browser

    main

    The SDK provides two bundles for direct web usage:

    1. UMD Bundle (browser.global.js): Exposes the SDK globally as HyperliquidSDK. Use this with standard <script> tags.
    2. ESM Bundle (browser.js): Use this with ES modules (import syntax).

    For detailed instructions, refer to the Browser Usage Guide.

    <!-- Global bundle (UMD) -->
    <script src="https://unpkg.com/hyperliquid/dist/browser.global.js"></script>
    
    <!-- ESM bundle -->
    <script type="module">
      import { Hyperliquid } from 'https://unpkg.com/hyperliquid/dist/browser.js';
    </script>
  11. Configure WebSocket functionality in Node.js

    main

    The SDK uses a native WebSocket implementation which requires Node.js version 22 or higher.

    If you are using an older version of Node.js, you must manually install the ws package to enable WebSocket functionality:

    npm install ws