hyperliquid

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2025 License: MIT Imports: 15 Imported by: 0

README

go-hyperliquid

Unofficial Go client for the Hyperliquid exchange API. This implementation follows the same philosophy and patterns as the official Python SDK.

Installation

go get github.com/sonirico/go-hyperliquid

Features

  • Complete WebSocket implementation for real-time market data and user events
  • Full REST API support including:
    • Market data (L2 order book, trades, candles)
    • Trading operations (orders, positions, leverage)
    • User account management
    • Wallet operations
  • Both mainnet and testnet environments
  • Proper error handling and type safety
  • Built-in reconnection and recovery mechanisms
  • Concurrent-safe operations

Usage

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/ethereum/go-ethereum/crypto"
    hyperliquid "github.com/sonirico/go-hyperliquid"
)

func main() {
    // Initialize client
    client := hyperliquid.NewClient(hyperliquid.MainnetAPIURL)
    
    // For trading, create an Exchange with your private key
    privateKey, _ := crypto.HexToECDSA("your-private-key")
    exchange := hyperliquid.NewExchange(
        privateKey,
        hyperliquid.MainnetAPIURL,
        nil,    // Meta will be fetched automatically
        "vault-address",
        "account-address",
        nil,    // SpotMeta will be fetched automatically
    )
    
    // Place a limit order
    order := hyperliquid.OrderRequest{
        Coin:    "BTC",
        IsBuy:   true,
        Size:    0.1,
        LimitPx: 40000.0,
        OrderType: hyperliquid.OrderType{
            Limit: &hyperliquid.LimitOrderType{
                Tif: "Gtc",
            },
        },
    }
    
    resp, err := exchange.Order(order, nil)
    if err != nil {
        log.Fatal(err)
    }
    
    // Subscribe to WebSocket updates
    ws := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL)
    if err := ws.Connect(context.Background()); err != nil {
        log.Fatal(err)
    }
    defer ws.Close()
    
    // Subscribe to BTC trades
    _, err = ws.Subscribe(hyperliquid.Subscription{
        Type: "trades",
        Coin: "BTC",
    }, func(msg hyperliquid.WSMessage) {
        fmt.Printf("Trade: %+v\n", msg)
    })
}

Documentation

For detailed API documentation, please refer to the official Hyperliquid docs.

License

MIT License

Copyright (c) 2025

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	MainnetAPIURL = "https://api.hyperliquid.xyz"
	TestnetAPIURL = "https://api.hyperliquid-testnet.xyz"
	LocalAPIURL   = "http://localhost:3001"
)

Variables

This section is empty.

Functions

func SignL1Action

func SignL1Action(
	privateKey *ecdsa.PrivateKey,
	action any,
	vaultAddress string,
	timestamp int64,
	isMainnet bool,
) (string, error)

Types

type APIError

type APIError struct {
	Code    int    `json:"code"`
	Message string `json:"msg"`
	Data    any    `json:"data,omitempty"`
}

func (APIError) Error

func (e APIError) Error() string

type AssetInfo

type AssetInfo struct {
	Name       string `json:"name"`
	SzDecimals int    `json:"szDecimals"`
}

type AssetPosition

type AssetPosition struct {
	Position Position `json:"position"`
	Type     string   `json:"type"`
}

type BuilderInfo

type BuilderInfo struct {
	Builder string `json:"b"`
	Fee     int    `json:"f"`
}

type Candle

type Candle struct {
	Timestamp int64  `json:"T"`
	Close     string `json:"c"`
	High      string `json:"h"`
	Interval  string `json:"i"`
	Low       string `json:"l"`
	Number    int    `json:"n"`
	Open      string `json:"o"`
	Symbol    string `json:"s"`
	Time      int64  `json:"t"`
	Volume    string `json:"v"`
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(baseURL string) *Client

type Exchange

type Exchange struct {
	// contains filtered or unexported fields
}

func NewExchange

func NewExchange(
	privateKey *ecdsa.PrivateKey,
	baseURL string,
	meta *Meta,
	vaultAddr, accountAddr string,
	spotMeta *SpotMeta,
) *Exchange

func (*Exchange) BulkOrders

func (e *Exchange) BulkOrders(orders []OrderRequest, builder *BuilderInfo) ([]OpenOrder, error)

func (*Exchange) Cancel

func (e *Exchange) Cancel(coin string, oid int64) (*OpenOrder, error)

func (*Exchange) CancelAll

func (e *Exchange) CancelAll(coin string) ([]OpenOrder, error)

func (*Exchange) CancelByCloid

func (e *Exchange) CancelByCloid(coin string, cloid string) (*OpenOrder, error)

func (*Exchange) Order

func (e *Exchange) Order(req OrderRequest, builder *BuilderInfo) (*OpenOrder, error)

func (*Exchange) Transfer

func (e *Exchange) Transfer(amount float64, destination string) (*UserState, error)

func (*Exchange) UpdateIsolatedMargin

func (e *Exchange) UpdateIsolatedMargin(coin string, margin float64) (*UserState, error)

func (*Exchange) UpdateLeverage

func (e *Exchange) UpdateLeverage(coin string, leverage int) (*UserState, error)

func (*Exchange) WithdrawEth

func (e *Exchange) WithdrawEth(amount float64, destination string) (*UserState, error)

func (*Exchange) WithdrawUsdc

func (e *Exchange) WithdrawUsdc(amount float64, destination string) (*UserState, error)

type FeeSchedule

type FeeSchedule struct {
	Add              string `json:"add"`
	Cross            string `json:"cross"`
	ReferralDiscount string `json:"referralDiscount"`
	Tiers            Tiers  `json:"tiers"`
}

type Fill

type Fill struct {
	ClosedPnl     string `json:"closedPnl"`
	Coin          string `json:"coin"`
	Crossed       bool   `json:"crossed"`
	Dir           string `json:"dir"`
	Hash          string `json:"hash"`
	Oid           int64  `json:"oid"`
	Price         string `json:"px"`
	Side          string `json:"side"`
	StartPosition string `json:"startPosition"`
	Size          string `json:"sz"`
	Time          int64  `json:"time"`
}

type FundingHistory

type FundingHistory struct {
	Coin        string `json:"coin"`
	FundingRate string `json:"fundingRate"`
	Premium     string `json:"premium"`
	Time        int64  `json:"time"`
}

type Info

type Info struct {
	// contains filtered or unexported fields
}

func NewInfo

func NewInfo(baseURL string, skipWS bool, meta *Meta, spotMeta *SpotMeta) *Info

func (*Info) AllMids

func (i *Info) AllMids() (map[string]string, error)

func (*Info) CandlesSnapshot

func (i *Info) CandlesSnapshot(name, interval string, startTime, endTime int64) ([]Candle, error)

func (*Info) FrontendOpenOrders

func (i *Info) FrontendOpenOrders(address string) ([]OpenOrder, error)

func (*Info) FundingHistory

func (i *Info) FundingHistory(
	name string,
	startTime int64,
	endTime *int64,
) ([]FundingHistory, error)

func (*Info) L2Snapshot

func (i *Info) L2Snapshot(name string) (*L2Book, error)

func (*Info) Meta

func (i *Info) Meta() (*Meta, error)

func (*Info) MetaAndAssetCtxs

func (i *Info) MetaAndAssetCtxs() (map[string]any, error)

func (*Info) NameToAsset

func (i *Info) NameToAsset(name string) int

func (*Info) OpenOrders

func (i *Info) OpenOrders(address string) ([]OpenOrder, error)

func (*Info) QueryOrderByCloid

func (i *Info) QueryOrderByCloid(user string, cloid string) (*OpenOrder, error)

func (*Info) QueryOrderByOid

func (i *Info) QueryOrderByOid(user string, oid int64) (*OpenOrder, error)

func (*Info) QueryReferralState

func (i *Info) QueryReferralState(user string) (*ReferralState, error)

func (*Info) QuerySubAccounts

func (i *Info) QuerySubAccounts(user string) ([]SubAccount, error)

func (*Info) QueryUserToMultiSigSigners

func (i *Info) QueryUserToMultiSigSigners(multiSigUser string) ([]MultiSigSigner, error)

func (*Info) SpotMeta

func (i *Info) SpotMeta() (*SpotMeta, error)

func (*Info) SpotMetaAndAssetCtxs

func (i *Info) SpotMetaAndAssetCtxs() (map[string]any, error)

func (*Info) SpotUserState

func (i *Info) SpotUserState(address string) (*UserState, error)

func (*Info) UserFees

func (i *Info) UserFees(address string) (*UserFees, error)

func (*Info) UserFills

func (i *Info) UserFills(address string) ([]Fill, error)

func (*Info) UserFillsByTime

func (i *Info) UserFillsByTime(address string, startTime int64, endTime *int64) ([]Fill, error)

func (*Info) UserFundingHistory

func (i *Info) UserFundingHistory(
	user string,
	startTime int64,
	endTime *int64,
) ([]UserFundingHistory, error)

func (*Info) UserStakingDelegations

func (i *Info) UserStakingDelegations(address string) ([]StakingDelegation, error)

func (*Info) UserStakingRewards

func (i *Info) UserStakingRewards(address string) ([]StakingReward, error)

func (*Info) UserStakingSummary

func (i *Info) UserStakingSummary(address string) (*StakingSummary, error)

func (*Info) UserState

func (i *Info) UserState(address string) (*UserState, error)

type L2Book

type L2Book struct {
	Coin   string    `json:"coin"`
	Levels [][]Level `json:"levels"`
	Time   int64     `json:"time"`
}

type Level

type Level struct {
	N  int     `json:"n"`
	Px float64 `json:"px,string"`
	Sz float64 `json:"sz,string"`
}

type Leverage

type Leverage struct {
	Type   string  `json:"type"`
	Value  int     `json:"value"`
	RawUsd *string `json:"rawUsd,omitempty"`
}

type LimitOrderType

type LimitOrderType struct {
	Tif string `json:"tif"` // "Alo", "Ioc", "Gtc"
}

type MMTier

type MMTier struct {
	Add                 string `json:"add"`
	MakerFractionCutoff string `json:"makerFractionCutoff"`
}

type MarginSummary

type MarginSummary struct {
	AccountValue    string `json:"accountValue"`
	TotalMarginUsed string `json:"totalMarginUsed"`
	TotalNtlPos     string `json:"totalNtlPos"`
	TotalRawUsd     string `json:"totalRawUsd"`
}

type Meta

type Meta struct {
	Universe []AssetInfo `json:"universe"`
}

type MultiSigSigner

type MultiSigSigner struct {
	User      string `json:"user"`
	Threshold int    `json:"threshold"`
}

type OpenOrder

type OpenOrder struct {
	Coin      string  `json:"coin"`
	LimitPx   float64 `json:"limitPx,string"`
	Oid       int64   `json:"oid"`
	Side      string  `json:"side"`
	Size      float64 `json:"sz,string"`
	Timestamp int64   `json:"timestamp"`
}

type OrderRequest

type OrderRequest struct {
	Coin       string    `json:"coin"`
	IsBuy      bool      `json:"is_buy"`
	Size       float64   `json:"sz"`
	LimitPx    float64   `json:"limit_px"`
	OrderType  OrderType `json:"order_type"`
	ReduceOnly bool      `json:"reduce_only"`
	Cloid      *string   `json:"cloid,omitempty"`
}

type OrderType

type OrderType struct {
	Limit   *LimitOrderType   `json:"limit,omitempty"`
	Trigger *TriggerOrderType `json:"trigger,omitempty"`
}

type OrderWire

type OrderWire struct {
	Asset      int     `json:"a"`
	IsBuy      bool    `json:"b"`
	OrderType  string  `json:"t,omitempty"`
	LimitPx    float64 `json:"p"`
	Size       float64 `json:"s"`
	ReduceOnly bool    `json:"r"`
	TriggerPx  float64 `json:"tp,omitempty"`
	IsMarket   bool    `json:"im,omitempty"`
	Tpsl       string  `json:"tpsl,omitempty"`
	Tif        string  `json:"tif,omitempty"`
	Cloid      string  `json:"c,omitempty"`
}

func OrderRequestToWire

func OrderRequestToWire(req OrderRequest, asset int) OrderWire

type Position

type Position struct {
	Coin           string   `json:"coin"`
	EntryPx        *string  `json:"entryPx"`
	Leverage       Leverage `json:"leverage"`
	LiquidationPx  *string  `json:"liquidationPx"`
	MarginUsed     string   `json:"marginUsed"`
	PositionValue  string   `json:"positionValue"`
	ReturnOnEquity string   `json:"returnOnEquity"`
	Szi            string   `json:"szi"`
	UnrealizedPnl  string   `json:"unrealizedPnl"`
}

type ReferralState

type ReferralState struct {
	ReferralCode string   `json:"referralCode"`
	Referrer     string   `json:"referrer"`
	Referred     []string `json:"referred"`
}

type Side

type Side string
const (
	SideAsk Side = "A"
	SideBid Side = "B"
)

type SpotAssetCtx

type SpotAssetCtx struct {
	DayNtlVlm         string  `json:"dayNtlVlm"`
	MarkPx            string  `json:"markPx"`
	MidPx             *string `json:"midPx"`
	PrevDayPx         string  `json:"prevDayPx"`
	CirculatingSupply string  `json:"circulatingSupply"`
	Coin              string  `json:"coin"`
}

type SpotAssetInfo

type SpotAssetInfo struct {
	Name        string `json:"name"`
	Tokens      []int  `json:"tokens"`
	Index       int    `json:"index"`
	IsCanonical bool   `json:"isCanonical"`
}

type SpotMeta

type SpotMeta struct {
	Universe []SpotAssetInfo `json:"universe"`
	Tokens   []SpotTokenInfo `json:"tokens"`
}

type SpotTokenInfo

type SpotTokenInfo struct {
	Name        string  `json:"name"`
	SzDecimals  int     `json:"szDecimals"`
	WeiDecimals int     `json:"weiDecimals"`
	Index       int     `json:"index"`
	TokenID     string  `json:"tokenId"`
	IsCanonical bool    `json:"isCanonical"`
	EvmContract *string `json:"evmContract"`
	FullName    *string `json:"fullName"`
}

type StakingDelegation

type StakingDelegation struct {
	Validator            string `json:"validator"`
	Amount               string `json:"amount"`
	LockedUntilTimestamp int64  `json:"lockedUntilTimestamp"`
}

type StakingReward

type StakingReward struct {
	Time        int64  `json:"time"`
	Source      string `json:"source"`
	TotalAmount string `json:"totalAmount"`
}

type StakingSummary

type StakingSummary struct {
	Delegated              string `json:"delegated"`
	Undelegated            string `json:"undelegated"`
	TotalPendingWithdrawal string `json:"totalPendingWithdrawal"`
	NPendingWithdrawals    int    `json:"nPendingWithdrawals"`
}

type SubAccount

type SubAccount struct {
	Name        string   `json:"name"`
	User        string   `json:"user"`
	Permissions []string `json:"permissions"`
}

type Subscription

type Subscription struct {
	Type     string `json:"type"`
	Coin     string `json:"coin,omitempty"`
	User     string `json:"user,omitempty"`
	Interval string `json:"interval,omitempty"`
}

type Tiers

type Tiers struct {
	MM  []MMTier  `json:"mm"`
	VIP []VIPTier `json:"vip"`
}

type Trade

type Trade struct {
	Coin  string   `json:"coin"`
	Side  string   `json:"side"`
	Px    string   `json:"px"`
	Sz    string   `json:"sz"`
	Time  int64    `json:"time"`
	Hash  string   `json:"hash"`
	Tid   int64    `json:"tid"`
	Users []string `json:"users"`
}

type TriggerOrderType

type TriggerOrderType struct {
	TriggerPx float64 `json:"triggerPx"`
	IsMarket  bool    `json:"isMarket"`
	Tpsl      string  `json:"tpsl"` // "tp" or "sl"
}

type UserFees

type UserFees struct {
	ActiveReferralDiscount string       `json:"activeReferralDiscount"`
	DailyUserVolume        []UserVolume `json:"dailyUserVlm"`
	FeeSchedule            FeeSchedule  `json:"feeSchedule"`
	UserAddRate            string       `json:"userAddRate"`
	UserCrossRate          string       `json:"userCrossRate"`
}

type UserFundingHistory

type UserFundingHistory struct {
	User      string `json:"user"`
	Type      string `json:"type"`
	StartTime int64  `json:"startTime"`
	EndTime   int64  `json:"endTime"`
}

type UserState

type UserState struct {
	AssetPositions     []AssetPosition `json:"assetPositions"`
	CrossMarginSummary MarginSummary   `json:"crossMarginSummary"`
	MarginSummary      MarginSummary   `json:"marginSummary"`
	Withdrawable       string          `json:"withdrawable"`
}

type UserVolume

type UserVolume struct {
	Date      string `json:"date"`
	Exchange  string `json:"exchange"`
	UserAdd   string `json:"userAdd"`
	UserCross string `json:"userCross"`
}

type VIPTier

type VIPTier struct {
	Add       string `json:"add"`
	Cross     string `json:"cross"`
	NtlCutoff string `json:"ntlCutoff"`
}

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

func (ValidationError) Error

func (e ValidationError) Error() string

type WSMessage

type WSMessage struct {
	Channel string          `json:"channel"`
	Data    json.RawMessage `json:"data"`
}

type WebsocketClient

type WebsocketClient struct {
	// contains filtered or unexported fields
}

func NewWebsocketClient

func NewWebsocketClient(baseURL string) *WebsocketClient

func (*WebsocketClient) Close

func (w *WebsocketClient) Close() error

func (*WebsocketClient) Connect

func (w *WebsocketClient) Connect(ctx context.Context) error

func (*WebsocketClient) Subscribe

func (w *WebsocketClient) Subscribe(sub Subscription, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToOrderbook

func (w *WebsocketClient) SubscribeToOrderbook(coin string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToTrades

func (w *WebsocketClient) SubscribeToTrades(coin string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) Unsubscribe

func (w *WebsocketClient) Unsubscribe(sub Subscription, id int) error

type WsCommand added in v0.1.2

type WsCommand struct {
	Method       string        `json:"method"`
	Subscription *Subscription `json:"subscription,omitempty"`
}

type WsMsg

type WsMsg struct {
	Channel string         `json:"channel"`
	Data    map[string]any `json:"data"`
}

WebSocket message types

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL