Skip to content

kkggg55/hyperliquid-go-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hyperliquid Go SDK

Go Reference License: MIT

Go SDK for Hyperliquid. Supports REST API and WebSocket connections for perpetuals and spot trading.

Features

  • REST API and WebSocket support
  • Perpetuals and spot trading
  • Type-safe responses with error handling
  • Auto-reconnection for WebSocket
  • Rate limiting (1200 requests/minute)

Installation

go get github.com/sxlgg/hyperliquid-sdk-go

Quick Start

REST API

package main

import (
    "fmt"
    "log"
    "github.com/sxlgg/hyperliquid-sdk-go/hyperliquid/api"
    "github.com/sxlgg/hyperliquid-sdk-go/hyperliquid/api/info/perpetuals"
)

func main() {
    client := hyperliquid.NewClient()

    // Get perpetuals metadata
    meta, err := perpetuals.GetMeta(client, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Assets: %d\n", len(meta.Universe))

    // Get user account state
    state, err := perpetuals.GetClearinghouseState(client, "0x...", nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Account Value: %s\n", state.MarginSummary.AccountValue)
}

WebSocket

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "github.com/sxlgg/hyperliquid-sdk-go/hyperliquid/websocket"
)

func main() {
    client := hyperliquid_websocket.NewClient()

    if err := client.Connect(); err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect()

    // Handle price updates
    client.SetHandler("allMids", func(data json.RawMessage) error {
        var mids hyperliquid_websocket.AllMids
        if err := json.Unmarshal(data, &mids); err != nil {
            return err
        }
        for coin, price := range mids.Mids {
            fmt.Printf("%s: $%s\n", coin, price)
        }
        return nil
    })

    // Subscribe to all mids
    subscription := hyperliquid_websocket.NewAllMidsSubscription(nil)
    if err := client.Subscribe(subscription); err != nil {
        log.Fatal(err)
    }

    select {} // Keep running
}

Trading

package main

import (
    "log"
    "github.com/sxlgg/hyperliquid-sdk-go/hyperliquid/api"
    "github.com/sxlgg/hyperliquid-sdk-go/hyperliquid/api/exchange"
)

func main() {
    client := hyperliquid.NewClient()

    // Create limit order
    order := exchange.CreateLimitOrder(
        0,        // ETH-USD
        true,     // Buy
        "2000",   // Price
        "0.1",    // Size
        false,    // Reduce only
        "Gtc",    // Time in force
        nil,      // Client order ID
    )

    // Place order (signature generation required)
    signature := exchange.Signature{R: "0x...", S: "0x...", V: 27}
    response, err := exchange.PlaceOrder(client, []exchange.Order{order}, "na", nil, 123456, signature, nil, nil)
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Order placed: %+v", response)
}

API Reference

Info Endpoints

Perpetuals (hyperliquid/api/info/perpetuals)

  • GetPerpDexs() - Get perpetual DEXs
  • GetMeta() - Perpetuals metadata
  • GetMetaAndAssetCtxs() - Metadata with asset contexts
  • GetClearinghouseState() - Account state
  • GetUserFunding() - Funding history
  • GetUserNonFundingLedgerUpdates() - Non-funding ledger updates
  • GetFundingHistory() - Funding rates
  • GetPredictedFundings() - Predicted funding
  • GetPerpsAtOpenInterestCap() - Perps at open interest cap
  • GetPerpDeployAuctionStatus() - Perp deploy auction status

Spot (hyperliquid/api/info/spot)

  • GetSpotMeta() - Spot metadata
  • GetSpotMetaAndAssetCtxs() - Spot metadata with contexts
  • GetSpotClearinghouseState() - Token balances
  • GetSpotDeployState() - Spot deploy auction state
  • GetTokenDetails() - Token information

Exchange Endpoints

Orders (hyperliquid/api/exchange)

  • PlaceOrder() - Place orders
  • CancelOrders() - Cancel orders
  • CancelOrdersByCloid() - Cancel by client order ID
  • ScheduleCancel() - Schedule future cancel
  • ModifyOrder() - Modify order
  • BatchModifyOrders() - Batch modify

TWAP Orders

  • PlaceTwapOrder() - Place TWAP order
  • CancelTwapOrder() - Cancel TWAP order

Account

  • UpdateLeverage() - Update leverage
  • UpdateIsolatedMargin() - Update margin
  • UsdSend() - Send USDC
  • SpotSend() - Send spot tokens
  • Withdraw() - Withdraw funds

Utilities

  • ReserveRequestWeight() - Reserve API weight

WebSocket Subscriptions

Market Data

  • AllMidsSubscription - All asset prices
  • L2BookSubscription - Order book
  • TradesSubscription - Trade updates
  • CandleSubscription - Candlestick data
  • BboSubscription - Best bid/offer
  • ActiveAssetCtxSubscription - Active asset context

User Data

  • NotificationSubscription - User notifications
  • WebData2Subscription - User web data
  • OrderUpdatesSubscription - Order status
  • UserEventsSubscription - User events
  • UserFillsSubscription - User fills
  • UserFundingsSubscription - Funding payments
  • UserNonFundingLedgerUpdatesSubscription - Non-funding updates
  • ActiveAssetDataSubscription - Active asset data

TWAP

  • UserTwapSliceFillsSubscription - TWAP slice fills
  • UserTwapHistorySubscription - TWAP history

Configuration

// Custom HTTP client
config := hyperliquid.DefaultConfig().
    WithBaseURL("https://api.hyperliquid.xyz").
    WithTimeout(30 * time.Second)
client := hyperliquid.NewClientWithConfig(config)

// WebSocket options
wsClient := hyperliquid_websocket.NewClient(
    hyperliquid_websocket.WithURL("wss://api.hyperliquid.xyz/ws"),
    hyperliquid_websocket.WithReconnect(true),
)

Error Handling

meta, err := perpetuals.GetMeta(client, nil)
if err != nil {
    if perpErr, ok := err.(*perpetuals.PerpError); ok {
        switch perpErr.Code {
        case perpetuals.ErrCodeInvalidAddress:
            // Handle invalid address
        case perpetuals.ErrCodeRequestFailed:
            // Handle request failure
        }
    }
}

Development

# Install dependencies
go mod tidy

# Run tests
go test ./...

# Run with coverage
go test -cover ./...

Potential Optimizations

  • Replace net/http with fasthttp for better performance
  • Connection pooling for WebSocket reconnections
  • Batch request optimization for high-frequency trading
  • Optional proxy client to bypass 1200 requests/minute

License

MIT License - see LICENSE file.

Disclaimer

Not officially affiliated with Hyperliquid. Use at your own risk.

About

Go SDK for Hyperliquid perpetuals and spot trading. REST API and WebSocket support with type-safe responses, auto-reconnection, and rate limiting.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages