hyperliquid

package module
v0.0.0-...-67e033d Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2025 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TifGtc string = "Gtc"
	TifIoc string = "Ioc"
	TifAlo string = "Alo"
)
View Source
const ARBITRUM_CHAIN_ID = 42161
View Source
const ARBITRUM_TESTNET_CHAIN_ID = 421614
View Source
const DEFAULT_SLIPPAGE = 0.005 // 0.5% default slippage

Execution constants

View Source
const GLOBAL_DEBUG = false // Default debug that is used in all tests
View Source
const HYPERLIQUID_CHAIN_ID = 1337

Signing constants

View Source
const PERP_MAX_DECIMALS = 6 // Default decimals for perp
View Source
const SPOT_MAX_DECIMALS = 8 // Default decimals for spot
View Source
const VERIFYING_CONTRACT = "0x0000000000000000000000000000000000000000"

Variables

View Source
var SZ_DECIMALS = 2 // Default decimals for usdc

Functions

func ArrayAppend

func ArrayAppend(data []byte, toAppend []byte) []byte

func CalculateSlippage

func CalculateSlippage(isBuy bool, px float64, slippage float64) float64

Calculate the slippage of a trade

func FloatToWire

func FloatToWire(x float64, maxDecimals int, szDecimals int) string

Format the float with custom decimal places, default is 6 (perp), 8 (spot). https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size

func GetDefaultTimeRange

func GetDefaultTimeRange() (int64, int64)

Returns default time range of 90 days Returns the start time and end time in milliseconds

func GetNonce

func GetNonce() uint64

Hyperliquid uses timestamps in milliseconds for nonce

func GetRandomCloid

func GetRandomCloid() string

Retruns a random cloid (Client Order ID)

func GetSlippage

func GetSlippage(sl *float64) float64

Get the slippage of a trade Returns the default slippage if the slippage is nil

func HexToBytes

func HexToBytes(addr string) []byte

func IsBuy

func IsBuy(szi float64) bool

func MakeUniversalRequest

func MakeUniversalRequest[T any](api IAPIService, request any) (*T, error)

MakeUniversalRequest is a generic function that takes an IAPIService and a request and returns a pointer to the result and an error. It makes a request to the API Service and unmarshals the result into the result type T

func RoundOrderPrice

func RoundOrderPrice(x float64, szDecimals int, maxDecimals int) string

Round the order price to the nearest tick size

func RoundOrderSize

func RoundOrderSize(x float64, szDecimals int) string

Round the order size to the nearest tick size

func SignRequestToEIP712TypedData

func SignRequestToEIP712TypedData(request *SignRequest) apitypes.TypedData

func SignatureToVRS

func SignatureToVRS(sig []byte) (byte, [32]byte, [32]byte, error)

func StructToMap

func StructToMap(strct any) (res map[string]interface{}, err error)

To sign raw messages via EIP-712

Types

type APIError

type APIError struct {
	Message string
}

API implementation general error

func (APIError) Error

func (e APIError) Error() string

type Asset

type Asset struct {
	Name         string `json:"name"`
	SzDecimals   int    `json:"szDecimals"`
	MaxLeverage  int    `json:"maxLeverage"`
	OnlyIsolated bool   `json:"onlyIsolated"`
}

type AssetInfo

type AssetInfo struct {
	SzDecimals  int
	WeiDecimals int
	AssetId     int
	SpotName    string // for spot asset (e.g. "@107")
}

type AssetPosition

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

type CancelCloidOrderAction

type CancelCloidOrderAction struct {
	Type    string            `msgpack:"type" json:"type"`
	Cancels []CancelCloidWire `msgpack:"cancels" json:"cancels"`
}

type CancelCloidWire

type CancelCloidWire struct {
	Asset int    `msgpack:"asset" json:"asset"`
	Cloid string `msgpack:"cloid" json:"cloid"`
}

type CancelOidOrderAction

type CancelOidOrderAction struct {
	Type    string          `msgpack:"type" json:"type"`
	Cancels []CancelOidWire `msgpack:"cancels" json:"cancels"`
}

type CancelOidWire

type CancelOidWire struct {
	Asset int `msgpack:"a" json:"a"`
	Oid   int `msgpack:"o" json:"o"`
}

type CancelOrderResponse

type CancelOrderResponse struct {
	Status   string              `json:"status"`
	Response InnerCancelResponse `json:"response"`
}

type CancelRequest

type CancelRequest struct {
	OrderId int `json:"oid"`
	Coin    int `json:"coin"`
}

type CancelResponseStatuses

type CancelResponseStatuses struct {
	Statuses []string `json:"statuses"`
}

type CandleSnapshot

type CandleSnapshot struct {
	CloseTime int64   `json:"t"`
	OpenTime  int64   `json:"T"`
	Symbol    string  `json:"s"`
	Interval  string  `json:"i"`
	Open      float64 `json:"o,string"`
	Close     float64 `json:"c,string"`
	High      float64 `json:"h,string"`
	Low       float64 `json:"l,string"`
	Volume    float64 `json:"v,string"`
	N         int     `json:"n"`
}

type CandleSnapshotRequest

type CandleSnapshotRequest struct {
	Typez string                   `json:"type"`
	Req   CandleSnapshotSubRequest `json:"req"`
}

type CandleSnapshotSubRequest

type CandleSnapshotSubRequest struct {
	Coin      string `json:"coin"`
	Interval  string `json:"interval"`
	StartTime int64  `json:"startTime"`
	EndTime   int64  `json:"endTime"`
}

type Client

type Client struct {
	Debug bool // Debug mode

	Logger *log.Logger // Logger for debug messages
	// contains filtered or unexported fields
}

Client is the default implementation of the Client interface.

It contains the base URL of the HyperLiquid API, the HTTP client, the debug mode, the network type, the private key, and the logger. The debug method prints the debug messages.

func NewClient

func NewClient(isMainnet bool) *Client

NewClient returns a new instance of the Client struct.

func (*Client) AccountAddress

func (client *Client) AccountAddress() string

Returns the public address connected to the API.

func (*Client) IsMainnet

func (client *Client) IsMainnet() bool

IsMainnet returns true if the client is connected to the mainnet.

func (*Client) KeyManager

func (client *Client) KeyManager() *PKeyManager

Returns the private key manager connected to the API.

func (*Client) Request

func (client *Client) Request(endpoint string, payload any) ([]byte, error)

Request sends a POST request to the HyperLiquid API.

func (*Client) SetAccountAddress

func (client *Client) SetAccountAddress(address string)

Some methods need public address to gather info (from infoAPI). In case you use PKeyManager from API section https://app.hyperliquid.xyz/API Then you can use this method to set the address.

func (*Client) SetDebugActive

func (client *Client) SetDebugActive()

SetDebugActive enables debug mode.

func (*Client) SetPrivateKey

func (client *Client) SetPrivateKey(privateKey string) error

SetPrivateKey sets the private key for the client.

type CloseRequest

type CloseRequest struct {
	Coin     string
	Px       float64
	Sz       float64
	Slippage float64
	Cloid    string
}

type Context

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

type DataResponse

type DataResponse struct {
	Statuses []StatusResponse `json:"statuses"`
}

type DefaultExchangeResponse

type DefaultExchangeResponse struct {
	Status   string `json:"status"`
	Response struct {
		Type string `json:"type"`
	} `json:"response"`
}

type Deposit

type Deposit struct {
	Hash   string  `json:"hash,omitempty"`
	Time   int64   `json:"time,omitempty"`
	Amount float64 `json:"usdc,omitempty"`
}

type ExchangeAPI

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

Implement the IExchangeAPI interface.

func NewExchangeAPI

func NewExchangeAPI(isMainnet bool) *ExchangeAPI

NewExchangeAPI creates a new default ExchangeAPI. Run SetPrivateKey() and SetAccountAddress() to set the private key and account address.

func (*ExchangeAPI) BuildBulkOrdersEIP712

func (api *ExchangeAPI) BuildBulkOrdersEIP712(requests []OrderRequest, grouping Grouping) (apitypes.TypedData, error)

Build bulk orders EIP712 message

func (*ExchangeAPI) BuildEIP712Message

func (api *ExchangeAPI) BuildEIP712Message(action any, timestamp uint64) (*SignRequest, error)

func (*ExchangeAPI) BuildOrderEIP712

func (api *ExchangeAPI) BuildOrderEIP712(request OrderRequest, grouping Grouping) (apitypes.TypedData, error)

Build order EIP712 message

func (*ExchangeAPI) CancelAllOrders

func (api *ExchangeAPI) CancelAllOrders() (*CancelOrderResponse, error)

Cancel all open orders

func (*ExchangeAPI) CancelAllOrdersByCoin

func (api *ExchangeAPI) CancelAllOrdersByCoin(coin string) (*CancelOrderResponse, error)

Cancel all orders for a given coin

func (*ExchangeAPI) CancelOrderByCloid

func (api *ExchangeAPI) CancelOrderByCloid(coin string, clientOID string) (*CancelOrderResponse, error)

Cancel exact order by Client Order Id https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid

func (*ExchangeAPI) CancelOrderByOID

func (api *ExchangeAPI) CancelOrderByOID(coin string, orderID int64) (*CancelOrderResponse, error)

Cancel exact order by OID

func (*ExchangeAPI) ClosePosition

func (api *ExchangeAPI) ClosePosition(coin string) (*PlaceOrderResponse, error)

Close all positions for a given coin. They are closing with a market order.

func (*ExchangeAPI) Endpoint

func (api *ExchangeAPI) Endpoint() string

func (*ExchangeAPI) LimitOrder

func (api *ExchangeAPI) LimitOrder(orderType string, coin string, size float64, px float64, reduceOnly bool, clientOID ...string) (*PlaceOrderResponse, error)

Open a limit order. Order type can be Gtc, Ioc, Alo. Size determines the amount of the coin to buy/sell. See the constants TifGtc, TifIoc, TifAlo.

func (*ExchangeAPI) MarketOrder

func (api *ExchangeAPI) MarketOrder(coin string, size float64, slippage *float64, clientOID ...string) (*PlaceOrderResponse, error)

Open a market order. Limit order with TIF=IOC and px=market price * (1 +- slippage). Size determines the amount of the coin to buy/sell.

MarketOrder("BTC", 0.1, nil) // Buy 0.1 BTC
MarketOrder("BTC", -0.1, nil) // Sell 0.1 BTC
MarketOrder("BTC", 0.1, &slippage) // Buy 0.1 BTC with slippage

func (*ExchangeAPI) MarketOrderSpot

func (api *ExchangeAPI) MarketOrderSpot(coin string, size float64, slippage *float64) (*PlaceOrderResponse, error)

MarketOrderSpot is a market order for a spot coin. It is used to buy/sell a spot coin. Limit order with TIF=IOC and px=market price * (1 +- slippage). Size determines the amount of the coin to buy/sell.

MarketOrderSpot("HYPE", 0.1, nil) // Buy 0.1 HYPE
MarketOrderSpot("HYPE", -0.1, nil) // Sell 0.1 HYPE
MarketOrderSpot("HYPE", 0.1, &slippage) // Buy 0.1 HYPE with slippage

func (*ExchangeAPI) Order

func (api *ExchangeAPI) Order(request OrderRequest, grouping Grouping) (*PlaceOrderResponse, error)

Place single order

func (*ExchangeAPI) OrderSpot

func (api *ExchangeAPI) OrderSpot(request OrderRequest, grouping Grouping) (*PlaceOrderResponse, error)

OrderSpot places a spot order

func (*ExchangeAPI) Sign

func (api *ExchangeAPI) Sign(request *SignRequest) (byte, [32]byte, [32]byte, error)

func (*ExchangeAPI) SignL1Action

func (api *ExchangeAPI) SignL1Action(action any, timestamp uint64) (byte, [32]byte, [32]byte, error)

func (*ExchangeAPI) SignUserSignableAction

func (api *ExchangeAPI) SignUserSignableAction(action any, payloadTypes []apitypes.Type, primaryType string) (byte, [32]byte, [32]byte, error)

func (*ExchangeAPI) SignWithdrawAction

func (api *ExchangeAPI) SignWithdrawAction(action WithdrawAction) (byte, [32]byte, [32]byte, error)

func (*ExchangeAPI) SlippagePrice

func (api *ExchangeAPI) SlippagePrice(coin string, isBuy bool, slippage float64) float64

Helper function to calculate the slippage price based on the market price.

func (*ExchangeAPI) SlippagePriceSpot

func (api *ExchangeAPI) SlippagePriceSpot(coin string, isBuy bool, slippage float64) float64

SlippagePriceSpot is a helper function to calculate the slippage price for a spot coin.

func (*ExchangeAPI) UpdateLeverage

func (api *ExchangeAPI) UpdateLeverage(coin string, isCross bool, leverage int) (*DefaultExchangeResponse, error)

Update leverage for a coin https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-leverage

type ExchangeRequest

type ExchangeRequest struct {
	Action       any          `json:"action"`
	Nonce        uint64       `json:"nonce"`
	Signature    RsvSignature `json:"signature"`
	VaultAddress *string      `json:"vaultAddress,omitempty" msgpack:",omitempty"`
}

Base request for /exchange endpoint

type FilledStatus

type FilledStatus struct {
	OrderId int     `json:"oid"`
	AvgPx   float64 `json:"avgPx,string"`
	TotalSz float64 `json:"totalSz,string"`
	Cloid   string  `json:"cloid,omitempty"`
}

type FundingDelta

type FundingDelta struct {
	Asset       string `json:"coin"`
	FundingRate string `json:"fundingRate"`
	Size        string `json:"szi"`
	UsdcAmount  string `json:"usdc"`
}

type FundingUpdate

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

type Grouping

type Grouping string
const GroupingNa Grouping = "na"
const GroupingTpSl Grouping = "positionTpsl"

type HistoricalFundingRate

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

type Hyperliquid

type Hyperliquid struct {
	ExchangeAPI
	InfoAPI
}

func NewHyperliquid

func NewHyperliquid(config *HyperliquidClientConfig) *Hyperliquid

func (*Hyperliquid) AccountAddress

func (h *Hyperliquid) AccountAddress() string

func (*Hyperliquid) IsMainnet

func (h *Hyperliquid) IsMainnet() bool

func (*Hyperliquid) SetAccountAddress

func (h *Hyperliquid) SetAccountAddress(accountAddress string)

func (*Hyperliquid) SetDebugActive

func (h *Hyperliquid) SetDebugActive()

func (*Hyperliquid) SetPrivateKey

func (h *Hyperliquid) SetPrivateKey(privateKey string) error

type HyperliquidClientConfig

type HyperliquidClientConfig struct {
	IsMainnet      bool
	PrivateKey     string
	AccountAddress string
}

HyperliquidClientConfig is a configuration struct for Hyperliquid API. PrivateKey can be empty if you only need to use the public endpoints. AccountAddress is the default account address for the API that can be changed with SetAccountAddress(). AccountAddress may be different from the address build from the private key due to Hyperliquid's account system.

type IAPIService

type IAPIService interface {
	Request(path string, payload any) ([]byte, error)
	Endpoint() string
	KeyManager() *PKeyManager
	// contains filtered or unexported methods
}

IAPIService is an interface for making requests to the API Service.

It has a Request method that takes a path and a payload and returns a byte array and an error. It has a debug method that takes a format string and args and returns nothing. It has an Endpoint method that returns a string.

type IClient

type IClient interface {
	IAPIService
	SetPrivateKey(privateKey string) error
	SetAccountAddress(address string)
	AccountAddress() string
	SetDebugActive()
	IsMainnet() bool
}

IClient is the interface that wraps the basic Requst method.

Request method sends a POST request to the HyperLiquid API. IsMainnet method returns true if the client is connected to the mainnet. debug method enables debug mode. SetPrivateKey method sets the private key for the client.

type IExchangeAPI

type IExchangeAPI interface {
	IClient

	// Open orders
	BulkOrders(requests []OrderRequest, grouping Grouping) (*PlaceOrderResponse, error)
	Order(request OrderRequest, grouping Grouping) (*PlaceOrderResponse, error)
	MarketOrder(coin string, size float64, slippage *float64, clientOID ...string) (*PlaceOrderResponse, error)
	LimitOrder(orderType string, coin string, size float64, px float64, isBuy bool, reduceOnly bool, clientOID ...string) (*PlaceOrderResponse, error)

	// Order management
	CancelOrderByOID(coin string, orderID int) (any, error)
	CancelOrderByCloid(coin string, clientOID string) (any, error)
	BulkCancelOrders(cancels []CancelOidWire) (any, error)
	CancelAllOrdersByCoin(coin string) (any, error)
	CancelAllOrders() (any, error)
	ClosePosition(coin string) (*PlaceOrderResponse, error)

	// Account management
	Withdraw(destination string, amount float64) (*WithdrawResponse, error)
	UpdateLeverage(coin string, isCross bool, leverage int) (any, error)
}

IExchangeAPI is an interface for the /exchange service.

type IHyperliquid

type IHyperliquid interface {
	IExchangeAPI
	IInfoAPI
}

type IInfoAPI

type IInfoAPI interface {
	IClient // Base client interface

	// INFO API ENDPOINTS
	GetAllMids() (*map[string]string, error)
	GetOpenOrders(address string) (*[]Order, error)
	GetAccountOpenOrders() (*[]Order, error)
	GetUserFills(address string) (*[]OrderFill, error)
	GetAccountFills() (*[]OrderFill, error)
	GetUserRateLimits(address string) (*float64, error)
	GetL2BookSnapshot(coin string) (*L2BookSnapshot, error)
	GetCandleSnapshot(coin string, interval string, startTime int64, endTime int64) (*CandleSnapshot, error)

	// PERPETUALS INFO API ENDPOINTS
	GetMeta() (*Meta, error)
	GetUserState(address string) (*UserState, error)
	GetAccountState() (*UserState, error)
	GetFundingUpdates(address string, startTime int64, endTime int64) (*[]FundingUpdate, error)
	GetAccountFundingUpdates(startTime int64, endTime int64) (*[]FundingUpdate, error)
	GetNonFundingUpdates(address string, startTime int64, endTime int64) (*[]NonFundingUpdate, error)
	GetAccountNonFundingUpdates(startTime int64, endTime int64) (*[]NonFundingUpdate, error)
	GetHistoricalFundingRates() (*[]HistoricalFundingRate, error)

	// Additional helper functions
	GetMartketPx(coin string) (float64, error)
	BuildMetaMap() (map[string]AssetInfo, error)
	GetWithdrawals(address string) (*[]Withdrawal, error)
	GetAccountWithdrawals() (*[]Withdrawal, error)
}

IInfoAPI is an interface for the /info service.

type InfoAPI

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

func NewInfoAPI

func NewInfoAPI(isMainnet bool) *InfoAPI

NewInfoAPI returns a new instance of the InfoAPI struct. It sets the base endpoint to "/info" and the client to the NewClient function. The isMainnet parameter is used to set the network type.

func (*InfoAPI) BuildMetaMap

func (api *InfoAPI) BuildMetaMap() (map[string]AssetInfo, error)

Helper function to build a map of asset names to asset info It is used to get the assetId for a given asset name

func (*InfoAPI) BuildSpotMetaMap

func (api *InfoAPI) BuildSpotMetaMap() (map[string]AssetInfo, error)

Helper function to build a map of asset names to asset info It is used to get the assetId for a given asset name

func (*InfoAPI) Endpoint

func (api *InfoAPI) Endpoint() string

func (*InfoAPI) GetAccountDeposits

func (api *InfoAPI) GetAccountDeposits() (*[]Deposit, error)

Helper function to get the deposits of the account address The same as GetDeposits but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountFills

func (api *InfoAPI) GetAccountFills() (*[]OrderFill, error)

Retrieve a account's fill history The same as GetUserFills but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountFundingUpdates

func (api *InfoAPI) GetAccountFundingUpdates(startTime int64, endTime int64) (*[]FundingUpdate, error)

Retrieve account's funding history The same as GetFundingUpdates but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountNonFundingUpdates

func (api *InfoAPI) GetAccountNonFundingUpdates(startTime int64, endTime int64) (*[]NonFundingUpdate, error)

Retrieve account's funding history or non-funding ledger updates The same as GetNonFundingUpdates but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountOpenOrders

func (api *InfoAPI) GetAccountOpenOrders() (*[]Order, error)

Retrieve a account's order history The same as GetOpenOrders but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountRateLimits

func (api *InfoAPI) GetAccountRateLimits() (*RatesLimits, error)

Query account rate limits The same as GetUserRateLimits but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountState

func (api *InfoAPI) GetAccountState() (*UserState, error)

Retrieve account's perpetuals account summary The same as GetUserState but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountStateSpot

func (api *InfoAPI) GetAccountStateSpot() (*UserStateSpot, error)

Retrieve account's spot account summary The same as GetUserStateSpot but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetAccountWithdrawals

func (api *InfoAPI) GetAccountWithdrawals() (*[]Withdrawal, error)

Helper function to get the withdrawals of the account address The same as GetWithdrawals but user is set to the account address Check AccountAddress() or SetAccountAddress() if there is a need to set the account address

func (*InfoAPI) GetCandleSnapshot

func (api *InfoAPI) GetCandleSnapshot(coin string, interval string, startTime int64, endTime int64) (*[]CandleSnapshot, error)

Candle snapshot (Only the most recent 5000 candles are available) https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candle-snapshot

func (*InfoAPI) GetDeposits

func (api *InfoAPI) GetDeposits(address string) (*[]Deposit, error)

Helper function to get the deposits of the given address By default returns last 90 days

func (*InfoAPI) GetMartketPx

func (api *InfoAPI) GetMartketPx(coin string) (float64, error)

Helper function to get the market price of a given coin The coin parameter is the name of the coin

Example:

api.GetMartketPx("BTC")

func (*InfoAPI) GetNonFundingUpdates

func (api *InfoAPI) GetNonFundingUpdates(address string, startTime int64, endTime int64) (*[]NonFundingUpdate, error)

Retrieve a user's funding history or non-funding ledger updates https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-a-users-funding-history-or-non-funding-ledger-updates

func (*InfoAPI) GetSpotMarketPx

func (api *InfoAPI) GetSpotMarketPx(coin string) (float64, error)

GetSpotMarketPx returns the market price of a given spot coin The coin parameter is the name of the coin

Example:

api.GetSpotMarketPx("HYPE")

func (*InfoAPI) GetSpotMeta

func (api *InfoAPI) GetSpotMeta() (*SpotMeta, error)

Retrieve spot metadata

func (*InfoAPI) GetWithdrawals

func (api *InfoAPI) GetWithdrawals(address string) (*[]Withdrawal, error)

Helper function to get the withdrawals of a given address By default returns last 90 days

type InfoRequest

type InfoRequest struct {
	User      string `json:"user,omitempty"`
	Typez     string `json:"type"`
	Oid       string `json:"oid,omitempty"`
	Coin      string `json:"coin,omitempty"`
	StartTime int64  `json:"startTime,omitempty"`
	EndTime   int64  `json:"endTime,omitempty"`
}

Base request for /info

type InnerCancelResponse

type InnerCancelResponse struct {
	Type string                 `json:"type"`
	Data CancelResponseStatuses `json:"data"`
}

type L2BookSnapshot

type L2BookSnapshot struct {
	Coin   string `json:"coin"`
	Time   int64  `json:"time"`
	Levels [][]struct {
		Px float64 `json:"px,string"`
		Sz float64 `json:"sz,string"`
		N  int     `json:"n"`
	} `json:"levels"`
}

type Leverage

type Leverage struct {
	Type  string `json:"type"`
	Value int    `json:"value"`
}

type LimitOrderType

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

type Liquidation

type Liquidation struct {
	User      string `json:"liquidatedUser"`
	MarkPrice string `json:"markPx"`
	Method    string `json:"method"`
}

type MarginSummary

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

type Market

type Market struct {
	PrevDayPx         string `json:"prevDayPx,omitempty"`
	DayNtlVlm         string `json:"dayNtlVlm,omitempty"`
	MarkPx            string `json:"markPx,omitempty"`
	MidPx             string `json:"midPx,omitempty"`
	CirculatingSupply string `json:"circulatingSupply,omitempty"`
	Coin              string `json:"coin,omitempty"`
	TotalSupply       string `json:"totalSupply,omitempty"`
	DayBaseVlm        string `json:"dayBaseVlm,omitempty"`
}

type Message

type Message struct {
	Source       string `json:"source"`
	ConnectionId []byte `json:"connectionId"`
}

type Meta

type Meta struct {
	Universe []Asset `json:"universe"`
}

type ModifyOrderAction

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

type ModifyOrderRequest

type ModifyOrderRequest struct {
	OrderId    int       `json:"oid"`
	Coin       string    `json:"coin"`
	IsBuy      bool      `json:"is_buy"`
	Sz         float64   `json:"sz"`
	LimitPx    float64   `json:"limit_px"`
	OrderType  OrderType `json:"order_type"`
	ReduceOnly bool      `json:"reduce_only"`
	Cloid      string    `json:"cloid,omitempty"`
}

type ModifyOrderWire

type ModifyOrderWire struct {
	OrderId int       `msgpack:"oid" json:"oid"`
	Order   OrderWire `msgpack:"order" json:"order"`
}

func ModifyOrderRequestToWire

func ModifyOrderRequestToWire(req ModifyOrderRequest, meta map[string]AssetInfo, isSpot bool) ModifyOrderWire

type ModifyResponse

type ModifyResponse struct {
	Status   string                  `json:"status"`
	Response PlaceOrderInnerResponse `json:"response"`
}

type NonFundingDelta

type NonFundingDelta struct {
	Type   string  `json:"type"`
	Usdc   float64 `json:"usdc,string,omitempty"`
	Amount float64 `json:"amount,string,omitempty"`
	ToPerp bool    `json:"toPerp,omitempty"`
	Token  string  `json:"token,omitempty"`
	Fee    float64 `json:"fee,string,omitempty"`
	Nonce  int64   `json:"nonce"`
}

Depending on Type this struct can has different non-nil fields

type NonFundingUpdate

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

type Order

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

type OrderFill

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

type OrderRequest

type OrderRequest struct {
	Coin       string    `json:"coin"`
	IsBuy      bool      `json:"is_buy"`
	Sz         float64   `json:"sz"`
	LimitPx    float64   `json:"limit_px"`
	OrderType  OrderType `json:"order_type"`
	ReduceOnly bool      `json:"reduce_only"`
	Cloid      string    `json:"cloid,omitempty"`
}

type OrderType

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

type OrderTypeWire

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

func OrderTypeToWire

func OrderTypeToWire(orderType OrderType) OrderTypeWire

type OrderWire

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

func OrderRequestToWire

func OrderRequestToWire(req OrderRequest, meta map[string]AssetInfo, isSpot bool) OrderWire

type PKeyManager

type PKeyManager struct {
	PrivateKeyStr string
	// contains filtered or unexported fields
}

func NewPKeyManager

func NewPKeyManager(privateKey string) (*PKeyManager, error)

NewPKeyManager creates a new PKeyManager instance from a private key string

func (*PKeyManager) PrivateECDSA

func (km *PKeyManager) PrivateECDSA() *ecdsa.PrivateKey

func (*PKeyManager) PublicAddress

func (km *PKeyManager) PublicAddress() common.Address

func (*PKeyManager) PublicAddressHex

func (km *PKeyManager) PublicAddressHex() string

func (*PKeyManager) PublicECDSA

func (km *PKeyManager) PublicECDSA() *ecdsa.PublicKey

type PlaceOrderAction

type PlaceOrderAction struct {
	Type     string      `msgpack:"type" json:"type"`
	Orders   []OrderWire `msgpack:"orders" json:"orders"`
	Grouping Grouping    `msgpack:"grouping" json:"grouping"`
}

func OrderWiresToOrderAction

func OrderWiresToOrderAction(orders []OrderWire, grouping Grouping) PlaceOrderAction

type PlaceOrderInnerResponse

type PlaceOrderInnerResponse struct {
	Type string       `json:"type"`
	Data DataResponse `json:"data"`
}

type PlaceOrderResponse

type PlaceOrderResponse struct {
	Status   string                  `json:"status"`
	Response PlaceOrderInnerResponse `json:"response"`
}

type Position

type Position struct {
	Coin           string   `json:"coin"`
	EntryPx        float64  `json:"entryPx,string"`
	Leverage       Leverage `json:"leverage"`
	LiquidationPx  float64  `json:"liquidationPx,string"`
	MarginUsed     float64  `json:"marginUsed,string"`
	PositionValue  float64  `json:"positionValue,string"`
	ReturnOnEquity float64  `json:"returnOnEquity,string"`
	Szi            float64  `json:"szi,string"`
	UnrealizedPnl  float64  `json:"unrealizedPnl,string"`
	MaxLeverage    int      `json:"maxLeverage"`
	CumFunding     struct {
		AllTime   float64 `json:"allTime,string"`
		SinceOpne float64 `json:"sinceOpen,string"`
		SinceChan float64 `json:"sinceChange,string"`
	} `json:"cumFunding"`
}

type RatesLimits

type RatesLimits struct {
	CumVlm        float64 `json:"cumVlm,string"`
	NRequestsUsed int     `json:"nRequestsUsed"`
	NRequestsCap  int     `json:"nRequestsCap"`
}

type RestingStatus

type RestingStatus struct {
	OrderId int    `json:"oid"`
	Cloid   string `json:"cloid,omitempty"`
}

type RsvSignature

type RsvSignature struct {
	R string `json:"r"`
	S string `json:"s"`
	V byte   `json:"v"`
}

func ToTypedSig

func ToTypedSig(r [32]byte, s [32]byte, v byte) RsvSignature

type SignRequest

type SignRequest struct {
	PrimaryType string
	DType       []apitypes.Type
	DTypeMsg    map[string]interface{}
	IsMainNet   bool
	DomainName  string
}

SignRequest is the implementation of EIP-712 typed data

func (*SignRequest) GetDomain

func (request *SignRequest) GetDomain() apitypes.TypedDataDomain

func (*SignRequest) GetTypes

func (request *SignRequest) GetTypes() apitypes.Types

type Signer

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

func NewSigner

func NewSigner(manager *PKeyManager) Signer

func (*Signer) Sign

func (signer *Signer) Sign(request *SignRequest) (byte, [32]byte, [32]byte, error)

type SpotAssetPosition

type SpotAssetPosition struct {
	/*
			 "coin": "USDC",
		            "token": 0,
		            "hold": "0.0",
		            "total": "14.625485",
		            "entryNtl": "0.0"
	*/
	Coin     string  `json:"coin"`
	Token    int     `json:"token"`
	Hold     float64 `json:"hold,string"`
	Total    float64 `json:"total,string"`
	EntryNtl float64 `json:"entryNtl,string"`
}

type SpotMeta

type SpotMeta struct {
	Universe []struct {
		Tokens      []int  `json:"tokens"`
		Name        string `json:"name"`
		Index       int    `json:"index"`
		IsCanonical bool   `json:"isCanonical"`
	} `json:"universe"`
	Tokens []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 any    `json:"evmContract"`
		FullName    any    `json:"fullName"`
	} `json:"tokens"`
}

type SpotMetaAndAssetCtxsResponse

type SpotMetaAndAssetCtxsResponse [2]interface{} // Array of exactly 2 elements

type StatusResponse

type StatusResponse struct {
	Resting RestingStatus `json:"resting,omitempty"`
	Filled  FilledStatus  `json:"filled,omitempty"`
	Error   string        `json:"error,omitempty"`
}

type TpSl

type TpSl string
const TriggerSl TpSl = "sl"
const TriggerTp TpSl = "tp"

type TriggerOrderType

type TriggerOrderType struct {
	IsMarket  bool   `json:"isMarket" msgpack:"isMarket"`
	TriggerPx string `json:"triggerPx" msgpack:"triggerPx"`
	TpSl      TpSl   `json:"tpsl" msgpack:"tpsl"`
}

type UpdateLeverageAction

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

type UserState

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

type UserStateRequest

type UserStateRequest struct {
	User  string `json:"user"`
	Typez string `json:"type"`
}

type UserStateSpot

type UserStateSpot struct {
	Balances []SpotAssetPosition `json:"balances"`
}

type WithdrawAction

type WithdrawAction struct {
	Type             string `msgpack:"type" json:"type"`
	Destination      string `msgpack:"destination" json:"destination"`
	Amount           string `msgpack:"amount" json:"amount"`
	Time             uint64 `msgpack:"time" json:"time"`
	HyperliquidChain string `msgpack:"hyperliquidChain" json:"hyperliquidChain"`
	SignatureChainID string `msgpack:"signatureChainId" json:"signatureChainId"`
}

type WithdrawResponse

type WithdrawResponse struct {
	Status string `json:"status"`
	Nonce  int64
}

type Withdrawal

type Withdrawal struct {
	Time   int64   `json:"time"`
	Hash   string  `json:"hash"`
	Amount float64 `json:"usdc"`
	Fee    float64 `json:"fee"`
	Nonce  int64   `json:"nonce"`
}

Jump to

Keyboard shortcuts

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