perp

package
v0.1.1 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 (
	PongInterval         = 1 * time.Minute
	ReconnectWait        = 1 * time.Second
	MaxReconnectAttempts = 10
)
View Source
const (
	BaseURL = "https://fapi.asterdex.com"
)
View Source
const (
	WSBaseURL = "wss://fstream.asterdex.com/ws"
)

Variables

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

special handle kline and !bookTicker

Functions

func BuildQueryString

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

BuildQueryString builds a query string from a map

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 AccountConfigUpdateEvent

type AccountConfigUpdateEvent struct {
	EventType       string `json:"e"`
	EventTime       int64  `json:"E"`
	TransactionTime int64  `json:"T"`
	AccountConfig   struct {
		Symbol   string `json:"s"`
		Leverage int    `json:"l"`
	} `json:"ac"`
	MultiAssetsConfig struct {
		MultiAssets bool `json:"j"`
	} `json:"ai"`
}

type AccountResponse

type AccountResponse struct {
	FeeTier                     int    `json:"feeTier"`
	CanTrade                    bool   `json:"canTrade"`
	CanDeposit                  bool   `json:"canDeposit"`
	CanWithdraw                 bool   `json:"canWithdraw"`
	UpdateTime                  int64  `json:"updateTime"`
	TotalInitialMargin          string `json:"totalInitialMargin"`
	TotalMaintMargin            string `json:"totalMaintMargin"`
	TotalWalletBalance          string `json:"totalWalletBalance"`
	TotalUnrealizedProfit       string `json:"totalUnrealizedProfit"`
	TotalMarginBalance          string `json:"totalMarginBalance"`
	TotalPositionInitialMargin  string `json:"totalPositionInitialMargin"`
	TotalOpenOrderInitialMargin string `json:"totalOpenOrderInitialMargin"`
	MaxWithdrawAmount           string `json:"maxWithdrawAmount"`
	Assets                      []struct {
		Asset                  string `json:"asset"`
		WalletBalance          string `json:"walletBalance"`
		UnrealizedProfit       string `json:"unrealizedProfit"`
		MarginBalance          string `json:"marginBalance"`
		MaintMargin            string `json:"maintMargin"`
		InitialMargin          string `json:"initialMargin"`
		PositionInitialMargin  string `json:"positionInitialMargin"`
		OpenOrderInitialMargin string `json:"openOrderInitialMargin"`
		MaxWithdrawAmount      string `json:"maxWithdrawAmount"`
		CrossWalletBalance     string `json:"crossWalletBalance"`
		CrossUnPnl             string `json:"crossUnPnl"`
		AvailableBalance       string `json:"availableBalance"`
		MarginAvailable        bool   `json:"marginAvailable"`
		UpdateTime             int64  `json:"updateTime"`
	} `json:"assets"`
	Positions []struct {
		Symbol                 string `json:"symbol"`
		InitialMargin          string `json:"initialMargin"`
		MaintMargin            string `json:"maintMargin"`
		UnrealizedProfit       string `json:"unrealizedProfit"`
		PositionInitialMargin  string `json:"positionInitialMargin"`
		OpenOrderInitialMargin string `json:"openOrderInitialMargin"`
		Leverage               string `json:"leverage"`
		Isolated               bool   `json:"isolated"`
		EntryPrice             string `json:"entryPrice"`
		MaxNotional            string `json:"maxNotional"`
		PositionSide           string `json:"positionSide"`
		PositionAmt            string `json:"positionAmt"`
		UpdateTime             int64  `json:"updateTime"`
	} `json:"positions"`
}

type AccountUpdateEvent

type AccountUpdateEvent struct {
	EventType       string `json:"e"`
	EventTime       int64  `json:"E"`
	TransactionTime int64  `json:"T"`
	UpdateData      struct {
		EventReasonType string `json:"m"`
		Balances        []struct {
			Asset              string `json:"a"`
			WalletBalance      string `json:"wb"`
			CrossWalletBalance string `json:"cw"`
			BalanceChange      string `json:"bc"`
		} `json:"B"`
		Positions []struct {
			Symbol              string `json:"s"`
			PositionAmount      string `json:"pa"`
			EntryPrice          string `json:"ep"`
			AccumulatedRealized string `json:"cr"`
			UnrealizedPnL       string `json:"up"`
			MarginType          string `json:"mt"`
			IsolatedWallet      string `json:"iw"`
			PositionSide        string `json:"ps"`
		} `json:"P"`
	} `json:"a"`
}

type AggTrade

type AggTrade struct {
	ID           int64  `json:"a"`
	Price        string `json:"p"`
	Quantity     string `json:"q"`
	FirstTradeID int64  `json:"f"`
	LastTradeID  int64  `json:"l"`
	Timestamp    int64  `json:"T"`
	IsBuyerMaker bool   `json:"m"`
}

type BalanceResponse

type BalanceResponse struct {
	AccountAlias       string `json:"accountAlias"`
	Asset              string `json:"asset"`
	Balance            string `json:"balance"`
	CrossWalletBalance string `json:"crossWalletBalance"`
	CrossUnPnl         string `json:"crossUnPnl"`
	AvailableBalance   string `json:"availableBalance"`
	MaxWithdrawAmount  string `json:"maxWithdrawAmount"`
}

type CancelAllOrdersParams

type CancelAllOrdersParams struct {
	Symbol string
}

type CancelOrderParams

type CancelOrderParams struct {
	Symbol            string
	OrderID           string
	OrigClientOrderID string
}

type Client

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

func NewClient

func NewClient() *Client

func (*Client) CancelAllOpenOrders

func (c *Client) CancelAllOpenOrders(ctx context.Context, p CancelAllOrdersParams) error

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, p CancelOrderParams) (*OrderResponse, error)

func (*Client) ChangeLeverage

func (c *Client) ChangeLeverage(ctx context.Context, symbol string, leverage int) (*LeverageResponse, error)

func (*Client) ChangeMarginType

func (c *Client) ChangeMarginType(ctx context.Context, symbol string, marginType string) error

func (*Client) ChangeMultiAssetsMode

func (c *Client) ChangeMultiAssetsMode(ctx context.Context, multiAssetsMargin bool) error

func (*Client) ChangePositionMode

func (c *Client) ChangePositionMode(ctx context.Context, dualSidePosition bool) error

func (*Client) CloseListenKey

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

func (*Client) ContinousKlines

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

ContinousKlines

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) GetAggTrades

func (c *Client) GetAggTrades(ctx context.Context, symbol string, limit int) ([]AggTrade, error)

func (*Client) GetAllFundingRates

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

GetAllFundingRates retrieves funding rates for all symbols Returns per-hour funding rates (converted from settlement interval rates)

func (*Client) GetBalance

func (c *Client) GetBalance(ctx context.Context) ([]BalanceResponse, error)

func (*Client) GetFeeRate

func (c *Client) GetFeeRate(ctx context.Context, symbol string) (*FeeRateResponse, error)

func (*Client) GetFundingInfo

func (c *Client) GetFundingInfo(ctx context.Context) ([]FundingInfo, error)

GetFundingInfo retrieves funding rate configuration information

func (*Client) GetFundingRate

func (c *Client) GetFundingRate(ctx context.Context, symbol string) (*FundingRateData, error)

GetFundingRate retrieves the funding rate for a specific symbol Returns per-hour funding rate (converted from the settlement interval rate)

func (*Client) GetMultiAssetsMode

func (c *Client) GetMultiAssetsMode(ctx context.Context) (*MultiAssetsModeResponse, 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) GetPositionMode

func (c *Client) GetPositionMode(ctx context.Context) (*PositionModeResponse, error)

func (*Client) GetPositionRisk

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

func (*Client) KeepAliveListenKey

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

func (*Client) Klines

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

func (*Client) MarkPrice

func (c *Client) MarkPrice(ctx context.Context, symbol string) (*MarkPriceResponse, error)

func (*Client) ModifyOrder

func (c *Client) ModifyOrder(ctx context.Context, p ModifyOrderParams) (*OrderResponse, 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) Put

func (c *Client) Put(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) WithCredentials

func (c *Client) WithCredentials(apiKey, secretKey string) *Client

func (*Client) WithDebug

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

type DepthResponse

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

type ExchangeInfoResponse

type ExchangeInfoResponse struct {
	Timezone        string        `json:"timezone"`
	ServerTime      int64         `json:"serverTime"`
	RateLimits      []interface{} `json:"rateLimits"`
	ExchangeFilters []interface{} `json:"exchangeFilters"`
	Symbols         []SymbolInfo  `json:"symbols"`
}

type FeeRateResponse

type FeeRateResponse struct {
	Symbol              string `json:"symbol"`
	MakerCommissionRate string `json:"makerCommissionRate"`
	TakerCommissionRate string `json:"takerCommissionRate"`
	RpiCommissionRate   string `json:"rpiCommissionRate"`
}

type FundingInfo

type FundingInfo struct {
	Symbol                   string `json:"symbol"`
	AdjustedFundingRateCap   string `json:"adjustedFundingRateCap"`
	AdjustedFundingRateFloor string `json:"adjustedFundingRateFloor"`
	FundingIntervalHours     int64  `json:"fundingIntervalHours"`
}

FundingInfo contains funding rate configuration from fundingInfo endpoint

type FundingRateData

type FundingRateData struct {
	Symbol               string `json:"symbol"`
	LastFundingRate      string `json:"lastFundingRate"`      // Per-hour funding rate (standardized)
	FundingIntervalHours int64  `json:"fundingIntervalHours"` // Actual settlement interval in hours
	FundingTime          int64  `json:"fundingTime"`          // Current funding time (calculated)
	NextFundingTime      int64  `json:"nextFundingTime"`
}

FundingRateData contains funding rate information from premiumIndex endpoint

type KlineResponse

type KlineResponse []interface{}

type LeverageResponse

type LeverageResponse struct {
	Leverage         int    `json:"leverage"`
	MaxNotionalValue string `json:"maxNotionalValue"`
	Symbol           string `json:"symbol"`
}

type ListenKeyResponse

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

type MarginTypeResponse

type MarginTypeResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

type MarkPriceResponse

type MarkPriceResponse struct {
	Symbol               string `json:"symbol"`
	MarkPrice            string `json:"markPrice"`
	IndexPrice           string `json:"indexPrice"`
	EstimatedSettlePrice string `json:"estimatedSettlePrice"`
	LastFundingRate      string `json:"lastFundingRate"`
	NextFundingTime      int64  `json:"nextFundingTime"`
}

type ModifyOrderParams

type ModifyOrderParams struct {
	OrderID           int64
	OrigClientOrderID string
	Symbol            string
	Side              string // BUY or SELL
	Quantity          string
	Price             string
	PriceMatch        string // NONE, OPPONENT, OPPONENT_5, OPPONENT_10, OPPONENT_20, QUEUE, QUEUE_5, QUEUE_10, QUEUE_20
}

type MsgDispatcher

type MsgDispatcher interface {
	Dispatch(data []byte) error
}

type MultiAssetsModeResponse

type MultiAssetsModeResponse struct {
	MultiAssetsMargin bool `json:"multiAssetsMargin"`
}

type OrderResponse

type OrderResponse struct {
	ClientOrderID string `json:"clientOrderId"`
	CumQty        string `json:"cumQty"`
	CumQuote      string `json:"cumQuote"`
	ExecutedQty   string `json:"executedQty"`
	OrderID       int64  `json:"orderId"`
	AvgPrice      string `json:"avgPrice"`
	OrigQty       string `json:"origQty"`
	Price         string `json:"price"`
	ReduceOnly    bool   `json:"reduceOnly"`
	Side          string `json:"side"`
	PositionSide  string `json:"positionSide"`
	Status        string `json:"status"`
	StopPrice     string `json:"stopPrice"`
	ClosePosition bool   `json:"closePosition"`
	Symbol        string `json:"symbol"`
	TimeInForce   string `json:"timeInForce"`
	Type          string `json:"type"`
	OrigType      string `json:"origType"`
	ActivatePrice string `json:"activatePrice"`
	PriceRate     string `json:"priceRate"`
	UpdateTime    int64  `json:"updateTime"`
	WorkingType   string `json:"workingType"`
	PriceProtect  bool   `json:"priceProtect"`
}

type OrderType

type OrderType string
const (
	OrderType_LIMIT                OrderType = "LIMIT"
	OrderType_MARKET               OrderType = "MARKET"
	OrderType_STOP_MARKET          OrderType = "STOP_MARKET"
	OrderType_STOP_LIMIT           OrderType = "STOP"
	OrderType_TAKE_PROFIT_MARKET   OrderType = "TAKE_PROFIT_MARKET"
	OrderType_TAKE_PROFIT_LIMIT    OrderType = "TAKE_PROFIT"
	OrderType_TRAILING_STOP_MARKET OrderType = "TRAILING_STOP_MARKET"
)

type OrderUpdateEvent

type OrderUpdateEvent struct {
	EventType       string `json:"e"`
	EventTime       int64  `json:"E"`
	TransactionTime int64  `json:"T"`
	Order           struct {
		Symbol               string `json:"s"`
		ClientOrderID        string `json:"c"`
		Side                 string `json:"S"`
		OrderType            string `json:"o"`
		TimeInForce          string `json:"f"`
		OriginalQty          string `json:"q"`
		OriginalPrice        string `json:"p"`
		AveragePrice         string `json:"ap"`
		StopPrice            string `json:"sp"`
		ExecutionType        string `json:"x"`
		OrderStatus          string `json:"X"`
		OrderID              int64  `json:"i"`
		LastFilledQty        string `json:"l"`
		AccumulatedFilledQty string `json:"z"`
		LastFilledPrice      string `json:"L"`
		CommissionAsset      string `json:"N"`
		Commission           string `json:"n"`
		TradeTime            int64  `json:"T"`
		TradeID              int64  `json:"t"`
		BidsNotional         string `json:"b"`
		AsksNotional         string `json:"a"`
		IsMaker              bool   `json:"m"`
		IsReduceOnly         bool   `json:"R"`
		WorkingType          string `json:"wt"`
		OriginalType         string `json:"ot"`
		PositionSide         string `json:"ps"`
		ClosePosition        bool   `json:"cp"`
		ActivationPrice      string `json:"AP"`
		CallbackRate         string `json:"cr"`
		RealizedProfit       string `json:"rp"`
	} `json:"o"`
}

type PlaceOrderParams

type PlaceOrderParams struct {
	Symbol           string
	Side             string
	PositionSide     string // Optional, for Hedge Mode
	Type             OrderType
	TimeInForce      TimeInForce // Optional
	Quantity         string
	Price            string // Optional
	NewClientOrderID string // Optional
	StopPrice        string // Optional
	ClosePosition    bool   // Optional
	ActivationPrice  string // Optional
	CallbackRate     string // Optional
	WorkingType      string // Optional
	PriceProtect     bool   // Optional
	ReduceOnly       bool   // Optional
}

type PositionModeResponse

type PositionModeResponse struct {
	DualSidePosition bool `json:"dualSidePosition"` // true: Hedge Mode, false: One-way Mode
}

type PositionRiskResponse

type PositionRiskResponse struct {
	EntryPrice       string `json:"entryPrice"`
	MarginType       string `json:"marginType"`
	IsAutoAddMargin  string `json:"isAutoAddMargin"`
	IsolatedMargin   string `json:"isolatedMargin"`
	Leverage         string `json:"leverage"`
	LiquidationPrice string `json:"liquidationPrice"`
	MarkPrice        string `json:"markPrice"`
	MaxNotionalValue string `json:"maxNotionalValue"`
	PositionAmt      string `json:"positionAmt"`
	Symbol           string `json:"symbol"`
	UnRealizedProfit string `json:"unRealizedProfit"`
	PositionSide     string `json:"positionSide"`
	Notional         string `json:"notional"`
	IsolatedWallet   string `json:"isolatedWallet"`
	UpdateTime       int64  `json:"updateTime"`
}

type ServerTimeResponse

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

type Subscription

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

type SymbolInfo

type SymbolInfo struct {
	Symbol                string                   `json:"symbol"`
	Pair                  string                   `json:"pair"`
	ContractType          string                   `json:"contractType"`
	DeliveryDate          int64                    `json:"deliveryDate"`
	OnboardDate           int64                    `json:"onboardDate"`
	Status                string                   `json:"status"`
	MaintMarginPercent    string                   `json:"maintMarginPercent"`
	RequiredMarginPercent string                   `json:"requiredMarginPercent"`
	BaseAsset             string                   `json:"baseAsset"`
	QuoteAsset            string                   `json:"quoteAsset"`
	MarginAsset           string                   `json:"marginAsset"`
	PricePrecision        int                      `json:"pricePrecision"`
	QuantityPrecision     int                      `json:"quantityPrecision"`
	BaseAssetPrecision    int                      `json:"baseAssetPrecision"`
	QuotePrecision        int                      `json:"quotePrecision"`
	UnderlyingType        string                   `json:"underlyingType"`
	UnderlyingSubType     []string                 `json:"underlyingSubType"`
	SettlePlan            int64                    `json:"settlePlan"`
	TriggerProtect        string                   `json:"triggerProtect"`
	Filters               []map[string]interface{} `json:"filters"`
	OrderType             []string                 `json:"orderType"`
	TimeInForce           []string                 `json:"timeInForce"`
	LiquidationFee        string                   `json:"liquidationFee"`
	MarketTakeBound       string                   `json:"marketTakeBound"`
}

type TickerResponse

type TickerResponse struct {
	Symbol             string `json:"symbol"`
	PriceChange        string `json:"priceChange"`
	PriceChangePercent string `json:"priceChangePercent"`
	WeightedAvgPrice   string `json:"weightedAvgPrice"`
	LastPrice          string `json:"lastPrice"`
	LastQty            string `json:"lastQty"`
	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 TimeInForce

type TimeInForce string
const (
	TimeInForce_GTC TimeInForce = "GTC"
	TimeInForce_IOC TimeInForce = "IOC"
	TimeInForce_FOK TimeInForce = "FOK"
	TimeInForce_GTX TimeInForce = "GTX"
)

type Trade

type Trade struct {
	Symbol          string `json:"symbol"`
	ID              int64  `json:"id"`
	OrderID         int64  `json:"orderId"`
	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"`
	PositionSide    string `json:"positionSide"`
	RealizedPnl     string `json:"realizedPnl"`
}

type TradeLiteEvent

type TradeLiteEvent struct {
	EventType       string `json:"e"`
	EventTime       int64  `json:"E"`
	TransactionTime int64  `json:"T"`
	Symbol          string `json:"s"`
	OriginalQty     string `json:"q"`
	OriginalPrice   string `json:"p"`
	IsMaker         bool   `json:"m"`
	ClientOrderID   string `json:"c"`
	Side            string `json:"S"`
	LastFilledPrice string `json:"L"`
	LastFilledQty   string `json:"l"`
	TradeID         int64  `json:"t"`
	OrderID         int64  `json:"i"`
}

type WsAccountClient

type WsAccountClient struct {
	*WsClient
	Client       *Client
	KeepAliveInt time.Duration
	ListenKey    string
	// contains filtered or unexported fields
}

func NewWsAccountClient

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

func (*WsAccountClient) Close

func (c *WsAccountClient) Close()

func (*WsAccountClient) Connect

func (c *WsAccountClient) Connect() error

func (*WsAccountClient) SubscribeAccountConfigUpdate

func (c *WsAccountClient) SubscribeAccountConfigUpdate(callback func(*AccountConfigUpdateEvent))

func (*WsAccountClient) SubscribeAccountUpdate

func (c *WsAccountClient) SubscribeAccountUpdate(callback func(*AccountUpdateEvent))

func (*WsAccountClient) SubscribeOrderUpdate

func (c *WsAccountClient) SubscribeOrderUpdate(callback func(*OrderUpdateEvent))

func (*WsAccountClient) WithURL

func (c *WsAccountClient) WithURL(url string) *WsAccountClient

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

type WsBookTickerEvent

type WsBookTickerEvent struct {
	EventType    string `json:"e"`
	EventTime    int64  `json:"E"` // Note: bookTicker doesn't always have "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"`
	Bids              [][]interface{} `json:"b"`
	Asks              [][]interface{} `json:"a"`
}

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 WsMarkPriceEvent

type WsMarkPriceEvent struct {
	EventType            string `json:"e"`
	EventTime            int64  `json:"E"`
	Symbol               string `json:"s"`
	MarkPrice            string `json:"p"`
	IndexPrice           string `json:"i"`
	EstimatedSettlePrice string `json:"P"`
	FundingRate          string `json:"r"`
	NextFundingTime      int64  `json:"T"`
}

type WsMarketClient

type WsMarketClient struct {
	*WsClient
}

func NewWsMarketClient

func NewWsMarketClient(ctx context.Context) *WsMarketClient

func (*WsMarketClient) SubscribeAggTrade

func (c *WsMarketClient) SubscribeAggTrade(symbol string, callback func(*WsAggTradeEvent) error) error

func (*WsMarketClient) SubscribeBookTicker

func (c *WsMarketClient) SubscribeBookTicker(symbol string, callback func(*WsBookTickerEvent) error) error

SubscribeBookTicker Optimal bid/ask price

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, callback func(*WsKlineEvent) error) error

func (*WsMarketClient) SubscribeLimitOrderBook

func (c *WsMarketClient) SubscribeLimitOrderBook(symbol string, levels int, interval string, callback func(*WsDepthEvent) error) error

SubscribeLimitOrderBook interval default 250ms, option 500ms 100ms only limit depth, options: 5 10 20

func (*WsMarketClient) SubscribeMarkPrice

func (c *WsMarketClient) SubscribeMarkPrice(symbol string, interval string, callback func(*WsMarkPriceEvent) error) error

SubscribeMarkPrice latest mark price interval default 1s, option 3s

func (*WsMarketClient) UnsubscribeAggTrade

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

func (*WsMarketClient) UnsubscribeBookTicker

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

func (*WsMarketClient) UnsubscribeIncrementOrderBook

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

func (*WsMarketClient) UnsubscribeKline

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

func (*WsMarketClient) UnsubscribeLimitOrderBook

func (c *WsMarketClient) UnsubscribeLimitOrderBook(symbol string, levels int, interval string) error

func (*WsMarketClient) UnsubscribeMarkPrice

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

Jump to

Keyboard shortcuts

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