hyperliquid

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

README

hyperliquid-go

Go Reference CI Go Report Card codecov OpenSSF Scorecard License

A Go SDK for the Hyperliquid API: market data, account state, trading and transfers over HTTP, and real-time subscriptions over WebSocket.

[!IMPORTANT] This is an unofficial, community-maintained SDK. It is not affiliated with, endorsed by or supported by Hyperliquid Labs. Trading digital assets and perpetual futures carries a high risk of loss. The software is provided "as is", without warranty of any kind (see LICENSE); you are responsible for every order and transfer it signs. Test on Testnet first.

Install

go get github.com/koative/hyperliquid-go

Requires Go 1.26 or newer. The package name is hyperliquid.

Quickstart

Read market data
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	ctx := context.Background()
	info := hyperliquid.NewInfoClient(hyperliquid.Mainnet)

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

	book, err := info.L2Book(ctx, hyperliquid.L2BookRequest{Coin: "ETH"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("ETH bid/ask:", book.Levels[0][0].Px, book.Levels[1][0].Px)
}
Place and cancel an order

Trade with an API (agent) wallet: a separate key that your account approves with ExchangeClient.ApproveAgent (or in the Hyperliquid UI under API). It can trade for the account but cannot withdraw or transfer funds.

ctx := context.Background()

signer, err := hyperliquid.NewPrivateKeySigner(os.Getenv("HL_AGENT_KEY"))
if err != nil {
	log.Fatal(err)
}
ex := hyperliquid.NewExchangeClient(hyperliquid.Testnet, signer)
info := hyperliquid.NewInfoClient(hyperliquid.Testnet)

// Orders take asset IDs; Markets resolves names such as "ETH", "PURR/USDC"
// or "xyz:TSLA" and knows each asset's size decimals.
markets, err := hyperliquid.LoadMarkets(ctx, info)
if err != nil {
	log.Fatal(err)
}
eth, _ := markets.Asset("ETH")

// Bid 5% below mid, rounded to the asset's tick and lot size.
mids, err := info.AllMids(ctx, hyperliquid.AllMidsRequest{})
if err != nil {
	log.Fatal(err)
}
mid, _ := mids[eth.Name].Float64()
px, err := eth.FormatPrice(hyperliquid.DecimalFromFloat(mid * 0.95))
if err != nil {
	log.Fatal(err)
}
sz, err := eth.FormatSize("0.01")
if err != nil {
	log.Fatal(err)
}

results, err := ex.Order(ctx, hyperliquid.OrderAction{
	Orders: []hyperliquid.Order{{
		Asset: eth.ID,
		IsBuy: true,
		Price: px,
		Size:  sz,
		Type:  hyperliquid.OrderType{Limit: &hyperliquid.LimitOrder{Tif: hyperliquid.TifGtc}},
	}},
})
if rejected, ok := errors.AsType[*hyperliquid.StatusError](err); ok {
	log.Fatalf("order rejected: %s", rejected.Message)
} else if err != nil {
	log.Fatal(err) // *hyperliquid.APIError, network error, ...
}
if results[0].Resting == nil {
	return // filled immediately
}

err = ex.Cancel(ctx, hyperliquid.CancelAction{
	Cancels: []hyperliquid.Cancel{{Asset: eth.ID, Oid: results[0].Resting.Oid}},
})
if err != nil {
	log.Fatal(err)
}

To trade for a vault or sub-account, use ex.WithVault(address).

Subscribe over WebSocket
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()

ws, err := hyperliquid.DialWebSocket(ctx, hyperliquid.Mainnet)
if err != nil {
	log.Fatal(err)
}
defer ws.Close()

_, err = ws.Trades(ctx, hyperliquid.TradesSubscription{Coin: "BTC"}, func(trades []hyperliquid.Trade) {
	for _, t := range trades {
		fmt.Println(t.Side, t.Sz, "@", t.Px)
	}
})
if err != nil {
	log.Fatal(err)
}
<-ctx.Done() // stream until Ctrl-C

The client keeps the connection alive, reconnects and re-subscribes automatically. Pass hyperliquid.WithWebSocket(ws) to NewInfoClient or NewExchangeClient to send their requests over the same connection.

More examples are in the package documentation.

Features

  • Info API: market data (mids, metadata, order books, candles, funding), account state (positions, orders, fills, fees, portfolio), spot, vaults, staking, sub-accounts and the explorer endpoints.
  • Exchange API: orders (limit, trigger, TP/SL, TWAP, builder fees), modify and cancel (by order or client ID), leverage and margin, transfers and withdrawals, agent and builder approvals, vaults and sub-accounts, staking, multi-sig, and HIP-1/HIP-3 deploy actions.
  • WebSocket: typed subscriptions for every channel, info and exchange requests over the socket, explorer block and transaction streams, with keep-alive, automatic reconnect and re-subscribe.
  • Mainnet and Testnet, vaults and sub-accounts, expiring actions.
  • Pluggable signing through the Signer interface (KMS, HSM, remote signers).

Design

  • Lossless decimals. Prices, sizes and amounts are Decimal, a string type that keeps Hyperliquid's wire form exactly. Convert with Decimal.Float64 or the decimal library of your choice; round with FormatPrice and FormatSize. No float64 touches money on the wire.
  • Small dependency tree. No go-ethereum: the only dependencies are decred secp256k1, golang.org/x/crypto/sha3 and coder/websocket. EIP-712 and MessagePack are implemented in the package.
  • Verified signing. Signatures are tested byte for byte against golden vectors generated with the official Python SDK.
  • Checked against the live API every night. Every Info endpoint and WebSocket channel is decoded strictly on Mainnet, and every exchange action is submitted to Testnet, where the exchange must recover our signer's address. API changes surface as an issue, usually before users hit them.
  • Idiomatic Go. context.Context on every call; clients are safe for concurrent use; nonces are strictly increasing per process; errors are typed (*APIError for rejected requests, *StatusError per failed item of a batch).

Documentation

Versioning

The module follows semantic versioning. While it is at v0, breaking changes may land in minor releases (v0.x.0) and are listed in the changelog; patch releases are compatible.

The SDK supports the two most recent Go releases, matching the Go release policy. The minimum Go version is only raised in a minor release.

Contributing and security

Contributions are welcome; see CONTRIBUTING.md. Report vulnerabilities privately as described in SECURITY.md.

License

Apache License 2.0. Copyright 2026 Koative.

Documentation

Overview

Package hyperliquid is a client for the Hyperliquid exchange API.

It has three clients:

  • InfoClient reads market data, account state and the explorer. It needs no keys.
  • ExchangeClient signs and submits actions: orders, cancels, transfers, vault, staking and deployer operations.
  • WebSocketClient streams subscriptions, and can also carry InfoClient and ExchangeClient requests (see WithWebSocket).

Every method takes a context.Context and every client is safe for concurrent use.

Quick start

info := hyperliquid.NewInfoClient(hyperliquid.Mainnet)
book, err := info.L2Book(ctx, hyperliquid.L2BookRequest{Coin: "BTC"})

signer, err := hyperliquid.NewPrivateKeySigner(os.Getenv("HL_AGENT_KEY"))
ex := hyperliquid.NewExchangeClient(hyperliquid.Mainnet, signer)
statuses, err := ex.Order(ctx, hyperliquid.OrderAction{Orders: []hyperliquid.Order{{
	Asset: 0, IsBuy: true, Price: "50000", Size: "0.001",
	Type: hyperliquid.OrderType{Limit: &hyperliquid.LimitOrder{Tif: hyperliquid.TifGtc}},
}}})

Networks

Mainnet and Testnet hold the API URLs of each network and select the signature domain. Declare a Network value for other deployments, such as a local node.

Signing

Actions are signed by a Signer. NewPrivateKeySigner covers in-memory keys; implement Signer to sign with a KMS or HSM. Trading and other L1 actions may be signed by an API wallet approved with ExchangeClient.ApproveAgent. User-signed actions (transfers, withdrawals, agent and builder approvals, staking) must be signed by the account's own key. Signatures are tested byte for byte against the official Python SDK.

Assets and numbers

Exchange actions identify markets by asset ID. LoadMarkets resolves names such as "BTC", "PURR/USDC", "@107" or "xyz:TSLA" (a builder-deployed perp) to an Asset with its ID and size decimals.

Prices, sizes and amounts are Decimal strings, exactly as Hyperliquid sends them, so no precision is lost. Round order prices and sizes with FormatPrice and FormatSize (or Asset.FormatPrice). Timestamps are milliseconds since the Unix epoch.

Errors

Requests rejected by the API return an *APIError. Batch actions such as ExchangeClient.Order and ExchangeClient.Cancel are accepted or rejected per item; failed items are reported as a joined *StatusError per item, alongside the per-item results:

statuses, err := ex.Order(ctx, action)
var rejected *hyperliquid.StatusError
if errors.As(err, &rejected) {
	log.Printf("order %d: %s", rejected.Index, rejected.Message)
}

Nonces, vaults and expiry

Each action is signed with a nonce: the current time in milliseconds, strictly increasing across every ExchangeClient in the process, so concurrent actions never reuse a nonce even from separately constructed clients for the same signer. Draw the explicit nonces of ExchangeClient.SignMultiSig, ExchangeClient.MultiSig and ExchangeClient.Noop from NextNonce. ExchangeClient.WithVault trades on behalf of a vault or sub-account, and ExchangeClient.WithExpiresAfter makes the exchange reject actions that arrive late.

Multi-sig

For a multi-sig account, each authorized user signs the action with ExchangeClient.SignMultiSig, and the leader submits it with the collected signatures using ExchangeClient.MultiSig.

WebSocket

DialWebSocket connects to the streaming API. Each subscription method takes a handler that receives messages in order on the subscription's own goroutine:

ws, err := hyperliquid.DialWebSocket(ctx, hyperliquid.Mainnet)
defer ws.Close()
sub, err := ws.Trades(ctx, hyperliquid.TradesSubscription{Coin: "BTC"}, func(trades []hyperliquid.Trade) {
	fmt.Println(trades[0].Px)
})

The client keeps the connection alive, reconnects with backoff and re-subscribes automatically.

This package is not affiliated with Hyperliquid Labs.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Mainnet is the Hyperliquid mainnet.
	Mainnet = Network{
		APIURL:       "https://api.hyperliquid.xyz",
		WebSocketURL: "wss://api.hyperliquid.xyz/ws",
		RPCURL:       "https://rpc.hyperliquid.xyz",
		Mainnet:      true,
	}
	// Testnet is the Hyperliquid testnet.
	Testnet = Network{
		APIURL:       "https://api.hyperliquid-testnet.xyz",
		WebSocketURL: "wss://api.hyperliquid-testnet.xyz/ws",
		RPCURL:       "https://rpc.hyperliquid-testnet.xyz",
	}
)
View Source
var (
	// GroupingNA places independent orders.
	GroupingNA = Grouping{/* contains filtered or unexported fields */}
	// GroupingNormalTpsl attaches fixed-size TP/SL orders to the first order.
	GroupingNormalTpsl = Grouping{/* contains filtered or unexported fields */}
	// GroupingPositionTpsl attaches TP/SL orders that track the position size.
	GroupingPositionTpsl = Grouping{/* contains filtered or unexported fields */}
)
View Source
var (
	// FinalizeFirstStorageSlot proves deployment by the finalizer address
	// stored in the contract's first storage slot.
	FinalizeFirstStorageSlot = FinalizeEVMContractInput{/* contains filtered or unexported fields */}
	// FinalizeCustomStorageSlot proves deployment by the finalizer address
	// stored at slot keccak256("HyperCore deployer").
	FinalizeCustomStorageSlot = FinalizeEVMContractInput{/* contains filtered or unexported fields */}
)
View Source
var (
	// ErrWebSocketClosed is returned by [WebSocketClient] methods after
	// [WebSocketClient.Close], and by [Subscription.Err] for subscriptions
	// ended by it.
	ErrWebSocketClosed = errors.New("hyperliquid: websocket closed")
	// ErrWebSocketDisconnected is returned by requests in flight when the
	// connection drops. The request may or may not have been executed.
	ErrWebSocketDisconnected = errors.New("hyperliquid: websocket disconnected")
	// ErrSubscriptionOverflow is returned by [Subscription.Err] for a
	// subscription ended because its handler fell more than 4096 messages
	// behind.
	ErrSubscriptionOverflow = errors.New("hyperliquid: websocket subscription handler fell behind")
)
View Source
var ErrTruncatedToZero = errors.New("hyperliquid: value truncated to zero")

ErrTruncatedToZero is returned by FormatPrice and FormatSize when the value has no significant digits left after rounding.

Functions

func NextNonce

func NextNonce() uint64

NextNonce returns a fresh nonce: the current time in milliseconds, or one more than the last nonce issued in this process if that is later. Use it for the explicit nonces of ExchangeClient.SignMultiSig, ExchangeClient.MultiSig and ExchangeClient.Noop, so they never collide with the nonces the client draws for other actions.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status code. It is 0 only for errors reported
	// inside an ok /exchange response body or over WebSocket.
	StatusCode int
	// Message is the server's error message.
	Message string
}

APIError is an error reported by the Hyperliquid API.

func (*APIError) Error

func (e *APIError) Error() string

type AQAv2Role

type AQAv2Role string

AQAv2Role is a role of an aligned quote asset (AQAv2) token.

const (
	AQAv2RoleTechnical AQAv2Role = "technical"
	AQAv2RoleTreasury  AQAv2Role = "treasury"
)

AQAv2 roles.

type Abstraction

type Abstraction string

Abstraction is an account abstraction mode, which decides how balances are shared between spot and the perp dexes.

const (
	AbstractionDisabled        Abstraction = "disabled"
	AbstractionUnifiedAccount  Abstraction = "unifiedAccount"
	AbstractionPortfolioMargin Abstraction = "portfolioMargin"
	// AbstractionDefault is reported by [InfoClient] for accounts that
	// never set a mode; it cannot be set.
	AbstractionDefault Abstraction = "default"
)

Abstraction modes.

type Action

type Action interface {
	// contains filtered or unexported methods
}

Action is an exchange action. The *Action types in this package implement it; pass them to ExchangeClient.SignMultiSig and ExchangeClient.MultiSig.

type ActivateOutcomeDeployerAction

type ActivateOutcomeDeployerAction struct {
	Activate   *OutcomeDeployerActivation
	Deactivate bool
}

ActivateOutcomeDeployerAction makes the signer a HIP-4 outcome deployer with its own venue, or permanently retires it. Set exactly one field.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions.

func (ActivateOutcomeDeployerAction) MarshalJSON

func (a ActivateOutcomeDeployerAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes a as {"activate":{…}} or {"deactivate":null}.

type ActiveAssetCtxEvent

type ActiveAssetCtxEvent struct {
	Coin string       `json:"coin"`
	Ctx  PerpAssetCtx `json:"ctx"`
}

ActiveAssetCtxEvent is a message of WebSocketClient.ActiveAssetCtx.

type ActiveAssetCtxSubscription

type ActiveAssetCtxSubscription struct {
	Coin string `json:"coin"`
}

ActiveAssetCtxSubscription is the request of WebSocketClient.ActiveAssetCtx and WebSocketClient.ActiveSpotAssetCtx.

type ActiveAssetData

type ActiveAssetData struct {
	User     Address  `json:"user"`
	Coin     string   `json:"coin"`
	Leverage Leverage `json:"leverage"`
	// MaxTradeSzs and AvailableToTrade are [buy, sell].
	MaxTradeSzs      [2]Decimal `json:"maxTradeSzs"`
	AvailableToTrade [2]Decimal `json:"availableToTrade"`
	MarkPx           Decimal    `json:"markPx"`
}

ActiveAssetData is a user's trading limits for one perpetual.

type ActiveAssetDataRequest

type ActiveAssetDataRequest struct {
	Coin string  `json:"coin"`
	User Address `json:"user"`
}

ActiveAssetDataRequest is the request for InfoClient.ActiveAssetData.

type ActiveAssetDataSubscription

type ActiveAssetDataSubscription struct {
	Coin string  `json:"coin"`
	User Address `json:"user"`
}

ActiveAssetDataSubscription is the request of WebSocketClient.ActiveAssetData.

type ActiveSpotAssetCtxEvent

type ActiveSpotAssetCtxEvent struct {
	Coin string       `json:"coin"`
	Ctx  SpotAssetCtx `json:"ctx"`
}

ActiveSpotAssetCtxEvent is a message of WebSocketClient.ActiveSpotAssetCtx.

type Address

type Address [20]byte

Address is a 20-byte account address. It encodes as a lowercase 0x-prefixed hex string, the form Hyperliquid signs and expects.

func MustParseAddress

func MustParseAddress(s string) Address

MustParseAddress is like ParseAddress but panics on error. It is intended for constants and tests.

func ParseAddress

func ParseAddress(s string) (Address, error)

ParseAddress parses a 0x-prefixed (or bare) 40-character hex address.

func (Address) IsZero

func (a Address) IsZero() bool

IsZero reports whether a is the zero address.

func (Address) MarshalText

func (a Address) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Address) String

func (a Address) String() string

String returns the lowercase 0x-prefixed hex form of a.

func (*Address) UnmarshalText

func (a *Address) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type AddressEncoding

type AddressEncoding string

AddressEncoding is the text encoding of a recipient address on another chain.

const (
	AddressEncodingHex    AddressEncoding = "hex"
	AddressEncodingBase58 AddressEncoding = "base58"
)

Address encodings.

type AgentSendAssetAction

type AgentSendAssetAction struct {
	Destination Address `json:"destination"`
	// SourceDex and DestinationDex are perp dex names; "" is the default
	// perp dex and "spot" is the spot balance.
	SourceDex      string `json:"sourceDex"`
	DestinationDex string `json:"destinationDex"`
	// Token is "<name>:<tokenId>", e.g. "USDC:0xeb62eee3685fc4c43992febcd9e75443".
	Token  string  `json:"token"`
	Amount Decimal `json:"amount"`
	// FromSubAccount optionally sends from a sub-account.
	FromSubAccount *Address `json:"fromSubAccount"`
}

AgentSendAssetAction moves a token between perp dexes, spot and accounts, like SendAssetAction, but may be signed by an API wallet.

func (AgentSendAssetAction) MarshalJSON

func (a AgentSendAssetAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes a nil FromSubAccount as "".

type AgentSetAbstractionAction

type AgentSetAbstractionAction struct {
	Abstraction Abstraction `json:"abstraction"`
}

AgentSetAbstractionAction sets the account abstraction mode, like UserSetAbstractionAction, but may be signed by an API wallet.

func (AgentSetAbstractionAction) MarshalJSON

func (a AgentSetAbstractionAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes the abstraction in its short wire form ("i", "u", "p").

type AllDexsAssetCtxsEvent

type AllDexsAssetCtxsEvent struct {
	// Ctxs maps each perp dex ("" for the main dex) to its asset contexts.
	Ctxs TupleMap[string, []PerpAssetCtx] `json:"ctxs"`
}

AllDexsAssetCtxsEvent is a message of WebSocketClient.AllDexsAssetCtxs.

type AllDexsClearinghouseStateEvent

type AllDexsClearinghouseStateEvent struct {
	User Address `json:"user"`
	// ClearinghouseStates maps each perp dex ("" for the main dex) to the
	// user's state on it.
	ClearinghouseStates TupleMap[string, ClearinghouseState] `json:"clearinghouseStates"`
}

AllDexsClearinghouseStateEvent is a message of WebSocketClient.AllDexsClearinghouseState.

type AllDexsClearinghouseStateSubscription

type AllDexsClearinghouseStateSubscription struct {
	User Address `json:"user"`
}

AllDexsClearinghouseStateSubscription is the request of WebSocketClient.AllDexsClearinghouseState.

type AllMidsEvent

type AllMidsEvent struct {
	// Mids maps every coin to its mid price.
	Mids map[string]Decimal `json:"mids"`
	// Dex is the perp dex; empty for the main dex.
	Dex string `json:"dex,omitempty"`
}

AllMidsEvent is a message of WebSocketClient.AllMids.

type AllMidsRequest

type AllMidsRequest struct {
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

AllMidsRequest is the request for InfoClient.AllMids.

type AllMidsSubscription

type AllMidsSubscription struct {
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

AllMidsSubscription is the request of WebSocketClient.AllMids.

type ApproveAgentAction

type ApproveAgentAction struct {
	AgentAddress Address `json:"agentAddress"`
	// AgentName names the agent (at most 16 characters, optionally followed
	// by " valid_until <ms>"). Approving a name again replaces its agent.
	// An empty name approves the unnamed agent.
	AgentName string `json:"agentName"`
}

ApproveAgentAction authorizes an API (agent) wallet to sign L1 actions, such as orders, on behalf of the signer. It must be signed by the account's own key. Create the agent key with NewPrivateKeySigner and sign with it via NewExchangeClient.

type ApproveBuilderFeeAction

type ApproveBuilderFeeAction struct {
	// MaxFeeRate is the maximum fee as a percentage of notional, such as
	// "0.001" for 0.001%. It is sent with the "%" suffix.
	MaxFeeRate Decimal `json:"maxFeeRate"`
	Builder    Address `json:"builder"`
}

ApproveBuilderFeeAction allows a builder to charge the signer up to MaxFeeRate on orders that name it in OrderAction.Builder. It must be signed by the account's own key.

func (ApproveBuilderFeeAction) MarshalJSON

func (a ApproveBuilderFeeAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes MaxFeeRate with the trailing "%" the exchange expects.

type ApprovedBuildersRequest

type ApprovedBuildersRequest struct {
	User Address `json:"user"`
}

ApprovedBuildersRequest is the request for InfoClient.ApprovedBuilders.

type Asset

type Asset struct {
	// ID is the asset ID: the universe index for main-dex perps,
	// 100000 + 10000*dexIndex + index for builder-dex perps and
	// 10000 + pair index for spot pairs.
	ID int
	// Name is the coin that info endpoints and subscriptions accept: the
	// perp name ("BTC", "xyz:TSLA") or the spot pair's own name ("PURR/USDC"
	// for canonical pairs, "@107" otherwise).
	Name string
	// SzDecimals is the size precision; for spot pairs, the base token's.
	SzDecimals int
	Spot       bool
	// Dex is the builder dex name, empty for main-dex perps and spot.
	Dex string
}

Asset is a tradable market and the asset ID that exchange actions use for it.

func (Asset) FormatPrice

func (a Asset) FormatPrice(px Decimal) (Decimal, error)

FormatPrice rounds px to a valid price for a; see FormatPrice.

func (Asset) FormatSize

func (a Asset) FormatSize(sz Decimal) (Decimal, error)

FormatSize rounds sz to a valid size for a; see FormatSize.

type AssetCtxsEvent

type AssetCtxsEvent struct {
	Dex string `json:"dex"`
	// Ctxs is ordered like the dex's [Meta.Universe].
	Ctxs []PerpAssetCtx `json:"ctxs"`
}

AssetCtxsEvent is a message of WebSocketClient.AssetCtxs.

type AssetCtxsSubscription

type AssetCtxsSubscription struct {
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex"`
}

AssetCtxsSubscription is the request of WebSocketClient.AssetCtxs.

type AssetPosition

type AssetPosition struct {
	// Type is always "oneWay".
	Type     string   `json:"type"`
	Position Position `json:"position"`
}

AssetPosition is an open perpetual position.

type AuctionStatus

type AuctionStatus struct {
	// StartTimeSeconds is in seconds since the Unix epoch.
	StartTimeSeconds int64   `json:"startTimeSeconds"`
	DurationSeconds  int64   `json:"durationSeconds"`
	StartGas         Decimal `json:"startGas"`
	// CurrentGas is nil once the auction has been won.
	CurrentGas *Decimal `json:"currentGas"`
	// EndGas is the winning price, or nil while the auction runs.
	EndGas *Decimal `json:"endGas"`
}

AuctionStatus is the state of a Dutch gas auction, such as the one for deploying a perp dex asset or a spot pair.

type AuthorizeAQAv2RoleAction

type AuthorizeAQAv2RoleAction struct {
	Token int       `json:"token"`
	Role  AQAv2Role `json:"role"`
}

AuthorizeAQAv2RoleAction authorizes the signer for a role of an aligned quote asset token.

type BatchModifyAction

type BatchModifyAction struct {
	Modifies []Modify `json:"modifies"`
	// AlwaysPlace places the new orders even if canceling the old ones fails.
	AlwaysPlace bool `json:"a,omitempty"`
}

BatchModifyAction replaces several resting orders.

type BboEvent

type BboEvent struct {
	Coin string `json:"coin"`
	// Time is in milliseconds since the Unix epoch.
	Time int64 `json:"time"`
	// Bbo holds the best bid and the best ask; either is nil when that side
	// is empty.
	Bbo [2]*L2Level `json:"bbo"`
}

BboEvent is a message of WebSocketClient.Bbo.

type BboSubscription

type BboSubscription struct {
	Coin string `json:"coin"`
}

BboSubscription is the request of WebSocketClient.Bbo.

type BlacklistUser

type BlacklistUser struct {
	User        Address
	Blacklisted bool
}

BlacklistUser blacklists a user from genesis, or removes them from the blacklist. It encodes as [user, blacklisted].

func (BlacklistUser) MarshalJSON

func (b BlacklistUser) MarshalJSON() ([]byte, error)

MarshalJSON encodes b as [user, blacklisted].

type BlockDetails

type BlockDetails struct {
	// BlockTime is in milliseconds since the Unix epoch.
	BlockTime int64        `json:"blockTime"`
	Hash      string       `json:"hash"`
	Height    int64        `json:"height"`
	NumTxs    int          `json:"numTxs"`
	Proposer  Address      `json:"proposer"`
	Txs       []ExplorerTx `json:"txs"`
}

BlockDetails is an L1 block with its transactions.

type BlockDetailsRequest

type BlockDetailsRequest struct {
	Height int64 `json:"height"`
}

BlockDetailsRequest is the request for InfoClient.BlockDetails.

type BorrowLendAction

type BorrowLendAction struct {
	Operation BorrowLendOperation `json:"operation"`
	// Token is the spot token index.
	Token int `json:"token"`
	// Amount is the token amount; nil means the full balance or debt.
	Amount *Decimal `json:"amount"`
}

BorrowLendAction supplies, withdraws, borrows or repays a token.

type BorrowLendBalance

type BorrowLendBalance struct {
	// Basis is the principal; Value includes accrued interest.
	Basis Decimal `json:"basis"`
	Value Decimal `json:"value"`
}

BorrowLendBalance is a borrowed or supplied amount.

type BorrowLendInterest

type BorrowLendInterest struct {
	// Time is in milliseconds since the Unix epoch.
	Time   int64   `json:"time"`
	Token  string  `json:"token"`
	Borrow Decimal `json:"borrow"`
	Supply Decimal `json:"supply"`
	// NSamples is the number of interest samples aggregated in the entry.
	NSamples int `json:"nSamples"`
}

BorrowLendInterest is the interest accrued on one token over one period.

type BorrowLendOperation

type BorrowLendOperation string

BorrowLendOperation is the operation of a BorrowLendAction.

const (
	BorrowLendSupply   BorrowLendOperation = "supply"
	BorrowLendWithdraw BorrowLendOperation = "withdraw"
	BorrowLendRepay    BorrowLendOperation = "repay"
	BorrowLendBorrow   BorrowLendOperation = "borrow"
)

Borrow/lend operations.

type BorrowLendReserveState

type BorrowLendReserveState struct {
	BorrowYearlyRate Decimal `json:"borrowYearlyRate"`
	SupplyYearlyRate Decimal `json:"supplyYearlyRate"`
	Balance          Decimal `json:"balance"`
	Utilization      Decimal `json:"utilization"`
	OraclePx         Decimal `json:"oraclePx"`
	// LTV is the loan-to-value ratio of the token as collateral.
	LTV           Decimal `json:"ltv"`
	TotalSupplied Decimal `json:"totalSupplied"`
	TotalBorrowed Decimal `json:"totalBorrowed"`
}

BorrowLendReserveState is the state of a token's borrow/lend reserve.

type BorrowLendReserveStateRequest

type BorrowLendReserveStateRequest struct {
	// Token is the spot token index.
	Token int `json:"token"`
}

BorrowLendReserveStateRequest is the request for InfoClient.BorrowLendReserveState.

type BorrowLendTokenState

type BorrowLendTokenState struct {
	Borrow BorrowLendBalance `json:"borrow"`
	Supply BorrowLendBalance `json:"supply"`
}

BorrowLendTokenState is a user's borrow and supply of one token.

type BorrowLendUserState

type BorrowLendUserState struct {
	// TokenToState maps spot token indices to positions.
	TokenToState TupleMap[int, BorrowLendTokenState] `json:"tokenToState"`
	// Health is "healthy", "atRisk", "marketLiquidatable" or
	// "backstopLiquidatable".
	Health       string   `json:"health"`
	HealthFactor *Decimal `json:"healthFactor"`
}

BorrowLendUserState is a user's borrow/lend positions.

type BorrowLendUserStateRequest

type BorrowLendUserStateRequest struct {
	User Address `json:"user"`
}

BorrowLendUserStateRequest is the request for InfoClient.BorrowLendUserState.

type Builder

type Builder struct {
	Address Address `json:"b"`
	// Fee is in tenths of a basis point: 10 means 0.01%.
	Fee int `json:"f"`
}

Builder is a builder fee attached to orders.

type CDepositAction

type CDepositAction struct {
	// Wei is the amount in units of 1e-8 HYPE.
	Wei uint64 `json:"wei"`
}

CDepositAction moves HYPE from the spot balance into staking, where it can be delegated with TokenDelegateAction. It must be signed by the account's own key.

type CSignerAction

type CSignerAction struct {
	JailSelf   bool
	UnjailSelf bool
}

CSignerAction jails or unjails the signer's validator. Set exactly one field.

func (CSignerAction) MarshalJSON

func (a CSignerAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes a as {"jailSelf":null} or {"unjailSelf":null}.

type CValidatorAction

type CValidatorAction struct {
	ChangeProfile *ValidatorProfileChange `json:"changeProfile,omitempty"`
	Register      *ValidatorRegistration  `json:"register,omitempty"`
	Unregister    bool                    `json:"-"`
}

CValidatorAction registers, updates or unregisters the signer's validator. Set exactly one field.

func (CValidatorAction) MarshalJSON

func (a CValidatorAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes Unregister as {"unregister":null}.

type CWithdrawAction

type CWithdrawAction struct {
	// Wei is the amount in units of 1e-8 HYPE.
	Wei uint64 `json:"wei"`
}

CWithdrawAction moves undelegated HYPE from staking back to the spot balance, after an unstaking queue. It must be signed by the account's own key.

type Cancel

type Cancel struct {
	Asset int   `json:"a"`
	Oid   int64 `json:"o"`
}

Cancel identifies an order to cancel.

type CancelAction

type CancelAction struct {
	Cancels []Cancel `json:"cancels"`
	// Fast prioritizes the cancel in the mempool.
	Fast bool `json:"f,omitempty"`
}

CancelAction cancels orders by order ID.

type CancelByCloid

type CancelByCloid struct {
	Asset int   `json:"asset"`
	Cloid Cloid `json:"cloid"`
}

CancelByCloid identifies an order to cancel by its client order ID.

type CancelByCloidAction

type CancelByCloidAction struct {
	Cancels []CancelByCloid `json:"cancels"`
	// Fast prioritizes the cancel in the mempool.
	Fast bool `json:"f,omitempty"`
}

CancelByCloidAction cancels orders by client order ID.

type Candle

type Candle struct {
	// OpenTime and CloseTime are in milliseconds since the Unix epoch.
	OpenTime  int64          `json:"t"`
	CloseTime int64          `json:"T"`
	Coin      string         `json:"s"`
	Interval  CandleInterval `json:"i"`
	Open      Decimal        `json:"o"`
	Close     Decimal        `json:"c"`
	High      Decimal        `json:"h"`
	Low       Decimal        `json:"l"`
	// Volume is in base units.
	Volume Decimal `json:"v"`
	// Trades is the number of trades.
	Trades int `json:"n"`
}

Candle is an OHLCV candle.

type CandleInterval

type CandleInterval string

CandleInterval is a candle duration.

const (
	Candle1m  CandleInterval = "1m"
	Candle3m  CandleInterval = "3m"
	Candle5m  CandleInterval = "5m"
	Candle15m CandleInterval = "15m"
	Candle30m CandleInterval = "30m"
	Candle1h  CandleInterval = "1h"
	Candle2h  CandleInterval = "2h"
	Candle4h  CandleInterval = "4h"
	Candle8h  CandleInterval = "8h"
	Candle12h CandleInterval = "12h"
	Candle1d  CandleInterval = "1d"
	Candle3d  CandleInterval = "3d"
	Candle1w  CandleInterval = "1w"
	Candle1M  CandleInterval = "1M"
)

Candle intervals.

type CandleSnapshotRequest

type CandleSnapshotRequest struct {
	Coin     string         `json:"coin"`
	Interval CandleInterval `json:"interval"`
	// StartTime and EndTime bound the candle open times in milliseconds
	// since the Unix epoch. A zero EndTime means now.
	StartTime int64 `json:"startTime"`
	EndTime   int64 `json:"endTime,omitempty"`
}

CandleSnapshotRequest is the request for InfoClient.CandleSnapshot.

type CandleSubscription

type CandleSubscription struct {
	Coin     string         `json:"coin"`
	Interval CandleInterval `json:"interval"`
}

CandleSubscription is the request of WebSocketClient.Candle.

type ClaimRewardsAction

type ClaimRewardsAction struct{}

ClaimRewardsAction claims referral and builder rewards.

type ClearinghouseState

type ClearinghouseState struct {
	// MarginSummary covers all positions; CrossMarginSummary only
	// cross-margined ones.
	MarginSummary              MarginSummary   `json:"marginSummary"`
	CrossMarginSummary         MarginSummary   `json:"crossMarginSummary"`
	CrossMaintenanceMarginUsed Decimal         `json:"crossMaintenanceMarginUsed"`
	Withdrawable               Decimal         `json:"withdrawable"`
	AssetPositions             []AssetPosition `json:"assetPositions"`
	// Time is in milliseconds since the Unix epoch.
	Time int64 `json:"time"`
}

ClearinghouseState is a user's perpetuals account on one dex.

type ClearinghouseStateEvent

type ClearinghouseStateEvent struct {
	Dex                string             `json:"dex"`
	User               Address            `json:"user"`
	ClearinghouseState ClearinghouseState `json:"clearinghouseState"`
}

ClearinghouseStateEvent is a message of WebSocketClient.ClearinghouseState.

type ClearinghouseStateRequest

type ClearinghouseStateRequest struct {
	User Address `json:"user"`
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

ClearinghouseStateRequest is the request for InfoClient.ClearinghouseState.

type ClearinghouseStateSubscription

type ClearinghouseStateSubscription struct {
	User Address `json:"user"`
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex"`
}

ClearinghouseStateSubscription is the request of WebSocketClient.ClearinghouseState.

type Cloid

type Cloid [16]byte

Cloid is a 16-byte client order ID, chosen by the client to track an order. It encodes as a lowercase 0x-prefixed 32-character hex string.

func MustParseCloid

func MustParseCloid(s string) Cloid

MustParseCloid is like ParseCloid but panics on error.

func ParseCloid

func ParseCloid(s string) (Cloid, error)

ParseCloid parses a 0x-prefixed (or bare) 32-character hex client order ID.

func (Cloid) MarshalText

func (c Cloid) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Cloid) String

func (c Cloid) String() string

String returns the lowercase 0x-prefixed hex form of c.

func (*Cloid) UnmarshalText

func (c *Cloid) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type ConvertToMultiSigUserAction

type ConvertToMultiSigUserAction struct {
	Signers *MultiSigSigners
}

ConvertToMultiSigUserAction turns the signer into a multi-sig account controlled by Signers, or, sent through ExchangeClient.MultiSig with nil Signers, back into a normal account. It must be signed by the account's own key.

func (ConvertToMultiSigUserAction) MarshalJSON

func (a ConvertToMultiSigUserAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes a in wire form: signers is a JSON string holding the signer set (users sorted, formatted like Python's json.dumps) or "null".

type CreateSubAccountAction

type CreateSubAccountAction struct {
	// Name is 1 to 16 characters.
	Name string `json:"name"`
}

CreateSubAccountAction creates a sub-account.

type CreateVaultAction

type CreateVaultAction struct {
	// Name is 3 to 50 characters.
	Name string `json:"name"`
	// Description is 10 to 250 characters.
	Description string `json:"description"`
	// InitialUSD is the leader's initial deposit in USDC times 1e6; at least
	// 100 USDC.
	InitialUSD uint64 `json:"initialUsd"`
}

CreateVaultAction creates a vault led by the account.

type CumFunding

type CumFunding struct {
	AllTime     Decimal `json:"allTime"`
	SinceOpen   Decimal `json:"sinceOpen"`
	SinceChange Decimal `json:"sinceChange"`
}

CumFunding is the cumulative funding paid by a position (negative when received).

type DailyUserVolume

type DailyUserVolume struct {
	// Date is formatted YYYY-MM-DD.
	Date      string  `json:"date"`
	UserCross Decimal `json:"userCross"`
	UserAdd   Decimal `json:"userAdd"`
	Exchange  Decimal `json:"exchange"`
}

DailyUserVolume is a user's and the exchange's volume on one day.

type Decimal

type Decimal string

Decimal is a base-10 number in Hyperliquid's string wire form, such as "0.001" or "-12.5".

Hyperliquid transmits prices, sizes and amounts as decimal strings, and Decimal keeps them lossless: use Decimal.Float64 or your preferred decimal library for arithmetic. When marshalled to JSON a Decimal is normalized (leading and trailing zeros stripped, "-0" collapsed to "0"); signatures are computed over the normalized form, which is what the exchange expects.

func DecimalFromFloat

func DecimalFromFloat(f float64) Decimal

DecimalFromFloat returns the shortest decimal representation of f. Round prices and sizes with FormatPrice and FormatSize before placing orders.

func FormatPrice

func FormatPrice(px Decimal, szDecimals int, spot bool) (Decimal, error)

FormatPrice rounds px toward zero to a valid Hyperliquid price for an asset with the given size decimals: at most 5 significant figures (integers are always allowed) and at most 6-szDecimals decimal places for perpetuals or 8-szDecimals for spot.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size.

Example
package main

import (
	"fmt"

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

func main() {
	// ETH perp has szDecimals 4: at most 5 significant figures and 2 decimals.
	px, _ := hyperliquid.FormatPrice("2712.3456", 4, false)
	sz, _ := hyperliquid.FormatSize("0.123456", 4)
	fmt.Println(px, sz)
}
Output:
2712.3 0.1234

func FormatSize

func FormatSize(sz Decimal, szDecimals int) (Decimal, error)

FormatSize rounds sz toward zero to szDecimals decimal places.

func ParseDecimal

func ParseDecimal(s string) (Decimal, error)

ParseDecimal validates s and returns it in canonical form.

func (Decimal) Float64

func (d Decimal) Float64() (float64, error)

Float64 parses d as a float64.

func (Decimal) IsZero

func (d Decimal) IsZero() bool

IsZero reports whether d is empty or numerically zero.

func (Decimal) MarshalJSON

func (d Decimal) MarshalJSON() ([]byte, error)

MarshalJSON encodes d as a normalized JSON string. An empty Decimal encodes as "" and an invalid one is an error.

func (Decimal) String

func (d Decimal) String() string

String returns d as a string.

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a JSON string or a JSON number. Numbers in exponent form, such as 1.5e-05, are converted exactly to plain form ("0.000015").

type DelegateDelta

type DelegateDelta struct {
	Validator    Address `json:"validator"`
	Amount       Decimal `json:"amount"`
	IsUndelegate bool    `json:"isUndelegate"`
}

DelegateDelta is a delegation to or undelegation from a validator.

type Delegation

type Delegation struct {
	Validator Address `json:"validator"`
	Amount    Decimal `json:"amount"`
	// LockedUntilTimestamp is in milliseconds since the Unix epoch.
	LockedUntilTimestamp int64 `json:"lockedUntilTimestamp"`
}

Delegation is HYPE staked to a validator.

type DelegationsRequest

type DelegationsRequest struct {
	User Address `json:"user"`
}

DelegationsRequest is the request for InfoClient.Delegations.

type DelegatorDelta

type DelegatorDelta struct {
	Delegate   *DelegateDelta     `json:"delegate,omitempty"`
	CDeposit   *StakingDeposit    `json:"cDeposit,omitempty"`
	Withdrawal *StakingWithdrawal `json:"withdrawal,omitempty"`
}

DelegatorDelta is the content of a DelegatorEvent; exactly one field is set.

type DelegatorEvent

type DelegatorEvent struct {
	// Time is in milliseconds since the Unix epoch.
	Time  int64          `json:"time"`
	Hash  string         `json:"hash"`
	Delta DelegatorDelta `json:"delta"`
}

DelegatorEvent is a change to a user's staking balances.

type DelegatorHistoryRequest

type DelegatorHistoryRequest struct {
	User Address `json:"user"`
}

DelegatorHistoryRequest is the request for InfoClient.DelegatorHistory.

type DelegatorReward

type DelegatorReward struct {
	// Time is in milliseconds since the Unix epoch.
	Time int64 `json:"time"`
	// Source is "delegation" or "commission".
	Source      string  `json:"source"`
	TotalAmount Decimal `json:"totalAmount"`
}

DelegatorReward is a staking reward.

type DelegatorRewardsRequest

type DelegatorRewardsRequest struct {
	User Address `json:"user"`
}

DelegatorRewardsRequest is the request for InfoClient.DelegatorRewards.

type DelegatorSummary

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

DelegatorSummary summarizes a user's staking balances.

type DelegatorSummaryRequest

type DelegatorSummaryRequest struct {
	User Address `json:"user"`
}

DelegatorSummaryRequest is the request for InfoClient.DelegatorSummary.

type DeployerFee

type DeployerFee struct {
	// Scale is between 0 and 3, or between 0 and 10 (exclusive) in growth
	// mode.
	Scale Decimal `json:"scale"`
	// GrowthMode cuts all trading fees of the asset by 90%.
	GrowthMode bool `json:"growthMode"`
}

DeployerFee sets the fees of an asset's trades: the deployer receives Scale times the user's normal fee, and the protocol fee rises to match when Scale exceeds 1. On mainnet it may change once per 30 days.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-3-deployer-actions.

type EVMContract

type EVMContract struct {
	Address Address `json:"address"`
	// EVMExtraWeiDecimals is the EVM token's decimals minus the spot token's
	// wei decimals.
	EVMExtraWeiDecimals int `json:"evm_extra_wei_decimals"`
}

EVMContract is the HyperEVM contract linked to a spot token.

type EVMEscrow

type EVMEscrow struct {
	Coin  string  `json:"coin"`
	Token int     `json:"token"`
	Total Decimal `json:"total"`
}

EVMEscrow is a token amount in transit from HyperEVM to HyperCore.

type EVMUserModifyAction

type EVMUserModifyAction struct {
	UsingBigBlocks bool `json:"usingBigBlocks"`
}

EVMUserModifyAction selects the HyperEVM block type of the user's transactions.

type ExchangeClient

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

ExchangeClient signs and submits actions to the /exchange endpoint. It is safe for concurrent use.

Methods return an *APIError when the exchange rejects the request, and a joined *StatusError for each failed item of a batch (orders, cancels).

func NewExchangeClient

func NewExchangeClient(network Network, signer Signer, opts ...Option) *ExchangeClient

NewExchangeClient returns a client that signs with signer on network. The signer may be the account's own key or an API (agent) wallet approved with ExchangeClient.ApproveAgent; user-signed actions such as transfers and withdrawals require the account's own key.

func (*ExchangeClient) ActivateOutcomeDeployer

func (c *ExchangeClient) ActivateOutcomeDeployer(ctx context.Context, a ActivateOutcomeDeployerAction) error

ActivateOutcomeDeployer activates or deactivates the signer as an outcome deployer.

func (*ExchangeClient) AgentSendAsset

func (c *ExchangeClient) AgentSendAsset(ctx context.Context, a AgentSendAssetAction) error

AgentSendAsset moves a token between perp dexes, spot and accounts.

func (*ExchangeClient) AgentSetAbstraction

func (c *ExchangeClient) AgentSetAbstraction(ctx context.Context, a AgentSetAbstractionAction) error

AgentSetAbstraction sets the account abstraction mode.

func (*ExchangeClient) ApproveAgent

func (c *ExchangeClient) ApproveAgent(ctx context.Context, a ApproveAgentAction) error

ApproveAgent authorizes an API wallet.

func (*ExchangeClient) ApproveBuilderFee

func (c *ExchangeClient) ApproveBuilderFee(ctx context.Context, a ApproveBuilderFeeAction) error

ApproveBuilderFee approves a builder's maximum fee rate.

func (*ExchangeClient) AuthorizeAQAv2Role

func (c *ExchangeClient) AuthorizeAQAv2Role(ctx context.Context, a AuthorizeAQAv2RoleAction) error

AuthorizeAQAv2Role authorizes an aligned quote asset role.

func (*ExchangeClient) BatchModify

func (c *ExchangeClient) BatchModify(ctx context.Context, a BatchModifyAction) ([]OrderResult, error)

BatchModify replaces orders and returns one status per new order, like ExchangeClient.Order.

func (*ExchangeClient) BorrowLend

func (c *ExchangeClient) BorrowLend(ctx context.Context, a BorrowLendAction) error

BorrowLend supplies, withdraws, borrows or repays a token.

func (*ExchangeClient) CDeposit

func (c *ExchangeClient) CDeposit(ctx context.Context, a CDepositAction) error

CDeposit moves HYPE from spot into staking.

func (*ExchangeClient) CSigner

func (c *ExchangeClient) CSigner(ctx context.Context, a CSignerAction) error

CSigner submits a validator signer action.

func (*ExchangeClient) CValidator

func (c *ExchangeClient) CValidator(ctx context.Context, a CValidatorAction) error

CValidator submits a validator action.

func (*ExchangeClient) CWithdraw

func (c *ExchangeClient) CWithdraw(ctx context.Context, a CWithdrawAction) error

CWithdraw moves HYPE from staking to spot.

func (*ExchangeClient) Cancel

func (c *ExchangeClient) Cancel(ctx context.Context, a CancelAction) error

Cancel cancels orders. If some cancels fail, it returns a joined *StatusError per failed cancel.

func (*ExchangeClient) CancelByCloid

func (c *ExchangeClient) CancelByCloid(ctx context.Context, a CancelByCloidAction) error

CancelByCloid cancels orders by client order ID. If some cancels fail, it returns a joined *StatusError per failed cancel.

func (*ExchangeClient) ClaimRewards

func (c *ExchangeClient) ClaimRewards(ctx context.Context) error

ClaimRewards claims referral and builder rewards.

func (*ExchangeClient) ConvertToMultiSigUser

func (c *ExchangeClient) ConvertToMultiSigUser(ctx context.Context, a ConvertToMultiSigUserAction) error

ConvertToMultiSigUser converts the signer into a multi-sig account. To convert a multi-sig account back, submit the action with nil Signers via ExchangeClient.MultiSig.

func (*ExchangeClient) CreateSubAccount

func (c *ExchangeClient) CreateSubAccount(ctx context.Context, a CreateSubAccountAction) (Address, error)

CreateSubAccount creates a sub-account and returns its address.

func (*ExchangeClient) CreateVault

func (c *ExchangeClient) CreateVault(ctx context.Context, a CreateVaultAction) (Address, error)

CreateVault creates a vault and returns its address.

func (*ExchangeClient) EVMUserModify

func (c *ExchangeClient) EVMUserModify(ctx context.Context, a EVMUserModifyAction) error

EVMUserModify toggles HyperEVM big blocks.

func (*ExchangeClient) FinalizeEVMContract

func (c *ExchangeClient) FinalizeEVMContract(ctx context.Context, a FinalizeEVMContractAction) error

FinalizeEVMContract finalizes a spot token's EVM contract link.

func (*ExchangeClient) GossipPriorityBid

func (c *ExchangeClient) GossipPriorityBid(ctx context.Context, a GossipPriorityBidAction) error

GossipPriorityBid bids for a gossip priority slot.

func (*ExchangeClient) HIP3LiquidatorTransfer

func (c *ExchangeClient) HIP3LiquidatorTransfer(ctx context.Context, a HIP3LiquidatorTransferAction) error

HIP3LiquidatorTransfer moves funds to or from a HIP-3 backstop liquidator.

func (*ExchangeClient) LinkStakingUser

func (c *ExchangeClient) LinkStakingUser(ctx context.Context, a LinkStakingUserAction) error

LinkStakingUser requests or finalizes a staking link.

func (*ExchangeClient) Modify

func (c *ExchangeClient) Modify(ctx context.Context, a ModifyAction) error

Modify replaces a resting order.

func (*ExchangeClient) MultiSig

func (c *ExchangeClient) MultiSig(ctx context.Context, multiSigUser Address, a Action, nonce uint64, signatures []Signature) (json.RawMessage, error)

MultiSig submits action a for the multi-sig account multiSigUser, with c's signer as the leader (outer signer). signatures are the authorized users' approvals from ExchangeClient.SignMultiSig, made with the same nonce. It returns the raw response data of the inner action, if any. When that data is a batch result ({"statuses":[...]}), rejected items are also returned as a joined *StatusError each, like ExchangeClient.Order.

func (*ExchangeClient) Noop

func (c *ExchangeClient) Noop(ctx context.Context, nonce uint64) error

Noop submits a no-op with the given nonce, invalidating any pending action signed with that nonce.

func (*ExchangeClient) Order

Order places orders and returns one status per order, in request order. If some orders are rejected, the statuses are returned together with a joined *StatusError per rejected order.

Example
package main

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

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

func main() {
	// Trade with an API (agent) wallet approved for the account.
	signer, err := hyperliquid.NewPrivateKeySigner(os.Getenv("HL_AGENT_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	ex := hyperliquid.NewExchangeClient(hyperliquid.Testnet, signer)

	statuses, err := ex.Order(context.Background(), hyperliquid.OrderAction{
		Orders: []hyperliquid.Order{{
			Asset: 0, // BTC
			IsBuy: true,
			Price: "50000",
			Size:  "0.001",
			Type:  hyperliquid.OrderType{Limit: &hyperliquid.LimitOrder{Tif: hyperliquid.TifGtc}},
		}},
	})
	var rejected *hyperliquid.StatusError
	switch {
	case errors.As(err, &rejected):
		log.Printf("order %d rejected: %s", rejected.Index, rejected.Message)
	case err != nil:
		log.Fatal(err)
	case statuses[0].Resting != nil:
		fmt.Println("resting oid:", statuses[0].Resting.Oid)
	case statuses[0].Filled != nil:
		fmt.Println("filled at", statuses[0].Filled.AvgPx)
	}
}

func (*ExchangeClient) OutcomeDeploy

func (c *ExchangeClient) OutcomeDeploy(ctx context.Context, a OutcomeDeployAction) error

OutcomeDeploy submits an outcome deployer action.

func (*ExchangeClient) PerpDeploy

func (c *ExchangeClient) PerpDeploy(ctx context.Context, a PerpDeployAction) error

PerpDeploy submits a HIP-3 deployer action.

func (*ExchangeClient) RegisterReferrer

func (c *ExchangeClient) RegisterReferrer(ctx context.Context, a RegisterReferrerAction) error

RegisterReferrer registers a referral code.

func (*ExchangeClient) ReserveRequestWeight

func (c *ExchangeClient) ReserveRequestWeight(ctx context.Context, a ReserveRequestWeightAction) error

ReserveRequestWeight buys additional request rate limit.

func (*ExchangeClient) ScheduleCancel

func (c *ExchangeClient) ScheduleCancel(ctx context.Context, a ScheduleCancelAction) error

ScheduleCancel sets or clears the scheduled cancel of all open orders.

func (*ExchangeClient) SendAsset

func (c *ExchangeClient) SendAsset(ctx context.Context, a SendAssetAction) error

SendAsset moves a token between addresses, perp dexes and spot.

func (*ExchangeClient) SendToEVMWithData

func (c *ExchangeClient) SendToEVMWithData(ctx context.Context, a SendToEVMWithDataAction) error

SendToEVMWithData sends a token to a contract with a data payload.

func (*ExchangeClient) SetDisplayName

func (c *ExchangeClient) SetDisplayName(ctx context.Context, a SetDisplayNameAction) error

SetDisplayName sets the account's display name.

func (*ExchangeClient) SetReferrer

func (c *ExchangeClient) SetReferrer(ctx context.Context, a SetReferrerAction) error

SetReferrer sets the account's referrer.

func (*ExchangeClient) SignMultiSig

func (c *ExchangeClient) SignMultiSig(ctx context.Context, a Action, multiSigUser, outerSigner Address, nonce uint64) (Signature, error)

SignMultiSig returns c's signature approving action a for the multi-sig account multiSigUser. The action is submitted by the leader outerSigner with ExchangeClient.MultiSig using the same nonce; for L1 actions the vault and expiry of both clients must match.

func (*ExchangeClient) Signer

func (c *ExchangeClient) Signer() Signer

Signer returns the client's signer.

func (*ExchangeClient) SpotDeploy

func (c *ExchangeClient) SpotDeploy(ctx context.Context, a SpotDeployAction) error

SpotDeploy submits a spot deployer action.

func (*ExchangeClient) SpotSend

func (c *ExchangeClient) SpotSend(ctx context.Context, a SpotSendAction) error

SpotSend sends a spot token to another address.

func (*ExchangeClient) SpotUser

func (c *ExchangeClient) SpotUser(ctx context.Context, a SpotUserAction) error

SpotUser changes spot account settings.

func (*ExchangeClient) StakingLinkDisableTradingUser

func (c *ExchangeClient) StakingLinkDisableTradingUser(ctx context.Context, a StakingLinkDisableTradingUserAction) error

StakingLinkDisableTradingUser permanently disables a linked trading account.

func (*ExchangeClient) SubAccountModify

func (c *ExchangeClient) SubAccountModify(ctx context.Context, a SubAccountModifyAction) error

SubAccountModify renames a sub-account.

func (*ExchangeClient) SubAccountSpotTransfer

func (c *ExchangeClient) SubAccountSpotTransfer(ctx context.Context, a SubAccountSpotTransferAction) error

SubAccountSpotTransfer moves a spot token to or from a sub-account.

func (*ExchangeClient) SubAccountTransfer

func (c *ExchangeClient) SubAccountTransfer(ctx context.Context, a SubAccountTransferAction) error

SubAccountTransfer moves perp USDC to or from a sub-account.

func (*ExchangeClient) TokenDelegate

func (c *ExchangeClient) TokenDelegate(ctx context.Context, a TokenDelegateAction) error

TokenDelegate delegates or undelegates staked HYPE.

func (*ExchangeClient) TopUpIsolatedOnlyMargin

func (c *ExchangeClient) TopUpIsolatedOnlyMargin(ctx context.Context, a TopUpIsolatedOnlyMarginAction) error

TopUpIsolatedOnlyMargin tops up an isolated-only position's margin.

func (*ExchangeClient) TrailingStop

func (c *ExchangeClient) TrailingStop(ctx context.Context, a TrailingStopAction) (int64, error)

TrailingStop places a trailing stop order and returns its order ID.

func (*ExchangeClient) TwapCancel

func (c *ExchangeClient) TwapCancel(ctx context.Context, a TwapCancelAction) error

TwapCancel cancels a TWAP order. A failed cancel returns a *StatusError.

func (*ExchangeClient) TwapOrder

func (c *ExchangeClient) TwapOrder(ctx context.Context, a TwapOrderAction) (int64, error)

TwapOrder places a TWAP order and returns its TWAP ID. A rejected order returns a *StatusError.

func (*ExchangeClient) USDClassTransfer

func (c *ExchangeClient) USDClassTransfer(ctx context.Context, a USDClassTransferAction) error

USDClassTransfer moves USDC between the spot and perp balances.

func (*ExchangeClient) USDSend

func (c *ExchangeClient) USDSend(ctx context.Context, a USDSendAction) error

USDSend sends USDC to another address.

func (*ExchangeClient) UpdateIsolatedMargin

func (c *ExchangeClient) UpdateIsolatedMargin(ctx context.Context, a UpdateIsolatedMarginAction) error

UpdateIsolatedMargin changes the margin of an isolated position.

func (*ExchangeClient) UpdateLeverage

func (c *ExchangeClient) UpdateLeverage(ctx context.Context, a UpdateLeverageAction) error

UpdateLeverage sets the leverage of a perp asset.

func (*ExchangeClient) UserOutcome

func (c *ExchangeClient) UserOutcome(ctx context.Context, a UserOutcomeAction) error

UserOutcome splits, merges or negates outcome shares.

func (*ExchangeClient) UserPortfolioMargin

func (c *ExchangeClient) UserPortfolioMargin(ctx context.Context, a UserPortfolioMarginAction) error

UserPortfolioMargin enables or disables portfolio margin.

func (*ExchangeClient) UserSetAbstraction

func (c *ExchangeClient) UserSetAbstraction(ctx context.Context, a UserSetAbstractionAction) error

UserSetAbstraction sets an account's abstraction mode.

func (*ExchangeClient) ValidatorL1Stream

func (c *ExchangeClient) ValidatorL1Stream(ctx context.Context, a ValidatorL1StreamAction) error

ValidatorL1Stream submits a validator's risk-free rate vote.

func (*ExchangeClient) VaultDistribute

func (c *ExchangeClient) VaultDistribute(ctx context.Context, a VaultDistributeAction) error

VaultDistribute distributes vault funds to its followers.

func (*ExchangeClient) VaultModify

func (c *ExchangeClient) VaultModify(ctx context.Context, a VaultModifyAction) error

VaultModify changes a vault's settings.

func (*ExchangeClient) VaultTransfer

func (c *ExchangeClient) VaultTransfer(ctx context.Context, a VaultTransferAction) error

VaultTransfer deposits into or withdraws from a vault.

func (*ExchangeClient) WithExpiresAfter

func (c *ExchangeClient) WithExpiresAfter(t time.Time) *ExchangeClient

WithExpiresAfter returns a copy of c whose L1 actions are rejected by the exchange if they arrive after t.

func (*ExchangeClient) WithVault

func (c *ExchangeClient) WithVault(vault Address) *ExchangeClient

WithVault returns a copy of c that trades on behalf of a vault or sub-account. It applies to L1 actions only; user-signed actions always act for the signer.

func (*ExchangeClient) Withdraw

func (c *ExchangeClient) Withdraw(ctx context.Context, a WithdrawAction) error

Withdraw withdraws USDC to Arbitrum.

type ExchangeStatus

type ExchangeStatus struct {
	// Time is the server time in milliseconds since the Unix epoch.
	Time int64 `json:"time"`
	// SpecialStatuses describes an exceptional state, such as an
	// upgrade, or is nil.
	SpecialStatuses *string `json:"specialStatuses"`
}

ExchangeStatus is the status of the exchange.

type ExistingTokenWei

type ExistingTokenWei struct {
	Token int
	Wei   Decimal
}

ExistingTokenWei gives the holders of an existing token a genesis balance, distributed pro rata. It encodes as [token, wei].

func (ExistingTokenWei) MarshalJSON

func (e ExistingTokenWei) MarshalJSON() ([]byte, error)

MarshalJSON encodes e as [token, wei].

type ExplorerTx

type ExplorerTx struct {
	// Action is the transaction's action JSON, such as {"type":"order",...}.
	// Some historical transactions encode it as a JSON array.
	Action json.RawMessage `json:"action"`
	Block  int64           `json:"block"`
	// Error is the failure reason, or nil if the transaction succeeded.
	Error *string `json:"error"`
	Hash  string  `json:"hash"`
	// Time is in milliseconds since the Unix epoch.
	Time int64   `json:"time"`
	User Address `json:"user"`
}

ExplorerTx is a transaction as reported by the block explorer.

type ExtraAgent

type ExtraAgent struct {
	Address Address `json:"address"`
	Name    string  `json:"name"`
	// ValidUntil is the expiry in milliseconds since the Unix epoch, or nil.
	ValidUntil *int64 `json:"validUntil"`
}

ExtraAgent is a named API wallet approved by a user.

type ExtraAgentsRequest

type ExtraAgentsRequest struct {
	User Address `json:"user"`
}

ExtraAgentsRequest is the request for InfoClient.ExtraAgents.

type FastAssetCtx

type FastAssetCtx struct {
	// MarkPx is nil when unchanged.
	MarkPx *Decimal `json:"markPx,omitempty"`
	// MidPx is nil when unchanged or when the coin has no mid price.
	MidPx *Decimal `json:"midPx,omitempty"`
}

FastAssetCtx holds the prices of one coin in FastAssetCtxs.

type FastAssetCtxs

type FastAssetCtxs map[string]FastAssetCtx

FastAssetCtxs is a message of WebSocketClient.FastAssetCtxs: price updates keyed by coin. The first message holds every coin, later ones only the coins that changed.

func (*FastAssetCtxs) UnmarshalJSON

func (m *FastAssetCtxs) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the wire form: a base64 string of raw-DEFLATE (RFC 1951) compressed JSON.

type FeeSchedule

type FeeSchedule struct {
	Cross     Decimal  `json:"cross"`
	Add       Decimal  `json:"add"`
	SpotCross Decimal  `json:"spotCross"`
	SpotAdd   Decimal  `json:"spotAdd"`
	Tiers     FeeTiers `json:"tiers"`
	// ReferralDiscount is the discount fraction for referred users.
	ReferralDiscount     Decimal           `json:"referralDiscount"`
	StakingDiscountTiers []StakingDiscount `json:"stakingDiscountTiers"`
}

FeeSchedule is the base fee schedule.

type FeeTiers

type FeeTiers struct {
	VIP []VIPFeeTier `json:"vip"`
	MM  []MMFeeTier  `json:"mm"`
}

FeeTiers lists the volume and market-maker fee tiers.

type FillLiquidation

type FillLiquidation struct {
	LiquidatedUser Address `json:"liquidatedUser,omitzero"`
	MarkPx         Decimal `json:"markPx"`
	// Method is "market" or "backstop".
	Method string `json:"method"`
}

FillLiquidation describes the liquidation a fill was part of.

type FilledOrder

type FilledOrder struct {
	TotalSz Decimal `json:"totalSz"`
	AvgPx   Decimal `json:"avgPx"`
	Oid     int64   `json:"oid"`
	Cloid   *Cloid  `json:"cloid,omitempty"`
}

FilledOrder is an order that filled immediately.

type FinalizeEVMContractAction

type FinalizeEVMContractAction struct {
	Token int                      `json:"token"`
	Input FinalizeEVMContractInput `json:"input"`
}

FinalizeEVMContractAction completes the link between a spot token and an ERC-20 contract requested with SpotDeployAction.RequestEVMContract. It is signed by the contract's deployer.

type FinalizeEVMContractInput

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

FinalizeEVMContractInput is how the finalizer proves it deployed the contract.

func FinalizeCreate

func FinalizeCreate(nonce uint64) FinalizeEVMContractInput

FinalizeCreate proves deployment of a contract created by the finalizer account with the given transaction nonce.

func (FinalizeEVMContractInput) MarshalJSON

func (in FinalizeEVMContractInput) MarshalJSON() ([]byte, error)

MarshalJSON encodes in as "firstStorageSlot", "customStorageSlot" or {"create":{"nonce":n}}.

type FreezeUser

type FreezeUser struct {
	Token  int     `json:"token"`
	User   Address `json:"user"`
	Freeze bool    `json:"freeze"`
}

FreezeUser freezes or unfreezes a user's balance of a token.

type FrontendOpenOrder

type FrontendOpenOrder struct {
	Coin    string  `json:"coin"`
	Side    Side    `json:"side"`
	LimitPx Decimal `json:"limitPx"`
	// Sz is the remaining size; OrigSz the size when placed.
	Sz  Decimal `json:"sz"`
	Oid int64   `json:"oid"`
	// Timestamp is the placement time in milliseconds since the Unix epoch.
	Timestamp        int64   `json:"timestamp"`
	OrigSz           Decimal `json:"origSz"`
	TriggerCondition string  `json:"triggerCondition"`
	IsTrigger        bool    `json:"isTrigger"`
	TriggerPx        Decimal `json:"triggerPx"`
	// Children are the TP/SL orders attached to this order.
	Children       []FrontendOpenOrder `json:"children"`
	IsPositionTpsl bool                `json:"isPositionTpsl"`
	ReduceOnly     bool                `json:"reduceOnly"`
	// OrderType is "Market", "Limit", "Stop Market", "Stop Limit",
	// "Take Profit Market", "Take Profit Limit", "Twap Slice", "Vault Close"
	// or "Spot Dust Conversion".
	OrderType string `json:"orderType"`
	// Tif is nil for trigger orders; liquidations use "LiquidationMarket".
	Tif   *Tif   `json:"tif"`
	Cloid *Cloid `json:"cloid"`
}

FrontendOpenOrder is an order with the trigger and TP/SL details shown by the Hyperliquid web app.

type FrontendOpenOrdersRequest

type FrontendOpenOrdersRequest struct {
	User Address `json:"user"`
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

FrontendOpenOrdersRequest is the request for InfoClient.FrontendOpenOrders.

type FundingDelta

type FundingDelta struct {
	// Type is always "funding".
	Type string `json:"type"`
	Coin string `json:"coin"`
	// USDC is the amount paid (negative) or received (positive).
	USDC        Decimal `json:"usdc"`
	Szi         Decimal `json:"szi"`
	FundingRate Decimal `json:"fundingRate"`
	// NSamples is the number of premium samples, or nil.
	NSamples *int `json:"nSamples"`
}

FundingDelta is the content of a FundingUpdate.

type FundingHistoryRequest

type FundingHistoryRequest struct {
	Coin string `json:"coin"`
	// StartTime and EndTime are in milliseconds since the Unix epoch. A zero
	// EndTime means now.
	StartTime int64 `json:"startTime"`
	EndTime   int64 `json:"endTime,omitempty"`
}

FundingHistoryRequest is the request for InfoClient.FundingHistory.

type FundingPayment

type FundingPayment struct {
	// Time is in milliseconds since the Unix epoch.
	Time int64  `json:"time"`
	Coin string `json:"coin"`
	// USDC is the amount paid (negative) or received (positive).
	USDC        Decimal `json:"usdc"`
	Szi         Decimal `json:"szi"`
	FundingRate Decimal `json:"fundingRate"`
	// NSamples is the number of premium samples, or nil.
	NSamples *int `json:"nSamples"`
}

FundingPayment is a funding payment of one position.

type FundingRate

type FundingRate struct {
	Coin        string  `json:"coin"`
	FundingRate Decimal `json:"fundingRate"`
	Premium     Decimal `json:"premium"`
	// Time is in milliseconds since the Unix epoch.
	Time int64 `json:"time"`
}

FundingRate is a historical funding rate of a perpetual asset.

type FundingUpdate

type FundingUpdate struct {
	// Time is in milliseconds since the Unix epoch.
	Time  int64        `json:"time"`
	Hash  string       `json:"hash"`
	Delta FundingDelta `json:"delta"`
}

FundingUpdate is a funding payment of one position.

type GossipPriorityAuctionStatus

type GossipPriorityAuctionStatus struct {
	// IPs holds the IP address that won each slot, or nil for an empty slot.
	IPs []*string
	// Auctions holds the auction of each slot.
	Auctions []AuctionStatus
}

GossipPriorityAuctionStatus is the state of the gossip priority slot auctions.

func (*GossipPriorityAuctionStatus) UnmarshalJSON

func (s *GossipPriorityAuctionStatus) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the wire form [ips, auctions].

type GossipPriorityBidAction

type GossipPriorityBidAction struct {
	// SlotID is 0 or 1.
	SlotID int    `json:"slotId"`
	IP     string `json:"ip"`
	// MaxGas is the most to pay, in HYPE wei (1e-8).
	MaxGas uint64 `json:"maxGas"`
}

GossipPriorityBidAction bids in the Dutch auction for a gossip priority slot, which delivers prioritized mempool data to an IP address.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/priority-fees.

type Grouping

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

Grouping controls how the orders of an OrderAction are linked.

func GroupingPriority

func GroupingPriority(rate uint64) Grouping

GroupingPriority bids a priority fee of rate/1e8 of notional for faster execution. All orders must be IOC, or all must be non-reduce-only ALO.

func (Grouping) MarshalJSON

func (g Grouping) MarshalJSON() ([]byte, error)

MarshalJSON encodes g as "na", "normalTpsl", "positionTpsl" or {"p":rate}.

type HIP3LiquidatorTransferAction

type HIP3LiquidatorTransferAction struct {
	Dex string `json:"dex"`
	// Ntl is the amount in quote token units ×1e6; it must be a multiple of
	// 1e9.
	Ntl       uint64 `json:"ntl"`
	IsDeposit bool   `json:"isDeposit"`
}

HIP3LiquidatorTransferAction deposits into or withdraws from a HIP-3 dex's backstop liquidator.

type HaltTrading

type HaltTrading struct {
	Coin     string `json:"coin"`
	IsHalted bool   `json:"isHalted"`
}

HaltTrading halts or resumes trading of an asset.

type HistoricalOrdersRequest

type HistoricalOrdersRequest struct {
	User Address `json:"user"`
}

HistoricalOrdersRequest is the request for InfoClient.HistoricalOrders.

type InfoClient

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

InfoClient queries market data and account state through the /info endpoint. It needs no keys and is safe for concurrent use.

func NewInfoClient

func NewInfoClient(network Network, opts ...Option) *InfoClient

NewInfoClient returns a client for network.

func (*InfoClient) ActiveAssetData

func (c *InfoClient) ActiveAssetData(ctx context.Context, req ActiveAssetDataRequest) (*ActiveAssetData, error)

ActiveAssetData returns a user's leverage and maximum trade sizes for a perpetual.

func (*InfoClient) AllBorrowLendReserveStates

func (c *InfoClient) AllBorrowLendReserveStates(ctx context.Context) (TupleMap[int, BorrowLendReserveState], error)

AllBorrowLendReserveStates returns every reserve state, keyed by spot token index.

func (*InfoClient) AllMids

func (c *InfoClient) AllMids(ctx context.Context, req AllMidsRequest) (map[string]Decimal, error)

AllMids returns the mid price of every coin, keyed by coin name.

func (*InfoClient) AllPerpMetas

func (c *InfoClient) AllPerpMetas(ctx context.Context) ([]Meta, error)

AllPerpMetas returns the Meta of every perp dex, indexed like InfoClient.PerpDexs: element 0 is the main dex.

func (*InfoClient) ApprovedBuilders

func (c *InfoClient) ApprovedBuilders(ctx context.Context, req ApprovedBuildersRequest) ([]Address, error)

ApprovedBuilders returns the builders a user has approved fees for.

func (*InfoClient) BlockDetails

func (c *InfoClient) BlockDetails(ctx context.Context, req BlockDetailsRequest) (*BlockDetails, error)

BlockDetails returns a block from the explorer.

func (*InfoClient) BorrowLendReserveState

func (c *InfoClient) BorrowLendReserveState(ctx context.Context, req BorrowLendReserveStateRequest) (*BorrowLendReserveState, error)

BorrowLendReserveState returns a token's reserve state. Tokens without a reserve fail with an *APIError.

func (*InfoClient) BorrowLendUserState

func (c *InfoClient) BorrowLendUserState(ctx context.Context, req BorrowLendUserStateRequest) (*BorrowLendUserState, error)

BorrowLendUserState returns a user's borrow/lend positions and health.

func (*InfoClient) CandleSnapshot

func (c *InfoClient) CandleSnapshot(ctx context.Context, req CandleSnapshotRequest) ([]Candle, error)

CandleSnapshot returns candles in a time range. At most the 5000 most recent candles are available.

func (*InfoClient) ClearinghouseState

func (c *InfoClient) ClearinghouseState(ctx context.Context, req ClearinghouseStateRequest) (*ClearinghouseState, error)

ClearinghouseState returns a user's perpetuals account state.

func (*InfoClient) Delegations

func (c *InfoClient) Delegations(ctx context.Context, req DelegationsRequest) ([]Delegation, error)

Delegations returns a user's staking delegations.

func (*InfoClient) DelegatorHistory

func (c *InfoClient) DelegatorHistory(ctx context.Context, req DelegatorHistoryRequest) ([]DelegatorEvent, error)

DelegatorHistory returns a user's staking history.

func (*InfoClient) DelegatorRewards

func (c *InfoClient) DelegatorRewards(ctx context.Context, req DelegatorRewardsRequest) ([]DelegatorReward, error)

DelegatorRewards returns a user's staking rewards.

func (*InfoClient) DelegatorSummary

func (c *InfoClient) DelegatorSummary(ctx context.Context, req DelegatorSummaryRequest) (*DelegatorSummary, error)

DelegatorSummary returns a summary of a user's staking balances.

func (*InfoClient) ExchangeStatus

func (c *InfoClient) ExchangeStatus(ctx context.Context) (*ExchangeStatus, error)

ExchangeStatus returns the status of the exchange.

func (*InfoClient) ExtraAgents

func (c *InfoClient) ExtraAgents(ctx context.Context, req ExtraAgentsRequest) ([]ExtraAgent, error)

ExtraAgents returns a user's named API wallets.

func (*InfoClient) FrontendOpenOrders

func (c *InfoClient) FrontendOpenOrders(ctx context.Context, req FrontendOpenOrdersRequest) ([]FrontendOpenOrder, error)

FrontendOpenOrders returns a user's resting orders with trigger and TP/SL details.

func (*InfoClient) FundingHistory

func (c *InfoClient) FundingHistory(ctx context.Context, req FundingHistoryRequest) ([]FundingRate, error)

FundingHistory returns the funding rates of a coin, oldest first, at most 500 per call.

func (*InfoClient) GossipPriorityAuctionStatus

func (c *InfoClient) GossipPriorityAuctionStatus(ctx context.Context) (*GossipPriorityAuctionStatus, error)

GossipPriorityAuctionStatus returns the gossip priority slot auctions.

func (*InfoClient) GossipRootIPs

func (c *InfoClient) GossipRootIPs(ctx context.Context) ([]string, error)

GossipRootIPs returns the IPv4 addresses of the gossip root peers that non-validating nodes connect to.

func (*InfoClient) HistoricalOrders

func (c *InfoClient) HistoricalOrders(ctx context.Context, req HistoricalOrdersRequest) ([]OrderWithStatus, error)

HistoricalOrders returns up to 2000 of a user's most recent orders.

func (*InfoClient) IsVIP

func (c *InfoClient) IsVIP(ctx context.Context, req IsVIPRequest) (bool, error)

IsVIP reports whether a user has VIP status.

func (*InfoClient) L2Book

func (c *InfoClient) L2Book(ctx context.Context, req L2BookRequest) (*L2Book, error)

L2Book returns an order book snapshot of at most 20 levels per side, or nil if the coin does not exist.

Example
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	info := hyperliquid.NewInfoClient(hyperliquid.Mainnet)
	book, err := info.L2Book(context.Background(), hyperliquid.L2BookRequest{Coin: "BTC"})
	if err != nil {
		log.Fatal(err)
	}
	bids, asks := book.Levels[0], book.Levels[1]
	fmt.Printf("BTC %s / %s\n", bids[0].Px, asks[0].Px)
}

func (*InfoClient) LeadingVaults

func (c *InfoClient) LeadingVaults(ctx context.Context, req LeadingVaultsRequest) ([]LeadingVault, error)

LeadingVaults returns the vaults a user leads.

func (*InfoClient) LegalCheck

func (c *InfoClient) LegalCheck(ctx context.Context, req LegalCheckRequest) (*LegalCheck, error)

LegalCheck returns whether a user has accepted the terms and may use the exchange.

func (*InfoClient) Liquidatable

func (c *InfoClient) Liquidatable(ctx context.Context) ([]LiquidatablePosition, error)

Liquidatable returns the positions currently eligible for liquidation.

func (*InfoClient) MarginTable

func (c *InfoClient) MarginTable(ctx context.Context, req MarginTableRequest) (*MarginTable, error)

MarginTable returns a margin table. Unknown IDs fail with an *APIError.

func (*InfoClient) MaxBuilderFee

func (c *InfoClient) MaxBuilderFee(ctx context.Context, req MaxBuilderFeeRequest) (int, error)

MaxBuilderFee returns the maximum fee a user has approved for a builder, in tenths of a basis point (see Builder.Fee).

func (*InfoClient) MaxMarketOrderNtls

func (c *InfoClient) MaxMarketOrderNtls(ctx context.Context) (TupleMap[int, Decimal], error)

MaxMarketOrderNtls returns the maximum market order notional keyed by asset max leverage.

func (*InfoClient) Meta

func (c *InfoClient) Meta(ctx context.Context, req MetaRequest) (*Meta, error)

Meta returns perpetual market metadata.

func (*InfoClient) MetaAndAssetCtxs

func (c *InfoClient) MetaAndAssetCtxs(ctx context.Context, req MetaAndAssetCtxsRequest) (*MetaAndAssetCtxs, error)

MetaAndAssetCtxs returns perpetual metadata and asset contexts.

func (*InfoClient) OpenOrders

func (c *InfoClient) OpenOrders(ctx context.Context, req OpenOrdersRequest) ([]OpenOrder, error)

OpenOrders returns a user's resting orders.

func (*InfoClient) OrderStatus

func (c *InfoClient) OrderStatus(ctx context.Context, req OrderStatusRequest) (*OrderWithStatus, error)

OrderStatus returns an order and its status, or nil if the order is unknown.

func (*InfoClient) OutcomeMeta

func (c *InfoClient) OutcomeMeta(ctx context.Context) (*OutcomeMeta, error)

OutcomeMeta returns outcome market metadata.

func (*InfoClient) OutcomeTemplates

func (c *InfoClient) OutcomeTemplates(ctx context.Context) ([]OutcomeTemplate, error)

OutcomeTemplates returns the outcome templates.

func (*InfoClient) PerpAnnotation

func (c *InfoClient) PerpAnnotation(ctx context.Context, req PerpAnnotationRequest) (*PerpAnnotation, error)

PerpAnnotation returns a perpetual's annotation, or nil if it has none.

func (*InfoClient) PerpCategories

func (c *InfoClient) PerpCategories(ctx context.Context) (TupleMap[string, string], error)

PerpCategories returns the category ("crypto", "stocks", ...) of every categorized perpetual, keyed by coin.

func (*InfoClient) PerpConciseAnnotations

func (c *InfoClient) PerpConciseAnnotations(ctx context.Context) (TupleMap[string, PerpConciseAnnotation], error)

PerpConciseAnnotations returns the annotation of every annotated perpetual, keyed by coin.

func (*InfoClient) PerpDeployAuctionStatus

func (c *InfoClient) PerpDeployAuctionStatus(ctx context.Context) (*AuctionStatus, error)

PerpDeployAuctionStatus returns the auction for deploying a perp dex asset.

func (*InfoClient) PerpDexLimits

func (c *InfoClient) PerpDexLimits(ctx context.Context, req PerpDexLimitsRequest) (*PerpDexLimits, error)

PerpDexLimits returns the limits of a builder dex, or nil for the main dex and unknown dexes.

func (*InfoClient) PerpDexStatus

func (c *InfoClient) PerpDexStatus(ctx context.Context, req PerpDexStatusRequest) (*PerpDexStatus, error)

PerpDexStatus returns the state of a perp dex.

func (*InfoClient) PerpDexs

func (c *InfoClient) PerpDexs(ctx context.Context) ([]*PerpDex, error)

PerpDexs returns all perp dexes. Element 0 is nil and stands for the main dex; a builder dex's index is used in its asset IDs (see Markets).

func (*InfoClient) PerpsAtOpenInterestCap

func (c *InfoClient) PerpsAtOpenInterestCap(ctx context.Context, req PerpsAtOpenInterestCapRequest) ([]string, error)

PerpsAtOpenInterestCap returns the coins whose open interest is at its cap.

func (*InfoClient) Portfolio

func (c *InfoClient) Portfolio(ctx context.Context, req PortfolioRequest) (Portfolio, error)

Portfolio returns a user's account value and PnL history.

func (*InfoClient) PreTransferCheck

func (c *InfoClient) PreTransferCheck(ctx context.Context, req PreTransferCheckRequest) (*PreTransferCheck, error)

PreTransferCheck checks a transfer destination before sending to it.

func (*InfoClient) PredictedFundings

func (c *InfoClient) PredictedFundings(ctx context.Context) (TupleMap[string, TupleMap[string, *PredictedFunding]], error)

PredictedFundings returns predicted funding rates keyed by coin, then by venue ("HlPerp", "BinPerp", "BybitPerp", ...). A nil value means the venue has no prediction for the coin.

func (*InfoClient) RecentTrades

func (c *InfoClient) RecentTrades(ctx context.Context, req RecentTradesRequest) ([]Trade, error)

RecentTrades returns the most recent trades of a coin.

func (*InfoClient) Referral

func (c *InfoClient) Referral(ctx context.Context, req ReferralRequest) (*Referral, error)

Referral returns a user's referral status and rewards.

func (*InfoClient) SettledOutcome

func (c *InfoClient) SettledOutcome(ctx context.Context, req SettledOutcomeRequest) (*SettledOutcome, error)

SettledOutcome returns the settlement of an outcome, or nil if it has not settled.

func (*InfoClient) SpotClearinghouseState

func (c *InfoClient) SpotClearinghouseState(ctx context.Context, req SpotClearinghouseStateRequest) (*SpotClearinghouseState, error)

SpotClearinghouseState returns a user's spot balances.

func (*InfoClient) SpotDeployState

func (c *InfoClient) SpotDeployState(ctx context.Context, req SpotDeployStateRequest) (*SpotDeployState, error)

SpotDeployState returns a user's spot deployment state and the current token deploy auction.

func (*InfoClient) SpotMeta

func (c *InfoClient) SpotMeta(ctx context.Context) (*SpotMeta, error)

SpotMeta returns spot metadata.

func (*InfoClient) SpotMetaAndAssetCtxs

func (c *InfoClient) SpotMetaAndAssetCtxs(ctx context.Context) (*SpotMetaAndAssetCtxs, error)

SpotMetaAndAssetCtxs returns spot metadata and asset contexts.

func (*InfoClient) SpotPairDeployAuctionStatus

func (c *InfoClient) SpotPairDeployAuctionStatus(ctx context.Context) (*AuctionStatus, error)

SpotPairDeployAuctionStatus returns the auction for deploying a spot pair.

func (*InfoClient) SubAccounts

func (c *InfoClient) SubAccounts(ctx context.Context, req SubAccountsRequest) ([]SubAccount, error)

SubAccounts returns a master account's sub-accounts.

func (*InfoClient) SubAccounts2

func (c *InfoClient) SubAccounts2(ctx context.Context, req SubAccounts2Request) ([]SubAccount2, error)

SubAccounts2 returns a master account's sub-accounts with their state on every perp dex.

func (*InfoClient) TokenDetails

func (c *InfoClient) TokenDetails(ctx context.Context, req TokenDetailsRequest) (*TokenDetails, error)

TokenDetails returns details of a spot token.

func (*InfoClient) TwapHistory

func (c *InfoClient) TwapHistory(ctx context.Context, req TwapHistoryRequest) ([]TwapHistoryEntry, error)

TwapHistory returns a user's TWAP history.

func (*InfoClient) TxDetails

func (c *InfoClient) TxDetails(ctx context.Context, req TxDetailsRequest) (*ExplorerTx, error)

TxDetails returns a transaction from the explorer.

func (*InfoClient) USDCRouting

func (c *InfoClient) USDCRouting(ctx context.Context) (*USDCRouting, error)

USDCRouting returns the current USDC deposit and withdrawal routes.

func (*InfoClient) UserAbstraction

func (c *InfoClient) UserAbstraction(ctx context.Context, req UserAbstractionRequest) (Abstraction, error)

UserAbstraction returns a user's account abstraction mode.

func (*InfoClient) UserBorrowLendInterest

func (c *InfoClient) UserBorrowLendInterest(ctx context.Context, req UserBorrowLendInterestRequest) ([]BorrowLendInterest, error)

UserBorrowLendInterest returns the interest a user paid and earned.

func (*InfoClient) UserDetails

func (c *InfoClient) UserDetails(ctx context.Context, req UserDetailsRequest) ([]ExplorerTx, error)

UserDetails returns a user's recent transactions from the explorer.

func (*InfoClient) UserDexAbstraction

func (c *InfoClient) UserDexAbstraction(ctx context.Context, req UserDexAbstractionRequest) (bool, error)

UserDexAbstraction reports whether a user has enabled dex abstraction, which lets builder perp dexes use the main dex's collateral.

func (*InfoClient) UserFees

func (c *InfoClient) UserFees(ctx context.Context, req UserFeesRequest) (*UserFees, error)

UserFees returns a user's fee rates and volume history.

func (*InfoClient) UserFills

func (c *InfoClient) UserFills(ctx context.Context, req UserFillsRequest) ([]UserFill, error)

UserFills returns up to 2000 of a user's most recent fills.

func (*InfoClient) UserFillsByTime

func (c *InfoClient) UserFillsByTime(ctx context.Context, req UserFillsByTimeRequest) ([]UserFill, error)

UserFillsByTime returns up to 2000 of a user's fills in a time range.

func (*InfoClient) UserFunding

func (c *InfoClient) UserFunding(ctx context.Context, req UserFundingRequest) ([]FundingUpdate, error)

UserFunding returns a user's funding payments.

func (*InfoClient) UserNonFundingLedgerUpdates

func (c *InfoClient) UserNonFundingLedgerUpdates(ctx context.Context, req UserNonFundingLedgerUpdatesRequest) ([]LedgerUpdate, error)

UserNonFundingLedgerUpdates returns a user's deposits, withdrawals, transfers, liquidations and other non-funding balance changes.

func (*InfoClient) UserRateLimit

func (c *InfoClient) UserRateLimit(ctx context.Context, req UserRateLimitRequest) (*RateLimit, error)

UserRateLimit returns a user's action rate limit usage.

func (*InfoClient) UserRole

func (c *InfoClient) UserRole(ctx context.Context, req UserRoleRequest) (*UserRole, error)

UserRole returns whether an address is a user, vault, agent or sub-account.

func (*InfoClient) UserToMultiSigSigners

func (c *InfoClient) UserToMultiSigSigners(ctx context.Context, req UserToMultiSigSignersRequest) (*MultiSigSigners, error)

UserToMultiSigSigners returns the signers of a multi-sig user, or nil if the user is not multi-sig.

func (*InfoClient) UserTwapSliceFills

func (c *InfoClient) UserTwapSliceFills(ctx context.Context, req UserTwapSliceFillsRequest) ([]TwapSliceFill, error)

UserTwapSliceFills returns up to 2000 of a user's most recent TWAP slice fills.

func (*InfoClient) UserTwapSliceFillsByTime

func (c *InfoClient) UserTwapSliceFillsByTime(ctx context.Context, req UserTwapSliceFillsByTimeRequest) ([]TwapSliceFill, error)

UserTwapSliceFillsByTime returns a user's TWAP slice fills in a time range.

func (*InfoClient) UserVaultEquities

func (c *InfoClient) UserVaultEquities(ctx context.Context, req UserVaultEquitiesRequest) ([]VaultEquity, error)

UserVaultEquities returns the vaults a user has deposited into.

func (*InfoClient) ValidatorL1Votes

func (c *InfoClient) ValidatorL1Votes(ctx context.Context) ([]ValidatorL1Vote, error)

ValidatorL1Votes returns the pending validator L1 votes.

func (*InfoClient) ValidatorSummaries

func (c *InfoClient) ValidatorSummaries(ctx context.Context) ([]ValidatorSummary, error)

ValidatorSummaries returns all validators.

func (*InfoClient) VaultDetails

func (c *InfoClient) VaultDetails(ctx context.Context, req VaultDetailsRequest) (*VaultDetails, error)

VaultDetails returns a vault's details, or nil if it does not exist.

func (*InfoClient) VaultSummaries

func (c *InfoClient) VaultSummaries(ctx context.Context) ([]VaultSummary, error)

VaultSummaries returns summaries of vaults.

func (*InfoClient) WebData2

func (c *InfoClient) WebData2(ctx context.Context, req WebData2Request) (*WebData2, error)

WebData2 returns a user's account together with main-dex market data.

type InsertMarginTable

type InsertMarginTable struct {
	Dex         string          `json:"dex"`
	MarginTable MarginTableSpec `json:"marginTable"`
}

InsertMarginTable adds a margin table to a dex.

type IsVIPRequest

type IsVIPRequest struct {
	User Address `json:"user"`
}

IsVIPRequest is the request for InfoClient.IsVIP.

type IsolatedPositionIndex

type IsolatedPositionIndex struct {
	Asset int `json:"asset"`
}

IsolatedPositionIndex locates an isolated-margin position.

type L2Book

type L2Book struct {
	Coin string `json:"coin"`
	// Time is the snapshot time in milliseconds since the Unix epoch.
	Time int64 `json:"time"`
	// Levels holds the bids (Levels[0]) and asks (Levels[1]), best first.
	Levels [2][]L2Level `json:"levels"`
	// Spread is set only when NSigFigs was requested.
	Spread *Decimal `json:"spread,omitempty"`
	// Fast is set on snapshots from a WebSocket subscription in fast mode.
	Fast bool `json:"fast,omitempty"`
}

L2Book is an order book snapshot.

type L2BookRequest

type L2BookRequest struct {
	Coin string `json:"coin"`
	// NSigFigs aggregates levels to 2-5 significant figures; nil means full
	// precision.
	NSigFigs *int `json:"nSigFigs,omitempty"`
	// Mantissa (2 or 5) further aggregates levels when NSigFigs is 5.
	Mantissa *int `json:"mantissa,omitempty"`
}

L2BookRequest is the request for InfoClient.L2Book.

type L2BookSubscription

type L2BookSubscription struct {
	Coin string `json:"coin"`
	// NSigFigs aggregates levels to 2-5 significant figures; nil means full
	// precision.
	NSigFigs *int `json:"nSigFigs"`
	// Mantissa (2 or 5) further aggregates levels when NSigFigs is 5.
	Mantissa *int `json:"mantissa"`
	// Fast streams 5 levels per side every 0.5 seconds instead of 20 levels
	// every 5 seconds.
	Fast bool `json:"fast,omitempty"`
}

L2BookSubscription is the request of WebSocketClient.L2Book.

type L2Level

type L2Level struct {
	Px Decimal `json:"px"`
	Sz Decimal `json:"sz"`
	// N is the number of orders at this level.
	N int `json:"n"`
}

L2Level is an aggregated price level.

type LeadingVault

type LeadingVault struct {
	Address Address `json:"address"`
	Name    string  `json:"name"`
}

LeadingVault is a vault led by a user.

type LeadingVaultsRequest

type LeadingVaultsRequest struct {
	User Address `json:"user"`
}

LeadingVaultsRequest is the request for InfoClient.LeadingVaults.

type LedgerDelta

type LedgerDelta struct {
	Type        string  `json:"type"`
	USDC        Decimal `json:"usdc,omitempty"`
	ToPerp      bool    `json:"toPerp,omitempty"`
	User        Address `json:"user,omitzero"`
	Destination Address `json:"destination,omitzero"`
	Fee         Decimal `json:"fee,omitempty"`
	// SourceDex and DestinationDex are "" for the main perp dex and "spot"
	// for the spot account.
	SourceDex           string               `json:"sourceDex,omitempty"`
	DestinationDex      string               `json:"destinationDex,omitempty"`
	Dex                 string               `json:"dex,omitempty"`
	Token               string               `json:"token,omitempty"`
	Amount              Decimal              `json:"amount,omitempty"`
	USDCValue           Decimal              `json:"usdcValue,omitempty"`
	NativeTokenFee      Decimal              `json:"nativeTokenFee,omitempty"`
	Nonce               int64                `json:"nonce,omitempty"`
	FeeToken            string               `json:"feeToken,omitempty"`
	LiquidatedNtlPos    Decimal              `json:"liquidatedNtlPos,omitempty"`
	AccountValue        Decimal              `json:"accountValue,omitempty"`
	LeverageType        string               `json:"leverageType,omitempty"` // "Cross" or "Isolated"
	LiquidatedPositions []LiquidatedPosition `json:"liquidatedPositions,omitempty"`
	Vault               Address              `json:"vault,omitzero"`
	RequestedUSD        Decimal              `json:"requestedUsd,omitempty"`
	Commission          Decimal              `json:"commission,omitempty"`
	ClosingCost         Decimal              `json:"closingCost,omitempty"`
	Basis               Decimal              `json:"basis,omitempty"`
	NetWithdrawnUSD     Decimal              `json:"netWithdrawnUsd,omitempty"`
	IsDeposit           bool                 `json:"isDeposit,omitempty"`
	// Operation is "supply", "withdraw", "repay" or "borrow".
	Operation      string  `json:"operation,omitempty"`
	InterestAmount Decimal `json:"interestAmount,omitempty"`
}

LedgerDelta is the content of a LedgerUpdate. Type names the variant and selects which other fields are set:

  • "accountClassTransfer": USDC, ToPerp
  • "deposit": USDC
  • "internalTransfer": USDC, User, Destination, Fee
  • "liquidation": LiquidatedNtlPos, AccountValue, LeverageType, LiquidatedPositions
  • "rewardsClaim": Amount, Token
  • "spotTransfer": Token, Amount, USDCValue, User, Destination, Fee, NativeTokenFee, Nonce, FeeToken
  • "subAccountTransfer": USDC, User, Destination
  • "vaultCreate": Vault, USDC, Fee
  • "vaultDeposit", "vaultDistribution": Vault, USDC
  • "vaultWithdraw": Vault, User, RequestedUSD, Commission, ClosingCost, Basis, NetWithdrawnUSD
  • "withdraw": USDC, Nonce, Fee
  • "send": User, Destination, SourceDex, DestinationDex, Token, Amount, USDCValue, Fee, NativeTokenFee, Nonce, FeeToken
  • "deployGasAuction", "spotGenesis": Token, Amount
  • "cStakingTransfer": Token, Amount, IsDeposit
  • "borrowLend": Token, Operation, Amount, InterestAmount
  • "activateDexAbstraction": Dex, Token, Amount
  • "vaultLeaderCommission": User, USDC

type LedgerUpdate

type LedgerUpdate struct {
	// Time is in milliseconds since the Unix epoch.
	Time  int64       `json:"time"`
	Hash  string      `json:"hash"`
	Delta LedgerDelta `json:"delta"`
}

LedgerUpdate is a non-funding change to a user's balances.

type LegalCheck

type LegalCheck struct {
	AcceptedTerms bool `json:"acceptedTerms"`
	UserAllowed   bool `json:"userAllowed"`
	// Restrictions is an undocumented one-letter code: "n", "a", "o" or
	// "u".
	Restrictions string `json:"restrictions"`
}

LegalCheck is a user's terms acceptance and jurisdiction status.

type LegalCheckRequest

type LegalCheckRequest struct {
	User Address `json:"user"`
}

LegalCheckRequest is the request for InfoClient.LegalCheck.

type Leverage

type Leverage struct {
	// Type is "cross" or "isolated".
	Type  string `json:"type"`
	Value int    `json:"value"`
	// RawUSD is the isolated margin's raw USD value; empty for cross.
	RawUSD Decimal `json:"rawUsd,omitempty"`
}

Leverage is a position's margin mode and leverage.

type LimitOrder

type LimitOrder struct {
	Tif Tif `json:"tif"`
}

LimitOrder is a limit order type.

type LinkStakingUserAction

type LinkStakingUserAction struct {
	User       Address `json:"user"`
	IsFinalize bool    `json:"isFinalize"`
}

LinkStakingUserAction links a trading account to a staking account so the trading account gets the staking account's fee discount. The trading account sends it first naming the staking account, then the staking account finalizes it naming the trading account. It must be signed by the account's own key.

type LiquidatablePosition

type LiquidatablePosition struct {
	User          Address       `json:"user"`
	PositionIndex PositionIndex `json:"positionIndex"`
	// MarginAvailable holds two margin figures whose meaning is undocumented.
	MarginAvailable [2]Decimal `json:"marginAvailable"`
}

LiquidatablePosition is a position eligible for liquidation.

type LiquidatedPosition

type LiquidatedPosition struct {
	Coin string  `json:"coin"`
	Szi  Decimal `json:"szi"`
}

LiquidatedPosition is a position closed by a liquidation.

type LiquidationEvent

type LiquidationEvent struct {
	// Lid is the liquidation ID.
	Lid                    int64   `json:"lid"`
	Liquidator             Address `json:"liquidator"`
	LiquidatedUser         Address `json:"liquidated_user"`
	LiquidatedNtlPos       Decimal `json:"liquidated_ntl_pos"`
	LiquidatedAccountValue Decimal `json:"liquidated_account_value"`
}

LiquidationEvent is a liquidation that involves the user.

type MMFeeTier

type MMFeeTier struct {
	MakerFractionCutoff Decimal `json:"makerFractionCutoff"`
	// Add is the maker rate; negative is a rebate.
	Add Decimal `json:"add"`
}

MMFeeTier is a maker rebate tier reached by share of maker volume.

type MarginMode

type MarginMode string

MarginMode restricts how an asset can be margined.

const (
	MarginModeNormal MarginMode = "normal"
	// MarginModeStrictIsolated allows isolated margin only, and margin
	// cannot be removed from open positions.
	MarginModeStrictIsolated MarginMode = "strictIsolated"
	// MarginModeNoCross allows isolated margin only.
	MarginModeNoCross MarginMode = "noCross"
)

Margin modes.

type MarginSummary

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

MarginSummary aggregates account value and margin usage.

type MarginTable

type MarginTable struct {
	Description string       `json:"description"`
	MarginTiers []MarginTier `json:"marginTiers"`
}

MarginTable defines leverage tiers by position notional.

type MarginTableRequest

type MarginTableRequest struct {
	ID int `json:"id"`
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

MarginTableRequest is the request for InfoClient.MarginTable.

type MarginTableSpec

type MarginTableSpec struct {
	Description string `json:"description"`
	// MarginTiers lists at most 3 tiers by increasing lower bound and
	// decreasing max leverage.
	MarginTiers []MarginTierSpec `json:"marginTiers"`
}

MarginTableSpec is a margin table to insert with InsertMarginTable.

type MarginTier

type MarginTier struct {
	LowerBound  Decimal `json:"lowerBound"`
	MaxLeverage int     `json:"maxLeverage"`
}

MarginTier is one tier of a MarginTable.

type MarginTierSpec

type MarginTierSpec struct {
	// LowerBound is the position notional above which MaxLeverage applies.
	LowerBound  uint64 `json:"lowerBound"`
	MaxLeverage int    `json:"maxLeverage"`
}

MarginTierSpec is a tier of a MarginTableSpec.

type Markets

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

Markets resolves market names to [Asset]s. Build it with LoadMarkets; it is a snapshot and is safe for concurrent reads.

func LoadMarkets

func LoadMarkets(ctx context.Context, c *InfoClient) (*Markets, error)

LoadMarkets fetches the perp, builder dex and spot metadata and indexes every market.

func (*Markets) Asset

func (m *Markets) Asset(name string) (Asset, bool)

Asset looks up a market by name: a perp ("BTC"), a builder-dex perp ("xyz:TSLA"), a spot pair ("PURR/USDC") or a spot pair's coin alias ("@107").

type MaxBuilderFeeRequest

type MaxBuilderFeeRequest struct {
	User    Address `json:"user"`
	Builder Address `json:"builder"`
}

MaxBuilderFeeRequest is the request for InfoClient.MaxBuilderFee.

type MergeOutcome

type MergeOutcome struct {
	Outcome int `json:"outcome"`
	// Amount is the number of share pairs; nil merges the maximum.
	Amount *Decimal `json:"amount"`
}

MergeOutcome merges Yes and No shares of an outcome back into quote tokens.

type MergeQuestion

type MergeQuestion struct {
	Question int `json:"question"`
	// Amount is the number of share sets; nil merges the maximum.
	Amount *Decimal `json:"amount"`
}

MergeQuestion merges Yes shares of every outcome of a question into quote tokens.

type Meta

type Meta struct {
	// Universe lists the perpetual assets. An asset's index in Universe is
	// its asset ID on the main dex; see [Markets] for builder dexes.
	Universe []PerpAssetMeta `json:"universe"`
	// MarginTables maps margin table IDs, referenced by
	// [PerpAssetMeta.MarginTableID], to their tables.
	MarginTables TupleMap[int, MarginTable] `json:"marginTables"`
	// CollateralToken is the spot token index of the dex's collateral.
	CollateralToken int `json:"collateralToken"`
}

Meta describes the perpetual markets of a dex.

type MetaAndAssetCtxs

type MetaAndAssetCtxs struct {
	Meta Meta
	// AssetCtxs is parallel to Meta.Universe.
	AssetCtxs []PerpAssetCtx
}

MetaAndAssetCtxs is perpetual metadata with the market state of each asset.

func (*MetaAndAssetCtxs) UnmarshalJSON

func (m *MetaAndAssetCtxs) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the wire form [meta, assetCtxs].

type MetaAndAssetCtxsRequest

type MetaAndAssetCtxsRequest struct {
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

MetaAndAssetCtxsRequest is the request for InfoClient.MetaAndAssetCtxs.

type MetaRequest

type MetaRequest struct {
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

MetaRequest is the request for InfoClient.Meta.

type Modify

type Modify struct {
	Oid   OrderRef `json:"oid"`
	Order Order    `json:"order"`
}

Modify is one replacement of a BatchModifyAction.

type ModifyAction

type ModifyAction struct {
	Oid   OrderRef `json:"oid"`
	Order Order    `json:"order"`
	// AlwaysPlace places the new order even if canceling the old one fails.
	// Otherwise the new order must be a non-trigger ALO order or a
	// non-marketable GTC order.
	AlwaysPlace bool `json:"a,omitempty"`
}

ModifyAction replaces a resting order with a new one.

type MultiSigSigners

type MultiSigSigners struct {
	AuthorizedUsers []Address `json:"authorizedUsers"`
	// Threshold is the number of signatures an action needs, 1 to 10.
	Threshold int `json:"threshold"`
}

MultiSigSigners is the signer set of a multi-sig account.

type NegateOutcome

type NegateOutcome struct {
	Question int     `json:"question"`
	Outcome  int     `json:"outcome"`
	Amount   Decimal `json:"amount"`
}

NegateOutcome converts No shares of an outcome into Yes shares of every other outcome of its question.

type Network

type Network struct {
	// APIURL is the HTTP API base URL, e.g. "https://api.hyperliquid.xyz".
	APIURL string
	// WebSocketURL is the WebSocket API URL, e.g. "wss://api.hyperliquid.xyz/ws".
	WebSocketURL string
	// RPCURL is the base URL of the explorer RPC, e.g. "https://rpc.hyperliquid.xyz".
	RPCURL string
	// Mainnet selects mainnet signatures. Signatures made for one network
	// are rejected by the other.
	Mainnet bool
}

Network identifies a Hyperliquid deployment.

type NodeIP

type NodeIP struct {
	IP string `json:"Ip"`
}

NodeIP is a validator node's IP address.

type NonUserCancel

type NonUserCancel struct {
	Coin string `json:"coin"`
	Oid  int64  `json:"oid"`
}

NonUserCancel is an order canceled by the exchange rather than the user.

type NoopAction

type NoopAction struct{}

NoopAction does nothing; submitting it consumes its nonce.

type NotificationEvent

type NotificationEvent struct {
	Notification string `json:"notification"`
}

NotificationEvent is a message of WebSocketClient.Notification.

type NotificationSubscription

type NotificationSubscription struct {
	User Address `json:"user"`
}

NotificationSubscription is the request of WebSocketClient.Notification.

type OpenOrder

type OpenOrder struct {
	Coin    string  `json:"coin"`
	Side    Side    `json:"side"`
	LimitPx Decimal `json:"limitPx"`
	// Sz is the remaining size; OrigSz the size when placed.
	Sz  Decimal `json:"sz"`
	Oid int64   `json:"oid"`
	// Timestamp is the placement time in milliseconds since the Unix epoch.
	Timestamp  int64   `json:"timestamp"`
	OrigSz     Decimal `json:"origSz"`
	Cloid      *Cloid  `json:"cloid,omitempty"`
	ReduceOnly bool    `json:"reduceOnly,omitempty"`
}

OpenOrder is a resting order.

type OpenOrdersEvent

type OpenOrdersEvent struct {
	Dex    string              `json:"dex"`
	User   Address             `json:"user"`
	Orders []FrontendOpenOrder `json:"orders"`
}

OpenOrdersEvent is a message of WebSocketClient.OpenOrders.

type OpenOrdersRequest

type OpenOrdersRequest struct {
	User Address `json:"user"`
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

OpenOrdersRequest is the request for InfoClient.OpenOrders.

type OpenOrdersSubscription

type OpenOrdersSubscription struct {
	User Address `json:"user"`
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex"`
}

OpenOrdersSubscription is the request of WebSocketClient.OpenOrders.

type Option

type Option func(*options)

Option configures an InfoClient or ExchangeClient.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the HTTP client used for requests. The default client has a 10 second timeout.

func WithWebSocket

func WithWebSocket(ws *WebSocketClient) Option

WithWebSocket sends the requests of an InfoClient or ExchangeClient as WebSocket post requests over ws instead of HTTP. Explorer requests still use HTTP. Closing ws fails later requests with ErrWebSocketClosed.

type Order

type Order struct {
	// Asset is the asset ID: the index in [Meta] universe for perps,
	// 10000 + spot pair index for spot, and 100000 + 10000*dexIndex + index
	// for builder-deployed perp dexes.
	Asset int  `json:"a"`
	IsBuy bool `json:"b"`
	// Price is the limit price. Round it with [FormatPrice].
	Price Decimal `json:"p"`
	// Size is in base units. Round it with [FormatSize].
	Size       Decimal   `json:"s"`
	ReduceOnly bool      `json:"r"`
	Type       OrderType `json:"t"`
	// Cloid is an optional client order ID.
	Cloid *Cloid `json:"c,omitempty"`
}

Order is a single order of an OrderAction.

type OrderAction

type OrderAction struct {
	Orders []Order `json:"orders"`
	// Grouping links the orders; the zero value is [GroupingNA].
	Grouping Grouping `json:"grouping"`
	// Builder optionally pays a builder fee on the orders.
	Builder *Builder `json:"builder,omitempty"`
}

OrderAction places one or more orders.

type OrderProcessingStatus

type OrderProcessingStatus string

OrderProcessingStatus is the lifecycle status of an order: "open", "filled", "canceled", "triggered", "rejected", or a specific cancel or reject reason such as "marginCanceled", "selfTradeCanceled", "reduceOnlyCanceled", "scheduledCancel", "tickRejected" or "perpMarginRejected".

type OrderRef

type OrderRef struct {
	Oid   int64
	Cloid *Cloid
}

OrderRef identifies an order by exchange order ID or, when Cloid is set, by client order ID.

func (OrderRef) MarshalJSON

func (r OrderRef) MarshalJSON() ([]byte, error)

MarshalJSON encodes r as the order ID number or the client order ID string.

type OrderResult

type OrderResult struct {
	Resting *RestingOrder `json:"resting,omitempty"`
	Filled  *FilledOrder  `json:"filled,omitempty"`
	Error   string        `json:"error,omitempty"`
	// Status holds plain statuses such as "waitingForFill" and
	// "waitingForTrigger".
	Status string `json:"-"`
}

OrderResult is the outcome of one order. Exactly one of Resting, Filled, Error and Status is set.

func (*OrderResult) UnmarshalJSON

func (s *OrderResult) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts both object statuses and plain string statuses.

type OrderStatusRequest

type OrderStatusRequest struct {
	User Address `json:"user"`
	// Oid selects the order by ID or client order ID.
	Oid OrderRef `json:"oid"`
}

OrderStatusRequest is the request for InfoClient.OrderStatus.

type OrderType

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

OrderType is either a limit or a trigger order; set exactly one field.

type OrderUpdate

type OrderUpdate struct {
	Order  OpenOrder             `json:"order"`
	Status OrderProcessingStatus `json:"status"`
	// StatusTimestamp is in milliseconds since the Unix epoch.
	StatusTimestamp int64 `json:"statusTimestamp"`
}

OrderUpdate is a message item of WebSocketClient.OrderUpdates.

type OrderUpdatesSubscription

type OrderUpdatesSubscription struct {
	User Address `json:"user"`
}

OrderUpdatesSubscription is the request of WebSocketClient.OrderUpdates.

type OrderWithStatus

type OrderWithStatus struct {
	Order  FrontendOpenOrder     `json:"order"`
	Status OrderProcessingStatus `json:"status"`
	// StatusTimestamp is in milliseconds since the Unix epoch.
	StatusTimestamp int64 `json:"statusTimestamp"`
}

OrderWithStatus is an order with its latest status.

type OutcomeDeployAction

type OutcomeDeployAction struct {
	// Venue is the deployer's venue name; sub-deployers pass the venue they
	// act for.
	Venue     string           `json:"venue"`
	Operation OutcomeOperation `json:"operation"`
}

OutcomeDeployAction deploys or settles HIP-4 outcomes on a venue.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions.

type OutcomeDeployer

type OutcomeDeployer struct {
	Deployer Address `json:"deployer"`
	Venue    string  `json:"venue"`
	// SubDeployers maps function names, such as "settleOutcome", to the
	// addresses allowed to call them on the deployer's behalf.
	SubDeployers TupleMap[string, []Address] `json:"subDeployers"`
}

OutcomeDeployer is an outcome market deployer.

type OutcomeDeployerActivation

type OutcomeDeployerActivation struct {
	// VenueName is 2-4 lowercase letters, unique across venues and perp
	// dexes.
	VenueName string `json:"venueName"`
}

OutcomeDeployerActivation claims an outcome deployer's venue.

type OutcomeMeta

type OutcomeMeta struct {
	Outcomes  []OutcomeSpec     `json:"outcomes"`
	Questions []OutcomeQuestion `json:"questions"`
	Deployers []OutcomeDeployer `json:"deployers"`
	// FeeScale scales the trading fees of outcome markets.
	FeeScale Decimal `json:"feeScale"`
}

OutcomeMeta describes the HIP-4 outcome (prediction) markets.

type OutcomeMetaUpdate

type OutcomeMetaUpdate struct {
	OutcomeCreated  *OutcomeSpec     `json:"outcomeCreated,omitempty"`
	OutcomeSettled  *OutcomeSettled  `json:"outcomeSettled,omitempty"`
	QuestionUpdated *OutcomeQuestion `json:"questionUpdated,omitempty"`
	QuestionSettled *QuestionSettled `json:"questionSettled,omitempty"`
}

OutcomeMetaUpdate is a change to outcome market metadata. Exactly one field is set.

type OutcomeMetaUpdatesEvent

type OutcomeMetaUpdatesEvent struct {
	Updates []OutcomeMetaUpdate `json:"updates"`
}

OutcomeMetaUpdatesEvent is a message of WebSocketClient.OutcomeMetaUpdates.

type OutcomeOperation

type OutcomeOperation struct {
	// RegisterStandaloneOutcomeFromTemplate deploys a standalone yes/no
	// outcome; DeployerFeeScale is required.
	RegisterStandaloneOutcomeFromTemplate *OutcomeTemplateInstance `json:"registerStandaloneOutcomeFromTemplate,omitempty"`
	// RegisterQuestionFromTemplate deploys a question and its named
	// outcomes.
	RegisterQuestionFromTemplate *RegisterQuestionFromTemplate `json:"registerQuestionFromTemplate,omitempty"`
	// RegisterAndAssociateNamedOutcomeFromTemplate adds a named outcome to a
	// live question.
	RegisterAndAssociateNamedOutcomeFromTemplate *RegisterNamedOutcome `json:"registerAndAssociateNamedOutcomeFromTemplate,omitempty"`
	// SettleOutcome settles one outcome.
	SettleOutcome *OutcomeSettlement `json:"settleOutcome,omitempty"`
	// SettleQuestion2 settles the remaining named outcomes of a question.
	SettleQuestion2 *SettleQuestion `json:"settleQuestion2,omitempty"`
	// SetSubDeployers grants or revokes sub-deployer permissions; Variant is
	// an operation name, with "settleQuestion" covering SettleQuestion2.
	SetSubDeployers []SubDeployer `json:"setSubDeployers,omitempty"`
}

OutcomeOperation is the operation of an OutcomeDeployAction. Set exactly one field.

type OutcomeQuestion

type OutcomeQuestion struct {
	Question    int    `json:"question"`
	Name        string `json:"name"`
	Description string `json:"description"`
	// FallbackOutcome settles to Yes when no named outcome does.
	FallbackOutcome      int   `json:"fallbackOutcome"`
	NamedOutcomes        []int `json:"namedOutcomes"`
	SettledNamedOutcomes []int `json:"settledNamedOutcomes"`
}

OutcomeQuestion groups named outcomes, of which one settles to Yes.

type OutcomeSettled

type OutcomeSettled struct {
	Outcome int `json:"outcome"`
}

OutcomeSettled reports that an outcome settled.

type OutcomeSettlement

type OutcomeSettlement struct {
	Outcome int `json:"outcome"`
	// SettleFraction is the payout fraction of the yes side, between 0 and
	// 1; outcomes of a question settle to exactly 0 or 1.
	SettleFraction Decimal `json:"settleFraction"`
	// Details must be empty.
	Details string `json:"details"`
	// NameAndDescription and SideNames must match the outcome exactly.
	NameAndDescription [2]string `json:"nameAndDescription"`
	SideNames          [2]string `json:"sideNames"`
}

OutcomeSettlement settles an outcome.

type OutcomeSideSpec

type OutcomeSideSpec struct {
	Name string `json:"name"`
}

OutcomeSideSpec describes a side of an outcome, such as "Yes".

type OutcomeSpec

type OutcomeSpec struct {
	Outcome     int               `json:"outcome"`
	Name        string            `json:"name"`
	Description string            `json:"description"`
	SideSpecs   []OutcomeSideSpec `json:"sideSpecs"`
	// QuoteToken is the quote token name, such as "USDC".
	QuoteToken string `json:"quoteToken"`
	// Venue is the deployer's venue name, if any.
	Venue            string  `json:"venue,omitempty"`
	DeployerFeeScale Decimal `json:"deployerFeeScale,omitempty"`
}

OutcomeSpec describes an outcome. Side i of outcome n trades as asset 100000000 + 10*n + i.

type OutcomeTemplate

type OutcomeTemplate struct {
	ID          string              `json:"id"`
	Role        OutcomeTemplateRole `json:"role"`
	Name        string              `json:"name"`
	Description string              `json:"description"`
	// Keywords maps placeholder keywords to their value kind, such as
	// "string", "dateTime", "uDecimal" or "hlPerp".
	Keywords TupleMap[string, string] `json:"keywords"`
}

OutcomeTemplate is a template from which outcomes and questions are registered. Name and Description contain {keyword} placeholders.

type OutcomeTemplateInstance

type OutcomeTemplateInstance struct {
	ID string `json:"id"`
	// KeywordToValue maps each template keyword to its value.
	KeywordToValue TupleMap[string, string] `json:"keywordToValue"`
	// DeployerFeeScale, between 0 and 10, is required for standalone
	// outcomes and questions and must be empty for named outcomes. Users
	// pay the base fee times DeployerFeeScale + max(DeployerFeeScale, 1),
	// of which the deployer receives DeployerFeeScale.
	DeployerFeeScale Decimal `json:"deployerFeeScale,omitempty"`
}

OutcomeTemplateInstance instantiates an outcome or question template.

type OutcomeTemplateRole

type OutcomeTemplateRole struct {
	Question          bool                   `json:"-"`
	StandaloneOutcome *StandaloneOutcomeRole `json:"standaloneOutcome,omitempty"`
	QuestionOutcome   *QuestionOutcomeRole   `json:"questionOutcome,omitempty"`
}

OutcomeTemplateRole is what a template registers: a question, a standalone outcome, or an outcome of a question. Exactly one field is set.

func (*OutcomeTemplateRole) UnmarshalJSON

func (r *OutcomeTemplateRole) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the string "question" or an object with one key.

type PerpAnnotation

type PerpAnnotation struct {
	Category    string `json:"category"`
	Description string `json:"description"`
	DisplayName string `json:"displayName,omitempty"`
	// Keywords are search terms.
	Keywords []string `json:"keywords,omitempty"`
}

PerpAnnotation is descriptive metadata of a perpetual.

type PerpAnnotationRequest

type PerpAnnotationRequest struct {
	Coin string `json:"coin"`
}

PerpAnnotationRequest is the request for InfoClient.PerpAnnotation.

type PerpAssetCtx

type PerpAssetCtx struct {
	PrevDayPx    Decimal  `json:"prevDayPx"`
	DayNtlVlm    Decimal  `json:"dayNtlVlm"`
	MarkPx       Decimal  `json:"markPx"`
	MidPx        *Decimal `json:"midPx"`
	Funding      Decimal  `json:"funding"`
	OpenInterest Decimal  `json:"openInterest"`
	Premium      *Decimal `json:"premium"`
	OraclePx     Decimal  `json:"oraclePx"`
	// ImpactPxs holds the bid and ask impact prices, or nil.
	ImpactPxs  *[2]Decimal `json:"impactPxs"`
	DayBaseVlm Decimal     `json:"dayBaseVlm"`
}

PerpAssetCtx is the live market state of a perpetual asset.

type PerpAssetMeta

type PerpAssetMeta struct {
	Name          string `json:"name"`
	SzDecimals    int    `json:"szDecimals"`
	MaxLeverage   int    `json:"maxLeverage"`
	MarginTableID int    `json:"marginTableId"`
	// OnlyIsolated is deprecated upstream in favor of MarginMode.
	OnlyIsolated bool `json:"onlyIsolated,omitempty"`
	IsDelisted   bool `json:"isDelisted,omitempty"`
	// MarginMode is "strictIsolated", "noCross" or empty.
	MarginMode string `json:"marginMode,omitempty"`
	// GrowthMode is "enabled" or empty.
	GrowthMode string `json:"growthMode,omitempty"`
	// DeployerFeeScale is the builder dex deployer's fee scale; empty on the
	// main dex.
	DeployerFeeScale Decimal `json:"deployerFeeScale,omitempty"`
	// LastFeeScaleChangeTime is an ISO 8601 time without zone, such as
	// "2025-11-23T17:37:10.033211662"; empty on the main dex.
	LastFeeScaleChangeTime string `json:"lastFeeScaleChangeTime,omitempty"`
}

PerpAssetMeta describes a perpetual asset.

type PerpAssetRequest

type PerpAssetRequest struct {
	Coin          string  `json:"coin"`
	SzDecimals    int     `json:"szDecimals"`
	OraclePx      Decimal `json:"oraclePx"`
	MarginTableID int     `json:"marginTableId"`
	OnlyIsolated  bool    `json:"onlyIsolated"`
}

PerpAssetRequest describes a new asset of a RegisterPerpAsset.

type PerpAssetRequest2

type PerpAssetRequest2 struct {
	Coin          string     `json:"coin"`
	SzDecimals    int        `json:"szDecimals"`
	OraclePx      Decimal    `json:"oraclePx"`
	MarginTableID int        `json:"marginTableId"`
	MarginMode    MarginMode `json:"marginMode"`
}

PerpAssetRequest2 describes a new asset of a RegisterPerpAsset2.

type PerpConciseAnnotation

type PerpConciseAnnotation struct {
	Category    string   `json:"category"`
	DisplayName string   `json:"displayName,omitempty"`
	Keywords    []string `json:"keywords,omitempty"`
}

PerpConciseAnnotation is a PerpAnnotation without the description.

type PerpDeployAction

type PerpDeployAction struct {
	// RegisterAsset registers an asset; superseded by RegisterAsset2.
	RegisterAsset *RegisterPerpAsset `json:"registerAsset,omitempty"`
	// RegisterAsset2 registers an asset, and the dex itself when Schema is set.
	RegisterAsset2 *RegisterPerpAsset2 `json:"registerAsset2,omitempty"`
	// SetOracle updates oracle and mark prices.
	SetOracle *SetOracle `json:"setOracle,omitempty"`
	// SetFundingMultipliers maps coins to funding multipliers between 0
	// and 10.
	SetFundingMultipliers TupleMap[string, Decimal] `json:"setFundingMultipliers,omitempty"`
	// SetFundingInterestRates maps coins to 8-hour funding interest rates
	// between -0.01 and 0.01.
	SetFundingInterestRates TupleMap[string, Decimal] `json:"setFundingInterestRates,omitempty"`
	// SetFundingClamps maps coins to 8-hour funding clamps between 0 and
	// 0.01, which bound how far funding can move from the average premium
	// toward the interest rate (default 0.0003).
	SetFundingClamps TupleMap[string, Decimal] `json:"setFundingClamps,omitempty"`
	// HaltTrading halts or resumes trading of an asset.
	HaltTrading *HaltTrading `json:"haltTrading,omitempty"`
	// SetMarginTableIDs maps coins to margin table IDs.
	SetMarginTableIDs TupleMap[string, int] `json:"setMarginTableIds,omitempty"`
	// InsertMarginTable adds a margin table to a dex.
	InsertMarginTable *InsertMarginTable `json:"insertMarginTable,omitempty"`
	// SetFeeRecipient sets the dex's fee recipient.
	SetFeeRecipient *SetFeeRecipient `json:"setFeeRecipient,omitempty"`
	// SetOpenInterestCaps maps coins to open interest caps, in quote
	// notional; nil removes an asset's custom cap.
	SetOpenInterestCaps TupleMap[string, *uint64] `json:"setOpenInterestCaps,omitempty"`
	// SetSubDeployers grants or revokes sub-deployer permissions.
	SetSubDeployers *SetSubDeployers `json:"setSubDeployers,omitempty"`
	// SetMarginModes maps coins to margin modes.
	SetMarginModes TupleMap[string, MarginMode] `json:"setMarginModes,omitempty"`
	// SetDeployerFees maps coins to deployer fee settings.
	SetDeployerFees TupleMap[string, DeployerFee] `json:"setDeployerFees,omitempty"`
	// SetPerpAnnotation sets an asset's display metadata.
	SetPerpAnnotation *SetPerpAnnotation `json:"setPerpAnnotation,omitempty"`
	// DisableDex names a dex to disable.
	DisableDex string `json:"disableDex,omitempty"`
}

PerpDeployAction deploys and manages HIP-3 perpetual dexes and assets. Set exactly one field. Only the dex deployer (or an authorized sub-deployer, see SetSubDeployers) may submit it.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-3-deployer-actions.

type PerpDex

type PerpDex struct {
	// Name prefixes the dex's coins, as in "xyz:TSLA".
	Name          string   `json:"name"`
	FullName      string   `json:"fullName"`
	Deployer      Address  `json:"deployer"`
	OracleUpdater *Address `json:"oracleUpdater"`
	FeeRecipient  *Address `json:"feeRecipient"`
	// AssetToStreamingOICap maps coins to their streaming open interest cap.
	AssetToStreamingOICap TupleMap[string, Decimal] `json:"assetToStreamingOiCap"`
	// SubDeployers maps delegated permissions to the addresses allowed to
	// use them on the deployer's behalf.
	SubDeployers               TupleMap[SubDeployerVariant, []Address] `json:"subDeployers"`
	AssetToFundingMultiplier   TupleMap[string, Decimal]               `json:"assetToFundingMultiplier"`
	AssetToFundingInterestRate TupleMap[string, Decimal]               `json:"assetToFundingInterestRate"`
	AssetToFundingClamp        TupleMap[string, Decimal]               `json:"assetToFundingClamp"`
}

PerpDex describes a builder-deployed (HIP-3) perp dex.

type PerpDexLimits

type PerpDexLimits struct {
	TotalOICap     Decimal `json:"totalOiCap"`
	OISzCapPerPerp Decimal `json:"oiSzCapPerPerp"`
	MaxTransferNtl Decimal `json:"maxTransferNtl"`
	// CoinToOICap maps coins to their open interest cap.
	CoinToOICap TupleMap[string, Decimal] `json:"coinToOiCap"`
}

PerpDexLimits are the open interest and transfer limits of a builder dex.

type PerpDexLimitsRequest

type PerpDexLimitsRequest struct {
	Dex string `json:"dex"`
}

PerpDexLimitsRequest is the request for InfoClient.PerpDexLimits.

type PerpDexSchema

type PerpDexSchema struct {
	FullName        string `json:"fullName"`
	CollateralToken int    `json:"collateralToken"`
	// OracleUpdater may update oracle prices; nil means the deployer.
	OracleUpdater *Address `json:"oracleUpdater"`
}

PerpDexSchema describes a new HIP-3 dex.

type PerpDexStatus

type PerpDexStatus struct {
	TotalNetDeposit Decimal `json:"totalNetDeposit"`
}

PerpDexStatus is the state of a perp dex.

type PerpDexStatusRequest

type PerpDexStatusRequest struct {
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex"`
}

PerpDexStatusRequest is the request for InfoClient.PerpDexStatus.

type PerpsAtOpenInterestCapRequest

type PerpsAtOpenInterestCapRequest struct {
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex,omitempty"`
}

PerpsAtOpenInterestCapRequest is the request for InfoClient.PerpsAtOpenInterestCap.

type Portfolio

type Portfolio = TupleMap[string, PortfolioHistory]

Portfolio is an account's history keyed by period: "day", "week", "month", "allTime", and their perpetuals-only counterparts "perpDay", "perpWeek", "perpMonth", "perpAllTime".

type PortfolioHistory

type PortfolioHistory struct {
	AccountValueHistory []TimeValue `json:"accountValueHistory"`
	PnlHistory          []TimeValue `json:"pnlHistory"`
	// Vlm is the traded volume over the period.
	Vlm Decimal `json:"vlm"`
}

PortfolioHistory is an account's value and PnL history over one period.

type PortfolioRequest

type PortfolioRequest struct {
	User Address `json:"user"`
}

PortfolioRequest is the request for InfoClient.Portfolio.

type Position

type Position struct {
	Coin string `json:"coin"`
	// Szi is the signed size: positive for long, negative for short.
	Szi            Decimal  `json:"szi"`
	Leverage       Leverage `json:"leverage"`
	EntryPx        Decimal  `json:"entryPx"`
	PositionValue  Decimal  `json:"positionValue"`
	UnrealizedPnl  Decimal  `json:"unrealizedPnl"`
	ReturnOnEquity Decimal  `json:"returnOnEquity"`
	// LiquidationPx is nil when the position cannot be liquidated.
	LiquidationPx *Decimal   `json:"liquidationPx"`
	MarginUsed    Decimal    `json:"marginUsed"`
	MaxLeverage   int        `json:"maxLeverage"`
	CumFunding    CumFunding `json:"cumFunding"`
}

Position is the state of an open perpetual position.

type PositionIndex

type PositionIndex struct {
	Isolated *IsolatedPositionIndex `json:"isolated,omitempty"`
}

PositionIndex locates a position. Only isolated positions have been observed.

type PreTransferCheck

type PreTransferCheck struct {
	// Fee is the fee to activate a new destination account.
	Fee           Decimal `json:"fee"`
	IsSanctioned  bool    `json:"isSanctioned"`
	UserExists    bool    `json:"userExists"`
	UserHasSentTx bool    `json:"userHasSentTx"`
}

PreTransferCheck describes the destination of a transfer.

type PreTransferCheckRequest

type PreTransferCheckRequest struct {
	// User is the transfer destination; Source the sender.
	User   Address `json:"user"`
	Source Address `json:"source"`
}

PreTransferCheckRequest is the request for InfoClient.PreTransferCheck.

type PredictedFunding

type PredictedFunding struct {
	FundingRate Decimal `json:"fundingRate"`
	// NextFundingTime is in milliseconds since the Unix epoch.
	NextFundingTime int64 `json:"nextFundingTime"`
	// FundingIntervalHours is 0 when the venue does not report it.
	FundingIntervalHours int `json:"fundingIntervalHours,omitempty"`
}

PredictedFunding is the next funding rate of a coin on one venue.

type PrivateKeySigner

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

PrivateKeySigner signs with an in-memory secp256k1 private key.

func NewPrivateKeySigner

func NewPrivateKeySigner(hexKey string) (*PrivateKeySigner, error)

NewPrivateKeySigner returns a signer for a 0x-prefixed (or bare) 64-character hex private key.

Example
package main

import (
	"fmt"
	"log"

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

func main() {
	signer, err := hyperliquid.NewPrivateKeySigner("0x0123456789012345678901234567890123456789012345678901234567890123")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(signer.Address())
}
Output:
0x14791697260e4c9a71f18484c9f997b308e59325

func (*PrivateKeySigner) Address

func (s *PrivateKeySigner) Address() Address

Address returns the signer's address.

func (*PrivateKeySigner) SignHash

func (s *PrivateKeySigner) SignHash(_ context.Context, hash [32]byte) (Signature, error)

SignHash signs hash with a deterministic (RFC 6979) signature.

type QuestionOutcomeRole

type QuestionOutcomeRole struct {
	// Parent is the ID of the question's template.
	Parent string `json:"parent"`
}

QuestionOutcomeRole is the role of a template for outcomes of a question.

type QuestionSettled

type QuestionSettled struct {
	Question int `json:"question"`
}

QuestionSettled reports that a question settled.

type QuestionStatus

type QuestionStatus struct {
	Active  *int `json:"active,omitempty"`
	Settled *int `json:"settled,omitempty"`
}

QuestionStatus is a question ID tagged with the question's state. Exactly one field is set.

type RateLimit

type RateLimit struct {
	CumVlm           Decimal `json:"cumVlm"`
	NRequestsUsed    int     `json:"nRequestsUsed"`
	NRequestsCap     int     `json:"nRequestsCap"`
	NRequestsSurplus int     `json:"nRequestsSurplus"`
}

RateLimit is a user's address-based action rate limit. The cap grows with traded volume.

type RecentTradesRequest

type RecentTradesRequest struct {
	Coin string `json:"coin"`
}

RecentTradesRequest is the request for InfoClient.RecentTrades.

type Referral

type Referral struct {
	// ReferredBy is the user's referrer, or nil.
	ReferredBy       *ReferredBy      `json:"referredBy"`
	CumVlm           Decimal          `json:"cumVlm"`
	UnclaimedRewards Decimal          `json:"unclaimedRewards"`
	ClaimedRewards   Decimal          `json:"claimedRewards"`
	BuilderRewards   Decimal          `json:"builderRewards"`
	ReferrerState    ReferrerState    `json:"referrerState"`
	RewardHistory    []ReferralReward `json:"rewardHistory"`
	// TokenToState breaks the rewards down by spot token index.
	TokenToState TupleMap[int, ReferralTokenState] `json:"tokenToState"`
}

Referral is a user's referral status and rewards.

type ReferralRequest

type ReferralRequest struct {
	User Address `json:"user"`
}

ReferralRequest is the request for InfoClient.Referral.

type ReferralReward

type ReferralReward struct {
	Earned      Decimal `json:"earned"`
	Vlm         Decimal `json:"vlm"`
	ReferralVlm Decimal `json:"referralVlm"`
	// Time is in milliseconds since the Unix epoch.
	Time int64 `json:"time"`
}

ReferralReward is a referral reward accrual.

type ReferralState

type ReferralState struct {
	CumVlm                       Decimal `json:"cumVlm"`
	CumRewardedFeesSinceReferred Decimal `json:"cumRewardedFeesSinceReferred"`
	CumFeesRewardedToReferrer    Decimal `json:"cumFeesRewardedToReferrer"`
	// TimeJoined is in milliseconds since the Unix epoch.
	TimeJoined   int64                                  `json:"timeJoined"`
	User         Address                                `json:"user"`
	TokenToState TupleMap[int, ReferralStateTokenState] `json:"tokenToState"`
}

ReferralState is a referred user as seen by the referrer.

type ReferralStateTokenState

type ReferralStateTokenState struct {
	CumVlm                       Decimal `json:"cumVlm"`
	CumRewardedFeesSinceReferred Decimal `json:"cumRewardedFeesSinceReferred"`
	CumFeesRewardedToReferrer    Decimal `json:"cumFeesRewardedToReferrer"`
}

ReferralStateTokenState is a ReferralState for one spot token.

type ReferralTokenState

type ReferralTokenState struct {
	CumVlm           Decimal `json:"cumVlm"`
	UnclaimedRewards Decimal `json:"unclaimedRewards"`
	ClaimedRewards   Decimal `json:"claimedRewards"`
	BuilderRewards   Decimal `json:"builderRewards"`
}

ReferralTokenState is a user's referral volume and rewards for one spot token.

type ReferredBy

type ReferredBy struct {
	Referrer Address `json:"referrer"`
	Code     string  `json:"code"`
}

ReferredBy is the referrer of a user.

type ReferrerData

type ReferrerData struct {
	Code           string          `json:"code,omitempty"`
	NReferrals     int             `json:"nReferrals,omitempty"`
	ReferralStates []ReferralState `json:"referralStates,omitempty"`
	// Required is the volume left to trade before creating a code.
	Required Decimal `json:"required,omitempty"`
}

ReferrerData holds Code, NReferrals and ReferralStates in the "ready" stage, and Required in the "needToTrade" stage.

type ReferrerState

type ReferrerState struct {
	// Stage is "ready", "needToCreateCode" or "needToTrade".
	Stage string `json:"stage"`
	// Data is set for the "ready" and "needToTrade" stages.
	Data *ReferrerData `json:"data,omitempty"`
}

ReferrerState is a user's progress as a referrer.

type RegisterHyperliquidity

type RegisterHyperliquidity struct {
	// Spot is the spot pair index, not the token index.
	Spot    int     `json:"spot"`
	StartPx Decimal `json:"startPx"`
	// OrderSz is the size of each order, in tokens (not wei).
	OrderSz Decimal `json:"orderSz"`
	NOrders int     `json:"nOrders"`
	// NSeededLevels is the number of levels to seed with USDC.
	NSeededLevels *int `json:"nSeededLevels,omitempty"`
}

RegisterHyperliquidity seeds a spot pair with the HIP-2 market maker.

type RegisterNamedOutcome

type RegisterNamedOutcome struct {
	Question                     int                     `json:"question"`
	NamedOutcomeTemplateInstance OutcomeTemplateInstance `json:"namedOutcomeTemplateInstance"`
}

RegisterNamedOutcome adds a named outcome to a live question.

type RegisterPerpAsset

type RegisterPerpAsset struct {
	// MaxGas is the most to pay in the deploy auction, in HYPE wei (1e-8);
	// nil pays the current auction price.
	MaxGas       *uint64          `json:"maxGas"`
	AssetRequest PerpAssetRequest `json:"assetRequest"`
	Dex          string           `json:"dex"`
	// Schema registers the dex itself with the first asset; nil otherwise.
	Schema *PerpDexSchema `json:"schema"`
}

RegisterPerpAsset is the legacy asset registration of a PerpDeployAction; prefer RegisterPerpAsset2.

type RegisterPerpAsset2

type RegisterPerpAsset2 struct {
	// MaxGas is the most to pay in the deploy auction, in HYPE wei (1e-8);
	// nil pays the current auction price.
	MaxGas       *uint64           `json:"maxGas"`
	AssetRequest PerpAssetRequest2 `json:"assetRequest"`
	Dex          string            `json:"dex"`
	// Schema registers the dex itself with the first asset; nil otherwise.
	Schema *PerpDexSchema `json:"schema"`
}

RegisterPerpAsset2 registers a perpetual asset on a HIP-3 dex.

type RegisterQuestionFromTemplate

type RegisterQuestionFromTemplate struct {
	QuestionTemplateInstance OutcomeTemplateInstance `json:"questionTemplateInstance"`
	// NamedOutcomeTemplateInstances holds at most 100 outcomes.
	NamedOutcomeTemplateInstances []OutcomeTemplateInstance `json:"namedOutcomeTemplateInstances"`
}

RegisterQuestionFromTemplate deploys a question and its named outcomes.

type RegisterReferrerAction

type RegisterReferrerAction struct {
	Code string `json:"code"`
}

RegisterReferrerAction registers a referral code for the account.

type RegisterSpot

type RegisterSpot struct {
	// Tokens are the base and quote token indices.
	Tokens [2]int `json:"tokens"`
}

RegisterSpot registers a spot pair.

type RegisterToken2

type RegisterToken2 struct {
	Spec TokenSpec `json:"spec"`
	// MaxGas is the most to pay in the deploy auction, in HYPE wei (1e-8).
	MaxGas   uint64 `json:"maxGas"`
	FullName string `json:"fullName,omitempty"`
}

RegisterToken2 registers a spot token.

type RequestEVMContract

type RequestEVMContract struct {
	Token   int     `json:"token"`
	Address Address `json:"address"`
	// EVMExtraWeiDecimals is the EVM token's decimals minus the spot
	// token's wei decimals, between -2 and 18.
	EVMExtraWeiDecimals int `json:"evmExtraWeiDecimals"`
}

RequestEVMContract requests a link between a spot token and an ERC-20 contract on the HyperEVM.

type ReserveRequestWeightAction

type ReserveRequestWeightAction struct {
	Weight uint64 `json:"weight"`
	// Destination optionally reserves the weight for another existing user.
	Destination *Address `json:"destination,omitempty"`
}

ReserveRequestWeightAction buys additional request rate limit.

type RestingOrder

type RestingOrder struct {
	Oid   int64  `json:"oid"`
	Cloid *Cloid `json:"cloid,omitempty"`
}

RestingOrder is an order resting on the book.

type Retracement

type Retracement struct {
	// Pct is a percentage of the price, such as "1.5" for 1.5%.
	Pct *Decimal
	// Px is an absolute price distance.
	Px *Decimal
}

Retracement is the trailing distance of a TrailingStopAction. Set exactly one field.

func (Retracement) MarshalJSON

func (r Retracement) MarshalJSON() ([]byte, error)

MarshalJSON encodes r as {"pct":"<Pct>%"} or {"px":"<Px>"}.

type ScheduleCancelAction

type ScheduleCancelAction struct {
	// Time is when to cancel, in Unix milliseconds, at least 5 seconds in
	// the future. Zero clears the scheduled cancel.
	Time int64 `json:"time,omitempty"`
}

ScheduleCancelAction sets or clears a dead man's switch that cancels all open orders at a given time. At most 10 triggers are allowed per day.

type SendAssetAction

type SendAssetAction struct {
	Destination Address `json:"destination"`
	// SourceDex and DestinationDex name the balances: "" is the default perp
	// dex, "spot" is spot, anything else a builder-deployed perp dex.
	SourceDex      string `json:"sourceDex"`
	DestinationDex string `json:"destinationDex"`
	// Token is the token's "NAME:0x<tokenId>" identifier. It must be the
	// collateral token when a perp dex is involved.
	Token  string  `json:"token"`
	Amount Decimal `json:"amount"`
	// FromSubAccount optionally sends from a sub-account of the signer.
	FromSubAccount *Address `json:"fromSubAccount"`
}

SendAssetAction moves a token between addresses and between the balances of perp dexes and spot. It must be signed by the account's own key.

func (SendAssetAction) MarshalJSON

func (a SendAssetAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes a in wire form, where the main account is fromSubAccount "".

type SendToEVMWithDataAction

type SendToEVMWithDataAction struct {
	// Token is the token name, e.g. "USDC".
	Token     string  `json:"token"`
	Amount    Decimal `json:"amount"`
	SourceDex string  `json:"sourceDex"`
	// DestinationRecipient is the recipient address in AddressEncoding.
	DestinationRecipient string          `json:"destinationRecipient"`
	AddressEncoding      AddressEncoding `json:"addressEncoding"`
	DestinationChainID   uint32          `json:"destinationChainId"`
	GasLimit             uint64          `json:"gasLimit"`
	// Data is the payload passed to the receiver; it may be empty.
	Data []byte `json:"data"`
}

SendToEVMWithDataAction sends a token from HyperCore to a contract implementing ICoreReceiveWithData, passing it Data. It must be signed by the account's own key.

func (SendToEVMWithDataAction) MarshalJSON

func (a SendToEVMWithDataAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes a in wire form, where Data is 0x-prefixed hex.

type SetDeployerLabel

type SetDeployerLabel struct {
	// Label is 2-4 lowercase characters, unique across deployer labels and
	// perp dexes.
	Label string `json:"label"`
}

SetDeployerLabel sets the label shown for a deployer's tokens.

type SetDeployerTradingFeeShare

type SetDeployerTradingFeeShare struct {
	Token int `json:"token"`
	// Share is a percentage between 0 and 100, such as "12.5".
	Share Decimal `json:"share"`
}

SetDeployerTradingFeeShare sets the deployer's share of a token's trading fees.

func (SetDeployerTradingFeeShare) MarshalJSON

func (s SetDeployerTradingFeeShare) MarshalJSON() ([]byte, error)

MarshalJSON encodes Share with the trailing "%" the exchange expects.

type SetDisplayNameAction

type SetDisplayNameAction struct {
	// DisplayName is at most 20 characters; empty clears it.
	DisplayName string `json:"displayName"`
}

SetDisplayNameAction sets the account's leaderboard display name.

type SetFeeRecipient

type SetFeeRecipient struct {
	Dex          string  `json:"dex"`
	FeeRecipient Address `json:"feeRecipient"`
}

SetFeeRecipient sets a dex's fee recipient.

type SetOracle

type SetOracle struct {
	Dex       string                    `json:"dex"`
	OraclePxs TupleMap[string, Decimal] `json:"oraclePxs"`
	// MarkPxs holds mark price sets; the exchange combines them with the
	// local mark price.
	MarkPxs []TupleMap[string, Decimal] `json:"markPxs"`
	// ExternalPerpPxs are external prices that limit sudden mark price
	// deviations.
	ExternalPerpPxs TupleMap[string, Decimal] `json:"externalPerpPxs"`
}

SetOracle updates the prices of a dex's assets. Coins are full asset names such as "dex:BTC".

func (SetOracle) MarshalJSON

func (s SetOracle) MarshalJSON() ([]byte, error)

MarshalJSON encodes a nil MarkPxs as [].

type SetPerpAnnotation

type SetPerpAnnotation struct {
	Coin string `json:"coin"`
	// Category is a classification label of at most 15 characters.
	Category string `json:"category"`
	// Description is at most 400 characters.
	Description string `json:"description"`
	// DisplayName replaces the L1 name in frontends; nil leaves it unset.
	DisplayName *string `json:"displayName"`
	// Keywords are search hints.
	Keywords []string `json:"keywords"`
}

SetPerpAnnotation sets display metadata for an asset.

func (SetPerpAnnotation) MarshalJSON

func (s SetPerpAnnotation) MarshalJSON() ([]byte, error)

MarshalJSON encodes a nil Keywords as [].

type SetReferrerAction

type SetReferrerAction struct {
	Code string `json:"code"`
}

SetReferrerAction sets the account's referrer by referral code.

type SetSubDeployers

type SetSubDeployers struct {
	Dex          string        `json:"dex"`
	SubDeployers []SubDeployer `json:"subDeployers"`
}

SetSubDeployers changes which users may submit which PerpDeployAction variants on a dex.

type SetTokenAnnotation

type SetTokenAnnotation struct {
	Token      int             `json:"token"`
	Annotation TokenAnnotation `json:"annotation"`
}

SetTokenAnnotation sets a spot token's display metadata.

type SettleQuestion

type SettleQuestion struct {
	Question           int                 `json:"question"`
	OutcomeSettlements []OutcomeSettlement `json:"outcomeSettlements"`
	NameAndDescription [2]string           `json:"nameAndDescription"`
}

SettleQuestion settles every remaining named outcome of a question, exactly one of them to 1.

type SettledOutcome

type SettledOutcome struct {
	Spec OutcomeSpec `json:"spec"`
	// SettleFraction is the share of the payout settled to side 0, between
	// 0 and 1.
	SettleFraction Decimal `json:"settleFraction"`
	Details        string  `json:"details"`
	// Question is the question the outcome belongs to, if any.
	Question *SettledOutcomeQuestion `json:"question,omitempty"`
}

SettledOutcome is the settlement of an outcome.

type SettledOutcomeQuestion

type SettledOutcomeQuestion struct {
	Question    QuestionStatus `json:"question"`
	Name        string         `json:"name"`
	Description string         `json:"description"`
}

SettledOutcomeQuestion is the question of a SettledOutcome.

type SettledOutcomeRequest

type SettledOutcomeRequest struct {
	Outcome int `json:"outcome"`
}

SettledOutcomeRequest is the request for InfoClient.SettledOutcome.

type Side

type Side string

Side is the side of an order, fill or trade.

const (
	SideBid Side = "B" // buy
	SideAsk Side = "A" // sell
)

Sides.

type Signature

type Signature struct {
	R, S [32]byte
	V    byte // 27 or 28
}

Signature is a recoverable secp256k1 ECDSA signature.

func (Signature) MarshalJSON

func (s Signature) MarshalJSON() ([]byte, error)

MarshalJSON encodes s as {"r":"0x…","s":"0x…","v":27}. R and S are written without leading zeros, the canonical form required inside multi-sig actions and accepted everywhere else.

func (*Signature) UnmarshalJSON

func (s *Signature) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes {"r":"0x…","s":"0x…","v":27}.

type Signer

type Signer interface {
	// Address returns the address whose key produces the signatures.
	Address() Address
	// SignHash signs a 32-byte EIP-712 digest and returns a recoverable
	// secp256k1 signature.
	SignHash(ctx context.Context, hash [32]byte) (Signature, error)
}

Signer signs Hyperliquid actions.

PrivateKeySigner covers local keys, including API (agent) wallets. Implement Signer to keep keys in a KMS, HSM or remote signing service.

type SplitOutcome

type SplitOutcome struct {
	Outcome int     `json:"outcome"`
	Amount  Decimal `json:"amount"`
}

SplitOutcome splits Amount quote tokens into Amount Yes and Amount No shares of an outcome.

type SpotAssetCtx

type SpotAssetCtx struct {
	PrevDayPx         Decimal  `json:"prevDayPx"`
	DayNtlVlm         Decimal  `json:"dayNtlVlm"`
	MarkPx            Decimal  `json:"markPx"`
	MidPx             *Decimal `json:"midPx"`
	CirculatingSupply Decimal  `json:"circulatingSupply"`
	// Coin is the pair name, as in [SpotPairMeta.Name].
	Coin        string  `json:"coin"`
	TotalSupply Decimal `json:"totalSupply"`
	DayBaseVlm  Decimal `json:"dayBaseVlm"`
}

SpotAssetCtx is the live market state of a spot pair.

type SpotBalance

type SpotBalance struct {
	Coin string `json:"coin"`
	// Token is the spot token index.
	Token    int     `json:"token"`
	Total    Decimal `json:"total"`
	Hold     Decimal `json:"hold"`
	EntryNtl Decimal `json:"entryNtl"`
	SpotHold Decimal `json:"spotHold,omitempty"`
	LTV      Decimal `json:"ltv,omitempty"`
	Borrowed Decimal `json:"borrowed,omitempty"`
	Supplied Decimal `json:"supplied,omitempty"`
}

SpotBalance is a token or outcome balance. Outcome balances have a Coin of the form "+N" or "oN" and no Token; their borrow/lend fields are empty.

type SpotClearinghouseState

type SpotClearinghouseState struct {
	PortfolioMarginEnabled bool          `json:"portfolioMarginEnabled,omitempty"`
	Balances               []SpotBalance `json:"balances"`
	// EVMEscrows are balances in transit from HyperEVM.
	EVMEscrows                       []EVMEscrow            `json:"evmEscrows,omitempty"`
	PortfolioMarginRatio             Decimal                `json:"portfolioMarginRatio,omitempty"`
	TokenToPortfolioBorrowRatio      TupleMap[int, Decimal] `json:"tokenToPortfolioBorrowRatio,omitempty"`
	TokenToPortfolioSupplyRatio      TupleMap[int, Decimal] `json:"tokenToPortfolioSupplyRatio,omitempty"`
	TokenToAvailableAfterMaintenance TupleMap[int, Decimal] `json:"tokenToAvailableAfterMaintenance,omitempty"`
}

SpotClearinghouseState is a user's spot account.

type SpotClearinghouseStateRequest

type SpotClearinghouseStateRequest struct {
	User Address `json:"user"`
}

SpotClearinghouseStateRequest is the request for InfoClient.SpotClearinghouseState.

type SpotDeployAction

type SpotDeployAction struct {
	// RegisterToken2 registers a token, bidding in the deploy auction.
	RegisterToken2 *RegisterToken2 `json:"registerToken2,omitempty"`
	// UserGenesis assigns genesis balances; it may be sent repeatedly
	// before Genesis.
	UserGenesis *UserGenesis `json:"userGenesis,omitempty"`
	// Genesis finalizes the token's supply.
	Genesis *SpotGenesis `json:"genesis,omitempty"`
	// RegisterSpot registers a trading pair.
	RegisterSpot *RegisterSpot `json:"registerSpot,omitempty"`
	// RegisterHyperliquidity seeds a pair with the HIP-2 market maker.
	RegisterHyperliquidity *RegisterHyperliquidity `json:"registerHyperliquidity,omitempty"`
	// SetDeployerTradingFeeShare sets the deployer's share of trading fees.
	SetDeployerTradingFeeShare *SetDeployerTradingFeeShare `json:"setDeployerTradingFeeShare,omitempty"`
	// EnableQuoteToken makes a token usable as a quote token.
	EnableQuoteToken *SpotDeployToken `json:"enableQuoteToken,omitempty"`
	// DisableQuoteToken stops a token being usable as a quote token.
	DisableQuoteToken *SpotDeployToken `json:"disableQuoteToken,omitempty"`
	// EnableFreezePrivilege lets the deployer freeze users' balances; it must
	// be sent before Genesis.
	EnableFreezePrivilege *SpotDeployToken `json:"enableFreezePrivilege,omitempty"`
	// FreezeUser freezes or unfreezes a user's balance of the token.
	FreezeUser *FreezeUser `json:"freezeUser,omitempty"`
	// RevokeFreezePrivilege permanently gives up the freeze privilege.
	RevokeFreezePrivilege *SpotDeployToken `json:"revokeFreezePrivilege,omitempty"`
	// RequestEVMContract requests a link to an ERC-20 contract on the
	// HyperEVM, completed with [ExchangeClient.FinalizeEVMContract].
	RequestEVMContract *RequestEVMContract `json:"requestEvmContract,omitempty"`
	// SetTokenAnnotation sets the token's display metadata, at most once
	// per day.
	SetTokenAnnotation *SetTokenAnnotation `json:"setTokenAnnotation,omitempty"`
	// SetDeployerLabel sets the label displayed for all of the deployer's
	// tokens, once per deployer.
	SetDeployerLabel *SetDeployerLabel `json:"setDeployerLabel,omitempty"`
}

SpotDeployAction deploys and manages HIP-1 spot tokens and HIP-2 hyperliquidity. Set exactly one field.

See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/deploying-hip-1-and-hip-2-assets.

type SpotDeployState

type SpotDeployState struct {
	States     []SpotDeployTokenState `json:"states"`
	GasAuction AuctionStatus          `json:"gasAuction"`
}

SpotDeployState is a deployer's in-progress spot token deployments.

type SpotDeployStateRequest

type SpotDeployStateRequest struct {
	User Address `json:"user"`
}

SpotDeployStateRequest is the request for InfoClient.SpotDeployState.

type SpotDeployToken

type SpotDeployToken struct {
	Token int `json:"token"`
}

SpotDeployToken names the token of a token-only SpotDeployAction variant.

type SpotDeployTokenState

type SpotDeployTokenState struct {
	Token                   int       `json:"token"`
	Spec                    TokenSpec `json:"spec"`
	FullName                *string   `json:"fullName"`
	DeployerTradingFeeShare Decimal   `json:"deployerTradingFeeShare"`
	// Spots are the indices of the token's spot pairs.
	Spots                        []int    `json:"spots"`
	MaxSupply                    *Decimal `json:"maxSupply"`
	HyperliquidityGenesisBalance Decimal  `json:"hyperliquidityGenesisBalance"`
	TotalGenesisBalanceWei       Decimal  `json:"totalGenesisBalanceWei"`
	// UserGenesisBalances and ExistingTokenGenesisBalances are in wei.
	UserGenesisBalances          TupleMap[Address, Decimal] `json:"userGenesisBalances"`
	ExistingTokenGenesisBalances TupleMap[int, Decimal]     `json:"existingTokenGenesisBalances"`
	BlacklistUsers               []Address                  `json:"blacklistUsers"`
}

SpotDeployTokenState is the deployment state of one spot token; see SpotDeployAction for the steps.

type SpotGenesis

type SpotGenesis struct {
	Token     int     `json:"token"`
	MaxSupply Decimal `json:"maxSupply"`
	// NoHyperliquidity sets the hyperliquidity balance to zero.
	NoHyperliquidity bool `json:"noHyperliquidity,omitempty"`
}

SpotGenesis finalizes a token's supply.

type SpotMeta

type SpotMeta struct {
	Universe []SpotPairMeta  `json:"universe"`
	Tokens   []SpotTokenMeta `json:"tokens"`
}

SpotMeta describes the spot tokens and trading pairs.

type SpotMetaAndAssetCtxs

type SpotMetaAndAssetCtxs struct {
	Meta SpotMeta
	// AssetCtxs is parallel to Meta.Universe.
	AssetCtxs []SpotAssetCtx
}

SpotMetaAndAssetCtxs is spot metadata with the market state of each pair.

func (*SpotMetaAndAssetCtxs) UnmarshalJSON

func (m *SpotMetaAndAssetCtxs) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the wire form [meta, assetCtxs].

type SpotPairMeta

type SpotPairMeta struct {
	// Tokens holds the base and quote token indices.
	Tokens [2]int `json:"tokens"`
	// Name is "BASE/QUOTE" for a few canonical pairs and "@<Index>" otherwise;
	// it is the coin name used by info endpoints and subscriptions.
	Name        string `json:"name"`
	Index       int    `json:"index"`
	IsCanonical bool   `json:"isCanonical"`
}

SpotPairMeta describes a spot trading pair. Its asset ID is 10000 + Index.

type SpotSendAction

type SpotSendAction struct {
	Destination Address `json:"destination"`
	// Token is the token's "NAME:0x<tokenId>" identifier, e.g.
	// "PURR:0xc4bf3f870c0e9465323c0b6ed28096c2".
	Token  string  `json:"token"`
	Amount Decimal `json:"amount"`
}

SpotSendAction sends a spot token to another address on Hyperliquid. It must be signed by the account's own key.

type SpotStateEvent

type SpotStateEvent struct {
	User      Address                `json:"user"`
	SpotState SpotClearinghouseState `json:"spotState"`
}

SpotStateEvent is a message of WebSocketClient.SpotState.

type SpotStateSubscription

type SpotStateSubscription struct {
	User Address `json:"user"`
	// IgnorePortfolioMargin reports balances without portfolio margin
	// adjustments.
	IgnorePortfolioMargin bool `json:"ignorePortfolioMargin,omitempty"`
}

SpotStateSubscription is the request of WebSocketClient.SpotState.

type SpotTokenMeta

type SpotTokenMeta struct {
	Name        string `json:"name"`
	SzDecimals  int    `json:"szDecimals"`
	WeiDecimals int    `json:"weiDecimals"`
	Index       int    `json:"index"`
	// TokenID is the 0x-prefixed 32-hex-digit token ID.
	TokenID     string       `json:"tokenId"`
	IsCanonical bool         `json:"isCanonical"`
	EVMContract *EVMContract `json:"evmContract"`
	FullName    *string      `json:"fullName"`
	// DeployerTradingFeeShare is the fraction of trading fees paid to the
	// token deployer.
	DeployerTradingFeeShare Decimal `json:"deployerTradingFeeShare"`
	// DeployerLabel is the deployer's display label, if set.
	DeployerLabel string `json:"deployerLabel,omitempty"`
}

SpotTokenMeta describes a spot token.

type SpotUserAction

type SpotUserAction struct {
	ToggleSpotDusting *ToggleSpotDusting `json:"toggleSpotDusting,omitempty"`
}

SpotUserAction changes spot account settings. Set exactly one field.

type StakingDeposit

type StakingDeposit struct {
	Amount Decimal `json:"amount"`
}

StakingDeposit is a transfer from spot into the staking account.

type StakingDiscount

type StakingDiscount struct {
	BpsOfMaxSupply Decimal `json:"bpsOfMaxSupply"`
	Discount       Decimal `json:"discount"`
}

StakingDiscount is a fee discount for staking a share of the HYPE supply.

type StakingLink struct {
	// Type is "requested" or "tradingUser" (StakingUser set), or
	// "stakingUser" (TradingUser set).
	Type        string  `json:"type"`
	StakingUser Address `json:"stakingUser,omitzero"`
	TradingUser Address `json:"tradingUser,omitzero"`
}

StakingLink links a trading account to a staking account for fee discounts.

type StakingLinkDisableTradingUserAction

type StakingLinkDisableTradingUserAction struct {
	TradingUser Address `json:"tradingUser"`
}

StakingLinkDisableTradingUserAction permanently disables a trading account linked to the signing staking account and locks its funds, which move to the staking account after one year. It is irreversible and must be signed by the account's own key.

type StakingWithdrawal

type StakingWithdrawal struct {
	Amount Decimal `json:"amount"`
	// Phase is "initiated" or "finalized".
	Phase string `json:"phase"`
}

StakingWithdrawal is a transfer from the staking account to spot.

type StandaloneOutcomeRole

type StandaloneOutcomeRole struct {
	// SideNames are the names of the two sides.
	SideNames [2]string `json:"sideNames"`
}

StandaloneOutcomeRole is the role of a template for standalone outcomes.

type StatusError

type StatusError struct {
	// Index is the position of the failed item in the request.
	Index int
	// Message is the exchange's reason.
	Message string
}

StatusError reports that the exchange accepted a batch request but rejected one of its items, such as a single order of an order action.

func (*StatusError) Error

func (e *StatusError) Error() string

type SubAccount

type SubAccount struct {
	Name               string                 `json:"name"`
	SubAccountUser     Address                `json:"subAccountUser"`
	Master             Address                `json:"master"`
	ClearinghouseState ClearinghouseState     `json:"clearinghouseState"`
	SpotState          SpotClearinghouseState `json:"spotState"`
}

SubAccount is a sub-account with its main-dex state.

type SubAccount2

type SubAccount2 struct {
	Name           string  `json:"name"`
	SubAccountUser Address `json:"subAccountUser"`
	Master         Address `json:"master"`
	// DexToClearinghouseState maps perp dex names ("" for the main dex) to
	// the sub-account's state on that dex.
	DexToClearinghouseState TupleMap[string, ClearinghouseState] `json:"dexToClearinghouseState"`
	SpotState               SpotClearinghouseState               `json:"spotState"`
	Abstraction             Abstraction                          `json:"abstraction,omitempty"`
}

SubAccount2 is a sub-account with its state on every perp dex.

type SubAccountModifyAction

type SubAccountModifyAction struct {
	SubAccountUser Address `json:"subAccountUser"`
	Name           string  `json:"name"`
}

SubAccountModifyAction renames a sub-account.

type SubAccountSpotTransferAction

type SubAccountSpotTransferAction struct {
	SubAccountUser Address `json:"subAccountUser"`
	// IsDeposit moves funds into the sub-account; otherwise out of it.
	IsDeposit bool `json:"isDeposit"`
	// Token is "<name>:<tokenId>", e.g. "USDC:0xeb62eee3685fc4c43992febcd9e75443".
	Token  string  `json:"token"`
	Amount Decimal `json:"amount"`
}

SubAccountSpotTransferAction moves a spot token between the account and a sub-account.

type SubAccountTransferAction

type SubAccountTransferAction struct {
	SubAccountUser Address `json:"subAccountUser"`
	// IsDeposit moves funds into the sub-account; otherwise out of it.
	IsDeposit bool `json:"isDeposit"`
	// USD is the USDC amount times 1e6.
	USD uint64 `json:"usd"`
}

SubAccountTransferAction moves perp USDC between the account and a sub-account.

type SubAccounts2Request

type SubAccounts2Request struct {
	User Address `json:"user"`
}

SubAccounts2Request is the request for InfoClient.SubAccounts2.

type SubAccountsRequest

type SubAccountsRequest struct {
	User Address `json:"user"`
}

SubAccountsRequest is the request for InfoClient.SubAccounts.

type SubDeployer

type SubDeployer struct {
	// Variant is the wire name of the action variant, such as "setOracle".
	Variant string  `json:"variant"`
	User    Address `json:"user"`
	Allowed bool    `json:"allowed"`
}

SubDeployer grants or revokes one sub-deployer permission, in a SetSubDeployers or OutcomeOperation.SetSubDeployers.

type SubDeployerVariant

type SubDeployerVariant struct {
	Name     string
	HIP3Star bool
}

SubDeployerVariant is a permission delegated by a deployer: an action variant such as "setOracle" (the wire form "setOracle"), or, with HIP3Star set, a trading action such as "order" (the wire form {"hip3Star":"order"}).

func (SubDeployerVariant) MarshalJSON

func (v SubDeployerVariant) MarshalJSON() ([]byte, error)

MarshalJSON encodes v in its wire form.

func (*SubDeployerVariant) UnmarshalJSON

func (v *SubDeployerVariant) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes "name" or {"hip3Star":"name"}.

type Subscription

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

Subscription is a stream created by a WebSocketClient method. Its handler receives messages one at a time, in order, on a goroutine of its own; up to 4096 messages wait for a handler that falls behind. A Subscription ends when it is unsubscribed, when the client is closed, when its handler falls further behind, or when the server rejects it after a reconnect.

func (*Subscription) Done

func (l *Subscription) Done() <-chan struct{}

Done returns a channel that is closed when the subscription ends.

func (*Subscription) Err

func (l *Subscription) Err() error

Err returns why the subscription ended: nil while it is live or after Subscription.Unsubscribe, ErrWebSocketClosed after WebSocketClient.Close, ErrSubscriptionOverflow if its handler fell behind, or the server's *APIError.

func (*Subscription) Unsubscribe

func (l *Subscription) Unsubscribe(ctx context.Context) error

Unsubscribe ends the subscription. The server subscription is removed, and Unsubscribe waits for the server to confirm, once no other Subscription shares it. The handler is not called after Unsubscribe returns, except for a call already in progress.

type Tif

type Tif string

Tif is an order's time in force.

const (
	// TifGtc rests on the book until filled or canceled.
	TifGtc Tif = "Gtc"
	// TifIoc fills immediately what it can and cancels the rest.
	TifIoc Tif = "Ioc"
	// TifAlo (add liquidity only) is canceled instead of taking liquidity.
	TifAlo Tif = "Alo"
	// TifFrontendMarket is the market order type used by the Hyperliquid UI.
	TifFrontendMarket Tif = "FrontendMarket"
)

Time-in-force values.

type TimeValue

type TimeValue struct {
	// Time is in milliseconds since the Unix epoch.
	Time  int64
	Value Decimal
}

TimeValue is a timestamped value of a time series.

func (*TimeValue) UnmarshalJSON

func (t *TimeValue) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the wire form [time, value].

type ToggleSpotDusting

type ToggleSpotDusting struct {
	OptOut bool `json:"optOut"`
}

ToggleSpotDusting opts the account out of (or back into) the automatic conversion of spot dust.

type TokenAnnotation

type TokenAnnotation struct {
	// Category is a classification label of at most 15 characters.
	Category string `json:"category"`
	// Description is at most 400 characters.
	Description string `json:"description"`
	// DisplayName of at most 9 characters replaces the token name in
	// frontends; nil leaves it unset.
	DisplayName *string `json:"displayName"`
	// Keywords are at most 2 search hints of at most 10 characters each.
	Keywords []string `json:"keywords"`
}

TokenAnnotation is a spot token's display metadata.

func (TokenAnnotation) MarshalJSON

func (a TokenAnnotation) MarshalJSON() ([]byte, error)

MarshalJSON encodes a nil Keywords as [].

type TokenDelegateAction

type TokenDelegateAction struct {
	Validator Address `json:"validator"`
	// Wei is the amount in units of 1e-8 HYPE.
	Wei          uint64 `json:"wei"`
	IsUndelegate bool   `json:"isUndelegate"`
}

TokenDelegateAction delegates staked HYPE to a validator, or undelegates it. It must be signed by the account's own key.

type TokenDetails

type TokenDetails struct {
	Name              string  `json:"name"`
	MaxSupply         Decimal `json:"maxSupply"`
	TotalSupply       Decimal `json:"totalSupply"`
	CirculatingSupply Decimal `json:"circulatingSupply"`
	SzDecimals        int     `json:"szDecimals"`
	WeiDecimals       int     `json:"weiDecimals"`
	MidPx             Decimal `json:"midPx"`
	MarkPx            Decimal `json:"markPx"`
	PrevDayPx         Decimal `json:"prevDayPx"`
	// Genesis is nil for tokens without a genesis distribution.
	Genesis                    *TokenGenesis              `json:"genesis"`
	Deployer                   *Address                   `json:"deployer"`
	DeployGas                  *Decimal                   `json:"deployGas"`
	DeployTime                 *string                    `json:"deployTime"`
	SeededUSDC                 Decimal                    `json:"seededUsdc"`
	NonCirculatingUserBalances TupleMap[Address, Decimal] `json:"nonCirculatingUserBalances"`
	FutureEmissions            Decimal                    `json:"futureEmissions"`
}

TokenDetails describes a spot token's supply and deployment.

type TokenDetailsRequest

type TokenDetailsRequest struct {
	// TokenID is a token ID from [SpotTokenMeta.TokenID].
	TokenID string `json:"tokenId"`
}

TokenDetailsRequest is the request for InfoClient.TokenDetails.

type TokenGenesis

type TokenGenesis struct {
	UserBalances TupleMap[Address, Decimal] `json:"userBalances"`
	// ExistingTokenBalances maps token indices to the balance granted to
	// holders of that token.
	ExistingTokenBalances TupleMap[int, Decimal] `json:"existingTokenBalances"`
	BlacklistUsers        []Address              `json:"blacklistUsers"`
}

TokenGenesis is a token's genesis distribution.

type TokenSpec

type TokenSpec struct {
	Name        string `json:"name"`
	SzDecimals  int    `json:"szDecimals"`
	WeiDecimals int    `json:"weiDecimals"`
}

TokenSpec describes a new spot token.

type TopUpIsolatedOnlyMarginAction

type TopUpIsolatedOnlyMarginAction struct {
	Asset    int     `json:"asset"`
	Leverage Decimal `json:"leverage"`
}

TopUpIsolatedOnlyMarginAction sets the margin of an isolated-only position to reach a target leverage.

type Tpsl

type Tpsl string

Tpsl is the kind of a trigger order.

const (
	TpslTakeProfit Tpsl = "tp"
	TpslStopLoss   Tpsl = "sl"
)

Trigger order kinds.

type Trade

type Trade struct {
	Coin string `json:"coin"`
	// Side is the aggressor's side.
	Side Side    `json:"side"`
	Px   Decimal `json:"px"`
	Sz   Decimal `json:"sz"`
	// Time is in milliseconds since the Unix epoch.
	Time int64  `json:"time"`
	Hash string `json:"hash"`
	// Tid is the trade ID.
	Tid int64 `json:"tid"`
	// Users holds the buyer and the seller.
	Users [2]Address `json:"users"`
}

Trade is a public trade.

type TradesSubscription

type TradesSubscription struct {
	Coin string `json:"coin"`
}

TradesSubscription is the request of WebSocketClient.Trades.

type TrailingStopAction

type TrailingStopAction struct {
	Asset      int     `json:"asset"`
	IsBuy      bool    `json:"isBuy"`
	Size       Decimal `json:"sz"`
	ReduceOnly bool    `json:"reduceOnly"`
	// Retracement is the distance the stop trails the best price by.
	Retracement Retracement `json:"retracement"`
	// ActivationPx, if set, starts trailing only once the price reaches it.
	ActivationPx *Decimal `json:"activationPx"`
}

TrailingStopAction places a trailing stop order, which follows the price by Retracement once ActivationPx is reached.

type TriggerOrder

type TriggerOrder struct {
	// IsMarket executes as a market order when triggered; otherwise the
	// order's Price is the limit price.
	IsMarket  bool    `json:"isMarket"`
	TriggerPx Decimal `json:"triggerPx"`
	Tpsl      Tpsl    `json:"tpsl"`
}

TriggerOrder is a take-profit or stop-loss order type.

type TupleMap

type TupleMap[K comparable, V any] map[K]V

TupleMap is a map that Hyperliquid encodes as a JSON array of [key, value] pairs, such as tokenToState: [[0, {...}], [150, {...}]].

func (TupleMap[K, V]) MarshalJSON

func (m TupleMap[K, V]) MarshalJSON() ([]byte, error)

MarshalJSON encodes m as [[key, value], ...] sorted by key, the order the exchange requires in signed actions. A nil map encodes as [].

func (*TupleMap[K, V]) UnmarshalJSON

func (m *TupleMap[K, V]) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the wire form [[key, value], ...].

type Twap

type Twap struct {
	Asset int  `json:"a"`
	IsBuy bool `json:"b"`
	// Size is the total size in base units.
	Size       Decimal `json:"s"`
	ReduceOnly bool    `json:"r"`
	// Minutes is the duration, from 5 to 1440.
	Minutes int `json:"m"`
	// Randomize randomizes the timing of the slices.
	Randomize bool `json:"t"`
}

Twap holds the parameters of a TwapOrderAction.

type TwapActivation

type TwapActivation struct {
	Price Decimal `json:"p"`
	// Above activates when the mark price is above Price; otherwise below.
	Above bool `json:"a"`
}

TwapActivation is the activation condition of a TWAP order.

type TwapCancelAction

type TwapCancelAction struct {
	Asset  int   `json:"a"`
	TwapID int64 `json:"t"`
}

TwapCancelAction cancels a running TWAP order.

type TwapDetails

type TwapDetails struct {
	// Trigger, if set, delays the TWAP until the mark price crosses a price.
	Trigger *TwapActivation `json:"t"`
	// StopPx, if set, terminates the TWAP when reached.
	StopPx *Decimal `json:"s"`
}

TwapDetails holds the optional conditions of a TwapOrderAction.

type TwapHistoryEntry

type TwapHistoryEntry struct {
	// Time is in seconds (not milliseconds) since the Unix epoch.
	Time   int64      `json:"time"`
	State  TwapState  `json:"state"`
	Status TwapStatus `json:"status"`
	TwapID int64      `json:"twapId,omitempty"`
}

TwapHistoryEntry is a TWAP status change.

type TwapHistoryRequest

type TwapHistoryRequest struct {
	User Address `json:"user"`
}

TwapHistoryRequest is the request for InfoClient.TwapHistory.

type TwapOrderAction

type TwapOrderAction struct {
	Twap Twap `json:"twap"`
	// Details optionally adds an activation trigger and a stop price.
	Details *TwapDetails `json:"details,omitempty"`
}

TwapOrderAction places a TWAP order, which trades Size over Minutes in slices.

type TwapSliceFill

type TwapSliceFill struct {
	Fill   UserFill `json:"fill"`
	TwapID int64    `json:"twapId"`
}

TwapSliceFill is a fill of a TWAP slice.

type TwapState

type TwapState struct {
	Coin        string   `json:"coin"`
	ExecutedNtl Decimal  `json:"executedNtl"`
	ExecutedSz  Decimal  `json:"executedSz"`
	Minutes     int      `json:"minutes"`
	Randomize   bool     `json:"randomize"`
	ReduceOnly  bool     `json:"reduceOnly"`
	Side        Side     `json:"side"`
	StopPx      *Decimal `json:"stopPx"`
	Sz          Decimal  `json:"sz"`
	// Timestamp is the start time in milliseconds since the Unix epoch.
	Timestamp int64        `json:"timestamp"`
	Trigger   *TwapTrigger `json:"trigger"`
	User      Address      `json:"user"`
}

TwapState is the state of a TWAP order.

type TwapStatesEvent

type TwapStatesEvent struct {
	Dex  string  `json:"dex"`
	User Address `json:"user"`
	// States maps TWAP IDs to the running TWAP orders.
	States TupleMap[int64, TwapState] `json:"states"`
}

TwapStatesEvent is a message of WebSocketClient.TwapStates.

type TwapStatesSubscription

type TwapStatesSubscription struct {
	User Address `json:"user"`
	// Dex is the perp dex name; empty selects the main dex.
	Dex string `json:"dex"`
}

TwapStatesSubscription is the request of WebSocketClient.TwapStates.

type TwapStatus

type TwapStatus struct {
	// Status is "activated", "finished", "terminated", "waitingForTrigger",
	// "stopped" or "error".
	Status string `json:"status"`
	// Description explains an "error" status.
	Description string `json:"description,omitempty"`
}

TwapStatus is the status of a TWAP.

type TwapTrigger

type TwapTrigger struct {
	Px    Decimal `json:"px"`
	Above bool    `json:"above"`
}

TwapTrigger is the price condition that starts a TWAP.

type TxDetailsRequest

type TxDetailsRequest struct {
	// Hash is the 0x-prefixed transaction hash.
	Hash string `json:"hash"`
}

TxDetailsRequest is the request for InfoClient.TxDetails.

type USDCRouting

type USDCRouting struct {
	// DepositRoute and WithdrawalRoute are "bridge" or "cctp".
	DepositRoute    string `json:"depositRoute"`
	WithdrawalRoute string `json:"withdrawalRoute"`
}

USDCRouting is how USDC moves between Hyperliquid and Arbitrum.

type USDClassTransferAction

type USDClassTransferAction struct {
	Amount Decimal
	// ToPerp moves spot to perp when true, perp to spot otherwise.
	ToPerp bool
	// SubAccount optionally selects a sub-account of the signer.
	SubAccount *Address
}

USDClassTransferAction moves USDC between the spot and perp balances of the signer or, when SubAccount is set, of one of its sub-accounts. It must be signed by the account's own key.

func (USDClassTransferAction) MarshalJSON

func (a USDClassTransferAction) MarshalJSON() ([]byte, error)

MarshalJSON encodes a in wire form, where a sub-account is appended to the amount as "<amount> subaccount:<address>".

type USDSendAction

type USDSendAction struct {
	Destination Address `json:"destination"`
	Amount      Decimal `json:"amount"`
}

USDSendAction sends USDC from the perp balance to another address on Hyperliquid. It must be signed by the account's own key.

type UpdateIsolatedMarginAction

type UpdateIsolatedMarginAction struct {
	Asset int `json:"asset"`
	// IsBuy is the position side; the official SDKs always send true.
	IsBuy bool `json:"isBuy"`
	// Ntli is the signed USDC amount to add (positive) or remove (negative),
	// times 1e6.
	Ntli int64 `json:"ntli"`
}

UpdateIsolatedMarginAction adds margin to or removes margin from an isolated position.

type UpdateLeverageAction

type UpdateLeverageAction struct {
	Asset    int  `json:"asset"`
	IsCross  bool `json:"isCross"`
	Leverage int  `json:"leverage"`
}

UpdateLeverageAction sets the leverage and margin mode of a perp asset.

type UserAbstractionRequest

type UserAbstractionRequest struct {
	User Address `json:"user"`
}

UserAbstractionRequest is the request for InfoClient.UserAbstraction.

type UserBorrowLendInterestRequest

type UserBorrowLendInterestRequest struct {
	User Address `json:"user"`
	// StartTime and EndTime bound the results, in milliseconds since the
	// Unix epoch. A zero EndTime means now.
	StartTime int64 `json:"startTime"`
	EndTime   int64 `json:"endTime,omitempty"`
}

UserBorrowLendInterestRequest is the request for InfoClient.UserBorrowLendInterest.

type UserDetailsRequest

type UserDetailsRequest struct {
	User Address `json:"user"`
}

UserDetailsRequest is the request for InfoClient.UserDetails.

type UserDexAbstractionRequest

type UserDexAbstractionRequest struct {
	User Address `json:"user"`
}

UserDexAbstractionRequest is the request for InfoClient.UserDexAbstraction.

type UserEvent

type UserEvent struct {
	Fills          []UserFill         `json:"fills,omitempty"`
	Funding        *FundingPayment    `json:"funding,omitempty"`
	Liquidation    *LiquidationEvent  `json:"liquidation,omitempty"`
	NonUserCancel  []NonUserCancel    `json:"nonUserCancel,omitempty"`
	TwapHistory    []TwapHistoryEntry `json:"twapHistory,omitempty"`
	TwapSliceFills []TwapSliceFill    `json:"twapSliceFills,omitempty"`
}

UserEvent is a message of WebSocketClient.UserEvents. Exactly one field is set.

type UserEventsSubscription

type UserEventsSubscription struct {
	User Address `json:"user"`
}

UserEventsSubscription is the request of WebSocketClient.UserEvents.

type UserFees

type UserFees struct {
	DailyUserVlm      []DailyUserVolume `json:"dailyUserVlm"`
	FeeSchedule       FeeSchedule       `json:"feeSchedule"`
	UserCrossRate     Decimal           `json:"userCrossRate"`
	UserAddRate       Decimal           `json:"userAddRate"`
	UserSpotCrossRate Decimal           `json:"userSpotCrossRate"`
	UserSpotAddRate   Decimal           `json:"userSpotAddRate"`
	// ActiveReferralDiscount is the discount fraction from being referred.
	ActiveReferralDiscount Decimal `json:"activeReferralDiscount"`
	// Trial is an undocumented fee trial, usually null.
	Trial          json.RawMessage `json:"trial"`
	FeeTrialEscrow Decimal         `json:"feeTrialEscrow"`
	// NextTrialAvailableTimestamp is in milliseconds since the Unix epoch,
	// or nil.
	NextTrialAvailableTimestamp *int64          `json:"nextTrialAvailableTimestamp"`
	StakingLink                 *StakingLink    `json:"stakingLink"`
	ActiveStakingDiscount       StakingDiscount `json:"activeStakingDiscount"`
}

UserFees is a user's fee schedule, current rates and recent volume. Rates are fractions: 0.00045 means 4.5 basis points.

type UserFeesRequest

type UserFeesRequest struct {
	User Address `json:"user"`
}

UserFeesRequest is the request for InfoClient.UserFees.

type UserFill

type UserFill struct {
	Coin string  `json:"coin"`
	Px   Decimal `json:"px"`
	Sz   Decimal `json:"sz"`
	Side Side    `json:"side"`
	// Time is in milliseconds since the Unix epoch.
	Time          int64   `json:"time"`
	StartPosition Decimal `json:"startPosition"`
	// Dir describes the fill's effect, such as "Open Long" or "Close Short".
	Dir       string  `json:"dir"`
	ClosedPnl Decimal `json:"closedPnl"`
	Hash      string  `json:"hash"`
	Oid       int64   `json:"oid"`
	// Crossed reports whether the order took liquidity.
	Crossed bool `json:"crossed"`
	// Fee is negative for a maker rebate.
	Fee            Decimal          `json:"fee"`
	BuilderFee     Decimal          `json:"builderFee,omitempty"`
	Tid            int64            `json:"tid"`
	FeeToken       string           `json:"feeToken"`
	FeeTrialEscrow Decimal          `json:"feeTrialEscrow,omitempty"`
	TwapID         *int64           `json:"twapId"`
	Cloid          *Cloid           `json:"cloid,omitempty"`
	Liquidation    *FillLiquidation `json:"liquidation,omitempty"`
}

UserFill is a fill of one of a user's orders.

type UserFillsByTimeRequest

type UserFillsByTimeRequest struct {
	User Address `json:"user"`
	// StartTime and EndTime bound the results, in milliseconds since the
	// Unix epoch. A zero EndTime means now.
	StartTime int64 `json:"startTime"`
	EndTime   int64 `json:"endTime,omitempty"`
	// AggregateByTime merges partial fills of the same order at the same
	// time.
	AggregateByTime bool `json:"aggregateByTime,omitempty"`
	// Reversed returns the newest fills first.
	Reversed bool `json:"reversed,omitempty"`
}

UserFillsByTimeRequest is the request for InfoClient.UserFillsByTime.

type UserFillsEvent

type UserFillsEvent struct {
	User  Address    `json:"user"`
	Fills []UserFill `json:"fills"`
	// IsSnapshot is set on the first message, which holds recent history.
	IsSnapshot bool `json:"isSnapshot,omitempty"`
}

UserFillsEvent is a message of WebSocketClient.UserFills.

type UserFillsRequest

type UserFillsRequest struct {
	User Address `json:"user"`
	// AggregateByTime merges partial fills of the same order at the same
	// time.
	AggregateByTime bool `json:"aggregateByTime,omitempty"`
}

UserFillsRequest is the request for InfoClient.UserFills.

type UserFillsSubscription

type UserFillsSubscription struct {
	User Address `json:"user"`
	// AggregateByTime combines the partial fills of an order that matched
	// at the same time.
	AggregateByTime bool `json:"aggregateByTime"`
}

UserFillsSubscription is the request of WebSocketClient.UserFills.

type UserFundingRequest

type UserFundingRequest struct {
	User Address `json:"user"`
	// StartTime and EndTime bound the results, in milliseconds since the
	// Unix epoch. Zero leaves the bound open.
	StartTime int64 `json:"startTime,omitempty"`
	EndTime   int64 `json:"endTime,omitempty"`
}

UserFundingRequest is the request for InfoClient.UserFunding.

type UserFundingsEvent

type UserFundingsEvent struct {
	User     Address          `json:"user"`
	Fundings []FundingPayment `json:"fundings"`
	// IsSnapshot is set on the first message, which holds recent history.
	IsSnapshot bool `json:"isSnapshot,omitempty"`
}

UserFundingsEvent is a message of WebSocketClient.UserFundings.

type UserFundingsSubscription

type UserFundingsSubscription struct {
	User Address `json:"user"`
}

UserFundingsSubscription is the request of WebSocketClient.UserFundings.

type UserGenesis

type UserGenesis struct {
	Token               int                `json:"token"`
	UserAndWei          []UserWei          `json:"userAndWei"`
	ExistingTokenAndWei []ExistingTokenWei `json:"existingTokenAndWei"`
	// BlacklistUsers adds users to, or removes them from, the genesis
	// blacklist.
	BlacklistUsers []BlacklistUser `json:"blacklistUsers,omitempty"`
}

UserGenesis assigns genesis balances of a token, in wei.

func (UserGenesis) MarshalJSON

func (g UserGenesis) MarshalJSON() ([]byte, error)

MarshalJSON encodes nil required lists as [].

type UserHistoricalOrdersEvent

type UserHistoricalOrdersEvent struct {
	User         Address           `json:"user"`
	OrderHistory []OrderWithStatus `json:"orderHistory"`
	// IsSnapshot is set on the first message, which holds recent history.
	IsSnapshot bool `json:"isSnapshot,omitempty"`
}

UserHistoricalOrdersEvent is a message of WebSocketClient.UserHistoricalOrders.

type UserHistoricalOrdersSubscription

type UserHistoricalOrdersSubscription struct {
	User Address `json:"user"`
}

UserHistoricalOrdersSubscription is the request of WebSocketClient.UserHistoricalOrders.

type UserNonFundingLedgerUpdatesEvent

type UserNonFundingLedgerUpdatesEvent struct {
	User                    Address        `json:"user"`
	NonFundingLedgerUpdates []LedgerUpdate `json:"nonFundingLedgerUpdates"`
	// IsSnapshot is set on the first message, which holds recent history.
	IsSnapshot bool `json:"isSnapshot,omitempty"`
}

UserNonFundingLedgerUpdatesEvent is a message of WebSocketClient.UserNonFundingLedgerUpdates.

type UserNonFundingLedgerUpdatesRequest

type UserNonFundingLedgerUpdatesRequest struct {
	User Address `json:"user"`
	// StartTime and EndTime bound the results, in milliseconds since the
	// Unix epoch. Zero leaves the bound open.
	StartTime int64 `json:"startTime,omitempty"`
	EndTime   int64 `json:"endTime,omitempty"`
}

UserNonFundingLedgerUpdatesRequest is the request for InfoClient.UserNonFundingLedgerUpdates.

type UserNonFundingLedgerUpdatesSubscription

type UserNonFundingLedgerUpdatesSubscription struct {
	User Address `json:"user"`
}

UserNonFundingLedgerUpdatesSubscription is the request of WebSocketClient.UserNonFundingLedgerUpdates.

type UserOutcomeAction

type UserOutcomeAction struct {
	SplitOutcome  *SplitOutcome  `json:"splitOutcome,omitempty"`
	MergeOutcome  *MergeOutcome  `json:"mergeOutcome,omitempty"`
	MergeQuestion *MergeQuestion `json:"mergeQuestion,omitempty"`
	NegateOutcome *NegateOutcome `json:"negateOutcome,omitempty"`
}

UserOutcomeAction splits, merges or negates HIP-4 outcome shares. Set exactly one field.

type UserPortfolioMarginAction

type UserPortfolioMarginAction struct {
	User    Address `json:"user"`
	Enabled bool    `json:"enabled"`
}

UserPortfolioMarginAction enables or disables portfolio margin for an account. It must be signed by the account's own key.

type UserRateLimitRequest

type UserRateLimitRequest struct {
	User Address `json:"user"`
}

UserRateLimitRequest is the request for InfoClient.UserRateLimit.

type UserRole

type UserRole struct {
	// Role is "missing", "user", "vault", "agent" or "subAccount".
	Role string `json:"role"`
	// Data is set for agents and sub-accounts.
	Data *UserRoleData `json:"data,omitempty"`
}

UserRole is the kind of an account.

type UserRoleData

type UserRoleData struct {
	// User is the account an agent trades for.
	User Address `json:"user,omitzero"`
	// Master is the owner of a sub-account.
	Master Address `json:"master,omitzero"`
}

UserRoleData links an agent or sub-account to its owner.

type UserRoleRequest

type UserRoleRequest struct {
	User Address `json:"user"`
}

UserRoleRequest is the request for InfoClient.UserRole.

type UserSetAbstractionAction

type UserSetAbstractionAction struct {
	User        Address     `json:"user"`
	Abstraction Abstraction `json:"abstraction"`
}

UserSetAbstractionAction sets the abstraction mode of the signer or of one of its sub-accounts. It must be signed by the account's own key.

type UserToMultiSigSignersRequest

type UserToMultiSigSignersRequest struct {
	User Address `json:"user"`
}

UserToMultiSigSignersRequest is the request for InfoClient.UserToMultiSigSigners.

type UserTwapHistoryEvent

type UserTwapHistoryEvent struct {
	User    Address            `json:"user"`
	History []TwapHistoryEntry `json:"history"`
	// IsSnapshot is set on the first message, which holds recent history.
	IsSnapshot bool `json:"isSnapshot,omitempty"`
}

UserTwapHistoryEvent is a message of WebSocketClient.UserTwapHistory.

type UserTwapHistorySubscription

type UserTwapHistorySubscription struct {
	User Address `json:"user"`
}

UserTwapHistorySubscription is the request of WebSocketClient.UserTwapHistory.

type UserTwapSliceFillsByTimeRequest

type UserTwapSliceFillsByTimeRequest struct {
	User Address `json:"user"`
	// StartTime and EndTime bound the results, in milliseconds since the
	// Unix epoch. A zero EndTime means now.
	StartTime int64 `json:"startTime"`
	EndTime   int64 `json:"endTime,omitempty"`
}

UserTwapSliceFillsByTimeRequest is the request for InfoClient.UserTwapSliceFillsByTime.

type UserTwapSliceFillsEvent

type UserTwapSliceFillsEvent struct {
	User           Address         `json:"user"`
	TwapSliceFills []TwapSliceFill `json:"twapSliceFills"`
	// IsSnapshot is set on the first message, which holds recent history.
	IsSnapshot bool `json:"isSnapshot,omitempty"`
}

UserTwapSliceFillsEvent is a message of WebSocketClient.UserTwapSliceFills.

type UserTwapSliceFillsRequest

type UserTwapSliceFillsRequest struct {
	User Address `json:"user"`
}

UserTwapSliceFillsRequest is the request for InfoClient.UserTwapSliceFills.

type UserTwapSliceFillsSubscription

type UserTwapSliceFillsSubscription struct {
	User Address `json:"user"`
}

UserTwapSliceFillsSubscription is the request of WebSocketClient.UserTwapSliceFills.

type UserVaultEquitiesRequest

type UserVaultEquitiesRequest struct {
	User Address `json:"user"`
}

UserVaultEquitiesRequest is the request for InfoClient.UserVaultEquities.

type UserWei

type UserWei struct {
	User Address
	Wei  Decimal
}

UserWei is a genesis balance of a user, encoded as [user, wei].

func (UserWei) MarshalJSON

func (u UserWei) MarshalJSON() ([]byte, error)

MarshalJSON encodes u as [user, wei].

type VIPFeeTier

type VIPFeeTier struct {
	NtlCutoff Decimal `json:"ntlCutoff"`
	Cross     Decimal `json:"cross"`
	Add       Decimal `json:"add"`
	SpotCross Decimal `json:"spotCross"`
	SpotAdd   Decimal `json:"spotAdd"`
}

VIPFeeTier is a fee tier reached by 14-day volume.

type ValidatorL1StreamAction

type ValidatorL1StreamAction struct {
	RiskFreeRate Decimal `json:"riskFreeRate"`
}

ValidatorL1StreamAction is a validator's vote on the risk-free rate of aligned quote assets.

type ValidatorL1Vote

type ValidatorL1Vote struct {
	// ExpireTime is in milliseconds since the Unix epoch.
	ExpireTime int64 `json:"expireTime"`
	// Action is the voted-on action, a single-key object such as {"D": ...},
	// {"C": [...]}, {"E": {...}} or {"O": {...}} whose payloads are not
	// documented.
	Action        json.RawMessage `json:"action"`
	Votes         []Address       `json:"votes"`
	QuorumReached bool            `json:"quorumReached"`
}

ValidatorL1Vote is a pending L1 governance vote among validators.

type ValidatorProfile

type ValidatorProfile struct {
	NodeIP              NodeIP  `json:"node_ip"`
	Name                string  `json:"name"`
	Description         string  `json:"description"`
	DelegationsDisabled bool    `json:"delegations_disabled"`
	CommissionBps       int     `json:"commission_bps"`
	Signer              Address `json:"signer"`
}

ValidatorProfile is the profile of a new validator.

type ValidatorProfileChange

type ValidatorProfileChange struct {
	NodeIP             *NodeIP  `json:"node_ip"`
	Name               *string  `json:"name"`
	Description        *string  `json:"description"`
	Unjailed           bool     `json:"unjailed"`
	DisableDelegations *bool    `json:"disable_delegations"`
	CommissionBps      *int     `json:"commission_bps"`
	Signer             *Address `json:"signer"`
}

ValidatorProfileChange updates a validator's profile; nil fields are left unchanged.

type ValidatorRegistration

type ValidatorRegistration struct {
	Profile  ValidatorProfile `json:"profile"`
	Unjailed bool             `json:"unjailed"`
	// InitialWei is the initial self-delegation, in HYPE wei (1e-8).
	InitialWei uint64 `json:"initial_wei"`
}

ValidatorRegistration registers a validator.

type ValidatorStats

type ValidatorStats struct {
	// Period is "day", "week" or "month".
	Period         string  `json:"-"`
	UptimeFraction Decimal `json:"uptimeFraction"`
	PredictedAPR   Decimal `json:"predictedApr"`
	NSamples       int     `json:"nSamples"`
}

ValidatorStats are a validator's statistics over a period.

func (*ValidatorStats) UnmarshalJSON

func (s *ValidatorStats) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the wire form [period, stats].

type ValidatorSummary

type ValidatorSummary struct {
	Validator     Address `json:"validator"`
	Signer        Address `json:"signer"`
	Name          string  `json:"name"`
	Description   string  `json:"description"`
	NRecentBlocks int     `json:"nRecentBlocks"`
	// Stake is in HYPE wei (1e-8 HYPE).
	Stake    int64 `json:"stake"`
	IsJailed bool  `json:"isJailed"`
	// UnjailableAfter is in milliseconds since the Unix epoch, or nil.
	UnjailableAfter *int64  `json:"unjailableAfter"`
	IsActive        bool    `json:"isActive"`
	Commission      Decimal `json:"commission"`
	// Stats holds the "day", "week" and "month" statistics, in that order.
	Stats []ValidatorStats `json:"stats"`
}

ValidatorSummary describes a validator.

type VaultDetails

type VaultDetails struct {
	Name         string    `json:"name"`
	VaultAddress Address   `json:"vaultAddress"`
	Leader       Address   `json:"leader"`
	Description  string    `json:"description"`
	Portfolio    Portfolio `json:"portfolio"`
	// APR is a fraction: 0.05 means 5%.
	APR Decimal `json:"apr"`
	// FollowerState is the requested user's stake, or nil.
	FollowerState *VaultFollower `json:"followerState"`
	// LeaderFraction is the leader's share of the vault; LeaderCommission
	// the leader's share of follower profits.
	LeaderFraction   Decimal `json:"leaderFraction"`
	LeaderCommission Decimal `json:"leaderCommission"`
	// Followers includes the leader, whose User is Leader.
	Followers             []VaultFollower   `json:"followers"`
	MaxDistributable      Decimal           `json:"maxDistributable"`
	MaxWithdrawable       Decimal           `json:"maxWithdrawable"`
	IsClosed              bool              `json:"isClosed"`
	Relationship          VaultRelationship `json:"relationship"`
	AllowDeposits         bool              `json:"allowDeposits"`
	AlwaysCloseOnWithdraw bool              `json:"alwaysCloseOnWithdraw"`
}

VaultDetails describes a vault.

func (*VaultDetails) UnmarshalJSON

func (d *VaultDetails) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes d, resolving the leader's follower entry, which the wire marks "Leader" instead of an address.

type VaultDetailsRequest

type VaultDetailsRequest struct {
	VaultAddress Address `json:"vaultAddress"`
	// User optionally selects the follower reported in
	// [VaultDetails.FollowerState].
	User *Address `json:"user,omitempty"`
}

VaultDetailsRequest is the request for InfoClient.VaultDetails.

type VaultDistributeAction

type VaultDistributeAction struct {
	VaultAddress Address `json:"vaultAddress"`
	// USD is the USDC amount times 1e6; 0 closes the vault.
	USD uint64 `json:"usd"`
}

VaultDistributeAction distributes vault funds to its followers.

type VaultEquity

type VaultEquity struct {
	VaultAddress Address `json:"vaultAddress"`
	Equity       Decimal `json:"equity"`
	// LockedUntilTimestamp is in milliseconds since the Unix epoch.
	LockedUntilTimestamp int64 `json:"lockedUntilTimestamp"`
}

VaultEquity is a user's equity in a vault.

type VaultFollower

type VaultFollower struct {
	User        Address `json:"user"`
	VaultEquity Decimal `json:"vaultEquity"`
	// Pnl is since the last deposit; AllTimePnl over the follower's
	// lifetime.
	Pnl           Decimal `json:"pnl"`
	AllTimePnl    Decimal `json:"allTimePnl"`
	DaysFollowing int     `json:"daysFollowing"`
	// VaultEntryTime and LockupUntil are in milliseconds since the Unix
	// epoch.
	VaultEntryTime int64 `json:"vaultEntryTime"`
	LockupUntil    int64 `json:"lockupUntil"`
}

VaultFollower is a depositor's stake in a vault.

type VaultModifyAction

type VaultModifyAction struct {
	VaultAddress          Address `json:"vaultAddress"`
	AllowDeposits         *bool   `json:"allowDeposits"`
	AlwaysCloseOnWithdraw *bool   `json:"alwaysCloseOnWithdraw"`
}

VaultModifyAction changes a vault's settings. Nil fields are unchanged.

type VaultRelationship

type VaultRelationship struct {
	// Type is "normal", "parent" or "child".
	Type string `json:"type"`
	// Data is set for "parent" vaults.
	Data *VaultRelationshipData `json:"data,omitempty"`
}

VaultRelationship is a vault's place in a vault hierarchy.

type VaultRelationshipData

type VaultRelationshipData struct {
	ChildAddresses []Address `json:"childAddresses"`
}

VaultRelationshipData lists a parent vault's children.

type VaultSummary

type VaultSummary struct {
	Name         string            `json:"name"`
	VaultAddress Address           `json:"vaultAddress"`
	Leader       Address           `json:"leader"`
	TVL          Decimal           `json:"tvl"`
	IsClosed     bool              `json:"isClosed"`
	Relationship VaultRelationship `json:"relationship"`
	// CreateTimeMillis is in milliseconds since the Unix epoch.
	CreateTimeMillis int64 `json:"createTimeMillis"`
}

VaultSummary is a vault in InfoClient.VaultSummaries.

type VaultTransferAction

type VaultTransferAction struct {
	VaultAddress Address `json:"vaultAddress"`
	IsDeposit    bool    `json:"isDeposit"`
	// USD is the USDC amount times 1e6.
	USD uint64 `json:"usd"`
}

VaultTransferAction deposits USDC into or withdraws it from a vault.

type WebData2

type WebData2 struct {
	ClearinghouseState ClearinghouseState  `json:"clearinghouseState"`
	LeadingVaults      []LeadingVault      `json:"leadingVaults"`
	TotalVaultEquity   Decimal             `json:"totalVaultEquity"`
	OpenOrders         []FrontendOpenOrder `json:"openOrders"`
	AgentAddress       *Address            `json:"agentAddress"`
	// AgentValidUntil is in milliseconds since the Unix epoch.
	AgentValidUntil *int64         `json:"agentValidUntil"`
	CumLedger       Decimal        `json:"cumLedger"`
	Meta            Meta           `json:"meta"`
	AssetCtxs       []PerpAssetCtx `json:"assetCtxs"`
	// ServerTime is in milliseconds since the Unix epoch.
	ServerTime int64   `json:"serverTime"`
	IsVault    bool    `json:"isVault"`
	User       Address `json:"user"`
	// TwapStates maps TWAP IDs to running TWAPs.
	TwapStates             TupleMap[int64, TwapState] `json:"twapStates"`
	SpotState              *SpotClearinghouseState    `json:"spotState,omitempty"`
	SpotAssetCtxs          []SpotAssetCtx             `json:"spotAssetCtxs"`
	OptOutOfSpotDusting    bool                       `json:"optOutOfSpotDusting,omitempty"`
	PerpsAtOpenInterestCap []string                   `json:"perpsAtOpenInterestCap,omitempty"`
}

WebData2 is the aggregate account and market snapshot the Hyperliquid web app renders.

type WebData2Request

type WebData2Request struct {
	User Address `json:"user"`
}

WebData2Request is the request for InfoClient.WebData2.

type WebData3

type WebData3 struct {
	UserState WebData3UserState `json:"userState"`
	// PerpDexStates holds one entry per perp dex, main dex first.
	PerpDexStates []WebData3PerpDexState `json:"perpDexStates"`
}

WebData3 is a message of WebSocketClient.WebData3: account data shown by the Hyperliquid web app.

type WebData3PerpDexState

type WebData3PerpDexState struct {
	TotalVaultEquity       Decimal        `json:"totalVaultEquity"`
	PerpsAtOpenInterestCap []string       `json:"perpsAtOpenInterestCap,omitempty"`
	LeadingVaults          []LeadingVault `json:"leadingVaults,omitempty"`
}

WebData3PerpDexState is the per-dex part of WebData3.

type WebData3Subscription

type WebData3Subscription struct {
	User Address `json:"user"`
}

WebData3Subscription is the request of WebSocketClient.WebData3.

type WebData3UserState

type WebData3UserState struct {
	// AgentAddress is the web app's API wallet, or nil.
	AgentAddress *Address `json:"agentAddress"`
	// AgentValidUntil is in milliseconds since the Unix epoch, or nil.
	AgentValidUntil *int64 `json:"agentValidUntil"`
	// CumLedger is the cumulative net deposits.
	CumLedger Decimal `json:"cumLedger"`
	// ServerTime is in milliseconds since the Unix epoch.
	ServerTime            int64       `json:"serverTime"`
	IsVault               bool        `json:"isVault"`
	User                  Address     `json:"user"`
	OptOutOfSpotDusting   bool        `json:"optOutOfSpotDusting,omitempty"`
	DexAbstractionEnabled bool        `json:"dexAbstractionEnabled,omitempty"`
	Abstraction           Abstraction `json:"abstraction,omitempty"`
}

WebData3UserState is the account part of WebData3.

type WebSocketClient

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

WebSocketClient is a connection to the Hyperliquid WebSocket API. It streams subscriptions and, through WithWebSocket, carries InfoClient and ExchangeClient requests.

The client pings the server every 30 seconds and reconnects with capped exponential backoff when the connection drops or a ping goes unanswered, then re-subscribes every live subscription. Requests in flight when the connection drops fail with ErrWebSocketDisconnected; requests made while reconnecting wait for the new connection.

Subscription methods return once the server confirms the subscription; their ctx bounds only that handshake, not the subscription's lifetime. Subscriptions with an identical request share one server subscription. A subscription that joins a live one does not receive the stream's initial snapshot, such as the first full frame of WebSocketClient.FastAssetCtxs or the history of WebSocketClient.UserFills; it receives only later messages. See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket/subscriptions for the streams.

A WebSocketClient is safe for concurrent use. Call WebSocketClient.Close to release it.

func DialExplorerWebSocket

func DialExplorerWebSocket(ctx context.Context, network Network, opts ...WebSocketOption) (*WebSocketClient, error)

DialExplorerWebSocket connects to the WebSocket of network's explorer RPC, which serves only WebSocketClient.ExplorerBlock and WebSocketClient.ExplorerTxs.

func DialWebSocket

func DialWebSocket(ctx context.Context, network Network, opts ...WebSocketOption) (*WebSocketClient, error)

DialWebSocket connects to the WebSocket API of network.

func (*WebSocketClient) ActiveAssetCtx

func (c *WebSocketClient) ActiveAssetCtx(ctx context.Context, req ActiveAssetCtxSubscription, handler func(ActiveAssetCtxEvent)) (*Subscription, error)

ActiveAssetCtx streams the context of a perp asset. Use WebSocketClient.ActiveSpotAssetCtx for spot coins such as "@107".

func (*WebSocketClient) ActiveAssetData

func (c *WebSocketClient) ActiveAssetData(ctx context.Context, req ActiveAssetDataSubscription, handler func(ActiveAssetData)) (*Subscription, error)

ActiveAssetData streams a user's leverage and trading limits on a perp asset.

func (*WebSocketClient) ActiveSpotAssetCtx

func (c *WebSocketClient) ActiveSpotAssetCtx(ctx context.Context, req ActiveAssetCtxSubscription, handler func(ActiveSpotAssetCtxEvent)) (*Subscription, error)

ActiveSpotAssetCtx streams the context of a spot asset.

func (*WebSocketClient) AllDexsAssetCtxs

func (c *WebSocketClient) AllDexsAssetCtxs(ctx context.Context, handler func(AllDexsAssetCtxsEvent)) (*Subscription, error)

AllDexsAssetCtxs streams the contexts of every perp asset of every dex.

func (*WebSocketClient) AllDexsClearinghouseState

AllDexsClearinghouseState streams a user's perp account state on every dex.

func (*WebSocketClient) AllMids

func (c *WebSocketClient) AllMids(ctx context.Context, req AllMidsSubscription, handler func(AllMidsEvent)) (*Subscription, error)

AllMids streams the mid price of every coin.

func (*WebSocketClient) AssetCtxs

func (c *WebSocketClient) AssetCtxs(ctx context.Context, req AssetCtxsSubscription, handler func(AssetCtxsEvent)) (*Subscription, error)

AssetCtxs streams the contexts of every perp asset of a dex.

func (*WebSocketClient) Bbo

func (c *WebSocketClient) Bbo(ctx context.Context, req BboSubscription, handler func(BboEvent)) (*Subscription, error)

Bbo streams the best bid and offer of a coin on every change.

func (*WebSocketClient) Candle

func (c *WebSocketClient) Candle(ctx context.Context, req CandleSubscription, handler func(Candle)) (*Subscription, error)

Candle streams the current candle of a coin on every change.

func (*WebSocketClient) ClearinghouseState

func (c *WebSocketClient) ClearinghouseState(ctx context.Context, req ClearinghouseStateSubscription, handler func(ClearinghouseStateEvent)) (*Subscription, error)

ClearinghouseState streams a user's perp account state on a dex.

func (*WebSocketClient) Close

func (c *WebSocketClient) Close() error

Close closes the connection and ends every subscription with ErrWebSocketClosed. It returns once the client's goroutines, except subscription handlers still running, have exited.

func (*WebSocketClient) ExplorerBlock

func (c *WebSocketClient) ExplorerBlock(ctx context.Context, handler func([]BlockDetails)) (*Subscription, error)

ExplorerBlock streams new L1 blocks, without their transactions. It requires a client from DialExplorerWebSocket.

func (*WebSocketClient) ExplorerTxs

func (c *WebSocketClient) ExplorerTxs(ctx context.Context, handler func([]ExplorerTx)) (*Subscription, error)

ExplorerTxs streams new L1 transactions. It requires a client from DialExplorerWebSocket.

func (*WebSocketClient) FastAssetCtxs

func (c *WebSocketClient) FastAssetCtxs(ctx context.Context, handler func(FastAssetCtxs)) (*Subscription, error)

FastAssetCtxs streams mark and mid prices of every perp asset: a full snapshot, then changes. A subscription that joins a live identical one receives only changes.

func (*WebSocketClient) L2Book

func (c *WebSocketClient) L2Book(ctx context.Context, req L2BookSubscription, handler func(L2Book)) (*Subscription, error)

L2Book streams order book snapshots of a coin.

Messages carry only the coin, so subscriptions to one coin with different aggregation or speed receive each other's snapshots.

func (*WebSocketClient) Notification

func (c *WebSocketClient) Notification(ctx context.Context, req NotificationSubscription, handler func(NotificationEvent)) (*Subscription, error)

Notification streams the notifications the web app shows a user.

Messages do not name the user, so subscriptions for several users on one client all receive every user's notifications.

func (*WebSocketClient) OpenOrders

func (c *WebSocketClient) OpenOrders(ctx context.Context, req OpenOrdersSubscription, handler func(OpenOrdersEvent)) (*Subscription, error)

OpenOrders streams a user's open orders on a dex.

func (*WebSocketClient) OrderUpdates

func (c *WebSocketClient) OrderUpdates(ctx context.Context, req OrderUpdatesSubscription, handler func([]OrderUpdate)) (*Subscription, error)

OrderUpdates streams changes to a user's orders.

Messages do not name the user, so subscriptions for several users on one client all receive every user's updates.

func (*WebSocketClient) OutcomeMetaUpdates

func (c *WebSocketClient) OutcomeMetaUpdates(ctx context.Context, handler func(OutcomeMetaUpdatesEvent)) (*Subscription, error)

OutcomeMetaUpdates streams changes to outcome market metadata.

func (*WebSocketClient) SpotAssetCtxs

func (c *WebSocketClient) SpotAssetCtxs(ctx context.Context, handler func([]SpotAssetCtx)) (*Subscription, error)

SpotAssetCtxs streams the contexts of every spot asset.

func (*WebSocketClient) SpotState

func (c *WebSocketClient) SpotState(ctx context.Context, req SpotStateSubscription, handler func(SpotStateEvent)) (*Subscription, error)

SpotState streams a user's spot balances.

func (*WebSocketClient) Trades

func (c *WebSocketClient) Trades(ctx context.Context, req TradesSubscription, handler func([]Trade)) (*Subscription, error)

Trades streams the trades of a coin.

func (*WebSocketClient) TwapStates

func (c *WebSocketClient) TwapStates(ctx context.Context, req TwapStatesSubscription, handler func(TwapStatesEvent)) (*Subscription, error)

TwapStates streams a user's running TWAP orders on a dex.

func (*WebSocketClient) UserEvents

func (c *WebSocketClient) UserEvents(ctx context.Context, req UserEventsSubscription, handler func(UserEvent)) (*Subscription, error)

UserEvents streams a user's fills, funding payments, liquidations and exchange-initiated cancels.

Messages do not name the user, so subscriptions for several users on one client all receive every user's events.

func (*WebSocketClient) UserFills

func (c *WebSocketClient) UserFills(ctx context.Context, req UserFillsSubscription, handler func(UserFillsEvent)) (*Subscription, error)

UserFills streams a user's fills, starting with a snapshot of recent ones unless it joins a live identical subscription.

func (*WebSocketClient) UserFundings

func (c *WebSocketClient) UserFundings(ctx context.Context, req UserFundingsSubscription, handler func(UserFundingsEvent)) (*Subscription, error)

UserFundings streams a user's funding payments, starting with a snapshot of recent ones unless it joins a live identical subscription.

func (*WebSocketClient) UserHistoricalOrders

UserHistoricalOrders streams a user's order status changes, starting with a snapshot of recent ones unless it joins a live identical subscription.

func (*WebSocketClient) UserNonFundingLedgerUpdates

UserNonFundingLedgerUpdates streams a user's deposits, withdrawals, transfers and other ledger changes, starting with a snapshot of recent ones unless it joins a live identical subscription.

func (*WebSocketClient) UserTwapHistory

func (c *WebSocketClient) UserTwapHistory(ctx context.Context, req UserTwapHistorySubscription, handler func(UserTwapHistoryEvent)) (*Subscription, error)

UserTwapHistory streams a user's TWAP order status changes, starting with a snapshot of recent ones unless it joins a live identical subscription.

func (*WebSocketClient) UserTwapSliceFills

func (c *WebSocketClient) UserTwapSliceFills(ctx context.Context, req UserTwapSliceFillsSubscription, handler func(UserTwapSliceFillsEvent)) (*Subscription, error)

UserTwapSliceFills streams the fills of a user's TWAP orders, starting with a snapshot of recent ones unless it joins a live identical subscription.

func (*WebSocketClient) WebData3

func (c *WebSocketClient) WebData3(ctx context.Context, req WebData3Subscription, handler func(WebData3)) (*Subscription, error)

WebData3 streams the account data shown by the web app.

type WebSocketOption

type WebSocketOption func(*wsConfig)

WebSocketOption configures a WebSocketClient.

func WithWebSocketErrorHandler

func WithWebSocketErrorHandler(f func(error)) WebSocketOption

WithWebSocketErrorHandler sets a function that receives errors that belong to no request: lost connections (wrapping ErrWebSocketDisconnected), reconnection failures, server errors that match no request, and messages that fail to decode. It runs on the client's internal goroutines, possibly concurrently, so it must return promptly and must not call WebSocketClient.Close, subscribe, or send requests through the client. By default these errors are discarded.

type WithdrawAction

type WithdrawAction struct {
	Destination Address `json:"destination"`
	Amount      Decimal `json:"amount"`
}

WithdrawAction withdraws USDC from the perp balance to Arbitrum through the bridge; a fixed fee is deducted. It must be signed by the account's own key.

Directories

Path Synopsis
internal
msgpack
Package msgpack re-encodes JSON as MessagePack exactly the way Python's msgpack.packb encodes the equivalent dict: object keys keep their order, integers use the smallest encoding and strings of 32-255 bytes use str8.
Package msgpack re-encodes JSON as MessagePack exactly the way Python's msgpack.packb encodes the equivalent dict: object keys keep their order, integers use the smallest encoding and strings of 32-255 bytes use str8.

Jump to

Keyboard shortcuts

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