hyperliquid

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package hyperliquid provides a Go SDK for the Hyperliquid exchange.

The SDK provides unified access to all Hyperliquid APIs through a single client:

  • Trading: Place orders, cancel, modify, close positions
  • Info: Market data, positions, orders, vaults
  • HyperCore: Block data, trades, orders from the L1
  • EVM: Ethereum JSON-RPC for HyperEVM
  • Streaming: Real-time data via WebSocket and gRPC

Example:

sdk, err := hyperliquid.New("https://your-endpoint.quiknode.pro/TOKEN",
	hyperliquid.WithPrivateKey("0x..."),
	hyperliquid.WithAutoApprove(true),
)
if err != nil {
	log.Fatal(err)
}
defer sdk.Close()

// Place a market buy
order, err := sdk.MarketBuy("BTC", hyperliquid.WithSize(0.001))

Index

Constants

View Source
const (
	// DefaultTimeout is the default request timeout.
	DefaultTimeout = 30 * time.Second

	// DefaultSlippage is the default slippage for market orders (3%).
	DefaultSlippage = 0.03

	// DefaultMaxFee is the default max builder fee.
	DefaultMaxFee = "1%"

	// DefaultWorkerURL is the public worker URL.
	DefaultWorkerURL = "https://send.hyperliquidapi.com"

	// DefaultBuilderAddress is the QuickNode builder address.
	DefaultBuilderAddress = "0x8D62d3000eF0639d1fc9667D06BE7BB98d9993F5"

	// CacheTTL is the market metadata cache TTL.
	CacheTTL = 5 * time.Minute

	// HYPEWeiDecimals is Hyperliquid's HYPE staking precision.
	HYPEWeiDecimals = 8
)

Variables

View Source
var QNSupportedInfoMethods = map[string]bool{
	"meta": true, "spotMeta": true, "clearinghouseState": true, "spotClearinghouseState": true,
	"openOrders": true, "exchangeStatus": true, "frontendOpenOrders": true, "liquidatable": true,
	"activeAssetData": true, "maxMarketOrderNtls": true, "vaultSummaries": true, "userVaultEquities": true,
	"leadingVaults": true, "extraAgents": true, "subAccounts": true, "userFees": true, "userRateLimit": true,
	"spotDeployState": true, "perpDeployAuctionStatus": true, "delegations": true, "delegatorSummary": true,
	"maxBuilderFee": true, "userToMultiSigSigners": true, "userRole": true, "perpsAtOpenInterestCap": true,
	"validatorL1Votes": true, "marginTable": true, "perpDexs": true, "webData2": true, "outcomeMeta": true,
}

QNSupportedInfoMethods are Info API methods supported by QuickNode nodes.

Functions

func IsApprovalError

func IsApprovalError(err error) bool

IsApprovalError checks if the error is an approval-related error.

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode checks if an error has a specific code.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if the error is retryable.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if the error is a validation error.

func NormalizeAddress

func NormalizeAddress(addr string) string

NormalizeAddress normalizes an Ethereum address to checksummed format.

func ValidateAddress

func ValidateAddress(addr string) bool

ValidateAddress checks if a string is a valid Ethereum address.

Types

type BuildResponse

type BuildResponse struct {
	Hash   string         `json:"hash"`
	Nonce  int64          `json:"nonce"`
	Action map[string]any `json:"action"`
}

BuildResponse represents the response from a build request.

type CloseOption added in v0.1.4

type CloseOption func(*closeParams)

CloseOption is an option for closing a position.

func CloseWithSlippage added in v0.1.4

func CloseWithSlippage(slippage float64) CloseOption

CloseWithSlippage overrides the default slippage for this close. Slippage is expressed as a fraction (e.g. 0.05 = 5%).

type Config

type Config struct {
	Endpoint    string
	PrivateKey  string
	Testnet     bool
	AutoApprove bool
	MaxFee      string
	Slippage    float64
	Timeout     time.Duration
}

Config holds SDK configuration options.

type ConnectionState

type ConnectionState string

ConnectionState represents WebSocket/gRPC connection states.

const (
	ConnectionStateDisconnected ConnectionState = "disconnected"
	ConnectionStateConnecting   ConnectionState = "connecting"
	ConnectionStateConnected    ConnectionState = "connected"
	ConnectionStateReconnecting ConnectionState = "reconnecting"
)

type Decimal

type Decimal string

Decimal is a helper for precise decimal string handling.

func NewDecimal

func NewDecimal(v any) Decimal

NewDecimal creates a Decimal from various types.

func (Decimal) Float64

func (d Decimal) Float64() float64

Float64 returns the decimal as a float64.

func (Decimal) MarshalJSON

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

MarshalJSON implements json.Marshaler.

func (Decimal) String

func (d Decimal) String() string

String returns the decimal as a string.

func (*Decimal) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

type EVMClient

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

EVMClient provides access to the HyperEVM JSON-RPC API.

func NewEVMClient

func NewEVMClient(endpoint string, http *HTTPClient) *EVMClient

NewEVMClient creates a new EVM API client.

func (*EVMClient) Accounts

func (c *EVMClient) Accounts() ([]string, error)

Accounts returns list of accounts (usually empty for remote nodes).

func (*EVMClient) BigBlockGasPrice

func (c *EVMClient) BigBlockGasPrice() (int64, error)

BigBlockGasPrice returns gas price for big blocks.

func (*EVMClient) BlockNumber

func (c *EVMClient) BlockNumber() (int64, error)

BlockNumber returns the latest block number.

func (*EVMClient) Call

func (c *EVMClient) Call(to, data string, blockNumber string) (string, error)

Call executes a new message call without creating a transaction.

func (*EVMClient) ChainID

func (c *EVMClient) ChainID() (int64, error)

ChainID returns the chain ID.

func (*EVMClient) DebugGetBadBlocks

func (c *EVMClient) DebugGetBadBlocks() ([]any, error)

DebugGetBadBlocks returns bad blocks.

func (*EVMClient) DebugGetRawBlock

func (c *EVMClient) DebugGetRawBlock(blockNumber string) (string, error)

DebugGetRawBlock returns raw block data.

func (*EVMClient) DebugGetRawHeader

func (c *EVMClient) DebugGetRawHeader(blockNumber string) (string, error)

DebugGetRawHeader returns raw block header.

func (*EVMClient) DebugGetRawReceipts

func (c *EVMClient) DebugGetRawReceipts(blockNumber string) ([]string, error)

DebugGetRawReceipts returns raw receipts for a block.

func (*EVMClient) DebugGetRawTransaction

func (c *EVMClient) DebugGetRawTransaction(txHash string) (string, error)

DebugGetRawTransaction returns raw transaction data.

func (*EVMClient) DebugStorageRangeAt

func (c *EVMClient) DebugStorageRangeAt(blockHash string, txIndex int, contractAddress, keyStart string, maxResult int) (map[string]any, error)

DebugStorageRangeAt returns storage range at a specific point.

func (*EVMClient) DebugTraceBlock

func (c *EVMClient) DebugTraceBlock(blockRLP string, tracerConfig map[string]any) ([]any, error)

DebugTraceBlock traces a block by RLP.

func (*EVMClient) DebugTraceBlockByHash

func (c *EVMClient) DebugTraceBlockByHash(blockHash string, tracerConfig map[string]any) ([]any, error)

DebugTraceBlockByHash traces a block by hash.

func (*EVMClient) DebugTraceBlockByNumber

func (c *EVMClient) DebugTraceBlockByNumber(blockNumber string, tracerConfig map[string]any) ([]any, error)

DebugTraceBlockByNumber traces a block by number.

func (*EVMClient) DebugTraceCall

func (c *EVMClient) DebugTraceCall(tx map[string]any, blockNumber string, tracerConfig map[string]any) (map[string]any, error)

DebugTraceCall traces a call.

func (*EVMClient) DebugTraceTransaction

func (c *EVMClient) DebugTraceTransaction(txHash string, tracerConfig map[string]any) (map[string]any, error)

DebugTraceTransaction traces a transaction's execution.

func (*EVMClient) EstimateGas

func (c *EVMClient) EstimateGas(to, data string) (int64, error)

EstimateGas estimates the gas needed for a transaction.

func (*EVMClient) FeeHistory

func (c *EVMClient) FeeHistory(blockCount int, newestBlock string, rewardPercentiles []float64) (map[string]any, error)

FeeHistory returns fee history for a range of blocks.

func (*EVMClient) GasPrice

func (c *EVMClient) GasPrice() (int64, error)

GasPrice returns the current gas price.

func (*EVMClient) GetBalance

func (c *EVMClient) GetBalance(address string, blockNumber string) (string, error)

GetBalance returns the balance of an address in wei.

func (*EVMClient) GetBlockByHash

func (c *EVMClient) GetBlockByHash(hash string, fullTx bool) (map[string]any, error)

GetBlockByHash returns block info by hash.

func (*EVMClient) GetBlockByNumber

func (c *EVMClient) GetBlockByNumber(blockNumber string, fullTx bool) (map[string]any, error)

GetBlockByNumber returns block info by number.

func (*EVMClient) GetBlockReceipts

func (c *EVMClient) GetBlockReceipts(blockNumber string) ([]any, error)

GetBlockReceipts returns all receipts for a block.

func (*EVMClient) GetBlockTransactionCountByHash

func (c *EVMClient) GetBlockTransactionCountByHash(blockHash string) (int64, error)

GetBlockTransactionCountByHash returns transaction count in a block by hash.

func (*EVMClient) GetBlockTransactionCountByNumber

func (c *EVMClient) GetBlockTransactionCountByNumber(blockNumber string) (int64, error)

GetBlockTransactionCountByNumber returns transaction count in a block by number.

func (*EVMClient) GetCode

func (c *EVMClient) GetCode(address string, blockNumber string) (string, error)

GetCode returns the contract code at an address.

func (*EVMClient) GetLogs

func (c *EVMClient) GetLogs(filter map[string]any) ([]any, error)

GetLogs returns logs matching a filter.

func (*EVMClient) GetNonce

func (c *EVMClient) GetNonce(address string, blockNumber string) (int64, error)

GetNonce returns the transaction count (nonce) for an address.

func (*EVMClient) GetStorageAt

func (c *EVMClient) GetStorageAt(address, position, blockNumber string) (string, error)

GetStorageAt returns the value from a storage position at an address.

func (*EVMClient) GetSystemTxsByBlockHash

func (c *EVMClient) GetSystemTxsByBlockHash(blockHash string) ([]any, error)

GetSystemTxsByBlockHash returns system transactions by block hash.

func (*EVMClient) GetSystemTxsByBlockNumber

func (c *EVMClient) GetSystemTxsByBlockNumber(blockNumber string) ([]any, error)

GetSystemTxsByBlockNumber returns system transactions by block number.

func (*EVMClient) GetTransactionByBlockHashAndIndex

func (c *EVMClient) GetTransactionByBlockHashAndIndex(blockHash string, index int) (map[string]any, error)

GetTransactionByBlockHashAndIndex returns transaction by block hash and index.

func (*EVMClient) GetTransactionByBlockNumberAndIndex

func (c *EVMClient) GetTransactionByBlockNumberAndIndex(blockNumber string, index int) (map[string]any, error)

GetTransactionByBlockNumberAndIndex returns transaction by block number and index.

func (*EVMClient) GetTransactionByHash

func (c *EVMClient) GetTransactionByHash(hash string) (map[string]any, error)

GetTransactionByHash returns transaction info by hash.

func (*EVMClient) GetTransactionReceipt

func (c *EVMClient) GetTransactionReceipt(hash string) (map[string]any, error)

GetTransactionReceipt returns transaction receipt by hash.

func (*EVMClient) MaxPriorityFeePerGas

func (c *EVMClient) MaxPriorityFeePerGas() (int64, error)

MaxPriorityFeePerGas returns max priority fee per gas.

func (*EVMClient) NetVersion

func (c *EVMClient) NetVersion() (string, error)

NetVersion returns the network version.

func (*EVMClient) SendRawTransaction

func (c *EVMClient) SendRawTransaction(signedTx string) (string, error)

SendRawTransaction sends a signed transaction.

func (*EVMClient) Syncing

func (c *EVMClient) Syncing() (any, error)

Syncing returns sync status. Returns false if not syncing, or sync info if syncing.

func (*EVMClient) TraceBlock

func (c *EVMClient) TraceBlock(blockNumber string) ([]any, error)

TraceBlock returns traces of all transactions in a block.

func (*EVMClient) TraceCall

func (c *EVMClient) TraceCall(tx map[string]any, traceTypes []string, blockNumber string) (map[string]any, error)

TraceCall traces a call with specified trace types.

func (*EVMClient) TraceCallMany

func (c *EVMClient) TraceCallMany(calls []any, blockNumber string) ([]any, error)

TraceCallMany traces multiple calls.

func (*EVMClient) TraceFilter

func (c *EVMClient) TraceFilter(filterParams map[string]any) ([]any, error)

TraceFilter filters traces.

func (*EVMClient) TraceRawTransaction

func (c *EVMClient) TraceRawTransaction(rawTx string, traceTypes []string) (map[string]any, error)

TraceRawTransaction traces a raw transaction.

func (*EVMClient) TraceReplayBlockTransactions

func (c *EVMClient) TraceReplayBlockTransactions(blockNumber string, traceTypes []string) ([]any, error)

TraceReplayBlockTransactions replays and traces all transactions in a block.

func (*EVMClient) TraceReplayTransaction

func (c *EVMClient) TraceReplayTransaction(txHash string, traceTypes []string) (map[string]any, error)

TraceReplayTransaction replays and traces a transaction.

func (*EVMClient) TraceTransaction

func (c *EVMClient) TraceTransaction(txHash string) ([]any, error)

TraceTransaction returns trace of a transaction.

func (*EVMClient) UsingBigBlocks

func (c *EVMClient) UsingBigBlocks() (bool, error)

UsingBigBlocks returns whether the node is using big blocks.

func (*EVMClient) Web3ClientVersion

func (c *EVMClient) Web3ClientVersion() (string, error)

Web3ClientVersion returns the client version.

type EVMStream

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

EVMStream is a WebSocket client for EVM event streams.

func NewEVMStream

func NewEVMStream(endpoint string, config *EVMStreamConfig) *EVMStream

NewEVMStream creates a new EVM WebSocket stream client.

func (*EVMStream) Connected

func (s *EVMStream) Connected() bool

Connected returns true if the stream is connected.

func (*EVMStream) Logs

func (s *EVMStream) Logs(filter map[string]any, callback func(map[string]any)) *EVMStream

Logs subscribes to contract event logs.

func (*EVMStream) NewHeads

func (s *EVMStream) NewHeads(callback func(map[string]any)) *EVMStream

NewHeads subscribes to new block headers.

func (*EVMStream) NewPendingTransactions

func (s *EVMStream) NewPendingTransactions(callback func(map[string]any)) *EVMStream

NewPendingTransactions subscribes to pending transaction hashes.

func (*EVMStream) Run

func (s *EVMStream) Run() error

Run runs the stream (blocking).

func (*EVMStream) Start

func (s *EVMStream) Start() error

Start starts the stream in background.

func (*EVMStream) State

func (s *EVMStream) State() ConnectionState

State returns the current connection state.

func (*EVMStream) Stop

func (s *EVMStream) Stop()

Stop stops the stream.

func (*EVMStream) Subscriptions

func (s *EVMStream) Subscriptions() []string

Subscriptions returns the list of active subscription IDs.

func (*EVMStream) Unsubscribe

func (s *EVMStream) Unsubscribe(subscriptionID string) bool

Unsubscribe unsubscribes from a subscription.

type EVMStreamConfig

type EVMStreamConfig struct {
	OnError       func(error)
	OnClose       func()
	OnOpen        func()
	OnStateChange func(ConnectionState)
	Reconnect     bool
	MaxReconnect  int
	PingInterval  time.Duration
}

EVMStreamConfig holds configuration for EVM WebSocket streaming.

func DefaultEVMStreamConfig

func DefaultEVMStreamConfig() *EVMStreamConfig

DefaultEVMStreamConfig returns default EVM stream configuration.

type EVMSubscriptionType

type EVMSubscriptionType string

EVMSubscriptionType represents EVM WebSocket subscription types.

const (
	EVMSubscriptionNewHeads               EVMSubscriptionType = "newHeads"
	EVMSubscriptionLogs                   EVMSubscriptionType = "logs"
	EVMSubscriptionNewPendingTransactions EVMSubscriptionType = "newPendingTransactions"
)

type Error

type Error struct {
	Code     ErrorCode      `json:"code,omitempty"`
	Message  string         `json:"message"`
	Guidance string         `json:"guidance,omitempty"`
	Raw      map[string]any `json:"raw,omitempty"`
}

Error represents a Hyperliquid SDK error with structured information.

func ApprovalError

func ApprovalError(message string, approvalData map[string]any) *Error

ApprovalError creates an approval-related error.

func BuildError

func BuildError(message string) *Error

BuildError creates a build phase error.

func DuplicateOrderError

func DuplicateOrderError(rawError string) *Error

DuplicateOrderError creates a duplicate order error.

func GeoBlockedError

func GeoBlockedError(message string, data map[string]any) *Error

GeoBlockedError creates a geo-blocked error.

func InsufficientMarginError

func InsufficientMarginError(rawError string) *Error

InsufficientMarginError creates an insufficient margin error.

func InvalidNonceError

func InvalidNonceError(rawError string) *Error

InvalidNonceError creates an invalid nonce error.

func LeverageError

func LeverageError(rawError string) *Error

LeverageError creates a leverage conflict error.

func MaxOrdersError

func MaxOrdersError(rawError string) *Error

MaxOrdersError creates a max orders exceeded error.

func MustDepositError

func MustDepositError(rawError string) *Error

MustDepositError creates a must deposit first error.

func NewError

func NewError(code ErrorCode, message string) *Error

NewError creates a new Error.

func NoPositionError

func NoPositionError(asset string) *Error

NoPositionError creates a no position error.

func OrderNotFoundError

func OrderNotFoundError(oid int64) *Error

OrderNotFoundError creates an order not found error.

func ParseAPIError

func ParseAPIError(data map[string]any, statusCode int) *Error

ParseAPIError parses an API error response into an appropriate Error.

func RateLimitError

func RateLimitError(rawError string) *Error

RateLimitError creates a rate limit error.

func ReduceOnlyError

func ReduceOnlyError(rawError string) *Error

ReduceOnlyError creates a reduce-only violation error.

func SendError

func SendError(message string) *Error

SendError creates a send phase error.

func SignatureError

func SignatureError(message string) *Error

SignatureError creates a signature error.

func UserNotFoundError

func UserNotFoundError(rawError string) *Error

UserNotFoundError creates a user not found error.

func ValidationError

func ValidationError(message string) *Error

ValidationError creates a validation error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns nil (Error is the root error type).

func (*Error) WithGuidance

func (e *Error) WithGuidance(guidance string) *Error

WithGuidance adds guidance to the error.

func (*Error) WithRaw

func (e *Error) WithRaw(raw map[string]any) *Error

WithRaw adds raw response data to the error.

type ErrorCode

type ErrorCode string

ErrorCode represents semantic error codes.

const (
	ErrorCodeUnknown             ErrorCode = "UNKNOWN_ERROR"
	ErrorCodeTimeout             ErrorCode = "TIMEOUT"
	ErrorCodeConnectionError     ErrorCode = "CONNECTION_ERROR"
	ErrorCodeParseError          ErrorCode = "PARSE_ERROR"
	ErrorCodeInvalidJSON         ErrorCode = "INVALID_JSON"
	ErrorCodeMissingField        ErrorCode = "MISSING_FIELD"
	ErrorCodeInvalidParams       ErrorCode = "INVALID_PARAMS"
	ErrorCodeInvalidPriceTick    ErrorCode = "INVALID_PRICE_TICK"
	ErrorCodeInvalidSize         ErrorCode = "INVALID_SIZE"
	ErrorCodeSignatureInvalid    ErrorCode = "SIGNATURE_INVALID"
	ErrorCodeNoPosition          ErrorCode = "NO_POSITION"
	ErrorCodeOrderNotFound       ErrorCode = "ORDER_NOT_FOUND"
	ErrorCodeGeoBlocked          ErrorCode = "GEO_BLOCKED"
	ErrorCodeNotApproved         ErrorCode = "NOT_APPROVED"
	ErrorCodeFeeExceedsApproved  ErrorCode = "FEE_EXCEEDS_APPROVED"
	ErrorCodeInsufficientMargin  ErrorCode = "INSUFFICIENT_MARGIN"
	ErrorCodeLeverageConflict    ErrorCode = "LEVERAGE_CONFLICT"
	ErrorCodeRateLimited         ErrorCode = "RATE_LIMITED"
	ErrorCodeMaxOrdersExceeded   ErrorCode = "MAX_ORDERS_EXCEEDED"
	ErrorCodeReduceOnlyViolation ErrorCode = "REDUCE_ONLY_VIOLATION"
	ErrorCodeDuplicateOrder      ErrorCode = "DUPLICATE_ORDER"
	ErrorCodeUserNotFound        ErrorCode = "USER_NOT_FOUND"
	ErrorCodeMustDepositFirst    ErrorCode = "MUST_DEPOSIT_FIRST"
	ErrorCodeInvalidNonce        ErrorCode = "INVALID_NONCE"
	ErrorCodeGRPCError           ErrorCode = "GRPC_ERROR"
	ErrorCodeHTTPError           ErrorCode = "HTTP_ERROR"
	ErrorCodeBuildError          ErrorCode = "BUILD_ERROR"
	ErrorCodeSendError           ErrorCode = "SEND_ERROR"
)

type ExchangeResponse

type ExchangeResponse struct {
	Success          bool           `json:"success,omitempty"`
	User             string         `json:"user,omitempty"`
	ExchangeResponse map[string]any `json:"exchangeResponse,omitempty"`
}

ExchangeResponse represents the response from an exchange request.

type GRPCStream

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

GRPCStream is a gRPC client for real-time data streams.

func NewGRPCStream

func NewGRPCStream(endpoint string, config *GRPCStreamConfig) *GRPCStream

NewGRPCStream creates a new gRPC stream client.

func (*GRPCStream) Blocks

func (s *GRPCStream) Blocks(callback func(map[string]any)) *GRPCStream

Blocks subscribes to block data.

func (*GRPCStream) BookUpdates

func (s *GRPCStream) BookUpdates(coins []string, callback func(map[string]any)) *GRPCStream

BookUpdates subscribes to order book updates.

func (*GRPCStream) Connected

func (s *GRPCStream) Connected() bool

Connected returns true if the stream is connected.

func (*GRPCStream) Events

func (s *GRPCStream) Events(callback func(map[string]any)) *GRPCStream

Events subscribes to system events.

func (*GRPCStream) L2Book

func (s *GRPCStream) L2Book(coin string, callback func(map[string]any), opts ...L2BookOption) *GRPCStream

L2Book subscribes to Level 2 order book updates.

func (*GRPCStream) L4Book

func (s *GRPCStream) L4Book(coin string, callback func(map[string]any)) *GRPCStream

L4Book subscribes to Level 4 order book updates (individual orders).

func (*GRPCStream) Orders

func (s *GRPCStream) Orders(coins []string, callback func(map[string]any), users ...string) *GRPCStream

Orders subscribes to order stream.

func (*GRPCStream) Ping

func (s *GRPCStream) Ping() bool

Ping tests connectivity.

func (*GRPCStream) ReconnectAttempts

func (s *GRPCStream) ReconnectAttempts() int

ReconnectAttempts returns the number of reconnection attempts.

func (*GRPCStream) Run

func (s *GRPCStream) Run() error

Run runs the stream (blocking).

func (*GRPCStream) Start

func (s *GRPCStream) Start() error

Start starts the stream in background.

func (*GRPCStream) State

func (s *GRPCStream) State() ConnectionState

State returns the current connection state.

func (*GRPCStream) Stop

func (s *GRPCStream) Stop()

Stop stops the stream.

func (*GRPCStream) TWAP

func (s *GRPCStream) TWAP(coins []string, callback func(map[string]any)) *GRPCStream

TWAP subscribes to TWAP execution stream.

func (*GRPCStream) Trades

func (s *GRPCStream) Trades(coins []string, callback func(map[string]any)) *GRPCStream

Trades subscribes to trade stream.

func (*GRPCStream) WriterActions

func (s *GRPCStream) WriterActions(callback func(map[string]any)) *GRPCStream

WriterActions subscribes to writer actions.

type GRPCStreamConfig

type GRPCStreamConfig struct {
	OnError       func(error)
	OnClose       func()
	OnConnect     func()
	OnReconnect   func(attempt int)
	OnStateChange func(ConnectionState)
	Secure        bool
	Reconnect     bool
	MaxReconnect  int
}

GRPCStreamConfig holds configuration for gRPC streaming.

func DefaultGRPCStreamConfig

func DefaultGRPCStreamConfig() *GRPCStreamConfig

DefaultGRPCStreamConfig returns default gRPC stream configuration.

type GRPCStreamType

type GRPCStreamType string

GRPCStreamType represents available gRPC stream types.

const (
	GRPCStreamTypeTrades        GRPCStreamType = "TRADES"
	GRPCStreamTypeOrders        GRPCStreamType = "ORDERS"
	GRPCStreamTypeBookUpdates   GRPCStreamType = "BOOK_UPDATES"
	GRPCStreamTypeTWAP          GRPCStreamType = "TWAP"
	GRPCStreamTypeEvents        GRPCStreamType = "EVENTS"
	GRPCStreamTypeBlocks        GRPCStreamType = "BLOCKS"
	GRPCStreamTypeWriterActions GRPCStreamType = "WRITER_ACTIONS"
)

type HTTPClient

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

HTTPClient wraps http.Client with SDK-specific functionality.

func NewHTTPClient

func NewHTTPClient(timeout time.Duration) *HTTPClient

NewHTTPClient creates a new HTTP client with connection pooling.

func (*HTTPClient) Close

func (c *HTTPClient) Close()

Close closes the HTTP client.

func (*HTTPClient) Get

func (c *HTTPClient) Get(ctx context.Context, baseURL string, params map[string]string) (map[string]any, error)

Get sends a GET request and returns the parsed response.

func (*HTTPClient) Post

func (c *HTTPClient) Post(ctx context.Context, url string, body any) (map[string]any, error)

Post sends a POST request with JSON body and returns the parsed response.

func (*HTTPClient) PostRaw

func (c *HTTPClient) PostRaw(ctx context.Context, url string, body any) (any, error)

PostRaw sends a POST request and returns the raw response as any type.

type HyperCoreClient

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

HyperCoreClient provides access to the HyperCore JSON-RPC API.

func NewHyperCoreClient

func NewHyperCoreClient(endpoint string, http *HTTPClient) *HyperCoreClient

NewHyperCoreClient creates a new HyperCore API client.

func (*HyperCoreClient) BuildApproveBuilderFee

func (c *HyperCoreClient) BuildApproveBuilderFee(user, builder, maxFeeRate string, nonce int64) (map[string]any, error)

BuildApproveBuilderFee builds a builder fee approval for signing.

func (*HyperCoreClient) BuildCancel

func (c *HyperCoreClient) BuildCancel(coin string, oid int64, user string) (map[string]any, error)

BuildCancel builds a cancel action for signing.

func (*HyperCoreClient) BuildModify

func (c *HyperCoreClient) BuildModify(coin string, oid int64, user string, limitPx, sz *string, isBuy *bool) (map[string]any, error)

BuildModify builds a modify action for signing.

func (*HyperCoreClient) BuildOrder

func (c *HyperCoreClient) BuildOrder(coin string, isBuy bool, limitPx, sz, user string, reduceOnly bool, orderType map[string]any, cloid string) (map[string]any, error)

BuildOrder builds an order action for signing.

func (*HyperCoreClient) BuildRevokeBuilderFee

func (c *HyperCoreClient) BuildRevokeBuilderFee(user, builder string, nonce int64) (map[string]any, error)

BuildRevokeBuilderFee builds a builder fee revocation for signing.

func (*HyperCoreClient) GetBatchBlocks

func (c *HyperCoreClient) GetBatchBlocks(fromBlock, toBlock int64, stream ...string) ([]any, error)

GetBatchBlocks returns a range of blocks. Stream options: "trades", "orders", "events", "book", "twap", "writer_actions"

func (*HyperCoreClient) GetBlock

func (c *HyperCoreClient) GetBlock(blockNumber int64, stream ...string) (map[string]any, error)

GetBlock returns block data by number. Stream options: "trades", "orders", "events", "book", "twap", "writer_actions"

func (*HyperCoreClient) GetMaxBuilderFee

func (c *HyperCoreClient) GetMaxBuilderFee(user, builder string) (map[string]any, error)

GetMaxBuilderFee returns maximum builder fee for a user-builder pair.

func (*HyperCoreClient) LatestBlockNumber

func (c *HyperCoreClient) LatestBlockNumber(stream ...string) (int64, error)

LatestBlockNumber returns the latest block number for a stream. Stream options: "trades", "orders", "events", "book", "twap", "writer_actions"

func (*HyperCoreClient) LatestBlocks

func (c *HyperCoreClient) LatestBlocks(stream string, count int) (map[string]any, error)

LatestBlocks returns the latest N blocks for a stream. Stream options: "trades", "orders", "book_updates", "twap", "events", "writer_actions"

func (*HyperCoreClient) LatestBookUpdates

func (c *HyperCoreClient) LatestBookUpdates(count int, coin string) ([]map[string]any, error)

LatestBookUpdates returns recent book updates from latest blocks.

func (*HyperCoreClient) LatestOrders

func (c *HyperCoreClient) LatestOrders(count int, coin string) ([]map[string]any, error)

LatestOrders returns recent order events from latest blocks.

func (*HyperCoreClient) LatestTrades

func (c *HyperCoreClient) LatestTrades(count int, coin string) ([]map[string]any, error)

LatestTrades returns recent trades from latest blocks. This is an alternative to Info.RecentTrades() which may not be available on QuickNode.

func (*HyperCoreClient) ListDexes

func (c *HyperCoreClient) ListDexes() ([]string, error)

ListDexes returns all available DEX names.

func (*HyperCoreClient) ListMarkets

func (c *HyperCoreClient) ListMarkets(dex string) ([]any, error)

ListMarkets returns all available markets, optionally filtered by DEX.

func (*HyperCoreClient) OpenOrders

func (c *HyperCoreClient) OpenOrders(user string) ([]any, error)

OpenOrders returns open orders for a user.

func (*HyperCoreClient) OrderStatus

func (c *HyperCoreClient) OrderStatus(user string, oid int64) (map[string]any, error)

OrderStatus returns status of a specific order.

func (*HyperCoreClient) Preflight

func (c *HyperCoreClient) Preflight(coin string, isBuy bool, limitPx, sz, user string, reduceOnly bool, orderType map[string]any) (map[string]any, error)

Preflight validates an order before signing.

func (*HyperCoreClient) SendApproval

func (c *HyperCoreClient) SendApproval(action map[string]any, signature string) (map[string]any, error)

SendApproval sends a signed builder fee approval.

func (*HyperCoreClient) SendCancel

func (c *HyperCoreClient) SendCancel(action map[string]any, signature string, nonce int64) (map[string]any, error)

SendCancel sends a signed cancel.

func (*HyperCoreClient) SendModify

func (c *HyperCoreClient) SendModify(action map[string]any, signature string, nonce int64) (map[string]any, error)

SendModify sends a signed modify.

func (*HyperCoreClient) SendOrder

func (c *HyperCoreClient) SendOrder(action map[string]any, signature string, nonce int64) (map[string]any, error)

SendOrder sends a signed order.

func (*HyperCoreClient) SendRevocation

func (c *HyperCoreClient) SendRevocation(action map[string]any, signature string) (map[string]any, error)

SendRevocation sends a signed builder fee revocation.

func (*HyperCoreClient) Subscribe

func (c *HyperCoreClient) Subscribe(subscription map[string]any) (map[string]any, error)

Subscribe subscribes to a WebSocket stream via JSON-RPC.

func (*HyperCoreClient) Unsubscribe

func (c *HyperCoreClient) Unsubscribe(subscription map[string]any) (map[string]any, error)

Unsubscribe unsubscribes from a WebSocket stream.

type InfoClient

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

InfoClient provides access to the HyperCore Info API.

func NewInfoClient

func NewInfoClient(endpoint string, http *HTTPClient) *InfoClient

NewInfoClient creates a new Info API client.

func (*InfoClient) ActiveAssetData

func (c *InfoClient) ActiveAssetData(user, coin string) (map[string]any, error)

ActiveAssetData returns user's active asset trading parameters.

func (*InfoClient) AlignedQuoteTokenInfo

func (c *InfoClient) AlignedQuoteTokenInfo(token int) (map[string]any, error)

AlignedQuoteTokenInfo returns aligned quote token information.

func (*InfoClient) AllBorrowLendReserveStates

func (c *InfoClient) AllBorrowLendReserveStates() ([]any, error)

AllBorrowLendReserveStates returns borrow/lend reserve states for all tokens.

func (*InfoClient) AllMids

func (c *InfoClient) AllMids(opts ...InfoOption) (map[string]any, error)

AllMids returns all asset mid prices.

func (*InfoClient) AllPerpMetas

func (c *InfoClient) AllPerpMetas() (map[string]any, error)

AllPerpMetas returns consolidated universe, margin tables, asset contexts across all DEXs.

func (*InfoClient) ApprovedBuilders

func (c *InfoClient) ApprovedBuilders(user string) ([]any, error)

ApprovedBuilders returns list of approved builders for a user.

func (*InfoClient) BatchClearinghouseStates

func (c *InfoClient) BatchClearinghouseStates(users []string) ([]any, error)

BatchClearinghouseStates returns clearinghouse states for multiple users.

func (*InfoClient) BorrowLendReserveState

func (c *InfoClient) BorrowLendReserveState(token int) (map[string]any, error)

BorrowLendReserveState returns borrow/lend reserve state for a token.

func (*InfoClient) BorrowLendUserState

func (c *InfoClient) BorrowLendUserState(user string) (map[string]any, error)

BorrowLendUserState returns user's borrow/lend positions.

func (*InfoClient) Candles

func (c *InfoClient) Candles(coin, interval string, startTime, endTime int64) ([]any, error)

Candles returns historical OHLCV candlestick data.

func (*InfoClient) ClearinghouseState

func (c *InfoClient) ClearinghouseState(user string, opts ...InfoOption) (map[string]any, error)

ClearinghouseState returns user's perpetual positions and margin info.

func (*InfoClient) Delegations

func (c *InfoClient) Delegations(user string) ([]any, error)

Delegations returns user's delegations.

func (*InfoClient) DelegatorHistory

func (c *InfoClient) DelegatorHistory(user string) ([]any, error)

DelegatorHistory returns user's delegation history.

func (*InfoClient) DelegatorRewards

func (c *InfoClient) DelegatorRewards(user string) (map[string]any, error)

DelegatorRewards returns user's delegation rewards.

func (*InfoClient) DelegatorSummary

func (c *InfoClient) DelegatorSummary(user string) (map[string]any, error)

DelegatorSummary returns user's delegation summary.

func (*InfoClient) ExchangeStatus

func (c *InfoClient) ExchangeStatus() (map[string]any, error)

ExchangeStatus returns current exchange status.

func (*InfoClient) ExtraAgents

func (c *InfoClient) ExtraAgents(user string) ([]any, error)

ExtraAgents returns user's extra agents (API keys).

func (*InfoClient) FrontendOpenOrders

func (c *InfoClient) FrontendOpenOrders(user string, opts ...InfoOption) ([]any, error)

FrontendOpenOrders returns user's open orders with enhanced info.

func (*InfoClient) FundingHistory

func (c *InfoClient) FundingHistory(coin string, startTime int64, endTime *int64) ([]any, error)

FundingHistory returns historical funding rates for an asset.

func (*InfoClient) GossipRootIPs

func (c *InfoClient) GossipRootIPs() ([]string, error)

GossipRootIPs returns gossip root IPs for the network.

func (*InfoClient) HistoricalOrders

func (c *InfoClient) HistoricalOrders(user string) ([]any, error)

HistoricalOrders returns user's historical orders.

func (*InfoClient) L2Book

func (c *InfoClient) L2Book(coin string, opts ...InfoOption) (map[string]any, error)

L2Book returns the Level 2 order book for an asset.

func (*InfoClient) LeadingVaults

func (c *InfoClient) LeadingVaults(user string) ([]any, error)

LeadingVaults returns vaults that user is leading.

func (*InfoClient) Liquidatable

func (c *InfoClient) Liquidatable() ([]any, error)

Liquidatable returns list of liquidatable positions.

func (*InfoClient) MaxBuilderFee

func (c *InfoClient) MaxBuilderFee(user, builder string) (map[string]any, error)

MaxBuilderFee returns maximum builder fee for a user-builder pair.

func (*InfoClient) MaxMarketOrderNtls

func (c *InfoClient) MaxMarketOrderNtls() (map[string]any, error)

MaxMarketOrderNtls returns maximum market order notionals per asset.

func (*InfoClient) Meta

func (c *InfoClient) Meta() (map[string]any, error)

Meta returns exchange metadata including assets and margin configurations.

func (*InfoClient) MetaAndAssetCtxs

func (c *InfoClient) MetaAndAssetCtxs() (map[string]any, error)

MetaAndAssetCtxs returns metadata + real-time asset context.

func (*InfoClient) OpenOrders

func (c *InfoClient) OpenOrders(user string, opts ...InfoOption) ([]any, error)

OpenOrders returns user's open orders.

func (*InfoClient) OrderStatus

func (c *InfoClient) OrderStatus(user string, oid int64, opts ...InfoOption) (map[string]any, error)

OrderStatus returns status of a specific order.

func (*InfoClient) PerpAnnotation

func (c *InfoClient) PerpAnnotation(asset int) (map[string]any, error)

PerpAnnotation returns metadata descriptions for a perp.

func (*InfoClient) PerpCategories

func (c *InfoClient) PerpCategories() (map[string]any, error)

PerpCategories returns asset classifications for perps.

func (*InfoClient) PerpDeployAuctionStatus

func (c *InfoClient) PerpDeployAuctionStatus() (map[string]any, error)

PerpDeployAuctionStatus returns perpetual deploy auction status.

func (*InfoClient) PerpDexLimits

func (c *InfoClient) PerpDexLimits(dex string) (map[string]any, error)

PerpDexLimits returns OI caps and transfer limits for builder-deployed markets.

func (*InfoClient) PerpDexStatus

func (c *InfoClient) PerpDexStatus(dex string) (map[string]any, error)

PerpDexStatus returns total net deposits for builder-deployed markets.

func (*InfoClient) PerpDexs

func (c *InfoClient) PerpDexs() ([]any, error)

PerpDexs returns perpetual DEX information.

func (*InfoClient) PerpsAtOpenInterestCap

func (c *InfoClient) PerpsAtOpenInterestCap() ([]string, error)

PerpsAtOpenInterestCap returns perps that are at their open interest cap.

func (*InfoClient) Portfolio

func (c *InfoClient) Portfolio(user string) (map[string]any, error)

Portfolio returns user's portfolio history.

func (*InfoClient) PredictedFundings

func (c *InfoClient) PredictedFundings() ([]any, error)

PredictedFundings returns predicted funding rates for all assets.

func (*InfoClient) RecentTrades

func (c *InfoClient) RecentTrades(coin string) ([]any, error)

RecentTrades returns recent trades for an asset.

func (*InfoClient) Referral

func (c *InfoClient) Referral(user string) (map[string]any, error)

Referral returns user's referral information.

func (*InfoClient) SpotClearinghouseState

func (c *InfoClient) SpotClearinghouseState(user string) (map[string]any, error)

SpotClearinghouseState returns user's spot token balances.

func (*InfoClient) SpotDeployState

func (c *InfoClient) SpotDeployState(user string) (map[string]any, error)

SpotDeployState returns spot deployment state for user.

func (*InfoClient) SpotMeta

func (c *InfoClient) SpotMeta() (map[string]any, error)

SpotMeta returns spot trading metadata.

func (*InfoClient) SpotMetaAndAssetCtxs

func (c *InfoClient) SpotMetaAndAssetCtxs() (map[string]any, error)

SpotMetaAndAssetCtxs returns spot metadata + real-time asset context.

func (*InfoClient) SpotPairDeployAuctionStatus

func (c *InfoClient) SpotPairDeployAuctionStatus() (map[string]any, error)

SpotPairDeployAuctionStatus returns Dutch auction status for spot pair deployments.

func (*InfoClient) SubAccounts

func (c *InfoClient) SubAccounts(user string) ([]any, error)

SubAccounts returns user's sub-accounts.

func (*InfoClient) TokenDetails

func (c *InfoClient) TokenDetails(tokenID string) (map[string]any, error)

TokenDetails returns token details.

func (*InfoClient) UserAbstraction

func (c *InfoClient) UserAbstraction(user string) (map[string]any, error)

UserAbstraction returns user's account abstraction mode.

func (*InfoClient) UserDexAbstraction

func (c *InfoClient) UserDexAbstraction(user string) (map[string]any, error)

UserDexAbstraction returns user's DEX abstraction eligibility.

func (*InfoClient) UserFees

func (c *InfoClient) UserFees(user string) (map[string]any, error)

UserFees returns user's fee structure.

func (*InfoClient) UserFills

func (c *InfoClient) UserFills(user string, aggregateByTime bool) ([]any, error)

UserFills returns user's trade fills.

func (*InfoClient) UserFillsByTime

func (c *InfoClient) UserFillsByTime(user string, startTime int64, endTime *int64) ([]any, error)

UserFillsByTime returns user's trade fills within a time range.

func (*InfoClient) UserFunding

func (c *InfoClient) UserFunding(user string, startTime, endTime *int64) ([]any, error)

UserFunding returns user's funding payments.

func (*InfoClient) UserNonFundingLedgerUpdates

func (c *InfoClient) UserNonFundingLedgerUpdates(user string, startTime, endTime *int64) ([]any, error)

UserNonFundingLedgerUpdates returns user's non-funding ledger updates.

func (*InfoClient) UserRateLimit

func (c *InfoClient) UserRateLimit(user string) (map[string]any, error)

UserRateLimit returns user's rate limit status.

func (*InfoClient) UserRole

func (c *InfoClient) UserRole(user string) (map[string]any, error)

UserRole returns account type (user, agent, vault, or sub-account).

func (*InfoClient) UserTWAPHistory

func (c *InfoClient) UserTWAPHistory(user string) ([]any, error)

UserTWAPHistory returns user's TWAP order history.

func (*InfoClient) UserTWAPSliceFills

func (c *InfoClient) UserTWAPSliceFills(user string, limit int) ([]any, error)

UserTWAPSliceFills returns user's TWAP slice fills.

func (*InfoClient) UserToMultiSigSigners

func (c *InfoClient) UserToMultiSigSigners(user string) (map[string]any, error)

UserToMultiSigSigners returns multi-sig signers for a user.

func (*InfoClient) UserVaultEquities

func (c *InfoClient) UserVaultEquities(user string) (map[string]any, error)

UserVaultEquities returns user's vault equities.

func (*InfoClient) ValidatorL1Votes

func (c *InfoClient) ValidatorL1Votes() (map[string]any, error)

ValidatorL1Votes returns L1 validator votes.

func (*InfoClient) VaultDetails

func (c *InfoClient) VaultDetails(vaultAddress string, user string) (map[string]any, error)

VaultDetails returns vault details.

func (*InfoClient) VaultSummaries

func (c *InfoClient) VaultSummaries() ([]any, error)

VaultSummaries returns summaries of all vaults.

func (*InfoClient) WebData2

func (c *InfoClient) WebData2(user string) (map[string]any, error)

WebData2 returns comprehensive account snapshot.

type InfoOption

type InfoOption func(*infoParams)

InfoOption is an option for Info API methods.

func WithDex

func WithDex(dex string) InfoOption

WithDex sets the DEX for HIP-3 queries.

func WithMantissa

func WithMantissa(m int) InfoOption

WithMantissa sets the bucketing mantissa multiplier.

func WithNSigFigs

func WithNSigFigs(n int) InfoOption

WithNSigFigs sets the number of significant figures for price bucketing.

type L2Book

type L2Book struct {
	Coin        string        `json:"coin"`
	Time        int64         `json:"time"`
	BlockNumber int64         `json:"block_number"`
	Bids        []L2BookLevel `json:"bids"`
	Asks        []L2BookLevel `json:"asks"`
}

L2Book represents the L2 order book.

type L2BookLevel

type L2BookLevel struct {
	Price string `json:"px"`
	Size  string `json:"sz"`
	Count int    `json:"n"`
}

L2BookLevel represents a level in the L2 order book.

type L2BookOption

type L2BookOption func(*grpcSubscription)

L2BookOption is an option for L2Book subscription.

func L2BookNLevels

func L2BookNLevels(n int) L2BookOption

L2BookNLevels sets the number of price levels.

func L2BookNSigFigs

func L2BookNSigFigs(n int) L2BookOption

L2BookNSigFigs sets the number of significant figures for price aggregation.

type L4Order

type L4Order struct {
	User             string `json:"user"`
	Coin             string `json:"coin"`
	Side             string `json:"side"`
	LimitPx          string `json:"limit_px"`
	Size             string `json:"sz"`
	OID              int64  `json:"oid"`
	Timestamp        int64  `json:"timestamp"`
	TriggerCondition string `json:"trigger_condition,omitempty"`
	IsTrigger        bool   `json:"is_trigger,omitempty"`
	TriggerPx        string `json:"trigger_px,omitempty"`
	IsPositionTPSL   bool   `json:"is_position_tpsl,omitempty"`
	ReduceOnly       bool   `json:"reduce_only,omitempty"`
	OrderType        string `json:"order_type,omitempty"`
	TIF              string `json:"tif,omitempty"`
	CLOID            string `json:"cloid,omitempty"`
}

L4Order represents an individual order in the L4 order book.

type LeverageOption

type LeverageOption func(*leverageParams)

LeverageOption is an option for leverage updates.

func LeverageWithIsolated

func LeverageWithIsolated() LeverageOption

LeverageWithIsolated sets isolated margin mode.

type Market

type Market struct {
	Name       string `json:"name"`
	Index      int    `json:"index"`
	SzDecimals int    `json:"szDecimals"`
	IsSpot     bool   `json:"isSpot,omitempty"`
	Dex        string `json:"dex,omitempty"`
}

Market represents market metadata.

type Markets

type Markets struct {
	Perps []Market            `json:"perps"`
	Spot  []Market            `json:"spot"`
	HIP3  map[string][]Market `json:"hip3"`
	HIP4  []Market            `json:"hip4"`
}

Markets represents all available markets.

type ModifyOption

type ModifyOption func(*modifyParams)

ModifyOption is an option for order modification.

func ModifyWithReduceOnly

func ModifyWithReduceOnly() ModifyOption

ModifyWithReduceOnly sets the reduce-only flag for the modified order.

func ModifyWithTIF

func ModifyWithTIF(tif TIF) ModifyOption

ModifyWithTIF sets the time in force for the modified order.

type OpenOrdersOption

type OpenOrdersOption func(*openOrdersParams)

OpenOrdersOption is an option for OpenOrders.

func OpenOrdersWithDex

func OpenOrdersWithDex(dex string) OpenOrdersOption

OpenOrdersWithDex filters open orders by HIP-3 DEX name.

type Option

type Option func(*Config)

Option is a functional option for configuring the SDK.

func WithAutoApprove

func WithAutoApprove(autoApprove bool) Option

WithAutoApprove enables automatic builder fee approval.

func WithMaxFee

func WithMaxFee(maxFee string) Option

WithMaxFee sets the maximum builder fee to approve.

func WithPrivateKey

func WithPrivateKey(pk string) Option

WithPrivateKey sets the private key for signing transactions.

func WithSlippage

func WithSlippage(slippage float64) Option

WithSlippage sets the default slippage for market orders.

func WithTestnet

func WithTestnet(testnet bool) Option

WithTestnet enables testnet mode.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the request timeout.

type OrderBuilder

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

Order is a fluent order builder.

Examples:

// Simple limit buy
Order().Buy("BTC").Size(0.001).Price(67000).GTC()

// Market sell by notional
Order().Sell("ETH").Notional(500).Market()

// Post-only with reduce_only
Order().Buy("BTC").Size(0.01).Price(65000).ALO().ReduceOnly()

func Order

func Order() *OrderBuilder

Order creates a new order builder.

func (*OrderBuilder) ALO

func (o *OrderBuilder) ALO() *OrderBuilder

ALO sets time in force to Add Liquidity Only (post-only, maker only).

func (*OrderBuilder) Asset

func (o *OrderBuilder) Asset() string

Asset returns the order's asset.

func (*OrderBuilder) Buy

func (o *OrderBuilder) Buy(asset any) *OrderBuilder

Buy creates a buy order for the given asset.

func (*OrderBuilder) CLOID

func (o *OrderBuilder) CLOID(cloid string) *OrderBuilder

CLOID sets the client order ID for tracking.

func (*OrderBuilder) GTC

func (o *OrderBuilder) GTC() *OrderBuilder

GTC sets time in force to Good Till Cancelled.

func (*OrderBuilder) GetNotional

func (o *OrderBuilder) GetNotional() float64

GetNotional returns the order's notional value.

func (*OrderBuilder) GetPrice

func (o *OrderBuilder) GetPrice() string

GetPrice returns the order's price.

func (*OrderBuilder) GetPriorityFee added in v0.1.8

func (o *OrderBuilder) GetPriorityFee() *uint64

GetPriorityFee returns the order priority fee if set.

func (*OrderBuilder) GetSide

func (o *OrderBuilder) GetSide() Side

GetSide returns the order's side.

func (*OrderBuilder) GetSize

func (o *OrderBuilder) GetSize() string

GetSize returns the order's size.

func (*OrderBuilder) GetTIF

func (o *OrderBuilder) GetTIF() TIF

GetTIF returns the order's time in force.

func (*OrderBuilder) IOC

func (o *OrderBuilder) IOC() *OrderBuilder

IOC sets time in force to Immediate or Cancel.

func (*OrderBuilder) IsReduceOnly

func (o *OrderBuilder) IsReduceOnly() bool

IsReduceOnly returns whether the order is reduce-only.

func (*OrderBuilder) Limit

func (o *OrderBuilder) Limit(price any) *OrderBuilder

Limit is an alias for Price.

func (*OrderBuilder) Long

func (o *OrderBuilder) Long(asset any) *OrderBuilder

Long is an alias for Buy (perps terminology).

func (*OrderBuilder) Market

func (o *OrderBuilder) Market() *OrderBuilder

Market sets the order as a market order (price computed automatically).

func (*OrderBuilder) Notional

func (o *OrderBuilder) Notional(usd float64) *OrderBuilder

Notional sets the order size by USD notional value. SDK will calculate size based on current price.

func (*OrderBuilder) Price

func (o *OrderBuilder) Price(price any) *OrderBuilder

Price sets the limit price.

func (*OrderBuilder) PriorityFee added in v0.1.8

func (o *OrderBuilder) PriorityFee(priorityFee uint64) *OrderBuilder

PriorityFee sets Hyperliquid order priority p. p=10000 is 1 bp and is paid from undelegated staking HYPE.

func (*OrderBuilder) ReduceOnly

func (o *OrderBuilder) ReduceOnly() *OrderBuilder

ReduceOnly marks the order as reduce-only.

func (*OrderBuilder) Sell

func (o *OrderBuilder) Sell(asset any) *OrderBuilder

Sell creates a sell order for the given asset.

func (*OrderBuilder) SetSize

func (o *OrderBuilder) SetSize(size string)

SetSize sets the computed size (used internally for notional orders).

func (*OrderBuilder) Short

func (o *OrderBuilder) Short(asset any) *OrderBuilder

Short is an alias for Sell (perps terminology).

func (*OrderBuilder) Size

func (o *OrderBuilder) Size(size any) *OrderBuilder

Size sets the order size in asset units.

func (*OrderBuilder) String

func (o *OrderBuilder) String() string

String returns a string representation of the order.

func (*OrderBuilder) TIF

func (o *OrderBuilder) TIF(tif TIF) *OrderBuilder

TIF sets the time in force.

func (*OrderBuilder) ToAction

func (o *OrderBuilder) ToAction() map[string]any

ToAction converts the order to an API action format.

func (*OrderBuilder) Validate

func (o *OrderBuilder) Validate() error

Validate validates the order before sending.

type OrderGrouping

type OrderGrouping string

OrderGrouping represents order grouping for TP/SL attachment.

const (
	OrderGroupingNA           OrderGrouping = "na"           // No grouping (standalone order)
	OrderGroupingNormalTPSL   OrderGrouping = "normalTpsl"   // Attach TP/SL to the fill of this order
	OrderGroupingPositionTPSL OrderGrouping = "positionTpsl" // Attach TP/SL to the entire position
)

type OrderOption

type OrderOption func(*orderParams)

OrderOption is an option for order placement.

func WithGrouping

func WithGrouping(grouping OrderGrouping) OrderOption

WithGrouping sets the order grouping for TP/SL attachment.

func WithNotional

func WithNotional(usd float64) OrderOption

WithNotional sets the order size by USD notional value.

func WithOrderSlippage added in v0.1.4

func WithOrderSlippage(slippage float64) OrderOption

WithOrderSlippage overrides the default slippage for this order. Slippage is expressed as a fraction (e.g. 0.05 = 5%). Only applies to market orders; ignored for limit orders.

func WithPrice

func WithPrice(price any) OrderOption

WithPrice sets the limit price.

func WithPriorityFee added in v0.1.8

func WithPriorityFee(priorityFee uint64) OrderOption

WithPriorityFee sets Hyperliquid order priority p. p=10000 is 1 bp and is paid from undelegated staking HYPE.

func WithReduceOnly

func WithReduceOnly() OrderOption

WithReduceOnly marks the order as reduce-only.

func WithSize

func WithSize(size any) OrderOption

WithSize sets the order size in asset units.

func WithTIF

func WithTIF(tif TIF) OrderOption

WithTIF sets the time in force.

type PlacedOrder

type PlacedOrder struct {
	OID         int64          `json:"oid,omitempty"`
	Status      string         `json:"status"`
	Asset       string         `json:"asset"`
	Side        string         `json:"side"`
	Size        string         `json:"size"`
	Price       string         `json:"price,omitempty"`
	FilledSize  string         `json:"filled_size,omitempty"`
	AvgPrice    string         `json:"avg_price,omitempty"`
	RawResponse map[string]any `json:"raw_response,omitempty"`
	// contains filtered or unexported fields
}

PlacedOrder represents a successfully placed order with full context.

func ParsePlacedOrder

func ParsePlacedOrder(response map[string]any, asset string, side Side, size, price string, sdk *SDK) *PlacedOrder

ParsePlacedOrder parses an exchange response into a PlacedOrder.

func (*PlacedOrder) Cancel

func (o *PlacedOrder) Cancel() (map[string]any, error)

Cancel cancels this order.

func (*PlacedOrder) IsError

func (o *PlacedOrder) IsError() bool

IsError returns true if the order encountered an error.

func (*PlacedOrder) IsFilled

func (o *PlacedOrder) IsFilled() bool

IsFilled returns true if the order is completely filled.

func (*PlacedOrder) IsResting

func (o *PlacedOrder) IsResting() bool

IsResting returns true if the order is resting on the order book.

func (*PlacedOrder) Modify

func (o *PlacedOrder) Modify(price, size string) (*PlacedOrder, error)

Modify modifies this order's price and/or size.

type PredictionMarket added in v0.1.8

type PredictionMarket struct {
	Outcome       int              `json:"outcome"`
	Name          string           `json:"name"`
	Description   string           `json:"description"`
	Title         string           `json:"title"`
	Slug          string           `json:"slug"`
	Underlying    string           `json:"underlying,omitempty"`
	TargetPrice   string           `json:"targetPrice,omitempty"`
	Expiry        string           `json:"expiry,omitempty"`
	Period        string           `json:"period,omitempty"`
	Collateral    string           `json:"collateral"`
	MinOrderValue string           `json:"minOrderValue"`
	Aliases       []string         `json:"aliases"`
	Yes           PredictionSide   `json:"yes"`
	No            PredictionSide   `json:"no"`
	Sides         []PredictionSide `json:"sides"`
}

PredictionMarket is a HIP-4 prediction market with yes/no tradeable sides.

type PredictionMarketFilter added in v0.1.8

type PredictionMarketFilter struct {
	Query       string
	Underlying  string
	TargetPrice string
	Expiry      string
}

PredictionMarketFilter filters active HIP-4 markets by readable fields.

type PredictionMarkets added in v0.1.8

type PredictionMarkets []PredictionMarket

PredictionMarkets is a list of active HIP-4 markets.

func (PredictionMarkets) Find added in v0.1.8

Find returns the first market matching the filter.

type PredictionSide added in v0.1.8

type PredictionSide struct {
	Outcome             int    `json:"outcome"`
	Side                int    `json:"side"`
	Name                string `json:"name"`
	Symbol              string `json:"symbol"`
	Token               string `json:"token"`
	AssetID             int    `json:"assetId"`
	Mid                 string `json:"mid,omitempty"`
	SzDecimals          int    `json:"szDecimals"`
	SupportsPriorityFee bool   `json:"supportsPriorityFee"`
}

PredictionSide is a tradeable HIP-4 outcome side.

func (PredictionSide) String added in v0.1.8

func (p PredictionSide) String() string

type PreflightOption

type PreflightOption func(*preflightParams)

PreflightOption is an option for preflight validation.

func PreflightWithReduceOnly

func PreflightWithReduceOnly() PreflightOption

PreflightWithReduceOnly sets the reduce-only flag for preflight.

func PreflightWithTIF

func PreflightWithTIF(tif TIF) PreflightOption

PreflightWithTIF sets the time in force for preflight.

type SDK

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

SDK is the main Hyperliquid SDK client.

func New

func New(endpoint string, opts ...Option) (*SDK, error)

New creates a new SDK instance.

Example:

sdk, err := hyperliquid.New("https://your-endpoint.quiknode.pro/TOKEN",
	hyperliquid.WithPrivateKey("0x..."),
	hyperliquid.WithAutoApprove(true),
)

func (*SDK) Address

func (s *SDK) Address() string

Address returns the wallet address, or empty string if no wallet.

func (*SDK) AgentSetAbstraction

func (s *SDK) AgentSetAbstraction(mode string) (map[string]any, error)

AgentSetAbstraction sets account abstraction mode as an agent.

func (*SDK) ApprovalStatus

func (s *SDK) ApprovalStatus(user string) (map[string]any, error)

ApprovalStatus checks builder fee approval status.

func (*SDK) ApproveAgent

func (s *SDK) ApproveAgent(agentAddress, name string) (map[string]any, error)

ApproveAgent approves an agent (API wallet) to trade on your behalf.

func (*SDK) ApproveBuilderFee

func (s *SDK) ApproveBuilderFee(maxFee, builder string) (map[string]any, error)

ApproveBuilderFee approves builder fee for trading.

func (*SDK) Buy

func (s *SDK) Buy(asset any, opts ...OrderOption) (*PlacedOrder, error)

Buy places a buy order.

func (*SDK) BuyUSDH added in v0.1.8

func (s *SDK) BuyUSDH(amountUSDC any, opts ...OrderOption) (*PlacedOrder, error)

BuyUSDH buys USDH with USDC for HIP-4 prediction markets.

func (*SDK) Cancel

func (s *SDK) Cancel(oid int64, asset string) (map[string]any, error)

Cancel cancels an order by OID.

func (*SDK) CancelAll

func (s *SDK) CancelAll(asset string) (map[string]any, error)

CancelAll cancels all open orders, optionally filtered by asset.

func (*SDK) CancelByCloid

func (s *SDK) CancelByCloid(cloid string, asset string) (map[string]any, error)

CancelByCloid cancels an order by client order ID.

func (*SDK) Chain

func (s *SDK) Chain() string

Chain returns the chain identifier ("Mainnet" or "Testnet").

func (*SDK) Close

func (s *SDK) Close()

Close closes the SDK and releases resources.

func (*SDK) ClosePosition

func (s *SDK) ClosePosition(asset string, opts ...CloseOption) (*PlacedOrder, error)

ClosePosition closes an open position completely.

func (*SDK) Core

func (s *SDK) Core() *HyperCoreClient

Core returns the HyperCore API client.

func (*SDK) Delegate

func (s *SDK) Delegate(validator string, amount float64) (map[string]any, error)

Delegate delegates staked tokens to a validator.

func (*SDK) Dexes

func (s *SDK) Dexes() (map[string]any, error)

Dexes returns all HIP-3 DEXes.

func (*SDK) EVM

func (s *SDK) EVM() *EVMClient

EVM returns the EVM API client.

func (*SDK) FundPriorityFees added in v0.1.8

func (s *SDK) FundPriorityFees(amountHype float64) (map[string]any, error)

FundPriorityFees moves spot HYPE into undelegated staking HYPE for order priority fees.

func (*SDK) GetMid

func (s *SDK) GetMid(assetInput any) (float64, error)

GetMid returns the current mid price for an asset.

func (*SDK) Info

func (s *SDK) Info() *InfoClient

Info returns the Info API client.

func (*SDK) Long

func (s *SDK) Long(asset any, opts ...OrderOption) (*PlacedOrder, error)

Long is an alias for Buy (perps terminology).

func (*SDK) MarketBuy

func (s *SDK) MarketBuy(asset any, opts ...OrderOption) (*PlacedOrder, error)

MarketBuy places a market buy order.

func (*SDK) MarketSell

func (s *SDK) MarketSell(asset any, opts ...OrderOption) (*PlacedOrder, error)

MarketSell places a market sell order.

func (*SDK) Markets

func (s *SDK) Markets() (*Markets, error)

Markets returns all available markets.

func (*SDK) Modify

func (s *SDK) Modify(oid int64, asset, side, price, size string, opts ...ModifyOption) (*PlacedOrder, error)

Modify modifies an existing order.

func (*SDK) NewEVMStream

func (s *SDK) NewEVMStream(config *EVMStreamConfig) *EVMStream

NewEVMStream creates a new EVM WebSocket streaming client. The stream client is NOT shared across invocations - each call creates a new client.

func (*SDK) NewGRPCStream

func (s *SDK) NewGRPCStream(config *GRPCStreamConfig) *GRPCStream

NewGRPCStream creates a new gRPC streaming client. The stream client is NOT shared across invocations - each call creates a new client.

func (*SDK) NewStream

func (s *SDK) NewStream(config *StreamConfig) *Stream

NewStream creates a new WebSocket streaming client. The stream client is NOT shared across invocations - each call creates a new client.

func (*SDK) Noop

func (s *SDK) Noop() (map[string]any, error)

Noop performs a no-operation to consume a nonce.

func (*SDK) OpenOrders

func (s *SDK) OpenOrders(user string, opts ...OpenOrdersOption) (map[string]any, error)

OpenOrders returns open orders with enriched info and pre-built cancel actions.

func (*SDK) OrderStatus

func (s *SDK) OrderStatus(oid int64, user string) (map[string]any, error)

OrderStatus returns detailed status for an order.

func (*SDK) PlaceOrder

func (s *SDK) PlaceOrder(order *OrderBuilder) (*PlacedOrder, error)

PlaceOrder places an order using the fluent OrderBuilder.

func (*SDK) PlaceTriggerOrder

func (s *SDK) PlaceTriggerOrder(order *TriggerOrderBuilder, grouping OrderGrouping) (*PlacedOrder, error)

PlaceTriggerOrder places a trigger order using the fluent TriggerOrderBuilder.

func (*SDK) PredictionMarket added in v0.1.8

func (s *SDK) PredictionMarket(filter PredictionMarketFilter) (*PredictionMarket, error)

PredictionMarket finds one active HIP-4 prediction market.

func (*SDK) PredictionMarkets added in v0.1.8

func (s *SDK) PredictionMarkets() (PredictionMarkets, error)

PredictionMarkets lists active HIP-4 prediction markets with tradeable yes/no sides.

func (*SDK) PredictionSides added in v0.1.8

func (s *SDK) PredictionSides() ([]PredictionSide, error)

PredictionSides returns a flat list of tradeable HIP-4 sides.

func (*SDK) Predictions added in v0.1.8

func (s *SDK) Predictions() (PredictionMarkets, error)

Predictions is an alias for PredictionMarkets.

func (*SDK) Preflight

func (s *SDK) Preflight(asset string, side Side, price, size any, opts ...PreflightOption) (map[string]any, error)

Preflight validates an order before signing.

func (*SDK) RefreshMarkets

func (s *SDK) RefreshMarkets() (*Markets, error)

RefreshMarkets forces refresh of market metadata cache.

func (*SDK) ReserveRequestWeight

func (s *SDK) ReserveRequestWeight(weight int) (map[string]any, error)

ReserveRequestWeight purchases additional rate limit capacity.

func (*SDK) RevokeBuilderFee

func (s *SDK) RevokeBuilderFee(builder string) (map[string]any, error)

RevokeBuilderFee revokes builder fee approval.

func (*SDK) SL

func (s *SDK) SL(asset string, size any, triggerPrice any, opts ...TriggerOrderOption) (*PlacedOrder, error)

SL is an alias for StopLoss.

func (*SDK) ScheduleCancel

func (s *SDK) ScheduleCancel(timeMs int64) (map[string]any, error)

ScheduleCancel schedules cancellation of all orders after a delay. Pass 0 to cancel the scheduled cancel.

func (*SDK) Sell

func (s *SDK) Sell(asset any, opts ...OrderOption) (*PlacedOrder, error)

Sell places a sell order.

func (*SDK) SellUSDH added in v0.1.8

func (s *SDK) SellUSDH(amountUSDH any, opts ...OrderOption) (*PlacedOrder, error)

SellUSDH sells USDH back to USDC.

func (*SDK) SendAsset

func (s *SDK) SendAsset(token string, amount any, destination string, opts ...SendAssetOption) (map[string]any, error)

SendAsset performs a generalized asset transfer between DEXs and accounts.

func (*SDK) SendToEVMWithData

func (s *SDK) SendToEVMWithData(token string, amount any, destination, data, sourceDex string, destChainID int, gasLimit int) (map[string]any, error)

SendToEVMWithData transfers tokens to HyperEVM with custom data payload.

func (*SDK) SetAbstraction

func (s *SDK) SetAbstraction(mode string, user string) (map[string]any, error)

SetAbstraction sets account abstraction mode.

func (*SDK) Short

func (s *SDK) Short(asset any, opts ...OrderOption) (*PlacedOrder, error)

Short is an alias for Sell (perps terminology).

func (*SDK) Stake

func (s *SDK) Stake(amount float64) (map[string]any, error)

Stake moves spot HYPE into undelegated staking HYPE.

func (*SDK) StopLoss

func (s *SDK) StopLoss(asset string, size any, triggerPrice any, opts ...TriggerOrderOption) (*PlacedOrder, error)

StopLoss places a stop-loss trigger order.

func (*SDK) TP

func (s *SDK) TP(asset string, size any, triggerPrice any, opts ...TriggerOrderOption) (*PlacedOrder, error)

TP is an alias for TakeProfit.

func (*SDK) TWAPCancel

func (s *SDK) TWAPCancel(asset string, twapID int) (map[string]any, error)

TWAPCancel cancels an active TWAP order.

func (*SDK) TWAPOrder

func (s *SDK) TWAPOrder(asset string, size any, isBuy bool, durationMinutes int, opts ...TWAPOption) (map[string]any, error)

TWAPOrder places a TWAP (Time-Weighted Average Price) order.

func (*SDK) TakeProfit

func (s *SDK) TakeProfit(asset string, size any, triggerPrice any, opts ...TriggerOrderOption) (*PlacedOrder, error)

TakeProfit places a take-profit trigger order.

func (*SDK) Testnet

func (s *SDK) Testnet() bool

Testnet returns true if using testnet.

func (*SDK) TopUpIsolatedOnlyMargin

func (s *SDK) TopUpIsolatedOnlyMargin(asset string, leverage float64) (map[string]any, error)

TopUpIsolatedOnlyMargin tops up isolated margin to target leverage.

func (*SDK) TransferPerpToSpot

func (s *SDK) TransferPerpToSpot(amount any) (map[string]any, error)

TransferPerpToSpot transfers USDC from perp balance to spot balance.

func (*SDK) TransferSpot

func (s *SDK) TransferSpot(token, destination string, amount any) (map[string]any, error)

TransferSpot transfers spot tokens to another Hyperliquid address.

func (*SDK) TransferSpotToPerp

func (s *SDK) TransferSpotToPerp(amount any) (map[string]any, error)

TransferSpotToPerp transfers USDC from spot balance to perp balance.

func (*SDK) TransferUSD

func (s *SDK) TransferUSD(destination string, amount any) (map[string]any, error)

TransferUSD transfers USDC to another Hyperliquid address.

func (*SDK) Undelegate

func (s *SDK) Undelegate(validator string, amount float64) (map[string]any, error)

Undelegate undelegates staked tokens from a validator.

func (*SDK) Unstake

func (s *SDK) Unstake(amount float64) (map[string]any, error)

Unstake withdraws undelegated staking HYPE back to spot HYPE (7-day queue).

func (*SDK) UpdateIsolatedMargin

func (s *SDK) UpdateIsolatedMargin(asset string, isBuy bool, amount float64) (map[string]any, error)

UpdateIsolatedMargin adds or removes margin from an isolated position.

func (*SDK) UpdateLeverage

func (s *SDK) UpdateLeverage(asset string, leverage int, opts ...LeverageOption) (map[string]any, error)

UpdateLeverage updates leverage for an asset.

func (*SDK) ValidatorL1Stream

func (s *SDK) ValidatorL1Stream(riskFreeRate string) (map[string]any, error)

ValidatorL1Stream submits a validator vote for the risk-free rate.

func (*SDK) VaultDeposit

func (s *SDK) VaultDeposit(vaultAddress string, amount float64) (map[string]any, error)

VaultDeposit deposits USDC into a vault.

func (*SDK) VaultWithdraw

func (s *SDK) VaultWithdraw(vaultAddress string, amount float64) (map[string]any, error)

VaultWithdraw withdraws USDC from a vault.

func (*SDK) Withdraw

func (s *SDK) Withdraw(amount any, destination string) (map[string]any, error)

Withdraw initiates a withdrawal to Arbitrum.

type SendAssetOption

type SendAssetOption func(*sendAssetParams)

SendAssetOption is an option for SendAsset.

func SendAssetFromDex

func SendAssetFromDex(dex string) SendAssetOption

SendAssetFromDex sets the source DEX.

func SendAssetFromSubAccount

func SendAssetFromSubAccount(addr string) SendAssetOption

SendAssetFromSubAccount sets the source sub-account.

func SendAssetToDex

func SendAssetToDex(dex string) SendAssetOption

SendAssetToDex sets the destination DEX.

type Side

type Side string

Side represents the order side (buy or sell).

const (
	SideBuy  Side = "buy"
	SideSell Side = "sell"

	// Aliases for perp traders
	SideLong  Side = "buy"
	SideShort Side = "sell"
)

type Signature

type Signature struct {
	R string `json:"r"`
	S string `json:"s"`
	V int    `json:"v"`
}

Signature represents an ECDSA signature.

type Stream

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

Stream is a WebSocket client for real-time data streams.

func NewStream

func NewStream(endpoint string, config *StreamConfig) *Stream

NewStream creates a new WebSocket stream client.

func (*Stream) ActiveAssetCtx

func (s *Stream) ActiveAssetCtx(coin string, callback func(map[string]any)) string

ActiveAssetCtx subscribes to asset context data (pricing, volume, supply).

func (*Stream) ActiveAssetData

func (s *Stream) ActiveAssetData(user, coin string, callback func(map[string]any)) string

ActiveAssetData subscribes to user's active asset trading parameters.

func (*Stream) AllMids

func (s *Stream) AllMids(callback func(map[string]any)) string

AllMids subscribes to all mid price updates.

func (*Stream) BBO

func (s *Stream) BBO(coin string, callback func(map[string]any)) string

BBO subscribes to best bid/offer updates.

func (*Stream) BookUpdates

func (s *Stream) BookUpdates(coins []string, callback func(map[string]any)) string

BookUpdates subscribes to order book updates.

func (*Stream) Candle

func (s *Stream) Candle(coin, interval string, callback func(map[string]any)) string

Candle subscribes to candlestick data.

func (*Stream) ClearinghouseState

func (s *Stream) ClearinghouseState(user string, callback func(map[string]any)) string

ClearinghouseState subscribes to user's clearinghouse state updates.

func (*Stream) Connected

func (s *Stream) Connected() bool

Connected returns true if the stream is connected.

func (*Stream) Events

func (s *Stream) Events(callback func(map[string]any)) string

Events subscribes to system events.

func (*Stream) L2Book

func (s *Stream) L2Book(coin string, callback func(map[string]any)) string

L2Book subscribes to L2 order book snapshots.

func (*Stream) Notification

func (s *Stream) Notification(user string, callback func(map[string]any)) string

Notification subscribes to user notifications.

func (*Stream) OpenOrders

func (s *Stream) OpenOrders(user string, callback func(map[string]any)) string

OpenOrders subscribes to user's open orders.

func (*Stream) OrderUpdates

func (s *Stream) OrderUpdates(user string, callback func(map[string]any)) string

OrderUpdates subscribes to user's order status changes.

func (*Stream) Orders

func (s *Stream) Orders(coins []string, callback func(map[string]any), users ...string) string

Orders subscribes to order stream.

func (*Stream) ReconnectAttempts

func (s *Stream) ReconnectAttempts() int

ReconnectAttempts returns the number of reconnection attempts since last successful connection.

func (*Stream) Run

func (s *Stream) Run() error

Run runs the stream (blocking).

func (*Stream) Start

func (s *Stream) Start() error

Start starts the stream in background.

func (*Stream) State

func (s *Stream) State() ConnectionState

State returns the current connection state.

func (*Stream) Stop

func (s *Stream) Stop()

Stop stops the stream.

func (*Stream) Subscribe

func (s *Stream) Subscribe(streamType StreamType, callback func(map[string]any), opts ...SubscribeOption) string

Subscribe subscribes to a stream type.

func (*Stream) TWAP

func (s *Stream) TWAP(coins []string, callback func(map[string]any)) string

TWAP subscribes to TWAP execution stream.

func (*Stream) TWAPStates

func (s *Stream) TWAPStates(user string, callback func(map[string]any)) string

TWAPStates subscribes to TWAP algorithm states.

func (*Stream) Trades

func (s *Stream) Trades(coins []string, callback func(map[string]any)) string

Trades subscribes to trade stream.

func (*Stream) Unsubscribe

func (s *Stream) Unsubscribe(subID string)

Unsubscribe unsubscribes from a stream.

func (*Stream) UserEvents

func (s *Stream) UserEvents(user string, callback func(map[string]any)) string

UserEvents subscribes to comprehensive user events (fills, funding, liquidations).

func (*Stream) UserFills

func (s *Stream) UserFills(user string, callback func(map[string]any)) string

UserFills subscribes to user's trade fills.

func (*Stream) UserFundings

func (s *Stream) UserFundings(user string, callback func(map[string]any)) string

UserFundings subscribes to user's funding payment updates.

func (*Stream) UserNonFundingLedger

func (s *Stream) UserNonFundingLedger(user string, callback func(map[string]any)) string

UserNonFundingLedger subscribes to user's ledger changes (deposits, withdrawals, transfers).

func (*Stream) UserTWAPHistory

func (s *Stream) UserTWAPHistory(user string, callback func(map[string]any)) string

UserTWAPHistory subscribes to TWAP execution history and status.

func (*Stream) UserTWAPSliceFills

func (s *Stream) UserTWAPSliceFills(user string, callback func(map[string]any)) string

UserTWAPSliceFills subscribes to individual TWAP order slice fills.

func (*Stream) WebData3

func (s *Stream) WebData3(user string, callback func(map[string]any)) string

WebData3 subscribes to aggregate user information for frontend use.

func (*Stream) WriterActions

func (s *Stream) WriterActions(callback func(map[string]any)) string

WriterActions subscribes to spot token transfers.

type StreamConfig

type StreamConfig struct {
	OnError       func(error)
	OnClose       func()
	OnOpen        func()
	OnReconnect   func(attempt int)
	OnStateChange func(ConnectionState)
	Reconnect     bool
	MaxReconnect  int
	PingInterval  time.Duration
}

StreamConfig holds configuration for WebSocket streaming.

func DefaultStreamConfig

func DefaultStreamConfig() *StreamConfig

DefaultStreamConfig returns default stream configuration.

type StreamType

type StreamType string

StreamType represents available WebSocket stream types.

const (
	// QuickNode-supported streams
	StreamTypeTrades        StreamType = "trades"
	StreamTypeOrders        StreamType = "orders"
	StreamTypeBookUpdates   StreamType = "book_updates"
	StreamTypeTWAP          StreamType = "twap"
	StreamTypeEvents        StreamType = "events"
	StreamTypeWriterActions StreamType = "writer_actions"

	// Public Hyperliquid API streams
	StreamTypeL2Book               StreamType = "l2Book"
	StreamTypeAllMids              StreamType = "allMids"
	StreamTypeCandle               StreamType = "candle"
	StreamTypeBBO                  StreamType = "bbo"
	StreamTypeOpenOrders           StreamType = "openOrders"
	StreamTypeOrderUpdates         StreamType = "orderUpdates"
	StreamTypeUserEvents           StreamType = "userEvents"
	StreamTypeUserFills            StreamType = "userFills"
	StreamTypeUserFundings         StreamType = "userFundings"
	StreamTypeUserNonFundingLedger StreamType = "userNonFundingLedgerUpdates"
	StreamTypeClearinghouseState   StreamType = "clearinghouseState"
	StreamTypeActiveAssetCtx       StreamType = "activeAssetCtx"
	StreamTypeActiveAssetData      StreamType = "activeAssetData"
	StreamTypeTWAPStates           StreamType = "twapStates"
	StreamTypeUserTWAPSliceFills   StreamType = "userTwapSliceFills"
	StreamTypeUserTWAPHistory      StreamType = "userTwapHistory"
	StreamTypeNotification         StreamType = "notification"
	StreamTypeWebData3             StreamType = "webData3"
)

type SubscribeOption

type SubscribeOption func(*subscribeParams)

SubscribeOption is an option for subscriptions.

func SubscribeWithCoins

func SubscribeWithCoins(coins ...string) SubscribeOption

SubscribeWithCoins filters by coins.

func SubscribeWithUsers

func SubscribeWithUsers(users ...string) SubscribeOption

SubscribeWithUsers filters by users.

type TIF

type TIF string

TIF represents time in force for orders.

const (
	TIFIOC    TIF = "ioc"    // Immediate or cancel
	TIFGTC    TIF = "gtc"    // Good till cancelled
	TIFALO    TIF = "alo"    // Add liquidity only (post-only)
	TIFMarket TIF = "market" // Market order (auto-price)
)

type TWAPOption

type TWAPOption func(*twapParams)

TWAPOption is an option for TWAP orders.

func TWAPWithRandomize

func TWAPWithRandomize(randomize bool) TWAPOption

TWAPWithRandomize enables/disables slice timing randomization.

func TWAPWithReduceOnly

func TWAPWithReduceOnly() TWAPOption

TWAPWithReduceOnly marks the TWAP as reduce-only.

type TpSl

type TpSl string

TpSl represents trigger order type (take profit or stop loss).

const (
	TpSlTP TpSl = "tp" // Take profit
	TpSlSL TpSl = "sl" // Stop loss
)

type TriggerOrderBuilder

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

TriggerOrderBuilder is a fluent builder for stop-loss and take-profit orders.

Examples:

// Stop loss: sell when price drops to 60000 (market)
TriggerOrder().StopLoss("BTC").Size(0.001).TriggerPrice(60000).Market()

// Stop loss: sell at limit 59900 when price drops to 60000
TriggerOrder().StopLoss("BTC").Size(0.001).TriggerPrice(60000).Limit(59900)

// Take profit: sell when price rises to 80000
TriggerOrder().TakeProfit("BTC").Size(0.001).TriggerPrice(80000).Market()

func TriggerOrder

func TriggerOrder() *TriggerOrderBuilder

TriggerOrder creates a new trigger order builder.

func (*TriggerOrderBuilder) Asset

func (t *TriggerOrderBuilder) Asset() string

Asset returns the order's asset.

func (*TriggerOrderBuilder) CLOID

CLOID sets the client order ID for tracking.

func (*TriggerOrderBuilder) GetLimitPrice

func (t *TriggerOrderBuilder) GetLimitPrice() string

GetLimitPrice returns the order's limit price.

func (*TriggerOrderBuilder) GetSide

func (t *TriggerOrderBuilder) GetSide() Side

GetSide returns the order's side.

func (*TriggerOrderBuilder) GetSize

func (t *TriggerOrderBuilder) GetSize() string

GetSize returns the order's size.

func (*TriggerOrderBuilder) GetTriggerPrice

func (t *TriggerOrderBuilder) GetTriggerPrice() string

GetTriggerPrice returns the order's trigger price.

func (*TriggerOrderBuilder) Limit

func (t *TriggerOrderBuilder) Limit(price any) *TriggerOrderBuilder

Limit sets the order to execute as a limit order when triggered.

func (*TriggerOrderBuilder) Market

Market sets the order to execute as a market order when triggered.

func (*TriggerOrderBuilder) ReduceOnly

func (t *TriggerOrderBuilder) ReduceOnly() *TriggerOrderBuilder

ReduceOnly marks the order as reduce-only (close position only).

func (*TriggerOrderBuilder) SL

SL is an alias for StopLoss.

func (*TriggerOrderBuilder) Side

Side sets the order side when triggered (default: SELL for closing longs).

func (*TriggerOrderBuilder) Size

Size sets the order size in asset units.

func (*TriggerOrderBuilder) StopLoss

func (t *TriggerOrderBuilder) StopLoss(asset string) *TriggerOrderBuilder

StopLoss creates a stop-loss trigger order.

Stop loss triggers when price moves against your position:

  • For longs: triggers when price FALLS to trigger_price (sell to exit)
  • For shorts: triggers when price RISES to trigger_price (buy to exit)

func (*TriggerOrderBuilder) String

func (t *TriggerOrderBuilder) String() string

String returns a string representation of the trigger order.

func (*TriggerOrderBuilder) TP

TP is an alias for TakeProfit.

func (*TriggerOrderBuilder) TakeProfit

func (t *TriggerOrderBuilder) TakeProfit(asset string) *TriggerOrderBuilder

TakeProfit creates a take-profit trigger order.

Take profit triggers when price moves in favor of your position:

  • For longs: triggers when price RISES to trigger_price (sell to take profits)
  • For shorts: triggers when price FALLS to trigger_price (buy to take profits)

func (*TriggerOrderBuilder) ToAction

func (t *TriggerOrderBuilder) ToAction(grouping OrderGrouping) map[string]any

ToAction converts the trigger order to an API action format.

func (*TriggerOrderBuilder) Trigger

func (t *TriggerOrderBuilder) Trigger(price any) *TriggerOrderBuilder

Trigger is an alias for TriggerPrice.

func (*TriggerOrderBuilder) TriggerPrice

func (t *TriggerOrderBuilder) TriggerPrice(price any) *TriggerOrderBuilder

TriggerPrice sets the price at which the order activates.

func (*TriggerOrderBuilder) Validate

func (t *TriggerOrderBuilder) Validate() error

Validate validates the trigger order before sending.

type TriggerOrderOption

type TriggerOrderOption func(*TriggerOrderBuilder)

TriggerOrderOption is an option for trigger order placement.

func TriggerWithGrouping

func TriggerWithGrouping(grouping OrderGrouping) TriggerOrderOption

TriggerWithGrouping sets the grouping for trigger order.

func TriggerWithLimitPrice

func TriggerWithLimitPrice(price any) TriggerOrderOption

TriggerWithLimitPrice sets the limit price for trigger order execution.

func TriggerWithSide

func TriggerWithSide(side Side) TriggerOrderOption

TriggerWithSide sets the side for trigger order execution.

type Wallet

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

Wallet wraps an Ethereum private key for signing operations.

func NewWallet

func NewWallet(privateKeyHex string) (*Wallet, error)

NewWallet creates a wallet from a hex-encoded private key. The private key can optionally include the "0x" prefix.

func (*Wallet) Address

func (w *Wallet) Address() common.Address

Address returns the wallet's Ethereum address.

func (*Wallet) AddressString

func (w *Wallet) AddressString() string

AddressString returns the wallet's Ethereum address as a hex string.

func (*Wallet) SignHash

func (w *Wallet) SignHash(hashHex string) (*Signature, error)

SignHash signs a 32-byte hash and returns the signature components. This is an "unsafe" sign that doesn't prefix the message - used for signing pre-computed hashes from the Hyperliquid build endpoint.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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