spot

package
v0.1.3 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	BaseURL = "https://sapi.asterdex.com"
)
View Source
const (
	WSBaseURL = "wss://sstream.asterdex.com/ws"
)

Use Binance URL as default if Aster Spot URL is not confirmed different

Variables

View Source
var SingleEventMap = map[string]string{
	"depthUpdate":     "depth@100ms",
	"markPriceUpdate": "markPrice@1s",
	"24hrTicker":      "ticker",
	"24hrMiniTicker":  "miniTicker",
	"bookTicker":      "bookTicker",
	"aggTrade":        "aggTrade",
	"trade":           "trade",
}

Functions

func BuildQueryString

func BuildQueryString(params map[string]interface{}) string

BuildQueryString builds a query string from a map

func FormatSymbol

func FormatSymbol(symbol string) string

FormatSymbol formats the symbol to uppercase (e.g., btcusdt -> BTCUSDT)

func GenerateSignature

func GenerateSignature(secretKey, data string) string

GenerateSignature generates an HMAC SHA256 signature

func Timestamp

func Timestamp() int64

Timestamp returns the current timestamp in milliseconds

Types

type APIError

type APIError struct {
	Code    int    `json:"code"`
	Message string `json:"msg"`
}

APIError represents a Binance API error

func (*APIError) Error

func (e *APIError) Error() string

type AccountPositionEvent

type AccountPositionEvent struct {
	EventType         string `json:"e"`
	EventTime         int64  `json:"E"`
	LastAccountUpdate int64  `json:"u"`
	Balances          []struct {
		Asset  string `json:"a"`
		Free   string `json:"f"`
		Locked string `json:"l"`
	} `json:"B"`
}

AccountPositionEvent (OutboundAccountPosition)

type AccountResponse

type AccountResponse struct {
	MakerCommission  int64  `json:"makerCommission"`
	TakerCommission  int64  `json:"takerCommission"`
	BuyerCommission  int64  `json:"buyerCommission"`
	SellerCommission int64  `json:"sellerCommission"`
	CanTrade         bool   `json:"canTrade"`
	CanWithdraw      bool   `json:"canWithdraw"`
	CanDeposit       bool   `json:"canDeposit"`
	UpdateTime       int64  `json:"updateTime"`
	AccountType      string `json:"accountType"`
	Balances         []struct {
		Asset  string `json:"asset"`
		Free   string `json:"free"`
		Locked string `json:"locked"`
	} `json:"balances"`
}

type AggTradeEvent

type AggTradeEvent struct {
	WsEventHeader
	AggTradeID   int64  `json:"a"`
	Price        string `json:"p"`
	Quantity     string `json:"q"`
	FirstTradeID int64  `json:"f"`
	LastTradeID  int64  `json:"l"`
	TradeTime    int64  `json:"T"`
	IsBuyerMaker bool   `json:"m"`
	Ignore       bool   `json:"M"`
}

AggTradeEvent

type BookTickerEvent

type BookTickerEvent struct {
	UpdateID     int64  `json:"u"`
	Symbol       string `json:"s"`
	BestBidPrice string `json:"b"`
	BestBidQty   string `json:"B"`
	BestAskPrice string `json:"a"`
	BestAskQty   string `json:"A"`
}

BookTickerEvent

type BookTickerResponse

type BookTickerResponse struct {
	Symbol   string `json:"symbol"`
	BidPrice string `json:"bidPrice"`
	BidQty   string `json:"bidQty"`
	AskPrice string `json:"askPrice"`
	AskQty   string `json:"askQty"`
}

type CancelOrderResponse

type CancelOrderResponse struct {
	Symbol              string `json:"symbol"`
	OrigClientOrderID   string `json:"origClientOrderId"`
	OrderID             int64  `json:"orderId"`
	OrderListID         int64  `json:"orderListId"`
	ClientOrderID       string `json:"clientOrderId"`
	Price               string `json:"price"`
	OrigQty             string `json:"origQty"`
	ExecutedQty         string `json:"executedQty"`
	CummulativeQuoteQty string `json:"cummulativeQuoteQty"`
	Status              string `json:"status"`
	TimeInForce         string `json:"timeInForce"`
	Type                string `json:"type"`
	Side                string `json:"side"`
}

type CancelReplaceOrderParams

type CancelReplaceOrderParams struct {
	Symbol                  string
	Side                    string
	Type                    string
	CancelReplaceMode       string // STOP_ON_FAILURE or ALLOW_FAILURE
	TimeInForce             string // Optional
	Quantity                string
	Price                   string // Optional
	CancelOrderID           int64  // Optional
	CancelOrigClientOrderID string // Optional
	NewClientOrderID        string // Optional
	StopPrice               string // Optional
	IcebergQty              string // Optional
	NewOrderRespType        string // Optional
}

type CancelReplaceOrderResponse

type CancelReplaceOrderResponse struct {
	CancelResult     string               `json:"cancelResult"`
	NewOrderResult   string               `json:"newOrderResult"`
	CancelResponse   *CancelOrderResponse `json:"cancelResponse"`
	NewOrderResponse *OrderResponse       `json:"newOrderResponse"`
}

type Client

type Client struct {
	BaseURL    string
	APIKey     string
	SecretKey  string
	HTTPClient *http.Client
	Logger     *zap.SugaredLogger
	Debug      bool
}

func NewClient

func NewClient(apiKey, secretKey string) *Client

func (*Client) BookTicker

func (c *Client) BookTicker(ctx context.Context, symbol string) (*BookTickerResponse, error)

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, symbol string, orderID int64, origClientOrderID string) (*CancelOrderResponse, error)

func (*Client) CloseListenKey

func (c *Client) CloseListenKey(ctx context.Context, listenKey string) error

func (*Client) CreateListenKey

func (c *Client) CreateListenKey(ctx context.Context) (string, error)

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, endpoint string, params map[string]interface{}, signed bool, result interface{}) error

func (*Client) Depth

func (c *Client) Depth(ctx context.Context, symbol string, limit int) (*DepthResponse, error)

func (*Client) ExchangeInfo

func (c *Client) ExchangeInfo(ctx context.Context) (*ExchangeInfoResponse, error)

func (*Client) Get

func (c *Client) Get(ctx context.Context, endpoint string, params map[string]interface{}, signed bool, result interface{}) error

func (*Client) GetAccount

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

func (*Client) GetOpenOrders

func (c *Client) GetOpenOrders(ctx context.Context, symbol string) ([]OrderResponse, error)

func (*Client) GetOrder

func (c *Client) GetOrder(ctx context.Context, symbol string, orderID int64, origClientOrderID string) (*OrderResponse, error)

func (*Client) KeepAliveListenKey

func (c *Client) KeepAliveListenKey(ctx context.Context, listenKey string) error

func (*Client) Klines

func (c *Client) Klines(ctx context.Context, symbol, interval string, limit int, startTime, endTime int64) ([]KlineResponse, error)

func (*Client) MyTrades

func (c *Client) MyTrades(ctx context.Context, symbol string, limit int, startTime, endTime int64, fromID int64) ([]Trade, error)

func (*Client) PlaceOrder

func (c *Client) PlaceOrder(ctx context.Context, p PlaceOrderParams) (*OrderResponse, error)

func (*Client) Post

func (c *Client) Post(ctx context.Context, endpoint string, params map[string]interface{}, signed bool, result interface{}) error

func (*Client) Ticker

func (c *Client) Ticker(ctx context.Context, symbol string) (*TickerResponse, error)

func (*Client) WithBaseURL

func (c *Client) WithBaseURL(url string) *Client

func (*Client) WithDebug

func (c *Client) WithDebug(debug bool) *Client

type DepthEvent

type DepthEvent struct {
	WsEventHeader
	FirstUpdateID int64      `json:"U"`
	FinalUpdateID int64      `json:"u"`
	Bids          [][]string `json:"b"`
	Asks          [][]string `json:"a"`
}

DepthEvent

type DepthResponse

type DepthResponse struct {
	LastUpdateID int64      `json:"lastUpdateId"`
	Bids         [][]string `json:"bids"`
	Asks         [][]string `json:"asks"`
}

type ExchangeInfoResponse

type ExchangeInfoResponse struct {
	Timezone   string `json:"timezone"`
	ServerTime int64  `json:"serverTime"`
	Symbols    []struct {
		Symbol             string                   `json:"symbol"`
		Status             string                   `json:"status"`
		BaseAsset          string                   `json:"baseAsset"`
		QuoteAsset         string                   `json:"quoteAsset"`
		PricePrecision     int                      `json:"pricePrecision"`
		QuantityPrecision  int                      `json:"quantityPrecision"`
		BaseAssetPrecision int                      `json:"baseAssetPrecision"`
		QuotePrecision     int                      `json:"quotePrecision"`
		Filters            []map[string]interface{} `json:"filters"`
	} `json:"symbols"`
}

type ExecutionReportEvent

type ExecutionReportEvent struct {
	EventType                              string `json:"e"`
	EventTime                              int64  `json:"E"`
	Symbol                                 string `json:"s"`
	ClientOrderID                          string `json:"c"`
	Side                                   string `json:"S"`
	OrderType                              string `json:"o"`
	TimeInForce                            string `json:"f"`
	Quantity                               string `json:"q"`
	Price                                  string `json:"p"`
	StopPrice                              string `json:"P"`
	IcebergQuantity                        string `json:"F"`
	OrderListID                            int64  `json:"g"` // OCO
	OriginalClientOrderID                  string `json:"C"`
	ExecutionType                          string `json:"x"`
	OrderStatus                            string `json:"X"`
	RejectReason                           string `json:"r"`
	OrderID                                int64  `json:"i"`
	LastExecutedQuantity                   string `json:"l"`
	CumulativeFilledQuantity               string `json:"z"`
	LastExecutedPrice                      string `json:"L"`
	CommissionAmount                       string `json:"n"`
	CommissionAsset                        string `json:"N"`
	TransactionTime                        int64  `json:"T"`
	TradeID                                int64  `json:"t"`
	Ignore                                 int64  `json:"I"` // Ignore
	IsOrderWorking                         bool   `json:"w"` // Note: check case sensitive
	IsMaker                                bool   `json:"m"`
	Ignore2                                bool   `json:"M"`
	CreationTime                           int64  `json:"O"`
	CumulativeQuoteAssetTransactedQuantity string `json:"Z"`
	LastQuoteAssetTransactedQuantity       string `json:"Y"`
	QuoteOrderQuantity                     string `json:"Q"`

	// Working time might be missing or different key
	WorkingTime int64 `json:"W"`
	// SelfTradePreventionMode
	SelfTradePreventionMode string `json:"V"`
}

ExecutionReportEvent

type FlexibleFloat

type FlexibleFloat string

Helper to handle mixed number/string unmarshalling if needed

func (FlexibleFloat) Float64

func (f FlexibleFloat) Float64() float64

func (*FlexibleFloat) UnmarshalJSON

func (f *FlexibleFloat) UnmarshalJSON(data []byte) error

type KlineEvent

type KlineEvent struct {
	WsEventHeader
	Kline struct {
		StartTime           int64  `json:"t"`
		CloseTime           int64  `json:"T"`
		Symbol              string `json:"s"`
		Interval            string `json:"i"`
		FirstTradeID        int64  `json:"f"`
		LastTradeID         int64  `json:"L"`
		OpenPrice           string `json:"o"`
		ClosePrice          string `json:"c"`
		HighPrice           string `json:"h"`
		LowPrice            string `json:"l"`
		Volume              string `json:"v"`
		NumberOfTrades      int64  `json:"n"`
		IsClosed            bool   `json:"x"`
		QuoteVolume         string `json:"q"`
		TakerBuyBaseVolume  string `json:"V"`
		TakerBuyQuoteVolume string `json:"Q"`
		Ignore              string `json:"B"`
	} `json:"k"`
}

KlineEvent

type KlineResponse

type KlineResponse []interface{} // Klines are arrays of arrays

type ListenKeyResponse

type ListenKeyResponse struct {
	ListenKey string `json:"listenKey"`
}

type OrderResponse

type OrderResponse struct {
	Symbol              string `json:"symbol"`
	OrderID             int64  `json:"orderId"`
	OrderListID         int64  `json:"orderListId"`
	ClientOrderID       string `json:"clientOrderId"`
	TransactTime        int64  `json:"transactTime"`
	Price               string `json:"price"`
	OrigQty             string `json:"origQty"`
	ExecutedQty         string `json:"executedQty"`
	CummulativeQuoteQty string `json:"cummulativeQuoteQty"`
	Status              string `json:"status"`
	TimeInForce         string `json:"timeInForce"`
	Type                string `json:"type"`
	Side                string `json:"side"`
}

type PlaceOrderParams

type PlaceOrderParams struct {
	Symbol           string
	Side             string
	Type             string
	TimeInForce      string // Optional
	Quantity         string
	Price            string // Optional
	NewClientOrderID string // Optional
	StopPrice        string // Optional
	IcebergQty       string // Optional
	NewOrderRespType string // Optional
}

type ServerTimeResponse

type ServerTimeResponse struct {
	ServerTime int64 `json:"serverTime"`
}

type Subscription

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

type TickerResponse

type TickerResponse struct {
	Symbol             string `json:"symbol"`
	PriceChange        string `json:"priceChange"`
	PriceChangePercent string `json:"priceChangePercent"`
	WeightedAvgPrice   string `json:"weightedAvgPrice"`
	PrevClosePrice     string `json:"prevClosePrice"`
	LastPrice          string `json:"lastPrice"`
	LastQty            string `json:"lastQty"`
	BidPrice           string `json:"bidPrice"`
	BidQty             string `json:"bidQty"`
	AskPrice           string `json:"askPrice"`
	AskQty             string `json:"askQty"`
	OpenPrice          string `json:"openPrice"`
	HighPrice          string `json:"highPrice"`
	LowPrice           string `json:"lowPrice"`
	Volume             string `json:"volume"`
	QuoteVolume        string `json:"quoteVolume"`
	OpenTime           int64  `json:"openTime"`
	CloseTime          int64  `json:"closeTime"`
	FirstId            int64  `json:"firstId"`
	LastId             int64  `json:"lastId"`
	Count              int64  `json:"count"`
}

type Trade

type Trade struct {
	Symbol          string `json:"symbol"`
	ID              int64  `json:"id"`
	OrderID         int64  `json:"orderId"`
	OrderListID     int64  `json:"orderListId"`
	Price           string `json:"price"`
	Qty             string `json:"qty"`
	QuoteQty        string `json:"quoteQty"`
	Commission      string `json:"commission"`
	CommissionAsset string `json:"commissionAsset"`
	Time            int64  `json:"time"`
	IsBuyer         bool   `json:"isBuyer"`
	IsMaker         bool   `json:"isMaker"`
	IsBestMatch     bool   `json:"isBestMatch"`
}

type UserStreamManager

type UserStreamManager struct {
	Client       *Client
	ListenKey    string
	StopCh       chan struct{}
	KeepAliveInt time.Duration
}

func NewUserStreamManager

func NewUserStreamManager(client *Client) *UserStreamManager

func (*UserStreamManager) Start

func (m *UserStreamManager) Start(ctx context.Context) (string, error)

func (*UserStreamManager) Stop

func (m *UserStreamManager) Stop(ctx context.Context) error

type WsAccountClient

type WsAccountClient struct {
	*WsClient
	APIKey    string
	SecretKey string
	ListenKey string
	StreamMgr *UserStreamManager
	// contains filtered or unexported fields
}

func NewWsAccountClient

func NewWsAccountClient(ctx context.Context, apiKey, secretKey string) *WsAccountClient

func (*WsAccountClient) Close

func (c *WsAccountClient) Close()

func (*WsAccountClient) Connect

func (c *WsAccountClient) Connect() error

func (*WsAccountClient) SubscribeAccountPosition

func (c *WsAccountClient) SubscribeAccountPosition(handler func(*AccountPositionEvent))

func (*WsAccountClient) SubscribeExecutionReport

func (c *WsAccountClient) SubscribeExecutionReport(handler func(*ExecutionReportEvent))

type WsAccountUpdateEvent

type WsAccountUpdateEvent struct {
	EventType            string `json:"e"`
	EventTime            int64  `json:"E"`
	MakerCommissionRate  int64  `json:"m"`
	TakerCommissionRate  int64  `json:"t"`
	BuyerCommissionRate  int64  `json:"b"`
	SellerCommissionRate int64  `json:"s"`
	CanTrade             bool   `json:"T"`
	CanWithdraw          bool   `json:"W"`
	CanDeposit           bool   `json:"D"`
	LastUpdateTime       int64  `json:"u"`
	Balances             []struct {
		Asset  string `json:"a"`
		Free   string `json:"f"`
		Locked string `json:"l"`
	} `json:"B"`
}

type WsAggTradeEvent

type WsAggTradeEvent struct {
	EventType    string `json:"e"`
	EventTime    int64  `json:"E"`
	Symbol       string `json:"s"`
	AggTradeID   int64  `json:"a"`
	Price        string `json:"p"`
	Quantity     string `json:"q"`
	FirstTradeID int64  `json:"f"`
	LastTradeID  int64  `json:"l"`
	TradeTime    int64  `json:"T"`
	IsBuyerMaker bool   `json:"m"`
	Ignore       bool   `json:"M"`
}

type WsBookTickerEvent

type WsBookTickerEvent struct {
	EventType    string `json:"e"`
	EventTime    int64  `json:"E"`
	UpdateID     int64  `json:"u"`
	Symbol       string `json:"s"`
	BestBidPrice string `json:"b"`
	BestBidQty   string `json:"B"`
	BestAskPrice string `json:"a"`
	BestAskQty   string `json:"A"`
}

type WsClient

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

	Logger *zap.SugaredLogger
	Debug  bool

	ReconnectWait time.Duration

	// Message handler to be implemented/assigned by the embedding client
	Handler func([]byte)
	// contains filtered or unexported fields
}

func NewWsClient

func NewWsClient(ctx context.Context, url string) *WsClient

func (*WsClient) CallSubscription

func (c *WsClient) CallSubscription(key string, message []byte)

func (*WsClient) Close

func (c *WsClient) Close()

func (*WsClient) Connect

func (c *WsClient) Connect() error

func (*WsClient) IsConnected

func (c *WsClient) IsConnected() bool

func (*WsClient) SetHandler

func (c *WsClient) SetHandler(stream string, handler func([]byte) error)

SetHandler registers a local handler (no network request)

func (*WsClient) Subscribe

func (c *WsClient) Subscribe(stream string, handler func([]byte) error) error

Subscribe sends a subscription request

func (*WsClient) Unsubscribe

func (c *WsClient) Unsubscribe(stream string) error

Unsubscribe sends an unsubscribe request

func (*WsClient) WriteJSON

func (c *WsClient) WriteJSON(v interface{}) error

type WsDepthEvent

type WsDepthEvent struct {
	EventType         string          `json:"e"`
	EventTime         int64           `json:"E"`
	TransactionTime   int64           `json:"T"`
	Symbol            string          `json:"s"`
	FirstUpdateID     int64           `json:"U"`
	FinalUpdateID     int64           `json:"u"`
	FinalUpdateIDLast int64           `json:"pu"` // Spot has pu? Yes usually.
	Bids              [][]interface{} `json:"b"`
	Asks              [][]interface{} `json:"a"`
}

type WsEventHeader

type WsEventHeader struct {
	EventType string `json:"e"`
	EventTime int64  `json:"E"`
	Symbol    string `json:"s"`
}

WsEventHeader Common header for all websocket events

type WsExecutionReportEvent

type WsExecutionReportEvent struct {
	EventType           string `json:"e"`
	EventTime           int64  `json:"E"`
	Symbol              string `json:"s"`
	ClientOrderID       string `json:"c"`
	Side                string `json:"S"`
	OrderType           string `json:"o"`
	TimeInForce         string `json:"f"`
	Quantity            string `json:"q"`
	Price               string `json:"p"`
	StopPrice           string `json:"P"`
	IcebergQuantity     string `json:"F"`
	OrderListID         int64  `json:"g"`
	OriginalClientID    string `json:"C"` // Original client order ID; This is the ID of the order being canceled
	ExecutionType       string `json:"x"`
	OrderStatus         string `json:"X"`
	RejectReason        string `json:"r"`
	OrderID             int64  `json:"i"`
	LastExecutedQty     string `json:"l"`
	CumulativeFilledQty string `json:"z"`
	LastExecutedPrice   string `json:"L"`
	CommissionAmount    string `json:"n"`
	CommissionAsset     string `json:"N"`
	TransactionTime     int64  `json:"T"`
	TradeID             int64  `json:"t"`
	Ignore              int64  `json:"I"`
	IsOrderWorking      bool   `json:"w"`
	IsMaker             bool   `json:"m"`
	CreationTime        int64  `json:"O"`
	CumulativeQuoteQty  string `json:"Z"`
	LastQuoteQty        string `json:"Y"`
	QuoteOrderQty       string `json:"Q"`
}

type WsKlineEvent

type WsKlineEvent struct {
	EventType string `json:"e"`
	EventTime int64  `json:"E"`
	Symbol    string `json:"s"`
	Kline     struct {
		StartTime           int64  `json:"t"`
		EndTime             int64  `json:"T"`
		Symbol              string `json:"s"`
		Interval            string `json:"i"`
		FirstTradeID        int64  `json:"f"`
		LastTradeID         int64  `json:"L"`
		OpenPrice           string `json:"o"`
		ClosePrice          string `json:"c"`
		HighPrice           string `json:"h"`
		LowPrice            string `json:"l"`
		Volume              string `json:"v"`
		QuoteVolume         string `json:"q"`
		IsClosed            bool   `json:"x"`
		QuoteAssetVolume    string `json:"Q"`
		TakerBuyBaseVolume  string `json:"V"`
		TakerBuyQuoteVolume string `json:"n"`
	} `json:"k"`
}

type WsMarketClient

type WsMarketClient struct {
	*WsClient
}

func NewWsMarketClient

func NewWsMarketClient(ctx context.Context) *WsMarketClient

func (*WsMarketClient) SubscribeAggTrade

func (c *WsMarketClient) SubscribeAggTrade(symbol string, handler func(*AggTradeEvent) error) error

SubscribeAggTrade

func (*WsMarketClient) SubscribeBookTicker

func (c *WsMarketClient) SubscribeBookTicker(symbol string, handler func(*BookTickerEvent) error) error

SubscribeBookTicker

func (*WsMarketClient) SubscribeIncrementOrderBook

func (c *WsMarketClient) SubscribeIncrementOrderBook(symbol string, interval string, callback func(*WsDepthEvent) error) error

SubscribeIncrementOrderBook interval default 250ms, option 500ms 100ms only increment depth

func (*WsMarketClient) SubscribeKline

func (c *WsMarketClient) SubscribeKline(symbol string, interval string, handler func(*KlineEvent) error) error

SubscribeKline

func (*WsMarketClient) SubscribeLimitOrderBook

func (c *WsMarketClient) SubscribeLimitOrderBook(symbol string, depth int, speed string, handler func(*DepthEvent) error) error

SubscribeLimitOrderBook

func (*WsMarketClient) UnsubscribeAggTrade

func (c *WsMarketClient) UnsubscribeAggTrade(symbol string) error

UnsubscribeAggTrade

func (*WsMarketClient) UnsubscribeKline

func (c *WsMarketClient) UnsubscribeKline(symbol string, interval string) error

UnsubscribeKline

func (*WsMarketClient) UnsubscribeLimitOrderBook

func (c *WsMarketClient) UnsubscribeLimitOrderBook(symbol string, depth int, speed string) error

UnsubscribeLimitOrderBook

Jump to

Keyboard shortcuts

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