hyperliquid

package module
v1.0.36 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: MIT Imports: 33 Imported by: 0

README

Documentation

Overview

Package hyperliquid provides a Go client library for the Hyperliquid exchange API. It includes support for both REST API and WebSocket connections, allowing users to access market data, manage orders, and handle user account operations.

Index

Constants

View Source
const (
	MainnetAPIURL = "https://api.hyperliquid.xyz"
	TestnetAPIURL = "https://api.hyperliquid-testnet.xyz"
	LocalAPIURL   = "http://localhost:3001"
)
View Source
const (
	TifAlo = "Alo" // Add Liquidity Only
	TifIoc = "Ioc" // Immediate or Cancel
	TifGtc = "Gtc" // Good Till Cancel
)

Order Time-in-Force constants

View Source
const (
	DefaultSlippage = 0.05 // 5%
)

Constants for default values

Variables

This section is empty.

Functions

func FloatToUsdInt

func FloatToUsdInt(value float64) int

Utility function to convert float to USD integer representation

func GetTimestampMs

func GetTimestampMs() int64

GetTimestampMs returns current timestamp in milliseconds

func PriceToWire

func PriceToWire(x float64, asset int, info *Info, isSpot bool) (string, error)

PriceToWire converts a float64 price to a wire-compatible string format following Hyperliquid's price constraints: - Up to 5 significant figures - No more than MAX_DECIMALS - szDecimals decimal places - MAX_DECIMALS is 6 for perps, 8 for spot

Types

type APIError

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

func (APIError) Error

func (e APIError) Error() string

type APIResponse

type APIResponse[T any] struct {
	Status string
	Data   T
	Type   string
	Err    string
	Ok     bool
}

func (*APIResponse[T]) UnmarshalJSON

func (r *APIResponse[T]) UnmarshalJSON(data []byte) error

type AgentApprovalResponse

type AgentApprovalResponse struct {
	Status string `json:"status"`
	TxHash string `json:"txHash,omitempty"`
	Error  string `json:"error,omitempty"`
}

type ApprovalResponse

type ApprovalResponse struct {
	Status string `json:"status"`
	TxHash string `json:"txHash,omitempty"`
	Error  string `json:"error,omitempty"`
}

type ApproveAgentAction

type ApproveAgentAction struct {
	Type             string  `json:"type"                msgpack:"type"`
	HyperliquidChain string  `json:"hyperliquidChain"    msgpack:"hyperliquidChain"`
	SignatureChainId string  `json:"signatureChainId"    msgpack:"signatureChainId"`
	AgentAddress     string  `json:"agentAddress"        msgpack:"agentAddress"`
	AgentName        *string `json:"agentName,omitempty" msgpack:"agentName,omitempty"`
	Nonce            int64   `json:"nonce"               msgpack:"nonce"`
}

ApproveAgentAction represents approve agent action

type ApproveBuilderFeeAction

type ApproveBuilderFeeAction struct {
	Type             string `json:"type"             msgpack:"type"`
	HyperliquidChain string `json:"hyperliquidChain" msgpack:"hyperliquidChain"`
	SignatureChainId string `json:"signatureChainId" msgpack:"signatureChainId"`
	Builder          string `json:"builder"          msgpack:"builder"`
	MaxFeeRate       string `json:"maxFeeRate"       msgpack:"maxFeeRate"`
	Nonce            int64  `json:"nonce"            msgpack:"nonce"`
}

ApproveBuilderFeeAction represents approve builder fee action

type AssetCtx added in v1.0.22

type AssetCtx struct {
	DayNtlVlm    string   `json:"dayNtlVlm"`
	Funding      string   `json:"funding"`
	ImpactPxs    []string `json:"impactPxs"`
	MarkPx       string   `json:"markPx"`
	MidPx        string   `json:"midPx"`
	OpenInterest string   `json:"openInterest"`
	OraclePx     string   `json:"oraclePx"`
	Premium      string   `json:"premium"`
	PrevDayPx    string   `json:"prevDayPx"`
}

AssetCtx represents perpetual asset context data including mark price, funding, open interest, etc.

type AssetInfo

type AssetInfo struct {
	Name          string `json:"name"`
	SzDecimals    int    `json:"szDecimals"`
	MaxLeverage   int    `json:"maxLeverage"`
	MarginTableId int    `json:"marginTableId"`
	OnlyIsolated  bool   `json:"onlyIsolated"`
	IsDelisted    bool   `json:"isDelisted"`
}

type AssetPosition

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

type BatchModifyAction

type BatchModifyAction struct {
	Type     string         `json:"type"     msgpack:"type"`
	Dex      string         `json:"dex,omitempty" msgpack:"dex,omitempty"`
	Modifies []ModifyAction `json:"modifies" msgpack:"modifies"`
}

BatchModifyAction represents multiple order modifications

type BuilderInfo

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

type BulkCancelResponse

type BulkCancelResponse struct {
	Status string      `json:"status"`
	Data   []OpenOrder `json:"data,omitempty"`
	Error  string      `json:"error,omitempty"`
}

type BulkOrderResponse

type BulkOrderResponse struct {
	Status string        `json:"status"`
	Data   []OrderStatus `json:"data,omitempty"`
	Error  string        `json:"error,omitempty"`
}

type CancelAction

type CancelAction struct {
	Type    string            `json:"type"    msgpack:"type"`
	Dex     string            `json:"dex,omitempty" msgpack:"dex,omitempty"`
	Cancels []CancelOrderWire `json:"cancels" msgpack:"cancels"`
}

CancelAction represents the cancel action

type CancelByCloidAction

type CancelByCloidAction struct {
	Type    string              `json:"type"    msgpack:"type"`
	Dex     string              `json:"dex,omitempty" msgpack:"dex,omitempty"`
	Cancels []CancelByCloidWire `json:"cancels" msgpack:"cancels"`
}

CancelByCloidAction represents the cancel by cloid action

type CancelByCloidRequest

type CancelByCloidRequest struct {
	Coin  string `json:"coin"`
	Cloid string `json:"cloid"`
}

type CancelByCloidWire

type CancelByCloidWire struct {
	Asset    int    `json:"asset" msgpack:"asset"`
	ClientID string `json:"cloid" msgpack:"cloid"`
}

CancelByCloidWire represents cancel by cloid item wire format NB: the CancelByCloidWire MUST have `asset` and not `a` like CancelOrderWire See: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/master/hyperliquid/exchange.py

type CancelOrderRequest

type CancelOrderRequest struct {
	Coin    string
	OrderID int64
}

type CancelOrderRequestByCloid

type CancelOrderRequestByCloid struct {
	Coin  string
	Cloid string
}

type CancelOrderResponse

type CancelOrderResponse struct {
	Statuses MixedArray
}

type CancelOrderWire

type CancelOrderWire struct {
	Asset   int   `json:"a" msgpack:"a"`
	OrderID int64 `json:"o" msgpack:"o"`
}

CancelOrderWire represents cancel order item wire format

type CancelRequest

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

type CancelResponse

type CancelResponse struct {
	Status string     `json:"status"`
	Data   *OpenOrder `json:"data,omitempty"`
	Error  string     `json:"error,omitempty"`
}

type Candle

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

type Client

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

func NewClient

func NewClient(baseURL string) *Client

type Cloid

type Cloid struct {
	Value string
}

func (Cloid) ToRaw

func (c Cloid) ToRaw() string

type ConvertToMultiSigUserAction

type ConvertToMultiSigUserAction struct {
	Type             string `json:"type"             msgpack:"type"`
	HyperliquidChain string `json:"hyperliquidChain" msgpack:"hyperliquidChain"`
	SignatureChainId string `json:"signatureChainId" msgpack:"signatureChainId"`
	Signers          string `json:"signers"          msgpack:"signers"`
	Nonce            int64  `json:"nonce"            msgpack:"nonce"`
}

ConvertToMultiSigUserAction represents convert to multi-sig user action

type CreateOrderRequest

type CreateOrderRequest struct {
	Coin          string
	IsBuy         bool
	Price         float64
	Size          float64
	ReduceOnly    bool
	OrderType     OrderType
	ClientOrderID *string
}

type CreateSubAccountAction

type CreateSubAccountAction struct {
	Type string `json:"type" msgpack:"type"`
	Name string `json:"name" msgpack:"name"`
}

CreateSubAccountAction represents create sub-account action

type CreateSubAccountResponse

type CreateSubAccountResponse struct {
	Status string      `json:"status"`
	Data   *SubAccount `json:"data,omitempty"`
	Error  string      `json:"error,omitempty"`
}

type DefaultResponse added in v1.0.19

type DefaultResponse struct {
	Type string `json:"type"`
}

DefaultResponse represents a simple API response with type "default"

type EvmContract

type EvmContract struct {
	Address             string `json:"address"`
	EvmExtraWeiDecimals int    `json:"evm_extra_wei_decimals"`
}

type Exchange

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

func NewExchange

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

NewExchange creates a new Exchange instance. perpDexs is optional - pass nil for the default perp dex. perpDexName is optional - set to empty string for the default perp dex, or provide a builder dex name (e.g., "flx") for HIP-3 builder-deployed perps.

func (*Exchange) ApproveAgent

func (e *Exchange) ApproveAgent(name *string) (*AgentApprovalResponse, string, error)

ApproveAgent approves an agent to trade on behalf of the user Returns the result and the generated agent private key

func (*Exchange) ApproveBuilderFee

func (e *Exchange) ApproveBuilderFee(builder string, maxFeeRate string) (*ApprovalResponse, error)

ApproveBuilderFee approves builder fee payment using Python bridge for 100% signature compatibility

func (*Exchange) BulkCancel

func (e *Exchange) BulkCancel(
	requests []CancelOrderRequest,
) (res *APIResponse[CancelOrderResponse], err error)

func (*Exchange) BulkCancelByCloids

func (e *Exchange) BulkCancelByCloids(
	requests []CancelOrderRequestByCloid,
) (res *APIResponse[CancelOrderResponse], err error)

func (*Exchange) BulkModifyOrders

func (e *Exchange) BulkModifyOrders(
	modifyRequests []ModifyOrderRequest,
) ([]OrderStatus, error)

BulkModifyOrders modifies multiple orders

func (*Exchange) BulkOrders

func (e *Exchange) BulkOrders(
	orders []CreateOrderRequest,
	builder *BuilderInfo,
) (result *APIResponse[OrderResponse], err error)

func (*Exchange) BulkOrdersWithGrouping

func (e *Exchange) BulkOrdersWithGrouping(
	orders []CreateOrderRequest,
	grouping Grouping,
	builder *BuilderInfo,
) (result *APIResponse[OrderResponse], err error)

BulkOrdersWithGrouping places multiple orders in a single action with the provided grouping

func (*Exchange) CSignerInner

func (e *Exchange) CSignerInner(innerAction map[string]any) (*ValidatorResponse, error)

CSignerInner executes inner consensus signer action

func (*Exchange) CSignerJailSelf

func (e *Exchange) CSignerJailSelf() (*ValidatorResponse, error)

CSignerJailSelf jails self as consensus signer

func (*Exchange) CSignerUnjailSelf

func (e *Exchange) CSignerUnjailSelf() (*ValidatorResponse, error)

CSignerUnjailSelf unjails self as consensus signer

func (*Exchange) CValidatorChangeProfile

func (e *Exchange) CValidatorChangeProfile(newProfile map[string]any) (*ValidatorResponse, error)

CValidatorChangeProfile changes validator profile

func (*Exchange) CValidatorRegister

func (e *Exchange) CValidatorRegister(validatorProfile map[string]any) (*ValidatorResponse, error)

CValidatorRegister registers as consensus validator

func (*Exchange) CValidatorUnregister

func (e *Exchange) CValidatorUnregister() (*ValidatorResponse, error)

CValidatorUnregister unregisters as consensus validator

func (*Exchange) Cancel

func (e *Exchange) Cancel(
	coin string,
	oid int64,
) (res *APIResponse[CancelOrderResponse], err error)

func (*Exchange) CancelByCloid

func (e *Exchange) CancelByCloid(
	coin, cloid string,
) (res *APIResponse[CancelOrderResponse], err error)

func (*Exchange) ConvertToMultiSigUser

func (e *Exchange) ConvertToMultiSigUser(
	authorizedUsers []string,
	threshold int,
) (*MultiSigConversionResponse, error)

ConvertToMultiSigUser converts account to multi-signature user

func (*Exchange) CreateSubAccount

func (e *Exchange) CreateSubAccount(name string) (*CreateSubAccountResponse, error)

CreateSubAccount creates a new sub-account

func (*Exchange) GetAccountAddr

func (e *Exchange) GetAccountAddr() string

GetAccountAddr returns the account address

func (*Exchange) GetAssetTickSize added in v1.0.13

func (e *Exchange) GetAssetTickSize(assetName string) float64

GetAssetTickSize returns the tick size for a specific asset This uses the API metadata to dynamically calculate tick sizes

func (*Exchange) GetInfo

func (e *Exchange) GetInfo() *Info

GetInfo returns the info instance

func (*Exchange) MarketClose

func (e *Exchange) MarketClose(
	coin string,
	sz *float64,
	px *float64,
	slippage float64,
	cloid *string,
	builder *BuilderInfo,
) (OrderStatus, error)

MarketClose closes a position

func (*Exchange) MarketOpen

func (e *Exchange) MarketOpen(
	name string,
	isBuy bool,
	sz float64,
	px *float64,
	slippage float64,
	cloid *string,
	builder *BuilderInfo,
) (res OrderStatus, err error)

MarketOpen opens a market position

func (*Exchange) MarketOpenWithSLTP

func (e *Exchange) MarketOpenWithSLTP(
	name string,
	isBuy bool,
	sz float64,
	px *float64,
	slippage float64,
	tpslPercent float64,
	isTP bool,
	cloidOpen *string,
	cloidTPSL *string,
	builder *BuilderInfo,
) (result *APIResponse[OrderResponse], err error)

MarketOpenWithSLTP opens a position and places either a Stop-Loss (isTP=false) or Take-Profit (isTP=true) trigger in a single grouped action. The trigger is reduce-only and market-on-trigger. Full-position size is used for the trigger. For partial size, use MarketOpenWithSLTPPartial.

func (*Exchange) MarketOpenWithSLTPPartial

func (e *Exchange) MarketOpenWithSLTPPartial(
	name string,
	isBuy bool,
	sz float64,
	px *float64,
	slippage float64,
	tpslPercent float64,
	isTP bool,
	tpslSize *float64,
	cloidOpen *string,
	cloidTPSL *string,
	builder *BuilderInfo,
) (result *APIResponse[OrderResponse], err error)

MarketOpenWithSLTPPartial is like MarketOpenWithSLTP but allows specifying a partial TP/SL size via tpslSize. If tpslSize is nil, the trigger uses the full position size.

func (*Exchange) ModifyOrder

func (e *Exchange) ModifyOrder(
	req ModifyOrderRequest,
) (result OrderStatus, err error)

ModifyOrder modifies an existing order

func (*Exchange) MultiSig

func (e *Exchange) MultiSig(
	action map[string]any,
	signers []string,
	signatures []string,
) (*MultiSigResponse, error)

func (*Exchange) NewCreateOrderActionWithGrouping added in v1.0.34

func (e *Exchange) NewCreateOrderActionWithGrouping(
	orders []CreateOrderRequest,
	info *BuilderInfo,
	grouping Grouping,
) (OrderAction, error)

NewCreateOrderActionWithGrouping is the public wrapper for creating order actions This is useful for WebSocket POST requests where you need the action before signing

func (*Exchange) Order

func (e *Exchange) Order(
	req CreateOrderRequest,
	builder *BuilderInfo,
) (result OrderStatus, err error)

func (*Exchange) PerpDeployRegisterAsset

func (e *Exchange) PerpDeployRegisterAsset(
	asset string,
	perpDexInput PerpDexSchemaInput,
) (*PerpDeployResponse, error)

PerpDeployRegisterAsset registers a new perpetual asset

func (*Exchange) PerpDeploySetOracle

func (e *Exchange) PerpDeploySetOracle(
	asset string,
	oracleAddress string,
) (*SpotDeployResponse, error)

PerpDeploySetOracle sets oracle for perpetual asset

func (*Exchange) PerpDex added in v1.0.36

func (e *Exchange) PerpDex() string

PerpDex returns the configured builder perp dex name (e.g. "flx"), or empty string for default dex.

func (*Exchange) PerpDexClassTransfer

func (e *Exchange) PerpDexClassTransfer(
	dex, token string,
	amount float64,
	toPerp bool,
) (*TransferResponse, error)

PerpDexClassTransfer transfers tokens between perp dex classes

func (*Exchange) ScheduleCancel

func (e *Exchange) ScheduleCancel(scheduleTime *int64) (*ScheduleCancelResponse, error)

ScheduleCancel schedules cancellation of all open orders

func (*Exchange) SetExpiresAfter

func (e *Exchange) SetExpiresAfter(expiresAfter *int64)

SetExpiresAfter sets the expiration time for actions If expiresAfter is nil, actions will not have an expiration time If expiresAfter is set, actions will include this expiration timestamp

func (*Exchange) SetReferrer

func (e *Exchange) SetReferrer(code string) (*SetReferrerResponse, error)

SetReferrer sets a referral code

func (*Exchange) SlippagePrice

func (e *Exchange) SlippagePrice(
	name string,
	isBuy bool,
	slippage float64,
	px *float64,
) (float64, error)

SlippagePrice calculates the slippage price for market orders

func (*Exchange) SpotDeployEnableFreezePrivilege

func (e *Exchange) SpotDeployEnableFreezePrivilege() (*SpotDeployResponse, error)

SpotDeployEnableFreezePrivilege enables freeze privilege for spot deployer

func (*Exchange) SpotDeployFreezeUser

func (e *Exchange) SpotDeployFreezeUser(userAddress string) (*SpotDeployResponse, error)

SpotDeployFreezeUser freezes a user in spot trading

func (*Exchange) SpotDeployGenesis

func (e *Exchange) SpotDeployGenesis(deployer string, dexName string) (*SpotDeployResponse, error)

SpotDeployGenesis initializes spot genesis

func (*Exchange) SpotDeployRegisterHyperliquidity

func (e *Exchange) SpotDeployRegisterHyperliquidity(
	name string,
	tokens []string,
) (*SpotDeployResponse, error)

SpotDeployRegisterHyperliquidity registers hyperliquidity spot

func (*Exchange) SpotDeployRegisterSpot

func (e *Exchange) SpotDeployRegisterSpot(
	baseToken string,
	quoteToken string,
) (*SpotDeployResponse, error)

SpotDeployRegisterSpot registers spot market

func (*Exchange) SpotDeployRegisterToken

func (e *Exchange) SpotDeployRegisterToken(
	tokenName string,
	szDecimals int,
	weiDecimals int,
	maxGas int,
	fullName string,
) (*SpotDeployResponse, error)

SpotDeployRegisterToken registers a new spot token

func (*Exchange) SpotDeployRevokeFreezePrivilege

func (e *Exchange) SpotDeployRevokeFreezePrivilege() (*SpotDeployResponse, error)

SpotDeployRevokeFreezePrivilege revokes freeze privilege for spot deployer

func (*Exchange) SpotDeploySetDeployerTradingFeeShare

func (e *Exchange) SpotDeploySetDeployerTradingFeeShare(
	feeShare float64,
) (*SpotDeployResponse, error)

SpotDeploySetDeployerTradingFeeShare sets deployer trading fee share

func (*Exchange) SpotDeployUserGenesis

func (e *Exchange) SpotDeployUserGenesis(balances map[string]float64) (*SpotDeployResponse, error)

SpotDeployUserGenesis initializes user genesis for spot trading

func (*Exchange) SpotTransfer

func (e *Exchange) SpotTransfer(
	amount float64,
	destination, token string,
) (*TransferResponse, error)

SpotTransfer transfers spot tokens to another address

func (*Exchange) SubAccountSpotTransfer

func (e *Exchange) SubAccountSpotTransfer(
	subAccountUser string,
	isDeposit bool,
	token string,
	amount float64,
) (*TransferResponse, error)

SubAccountSpotTransfer transfers spot tokens to/from sub-account

func (*Exchange) SubAccountTransfer

func (e *Exchange) SubAccountTransfer(
	subAccountUser string,
	isDeposit bool,
	usd int,
) (*TransferResponse, error)

SubAccountTransfer transfers funds to/from sub-account

func (*Exchange) TokenDelegate

func (e *Exchange) TokenDelegate(
	validator string,
	wei int,
	isUndelegate bool,
) (*TransferResponse, error)

TokenDelegate delegates tokens for staking

func (*Exchange) UpdateIsolatedMargin

func (e *Exchange) UpdateIsolatedMargin(amount float64, name string) (*APIResponse[DefaultResponse], error)

func (*Exchange) UpdateLeverage

func (e *Exchange) UpdateLeverage(leverage int, name string, isCross bool) (*UserState, error)

func (*Exchange) UsdClassTransfer

func (e *Exchange) UsdClassTransfer(amount float64, toPerp bool) (*TransferResponse, error)

UsdClassTransfer transfers between USD classes

func (*Exchange) UsdTransfer

func (e *Exchange) UsdTransfer(amount float64, destination string) (*TransferResponse, error)

UsdTransfer transfers USD to another address

func (*Exchange) UseBigBlocks

func (e *Exchange) UseBigBlocks(enable bool) (*ApprovalResponse, error)

UseBigBlocks enables or disables big blocks

func (*Exchange) ValidatePriceForAsset added in v1.0.13

func (e *Exchange) ValidatePriceForAsset(price float64, assetName string) (float64, error)

ValidatePriceForAsset ensures a price meets tick size requirements for a specific asset This can be called before placing orders to prevent tick size errors

func (*Exchange) ValidateTPSLPrice added in v1.0.14

func (e *Exchange) ValidateTPSLPrice(price float64, assetName string, isTP bool) (float64, error)

ValidateTPSLPrice validates price specifically for TP/SL trigger orders TP/SL orders have different price validation requirements than regular orders

func (*Exchange) VaultUsdTransfer

func (e *Exchange) VaultUsdTransfer(
	vaultAddress string,
	isDeposit bool,
	usd int,
) (*TransferResponse, error)

VaultUsdTransfer transfers to/from vault

func (*Exchange) WithdrawFromBridge

func (e *Exchange) WithdrawFromBridge(
	amount float64,
	destination string,
) (*TransferResponse, error)

WithdrawFromBridge withdraws tokens from bridge using Python bridge for 100% signature compatibility

type FeeSchedule

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

type Fill

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

type FrontendOpenOrder

type FrontendOpenOrder struct {
	Coin             string  `json:"coin"`
	IsPositionTpsl   bool    `json:"isPositionTpsl"`
	IsTrigger        bool    `json:"isTrigger"`
	LimitPx          float64 `json:"limitPx,string"`
	Oid              int64   `json:"oid"`
	OrderType        string  `json:"orderType"`
	OrigSz           float64 `json:"origSz,string"`
	ReduceOnly       bool    `json:"reduceOnly"`
	Side             string  `json:"side"`
	Size             float64 `json:"sz,string"`
	Timestamp        int64   `json:"timestamp"`
	TriggerCondition string  `json:"triggerCondition"`
	TriggerPx        float64 `json:"triggerPx,string"`
}

FrontendOpenOrder represents the detailed order information returned by frontendOpenOrders

type FundingHistory

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

type Grouping

type Grouping string
const (
	GroupingNA           Grouping = "na"
	GroupingNormalTpsl   Grouping = "normalTpsl"
	GroupingPositionTpls Grouping = "positionTpsl"
)

type Info

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

func NewInfo

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

NewInfo creates a new Info instance. perpDexName is optional - set to empty string for the default perp dex, or provide a builder dex name (e.g., "flx") for HIP-3 builder-deployed perps.

func (*Info) AllMids

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

AllMids retrieves mids for all coins If dex is empty string, returns mids for the first perp dex (default) Note: Spot mids are only included with the first perp dex

func (*Info) CandlesSnapshot

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

func (*Info) FrontendOpenOrders

func (i *Info) FrontendOpenOrders(address string, dex ...string) ([]FrontendOpenOrder, error)

FrontendOpenOrders retrieves user's open orders with frontend info If dex is empty string, returns orders for the first perp dex (default) Note: Spot open orders are only included with the first perp dex

func (*Info) FundingHistory

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

func (*Info) L2Snapshot

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

func (*Info) Meta

func (i *Info) Meta(dex ...string) (*Meta, error)

Meta retrieves perpetuals metadata If dex is empty string, returns metadata for the first perp dex (default)

func (*Info) MetaAndAssetCtxs

func (i *Info) MetaAndAssetCtxs() (*MetaAndAssetCtxsResponse, error)

func (*Info) NameToAsset

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

func (*Info) OpenOrders

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

OpenOrders retrieves user's open orders If dex is empty string, returns orders for the first perp dex (default) Note: Spot open orders are only included with the first perp dex

func (*Info) PerpDexName added in v1.0.36

func (i *Info) PerpDexName() string

PerpDexName returns the configured builder perp dex name (e.g. "flx"), or empty string for default dex.

func (*Info) PerpDexs

func (i *Info) PerpDexs() (MixedArray, error)

PerpDexs returns the list of available perpetual dexes Returns an array where each element can be nil (for the default dex) or a PerpDex object The first element is always null (representing the default dex)

func (*Info) QueryFillByOid added in v1.0.11

func (i *Info) QueryFillByOid(user string, oid int64) (*Fill, error)

QueryFillByOid finds a specific fill by OID from user fills Since there's no direct fill query endpoint, we filter userFills by OID

func (*Info) QueryOrderByCloid

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

func (*Info) QueryOrderByOid

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

func (*Info) QueryReferralState

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

func (*Info) QuerySubAccounts

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

func (*Info) QueryUserToMultiSigSigners

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

func (*Info) SpotMeta

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

func (*Info) SpotMetaAndAssetCtxs

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

func (*Info) SpotUserState

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

func (*Info) UserFees

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

func (*Info) UserFills

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

func (*Info) UserFillsByTime

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

func (*Info) UserFundingHistory

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

func (*Info) UserStakingDelegations

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

func (*Info) UserStakingRewards

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

func (*Info) UserStakingSummary

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

func (*Info) UserState

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

UserState retrieves user's perpetuals account summary If dex is empty string, returns state for the first perp dex (default)

type L2Book

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

type Level

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

type Leverage

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

type LimitOrderType

type LimitOrderType struct {
	Tif string `json:"tif"` // TifAlo, TifIoc, TifGtc
}

type LimitOrderTypeWire

type LimitOrderTypeWire struct {
	Tif string `json:"tif" msgpack:"tif"` // TifAlo, TifIoc, TifGtc
}

type MMTier

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

type MarginSummary

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

type MarginTable added in v1.0.22

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

MarginTable represents a margin table with description and tiers

type MarginTier added in v1.0.22

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

MarginTier represents a single margin tier

type Meta

type Meta struct {
	Universe        []AssetInfo   `json:"universe"`
	MarginTables    []MarginTable `json:"marginTables"`
	CollateralToken int           `json:"collateralToken"`
}

type MetaAndAssetCtxsRawResponse added in v1.0.22

type MetaAndAssetCtxsRawResponse [2]interface{}

MetaAndAssetCtxsRawResponse represents the raw array response from the API

type MetaAndAssetCtxsResponse added in v1.0.22

type MetaAndAssetCtxsResponse struct {
	Meta      Meta       `json:"universe"`
	AssetCtxs []AssetCtx `json:"assetCtxs"`
}

MetaAndAssetCtxsResponse represents the response from the metaAndAssetCtxs endpoint The API returns an array with two elements: [meta, assetCtxs]

type MixedArray

type MixedArray []MixedValue

func (*MixedArray) UnmarshalJSON

func (ma *MixedArray) UnmarshalJSON(data []byte) error

type MixedValue

type MixedValue json.RawMessage

func (*MixedValue) Array

func (mv *MixedValue) Array() ([]json.RawMessage, bool)

func (MixedValue) MarshalJSON

func (mv MixedValue) MarshalJSON() ([]byte, error)

func (*MixedValue) Object

func (mv *MixedValue) Object() (map[string]any, bool)

func (*MixedValue) Parse

func (mv *MixedValue) Parse(v any) error

func (*MixedValue) String

func (mv *MixedValue) String() (string, bool)

func (*MixedValue) Type

func (mv *MixedValue) Type() string

func (*MixedValue) UnmarshalJSON

func (mv *MixedValue) UnmarshalJSON(data []byte) error

type ModifyAction

type ModifyAction struct {
	Type  string    `json:"type,omitempty"  msgpack:"type,omitempty"`
	Dex   string    `json:"dex,omitempty"   msgpack:"dex,omitempty"`
	Oid   any       `json:"oid"             msgpack:"oid"`
	Order OrderWire `json:"order"           msgpack:"order"`
}

ModifyAction represents a single order modification

type ModifyOrderRequest

type ModifyOrderRequest struct {
	Oid   any // can be int64 or Cloid
	Order CreateOrderRequest
}

type ModifyResponse

type ModifyResponse struct {
	Status string        `json:"status"`
	Data   []OrderStatus `json:"data,omitempty"`
	Error  string        `json:"error,omitempty"`
}

type MultiSigAction

type MultiSigAction struct {
	Type       string         `json:"type"       msgpack:"type"`
	Action     map[string]any `json:"action"     msgpack:"action"`
	Signers    []string       `json:"signers"    msgpack:"signers"`
	Signatures []string       `json:"signatures" msgpack:"signatures"`
}

MultiSigAction represents multi-signature action

type MultiSigConversionResponse

type MultiSigConversionResponse struct {
	Status string `json:"status"`
	TxHash string `json:"txHash,omitempty"`
	Error  string `json:"error,omitempty"`
}

type MultiSigResponse

type MultiSigResponse struct {
	Status string `json:"status"`
	TxHash string `json:"txHash,omitempty"`
	Error  string `json:"error,omitempty"`
}

type MultiSigSigner

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

type OpenOrder

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

type OrderAction

type OrderAction struct {
	Type     string       `json:"type"              msgpack:"type"`
	Dex      string       `json:"dex,omitempty"     msgpack:"dex,omitempty"`
	Orders   []OrderWire  `json:"orders"            msgpack:"orders"`
	Grouping string       `json:"grouping"          msgpack:"grouping"`
	Builder  *BuilderInfo `json:"builder,omitempty" msgpack:"builder,omitempty"`
}

OrderAction represents the order action with deterministic field ordering CRITICAL: Field order MUST match Python SDK insertion order for msgpack hash consistency

type OrderResponse

type OrderResponse struct {
	Statuses MixedArray `json:"statuses"`
}

type OrderStatus

type OrderStatus struct {
	Resting *OrderStatusResting `json:"resting,omitempty"`
	Filled  *OrderStatusFilled  `json:"filled,omitempty"`
	Error   *string             `json:"error,omitempty"`
}

type OrderStatusFilled

type OrderStatusFilled struct {
	TotalSz string `json:"totalSz"`
	AvgPx   string `json:"avgPx"`
	Oid     int    `json:"oid"`
}

type OrderStatusResponse added in v1.0.12

type OrderStatusResponse struct {
	Status string `json:"status"`
	Order  struct {
		Order struct {
			Coin             string  `json:"coin"`
			Side             string  `json:"side"`
			LimitPx          string  `json:"limitPx"`
			Sz               string  `json:"sz"`
			Oid              int64   `json:"oid"`
			Timestamp        int64   `json:"timestamp"`
			TriggerCondition string  `json:"triggerCondition"`
			IsTrigger        bool    `json:"isTrigger"`
			TriggerPx        string  `json:"triggerPx"`
			Children         []any   `json:"children"`
			IsPositionTpsl   bool    `json:"isPositionTpsl"`
			ReduceOnly       bool    `json:"reduceOnly"`
			OrderType        string  `json:"orderType"`
			OrigSz           string  `json:"origSz"`
			Tif              *string `json:"tif"`
			Cloid            *string `json:"cloid"`
		} `json:"order"`
		Status          string `json:"status"`
		StatusTimestamp int64  `json:"statusTimestamp"`
	} `json:"order"`
}

OrderStatusResponse represents the actual response from the orderStatus endpoint

type OrderStatusResting

type OrderStatusResting struct {
	Oid      int64  `json:"oid"`
	ClientID string `json:"cid"`
	Status   string `json:"status"`
}

type OrderType

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

type OrderTypeWire

type OrderTypeWire struct {
	Limit   *LimitOrderTypeWire   `json:"limit,omitempty" msgpack:"limit,omitempty"`
	Trigger *TriggerOrderTypeWire `json:"trigger,omitempty" msgpack:"trigger,omitempty"`
}

Wire format types for order types (used in actions.go)

type OrderWire

type OrderWire struct {
	Asset      int           `json:"a"           msgpack:"a"`
	IsBuy      bool          `json:"b"           msgpack:"b"`
	LimitPx    string        `json:"p"           msgpack:"p"`
	Size       string        `json:"s"           msgpack:"s"`
	ReduceOnly bool          `json:"r"           msgpack:"r"`
	OrderType  OrderTypeWire `json:"t"           msgpack:"t"`
	Cloid      *string       `json:"c,omitempty" msgpack:"c,omitempty"`
}

OrderWire represents the wire format for orders with deterministic field ordering

type PerpDeployAuctionStatus added in v1.0.36

type PerpDeployAuctionStatus struct {
	StartTimeSeconds int64   `json:"startTimeSeconds"`
	DurationSeconds  int64   `json:"durationSeconds"`
	StartGas         string  `json:"startGas"`
	CurrentGas       string  `json:"currentGas"`
	EndGas           *string `json:"endGas"`
}

PerpDeployAuctionStatus represents the status of a perp deploy auction

type PerpDeployResponse

type PerpDeployResponse struct {
	Status string `json:"status"`
	Data   struct {
		Statuses []TxStatus `json:"statuses"`
	} `json:"data"`
}

type PerpDex added in v1.0.36

type PerpDex struct {
	Name                     string     `json:"name"`
	FullName                 string     `json:"fullName"`
	Deployer                 string     `json:"deployer"`
	OracleUpdater            *string    `json:"oracleUpdater"`
	FeeRecipient             *string    `json:"feeRecipient"`
	AssetToStreamingOiCap    [][]string `json:"assetToStreamingOiCap"`    // Array of [coin, cap] tuples
	AssetToFundingMultiplier [][]string `json:"assetToFundingMultiplier"` // Array of [coin, multiplier] tuples
}

PerpDex represents a perpetual DEX

type PerpDexClassTransferAction

type PerpDexClassTransferAction struct {
	Type   string  `json:"type"   msgpack:"type"`
	Dex    string  `json:"dex"    msgpack:"dex"`
	Token  string  `json:"token"  msgpack:"token"`
	Amount float64 `json:"amount" msgpack:"amount"`
	ToPerp bool    `json:"toPerp" msgpack:"toPerp"`
}

PerpDexClassTransferAction represents perp dex class transfer

type PerpDexLimits added in v1.0.36

type PerpDexLimits struct {
	TotalOiCap     string     `json:"totalOiCap"`
	OiSzCapPerPerp string     `json:"oiSzCapPerPerp"`
	MaxTransferNtl string     `json:"maxTransferNtl"`
	CoinToOiCap    [][]string `json:"coinToOiCap"` // Array of [coin, cap] tuples
}

PerpDexLimits represents limits for a builder-deployed perp DEX

type PerpDexSchemaInput

type PerpDexSchemaInput struct {
	FullName        string  `json:"fullName"`
	CollateralToken int     `json:"collateralToken"`
	OracleUpdater   *string `json:"oracleUpdater"`
}

type PerpDexStatus added in v1.0.36

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

PerpDexStatus represents status for a builder-deployed perp DEX

type Position

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

type ReferralMember added in v1.0.5

type ReferralMember struct {
	CumVlm                       string `json:"cumVlm"`
	CumRewardedFeesSinceReferred string `json:"cumRewardedFeesSinceReferred"`
	CumFeesRewardedToReferrer    string `json:"cumFeesRewardedToReferrer"`
	TimeJoined                   int64  `json:"timeJoined"`
	User                         string `json:"user"`
}

type ReferralState

type ReferralState struct {
	ReferredBy       *ReferredBy    `json:"referredBy,omitempty"`
	CumVlm           string         `json:"cumVlm"`
	UnclaimedRewards string         `json:"unclaimedRewards"`
	ClaimedRewards   string         `json:"claimedRewards"`
	BuilderRewards   string         `json:"builderRewards"`
	ReferrerState    *ReferrerState `json:"referrerState,omitempty"`
	RewardHistory    []interface{}  `json:"rewardHistory"`
}

type ReferredBy added in v1.0.5

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

type ReferrerData added in v1.0.5

type ReferrerData struct {
	Code           string           `json:"code"`
	ReferralStates []ReferralMember `json:"referralStates"`
}

type ReferrerState added in v1.0.5

type ReferrerState struct {
	Stage string        `json:"stage"`
	Data  *ReferrerData `json:"data,omitempty"`
}

type ReserveRequestWeightAction

type ReserveRequestWeightAction struct {
	Type   string `json:"type"   msgpack:"type"`
	Weight int    `json:"weight" msgpack:"weight"`
}

ReserveRequestWeightAction represents reserve request weight action

type ScheduleCancelAction

type ScheduleCancelAction struct {
	Type string `json:"type"           msgpack:"type"`
	Time *int64 `json:"time,omitempty" msgpack:"time,omitempty"`
}

ScheduleCancelAction represents schedule cancel action

type ScheduleCancelResponse

type ScheduleCancelResponse struct {
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

type SetReferrerAction

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

SetReferrerAction represents set referrer action

type SetReferrerResponse

type SetReferrerResponse struct {
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

type Side

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

type SignatureResult

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

SignatureResult represents the structured signature result

func SignAgent

func SignAgent(
	privateKey *ecdsa.PrivateKey,
	agentAddress, agentName string,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignAgent signs agent approval action

func SignApproveBuilderFee

func SignApproveBuilderFee(
	privateKey *ecdsa.PrivateKey,
	builderAddress string,
	maxFeeRate float64,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignApproveBuilderFee signs approve builder fee action

func SignConvertToMultiSigUserAction

func SignConvertToMultiSigUserAction(
	privateKey *ecdsa.PrivateKey,
	signers []string,
	threshold int,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignConvertToMultiSigUserAction signs convert to multi-sig user action

func SignL1Action

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

SignL1Action implements the same logic as Python's sign_l1_action

func SignMultiSigAction

func SignMultiSigAction(
	privateKey *ecdsa.PrivateKey,
	innerAction map[string]any,
	signers []string,
	signatures []string,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignMultiSigAction signs multi-signature action

func SignPerpDexClassTransferAction

func SignPerpDexClassTransferAction(
	privateKey *ecdsa.PrivateKey,
	dex, token string,
	amount float64,
	toPerp bool,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignPerpDexClassTransferAction signs perp dex class transfer action

func SignSpotTransferAction

func SignSpotTransferAction(
	privateKey *ecdsa.PrivateKey,
	amount float64,
	destination, token string,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignSpotTransferAction signs spot transfer action

func SignTokenDelegateAction

func SignTokenDelegateAction(
	privateKey *ecdsa.PrivateKey,
	token string,
	amount float64,
	validatorAddress string,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignTokenDelegateAction signs token delegate action

func SignUsdClassTransferAction

func SignUsdClassTransferAction(
	privateKey *ecdsa.PrivateKey,
	amount float64,
	toPerp bool,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignUsdClassTransferAction signs USD class transfer action

func SignUsdTransferAction

func SignUsdTransferAction(
	privateKey *ecdsa.PrivateKey,
	amount float64,
	destination string,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignUsdTransferAction signs USD transfer action

func SignWithdrawFromBridgeAction

func SignWithdrawFromBridgeAction(
	privateKey *ecdsa.PrivateKey,
	destination string,
	amount, fee float64,
	timestamp int64,
	isMainnet bool,
) (SignatureResult, error)

SignWithdrawFromBridgeAction signs withdraw from bridge action

type SpotAssetCtx

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

type SpotAssetInfo

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

type SpotBalance added in v1.0.20

type SpotBalance struct {
	Coin     string `json:"coin"`
	Token    int    `json:"token"`
	Hold     string `json:"hold"`
	Total    string `json:"total"`
	EntryNtl string `json:"entryNtl"`
}

SpotBalance represents a single spot token balance entry returned by the spotClearinghouseState endpoint.

type SpotClearinghouseState added in v1.0.20

type SpotClearinghouseState struct {
	Balances []SpotBalance `json:"balances"`
}

SpotClearinghouseState is the response model for the spot balances endpoint.

type SpotDeployResponse

type SpotDeployResponse struct {
	Status string `json:"status"`
	TxHash string `json:"txHash,omitempty"`
	Error  string `json:"error,omitempty"`
}

type SpotMeta

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

type SpotTokenInfo

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

type SpotTransferAction

type SpotTransferAction struct {
	Type        string `json:"type"        msgpack:"type"`
	Destination string `json:"destination" msgpack:"destination"`
	Amount      string `json:"amount"      msgpack:"amount"`
	Token       string `json:"token"       msgpack:"token"`
	Time        int64  `json:"time"        msgpack:"time"`
}

SpotTransferAction represents spot transfer

type StakingDelegation

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

type StakingReward

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

type StakingSummary

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

type SubAccount

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

type SubAccountSpotTransferAction

type SubAccountSpotTransferAction struct {
	Type           string  `json:"type"           msgpack:"type"`
	SubAccountUser string  `json:"subAccountUser" msgpack:"subAccountUser"`
	IsDeposit      bool    `json:"isDeposit"      msgpack:"isDeposit"`
	Token          string  `json:"token"          msgpack:"token"`
	Amount         float64 `json:"amount"         msgpack:"amount"`
}

SubAccountSpotTransferAction represents sub-account spot transfer

type SubAccountTransferAction

type SubAccountTransferAction struct {
	Type           string `json:"type"           msgpack:"type"`
	SubAccountUser string `json:"subAccountUser" msgpack:"subAccountUser"`
	IsDeposit      bool   `json:"isDeposit"      msgpack:"isDeposit"`
	Usd            int    `json:"usd"            msgpack:"usd"`
}

SubAccountTransferAction represents sub-account transfer

type Subscription

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

type TWAPCancelAction

type TWAPCancelAction struct {
	Type   string `json:"type" msgpack:"type"`
	Asset  int    `json:"a"    msgpack:"a"`
	TWAPID int    `json:"t"    msgpack:"t"`
}

TWAPCancelAction represents TWAP cancel action

type TWAPOrderAction

type TWAPOrderAction struct {
	Type string        `json:"type" msgpack:"type"`
	TWAP TWAPOrderWire `json:"twap" msgpack:"twap"`
}

TWAPOrderAction represents TWAP order action

type TWAPOrderWire

type TWAPOrderWire struct {
	Asset      int    `json:"a" msgpack:"a"`
	IsBuy      bool   `json:"b" msgpack:"b"`
	Size       string `json:"s" msgpack:"s"`
	ReduceOnly bool   `json:"r" msgpack:"r"`
	Minutes    int    `json:"m" msgpack:"m"`
	Randomize  bool   `json:"t" msgpack:"t"`
}

TWAPOrderWire represents TWAP order wire format

type Tiers

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

type TokenDelegateAction

type TokenDelegateAction struct {
	Type             string `json:"type"             msgpack:"type"`
	HyperliquidChain string `json:"hyperliquidChain" msgpack:"hyperliquidChain"`
	SignatureChainId string `json:"signatureChainId" msgpack:"signatureChainId"`
	Validator        string `json:"validator"        msgpack:"validator"`
	Wei              int    `json:"wei"              msgpack:"wei"`
	IsUndelegate     bool   `json:"isUndelegate"     msgpack:"isUndelegate"`
	Nonce            int64  `json:"nonce"            msgpack:"nonce"`
}

TokenDelegateAction represents token delegate action

type Trade

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

type TransferResponse

type TransferResponse struct {
	Status string `json:"status"`
	TxHash string `json:"txHash,omitempty"`
	Error  string `json:"error,omitempty"`
}

type TriggerOrderType

type TriggerOrderType struct {
	TriggerPx float64 `json:"triggerPx"` // Keep as float64 for internal use, convert to string in wire format
	IsMarket  bool    `json:"isMarket"`
	Tpsl      string  `json:"tpsl"` // "tp" or "sl"
}

type TriggerOrderTypeWire

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

type TxStatus

type TxStatus struct {
	Coin   string `json:"coin"`
	Status string `json:"status"`
}

type UpdateIsolatedMarginAction

type UpdateIsolatedMarginAction struct {
	Type  string  `json:"type"  msgpack:"type"`
	Asset int     `json:"asset" msgpack:"asset"`
	IsBuy bool    `json:"isBuy" msgpack:"isBuy"`
	Ntli  float64 `json:"ntli"  msgpack:"ntli"`
}

UpdateIsolatedMarginAction represents isolated margin update

type UpdateLeverageAction

type UpdateLeverageAction struct {
	Type     string `json:"type"     msgpack:"type"`
	Asset    int    `json:"asset"    msgpack:"asset"`
	IsCross  bool   `json:"isCross"  msgpack:"isCross"`
	Leverage int    `json:"leverage" msgpack:"leverage"`
}

UpdateLeverageAction represents leverage update

type UsdClassTransferAction

type UsdClassTransferAction struct {
	Type   string `json:"type"   msgpack:"type"`
	Amount string `json:"amount" msgpack:"amount"`
	ToPerp bool   `json:"toPerp" msgpack:"toPerp"`
	Nonce  int64  `json:"nonce"  msgpack:"nonce"`
}

UsdClassTransferAction represents USD class transfer

type UsdTransferAction

type UsdTransferAction struct {
	Type        string `json:"type"        msgpack:"type"`
	Destination string `json:"destination" msgpack:"destination"`
	Amount      string `json:"amount"      msgpack:"amount"`
	Time        int64  `json:"time"        msgpack:"time"`
}

UsdTransferAction represents USD transfer

type UseBigBlocksAction

type UseBigBlocksAction struct {
	Type           string `json:"type"           msgpack:"type"`
	UsingBigBlocks bool   `json:"usingBigBlocks" msgpack:"usingBigBlocks"`
}

UseBigBlocksAction represents use big blocks action

type UserFees

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

type UserFundingHistory

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

type UserState

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

type UserVolume

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

type VIPTier

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

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidatorResponse

type ValidatorResponse struct {
	Status string `json:"status"`
	TxHash string `json:"txHash,omitempty"`
	Error  string `json:"error,omitempty"`
}

type VaultUsdTransferAction

type VaultUsdTransferAction struct {
	Type         string `json:"type"         msgpack:"type"`
	VaultAddress string `json:"vaultAddress" msgpack:"vaultAddress"`
	IsDeposit    bool   `json:"isDeposit"    msgpack:"isDeposit"`
	Usd          int    `json:"usd"          msgpack:"usd"`
}

VaultUsdTransferAction represents vault USD transfer

type WSMessage

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

type WebsocketClient

type WebsocketClient struct {
	MaxReconnectAttempts int           // 0 = unlimited (default)
	ReconnectWait        time.Duration // Can be customized
	// contains filtered or unexported fields
}

WebsocketClient manages a WebSocket connection to the Hyperliquid API. It handles automatic reconnection, subscription management, and POST requests.

func NewWebsocketClient

func NewWebsocketClient(baseURL string) *WebsocketClient

NewWebsocketClient creates a new WebSocket client for the given base URL. The client is not connected until Connect() is called.

func (*WebsocketClient) Close

func (w *WebsocketClient) Close() error

Close shuts down the WebSocket client and releases all resources.

func (*WebsocketClient) Connect

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

Connect establishes the WebSocket connection. It's safe to call multiple times - subsequent calls return immediately if already connected.

func (*WebsocketClient) PostActionRequest added in v1.0.34

func (w *WebsocketClient) PostActionRequest(
	action any,
	signature SignatureResult,
	nonce int64,
	vaultAddress string,
	timeout time.Duration,
) (json.RawMessage, error)

PostActionRequest sends a signed action request over WebSocket.

func (*WebsocketClient) PostInfoRequest added in v1.0.34

func (w *WebsocketClient) PostInfoRequest(
	payload map[string]any,
	timeout time.Duration,
) (json.RawMessage, error)

PostInfoRequest sends an info request over WebSocket.

func (*WebsocketClient) PostRequest added in v1.0.34

func (w *WebsocketClient) PostRequest(
	requestType string,
	payload any,
	timeout time.Duration,
) (*WsPostResponseData, error)

PostRequest sends a POST-style request over WebSocket and waits for response.

func (*WebsocketClient) Subscribe

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

Subscribe registers a callback for the given subscription. Returns a subscription ID that can be used to unsubscribe.

func (*WebsocketClient) SubscribeToActiveAssetCtx

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

func (*WebsocketClient) SubscribeToActiveAssetData added in v1.0.4

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

func (*WebsocketClient) SubscribeToAllMids

func (w *WebsocketClient) SubscribeToAllMids(callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToAllMidsWithDex added in v1.0.4

func (w *WebsocketClient) SubscribeToAllMidsWithDex(dex string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToBBO

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

func (*WebsocketClient) SubscribeToCandles

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

func (*WebsocketClient) SubscribeToNotification added in v1.0.4

func (w *WebsocketClient) SubscribeToNotification(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToOrderUpdates

func (w *WebsocketClient) SubscribeToOrderUpdates(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToOrderbook

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

func (*WebsocketClient) SubscribeToTrades

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

func (*WebsocketClient) SubscribeToUserEvents

func (w *WebsocketClient) SubscribeToUserEvents(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToUserFills

func (w *WebsocketClient) SubscribeToUserFills(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToUserFundings

func (w *WebsocketClient) SubscribeToUserFundings(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToUserNonFundingLedgerUpdates

func (w *WebsocketClient) SubscribeToUserNonFundingLedgerUpdates(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToUserTwapHistory added in v1.0.4

func (w *WebsocketClient) SubscribeToUserTwapHistory(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToUserTwapSliceFills added in v1.0.4

func (w *WebsocketClient) SubscribeToUserTwapSliceFills(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) SubscribeToWebData2

func (w *WebsocketClient) SubscribeToWebData2(user string, callback func(WSMessage)) (int, error)

func (*WebsocketClient) Unsubscribe

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

Unsubscribe removes a subscription by ID.

type WithdrawFromBridgeAction

type WithdrawFromBridgeAction struct {
	Type             string `json:"type"             msgpack:"type"`
	HyperliquidChain string `json:"hyperliquidChain" msgpack:"hyperliquidChain"`
	SignatureChainId string `json:"signatureChainId" msgpack:"signatureChainId"`
	Destination      string `json:"destination"      msgpack:"destination"`
	Amount           string `json:"amount"           msgpack:"amount"`
	Time             int64  `json:"time"             msgpack:"time"`
}

WithdrawFromBridgeAction represents withdraw from bridge action

type WsCommand

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

type WsMsg

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

WsMsg represents a WebSocket message with a channel and data payload.

type WsPostRequest added in v1.0.34

type WsPostRequest struct {
	Method  string    `json:"method"` // Always "post"
	ID      int       `json:"id"`
	Request WsRequest `json:"request"`
}

WsPostRequest is the request structure for WebSocket POST requests

type WsPostResponseData added in v1.0.34

type WsPostResponseData struct {
	ID       int        `json:"id"`
	Response WsResponse `json:"response"`
}

WsPostResponseData is the data field of a POST response message

type WsRequest added in v1.0.34

type WsRequest struct {
	Type    string `json:"type"` // "info" or "action"
	Payload any    `json:"payload"`
}

WsRequest wraps the actual request payload

type WsResponse added in v1.0.34

type WsResponse struct {
	Type    string          `json:"type"` // "info", "action", or "error"
	Payload json.RawMessage `json:"payload"`
}

WsResponse contains the actual response payload

Jump to

Keyboard shortcuts

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