Help us shape the future of Go! Take the 2026 Go Developer Survey

hyperliquid

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 34 Imported by: 0

README

goop-hyperliquid

Unofficial Hyperliquid client for Goop — a faithful port of sonirico/go-hyperliquid (same API surface, same deps including vago/lol, websockets, EIP-712 signing).

Wire types and exchange/info/ws logic currently live as the upstream Go package (consumed from Goop with import go) so behavior stays identical. Native Goop syntax is added where it does not require @[go] embeds. Gaps that block a full .goop rewrite are tracked in GOOP_LANG_BLOCKERS.md.

Requires Goop 1.17+ and a normal Go toolchain.

Install

goop get github.com/Macho0x/goop-hyperliquid
import goop . "github.com/Macho0x/goop-hyperliquid/hyperliquid"
import go "github.com/Macho0x/goop-hyperliquid" {
  val NewInfoGoop : Context -> string -> Info ptr
  (* … *)
}

Go-only consumers can also:

go get github.com/Macho0x/goop-hyperliquid

Goop usage

module main

import goop . "github.com/Macho0x/goop-hyperliquid/hyperliquid"

import go "context" {
  type Context
  val Background : unit -> Context
}

import go "fmt" {
  val Println : ...any -> unit
}

import go "github.com/Macho0x/goop-hyperliquid" {
  type Info
  type Meta
  val TestnetAPIURL : string
  val NewInfoGoop : Context -> string -> Info ptr
  val (i : Info ptr).MetaGoop : Context -> (Meta ptr, error)
}

let main () =
  begin
    let ctx = Background () in
    let info = NewInfoGoop ctx TestnetAPIURL in
    match info.MetaGoop ctx with
    | Ok _ -> Println "meta ok"
    | Error _ -> Println "meta failed"
  end

Prefer NewInfoGoop / MetaGoop from Goop (fixed arities). Full upstream API remains available via import go.

Go usage

Identical to upstream:

package main

import (
  "context"
  "log"

  "github.com/ethereum/go-ethereum/crypto"
  hl "github.com/Macho0x/goop-hyperliquid"
)

func main() {
  key, err := crypto.HexToECDSA("…")
  if err != nil {
    log.Fatal(err)
  }
  ex := hl.NewExchange(context.Background(), key, hl.TestnetAPIURL, nil, "", "", nil, nil)
  _ = ex
}

Parity status

Area Status
Info REST Identical upstream
Exchange + signing Identical upstream
WebSocket subscriptions Identical upstream
Deploy / validators / multisig Identical upstream
Native Goop helpers / examples In progress (see examples_goop/)
Full .goop rewrite of wire types Blocked on Goop JSON tags — GOOP_LANG_BLOCKERS.md

Develop

go test -short -run 'TestSign|TestFloat|TestType|TestAPI|TestUtils|TestMsgpack|TestUniq|TestMixed|TestTuple|TestWire' .
goop check hyperliquid/hyperliquid.goop
goop test examples_goop/
go test -short -run 'TestSign|TestFloat|TestType|TestAPI|TestUtils|TestMsgpack|TestUniq|TestMixed|TestTuple|TestWire' .

Attribution

Port of sonirico/go-hyperliquid (MIT). Follows the same philosophy as the official Hyperliquid Python SDK.

License

MIT — see LICENSE.

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 (
	ChannelPong               string = "pong"
	ChannelTrades             string = "trades"
	ChannelActiveAssetCtx     string = "activeAssetCtx"
	ChannelL2Book             string = "l2Book"
	ChannelCandle             string = "candle"
	ChannelAllMids            string = "allMids"
	ChannelNotification       string = "notification"
	ChannelOrderUpdates       string = "orderUpdates"
	ChannelUserFills          string = "userFills"
	ChannelWebData2           string = "webData2"
	ChannelBbo                string = "bbo"
	ChannelSubResponse        string = "subscriptionResponse"
	ChannelClearinghouseState string = "clearinghouseState"
	ChannelOpenOrders         string = "openOrders"
	ChannelTwapStates         string = "twapStates"
	ChannelWebData3           string = "webData3"
)
View Source
const (
	DefaultSlippage = 0.05 // 5%
)

Constants for default values

Variables

This section is empty.

Functions

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

func MetaUniverseCount added in v0.1.1

func MetaUniverseCount(ctx context.Context, baseURL string) (int, error)

MetaUniverseCount fetches meta and returns universe length (Goop-friendly; avoids result FFI mangling).

func MetaUniverseLen

func MetaUniverseLen(m *Meta) int

MetaUniverseLen returns len(meta.Universe).

func NewMsgDispatcher

func NewMsgDispatcher[T subscriptable](channel string) msgDispatcher

func NewNoopDispatcher

func NewNoopDispatcher() msgDispatcher

func NewPongDispatcher

func NewPongDispatcher() msgDispatcher

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 AccountHistory

type AccountHistory struct {
	AccountValueHistory []MixedArray `json:"accountValueHistory"` // [timestamp, value]
	PnlHistory          []MixedArray `json:"pnlHistory"`          // [timestamp, value]
	Vlm                 string       `json:"vlm"`
}

AccountHistory represents historical portfolio data for a specific time range

type ActiveAssetCtx

type ActiveAssetCtx struct {
	Coin string         `json:"coin"`
	Ctx  SharedAssetCtx `json:"ctx"`
}

func (ActiveAssetCtx) Key

func (a ActiveAssetCtx) Key() string

type ActiveAssetCtxSubscriptionParams

type ActiveAssetCtxSubscriptionParams struct {
	Coin string
}

type AgentApprovalResponse

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

type AgentSigner

type AgentSigner interface {
	SignAgent(
		ctx context.Context,
		agentAddress, agentName string,
		nonce int64,
		isMainnet bool,
	) (SignatureResult, error)
}

AgentSigner signs agent approval actions. When nil on Exchange, the default ECDSA implementation is used.

func ECDSAAgentSigner

func ECDSAAgentSigner(pk *ecdsa.PrivateKey) AgentSigner

ECDSAAgentSigner implements AgentSigner using an ECDSA private key.

type AllMids

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

func (AllMids) Key

func (a AllMids) Key() string

type AllMidsSubscriptionParams

type AllMidsSubscriptionParams struct {
	Dex *string
}

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"`
	SignatureChainId string  `json:"signatureChainId"    msgpack:"signatureChainId"`
	HyperliquidChain string  `json:"hyperliquidChain"    msgpack:"hyperliquidChain"`
	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"`
	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

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

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 AssetRequest

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

type AssetRequest2

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

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 Bbo

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

func (Bbo) Key

func (w Bbo) Key() string

type BboSubscriptionParams

type BboSubscriptionParams struct {
	Coin string
}

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 `o` like CancelOrderWire has See: https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/f19056ca1b65cc15a019d92dffa9ada887b3d808/hyperliquid/exchange.py#L305-L310

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 {
	TimeOpen    int64  `json:"t"` // open millis
	TimeClose   int64  `json:"T"` // close millis
	Interval    string `json:"i"` // interval
	TradesCount int    `json:"n"` // number of trades
	Open        string `json:"o"` // open price
	High        string `json:"h"` // high price
	Low         string `json:"l"` // low price
	Close       string `json:"c"` // close price
	Symbol      string `json:"s"` // coin
	Volume      string `json:"v"` // volume (base unit)
}

func (Candle) Key

func (c Candle) Key() string

type CandlesSubscriptionParams

type CandlesSubscriptionParams struct {
	Coin     string
	Interval string
}

type ClearinghouseState

type ClearinghouseState struct {
	MarginSummary              *MarginSummary  `json:"marginSummary,omitempty"`
	CrossMarginSummary         *MarginSummary  `json:"crossMarginSummary,omitempty"`
	CrossMaintenanceMarginUsed string          `json:"crossMaintenanceMarginUsed,omitempty"`
	Withdrawable               string          `json:"withdrawable,omitempty"`
	AssetPositions             []AssetPosition `json:"assetPositions,omitempty"`
	Time                       int64           `json:"time,omitempty"`
}

func (ClearinghouseState) Key

func (c ClearinghouseState) Key() string

type ClearinghouseStateMessage

type ClearinghouseStateMessage struct {
	Dex                string             `json:"dex,omitempty"`
	User               string             `json:"user,omitempty"`
	ClearinghouseState ClearinghouseState `json:"clearinghouseState"`
}

func (ClearinghouseStateMessage) Key

type ClearinghouseStateSubscriptionParams

type ClearinghouseStateSubscriptionParams struct {
	User string
	Dex  *string
}

type ClientOpt

type ClientOpt = Opt[client]

func ClientOptHTTPClient

func ClientOptHTTPClient(httpClient *http.Client) ClientOpt

ClientOptHTTPClient allows setting a custom http.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"`
	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
}

func (*CreateOrderRequest) String

func (s *CreateOrderRequest) String() 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 CreateVaultAction

type CreateVaultAction struct {
	Type        string `json:"type"        msgpack:"type"`
	Name        string `json:"name"        msgpack:"name"`
	Description string `json:"description" msgpack:"description"`
	InitialUsd  int    `json:"initialUsd"  msgpack:"initialUsd"`
}

CreateVaultAction represents create vault action

type CreateVaultResponse

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

type CumFunding

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

type Delta

type Delta struct {
	Coin        string `json:"coin"`
	FundingRate string `json:"fundingRate"`
	Size        string `json:"size"`
	Type        string `json:"type"`
	USDC        string `json:"usdc"`
}

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(
	ctx context.Context,
	privateKey *ecdsa.PrivateKey,
	baseURL string,
	meta *Meta,
	vaultAddr, accountAddr string,
	spotMeta *SpotMeta,
	perpDexs *MixedArray,
	opts ...ExchangeOpt,
) *Exchange

func NewExchangeGoop

func NewExchangeGoop(
	ctx context.Context,
	privateKey *ecdsa.PrivateKey,
	baseURL string,
	accountAddr string,
) *Exchange

NewExchangeGoop builds an Exchange with empty vault/account and auto meta.

func (*Exchange) ApproveAgent

func (e *Exchange) ApproveAgent(
	ctx context.Context,
	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(
	ctx context.Context,
	builder string,
	maxFeeRate string,
) (*ApprovalResponse, error)

ApproveBuilderFee approves builder fee payment

func (*Exchange) BulkCancel

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

func (*Exchange) BulkCancelByCloids

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

func (*Exchange) BulkModifyOrders

func (e *Exchange) BulkModifyOrders(
	ctx context.Context,
	modifyRequests []ModifyOrderRequest,
) ([]OrderStatus, error)

BulkModifyOrders modifies multiple orders

func (*Exchange) BulkOrders

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

func (*Exchange) CSignerInner

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

CSignerInner executes inner consensus signer action

func (*Exchange) CSignerJailSelf

func (e *Exchange) CSignerJailSelf(ctx context.Context) (*ValidatorResponse, error)

CSignerJailSelf jails self as consensus signer

func (*Exchange) CSignerUnjailSelf

func (e *Exchange) CSignerUnjailSelf(ctx context.Context) (*ValidatorResponse, error)

CSignerUnjailSelf unjails self as consensus signer

func (*Exchange) CValidatorChangeProfile

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

CValidatorChangeProfile changes validator profile

func (*Exchange) CValidatorRegister

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

CValidatorRegister registers as consensus validator

func (*Exchange) CValidatorUnregister

func (e *Exchange) CValidatorUnregister(ctx context.Context) (*ValidatorResponse, error)

CValidatorUnregister unregisters as consensus validator

func (*Exchange) Cancel

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

func (*Exchange) CancelByCloid

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

func (*Exchange) ConvertToMultiSigUser

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

ConvertToMultiSigUser converts account to multi-signature user

func (*Exchange) CreateSubAccount

func (e *Exchange) CreateSubAccount(
	ctx context.Context,
	name string,
) (*CreateSubAccountResponse, error)

CreateSubAccount creates a new sub-account

func (*Exchange) CreateVault

func (e *Exchange) CreateVault(
	ctx context.Context,
	name string,
	description string,
	initialUsd int,
) (*CreateVaultResponse, error)

CreateVault creates a new vault

func (*Exchange) Info

func (e *Exchange) Info() *Info

func (*Exchange) MarketClose

func (e *Exchange) MarketClose(
	ctx context.Context,
	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(
	ctx context.Context,
	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) ModifyOrder

func (e *Exchange) ModifyOrder(
	ctx context.Context,
	req ModifyOrderRequest,
) (result OrderStatus, err error)

ModifyOrder modifies an existing order

func (*Exchange) MultiSig

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

func (*Exchange) Order

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

func (*Exchange) PerpDeployHaltTrading

func (e *Exchange) PerpDeployHaltTrading(
	ctx context.Context,
	coin string,
	isHalted bool,
) (*PerpDeployResponse, error)

PerpHaltTrading halts or unhalts trading for a builder-deployed DEX

func (*Exchange) PerpDeployRegisterAsset

func (e *Exchange) PerpDeployRegisterAsset(
	ctx context.Context,
	dex string,
	maxGas *int,
	assetRequest AssetRequest,
	schema *PerpDexSchemaInput,
) (*PerpDeployResponse, error)

PerpDeployRegisterAsset registers a new perpetual asset on a builder-deployed DEX. Provide schema to also initialize a new dex alongside the asset registration.

func (*Exchange) PerpDeployRegisterAsset2

func (e *Exchange) PerpDeployRegisterAsset2(
	ctx context.Context,
	dex string,
	maxGas *int,
	assetRequest AssetRequest2,
	schema *PerpDexSchemaInput,
) (*PerpDeployResponse, error)

PerpDeployRegisterAsset2 registers a new perpetual asset on a builder-deployed DEX using marginMode instead of onlyIsolated. Provide schema to also initialize a new dex.

func (*Exchange) PerpDeploySetOracle

func (e *Exchange) PerpDeploySetOracle(
	ctx context.Context,
	dex string,
	oraclePxs map[string]string,
	allMarkPxs []map[string]string,
	externalPerpPxs map[string]string,
) (*PerpDeployResponse, error)

PerpDeploySetOracle sets oracle prices for a builder-deployed DEX This matches the Python SDK's perp_deploy_set_oracle method oraclePxs: map of coin to oracle price string allMarkPxs: list of maps, each map contains coin to mark price string externalPerpPxs: map of coin to external perp price string

func (*Exchange) PerpDex

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(
	ctx context.Context,
	dex, token string,
	amount float64,
	toPerp bool,
) (*TransferResponse, error)

PerpDexClassTransfer transfers tokens between perp dex classes

func (*Exchange) Reserve

func (e *Exchange) Reserve(ctx context.Context, weight int) (*ReserveRequestWeightResponse, error)

Reserve reserves request weight capacity on the exchange. Each weight unit costs 0.0005 USDC from Perps balance. This increases address-based rate limits without requiring trading volume.

func (*Exchange) ScheduleCancel

func (e *Exchange) ScheduleCancel(
	ctx context.Context,
	scheduleTime *int64,
) (*ScheduleCancelResponse, error)

ScheduleCancel schedules cancellation of all open orders

func (*Exchange) SendAsset

func (e *Exchange) SendAsset(
	ctx context.Context,
	destination string,
	sourceDex string,
	destinationDex string,
	token string,
	amount float64,
) (*ReserveRequestWeightResponse, error)

For the default perp dex use the empty string "" as name. For spot use "spot". Token must match the collateral token if transferring to or from a perp dex.

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 nonce

func (*Exchange) SetLastNonce

func (e *Exchange) SetLastNonce(n int64)

SetLastNonce allows for resuming from a persisted nonce, e.g. the nonce was stored before a restart Only useful if a lot of increments happen for unique nonces. Most users do not need this.

func (*Exchange) SetReferrer

func (e *Exchange) SetReferrer(ctx context.Context, code string) (*SetReferrerResponse, error)

SetReferrer sets a referral code

func (*Exchange) SlippagePrice

func (e *Exchange) SlippagePrice(
	ctx context.Context,
	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(
	ctx context.Context,
) (*SpotDeployResponse, error)

SpotDeployEnableFreezePrivilege enables freeze privilege for spot deployer

func (*Exchange) SpotDeployFreezeUser

func (e *Exchange) SpotDeployFreezeUser(
	ctx context.Context,
	userAddress string,
) (*SpotDeployResponse, error)

SpotDeployFreezeUser freezes a user in spot trading

func (*Exchange) SpotDeployGenesis

func (e *Exchange) SpotDeployGenesis(
	ctx context.Context,
	deployer string,
	dexName string,
) (*SpotDeployResponse, error)

SpotDeployGenesis initializes spot genesis

func (*Exchange) SpotDeployRegisterHyperliquidity

func (e *Exchange) SpotDeployRegisterHyperliquidity(
	ctx context.Context,
	name string,
	tokens []string,
) (*SpotDeployResponse, error)

SpotDeployRegisterHyperliquidity registers hyperliquidity spot

func (*Exchange) SpotDeployRegisterSpot

func (e *Exchange) SpotDeployRegisterSpot(
	ctx context.Context,
	baseToken string,
	quoteToken string,
) (*SpotDeployResponse, error)

SpotDeployRegisterSpot registers spot market

func (*Exchange) SpotDeployRegisterToken

func (e *Exchange) SpotDeployRegisterToken(
	ctx context.Context,
	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(
	ctx context.Context,
) (*SpotDeployResponse, error)

SpotDeployRevokeFreezePrivilege revokes freeze privilege for spot deployer

func (*Exchange) SpotDeploySetDeployerTradingFeeShare

func (e *Exchange) SpotDeploySetDeployerTradingFeeShare(
	ctx context.Context,
	feeShare float64,
) (*SpotDeployResponse, error)

SpotDeploySetDeployerTradingFeeShare sets deployer trading fee share

func (*Exchange) SpotDeployUserGenesis

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

SpotDeployUserGenesis initializes user genesis for spot trading

func (*Exchange) SpotTransfer

func (e *Exchange) SpotTransfer(
	ctx context.Context,
	amount float64,
	destination, token string,
) (*TransferResponse, error)

SpotTransfer transfers spot tokens to another address

func (*Exchange) SubAccountSpotTransfer

func (e *Exchange) SubAccountSpotTransfer(
	ctx context.Context,
	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(
	ctx context.Context,
	subAccountUser string,
	isDeposit bool,
	usd int,
) (*TransferResponse, error)

SubAccountTransfer transfers funds to/from sub-account

func (*Exchange) TokenDelegate

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

TokenDelegate delegates tokens for staking

func (*Exchange) UpdateIsolatedMargin

func (e *Exchange) UpdateIsolatedMargin(
	ctx context.Context,
	amount float64,
	name string,
) (*UserState, error)

func (*Exchange) UpdateLeverage

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

func (*Exchange) UsdClassTransfer

func (e *Exchange) UsdClassTransfer(
	ctx context.Context,
	amount float64,
	toPerp bool,
) (*TransferResponse, error)

UsdClassTransfer transfers between USD classes

func (*Exchange) UsdTransfer

func (e *Exchange) UsdTransfer(
	ctx context.Context,
	amount float64,
	destination string,
) (*TransferResponse, error)

UsdTransfer transfers USD to another address

func (*Exchange) UseBigBlocks

func (e *Exchange) UseBigBlocks(ctx context.Context, enable bool) (*ApprovalResponse, error)

UseBigBlocks enables or disables big blocks

func (*Exchange) UserDexAbstraction

func (e *Exchange) UserDexAbstraction(
	ctx context.Context,
	user string,
	enabled bool,
) (*ReserveRequestWeightResponse, error)

UserDexAbstraction Methods set dex abstraction

func (*Exchange) UserSetAbstraction

func (e *Exchange) UserSetAbstraction(
	ctx context.Context,
	user string,
	abstraction string,
) (*ReserveRequestWeightResponse, error)

UserSetAbstraction Methods set abstraction

func (*Exchange) VaultDistribute

func (e *Exchange) VaultDistribute(
	ctx context.Context,
	vaultAddress string,
	usd int,
) (*TransferResponse, error)

func (*Exchange) VaultModify

func (e *Exchange) VaultModify(
	ctx context.Context,
	vaultAddress string,
	allowDeposits bool,
	alwaysCloseOnWithdraw bool,
) (*TransferResponse, error)

func (*Exchange) VaultUsdTransfer

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

VaultUsdTransfer transfers to/from vault

func (*Exchange) WithdrawFromBridge

func (e *Exchange) WithdrawFromBridge(
	ctx context.Context,
	amount float64,
	destination string,
) (*TransferResponse, error)

WithdrawFromBridge withdraws tokens from bridge

type ExchangeOpt

type ExchangeOpt = Opt[Exchange]

func ExchangeOptAgentSigner

func ExchangeOptAgentSigner(s AgentSigner) ExchangeOpt

ExchangeOptAgentSigner injects an AgentSigner. When nil, the default ECDSA implementation with privateKey is used.

func ExchangeOptClientOptions

func ExchangeOptClientOptions(opts ...ClientOpt) ExchangeOpt

ExchangeOptClientOptions allows passing of ClientOpt to Client

func ExchangeOptDebugMode

func ExchangeOptDebugMode() ExchangeOpt

func ExchangeOptInfoOptions

func ExchangeOptInfoOptions(opts ...InfoOpt) ExchangeOpt

ExchangeOptInfoOptions allows passing of InfoOpt to Info

func ExchangeOptL1Signer

func ExchangeOptL1Signer(s L1ActionSigner) ExchangeOpt

ExchangeOptL1Signer injects an L1ActionSigner. When nil, the default ECDSA implementation with privateKey is used.

func ExchangeOptPerpDex

func ExchangeOptPerpDex(dex string) ExchangeOpt

func ExchangeOptUserSignedSigner

func ExchangeOptUserSignedSigner(s UserSignedActionSigner) ExchangeOpt

ExchangeOptUserSignedSigner injects a UserSignedActionSigner. When nil, the default ECDSA implementation with privateKey is used.

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"`
	BuilderFee    string `json:"builderFee,omitempty"`
	Tid           int64  `json:"tid"`
}

type FillLiquidation

type FillLiquidation struct {
	LiquidatedUser *string `json:"liquidatedUser,omitempty"`
	MarkPx         string  `json:"markPx"`
	Method         string  `json:"method"`
}

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             OrderSide `json:"side"`
	Sz               float64   `json:"sz,string"`
	Timestamp        int64     `json:"timestamp"`
	TriggerCondition string    `json:"triggerCondition"`
	TriggerPx        float64   `json:"triggerPx,string"`
}

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 HaltTrading

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

type Handler

type Handler[T subscriptable] func(wsMessage) (T, error)

type Info

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

func NewInfo

func NewInfo(
	ctx context.Context,
	baseURL string,
	skipWS bool,
	meta *Meta,
	spotMeta *SpotMeta,
	perpDexs *MixedArray,
	opts ...InfoOpt,
) *Info

func NewInfoGoop

func NewInfoGoop(ctx context.Context, baseURL string) *Info

NewInfoGoop builds an Info client (skipWS=true, meta fetched on demand).

func NewInfoGoopDebug

func NewInfoGoopDebug(ctx context.Context, baseURL string) *Info

NewInfoGoopDebug builds an Info client with debug HTTP logging.

func (*Info) AllMids

func (i *Info) AllMids(ctx context.Context, 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) AllPerpMetas

func (i *Info) AllPerpMetas(ctx context.Context) ([]*Meta, error)

allPerpMetas Retrieve all perpetuals metadata (universe and margin tables)

func (*Info) CandlesSnapshot

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

func (*Info) CoinToAsset

func (i *Info) CoinToAsset(coin string) (int, bool)

func (*Info) FrontendOpenOrders

func (i *Info) FrontendOpenOrders(
	ctx context.Context,
	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(
	ctx context.Context,
	name string,
	startTime int64,
	endTime *int64,
) ([]FundingHistory, error)

func (*Info) HistoricalOrders

func (i *Info) HistoricalOrders(ctx context.Context, address string) ([]OrderQueryResponse, error)

func (*Info) L2Snapshot

func (i *Info) L2Snapshot(ctx context.Context, name string) (*L2Book, error)

func (*Info) Meta

func (i *Info) Meta(ctx context.Context, 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(
	ctx context.Context,
	params MetaAndAssetCtxsParams,
) (*MetaAndAssetCtxs, error)

MetaAndAssetCtxs retrieves perpetuals metadata and asset contexts If params.Dex is nil or empty string, returns data for the first perp dex (default)

func (*Info) MetaGoop

func (i *Info) MetaGoop(ctx context.Context) (*Meta, error)

MetaGoop fetches perp meta for the default dex (empty string).

func (*Info) OpenOrders

func (i *Info) OpenOrders(ctx context.Context, 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) PerpDeployAuctionStatus

func (i *Info) PerpDeployAuctionStatus(ctx context.Context) (*PerpDeployAuctionStatus, error)

PerpDeployAuctionStatus retrieves information about the Perp Deploy Auction

func (*Info) PerpDexLimits

func (i *Info) PerpDexLimits(ctx context.Context, dex string) (*PerpDexLimits, error)

PerpDexLimits retrieves builder-deployed perp market limits dex must be a non-empty string (the empty string is not allowed for this endpoint)

func (*Info) PerpDexStatus

func (i *Info) PerpDexStatus(ctx context.Context, dex string) (*PerpDexStatus, error)

PerpDexStatus retrieves perp market status If dex is empty string, returns status for the first perp dex (default)

func (*Info) PerpDexs

func (i *Info) PerpDexs(ctx context.Context) (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) Portfolio

func (i *Info) Portfolio(ctx context.Context, user string) ([]Portfolio, error)

portfolio returns the user's portfolio

func (*Info) QueryOrderByCloid

func (i *Info) QueryOrderByCloid(
	ctx context.Context,
	user, cloid string,
) (*OrderQueryResult, error)

func (*Info) QueryOrderByOid

func (i *Info) QueryOrderByOid(
	ctx context.Context,
	user string,
	oid int64,
) (*OrderQueryResult, error)

func (*Info) QueryReferralState

func (i *Info) QueryReferralState(ctx context.Context, user string) (*ReferralState, error)

func (*Info) QuerySubAccounts

func (i *Info) QuerySubAccounts(ctx context.Context, user string) ([]SubAccount, error)

func (*Info) QueryUserAbstractionState

func (i *Info) QueryUserAbstractionState(ctx context.Context, user string) (string, error)

QueryUserAbstractionState returns the user's abstraction state

func (*Info) QueryUserDexAbstractionState

func (i *Info) QueryUserDexAbstractionState(ctx context.Context, user string) (string, error)

QueryUserDexAbstractionState returns the user's dex abstraction state

func (*Info) QueryUserToMultiSigSigners

func (i *Info) QueryUserToMultiSigSigners(
	ctx context.Context,
	multiSigUser string,
) ([]MultiSigSigner, error)

func (*Info) QueryUserVaultEquities

func (i *Info) QueryUserVaultEquities(ctx context.Context, user string) ([]VaultEquity, error)

QueryUserVaultEquities returns Retrieve a user's vault deposits

func (*Info) QueryVaultDetails

func (i *Info) QueryVaultDetails(ctx context.Context, VaultAddress string, user string) (*VaultDetails, error)

QueryVaultDetails returns the details of a vault.

func (*Info) SpotMeta

func (i *Info) SpotMeta(ctx context.Context) (*SpotMeta, error)

func (*Info) SpotMetaAndAssetCtxs

func (i *Info) SpotMetaAndAssetCtxs(ctx context.Context) (*SpotMetaAndAssetCtxs, error)

func (*Info) SpotUserState

func (i *Info) SpotUserState(ctx context.Context, address string) (*SpotUserState, error)

func (*Info) TokenDetails

func (i *Info) TokenDetails(ctx context.Context, tokenId string) (*TokenDetail, error)

func (*Info) UserActiveAssetData

func (i *Info) UserActiveAssetData(
	ctx context.Context,
	address string,
	coin string,
) (*UserActiveAssetData, error)

func (*Info) UserFees

func (i *Info) UserFees(ctx context.Context, address string) (*UserFees, error)

func (*Info) UserFills

func (i *Info) UserFills(ctx context.Context, params UserFillsParams) ([]Fill, error)

func (*Info) UserFillsByTime

func (i *Info) UserFillsByTime(
	ctx context.Context,
	address string,
	startTime int64,
	endTime *int64,
	aggregateByTime *bool,
) ([]Fill, error)

func (*Info) UserFundingHistory

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

func (*Info) UserNonFundingLedgerUpdates

func (i *Info) UserNonFundingLedgerUpdates(
	ctx context.Context,
	user string,
	startTime int64,
	endTime *int64,
) ([]UserNonFundingLedgerUpdates, error)

func (*Info) UserStakingDelegations

func (i *Info) UserStakingDelegations(
	ctx context.Context,
	address string,
) ([]StakingDelegation, error)

func (*Info) UserStakingRewards

func (i *Info) UserStakingRewards(ctx context.Context, address string) ([]StakingReward, error)

func (*Info) UserStakingSummary

func (i *Info) UserStakingSummary(ctx context.Context, address string) (*StakingSummary, error)

func (*Info) UserState

func (i *Info) UserState(ctx context.Context, 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 InfoOpt

type InfoOpt = Opt[Info]

func InfoOptClientOptions

func InfoOptClientOptions(opts ...ClientOpt) InfoOpt

InfoOptClientOptions allows passing of ClientOpt to Info

func InfoOptDebugMode

func InfoOptDebugMode() InfoOpt

func InfoOptPerpDexName

func InfoOptPerpDexName(dex string) InfoOpt

type L1ActionSigner

type L1ActionSigner interface {
	SignL1Action(
		ctx context.Context,
		action any,
		vaultAddress string,
		timestamp int64,
		expiresAfter *int64,
		isMainnet bool,
	) (SignatureResult, error)
}

L1ActionSigner signs L1 actions (msgpack + phantom agent EIP-712). When nil on Exchange, the default ECDSA implementation is used.

func ECDSAL1Signer

func ECDSAL1Signer(pk *ecdsa.PrivateKey) L1ActionSigner

ECDSAL1Signer implements L1ActionSigner using an ECDSA private key.

type L2Book

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

func (L2Book) Key

func (c L2Book) Key() string

type L2BookSubscriptionParams

type L2BookSubscriptionParams struct {
	Coin     string
	NSigFigs int
	Mantissa int
	Fast     bool
}

type LeadingVault

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

type LedgerDelta

type LedgerDelta struct {
	Type           string `json:"type"`
	USDC           string `json:"usdc"`
	User           string `json:"user"`
	Destination    string `json:"destination"`
	Fee            string `json:"fee"`
	Token          string `json:"token"`
	UsdcValue      string `json:"usdcValue"`
	SourceDex      string `json:"sourceDex"`
	DestinationDex string `json:"destinationDex"`
}

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 Tif `json:"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

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

type MarginTier

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

type Meta

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

type MetaAndAssetCtxs

type MetaAndAssetCtxs struct {
	Meta
	Ctxs []AssetCtx
}

This type has no JSON annotation because it cannot be directly unmarshalled from the response

type MetaAndAssetCtxsParams

type MetaAndAssetCtxsParams struct {
	// Dex specifies the DEX to query. If nil or empty string, queries the default (first) perp dex.
	Dex *string
}

MetaAndAssetCtxsParams contains optional parameters for MetaAndAssetCtxs request

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 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   *int64
	Cloid *Cloid
	Order CreateOrderRequest
}

ModifyOrderRequest identifies an order by either exchange-provided Oid or client-provided Cloid. Exactly one of Oid or Cloid must be non-nil.

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 Notification

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

func (Notification) Key

func (n Notification) Key() string

type NotificationSubscriptionParams

type NotificationSubscriptionParams struct {
	User string
}

type OpenOrder

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

type OpenOrders

type OpenOrders struct {
	Dex    string         `json:"dex"`
	User   string         `json:"user"`
	Orders []WsBasicOrder `json:"orders"`
}

func (OpenOrders) Key

func (o OpenOrders) Key() string

type OpenOrdersSubscriptionParams

type OpenOrdersSubscriptionParams struct {
	User string
	Dex  *string
}

type Opt

type Opt[T any] func(*T)

func (Opt[T]) Apply

func (o Opt[T]) Apply(opt *T)

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 OrderFillsSubscriptionParams

type OrderFillsSubscriptionParams struct {
	User string
}

type OrderQueryResponse

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

type OrderQueryResult

type OrderQueryResult struct {
	Status OrderQueryStatus   `json:"status"`
	Order  OrderQueryResponse `json:"order,omitempty"`
}

type OrderQueryStatus

type OrderQueryStatus string
const (
	OrderQueryStatusSuccess OrderQueryStatus = "order"
	OrderQueryStatusError   OrderQueryStatus = "unknownOid"
)

type OrderResponse

type OrderResponse struct {
	Statuses []OrderStatus
}

type OrderSide

type OrderSide string
const (
	OrderSideAsk OrderSide = "A"
	OrderSideBid OrderSide = "B"
)

type OrderStatus

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

func (*OrderStatus) String

func (s *OrderStatus) String() string

type OrderStatusFilled

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

type OrderStatusResting

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

type OrderStatusValue

type OrderStatusValue string
const (
	// Placed successfully
	OrderStatusValueOpen OrderStatusValue = "open"
	// Filled
	OrderStatusValueFilled OrderStatusValue = "filled"
	// Canceled by user
	OrderStatusValueCanceled OrderStatusValue = "canceled"
	// Trigger order triggered
	OrderStatusValueTriggered OrderStatusValue = "triggered"
	// Rejected at time of placement
	OrderStatusValueRejected OrderStatusValue = "rejected"
	// Canceled because insufficient margin to fill
	OrderStatusValueMarginCanceled OrderStatusValue = "marginCanceled"
	// Vaults only. Canceled due to a user's withdrawal from vault
	OrderStatusValueVaultWithdrawalCanceled OrderStatusValue = "vaultWithdrawalCanceled"
	// Canceled due to order being too aggressive when open interest was at cap
	OrderStatusValueOpenInterestCapCanceled OrderStatusValue = "openInterestCapCanceled"
	// Canceled due to self-trade prevention
	OrderStatusValueSelfTradeCanceled OrderStatusValue = "selfTradeCanceled"
	// Canceled reduced-only order that does not reduce position
	OrderStatusValueReduceOnlyCanceled OrderStatusValue = "reduceOnlyCanceled"
	// TP/SL only. Canceled due to sibling ordering being filled
	OrderStatusValueSiblingFilledCanceled OrderStatusValue = "siblingFilledCanceled"
	// Canceled due to asset delisting
	OrderStatusValueDelistedCanceled OrderStatusValue = "delistedCanceled"
	// Canceled due to liquidation
	OrderStatusValueLiquidatedCanceled OrderStatusValue = "liquidatedCanceled"
	// API only. Canceled due to exceeding scheduled cancel deadline (dead man's switch)
	OrderStatusValueScheduledCancel OrderStatusValue = "scheduledCancel"
	// Rejected due to invalid tick price
	OrderStatusValueTickRejected OrderStatusValue = "tickRejected"
	// Rejected due to order notional below minimum
	OrderStatusValueMinTradeNtlRejected OrderStatusValue = "minTradeNtlRejected"
	// Rejected due to insufficient margin
	OrderStatusValuePerpMarginRejected OrderStatusValue = "perpMarginRejected"
	// Rejected due to reduce only
	OrderStatusValueReduceOnlyRejected OrderStatusValue = "reduceOnlyRejected"
	// Rejected due to post-only immediate match
	OrderStatusValueBadAloPxRejected OrderStatusValue = "badAloPxRejected"
	// Rejected due to IOC not able to match
	OrderStatusValueIocCancelRejected OrderStatusValue = "iocCancelRejected"
	// Rejected due to invalid TP/SL price
	OrderStatusValueBadTriggerPxRejected OrderStatusValue = "badTriggerPxRejected"
	// Rejected due to lack of liquidity for market order
	OrderStatusValueMarketOrderNoLiquidityRejected OrderStatusValue = "marketOrderNoLiquidityRejected"
	// Rejected due to open interest cap
	OrderStatusValuePositionIncreaseAtOpenInterestCapRejected OrderStatusValue = "positionIncreaseAtOpenInterestCapRejected"
	// Rejected due to open interest cap
	OrderStatusValuePositionFlipAtOpenInterestCapRejected OrderStatusValue = "positionFlipAtOpenInterestCapRejected"
	// Rejected due to price too aggressive at open interest cap
	OrderStatusValueTooAggressiveAtOpenInterestCapRejected OrderStatusValue = "tooAggressiveAtOpenInterestCapRejected"
	// Rejected due to open interest cap
	OrderStatusValueOpenInterestIncreaseRejected OrderStatusValue = "openInterestIncreaseRejected"
	// Rejected due to insufficient spot balance
	OrderStatusValueInsufficientSpotBalanceRejected OrderStatusValue = "insufficientSpotBalanceRejected"
	// Rejected due to price too far from oracle
	OrderStatusValueOracleRejected OrderStatusValue = "oracleRejected"
	// Rejected due to exceeding margin tier limit at current leverage
	OrderStatusValuePerpMaxPositionRejected OrderStatusValue = "perpMaxPositionRejected"
)

type OrderType

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

type OrderUpdatesSubscriptionParams

type OrderUpdatesSubscriptionParams struct {
	User string
}

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  OrderWireType `json:"t"           msgpack:"t"`           // 6th
	Cloid      *string       `json:"c,omitempty" msgpack:"c,omitempty"` // 7th (optional)
}

OrderWire represents the wire format for orders with deterministic field ordering CRITICAL: Field order MUST exactly match Python SDK insertion order: a, b, p, s, r, t, c See hyperliquid-python-sdk/hyperliquid/utils/signing.py:order_request_to_order_wire

type OrderWireType

type OrderWireType struct {
	Limit   *OrderWireTypeLimit   `json:"limit,omitempty"   msgpack:"limit,omitempty"`
	Trigger *OrderWireTypeTrigger `json:"trigger,omitempty" msgpack:"trigger,omitempty"`
}

OrderWireType represents the type of order (limit or trigger).

type OrderWireTypeLimit

type OrderWireTypeLimit struct {
	Tif Tif `json:"tif,string" msgpack:"tif"`
}

OrderWireTypeLimit represents a limit order with time-in-force.

type OrderWireTypeTrigger

type OrderWireTypeTrigger struct {
	// CRITICAL: Field order MUST match Python SDK insertion order: isMarket, triggerPx, tpsl
	// See hyperliquid-python-sdk/hyperliquid/utils/signing.py:order_type_to_wire (lines 151-154)
	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"
}

OrderWireTypeTrigger represents a trigger order (stop-loss/take-profit).

type PerpDeployAuctionStatus

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 PerpDeployHaltTradingAction

type PerpDeployHaltTradingAction struct {
	Type        string      `json:"type"        msgpack:"type"`
	HaltTrading HaltTrading `json:"haltTrading" msgpack:"haltTrading"`
}

type PerpDeployRegisterAsset2Action

type PerpDeployRegisterAsset2Action struct {
	Type           string         `json:"type"           msgpack:"type"`
	RegisterAsset2 RegisterAsset2 `json:"registerAsset2" msgpack:"registerAsset2"`
}

type PerpDeployRegisterAssetAction

type PerpDeployRegisterAssetAction struct {
	Type          string        `json:"type"          msgpack:"type"`
	RegisterAsset RegisterAsset `json:"registerAsset" msgpack:"registerAsset"`
}

type PerpDeployResponse

type PerpDeployResponse struct {
	Status string `json:"status"`
	// Response is either a string or object `{"type": "...", ...}`
	Response json.RawMessage `json:"response,omitempty"`
	Data     struct {
		Statuses []TxStatus `json:"statuses"`
	} `json:"data"`
}

type PerpDeploySetOracleAction

type PerpDeploySetOracleAction struct {
	Type      string    `json:"type"      msgpack:"type"`
	SetOracle SetOracle `json:"setOracle" msgpack:"setOracle"`
}

type PerpDex

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

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 PerpDexState

type PerpDexState struct {
	TotalVaultEquity       float64         `json:"totalVaultEquity,string"`
	PerpsAtOpenInterestCap *[]string       `json:"perpsAtOpenInterestCap,omitempty"`
	LeadingVaults          *[]LeadingVault `json:"leadingVaults,omitempty"`
}

type PerpDexStatus

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

PerpDexStatus represents status for a builder-deployed perp DEX

type Portfolio

type Portfolio []MixedValue // [string, AccountHistory]

Portfolio represents a user's portfolio

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"`
	CumFunding     *CumFunding `json:"cumFunding,omitempty"`
}

type QueriedOrder

type QueriedOrder struct {
	Coin             string         `json:"coin"`
	Side             OrderSide      `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         []QueriedOrder `json:"children"`
	IsPositionTpsl   bool           `json:"isPositionTpsl"`
	ReduceOnly       bool           `json:"reduceOnly"`
	OrderType        string         `json:"orderType"`
	OrigSz           string         `json:"origSz"`
	Tif              Tif            `json:"tif"`
	Cloid            *string        `json:"cloid"`
}

type ReferralState

type ReferralState struct {
	ReferralCode string   `json:"referralCode"`
	Referrer     string   `json:"referrer"`
	Referred     []string `json:"referred"`
}

type RegisterAsset

type RegisterAsset struct {
	MaxGas       *int                 `json:"maxGas"       msgpack:"maxGas"`
	AssetRequest AssetRequest         `json:"assetRequest" msgpack:"assetRequest"`
	Dex          string               `json:"dex"          msgpack:"dex"`
	Schema       *RegisterAssetSchema `json:"schema"       msgpack:"schema"`
}

type RegisterAsset2

type RegisterAsset2 struct {
	MaxGas       *int                 `json:"maxGas"       msgpack:"maxGas"`
	AssetRequest AssetRequest2        `json:"assetRequest" msgpack:"assetRequest"`
	Dex          string               `json:"dex"          msgpack:"dex"`
	Schema       *RegisterAssetSchema `json:"schema"       msgpack:"schema"`
}

type RegisterAssetSchema

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

type ReserveRequestWeightAction

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

ReserveRequestWeightAction reserves request weight capacity Weight reservation costs 0.0005 USDC per weight unit

type ReserveRequestWeightResponse

type ReserveRequestWeightResponse struct {
	Status   string               `json:"status"`
	Response *ReserveResponseData `json:"response,omitempty"`
	Error    string               `json:"error,omitempty"`
}

type ReserveResponseData

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

ReserveResponseData represents the parsed success data from a 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 SetOracle

type SetOracle struct {
	Dex             string       `json:"dex"             msgpack:"dex"`
	OraclePxs       [][]string   `json:"oraclePxs"       msgpack:"oraclePxs"`
	MarkPxs         [][][]string `json:"markPxs"         msgpack:"markPxs"`
	ExternalPerpPxs [][]string   `json:"externalPerpPxs" msgpack:"externalPerpPxs"`
}

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 SharedAssetCtx

type SharedAssetCtx struct {
	DayNtlVlm float64 `json:"dayNtlVlm,string"`
	PrevDayPx float64 `json:"prevDayPx,string"`
	MarkPx    float64 `json:"markPx,string"`
	MidPx     float64 `json:"midPx,string"`

	// PerpsAssetCtx
	Funding      float64 `json:"funding,string,omitempty"`
	OpenInterest float64 `json:"openInterest,string,omitempty"`
	OraclePx     float64 `json:"oraclePx,string,omitempty"`

	// SpotAssetCtx
	CirculatingSupply float64 `json:"circulatingSupply,string,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,
	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 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

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

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 SpotMetaAndAssetCtxs

type SpotMetaAndAssetCtxs struct {
	Meta SpotMeta
	Ctxs []SpotAssetCtx
}

This type has no JSON annotation because it cannot be directly unmarshalled from the response

type SpotState

type SpotState struct {
	Balances []SpotBalance `json:"balances,omitempty"`
}

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 SpotUserState

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

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 {
	ID      string
	Payload any
	Close   func()
}

type Tiers

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

type Tif

type Tif string
const (
	// Add Liquidity Only
	TifAlo Tif = "Alo"
	// Immediate or Cancel
	TifIoc Tif = "Ioc"
	// Good Till Cancel
	TifGtc Tif = "Gtc"
)

Order Time-in-Force constants

type TokenDelegateAction

type TokenDelegateAction struct {
	Type         string `json:"type"         msgpack:"type"`
	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 TokenDetail

type TokenDetail struct {
	Name                       string              `json:"name"`
	MaxSupply                  string              `json:"maxSupply"`
	TotalSupply                string              `json:"totalSupply"`
	CirculatingSupply          string              `json:"circulatingSupply"`
	SzDecimals                 int                 `json:"szDecimals"`
	WeiDecimals                int                 `json:"weiDecimals"`
	MidPx                      string              `json:"midPx"`
	MarkPx                     string              `json:"markPx"`
	PrevDayPx                  string              `json:"prevDayPx"`
	Genesis                    *TokenDetailGenesis `json:"genesis"`
	Deployer                   *string             `json:"deployer"`
	DeployGas                  *string             `json:"deployGas"`
	DeployTime                 *string             `json:"deployTime"`
	SeededUsdc                 string              `json:"seededUsdc"`
	NonCirculatingUserBalances [][]string          `json:"nonCirculatingUserBalances"`
	FutureEmissions            string              `json:"futureEmissions"`
}

type TokenDetailGenesis

type TokenDetailGenesis struct {
	UserBalances          [][]string   `json:"userBalances"`
	ExistingTokenBalances []MixedArray `json:"existingTokenBalances"`
}

type Tpsl

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

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 Trades

type Trades []Trade

func (Trades) Key

func (t Trades) Key() string

type TradesSubscriptionParams

type TradesSubscriptionParams struct {
	Coin string
}

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" msgpack:"triggerPx"`
	IsMarket  bool    `json:"isMarket"  msgpack:"isMarket"`
	Tpsl      Tpsl    `json:"tpsl"      msgpack:"tpsl"` // "tp" or "sl"
}

type Tuple2

type Tuple2[E1 any, E2 any] struct {
	First  E1
	Second E2
}

func (Tuple2[E1, E2]) MarshalJSON

func (t Tuple2[E1, E2]) MarshalJSON() ([]byte, error)

func (*Tuple2[E1, E2]) UnmarshalJSON

func (t *Tuple2[E1, E2]) UnmarshalJSON(data []byte) error

type TwapState

type TwapState struct {
	Coin        string  `json:"coin"`
	User        string  `json:"user"`
	Side        string  `json:"side"`
	Sz          float64 `json:"sz,string"`
	ExecutedSz  float64 `json:"executedSz,string"`
	ExecutedNtl float64 `json:"executedNtl,string"`
	Minutes     int     `json:"minutes"`
	ReduceOnly  bool    `json:"reduceOnly"`
	Randomize   bool    `json:"randomize"`
	Timestamp   int64   `json:"timestamp"`
}

type TwapStates

type TwapStates struct {
	Dex    string                   `json:"dex"`
	User   string                   `json:"user"`
	States []Tuple2[int, TwapState] `json:"states"`
}

func (TwapStates) Key

func (t TwapStates) Key() string

type TwapStatesSubscriptionParams

type TwapStatesSubscriptionParams struct {
	User string
	Dex  *string
}

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 UserActiveAssetData

type UserActiveAssetData struct {
	User             string   `json:"user"`
	Coin             string   `json:"coin"`
	Leverage         Leverage `json:"leverage"`
	MaxTradeSzs      []string `json:"maxTradeSzs"`
	AvailableToTrade []string `json:"availableToTrade"`
	MarkPx           string   `json:"markPx"`
}

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"`
	UserSpotCrossRate      string       `json:"userSpotCrossRate"`
	UserSpotAddRate        string       `json:"userSpotAddRate"`
}

type UserFillsParams

type UserFillsParams struct {
	Address         string
	AggregateByTime *bool
}

type UserFundingHistory

type UserFundingHistory struct {
	Delta Delta  `json:"delta"`
	Hash  string `json:"hash"`
	Time  int64  `json:"time"`
}

type UserNonFundingLedgerUpdates

type UserNonFundingLedgerUpdates struct {
	Delta LedgerDelta `json:"delta"`
	Hash  string      `json:"hash"`
	Time  int64       `json:"time"`
}

type UserSignedActionSigner

type UserSignedActionSigner interface {
	SignUserSignedAction(
		ctx context.Context,
		action map[string]any,
		payloadTypes []apitypes.Type,
		primaryType string,
		isMainnet bool,
	) (SignatureResult, error)
}

UserSignedActionSigner signs direct EIP-712 user-signed actions. When nil on Exchange, the default ECDSA implementation is used.

func ECDSAUserSignedSigner

func ECDSAUserSignedSigner(pk *ecdsa.PrivateKey) UserSignedActionSigner

ECDSAUserSignedSigner implements UserSignedActionSigner using an ECDSA private key.

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 VaultDetails

type VaultDetails struct {
	Name                  string             `json:"name"`
	VaultAddress          string             `json:"vaultAddress"`
	Leader                string             `json:"leader"`
	Description           string             `json:"description"`
	Portfolio             Portfolio          `json:"portfolio"`
	Apr                   float64            `json:"apr"`
	FollowerState         json.RawMessage    `json:"followerState"`
	LeaderFraction        float64            `json:"leaderFraction"`
	LeaderCommission      float64            `json:"leaderCommission"`
	Followers             []VaultFollower    `json:"followers"`
	MaxDistributable      float64            `json:"maxDistributable"`
	MaxWithdrawable       float64            `json:"maxWithdrawable"`
	IsClosed              bool               `json:"isClosed"`
	Relationship          *VaultRelationship `json:"relationship"`
	AllowDeposits         bool               `json:"allowDeposits"`
	AlwaysCloseOnWithdraw bool               `json:"alwaysCloseOnWithdraw"`
}

type VaultDistributeAction

type VaultDistributeAction struct {
	Type         string `json:"type"         msgpack:"type"`
	VaultAddress string `json:"vaultAddress" msgpack:"vaultAddress"`
	Usd          int    `json:"usd"          msgpack:"usd"`
}

VaultDistributeAction represents vault distribute action

type VaultEquity

type VaultEquity struct {
	LockedUntilTimestamp int64  `json:"lockedUntilTimestamp"`
	Equity               string `json:"equity"`
	VaultAddress         string `json:"vaultAddress"`
}

VaultEquity represents a user's vault equity

type VaultFollower

type VaultFollower struct {
	User           string `json:"user"`
	VaultEquity    string `json:"vaultEquity"`
	Pnl            string `json:"pnl"`
	AllTimePnl     string `json:"allTimePnl"`
	DaysFollowing  int    `json:"daysFollowing"`
	VaultEntryTime int64  `json:"vaultEntryTime"`
	LockupUntil    int64  `json:"lockupUntil"`
}

type VaultModifyAction

type VaultModifyAction struct {
	Type                  string `json:"type"                  msgpack:"type"`
	VaultAddress          string `json:"vaultAddress"          msgpack:"vaultAddress"`
	AllowDeposits         bool   `json:"allowDeposits"         msgpack:"allowDeposits"`
	AlwaysCloseOnWithdraw bool   `json:"alwaysCloseOnWithdraw" msgpack:"alwaysCloseOnWithdraw"`
}

VaultModifyAction represents vault modify action

type VaultRelationship

type VaultRelationship struct {
	Type string `json:"type"`
	Data struct {
		ChildAddresses []string `json:"childAddresses"`
	} `json:"data"`
}

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 WebData2

type WebData2 struct {
	ClearinghouseState     *ClearinghouseState `json:"clearinghouseState,omitempty"`
	LeadingVaults          []any               `json:"leadingVaults,omitempty"`
	TotalVaultEquity       string              `json:"totalVaultEquity,omitempty"`
	OpenOrders             []WsBasicOrder      `json:"openOrders,omitempty"`
	AgentAddress           *string             `json:"agentAddress,omitempty"`
	AgentValidUntil        *int64              `json:"agentValidUntil,omitempty"`
	CumLedger              string              `json:"cumLedger,omitempty"`
	Meta                   *WebData2Meta       `json:"meta,omitempty"`
	AssetCtxs              []AssetCtx          `json:"assetCtxs,omitempty"`
	ServerTime             int64               `json:"serverTime,omitempty"`
	IsVault                bool                `json:"isVault,omitempty"`
	User                   string              `json:"user,omitempty"`
	TwapStates             []any               `json:"twapStates,omitempty"`
	SpotState              *SpotState          `json:"spotState,omitempty"`
	SpotAssetCtxs          []SpotAssetCtx      `json:"spotAssetCtxs,omitempty"`
	PerpsAtOpenInterestCap []string            `json:"perpsAtOpenInterestCap,omitempty"`
}

func (WebData2) Key

func (w WebData2) Key() string

type WebData2AssetInfo

type WebData2AssetInfo struct {
	SzDecimals    int    `json:"szDecimals,omitempty"`
	Name          string `json:"name,omitempty"`
	MaxLeverage   int    `json:"maxLeverage,omitempty"`
	MarginTableID int    `json:"marginTableId,omitempty"`
	IsDelisted    bool   `json:"isDelisted,omitempty"`
	OnlyIsolated  bool   `json:"onlyIsolated,omitempty"`
}

type WebData2MarginTable

type WebData2MarginTable struct {
	Description string               `json:"description,omitempty"`
	MarginTiers []WebData2MarginTier `json:"marginTiers,omitempty"`
}

type WebData2MarginTier

type WebData2MarginTier struct {
	LowerBound  string `json:"lowerBound,omitempty"`
	MaxLeverage int    `json:"maxLeverage,omitempty"`
}

type WebData2Meta

type WebData2Meta struct {
	Universe     []WebData2AssetInfo                `json:"universe,omitempty"`
	MarginTables []Tuple2[int, WebData2MarginTable] `json:"marginTables,omitempty"`
}

type WebData2SubscriptionParams

type WebData2SubscriptionParams struct {
	User string
}

type WebData3

type WebData3 struct {
	UserState     WebData3UserState `json:"userState"`
	PerpDexStates []PerpDexState    `json:"perpDexStates"`
}

func (WebData3) Key

func (w WebData3) Key() string

type WebData3SubscriptionParams

type WebData3SubscriptionParams struct {
	User string
	Dex  *string
}

type WebData3UserState

type WebData3UserState struct {
	AgentAddress          *string `json:"agentAddress,omitempty"`
	AgentValidUntil       *int64  `json:"agentValidUntil,omitempty"`
	ServerTime            int64   `json:"serverTime"`
	CumLedger             float64 `json:"cumLedger,string"`
	IsVault               bool    `json:"isVault"`
	User                  string  `json:"user"`
	OptOutOfSpotDusting   *bool   `json:"optOutOfSpotDusting,omitempty"`
	DexAbstractionEnabled *bool   `json:"dexAbstractionEnabled,omitempty"`
}

type WebsocketClient

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

func NewWebsocketClient

func NewWebsocketClient(baseURL string, opts ...WsOpt) *WebsocketClient

func NewWebsocketClientGoop

func NewWebsocketClientGoop(baseURL string) *WebsocketClient

NewWebsocketClientGoop builds a WebsocketClient for the given API base URL.

func (*WebsocketClient) ActiveAssetCtx

func (w *WebsocketClient) ActiveAssetCtx(
	params ActiveAssetCtxSubscriptionParams,
	callback func(ActiveAssetCtx, error),
) (*Subscription, error)

func (*WebsocketClient) AllMids

func (w *WebsocketClient) AllMids(
	params AllMidsSubscriptionParams,
	callback func(AllMids, error),
) (*Subscription, error)

func (*WebsocketClient) Bbo

func (w *WebsocketClient) Bbo(
	params BboSubscriptionParams,
	callback func(Bbo, error),
) (*Subscription, error)

func (*WebsocketClient) Candles

func (w *WebsocketClient) Candles(
	params CandlesSubscriptionParams,
	callback func(Candle, error),
) (*Subscription, error)

func (*WebsocketClient) ClearinghouseState

func (w *WebsocketClient) ClearinghouseState(
	params ClearinghouseStateSubscriptionParams,
	callback func(ClearinghouseState, error),
) (*Subscription, error)

func (*WebsocketClient) Close

func (w *WebsocketClient) Close() error

func (*WebsocketClient) Connect

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

func (*WebsocketClient) L2Book

func (w *WebsocketClient) L2Book(
	params L2BookSubscriptionParams,
	callback func(L2Book, error),
) (*Subscription, error)

func (*WebsocketClient) Notification

func (w *WebsocketClient) Notification(
	params NotificationSubscriptionParams,
	callback func(Notification, error),
) (*Subscription, error)

func (*WebsocketClient) OpenOrders

func (w *WebsocketClient) OpenOrders(
	params OpenOrdersSubscriptionParams,
	callback func(OpenOrders, error),
) (*Subscription, error)

func (*WebsocketClient) OrderFills

func (w *WebsocketClient) OrderFills(
	params OrderFillsSubscriptionParams,
	callback func(WsOrderFills, error),
) (*Subscription, error)

func (*WebsocketClient) OrderUpdates

func (w *WebsocketClient) OrderUpdates(
	params OrderUpdatesSubscriptionParams,
	callback func([]WsOrder, error),
) (*Subscription, error)

func (*WebsocketClient) Trades

func (w *WebsocketClient) Trades(
	params TradesSubscriptionParams,
	callback func([]Trade, error),
) (*Subscription, error)

func (*WebsocketClient) TwapStates

func (w *WebsocketClient) TwapStates(
	params TwapStatesSubscriptionParams,
	callback func(TwapStates, error),
) (*Subscription, error)

func (*WebsocketClient) WebData2

func (w *WebsocketClient) WebData2(
	params WebData2SubscriptionParams,
	callback func(WebData2, error),
) (*Subscription, error)

func (*WebsocketClient) WebData3

func (w *WebsocketClient) WebData3(
	params WebData3SubscriptionParams,
	callback func(WebData3, error),
) (*Subscription, error)

type WithdrawFromBridgeAction

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

WithdrawFromBridgeAction represents withdraw from bridge action

type WsBasicOrder

type WsBasicOrder 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"`
	Cloid     *string `json:"cloid"`
}

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 WsOpt

type WsOpt = Opt[WebsocketClient]

func WsOptDebugMode

func WsOptDebugMode() WsOpt

func WsOptDialer

func WsOptDialer(dialer *websocket.Dialer) WsOpt

WsOptDialer allows setting a custom websocket.Dialer

func WsOptReadTimeout

func WsOptReadTimeout(timeout time.Duration) WsOpt

WsOptReadTimeout sets the maximum duration to wait for a single read from the server. If no message is received within the timeout the connection is closed and a reconnection is attempted. Must exceed the internal ping interval (50 s). Defaults to 90 s.

type WsOrder

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

type WsOrderFill

type WsOrderFill struct {
	Coin          string           `json:"coin"`
	Px            string           `json:"px"` // price
	Sz            string           `json:"sz"` // size
	Side          string           `json:"side"`
	Time          int64            `json:"time"`
	StartPosition string           `json:"startPosition"`
	Dir           string           `json:"dir"` // used for frontend display
	ClosedPnl     string           `json:"closedPnl"`
	Hash          string           `json:"hash"`    // L1 transaction hash
	Oid           int64            `json:"oid"`     // order id
	Crossed       bool             `json:"crossed"` // whether order crossed the spread (was taker)
	Fee           string           `json:"fee"`     // negative means rebate
	Tid           int64            `json:"tid"`     // unique trade id
	Liquidation   *FillLiquidation `json:"liquidation,omitempty"`
	FeeToken      string           `json:"feeToken"`             // the token the fee was paid in
	BuilderFee    *string          `json:"builderFee,omitempty"` // amount paid to builder, also included in fee
}

type WsOrderFills

type WsOrderFills struct {
	IsSnapshot bool          `json:"isSnapshot"`
	User       string        `json:"user"`
	Fills      []WsOrderFill `json:"fills"`
}

func (WsOrderFills) Key

func (w WsOrderFills) Key() string

type WsOrders

type WsOrders []WsOrder

func (WsOrders) Key

func (w WsOrders) Key() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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