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
API | Description | Implementation |
---|---|---|
getAllMids | Get all mid prices for all available cryptocurrencies | Direct mapping to SDK's info.getAllMids() |
getL2Book | Get order book data for a symbol | Direct mapping to SDK's info.getL2Book() |
getCandleSnapshot | Get historical candle data | Direct mapping to SDK's info.getCandleSnapshot() |
getMetaAndAssetCtxs | Get metadata and asset contexts for perpetual futures | Direct mapping to SDK's info.perpetuals.getMetaAndAssetCtxs() |
getSpotMetaAndAssetCtxs | Get metadata and asset contexts for spot markets | Direct mapping to SDK's info.spot.getSpotMetaAndAssetCtxs() |
Account Information APIs
API | Description | Implementation |
---|---|---|
getClearinghouseState | Get perpetual futures account state | Direct mapping to SDK's info.perpetuals.getClearinghouseState() |
getSpotClearinghouseState | Get spot account state | Direct mapping to SDK's info.spot.getSpotClearinghouseState() |
getUserOpenOrders | Get open orders | Direct mapping to SDK's info.getUserOpenOrders() |
getUserFills | Get trade fills | Direct mapping to SDK's info.getUserFills() |
getUserFillsByTime | Get trade fills by time range | Direct mapping to SDK's info.getUserFillsByTime() |
getUserFunding | Get funding payments | Direct mapping to SDK's info.perpetuals.getUserFunding() |
getFundingHistory | Get funding rate history | Direct mapping to SDK's info.perpetuals.getFundingHistory() |
getPredictedFundings | Get predicted funding rates | Direct mapping to SDK's info.perpetuals.getPredictedFundings() |
Order Management APIs
API | Description | Implementation |
---|---|---|
placeOrder | Place an order (market, limit, trigger) | Direct mapping to SDK's exchange.placeOrder() |
placeTwapOrder | Place a TWAP order | Direct mapping to SDK's exchange.placeTwapOrder() |
cancelOrder | Cancel an order | Direct mapping to SDK's exchange.cancelOrder() |
cancelOrderByCloid | Cancel an order by client order ID | Direct mapping to SDK's exchange.cancelOrderByCloid() |
cancelTwapOrder | Cancel a TWAP order | Direct mapping to SDK's exchange.cancelTwapOrder() |
modifyOrder | Modify an existing order | Direct mapping to SDK's exchange.modifyOrder() |
Position Management APIs
API | Description | Implementation |
---|---|---|
updateLeverage | Update leverage for a symbol | Direct mapping to SDK's exchange.updateLeverage() |
updateIsolatedMargin | Update isolated margin for a position | Direct mapping to SDK's exchange.updateIsolatedMargin() |
marketClose | Close a position with a market order | Implemented via SDK's custom.marketClose() |
closeAllPositions | Close all positions | Implemented via SDK's custom.closeAllPositions() |
Transfer and Withdrawal APIs
API | Description | Implementation |
---|---|---|
usdTransfer | Transfer USDC to another wallet | Direct mapping to SDK's exchange.usdTransfer() |
initiateWithdrawal | Withdraw USDC to Arbitrum | Direct mapping to SDK's exchange.initiateWithdrawal() |
spotTransfer | Transfer spot assets to another wallet | Direct mapping to SDK's exchange.spotTransfer() |
transferBetweenSpotAndPerp | Transfer between spot and perpetual accounts | Direct mapping to SDK's exchange.transferBetweenSpotAndPerp() |
Vault Management APIs
API | Description | Implementation |
---|---|---|
createVault | Create a new vault | Direct mapping to SDK's exchange.createVault() |
getVaultDetails | Get vault details | Direct mapping to SDK's info.getVaultDetails() |
vaultTransfer | Transfer funds between vault and wallet | Direct mapping to SDK's exchange.vaultTransfer() |
vaultDistribute | Distribute funds from vault to followers | Direct mapping to SDK's exchange.vaultDistribute() |
vaultModify | Modify vault configuration | Direct mapping to SDK's exchange.vaultModify() |
Sub-Account Management APIs
API | Description | Implementation |
---|---|---|
createSubAccount | Create a new sub-account | Direct mapping to SDK's exchange.createSubAccount() |
getSubAccounts | Get all sub-accounts | Direct mapping to SDK's info.getSubAccounts() |
subAccountTransfer | Transfer funds between sub-accounts (perpetual) | Direct mapping to SDK's exchange.subAccountTransfer() |
subAccountSpotTransfer | Transfer spot assets between sub-accounts | Direct mapping to SDK's exchange.subAccountSpotTransfer() |
Miscellaneous APIs
API | Description | Implementation |
---|---|---|
setReferrer | Set a referrer code | Direct mapping to SDK's exchange.setReferrer() |
referral | Get referral information | Direct mapping to SDK's info.referral() |
setDisplayName | Set display name for leaderboard | Direct mapping to SDK's exchange.setDisplayName() |
getUserRole | Get the role of a user | Direct mapping to SDK's info.getUserRole() |
approveAgent | Approve an agent to trade on behalf of the user | Direct mapping to SDK's exchange.approveAgent() |
approveBuilderFee | Approve a builder fee | Direct mapping to SDK's exchange.approveBuilderFee() |
Authentication Implementation
The MCP server implements authentication using both private key and wallet address:
- 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.
- 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.
- 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:
- Client Validation: Before executing any operation, the server validates that the Hyperliquid client is initialized.
- Authentication Validation: For operations that require authentication, the server validates that the user is properly authenticated.
- Parameter Validation: The server validates all parameters before passing them to the SDK, ensuring that they are of the correct type and format.
- Error Handling: The server catches and handles all errors from the SDK, providing clear error messages to the user.
- 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:
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:
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:
4. Numeric Value Handling
The Hyperliquid API often returns numeric values as strings. The MCP server converts these to numbers for easier consumption:
5. WebSocket Support
The Hyperliquid SDK supports WebSocket connections for real-time data. The MCP server initializes the client with WebSocket support enabled:
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:
Running the Server
Start the server by running:
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 cryptocurrencygetOrderBook
: Get the current order book for a specified cryptocurrencygetCandleData
: Get historical candle data for a specified cryptocurrencygetAllMids
: Get all mid prices for all available cryptocurrencies
Account Information Tools
getAccountInfo
: Get information about the user's perpetual futures accountgetSpotAccountInfo
: Get information about the user's spot trading accountgetUserOpenOrders
: Get all open orders for the usergetUserFills
: Get recent fills for the user
Order Management Tools
placeMarketOrder
: Place a market order for a specified cryptocurrencyplaceLimitOrder
: Place a limit order for a specified cryptocurrencyplaceTriggerOrder
: Place a trigger order (stop loss or take profit)placeTwapOrder
: Place a TWAP (Time-Weighted Average Price) ordercancelOrder
: Cancel an existing ordercancelOrderByCloid
: Cancel an order by client order IDcancelAllOrders
: Cancel all open ordersmodifyOrder
: Modify an existing order
Position Management Tools
updateLeverage
: Update the leverage for a specified cryptocurrencyupdateIsolatedMargin
: Update the isolated margin for a positionclosePosition
: Close an open positioncloseAllPositions
: Close all open positions
Transfer and Withdrawal Tools
usdTransfer
: Transfer USDC to another walletinitiateWithdrawal
: Withdraw USDC to ArbitrumspotTransfer
: Transfer spot assets to another wallettransferBetweenSpotAndPerp
: Transfer funds between spot and perpetual accounts
Vault Management Tools
createVault
: Create a new vaultgetVaultDetails
: Get details about a vaultvaultTransfer
: Transfer funds between vault and perpetual futures walletvaultDistribute
: Distribute funds from a vault to followersvaultModify
: Modify vault configuration
Sub-Account Management Tools
createSubAccount
: Create a new sub-accountgetSubAccounts
: Get all sub-accounts for the usersubAccountTransfer
: 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 marketaccount-info
: Account information including balances and positions for perpetual futuresspot-market-data
: Market data for popular cryptocurrencies in the spot marketspot-account-info
: Account information including balances for spot tradingopen-orders
: All open orders for the userpositions
: All open positions for the userfunding-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.
This server cannot be installed
A comprehensive MCP server that provides a complete wrapper around the Hyperliquid SDK, enabling AI assistants to interact with both spot and futures markets for retrieving data, executing trades, and managing positions.
Appeared in Searches
- Information about trading or trade-related activities
- A server for analyzing A-shares, Hong Kong stocks, and U.S. stocks; generating daily stock trend reports; and assessing specific company stock value trends
- An example MCP for client prototyping in a business context with a public API call
- Resources for Analyzing Stock Patterns