nado

package
v0.1.4 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	GatewayV1URL = "https://gateway.prod.nado.xyz/v1"
	GatewayV2URL = "https://gateway.prod.nado.xyz/v2"
	ArchiveV1URL = "https://archive.prod.nado.xyz/v1"
	ArchiveV2URL = "https://archive.prod.nado.xyz/v2"
)
View Source
const (
	AppendixOffsetVersion     = 0
	AppendixOffsetIsolated    = 8
	AppendixOffsetOrderType   = 9
	AppendixOffsetReduceOnly  = 11
	AppendixOffsetTriggerType = 12
	AppendixOffsetReserved    = 14
	AppendixOffsetValue       = 64

	AppendixMaskVersion     = 0xFF
	AppendixMaskIsolated    = 0x1
	AppendixMaskOrderType   = 0x3
	AppendixMaskReduceOnly  = 0x1
	AppendixMaskTriggerType = 0x3
	AppendixMaskValue       = 0xFFFFFFFFFFFFFFFF // 64 bits

	AppendixVersion = 1

	// Trigger Types
	TriggerTypeNone              = 0
	TriggerTypePrice             = 1
	TriggerTypeTwap              = 2
	TriggerTypeTwapCustomAmounts = 3

	// TWAP Constants
	TwapOffsetTimes    = 32
	TwapOffsetSlippage = 0
	TwapMaskTimes      = 0xFFFFFFFF
	TwapMaskSlippage   = 0xFFFFFFFF
	TwapSlippageScale  = 1_000_000

	// Order Types for Appendix
	AppendixOrderTypeDefault  = 0
	AppendixOrderTypeIOC      = 1
	AppendixOrderTypeFOK      = 2
	AppendixOrderTypePostOnly = 3
)

Appendix Bit Field Constants

View Source
const (
	EIP712DomainName    = "Nado"
	EIP712DomainVersion = "0.0.1"
	ChainID             = 57073
	EndpointAddress     = "0x05ec92d78ed421f3d3ada77ffde167106565974e"
)

Domain separator constants

View Source
const (
	AppendixTriggerTypeNone              = 0
	AppendixTriggerTypePrice             = 1
	AppendixTriggerTypeTWAP              = 2
	AppendixTriggerTypeTWAPCustomAmounts = 3
)

Trigger Types for Appendix

View Source
const (
	WsURL              = "wss://gateway.prod.nado.xyz/v1/ws"        // Gateway WS for Executes/Queries
	WsSubscriptionsURL = "wss://gateway.prod.nado.xyz/v1/subscribe" // Subscriptions WS
	PingInterval       = 30 * time.Second
	ReadTimeout        = 60 * time.Second
)
View Source
const (
	AuthRequestID = 1111 // Fixed ID for authentication
)

Variables

View Source
var (
	ErrInvalidSymbol       = errors.New("nado: invalid symbol")
	ErrInvalidSide         = errors.New("nado: invalid side")
	ErrInvalidOrderType    = errors.New("nado: invalid order type")
	ErrNotAuthenticated    = errors.New("nado: not authenticated")
	ErrTimeout             = errors.New("nado: timeout")
	ErrCredentialsRequired = errors.New("nado: credentials required")
)
View Source
var CancelOrdersTypes = []apitypes.Type{
	{Name: "sender", Type: "bytes32"},
	{Name: "productIds", Type: "uint32[]"},
	{Name: "digests", Type: "bytes32[]"},
	{Name: "nonce", Type: "uint64"},
}
View Source
var CancelProductOrdersTypes = []apitypes.Type{
	{Name: "sender", Type: "bytes32"},
	{Name: "productIds", Type: "uint32[]"},
	{Name: "nonce", Type: "uint64"},
}
View Source
var OrderTypes = []apitypes.Type{
	{Name: "sender", Type: "bytes32"},
	{Name: "priceX18", Type: "int128"},
	{Name: "amount", Type: "int128"},
	{Name: "expiration", Type: "uint64"},
	{Name: "nonce", Type: "uint64"},
	{Name: "appendix", Type: "uint128"},
}
View Source
var StreamAuthenticationTypes = []apitypes.Type{
	{Name: "sender", Type: "bytes32"},
	{Name: "expiration", Type: "uint64"},
}

Functions

func BuildAppendix

func BuildAppendix(input ClientOrderInput) string

func BuildSender

func BuildSender(address common.Address, subAccountName string) string

BuildSender constructs the bytes32 sender field (Address + SubAccount)

func GenOrderVerifyingContract

func GenOrderVerifyingContract(productID int64) string

func GetNonce

func GetNonce() int64

func MulX18

func MulX18(x, y *big.Int) *big.Int

MulX18 multiplies two 18-decimal fixed-point numbers. result = (x * y) / 1e18

func RoundX18

func RoundX18(val, increment *big.Int) *big.Int

RoundX18 rounds a value to the nearest increment. result = (val / increment) * increment Note: This implements floor/truncation rounding similar to finding the nearest tick grid. If typical rounding is needed, (val + increment/2) / increment * increment. Given SDK context "round_x18", usually means "align to grid". Let's implement standard grid alignment (floor/truncation for safety on price increments usually safer for bids, but varies). Python "round_x18" usually rounds to nearest. Python: `round(value / interval) * interval`

func ToBigInt

func ToBigInt(val string) *big.Int

string to bigint

func ToX18

func ToX18(v interface{}) *big.Int

ToX18 converts a number to an 18-decimal fixed-point big.Int. It supports int, int64, float32, and float64.

Types

type AccountInfo

type AccountInfo struct {
	Subaccount          string               `json:"subaccount"`
	Exists              bool                 `json:"exists"`
	Healths             []Health             `json:"healths"`
	HealthContributions []HealthContribution `json:"health_contributions"`
	SpotCount           int                  `json:"spot_count"`
	PerpCount           int                  `json:"perp_count"`
	SpotBalances        []Balance            `json:"spot_balances"`
	PerpBalances        []Balance            `json:"perp_balances"`
}

type AccountProductOrders

type AccountProductOrders struct {
	Sender    string  `json:"sender,omitempty"`
	ProductID int64   `json:"product_id"`
	Orders    []Order `json:"orders"`
}

type AccountSnapshotsQuery

type AccountSnapshotsQuery struct {
	Subaccounts []string `json:"subaccounts"`
	Timestamps  []int64  `json:"timestamps"`
}

type ApiV1Response

type ApiV1Response struct {
	Status      string          `json:"status"`
	Data        json.RawMessage `json:"data,omitempty"`
	Error       string          `json:"error,omitempty"`
	ErrorCode   int             `json:"error_code,omitempty"`
	RequestType string          `json:"request_type,omitempty"`
}

type AprV2

type AprV2 struct {
	Name       string  `json:"name"`
	Symbol     string  `json:"symbol"`
	ProductID  string  `json:"product_id"`
	DepositApr float64 `json:"deposit_apr"`
	BorrowApr  float64 `json:"borrow_apr"`
	Tvl        float64 `json:"tvl"`
}

type ArchiveCandlestick

type ArchiveCandlestick struct {
	ProductID     int64  `json:"product_id"`
	Granularity   int64  `json:"granularity"`
	SubmissionIdx string `json:"submission_idx"`
	Timestamp     string `json:"timestamp"`
	OpenX18       string `json:"open_x18"`
	HighX18       string `json:"high_x18"`
	LowX18        string `json:"low_x18"`
	CloseX18      string `json:"close_x18"`
	Volume        string `json:"volume"` // x18
}

ArchiveCandlestick represents a single candle data point from Archive Indexer

type ArchiveMatchesRequest

type ArchiveMatchesRequest struct {
	Matches MatchesQuery `json:"matches"`
}

type ArchiveMatchesResponse

type ArchiveMatchesResponse struct {
	Matches []Match `json:"matches"`
	Txs     []Tx    `json:"txs"`
}

type ArchiveSnapshotRequest

type ArchiveSnapshotRequest struct {
	AccountSnapshots AccountSnapshotsQuery `json:"account_snapshots"`
}

type ArchiveSnapshotResponse

type ArchiveSnapshotResponse struct {
	Snapshots []Snapshot `json:"snapshots"`
}

type AssetV2

type AssetV2 struct {
	ProductId   int64    `json:"product_id"`
	TickerId    string   `json:"ticker_id"`
	MarketType  string   `json:"market_type"` // spot, perp
	Name        string   `json:"name"`
	Symbol      string   `json:"symbol"`
	TakerFee    *float64 `json:"taker_fee,omitempty"`
	MakerFee    *float64 `json:"maker_fee,omitempty"`
	CanWithdraw bool     `json:"can_withdraw"`
	CanDeposit  bool     `json:"can_deposit"`
}

type Balance

type Balance struct {
	ProductID int64 `json:"product_id"`
	Balance   struct {
		Amount                string  `json:"amount"`
		VQuoteBalance         *string `json:"v_quote_balance,omitempty"`
		LastCumulativeFunding *string `json:"last_cumulative_funding_x18,omitempty"`
	} `json:"balance"`
}

type BaseWsClient

type BaseWsClient struct {
	Logger *zap.SugaredLogger
	// contains filtered or unexported fields
}

BaseWsClient handles the underlying WebSocket connection.

func NewBaseWsClient

func NewBaseWsClient(ctx context.Context, url string, onMessage func([]byte)) *BaseWsClient

func (*BaseWsClient) Close

func (c *BaseWsClient) Close()

func (*BaseWsClient) Connect

func (c *BaseWsClient) Connect() error

func (*BaseWsClient) IsConnected

func (c *BaseWsClient) IsConnected() bool

func (*BaseWsClient) SendMessage

func (c *BaseWsClient) SendMessage(v interface{}) error

type CancelOrdersInput

type CancelOrdersInput struct {
	ProductIds []int64
	Digests    []string
}

CancelOrdersInput represents payload for cancelling specific orders

type CancelOrdersResponse

type CancelOrdersResponse struct {
	CancelledOrders []Order `json:"cancelled_orders"`
}

type CancelProductOrdersResponse

type CancelProductOrdersResponse struct {
	CancelledOrders []Order `json:"cancelled_orders"`
}

type Candlestick

type Candlestick struct {
	Type        string `json:"type"`
	Timestamp   string `json:"timestamp"`
	ProductId   int64  `json:"product_id"`
	Granularity int32  `json:"granularity"`
	OpenX18     string `json:"open_x18"`
	HighX18     string `json:"high_x18"`
	LowX18      string `json:"low_x18"`
	CloseX18    string `json:"close_x18"`
	Volume      string `json:"volume"`
}

type CandlestickRequest

type CandlestickRequest struct {
	Candlesticks Candlesticks `json:"candlesticks"`
}

type CandlestickResponse

type CandlestickResponse struct {
	Candlesticks []ArchiveCandlestick `json:"candlesticks"`
}

type Candlesticks

type Candlesticks struct {
	ProductID   int64 `json:"product_id"`
	Granularity int64 `json:"granularity"`
	MaxTime     int64 `json:"max_time,omitempty"`
	Limit       int   `json:"limit,omitempty"`
}

type Client

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

func NewClient

func NewClient() *Client

func (*Client) CancelAndPlace

func (c *Client) CancelAndPlace(ctx context.Context, cancelInput CancelOrdersInput, placeInput ClientOrderInput) (*PlaceOrderResponse, error)

CancelAndPlace executes a cancel and place order in a single transaction.

func (*Client) CancelOrders

func (c *Client) CancelOrders(ctx context.Context, input CancelOrdersInput) (*CancelOrdersResponse, error)

CancelOrders cancels specific orders by their digests (IDs).

func (*Client) CancelProductOrders

func (c *Client) CancelProductOrders(ctx context.Context, productIds []int64) (*CancelProductOrdersResponse, error)

CancelProductOrders cancels all orders for specific products or all if empty.

func (*Client) Execute

func (c *Client) Execute(ctx context.Context, reqBody interface{}) ([]byte, error)

Execute sends a POST request (V1) for execution/transaction endpoints.

func (*Client) GetAccount

func (c *Client) GetAccount(ctx context.Context) (*AccountInfo, error)

GetAccount returns the account summary (balances, positions).

func (*Client) GetAccountMultiProductsOrders

func (c *Client) GetAccountMultiProductsOrders(ctx context.Context, productIDs []int64, sender string) (*AccountProductOrders, error)

func (*Client) GetAccountProductOrders

func (c *Client) GetAccountProductOrders(ctx context.Context, productID int64, sender string) (*AccountProductOrders, error)

GetAccountProductOrders returns open orders for a specific product and sender.

func (*Client) GetAllFundingRates

func (c *Client) GetAllFundingRates(ctx context.Context) ([]FundingRateData, error)

GetAllFundingRates retrieves funding rates for all perp products Returns per-hour funding rates (Nado uses 1-hour intervals)

func (*Client) GetApr

func (c *Client) GetApr(ctx context.Context) ([]AprV2, error)

GetApr returns the APRs from V2 APR endpoint.

func (*Client) GetAssets

func (c *Client) GetAssets(ctx context.Context) ([]AssetV2, error)

GetAssets returns the list of assets from V2 Assets endpoint.

func (*Client) GetCandlesticks

func (c *Client) GetCandlesticks(ctx context.Context, req CandlestickRequest) ([]ArchiveCandlestick, error)

GetCandlesticks queries historical candlesticks from the archive indexer.

func (*Client) GetContracts

func (c *Client) GetContracts(ctx context.Context, edge *bool) (ContractV2Map, error)

GetContracts returns the list of contracts from V2 Contracts endpoint.

func (*Client) GetContractsV1

func (c *Client) GetContractsV1(ctx context.Context) (*ContractV1, error)

func (*Client) GetFeeRates

func (c *Client) GetFeeRates(ctx context.Context) (*FeeRates, error)

GetFeeRates returns the fee rates for the sender.

func (*Client) GetFundingRate

func (c *Client) GetFundingRate(ctx context.Context, productID int64) (*FundingRateData, error)

GetFundingRate retrieves the funding rate for a specific product Returns per-hour funding rate (Nado uses 1-hour intervals)

func (*Client) GetMarketLiquidity

func (c *Client) GetMarketLiquidity(ctx context.Context, productID int64, depth int) (*MarketLiquidity, error)

func (*Client) GetMarketPrice

func (c *Client) GetMarketPrice(ctx context.Context, productID int64) (*MarketPrice, error)

func (*Client) GetMarketPrices

func (c *Client) GetMarketPrices(ctx context.Context, productID []int) ([]MarketPrice, error)

func (*Client) GetMatches

func (c *Client) GetMatches(ctx context.Context, subaccount string, productIDs []int64, limit int) (*ArchiveMatchesResponse, error)

GetMatches queries historical matches for a subaccount.

func (*Client) GetNonces

func (c *Client) GetNonces(ctx context.Context) (*Nonce, error)

func (*Client) GetOrder

func (c *Client) GetOrder(ctx context.Context, productID int64, digest string) (*Order, error)

GetOrder returns a specific order.

func (*Client) GetOrderBook

func (c *Client) GetOrderBook(ctx context.Context, tickerID string, depth int) (*OrderBookV2, error)

GetOrderBook returns the orderbook for a ticker using V2.

func (*Client) GetPairs

func (c *Client) GetPairs(ctx context.Context, market *string) ([]PairV2, error)

GetPairs returns the list of products from V2 Pairs endpoint.

func (*Client) GetSubaccountSnapshots

func (c *Client) GetSubaccountSnapshots(ctx context.Context, subaccounts []string, timestamps []int64) (*ArchiveSnapshotResponse, error)

GetSubaccountSnapshots queries the archive for account state at specific timestamps.

func (*Client) GetSymbols

func (c *Client) GetSymbols(ctx context.Context, productType *string) (*SymbolsInfo, error)

func (*Client) GetTickers

func (c *Client) GetTickers(ctx context.Context, market MarketType, edge *bool) (TickerV2Map, error)

GetTickers

func (*Client) GetTrades

func (c *Client) GetTrades(ctx context.Context, tickerID string, limit *int, maxTradeID *int64) ([]TradeV2, error)

func (*Client) PlaceMarketOrder

func (c *Client) PlaceMarketOrder(ctx context.Context, params PlaceMarketOrderInput) (*PlaceOrderResponse, error)

PlaceMarketOrder executes a FOK order using top of the book price with provided slippage. @deprecated Use PlaceOrder with OrderTypeFOK instead.

func (*Client) PlaceOrder

func (c *Client) PlaceOrder(ctx context.Context, input ClientOrderInput) (*PlaceOrderResponse, error)

PlaceOrder executes a new order.

func (*Client) QueryArchiveV1

func (c *Client) QueryArchiveV1(ctx context.Context, params interface{}) (data []byte, err error)

QueryArchiveV1 v1 endpoints api: only support get method

func (*Client) QueryArchiveV2

func (c *Client) QueryArchiveV2(ctx context.Context, path string, params url.Values, dest interface{}) error

QueryArchiveV2 v2 endpoints api: only support get method

func (*Client) QueryGateWayV1

func (c *Client) QueryGateWayV1(ctx context.Context, method string, req map[string]interface{}) ([]byte, error)

QueryV1 v1 endpoints api: support get and post method

func (*Client) QueryGatewayV2

func (c *Client) QueryGatewayV2(ctx context.Context, path string, params url.Values, dest interface{}) error

QueryGatewayV2 v2 endpoints api: only support get method

func (*Client) WithCredentials

func (c *Client) WithCredentials(privateKey, subaccount string) (*Client, error)

type ClientOrderInput

type ClientOrderInput struct {
	ProductId  int64
	Price      string
	Amount     string
	Side       OrderSide
	OrderType  OrderType
	ReduceOnly bool
	PostOnly   bool
	Isolated   bool
	// IsolatedMargin is the initial margin amount for the isolated position in standard units (e.g. USDC).
	// It will be scaled to x6 precision (micros) internally.
	IsolatedMargin float64

	// Trigger related
	TriggerType  int // 0=None, 1=Price, 2=Twap, 3=TwapCustom
	TwapTimes    int
	TwapSlippage float64
}

ClientOrderInput represents the user input for placing an order

type ContractV1

type ContractV1 struct {
	ChainID         string `json:"chain_id"`
	EndpointAddress string `json:"endpoint_address"`
}

type ContractV2

type ContractV2 struct {
	ProductID                int     `json:"product_id"`
	TickerID                 string  `json:"ticker_id"`
	BaseCurrency             string  `json:"base_currency"`
	QuoteCurrency            string  `json:"quote_currency"`
	LastPrice                float64 `json:"last_price"`
	BaseVolume               float64 `json:"base_volume"`
	QuoteVolume              float64 `json:"quote_volume"`
	ProductType              string  `json:"product_type"`
	ContractPrice            float64 `json:"contract_price"`
	ContractPriceCurrency    string  `json:"contract_price_currency"`
	OpenInterest             float64 `json:"open_interest"`
	OpenInterestUsd          float64 `json:"open_interest_usd"`
	IndexPrice               float64 `json:"index_price"`
	FundingRate              float64 `json:"funding_rate"`
	NextFundingRateTimestamp int64   `json:"next_funding_rate_timestamp"`
	PriceChangePercent24H    float64 `json:"price_change_percent_24h"`
}

type ContractV2Map

type ContractV2Map map[string]ContractV2 // ticker_id -> Contract info object

type ExecTransaction

type ExecTransaction[T any] struct {
	Tx        T       `json:"tx"`
	Signature string  `json:"signature"`
	Digest    *string `json:"digest"` // Nullable
}

Internal wrapper for JSON marshaling of execute payloads

type FeeRate

type FeeRate struct {
	MakerFeeRate string `json:"maker_fee_rate"`
	TakerFeeRate string `json:"taker_fee_rate"`
}

type FeeRates

type FeeRates struct {
	MakerFeeRateX18         []string `json:"maker_fee_rates_x18"`
	TakerFeeRateX18         []string `json:"taker_fee_rates_x18"`
	LiquidationSequencerFee string   `json:"liquidation_sequencer_fee"`
	HealthCheckSequencerFee string   `json:"health_check_sequencer_fee"`
	TakerSequencerFee       string   `json:"taker_sequencer_fee"`
	WithdrawSequencerFees   []string `json:"withdraw_sequencer_fees"`
}

type Fill

type Fill struct {
	TradeId   string `json:"trade_id"`
	ProductId int64  `json:"product_id"`
	Price     string `json:"price"`
	Size      string `json:"size"`
	Side      string `json:"side"`
	Fee       string `json:"fee"`
	Time      int64  `json:"time"`
}

type FundingPayment

type FundingPayment struct {
	Type                      string `json:"type"`
	Timestamp                 string `json:"timestamp"`
	ProductId                 int64  `json:"product_id"`
	PaymentAmount             string `json:"payment_amount"`
	OpenInterest              string `json:"open_interest"`
	CumulativeFundingLongX18  string `json:"cumulative_funding_long_x18"`
	CumulativeFundingShortX18 string `json:"cumulative_funding_short_x18"`
	Dt                        int64  `json:"dt"`
}

type FundingRate

type FundingRate struct {
	Type           string `json:"type"`
	Timestamp      string `json:"timestamp"`
	ProductId      int64  `json:"product_id"`
	FundingRateX18 string `json:"funding_rate_x18"`
	UpdateTime     int64  `json:"update_time"`
}

type FundingRateData

type FundingRateData struct {
	ProductID            int64  `json:"product_id"`
	Symbol               string `json:"symbol"`               // Retrieved from symbols
	FundingRate          string `json:"fundingRate"`          // Per-hour funding rate (standardized)
	FundingIntervalHours int64  `json:"fundingIntervalHours"` // Always 1 for Nado
	FundingTime          int64  `json:"fundingTime"`          // Current hour start (calculated)
	NextFundingTime      int64  `json:"nextFundingTime"`      // Next hour start (calculated)
	UpdateTime           int64  `json:"updateTime"`           // Last update time from API
}

FundingRateData contains standardized funding rate information

type FundingRateResponse

type FundingRateResponse struct {
	ProductID      int64  `json:"product_id"`
	FundingRateX18 string `json:"funding_rate_x18"` // 24hr funding rate * 10^18
	UpdateTime     string `json:"update_time"`      // Epoch seconds
}

FundingRateResponse represents the response from Archive funding rate query

type GetAccountMultiProductsOrders

type GetAccountMultiProductsOrders struct {
	Sender        string                 `json:"sender"`
	ProductOrders []AccountProductOrders `json:"product_orders"`
}

type Health

type Health struct {
	Assets      string `json:"assets"`
	Liabilities string `json:"liabilities"`
	Health      string `json:"health"`
}

type HealthContribution

type HealthContribution [3]string

type Liquidation

type Liquidation struct {
	Type       string  `json:"type"`
	Timestamp  string  `json:"timestamp"`
	ProductIds []int64 `json:"product_ids"`
	Liquidator string  `json:"liquidator"`
	Liquidatee string  `json:"liquidatee"`
	Amount     string  `json:"amount"`
	Price      string  `json:"price"`
}

type MarketLiquidity

type MarketLiquidity struct {
	ProductID int64       `json:"product_id"`
	Timestamp string      `json:"timestamp"`
	Bids      [][2]string `json:"bids"`
	Asks      [][2]string `json:"asks"`
}

type MarketPrice

type MarketPrice struct {
	ProductID int    `json:"product_id"`
	BidX18    string `json:"bid_x18"`
	AskX18    string `json:"ask_x18"`
}

type MarketPricesReq

type MarketPricesReq struct {
	Type       string `json:"type"`
	ProductIds []int  `json:"product_ids"`
}

type MarketType

type MarketType string
const (
	MarketTypeSpot MarketType = "spot"
	MarketTypePerp MarketType = "perp"
)

type Match

type Match struct {
	Digest             string            `json:"digest"`
	Order              MatchOrder        `json:"order"`
	BaseFilled         string            `json:"base_filled"` // User sample: "base_filled" (no x18 suffix in key, but value is x18)
	QuoteFilled        string            `json:"quote_filled"`
	Fee                string            `json:"fee"`
	SequencerFee       string            `json:"sequencer_fee"`
	SubmissionIdx      string            `json:"submission_idx"`
	Timestamp          string            `json:"timestamp"`
	PreBalance         MatchBalanceOuter `json:"pre_balance"`
	PostBalance        MatchBalanceOuter `json:"post_balance"`
	NetEntryUnrealized string            `json:"net_entry_unrealized"` // Cost basis for current position
	NetEntryCumulative string            `json:"net_entry_cumulative"` // Cumulative cost basis
	ClosedAmount       string            `json:"closed_amount"`        // Amount closed in this match
	RealizedPnL        string            `json:"realized_pnl"`         // Realized PnL from closing
}

type MatchBalanceBase

type MatchBalanceBase struct {
	Perp *MatchBalancePerp `json:"perp,omitempty"`
	Spot *MatchBalanceSpot `json:"spot,omitempty"`
}

type MatchBalanceOuter

type MatchBalanceOuter struct {
	Base MatchBalanceBase `json:"base"`
}

type MatchBalancePerp

type MatchBalancePerp struct {
	ProductID int64 `json:"product_id"`
	Balance   struct {
		Amount                string `json:"amount"`
		VQuoteBalance         string `json:"v_quote_balance"`
		LastCumulativeFunding string `json:"last_cumulative_funding_x18"`
	} `json:"balance"`
}

type MatchBalanceSpot

type MatchBalanceSpot struct {
	ProductID int64 `json:"product_id"`
	Balance   struct {
		Amount string `json:"amount"`
	} `json:"balance"`
}

type MatchOrder

type MatchOrder struct {
	Sender     string `json:"sender"`
	PriceX18   string `json:"priceX18"`
	Amount     string `json:"amount"`
	Expiration string `json:"expiration"`
	Nonce      string `json:"nonce"`
	Appendix   string `json:"appendix"`
}

type MatchOrders

type MatchOrders struct {
	ProductId int     `json:"product_id"`
	Taker     TxTaker `json:"taker"`
	Maker     TxMaker `json:"maker"`
}

type MatchesQuery

type MatchesQuery struct {
	Subaccounts []string `json:"subaccounts"`
	ProductIds  []int64  `json:"product_ids,omitempty"`
	Limit       int      `json:"limit,omitempty"`
	MaxTime     int64    `json:"max_time,omitempty"`
}

type Nonce

type Nonce struct {
	TxNonce    string `json:"tx_nonce"`
	OrderNonce string `json:"order_nonce"`
}

type Order

type Order struct {
	ProductID      int64  `json:"product_id"`
	Sender         string `json:"sender"`
	PriceX18       string `json:"price_x18"`
	Amount         string `json:"amount"`
	Expiration     string `json:"expiration"`
	Nonce          string `json:"nonce"`
	UnfilledAmount string `json:"unfilled_amount"`
	Digest         string `json:"digest"`
	PlacedAt       int64  `json:"placed_at"`
	Appendix       string `json:"appendix"`
	OrderType      string `json:"order_type"`
}

type OrderBook

type OrderBook struct {
	Type             string      `json:"type"`
	MinTimestamp     string      `json:"min_timestamp"`
	MaxTimestamp     string      `json:"max_timestamp"`
	LastMaxTimestamp string      `json:"last_max_timestamp"`
	ProductId        int64       `json:"product_id"`
	Bids             [][2]string `json:"bids"` // [price, size]
	Asks             [][2]string `json:"asks"` // [price, size]
}

type OrderBookV2

type OrderBookV2 struct {
	ProductId int64        `json:"product_id"`
	TickerId  string       `json:"ticker_id"`
	Bids      [][2]float64 `json:"bids"`
	Asks      [][2]float64 `json:"asks"`
	Timestamp int64        `json:"timestamp"`
}

type OrderSide

type OrderSide string
const (
	OrderSideBuy  OrderSide = "buy"
	OrderSideSell OrderSide = "sell"
)

type OrderType

type OrderType string
const (
	OrderTypeLimit           OrderType = "limit"
	OrderTypeMarket          OrderType = "market"
	OrderTypeStopLoss        OrderType = "stop_loss"
	OrderTypeTakeProfit      OrderType = "take_profit"
	OrderTypeStopLossLimit   OrderType = "stop_loss_limit"
	OrderTypeTakeProfitLimit OrderType = "take_profit_limit"
	OrderTypeIOC             OrderType = "ioc"
	OrderTypeFOK             OrderType = "fok"
)

type OrderUpdate

type OrderUpdate struct {
	Type      string `json:"type"`
	Timestamp string `json:"timestamp"`
	ProductId int64  `json:"product_id"`
	Digest    string `json:"digest"`
	Amount    string `json:"amount"`
	Reason    string `json:"reason"`
	Id        int64  `json:"id"`
}

type OrderUpdateReason added in v0.1.3

type OrderUpdateReason string

OrderUpdateReason represents the WS order update reason string. Nado uses event-based status via the "reason" field in order update messages.

const (
	OrderReasonPlaced   OrderUpdateReason = "placed"
	OrderReasonFilled   OrderUpdateReason = "filled"
	OrderReasonCanceled OrderUpdateReason = "canceled"
)

type PairV2

type PairV2 struct {
	ProductId int64  `json:"product_id"`
	TickerId  string `json:"ticker_id"`
	Base      string `json:"base"`
	Quote     string `json:"quote"`
}

type PlaceMarketOrderInput

type PlaceMarketOrderInput struct {
	ProductId    int64
	Amount       float64
	Side         OrderSide
	Slippage     float64 // Defaults to 0.005 (0.5%)
	ReduceOnly   bool
	SpotLeverage *float64
}

type PlaceOrder

type PlaceOrder struct {
	ProductID int              `json:"product_id"`
	Order     PlaceOrderParams `json:"order"`
	Signature string           `json:"signature"`
	ID        int64            `json:"id"`
}

type PlaceOrderParams

type PlaceOrderParams struct {
	Sender     string  `json:"sender"`
	PriceX18   float64 `json:"price_x18"`
	Amount     float64 `json:"amount"`
	Expiration string  `json:"expiration"`
	Nonce      string  `json:"nonce"`
	Appendix   string  `json:"appendix"`
}

type PlaceOrderRequest

type PlaceOrderRequest struct {
	PlaceOrder PlaceOrder `json:"place_order"`
}

type PlaceOrderResponse

type PlaceOrderResponse struct {
	Digest string `json:"digest"`
}

type PositionChange

type PositionChange struct {
	ProductId  int64  `json:"product_id"`
	Amount     string `json:"amount"`
	EntryPrice string `json:"entry_price"`
	Side       string `json:"side"`
}

type PreparedOrder

type PreparedOrder struct {
	Tx        TxOrder
	Signature string
	Digest    string
	Request   map[string]interface{}
}

PreparedOrder contains the signed order and request ready for execution

type Product

type Product struct {
	ProductId  int64  `json:"product_id"`
	Symbol     string `json:"symbol"`
	BaseAsset  string `json:"base_asset"`
	QuoteAsset string `json:"quote_asset"`
	Decimals   int    `json:"decimals"`
	MinSize    string `json:"min_size"`
	TickSize   string `json:"tick_size"`
}

type QueryRequest

type QueryRequest struct {
	Type      string `json:"type"`
	ProductId *int64 `json:"product_id,omitempty"`
	Limit     int    `json:"limit,omitempty"`
	Depth     int    `json:"depth,omitempty"`
	OrderId   string `json:"order_id,omitempty"`
	Address   string `json:"address,omitempty"`
}

type Sender

type Sender struct {
	Address    string // hex string
	SubAccount string // hex string
}

type Signer

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

Signer handles EIP-712 signing

func NewSigner

func NewSigner(privateKeyHex string) (*Signer, error)

func (*Signer) GetAddress

func (s *Signer) GetAddress() common.Address

func (*Signer) SignCancelOrders

func (s *Signer) SignCancelOrders(tx TxCancelOrders, verifyingContract string) (string, error)

SignCancelOrders signs a batch cancel request by digests

func (*Signer) SignCancelProductOrders

func (s *Signer) SignCancelProductOrders(tx TxCancelProductOrders, verifyingContract string) (string, error)

SignCancelProductOrders signs a batch cancel request

func (*Signer) SignOrder

func (s *Signer) SignOrder(order TxOrder, verifyingContract string) (string, string, error)

SignOrder signs an order and returns signature and digest

func (*Signer) SignStreamAuthentication

func (s *Signer) SignStreamAuthentication(tx TxStreamAuth, verifyingContract string) (string, error)

SignStreamAuthentication signs a stream auth request

type Snapshot

type Snapshot struct {
	Subaccount string            `json:"subaccount"`
	Timestamp  int64             `json:"timestamp"`
	Balances   []SnapshotBalance `json:"products"` // Use SnapshotProduct
}

type SnapshotBalance

type SnapshotBalance struct {
	ProductID            int64   `json:"product_id"`
	Balance              Balance `json:"balance"`
	NetFundingCumulative string  `json:"net_funding_cumulative_x18"`
}

Reuse SnapshotProduct as Balances item

type StreamParams

type StreamParams struct {
	Type        string `json:"type"`
	ProductId   *int64 `json:"product_id"` // nullable
	Subaccount  string `json:"subaccount,omitempty"`
	Granularity int32  `json:"granularity,omitempty"`
}

type SubscriptionRequest

type SubscriptionRequest struct {
	Method string       `json:"method"` // "subscribe" or "unsubscribe"
	Stream StreamParams `json:"stream"`
	Id     int64        `json:"id"`
}

type Symbol

type Symbol struct {
	Type                     string  `json:"type"`
	ProductID                int     `json:"product_id"`
	Symbol                   string  `json:"symbol"`
	PriceIncrementX18        string  `json:"price_increment_x18"`
	SizeIncrement            string  `json:"size_increment"`
	MinSize                  string  `json:"min_size"`
	MakerFeeRateX18          string  `json:"maker_fee_rate_x18"`
	TakerFeeRateX18          string  `json:"taker_fee_rate_x18"`
	LongWeightInitialX18     string  `json:"long_weight_initial_x18"`
	LongWeightMaintenanceX18 string  `json:"long_weight_maintenance_x18"`
	MaxOpenInterestX18       *string `json:"max_open_interest_x18,omitempty"`
	TradingStatus            string  `json:"trading_status,omitempty"`
}

type SymbolsInfo

type SymbolsInfo struct {
	Symbols map[string]Symbol `json:"symbols"`
}

type Ticker

type Ticker struct {
	Type      string `json:"type"`
	Timestamp string `json:"timestamp"`
	ProductId int64  `json:"product_id"`
	BidPrice  string `json:"bid_price"`
	AskPrice  string `json:"ask_price"`
	BidQty    string `json:"bid_qty"`
	AskQty    string `json:"ask_qty"`
}

type TickerV2

type TickerV2 struct {
	ProductID             int     `json:"product_id"`
	TickerID              string  `json:"ticker_id"`
	BaseCurrency          string  `json:"base_currency"`
	QuoteCurrency         string  `json:"quote_currency"`
	LastPrice             float64 `json:"last_price"`
	BaseVolume            float64 `json:"base_volume"`
	QuoteVolume           float64 `json:"quote_volume"`
	PriceChangePercent24H float64 `json:"price_change_percent_24h"`
}

type TickerV2Map

type TickerV2Map map[string]TickerV2

type Trade

type Trade struct {
	Type         string `json:"type"`
	Timestamp    string `json:"timestamp"`
	ProductId    int64  `json:"product_id"`
	Price        string `json:"price"`
	TakerQty     string `json:"taker_qty"`
	MakerQty     string `json:"maker_qty"`
	IsTakerBuyer bool   `json:"is_taker_buyer"`
}

type TradeV2

type TradeV2 struct {
	ProductID   int     `json:"product_id"`
	TickerID    string  `json:"ticker_id"`
	TradeID     int64   `json:"trade_id"`
	Price       float64 `json:"price"`
	BaseFilled  float64 `json:"base_filled"`
	QuoteFilled float64 `json:"quote_filled"`
	Timestamp   int64   `json:"timestamp"`
	TradeType   string  `json:"trade_type"`
}

type Tx

type Tx struct {
	SubmissionIdx string `json:"submission_idx"`
	Timestamp     string `json:"timestamp"`
	TxInfo        TxInfo `json:"tx"`
}

type TxCancelOrder

type TxCancelOrder struct {
	Sender    string `json:"sender"` // bytes32
	ProductId uint32 `json:"productId"`
	Nonce     string `json:"nonce"` // uint64 -> string
}

type TxCancelOrders

type TxCancelOrders struct {
	Sender     string   `json:"sender"`     // bytes32
	ProductIds []int64  `json:"productIds"` // int64
	Digests    []string `json:"digests"`    // bytes32[]
	Nonce      string   `json:"nonce"`      // uint64 -> string
}

type TxCancelProductOrders

type TxCancelProductOrders struct {
	Sender     string  `json:"sender"`     // bytes32
	ProductIds []int64 `json:"productIds"` // uint32[]
	Nonce      string  `json:"nonce"`      // uint64 -> string
}

type TxInfo

type TxInfo struct {
	MatchOrders MatchOrders `json:"match_orders"`
}

type TxMaker

type TxMaker struct {
	Order     TxMatchOrder `json:"order"`
	Signature string       `json:"signature"`
}

type TxMatchOrder

type TxMatchOrder struct {
	Sender     string `json:"sender"`
	PriceX18   string `json:"price_x18"`
	Amount     string `json:"amount"`
	Expiration uint64 `json:"expiration"` // uint64: can be max uint64 (18446744073709551615)
	Nonce      uint64 `json:"nonce"`      // uint64: same range as expiration
	Appendix   string `json:"appendix"`
}

type TxOrder

type TxOrder struct {
	Sender     string `json:"sender"`     // bytes32
	ProductId  uint32 `json:"productId"`  // Not signed directly in EIP-712 Order struct but used for contract address derivation
	Amount     string `json:"amount"`     // int128 -> string
	PriceX18   string `json:"priceX18"`   // int128 -> string
	Nonce      string `json:"nonce"`      // uint64 -> string
	Expiration string `json:"expiration"` // uint64 -> string
	Appendix   string `json:"appendix"`   // uint128 -> string
}

type TxStreamAuth

type TxStreamAuth struct {
	Sender     string `json:"sender"`     // bytes32
	Expiration string `json:"expiration"` // uint64 -> string
}

type TxTaker

type TxTaker struct {
	Order     TxMatchOrder `json:"order"`
	Signature string       `json:"signature"`
}

type WsAccountClient

type WsAccountClient struct {
	Logger *zap.SugaredLogger
	// contains filtered or unexported fields
}

WsAccountClient handles private account data subscriptions with authentication Read loop has NO timeout since account updates may be infrequent (no trading activity)

func NewWsAccountClient

func NewWsAccountClient(ctx context.Context) *WsAccountClient

func (*WsAccountClient) Close

func (c *WsAccountClient) Close()

func (*WsAccountClient) Connect

func (c *WsAccountClient) Connect() error

func (*WsAccountClient) IsConnected

func (c *WsAccountClient) IsConnected() bool

func (*WsAccountClient) Subscribe

func (c *WsAccountClient) Subscribe(stream StreamParams, callback func([]byte)) error

func (*WsAccountClient) SubscribeFills

func (c *WsAccountClient) SubscribeFills(productId *int64, callback func(*Fill)) error

func (*WsAccountClient) SubscribeOrders

func (c *WsAccountClient) SubscribeOrders(productId *int64, callback func(*OrderUpdate)) error

func (*WsAccountClient) SubscribePositions

func (c *WsAccountClient) SubscribePositions(productId *int64, callback func(*PositionChange)) error

func (*WsAccountClient) Unsubscribe

func (c *WsAccountClient) Unsubscribe(stream StreamParams) error

func (*WsAccountClient) UnsubscribeOrders

func (c *WsAccountClient) UnsubscribeOrders(productId *int64) error

func (*WsAccountClient) UnsubscribePositions

func (c *WsAccountClient) UnsubscribePositions(productId *int64) error

func (*WsAccountClient) WithCredentials

func (c *WsAccountClient) WithCredentials(privateKey string) *WsAccountClient

type WsApiClient

type WsApiClient struct {
	*BaseWsClient

	Signer *Signer

	Logger *zap.SugaredLogger
	// contains filtered or unexported fields
}

WsApiClient handles executes and queries via WebSocket. It maps responses to requests via ID.

func NewWsApiClient

func NewWsApiClient(ctx context.Context, privateKey string) (*WsApiClient, error)

func (*WsApiClient) CancelAndPlace

func (c *WsApiClient) CancelAndPlace(ctx context.Context, cancelInput CancelOrdersInput, placeInput ClientOrderInput) (*PlaceOrderResponse, error)

CancelAndPlace executes a cancel and place order in a single transaction via WebSocket.

func (*WsApiClient) CancelOrders

func (c *WsApiClient) CancelOrders(ctx context.Context, input CancelOrdersInput) (*CancelOrdersResponse, error)

CancelOrders cancels specific orders by their digests (IDs).

func (*WsApiClient) Execute

func (c *WsApiClient) Execute(ctx context.Context, req map[string]interface{}, sig *string) (*WsResponse, error)

Execute sends a request and waits for a response with matching ID.

func (*WsApiClient) ExecutePreparedOrder

func (c *WsApiClient) ExecutePreparedOrder(ctx context.Context, order *PreparedOrder) (*PlaceOrderResponse, error)

ExecutePreparedOrder executes a previously prepared order.

func (*WsApiClient) PlaceOrder

func (c *WsApiClient) PlaceOrder(ctx context.Context, input ClientOrderInput) (*PlaceOrderResponse, error)

PlaceOrder executes a new order via Gateway WebSocket.

func (*WsApiClient) PrepareOrder

func (c *WsApiClient) PrepareOrder(ctx context.Context, input ClientOrderInput) (*PreparedOrder, error)

PrepareOrder builds and signs an order without sending it.

func (*WsApiClient) SetSubaccount

func (c *WsApiClient) SetSubaccount(sub string)

func (*WsApiClient) WsCancelProductOrders

func (c *WsApiClient) WsCancelProductOrders(txCancel TxCancelProductOrders) (*WsResponse, error)

WsCancelProductOrders cancels orders via WS Deprecated: Use CancelOrders instead.

type WsAuthRequest

type WsAuthRequest struct {
	Method    string       `json:"method"` // "authenticate"
	Id        int64        `json:"id"`
	Tx        TxStreamAuth `json:"tx"`
	Signature string       `json:"signature"`
}

type WsMarketClient

type WsMarketClient struct {
	Logger *zap.SugaredLogger
	// contains filtered or unexported fields
}

WsMarketClient handles public market data subscriptions without authentication Read loop has 60s timeout since market data streams continuously

func NewWsMarketClient

func NewWsMarketClient(ctx context.Context) *WsMarketClient

func (*WsMarketClient) Close

func (c *WsMarketClient) Close()

func (*WsMarketClient) Connect

func (c *WsMarketClient) Connect() error

func (*WsMarketClient) IsConnected

func (c *WsMarketClient) IsConnected() bool

func (*WsMarketClient) Subscribe

func (c *WsMarketClient) Subscribe(stream StreamParams, callback func([]byte)) error

func (*WsMarketClient) SubscribeFundingPayment

func (c *WsMarketClient) SubscribeFundingPayment(productId int64, callback func(*FundingPayment)) error

func (*WsMarketClient) SubscribeFundingRate

func (c *WsMarketClient) SubscribeFundingRate(productId *int64, callback func(*FundingRate)) error

func (*WsMarketClient) SubscribeLatestCandlestick

func (c *WsMarketClient) SubscribeLatestCandlestick(productId int64, granularity int32, callback func(*Candlestick)) error

func (*WsMarketClient) SubscribeLiquidation

func (c *WsMarketClient) SubscribeLiquidation(productId *int64, callback func(*Liquidation)) error

func (*WsMarketClient) SubscribeOrderBook

func (c *WsMarketClient) SubscribeOrderBook(productId int64, callback func(*OrderBook)) error

SubscribeOrderBook subscribes to orderbook

func (*WsMarketClient) SubscribeTicker

func (c *WsMarketClient) SubscribeTicker(productId int64, callback func(*Ticker)) error

func (*WsMarketClient) SubscribeTrades

func (c *WsMarketClient) SubscribeTrades(productId int64, callback func(*Trade)) error

func (*WsMarketClient) Unsubscribe

func (c *WsMarketClient) Unsubscribe(stream StreamParams) error

func (*WsMarketClient) UnsubscribeLatestCandlestick

func (c *WsMarketClient) UnsubscribeLatestCandlestick(productId int64, granularity int32) error

func (*WsMarketClient) UnsubscribeOrderBook

func (c *WsMarketClient) UnsubscribeOrderBook(productId int64) error

func (*WsMarketClient) UnsubscribeTicker

func (c *WsMarketClient) UnsubscribeTicker(productId int64) error

func (*WsMarketClient) UnsubscribeTrades

func (c *WsMarketClient) UnsubscribeTrades(productId int64) error

type WsMessage

type WsMessage struct {
	Type      string          `json:"type"` // Used for inference if available
	Channel   string          `json:"channel,omitempty"`
	Data      json.RawMessage `json:"data,omitempty"`
	Status    string          `json:"status,omitempty"`
	Error     string          `json:"error,omitempty"`
	ErrorCode int             `json:"error_code,omitempty"`
	// Auth specific
	Method string `json:"method,omitempty"`
	Id     int64  `json:"id,omitempty"`
}

type WsResponse

type WsResponse struct {
	Id          *int64          `json:"id,omitempty"`
	Signature   *string         `json:"signature,omitempty"`
	Status      string          `json:"status"`
	Error       string          `json:"error,omitempty"`
	ErrorCode   int             `json:"error_code,omitempty"`
	Data        json.RawMessage `json:"data,omitempty"`
	RequestType string          `json:"request_type,omitempty"`
}

Jump to

Keyboard shortcuts

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