npm package: @mseep/hyperliquid-mcp-server
Description: Hyperliquid MCP Server - A comprehensive wrapper around the Hyperliquid SDK for AI assistants
Author: TradingBalthazar
Latest version: 1.0.0

# 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:

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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
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:

```json
{
  "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:

```bash
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.