Hyperliquid MCP Server

Hyperliquid MCP Server - Complete Implementation

This MCP (Model Context Protocol) server provides a comprehensive wrapper around the Hyperliquid SDK, exposing the full range of trading capabilities for both spot and futures markets to AI assistants. It enables AI assistants to interact with the Hyperliquid exchange for retrieving market data, executing trades, managing positions, and more.

Features

Comprehensive API Coverage

  • Complete implementation of all Hyperliquid SDK APIs for both spot and futures trading
  • Market data retrieval (prices, order books, candles)
  • Order placement and management (market, limit, trigger, TWAP)
  • Position management (leverage, margin, closing)
  • Account information and balances
  • Funding rate information
  • Transfers and withdrawals
  • Vault management
  • Sub-account management
  • Referral system integration

Technical Features

  • Proper authentication using both private key and wallet address
  • Comprehensive error handling and validation
  • Real-time market data access
  • Support for client order IDs (cloid) for order tracking
  • Support for both testnet and mainnet

Identified APIs and Implementation

Based on a thorough examination of the Hyperliquid SDK repository, I've identified and implemented the following APIs:

Market Data APIs

APIDescriptionImplementation
getAllMidsGet all mid prices for all available cryptocurrenciesDirect mapping to SDK's info.getAllMids()
getL2BookGet order book data for a symbolDirect mapping to SDK's info.getL2Book()
getCandleSnapshotGet historical candle dataDirect mapping to SDK's info.getCandleSnapshot()
getMetaAndAssetCtxsGet metadata and asset contexts for perpetual futuresDirect mapping to SDK's info.perpetuals.getMetaAndAssetCtxs()
getSpotMetaAndAssetCtxsGet metadata and asset contexts for spot marketsDirect mapping to SDK's info.spot.getSpotMetaAndAssetCtxs()

Account Information APIs

APIDescriptionImplementation
getClearinghouseStateGet perpetual futures account stateDirect mapping to SDK's info.perpetuals.getClearinghouseState()
getSpotClearinghouseStateGet spot account stateDirect mapping to SDK's info.spot.getSpotClearinghouseState()
getUserOpenOrdersGet open ordersDirect mapping to SDK's info.getUserOpenOrders()
getUserFillsGet trade fillsDirect mapping to SDK's info.getUserFills()
getUserFillsByTimeGet trade fills by time rangeDirect mapping to SDK's info.getUserFillsByTime()
getUserFundingGet funding paymentsDirect mapping to SDK's info.perpetuals.getUserFunding()
getFundingHistoryGet funding rate historyDirect mapping to SDK's info.perpetuals.getFundingHistory()
getPredictedFundingsGet predicted funding ratesDirect mapping to SDK's info.perpetuals.getPredictedFundings()

Order Management APIs

APIDescriptionImplementation
placeOrderPlace an order (market, limit, trigger)Direct mapping to SDK's exchange.placeOrder()
placeTwapOrderPlace a TWAP orderDirect mapping to SDK's exchange.placeTwapOrder()
cancelOrderCancel an orderDirect mapping to SDK's exchange.cancelOrder()
cancelOrderByCloidCancel an order by client order IDDirect mapping to SDK's exchange.cancelOrderByCloid()
cancelTwapOrderCancel a TWAP orderDirect mapping to SDK's exchange.cancelTwapOrder()
modifyOrderModify an existing orderDirect mapping to SDK's exchange.modifyOrder()

Position Management APIs

APIDescriptionImplementation
updateLeverageUpdate leverage for a symbolDirect mapping to SDK's exchange.updateLeverage()
updateIsolatedMarginUpdate isolated margin for a positionDirect mapping to SDK's exchange.updateIsolatedMargin()
marketCloseClose a position with a market orderImplemented via SDK's custom.marketClose()
closeAllPositionsClose all positionsImplemented via SDK's custom.closeAllPositions()

Transfer and Withdrawal APIs

APIDescriptionImplementation
usdTransferTransfer USDC to another walletDirect mapping to SDK's exchange.usdTransfer()
initiateWithdrawalWithdraw USDC to ArbitrumDirect mapping to SDK's exchange.initiateWithdrawal()
spotTransferTransfer spot assets to another walletDirect mapping to SDK's exchange.spotTransfer()
transferBetweenSpotAndPerpTransfer between spot and perpetual accountsDirect mapping to SDK's exchange.transferBetweenSpotAndPerp()

Vault Management APIs

APIDescriptionImplementation
createVaultCreate a new vaultDirect mapping to SDK's exchange.createVault()
getVaultDetailsGet vault detailsDirect mapping to SDK's info.getVaultDetails()
vaultTransferTransfer funds between vault and walletDirect mapping to SDK's exchange.vaultTransfer()
vaultDistributeDistribute funds from vault to followersDirect mapping to SDK's exchange.vaultDistribute()
vaultModifyModify vault configurationDirect mapping to SDK's exchange.vaultModify()

Sub-Account Management APIs

APIDescriptionImplementation
createSubAccountCreate a new sub-accountDirect mapping to SDK's exchange.createSubAccount()
getSubAccountsGet all sub-accountsDirect mapping to SDK's info.getSubAccounts()
subAccountTransferTransfer funds between sub-accounts (perpetual)Direct mapping to SDK's exchange.subAccountTransfer()
subAccountSpotTransferTransfer spot assets between sub-accountsDirect mapping to SDK's exchange.subAccountSpotTransfer()

Miscellaneous APIs

APIDescriptionImplementation
setReferrerSet a referrer codeDirect mapping to SDK's exchange.setReferrer()
referralGet referral informationDirect mapping to SDK's info.referral()
setDisplayNameSet display name for leaderboardDirect mapping to SDK's exchange.setDisplayName()
getUserRoleGet the role of a userDirect mapping to SDK's info.getUserRole()
approveAgentApprove an agent to trade on behalf of the userDirect mapping to SDK's exchange.approveAgent()
approveBuilderFeeApprove a builder feeDirect mapping to SDK's exchange.approveBuilderFee()

Authentication Implementation

The MCP server implements authentication using both private key and wallet address:

  1. Private Key Authentication: The server accepts a private key via environment variable or configuration file. This private key is used to sign transactions and authenticate with the Hyperliquid API.
  2. Wallet Address Authentication: The server also accepts a wallet address, which is used for read-only operations. If a private key is provided but no wallet address, the server will derive the wallet address from the private key.
  3. Vault Address Support: For vault operations, the server also supports specifying a vault address.

Authentication validation is performed before executing any operation that requires it, ensuring that the user is properly authenticated before attempting to execute trades or access account information.

Error Handling and Validation

The MCP server implements comprehensive error handling and validation:

  1. Client Validation: Before executing any operation, the server validates that the Hyperliquid client is initialized.
  2. Authentication Validation: For operations that require authentication, the server validates that the user is properly authenticated.
  3. Parameter Validation: The server validates all parameters before passing them to the SDK, ensuring that they are of the correct type and format.
  4. Error Handling: The server catches and handles all errors from the SDK, providing clear error messages to the user.
  5. Logging: The server logs all operations and errors, making it easier to debug issues.

Implementation Challenges and Special Considerations

1. Market Order Implementation

Hyperliquid's API doesn't have a direct "market order" endpoint. Instead, market orders are implemented as aggressive limit orders with Immediate-or-Cancel (IOC) time-in-force. To ensure execution, we apply a slippage factor to the current price:

// Apply 0.5% slippage for market orders to ensure execution const slippagePrice = isBuy ? currentPrice * 1.005 : // Buy 0.5% higher than mid price currentPrice * 0.995; // Sell 0.5% lower than mid price

2. Spot Market Symbol Handling

Spot market symbols in Hyperliquid have a "-SPOT" suffix. The MCP server handles this transparently, adding the suffix when needed:

// For spot market orders, we need to use the same API endpoint but with the spot symbol const spotSymbol = `${symbol}-SPOT`;

3. Order Response Parsing

The response format from the Hyperliquid API for order placement is complex and requires careful parsing to extract the order ID:

// Extract order ID from the response let orderId = null; if (result.response && result.response.data && result.response.data.statuses) { for (const status of result.response.data.statuses) { if (status.resting) { orderId = status.resting.oid; break; } else if (status.filled) { orderId = status.filled.oid; break; } } }

4. Numeric Value Handling

The Hyperliquid API often returns numeric values as strings. The MCP server converts these to numbers for easier consumption:

// Convert string values to numbers const result = {}; for (const [symbol, price] of Object.entries(allMids)) { result[symbol] = parseFloat(price); }

5. WebSocket Support

The Hyperliquid SDK supports WebSocket connections for real-time data. The MCP server initializes the client with WebSocket support enabled:

client = new Hyperliquid({ privateKey: config.privateKey, testnet: config.testnet, walletAddress: config.walletAddress, vaultAddress: config.vaultAddress, enableWs: true });

Prerequisites

  • Node.js (v14 or higher)
  • A Hyperliquid account
  • An Ethereum private key for authentication (required for trading)
  • Your wallet address (required for trading)

Configuration

The server can be configured using environment variables or a configuration file:

Environment Variables

  • HYPERLIQUID_PRIVATE_KEY: Your Ethereum private key for authentication (required for trading)
  • HYPERLIQUID_WALLET_ADDRESS: Your wallet address (required for trading)
  • HYPERLIQUID_VAULT_ADDRESS: Your vault address (optional, for vault operations)
  • HYPERLIQUID_TESTNET: Set to 'true' to use testnet, 'false' for mainnet (default: false)
  • LOG_LEVEL: Logging level - 'debug', 'info', 'warn', or 'error' (default: 'info')

Configuration File

You can also create a .hyperliquid-config.json file in the same directory as the server with the following structure:

{ "privateKey": "your-ethereum-private-key", "walletAddress": "your-wallet-address", "vaultAddress": "your-vault-address", "testnet": false, "logLevel": "info", "popularCoins": ["BTC", "ETH", "SOL", "AVAX", "ARB", "DOGE", "LINK", "MATIC"] }

Running the Server

Start the server by running:

node hyperliquid-mcp-server-complete.js

Available Tools

The server provides a comprehensive set of tools for interacting with the Hyperliquid exchange. Here are some examples:

Market Data Tools

  • getMarketPrice: Get the current price for a specified cryptocurrency
  • getOrderBook: Get the current order book for a specified cryptocurrency
  • getCandleData: Get historical candle data for a specified cryptocurrency
  • getAllMids: Get all mid prices for all available cryptocurrencies

Account Information Tools

  • getAccountInfo: Get information about the user's perpetual futures account
  • getSpotAccountInfo: Get information about the user's spot trading account
  • getUserOpenOrders: Get all open orders for the user
  • getUserFills: Get recent fills for the user

Order Management Tools

  • placeMarketOrder: Place a market order for a specified cryptocurrency
  • placeLimitOrder: Place a limit order for a specified cryptocurrency
  • placeTriggerOrder: Place a trigger order (stop loss or take profit)
  • placeTwapOrder: Place a TWAP (Time-Weighted Average Price) order
  • cancelOrder: Cancel an existing order
  • cancelOrderByCloid: Cancel an order by client order ID
  • cancelAllOrders: Cancel all open orders
  • modifyOrder: Modify an existing order

Position Management Tools

  • updateLeverage: Update the leverage for a specified cryptocurrency
  • updateIsolatedMargin: Update the isolated margin for a position
  • closePosition: Close an open position
  • closeAllPositions: Close all open positions

Transfer and Withdrawal Tools

  • usdTransfer: Transfer USDC to another wallet
  • initiateWithdrawal: Withdraw USDC to Arbitrum
  • spotTransfer: Transfer spot assets to another wallet
  • transferBetweenSpotAndPerp: Transfer funds between spot and perpetual accounts

Vault Management Tools

  • createVault: Create a new vault
  • getVaultDetails: Get details about a vault
  • vaultTransfer: Transfer funds between vault and perpetual futures wallet
  • vaultDistribute: Distribute funds from a vault to followers
  • vaultModify: Modify vault configuration

Sub-Account Management Tools

  • createSubAccount: Create a new sub-account
  • getSubAccounts: Get all sub-accounts for the user
  • subAccountTransfer: Transfer funds between sub-accounts (perpetual)
  • subAccountSpotTransfer: Transfer spot assets between sub-accounts

Available Resources

The server provides the following resources:

  • market-data: Market data for popular cryptocurrencies in the perpetual futures market
  • account-info: Account information including balances and positions for perpetual futures
  • spot-market-data: Market data for popular cryptocurrencies in the spot market
  • spot-account-info: Account information including balances for spot trading
  • open-orders: All open orders for the user
  • positions: All open positions for the user
  • funding-rates: Current funding rates for all cryptocurrencies

Security Considerations

  • Private Key Security: Your Ethereum private key provides full access to your funds. Never share it or expose it in public repositories.
  • Use Testnet First: Always test your setup on testnet before using real funds on mainnet.
  • Limit Access: Restrict access to the MCP server to trusted AI assistants and applications.

Disclaimer

Trading cryptocurrencies involves significant risk. This tool is provided for educational and informational purposes only. Always understand the risks involved before trading, and never trade with funds you cannot afford to lose.

ID: 8j15gr3bne