hyperliquid

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MainnetAPIURL = "https://api.hyperliquid.xyz"
)

Variables

View Source
var ErrCredentialsRequired = fmt.Errorf("credentials required")

Functions

func FloatToString

func FloatToString(x float64) (string, error)

func FloatToUsdInt

func FloatToUsdInt(value float64) int

FloatToUsdInt converts float to USD integer representation

func GetTimestampMs

func GetTimestampMs() int64

GetTimestampMs returns current timestamp in milliseconds

func IsWalletDoesNotExistError

func IsWalletDoesNotExistError(err error) bool

IsWalletDoesNotExistError checks if the error is a "wallet does not exist" error from the API

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 `json:"status"`
	Response *struct {
		Type string `json:"type"`
		Data T      `json:"data"`
	} `json:"response"`
}

type ActiveStakingDiscount

type ActiveStakingDiscount struct {
	BpsOfMaxSupply string `json:"bpsOfMaxSupply"`
	Discount       string `json:"discount"`
}

type BatchModifyAction

type BatchModifyAction struct {
	Type     string              `json:"type"     msgpack:"type"`
	Modifies []ModifyOrderAction `json:"modifies" msgpack:"modifies"`
}

type Builder

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

type CancelOrderAction

type CancelOrderAction struct {
	Type    string            `json:"type" msgpack:"type"`
	Cancels []CancelOrderWire `json:"cancels" msgpack:"cancels"`
}

cancel order

type CancelOrderWire

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

type Client

type Client struct {
	Logger  *zap.SugaredLogger
	Debug   bool
	BaseURL string
	Http    *http.Client

	PrivateKey  *ecdsa.PrivateKey
	Vault       string
	AccountAddr string

	LastNonce    atomic.Int64
	ExpiresAfter *int64
}

func NewClient

func NewClient() *Client

func (*Client) GetNextNonce

func (c *Client) GetNextNonce() int64

func (*Client) GetUserFees

func (c *Client) GetUserFees(ctx context.Context) (*UserFees, error)

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, payload any) ([]byte, error)

func (*Client) PostAction

func (c *Client) PostAction(ctx context.Context, action any, sig SignatureResult, nonce int64) ([]byte, error)

func (*Client) WithAccount

func (c *Client) WithAccount(accountAddr string) *Client

func (*Client) WithCredentials

func (c *Client) WithCredentials(privateKey string, vault *string) *Client

type CreateOrderAction

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

type DailyUserVlm

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

type FeeSchedule

type FeeSchedule struct {
	Cross                  string                `json:"cross"`
	Add                    string                `json:"add"`
	SpotCross              string                `json:"spotCross"`
	SpotAdd                string                `json:"spotAdd"`
	Tiers                  Tiers                 `json:"tiers"`
	ReferralDiscount       string                `json:"referralDiscount"`
	StakingDiscountTiers   []StakingDiscountTier `json:"stakingDiscountTiers"`
	UserCrossRate          string                `json:"userCrossRate"`
	UserAddRate            string                `json:"userAddRate"`
	UserSpotCrossRate      string                `json:"userSpotCrossRate"`
	UserSpotAddRate        string                `json:"userSpotAddRate"`
	ActiveReferralDiscount string                `json:"activeReferralDiscount"`
	FeeTrialReward         string                `json:"feeTrialReward"`
	StakingLink            StakingLink           `json:"stakingLink"`
	ActiveStakingDiscount  ActiveStakingDiscount `json:"activeStakingDiscount"`
}

type Grouping

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

type MM

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

type MixedArray

type MixedArray []MixedValue

func (MixedArray) FirstError

func (ma MixedArray) FirstError() error

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 ModifyOrderAction

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

modify order

type OrderStatusValue added in v0.1.4

type OrderStatusValue string

OrderStatusValue represents the status string returned by the Hyperliquid API. Used in both REST and WS order responses for perp and spot markets. See: https://hyperliquid.gitbook.io/hyperliquid-docs

const (
	StatusOpen                    OrderStatusValue = "open"
	StatusFilled                  OrderStatusValue = "filled"
	StatusCanceled                OrderStatusValue = "canceled"
	StatusTriggered               OrderStatusValue = "triggered"
	StatusRejected                OrderStatusValue = "rejected"
	StatusMarginCanceled          OrderStatusValue = "marginCanceled"
	StatusVaultWithdrawalCanceled OrderStatusValue = "vaultWithdrawalCanceled"
	StatusOpenInterestCapCanceled OrderStatusValue = "openInterestCapCanceled"
	StatusSelfTradeCanceled       OrderStatusValue = "selfTradeCanceled"
	StatusReduceOnlyCanceled      OrderStatusValue = "reduceOnlyCanceled"
	StatusSiblingFilledCanceled   OrderStatusValue = "siblingFilledCanceled"
	StatusDelistedCanceled        OrderStatusValue = "delistedCanceled"
	StatusLiquidatedCanceled      OrderStatusValue = "liquidatedCanceled"
	StatusScheduledCancel         OrderStatusValue = "scheduledCancel"
	StatusTickRejected            OrderStatusValue = "tickRejected"
	StatusMinTradeNtlRejected     OrderStatusValue = "minTradeNtlRejected"
)

type OrderTypeWire

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

type OrderTypeWireLimit

type OrderTypeWireLimit struct {
	Tif Tif `json:"tif" msgpack:"tif"`
}

type OrderTypeWireTrigger

type OrderTypeWireTrigger struct {
	IsMarket  bool   `json:"isMarket"  msgpack:"isMarket"`  // 1st
	TriggerPx string `json:"triggerPx" msgpack:"triggerPx"` // 2nd - Must be string for msgpack serialization
	Tpsl      Tpsl   `json:"tpsl"      msgpack:"tpsl"`      // 3rd - "tp" or "sl"
}

type OrderWire

type OrderWire struct {
	Asset      int           `json:"a"           msgpack:"a"`           // 1st
	IsBuy      bool          `json:"b"           msgpack:"b"`           // 2nd
	LimitPx    string        `json:"p"           msgpack:"p"`           // 3rd
	Size       string        `json:"s"           msgpack:"s"`           // 4th
	ReduceOnly bool          `json:"r"           msgpack:"r"`           // 5th
	OrderType  OrderTypeWire `json:"t"           msgpack:"t"`           // 6th
	Cloid      *string       `json:"c,omitempty" msgpack:"c,omitempty"` // 7th (optional)
}

create order

type PostResult

type PostResult struct {
	Response WsPostResponsePayload
	Error    error
}

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,
	nonce int64,
	isMainnet bool,
) (SignatureResult, error)

SignAgent signs agent approval action using EIP-712 direct signing

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)

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 SignUserSignedAction

func SignUserSignedAction(
	privateKey *ecdsa.PrivateKey,
	action map[string]any,
	payloadTypes []apitypes.Type,
	primaryType string,
	isMainnet bool,
) (SignatureResult, error)

SignUserSignedAction signs actions that require direct EIP-712 signing (e.g., approveAgent, approveBuilderFee, convertToMultiSigUser)

IMPORTANT: The message will contain MORE fields than declared in payloadTypes to avoid the error "422 Failed to deserialize the JSON body" and "User or API Wallet 0x123... does not exist". This matches Python SDK behavior where the field order doesn't matter and extra fields (type, signatureChainId) are present in the message but ignored during EIP-712 hashing via hashStructLenient.

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 StakingDiscountTier

type StakingDiscountTier struct {
	BpsOfMaxSupply string `json:"bpsOfMaxSupply"`
	Discount       string `json:"discount"`
}
type StakingLink struct {
	Type        string `json:"type"`
	StakingUser string `json:"stakingUser"`
}

type Tiers

type Tiers struct {
	Vip []Vip `json:"vip"`
	MM  []MM  `json:"mm"`
}

type Tif

type Tif string
const (
	TifGtc Tif = "Gtc"
	TifIoc Tif = "Ioc"
	TifFok Tif = "Fok"
)

type Tpsl

type Tpsl string
const (
	TakeProfit Tpsl = "tp"
	StopLoss   Tpsl = "sl"
)

type UpdateIsolatedMarginAction

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

update isolated margin

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"`
}

update leverage

type UsdClassTransferAction

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

type UserFees

type UserFees struct {
	DailyUserVlm []DailyUserVlm `json:"dailyUserVlm"`
	FeeSchedule  FeeSchedule    `json:"feeSchedule"`
}

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

func (ValidationError) Error

func (e ValidationError) Error() string

type Vip

type Vip struct {
	NtlCutoff string `json:"ntlCutoff"`
	Cross     string `json:"cross"`
	Add       string `json:"add"`
	SpotCross string `json:"spotCross"`
	SpotAdd   string `json:"spotAdd"`
}

type WebsocketClient

type WebsocketClient struct {
	URL     string
	Conn    *websocket.Conn
	Mu      sync.RWMutex
	WriteMu sync.Mutex

	ReconnectWait time.Duration
	Debug         bool
	Logger        *zap.SugaredLogger

	PrivateKey  *ecdsa.PrivateKey
	Vault       string
	AccountAddr string

	LastNonce    atomic.Int64
	NextPostID   atomic.Int64
	PostChannels map[int64]chan PostResult

	PingInterval time.Duration
	// contains filtered or unexported fields
}

func NewWebsocketClient

func NewWebsocketClient(ctx context.Context) *WebsocketClient

func (*WebsocketClient) Close

func (c *WebsocketClient) Close()

func (*WebsocketClient) Connect

func (c *WebsocketClient) Connect() error

func (*WebsocketClient) GetNextNonce

func (c *WebsocketClient) GetNextNonce() int64

func (*WebsocketClient) PostAction

func (c *WebsocketClient) PostAction(action any, sig SignatureResult, nonce int64) (chan PostResult, error)

func (*WebsocketClient) PostRequest

func (c *WebsocketClient) PostRequest(payload WsPostRequestPayload) (chan PostResult, error)

func (*WebsocketClient) SendCommand

func (c *WebsocketClient) SendCommand(cmd any) error

SendCommand sends a raw JSON command

func (*WebsocketClient) Subscribe

func (c *WebsocketClient) Subscribe(channel string, subscription any, handler func(WsMessage)) error

Subscribe registers a handler for a specific channel name and optionally sends a subscription request.

func (*WebsocketClient) Unsubscribe

func (c *WebsocketClient) Unsubscribe(channel string, subscription any) error

Unsubscribe removes a handler and optionally sends unsubscribe command

func (*WebsocketClient) WithCredentials

func (c *WebsocketClient) WithCredentials(privateKey string, vault *string) *WebsocketClient

func (*WebsocketClient) WithURL

func (c *WebsocketClient) WithURL(u string) *WebsocketClient

type WsAllMids

type WsAllMids struct {
	Mids map[string]string `json:"mids"`
}

type WsBbo

type WsBbo struct {
	Coin string    `json:"coin"`
	Time int64     `json:"time"`
	Bbo  []WsLevel `json:"bbo"`
}

type WsCandle

type WsCandle struct {
	T      int64  `json:"t"` // Open time
	TClose int64  `json:"T"` // Close time
	S      string `json:"s"` // Symbol/Coin
	I      string `json:"i"` // Interval
	O      string `json:"o"` // Open
	C      string `json:"c"` // Close
	H      string `json:"h"` // High
	L      string `json:"l"` // Low
	V      string `json:"v"` // Volume
	N      int64  `json:"n"` // Number of trades
}

type WsL2Book

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

type WsLevel

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

type WsLiquidation

type WsLiquidation struct {
	Lid                    int64  `json:"lid"`
	Liquidator             string `json:"liquidator"`
	LiquidatedUser         string `json:"liquidated_user"`
	LiquidatedNtlPos       string `json:"liquidated_ntl_pos"`
	LiquidatedAccountValue string `json:"liquidated_account_value"`
}

type WsMessage

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

type WsNonUserCancel

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

type WsOrder

type WsOrder 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"`
	OrigSz    string `json:"origSz"`
	Cliod     string `json:"cloid"`
}

type WsOrderUpdate

type WsOrderUpdate struct {
	Order           WsOrder          `json:"order"`
	Status          OrderStatusValue `json:"status"`
	StatusTimestamp int64            `json:"statusTimestamp"`
}

type WsPostRequest

type WsPostRequest struct {
	Method  string               `json:"method"`
	ID      int64                `json:"id"`
	Request WsPostRequestPayload `json:"request"`
}

type WsPostRequestPayload

type WsPostRequestPayload struct {
	Type    string `json:"type"`
	Payload any    `json:"payload"`
}

type WsPostResponse

type WsPostResponse struct {
	ID       int64                 `json:"id"`
	Response WsPostResponsePayload `json:"response"`
}

type WsPostResponsePayload

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

type WsSubscribeRequest

type WsSubscribeRequest struct {
	Method       string `json:"method"`
	Subscription any    `json:"subscription"`
}

type WsSubscriptionResponse

type WsSubscriptionResponse struct {
	Method       string          `json:"method"`
	Subscription json.RawMessage `json:"subscription"`
}

type WsTrade

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

type WsUserEvent

type WsUserEvent struct {
	Fills         []WsUserFill      `json:"fills,omitempty"`
	Funding       *WsUserFunding    `json:"funding,omitempty"`
	Liquidation   *WsLiquidation    `json:"liquidation,omitempty"`
	NonUserCancel []WsNonUserCancel `json:"nonUserCancel,omitempty"`
}

type WsUserFill

type WsUserFill struct {
	Coin          string         `json:"coin"`
	Px            string         `json:"px"`
	Sz            string         `json:"sz"`
	Side          string         `json:"side"`
	Time          int64          `json:"time"`
	StartPosition string         `json:"startPosition"`
	Dir           string         `json:"dir"`
	ClosedPnl     string         `json:"closedPnl"`
	Hash          string         `json:"hash"`
	Oid           int64          `json:"oid"`
	Crossed       bool           `json:"crossed"`
	Fee           string         `json:"fee"`
	FeeToken      string         `json:"feeToken"`
	Tid           int64          `json:"tid"`
	BuilderFee    string         `json:"builderFee,omitempty"`
	Liquidation   *WsLiquidation `json:"liquidation,omitempty"`
}

type WsUserFills

type WsUserFills struct {
	IsSnapshot bool         `json:"isSnapshot,omitempty"`
	User       string       `json:"user"`
	Fills      []WsUserFill `json:"fills"`
}

type WsUserFunding

type WsUserFunding struct {
	Time        int64  `json:"time"`
	Coin        string `json:"coin"`
	Usdc        string `json:"usdc"`
	Szi         string `json:"szi"`
	FundingRate string `json:"fundingRate"`
}

type WsUserLiquidations

type WsUserLiquidations struct {
	Tid  int64  `json:"tid"`
	Coin string `json:"coin"`
	Usdc string `json:"usdc"`
	Sz   string `json:"sz"`
	Px   string `json:"px"`
	Time int64  `json:"time"`
}

type WsUserNonFundingLedgerUpdates

type WsUserNonFundingLedgerUpdates struct {
	Time int64  `json:"time"`
	Coin string `json:"coin"`
	Usdc string `json:"usdc"`
	Type string `json:"type"` // e.g. "deposit", "withdraw", "transfer", "internal_transfer", "subaccount_transfer"
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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