common

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const AlgoRestApiProdUrl = "https://api.binance.com"

Algo API URLs

View Source
const AlphaRestApiProdUrl = "https://www.binance.com"

Alpha API URLs

View Source
const C2CRestApiProdUrl = "https://api.binance.com"

C2C API URLs

View Source
const ConvertRestApiProdUrl = "https://api.binance.com"

Convert API URLs

View Source
const CopyTradingRestApiProdUrl = "https://api.binance.com"

Copy Trading API URLs

View Source
const CryptoLoanRestApiProdUrl = "https://api.binance.com"

Crypto Loan API URLs

View Source
const DerivativesTradingCoinFuturesRestApiProdUrl = "https://dapi.binance.com"

Derivatives Trading Coin Futures API URLs

View Source
const DerivativesTradingCoinFuturesRestApiTestnetUrl = "https://testnet.binancefuture.com"
View Source
const DerivativesTradingCoinFuturesWebsocketApiProdUrl = "wss://ws-dapi.binance.com/ws-dapi/v1"
View Source
const DerivativesTradingCoinFuturesWebsocketApiTestnetUrl = "wss://testnet.binancefuture.com/ws-dapi/v1"
View Source
const DerivativesTradingCoinFuturesWebsocketStreamsProdUrl = "wss://dstream.binance.com/stream"
View Source
const DerivativesTradingCoinFuturesWebsocketStreamsTestnetUrl = "wss://dstream.binancefuture.com/stream"
View Source
const DerivativesTradingOptionsRestApiProdUrl = "https://eapi.binance.com"

Derivatives Trading Options API URLs

View Source
const DerivativesTradingOptionsWebsocketStreamsProdUrl = "wss://fstream.binance.com"
View Source
const DerivativesTradingPortfolioMarginProRestApiProdUrl = "https://api.binance.com"

Derivatives Trading Portfolio Margin Pro API URLs

View Source
const DerivativesTradingPortfolioMarginProWebsocketStreamsProdUrl = "wss://fstream.binance.com/pm-classic"
View Source
const DerivativesTradingPortfolioMarginRestApiProdUrl = "https://papi.binance.com"

Derivatives Trading Portfolio Margin API URLs

View Source
const DerivativesTradingPortfolioMarginRestApiTestnetUrl = "https://testnet.binancefuture.com"
View Source
const DerivativesTradingPortfolioMarginWebsocketStreamsProdUrl = "wss://fstream.binance.com/pm"
View Source
const DerivativesTradingPortfolioMarginWebsocketStreamsTestnetUrl = "wss://fstream.binancefuture.com/pm"
View Source
const DerivativesTradingUsdsFuturesRestApiProdUrl = "https://fapi.binance.com"

Derivatives Trading USDS Futures API URLs

View Source
const DerivativesTradingUsdsFuturesRestApiTestnetUrl = "https://testnet.binancefuture.com"
View Source
const DerivativesTradingUsdsFuturesWebsocketApiProdUrl = "wss://ws-fapi.binance.com/ws-fapi/v1"
View Source
const DerivativesTradingUsdsFuturesWebsocketApiTestnetUrl = "wss://testnet.binancefuture.com/ws-fapi/v1"
View Source
const DerivativesTradingUsdsFuturesWebsocketStreamsProdUrl = "wss://fstream.binance.com/stream"
View Source
const DerivativesTradingUsdsFuturesWebsocketStreamsTestnetUrl = "wss://stream.binancefuture.com/stream"
View Source
const DualInvestmentRestApiProdUrl = "https://api.binance.com"

Dual Investment API URLs

View Source
const FiatRestApiProdUrl = "https://api.binance.com"

Fiat API URLs

View Source
const GiftCardRestApiProdUrl = "https://api.binance.com"

Gift Card API URLs

View Source
const MarginTradingRestApiProdUrl = "https://api.binance.com"

Margin Trading API URLs

View Source
const MarginTradingRiskWebsocketStreamsProdUrl = "wss://margin-stream.binance.com"
View Source
const MarginTradingWebsocketStreamsProdUrl = "wss://stream.binance.com:9443"
View Source
const MiningRestApiProdUrl = "https://api.binance.com"

Mining API URLs

View Source
const NFTRestApiProdUrl = "https://api.binance.com"

NFT API URLs

View Source
const PayRestApiProdUrl = "https://api.binance.com"

Pay API URLs

View Source
const RebateRestApiProdUrl = "https://api.binance.com"

Rebate API URLs

View Source
const SimpleEarnRestApiProdUrl = "https://api.binance.com"

Simple Earn API URLs

View Source
const SpotRestApiMarketUrl = "https://data-api.binance.vision"
View Source
const SpotRestApiProdUrl = "https://api.binance.com"

Spot API URLs

View Source
const SpotRestApiTestnetUrl = "https://testnet.binance.vision"
View Source
const SpotWebsocketApiProdUrl = "wss://ws-api.binance.com/ws-api/v3"
View Source
const SpotWebsocketApiTestnetUrl = "wss://ws-api.testnet.binance.vision/ws-api/v3"
View Source
const SpotWebsocketStreamsMarketUrl = "wss://data-stream.binance.vision/stream"
View Source
const SpotWebsocketStreamsProdUrl = "wss://stream.binance.com:9443/stream"
View Source
const SpotWebsocketStreamsTestnetUrl = "wss://stream.testnet.binance.vision/stream"
View Source
const StakingRestApiProdUrl = "https://api.binance.com"

Stake API URLs

View Source
const SubAccountRestApiProdUrl = "https://api.binance.com"

Sub-Account API URLs

View Source
const VipLoanRestApiProdUrl = "https://api.binance.com"

VIP Loan API URLs

View Source
const WalletRestApiProdUrl = "https://api.binance.com"

Wallet API URLs

Variables

View Source
var (
	JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`)
	XmlCheck  = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`)
)
View Source
var GenerateIntUUID = func() int32 {
	return randpkg.Int32()
}

GenerateIntUUID is a function that generates a new random int32 UUID.

@return An int32 representing the generated UUID.

View Source
var GenerateUUID = func() string {
	return uuid.New().String()
}

GenerateUUID is a function that generates a new UUID string.

@return A string representing the generated UUID.

View Source
var ShouldRetryRequest = func(err error, method string, retriesLeft int, resp *http.Response) bool {
	if retriesLeft <= 0 {
		return false
	}

	retriableMethods := map[string]bool{
		"GET":    true,
		"DELETE": true,
	}
	if _, ok := retriableMethods[strings.ToUpper(method)]; !ok {
		return false
	}

	if resp == nil {
		return true
	}

	retriableStatusCodes := map[int]bool{
		500: true,
		502: true,
		503: true,
		504: true,
	}

	return retriableStatusCodes[resp.StatusCode]
}

ShouldRetryRequest determines whether a request should be retried based on the error, HTTP method, retries left, and response.

@param err The error encountered during the request. @param method The HTTP method used for the request. @param retriesLeft The number of retries left. @param resp The HTTP response received (if any). @return A boolean indicating whether the request should be retried.

Functions

func BuildTransport

func BuildTransport(agent HTTPSAgent, cfg *ConfigurationRestAPI) http.RoundTripper

BuildTransport constructs an http.RoundTripper based on the provided HTTPSAgent and ConfigurationRestAPI.

@param agent The HTTPSAgent which can be nil, *tls.Config, or http.RoundTripper. @param cfg The ConfigurationRestAPI containing settings like Compression. @return An http.RoundTripper configured according to the provided agent and configuration.

func Decode

func Decode(v interface{}, b []byte, contentType string) (err error)

Decode decodes response body into the given interface v based on content type.

@param v The interface to decode the response body into. @param b The response body as a byte slice. @param contentType The content type of the response body. @return An error if decoding fails.

func FilterArrays

func FilterArrays[T any](slice []T, keep func(T) bool) []T

FilterArrays filters elements from a slice based on a provided condition function.

@param slice The input slice of type T. @param keep A function that determines whether to keep an element (returns true) or discard it (returns false). @return A new slice containing only the elements for which the keep function returned true.

func GetCustomHeaders

func GetCustomHeaders(c *ConfigurationRestAPI) map[string]string

func GetTimestamp

func GetTimestamp() int64

GetTimestamp returns the current timestamp in milliseconds.

@return The current timestamp in milliseconds as an int64.

func IsNil

func IsNil(i interface{}) bool

IsNil checks if the given interface is nil.

@param i The interface to check. @return True if the interface is nil, otherwise false.

func LoadPrivateKey

func LoadPrivateKey(privateKey string, passphrase string) (crypto.Signer, error)

LoadPrivateKey loads a private key from a PEM-formatted string or file path,

@param privateKey The PEM-formatted private key string or file path. @param passphrase The passphrase used to decrypt the private key, if it is encrypted. @return A crypto.Signer representing the loaded private key, or an error if loading fails.

func NewStrictDecoder

func NewStrictDecoder(data []byte) *json.Decoder

NewStrictDecoder creates a JSON decoder that disallows unknown fields.

@param data The JSON data as a byte slice. @return A JSON decoder configured to disallow unknown fields.

func NormalizePrivateKeyInput

func NormalizePrivateKeyInput(input string) (string, error)

NormalizePrivateKeyInput normalizes the private key input by checking if it's a file path or a PEM string.

@param input The private key input, which can be a file path or a PEM string. @return The normalized private key as a string and an error if any occurs during reading the file.

func ParameterAddToHeaderOrQuery

func ParameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, style string, collectionType string)

ParameterAddToHeaderOrQuery adds a parameter to header or query parameters.

@param headerOrQueryParams The header or query parameters to which the parameter will be added. @param keyPrefix The key under which the parameter will be added. @param obj The parameter value to be added. @param style The style of the parameter (e.g., "deepObject"). @param collectionType The collection type (e.g., "csv") for handling multiple values.

func ParsePrivateKey

func ParsePrivateKey(pemData string, password []byte) (crypto.Signer, error)

ParsePrivateKey parses a PEM encoded private key, which may be encrypted.

@param pemData The PEM encoded private key data. @param password The password used to decrypt the private key, if it is encrypted. @return A crypto.Signer representing the private key and an error if parsing fails.

func PrepareRequest

func PrepareRequest(
	ctx context.Context,
	path string, method string,
	headerParams map[string]string,
	queryParams url.Values,
	bodyParams interface{},
	c *ConfigurationRestAPI,
	signed bool) (localVarRequest *http.Request, err error)

PrepareRequest prepares an HTTP request with the given parameters.

@param ctx The context for the request. @param path The URL path for the request. @param method The HTTP method (GET, POST, etc.). @param headerParams A map of header parameters to include in the request. @param queryParams The query parameters for the request. @param c The configuration containing API keys, secrets, and other settings. @param signed A boolean indicating whether the request requires signing. @return The prepared HTTP request or an error if preparation fails.

func Pretty

func Pretty(v any) string

Pretty converts a value to its pretty-printed JSON string representation.

@param v The value to be pretty-printed. @return A string containing the pretty-printed JSON representation of the value.

func PtrBool

func PtrBool(v bool) *bool

PtrBool is a helper routine that returns a pointer to given boolean value.

@param v The bool value to be pointed to. @return A pointer to the provided bool value.

func PtrFloat32

func PtrFloat32(v float32) *float32

PtrFloat32 is a helper routine that returns a pointer to given float value.

@param v The float32 value to be pointed to. @return A pointer to the provided float32 value.

func PtrFloat64

func PtrFloat64(v float64) *float64

PtrFloat64 is a helper routine that returns a pointer to given float value.

@param v The float64 value to be pointed to. @return A pointer to the provided float64 value.

func PtrInt

func PtrInt(v int) *int

PtrInt is a helper routine that returns a pointer to given integer value.

@param v The int value to be pointed to. @return A pointer to the provided int value.

func PtrInt32

func PtrInt32(v int32) *int32

PtrInt32 is a helper routine that returns a pointer to given integer value.

@param v The int32 value to be pointed to. @return A pointer to the provided int32 value.

func PtrInt64

func PtrInt64(v int64) *int64

PtrInt64 is a helper routine that returns a pointer to given integer value.

@param v The int64 value to be pointed to. @return A pointer to the provided int64 value.

func PtrString

func PtrString(v string) *string

PtrString is a helper routine that returns a pointer to given string value.

@param v The string value to be pointed to. @return A pointer to the provided string value.

func PtrTime

func PtrTime(v time.Time) *time.Time

PtrTime is helper routine that returns a pointer to given Time value.

@param v The time.Time value to be pointed to. @return A pointer to the provided time.Time value.

func RandomString

func RandomString() (string, error)

RandomString generates a random hexadecimal string of length 32 (16 bytes).

@return A random hexadecimal string and an error if any occurs during generation.

func ReportError

func ReportError(format string, a ...interface{}) error

ReportError formats an error message.

@param format The format string. @param a The arguments to be formatted. @return An error with the formatted message.

func SelectHeaderContentType

func SelectHeaderContentType(contentTypes []string) string

SelectHeaderContentType selects a content type from the available options.

@param contentTypes A slice of content type strings. @return The selected content type string.

func SendMessage

func SendMessage[T any](w *WebsocketAPI, payload map[string]any, sendParams SendParams) (chan *ResponseOrRaw[T], chan error, error)

SendMessage sends a message over the WebSocket connection and returns channels for the response and error.

@param T The type of the expected response. @param w The WebsocketAPI instance. @param payload The message payload to be sent. @param sendParams Parameters for sending the message. @return A channel for the typed response, a channel for errors, and an error if sending fails.

func SetupProxy

func SetupProxy(cfg *ConfigurationRestAPI) *http.Client

SetupProxy sets up the HTTP client with proxy settings if provided in the configuration.

@param cfg The configuration containing proxy settings. @return An HTTP client configured with the proxy settings if provided, otherwise a default HTTP client.

func SignMessage

func SignMessage(priv crypto.Signer, message []byte) ([]byte, error)

SignMessage signs a message using the provided private key.

@param priv The private key used for signing. @param message The message to be signed. @return The signature as a byte slice and an error if any occurs during signing.

func Urlencode

func Urlencode(params map[string]any) string

Urlencode encodes a map of parameters into a URL-encoded query string.

@param params A map of parameter names to their corresponding values. @return A URL-encoded query string representing the parameters.

func WsBuildTransport

func WsBuildTransport(agent HTTPSAgent, tlsConfig *tls.Config) http.RoundTripper

WsBuildTransport constructs an http.RoundTripper for WebSocket connections based on the provided agent and TLS configuration.

@param agent The HTTPSAgent which can be a string (proxy URL) or other types. @param tlsConfig The TLS configuration to be used if applicable. @return An http.RoundTripper configured according to the provided agent and TLS configuration.

func WsStreamsPlaceholder

func WsStreamsPlaceholder(stream string, params map[string]string) string

WsStreamsPlaceholder replaces placeholders in a WebSocket stream string with actual parameter values.

@param stream The WebSocket stream string containing placeholders. @param params A map of parameter names to their corresponding values. @return The WebSocket stream string with placeholders replaced by actual values.

Types

type BadRequestError

type BadRequestError struct {
	BaseError
}

BadRequestError represents an error that occurs when a request is invalid or cannot be otherwise served.

func NewBadRequestError

func NewBadRequestError(msg string) *BadRequestError

type BaseError

type BaseError struct {
	Name    string
	Message string
}

func (*BaseError) Error

func (e *BaseError) Error() string

type ConfigurationRestAPI

type ConfigurationRestAPI struct {
	ApiKey               string
	ApiSecret            string
	BasePath             string
	Timeout              time.Duration
	Proxy                *ProxyConfig
	KeepAlive            bool
	Compression          bool
	Retries              int
	Backoff              int
	TimeUnit             TimeUnit
	PrivateKey           string
	PrivateKeyPassphrase string
	CustomHeaders        map[string]string
	Signer               Signer
	HTTPSAgent           HTTPSAgent
}

ConfigurationRestAPI holds configuration settings for REST API interactions.

@field ApiKey The API key for authentication. @field ApiSecret The API secret for authentication. @field BasePath The base URL for the API. @field Timeout The timeout duration for API requests. @field Proxy The proxy configuration. @field KeepAlive Indicates whether to keep connections alive. @field Compression Indicates whether to use compression. @field Retries The number of retry attempts for failed requests. @field Backoff The backoff duration between retries. @field TimeUnit The time unit used for rate limiting. @field PrivateKey The private key for signing requests. @field PrivateKeyPassphrase The passphrase for the private key. @field CustomHeaders A map of custom headers to include in requests. @field Signer The signer used for request signing. @field HTTPSAgent The HTTPS agent configuration.

func NewConfigurationRestAPI

func NewConfigurationRestAPI(opts ...ConfigurationRestAPIOption) *ConfigurationRestAPI

NewConfigurationRestAPI creates a new ConfigurationRestAPI with the provided options.

@param opts A variadic list of ConfigurationRestAPIOption functions to customize the configuration. @return A pointer to the newly created ConfigurationRestAPI.

type ConfigurationRestAPIOption

type ConfigurationRestAPIOption func(*ConfigurationRestAPI)

func WithApiSecret

func WithApiSecret(v string) ConfigurationRestAPIOption

func WithBackoff

func WithBackoff(v int) ConfigurationRestAPIOption

func WithBasePath

func WithBasePath(v string) ConfigurationRestAPIOption

func WithCompression

func WithCompression(v bool) ConfigurationRestAPIOption

func WithCustomHeaders

func WithCustomHeaders(v map[string]string) ConfigurationRestAPIOption

func WithKeepAlive

func WithKeepAlive(v bool) ConfigurationRestAPIOption

func WithPrivateKey

func WithPrivateKey(v string) ConfigurationRestAPIOption

func WithPrivateKeyPassphrase

func WithPrivateKeyPassphrase(v string) ConfigurationRestAPIOption

func WithProxy

func WithProxy(proxy ProxyConfig) ConfigurationRestAPIOption

func WithRetries

func WithRetries(v int) ConfigurationRestAPIOption

type ConfigurationWebsocketApi

type ConfigurationWebsocketApi struct {
	ApiKey               string
	ApiSecret            string
	PrivateKey           string
	PrivateKeyPassphrase string
	BasePath             string
	Timeout              time.Duration
	ReconnectDelay       time.Duration
	Compression          bool
	Proxy                *ProxyConfig
	Mode                 WebsocketMode
	PoolSize             int
	TimeUnit             TimeUnit
	SessionReLogon       bool
	Signer               Signer
	Agent                HTTPSAgent
}

ConfigurationWebsocketApi holds configuration settings for WebSocket API interactions.

@field ApiKey The API key for authentication. @field ApiSecret The API secret for authentication. @field PrivateKey The private key for signing requests. @field PrivateKeyPassphrase The passphrase for the private key. @field BasePath The base URL for the WebSocket API. @field Timeout The timeout duration for WebSocket connections. @field ReconnectDelay The delay duration before attempting to reconnect. @field Compression Indicates whether to use compression. @field Proxy The proxy configuration. @field Mode The WebSocket connection mode. @field PoolSize The size of the connection pool. @field TimeUnit The time unit used for rate limiting. @field SessionReLogon Indicates whether to re-logon on session expiration. @field Signer The signer used for request signing. @field Agent The HTTPS agent configuration.

func NewConfigurationWebsocketApi

func NewConfigurationWebsocketApi(opts ...ConfigurationWebsocketApiOption) *ConfigurationWebsocketApi

NewConfigurationWebsocketApi creates a new ConfigurationWebsocketApi with the provided options.

@param opts A variadic list of ConfigurationWebsocketApiOption functions to customize the configuration. @return A pointer to the newly created ConfigurationWebsocketApi.

func (*ConfigurationWebsocketApi) GetAgent

func (c *ConfigurationWebsocketApi) GetAgent() HTTPSAgent

func (*ConfigurationWebsocketApi) GetBasePath

func (c *ConfigurationWebsocketApi) GetBasePath() string

func (*ConfigurationWebsocketApi) GetCompression

func (c *ConfigurationWebsocketApi) GetCompression() bool

func (*ConfigurationWebsocketApi) GetProxy

func (c *ConfigurationWebsocketApi) GetProxy() *ProxyConfig

func (*ConfigurationWebsocketApi) GetReconnectDelay

func (c *ConfigurationWebsocketApi) GetReconnectDelay() time.Duration

func (*ConfigurationWebsocketApi) GetTLSConfig

func (c *ConfigurationWebsocketApi) GetTLSConfig() *tls.Config

GetTLSConfig retrieves the TLS configuration from the HTTPS agent or proxy settings.

@return A pointer to the tls.Config if available, otherwise nil.

func (*ConfigurationWebsocketApi) GetTimeUnit

func (c *ConfigurationWebsocketApi) GetTimeUnit() TimeUnit

type ConfigurationWebsocketStreams

type ConfigurationWebsocketStreams struct {
	BasePath       string
	ReconnectDelay time.Duration
	Compression    bool
	Proxy          *ProxyConfig
	Mode           WebsocketMode
	PoolSize       int
	TimeUnit       TimeUnit
	Agent          HTTPSAgent
}

ConfigurationWebsocketStreams holds configuration settings for WebSocket Streams interactions.

@field BasePath The base URL for the WebSocket Streams. @field ReconnectDelay The delay duration before attempting to reconnect. @field Compression Indicates whether to use compression. @field Proxy The proxy configuration. @field Mode The WebSocket connection mode. @field PoolSize The size of the connection pool. @field TimeUnit The time unit used for rate limiting. @field Agent The HTTPS agent configuration.

func NewConfigurationWebsocketStreams

func NewConfigurationWebsocketStreams(opts ...ConfigurationWebsocketStreamsOption) *ConfigurationWebsocketStreams

NewConfigurationWebsocketStreams creates a new ConfigurationWebsocketStreams with the provided options.

@param opts A variadic list of ConfigurationWebsocketStreamsOption functions to customize the configuration. @return A pointer to the newly created ConfigurationWebsocketStreams.

func (*ConfigurationWebsocketStreams) GetAgent

func (*ConfigurationWebsocketStreams) GetBasePath

func (c *ConfigurationWebsocketStreams) GetBasePath() string

func (*ConfigurationWebsocketStreams) GetCompression

func (c *ConfigurationWebsocketStreams) GetCompression() bool

func (*ConfigurationWebsocketStreams) GetProxy

func (*ConfigurationWebsocketStreams) GetReconnectDelay

func (c *ConfigurationWebsocketStreams) GetReconnectDelay() time.Duration

func (*ConfigurationWebsocketStreams) GetTLSConfig

func (c *ConfigurationWebsocketStreams) GetTLSConfig() *tls.Config

GetTLSConfig retrieves the TLS configuration from the HTTPS agent or proxy settings.

@return A pointer to the tls.Config if available, otherwise nil.

func (*ConfigurationWebsocketStreams) GetTimeUnit

func (c *ConfigurationWebsocketStreams) GetTimeUnit() TimeUnit

type ConfigurationWrapper

type ConfigurationWrapper struct {
	APIConfig     *ConfigurationWebsocketApi
	StreamsConfig *ConfigurationWebsocketStreams
}

func (ConfigurationWrapper) IsAPI

func (c ConfigurationWrapper) IsAPI() bool

IsAPI checks if the configuration is for API.

@return True if the configuration is for API, otherwise false.

func (ConfigurationWrapper) IsStreams

func (c ConfigurationWrapper) IsStreams() bool

IsStreams checks if the configuration is for Streams.

@return True if the configuration is for Streams, otherwise false.

type ConnectorClientError

type ConnectorClientError struct {
	BaseError
}

ConnectorClientError represents a general error in the Connector client.

func NewConnectorClientError

func NewConnectorClientError(msg string) *ConnectorClientError

type ForbiddenError

type ForbiddenError struct {
	BaseError
}

ForbiddenError represents an error when a resource is forbidden.

func NewForbiddenError

func NewForbiddenError(msg string) *ForbiddenError

type HTTPSAgent

type HTTPSAgent interface{}

type Interval

type Interval string
const (
	Second Interval = "SECOND"
	Minute Interval = "MINUTE"
	Day    Interval = "DAY"
)

type IntervalDetails

type IntervalDetails struct {
	Interval    string
	IntervalNum int
}

func ParseIntervalDetails

func ParseIntervalDetails(headerKey string) *IntervalDetails

ParseIntervalDetails extracts interval details from a header key.

@param headerKey The header key containing interval information. @return An IntervalDetails struct with the extracted interval and number, or nil if parsing fails.

type MappedNullable

type MappedNullable interface {
	ToMap() (map[string]interface{}, error)
}

type NetworkError

type NetworkError struct {
	BaseError
}

NetworkError represents an error that occurs when a network error occurs.

func NewNetworkError

func NewNetworkError(msg string) *NetworkError

type NotFoundError

type NotFoundError struct {
	BaseError
}

NotFoundError represents an error that occurs when the requested resource was not found.

func NewNotFoundError

func NewNotFoundError(msg string) *NotFoundError

type NullableTime

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

func NewNullableTime

func NewNullableTime(val *time.Time) *NullableTime

NewNullableTime creates a new NullableTime with the given value.

@param val A pointer to the time.Time value to set. @return A pointer to the newly created NullableTime.

func (NullableTime) Get

func (v NullableTime) Get() *time.Time

Get returns the value of the NullableTime.

@return A pointer to the time.Time value, or nil if not set.

func (NullableTime) IsSet

func (v NullableTime) IsSet() bool

IsSet checks if the NullableTime has been set.

func (NullableTime) MarshalJSON

func (v NullableTime) MarshalJSON() ([]byte, error)

MarshalJSON serializes the NullableTime to JSON.

@return The JSON representation of the NullableTime or an error if serialization fails.

func (*NullableTime) Set

func (v *NullableTime) Set(val *time.Time)

Set assigns a value to the NullableTime and marks it as set.

@param val A pointer to the time.Time value to set.

func (*NullableTime) UnmarshalJSON

func (v *NullableTime) UnmarshalJSON(src []byte) error

UnmarshalJSON deserializes JSON data into the NullableTime.

@param src The JSON data as a byte slice. @return An error if deserialization fails.

func (*NullableTime) Unset

func (v *NullableTime) Unset()

Unset clears the value of the NullableTime and marks it as not set.

type ProxyConfig

type ProxyConfig struct {
	Host     string
	Port     int
	Protocol string
	Auth     struct {
		Username string
		Password string
	}
	TLSConfig *tls.Config
}

func (ProxyConfig) IsEmpty

func (pc ProxyConfig) IsEmpty() bool

IsEmpty checks if the ProxyConfig is empty.

@return True if all fields in the ProxyConfig are empty or zero, otherwise false.

func (ProxyConfig) URL

func (pc ProxyConfig) URL() (*url.URL, error)

URL constructs the full URL for the proxy configuration.

@return A pointer to the url.URL representing the proxy URL, or an error if the host is not set.

type RateLimit

type RateLimit struct {
	RateLimitType RateLimitType
	Interval      Interval
	IntervalNum   int32
	Count         int32
	RetryAfter    int32
}

func ParseRateLimitHeaders

func ParseRateLimitHeaders(header http.Header) ([]RateLimit, error)

ParseRateLimitHeaders parses rate limit information from HTTP headers.

@param header The HTTP headers containing rate limit information. @return A slice of RateLimit structs representing the parsed rate limits or an error if parsing fails.

type RateLimitBanError

type RateLimitBanError struct {
	BaseError
}

RateLimitBanError represents an error when a client IP has been banned.

func NewRateLimitBanError

func NewRateLimitBanError(msg string) *RateLimitBanError

type RateLimitType

type RateLimitType string
const (
	RequestWeight RateLimitType = "REQUEST_WEIGHT"
	Orders        RateLimitType = "ORDERS"
)

type RequiredError

type RequiredError struct {
	BaseError
	Field string
}

RequiredError represents an error when a required parameter is missing or undefined.

func NewRequiredError

func NewRequiredError(field, msg string) *RequiredError

type ResponseOrRaw

type ResponseOrRaw[T any] struct {
	Typed *T
	Raw   map[string]interface{}
}

ResponseOrRaw represents a response that can be either a typed structure or a raw map.

@param T The type of the typed response. @field Typed A pointer to the typed response structure. @field Raw A map representing the raw response data.

type RestApiResponse

type RestApiResponse[T any] struct {
	Data       T
	Status     int
	Headers    http.Header
	RateLimits []RateLimit
}

RestApiResponse represents a generic REST API response.

@param T The type of the data contained in the response. @field Data The data returned by the API. @field Status The HTTP status code of the response. @field Headers The HTTP headers of the response. @field RateLimits A list of rate limit information associated with the response.

func SendRequest

func SendRequest[T any](ctx context.Context, path string, method string, queryParams url.Values, bodyParams interface{}, cfg *ConfigurationRestAPI, signed bool) (*RestApiResponse[T], error)

SendRequest sends an HTTP request and handles retries, response decoding, and error handling.

@param ctx The context for the request. @param path The URL path for the request. @param method The HTTP method (GET, POST, etc.). @param queryParams The query parameters for the request. @param cfg The configuration containing API keys, secrets, and other settings. @param signed A boolean indicating whether the request requires signing. @return The response from the REST API or an error if the request fails.

type ResultUserData

type ResultUserData[T any, Ty any] struct {
	Value  *ResponseOrRaw[T]
	Stream *StreamHandler[Ty]
	Err    error
}

type ResultWebsocket

type ResultWebsocket[T any] struct {
	Value *ResponseOrRaw[T]
	Err   error
}

type SendParams

type SendParams struct {
	Signed           bool
	WithAPIKey       bool
	WithSessionLogon bool
}

type ServerError

type ServerError struct {
	BaseError
}

ServerError represents an error that occurs when there is an internal server error.

func NewServerError

func NewServerError(msg string, statusCode int) *ServerError

type SessionLogonRequest

type SessionLogonRequest struct {
	Method string
	Params map[string]interface{}
	ID     string
	Priv   crypto.Signer
}

type Signer

type Signer interface {
	Sign(data []byte) ([]byte, error)
}

type StreamHandler

type StreamHandler[T any] struct {
	Stream   string
	Wrapper  *StreamHandlerWrapper
	Callback func(T)
	ErrorCb  func(error)
}

func CreateStreamHandler

func CreateStreamHandler[T any](wrapper *StreamHandlerWrapper, stream string, id []any, strictInt bool) (*StreamHandler[T], error)

CreateStreamHandler creates a new StreamHandler for the specified stream and registers it with the provided StreamHandlerWrapper.

@param wrapper The StreamHandlerWrapper containing either a WebsocketStreams or WebsocketAPI instance. @param stream The name of the stream to handle. @param id An optional slice of IDs associated with the stream. @return A pointer to the created StreamHandler or an error if subscription fails.

func (*StreamHandler[T]) On

func (h *StreamHandler[T]) On(event string, callback func(T))

On registers a callback for the specified event on the stream associated with the StreamHandler.

@param event The event type to listen for (e.g., "message"). @param callback The callback function to handle incoming messages of type T.

func (*StreamHandler[T]) OnError

func (h *StreamHandler[T]) OnError(cb func(error))

OnError registers an error callback for the stream associated with the StreamHandler.

@param cb The callback function to handle errors.

func (*StreamHandler[T]) Unsubscribe

func (h *StreamHandler[T]) Unsubscribe()

Unsubscribe unsubscribes from the stream associated with the StreamHandler.

type StreamHandlerWrapper

type StreamHandlerWrapper struct {
	WebsocketStreams *WebsocketStreams
	WebsocketAPI     *WebsocketAPI
}

type TimeUnit

type TimeUnit string
const (
	MILLISECOND TimeUnit = "MILLISECOND"
	Millisecond TimeUnit = "millisecond"
	MICROSECOND TimeUnit = "MICROSECOND"
	Microsecond TimeUnit = "microsecond"
)

type TooManyRequestsError

type TooManyRequestsError struct {
	BaseError
}

TooManyRequestsError represents an error when a client is rate-limited.

func NewTooManyRequestsError

func NewTooManyRequestsError(msg string) *TooManyRequestsError

type UnauthorizedError

type UnauthorizedError struct {
	BaseError
}

UnauthorizedError represents an error when a client is unauthorized.

func NewUnauthorizedError

func NewUnauthorizedError(msg string) *UnauthorizedError

type WebSocketCommon

type WebSocketCommon struct {
	Connections     []*WebSocketConnection
	ReconnectTasks  map[string]chan struct{}
	Mode            WebsocketMode
	PoolSize        int
	ProxyDialer     proxy.Dialer
	RoundRobinIndex int
}

func NewWebSocketCommon

func NewWebSocketCommon(cfg *ConfigurationWrapper) (*WebSocketCommon, error)

NewWebSocketCommon creates a new instance of WebSocketCommon based on the provided configuration.

@param cfg The configuration wrapper containing either API or Streams configuration. @return A pointer to the WebSocketCommon instance or an error if initialization fails.

func (*WebSocketCommon) Connect

func (w *WebSocketCommon) Connect(config WebSocketConfig, userAgent string) error

Connect establishes the WebSocket connection using the provided configuration and user agent.

@param config The WebSocketConfig containing configuration details. @param userAgent The user agent string to be used for the connection. @return An error if the connection fails, otherwise nil.

func (*WebSocketCommon) CreateWebSocketDialer

func (w *WebSocketCommon) CreateWebSocketDialer(config WebSocketConfig) websocket.Dialer

CreateWebSocketDialer creates a WebSocket dialer with the specified configuration.

@param config The WebSocketConfig containing configuration details. @return A configured websocket.Dialer instance.

func (*WebSocketCommon) GetConnection

func (w *WebSocketCommon) GetConnection() (*WebSocketConnection, error)

GetConnection retrieves an available WebSocket connection using a round-robin strategy.

@return A pointer to the WebSocketConnection or an error if no connections are available.

func (*WebSocketCommon) KeepAlive

func (w *WebSocketCommon) KeepAlive(connection *WebSocketConnection, config WebSocketConfig, userAgent string)

KeepAlive periodically checks the health of the WebSocket connection and reconnects if necessary.

@param connection The WebSocketConnection to monitor. @param config The WebSocketConfig containing configuration details. @param userAgent The user agent string to use for the connection.

func (*WebSocketCommon) Ping

func (w *WebSocketCommon) Ping(conn *WebSocketConnection) error

Ping sends a ping message over the WebSocket connection.

@param conn The WebSocket connection to send the ping on. @return An error if the ping fails, otherwise nil.

type WebSocketConfig

type WebSocketConfig interface {
	GetAgent() HTTPSAgent
	GetBasePath() string
	GetReconnectDelay() time.Duration
	GetCompression() bool
	GetProxy() *ProxyConfig
	GetTLSConfig() *tls.Config
	GetTimeUnit() TimeUnit
}

type WebSocketConn

type WebSocketConn interface {
	WriteMessage(messageType int, data []byte) error
	ReadMessage() (messageType int, p []byte, err error)
	Close() error
	SetReadLimit(limit int64)
}

type WebSocketConnection

type WebSocketConnection struct {
	Id                  string
	Connected           WebsocketStatus
	PendingMessages     sync.Map
	StreamCallbackMap   map[string][]func(map[string]interface{})
	Websocket           WebSocketConn
	SessionLogon        bool
	SessionLogonRequest *SessionLogonRequest
	StreamConnectionMap []string
	Done                chan struct{}
	ErrorChan           chan error
	// contains filtered or unexported fields
}

func (*WebSocketConnection) HandleReadError

func (c *WebSocketConnection) HandleReadError(err error)

HandleReadError processes errors encountered during WebSocket read operations.

@param err The error encountered during the read operation.

func (*WebSocketConnection) IsHealthy

func (c *WebSocketConnection) IsHealthy() bool

IsHealthy checks if the WebSocket connection is healthy.

@return True if the connection is healthy, otherwise false.

func (*WebSocketConnection) Listen

func (c *WebSocketConnection) Listen()

Listen starts listening for incoming messages on the WebSocket connection.

func (*WebSocketConnection) ProcessMessage

func (c *WebSocketConnection) ProcessMessage() error

ProcessMessage reads and processes a single message from the WebSocket connection.

@return An error if processing fails, otherwise nil.

type WebSocketError

type WebSocketError struct {
	Op      string
	ConnID  string
	Err     error
	Message string
	Code    int
}

func (*WebSocketError) Error

func (e *WebSocketError) Error() string

WebSocketError represents an error that occurred during WebSocket operations.

type WebsocketAPI

type WebsocketAPI struct {
	Cfg                       *ConfigurationWebsocketApi
	GlobalStreamConnectionMap map[string][]*WebSocketConnection
	WsCommon                  *WebSocketCommon
}

func NewWebsocketAPI

func NewWebsocketAPI(cfg *ConfigurationWebsocketApi) (*WebsocketAPI, error)

NewWebsocketAPI creates a new instance of WebsocketAPI.

@param cfg The configuration for the WebSocket API. @return A pointer to the WebsocketAPI instance or an error if initialization fails.

func (*WebsocketAPI) CloseWebSocketConnection

func (w *WebsocketAPI) CloseWebSocketConnection() error

CloseWebSocketConnection closes all active WebSocket connections.

@return An error if any connection fails to close, otherwise nil.

func (*WebsocketAPI) Connect

func (w *WebsocketAPI) Connect(userAgent string) error

Connect establishes the WebSocket connection using the provided user agent.

@param userAgent The user agent string to be used for the connection. @return An error if the connection fails, otherwise nil.

func (*WebsocketAPI) Subscribe

func (w *WebsocketAPI) Subscribe(id string) error

Subscribe subscribes to the specified stream ID.

@param id The stream ID to subscribe to. @return An error if the subscription fails, otherwise nil.

func (*WebsocketAPI) Unsubscribe

func (w *WebsocketAPI) Unsubscribe(id string) error

Unsubscribe unsubscribes from the specified stream ID.

@param id The stream ID to unsubscribe from. @return An error if the unsubscription fails, otherwise nil.

type WebsocketMode

type WebsocketMode string
const (
	SINGLE WebsocketMode = "single"
	POOL   WebsocketMode = "pool"
)

type WebsocketStatus

type WebsocketStatus string
const (
	CONNECTING WebsocketStatus = "CONNECTING"
	OPEN       WebsocketStatus = "OPEN"
	CLOSING    WebsocketStatus = "CLOSING"
	CLOSED     WebsocketStatus = "CLOSED"
)

type WebsocketStreams

type WebsocketStreams struct {
	Cfg                       *ConfigurationWebsocketStreams
	GlobalStreamConnectionMap map[string][]*WebSocketConnection
	WsCommon                  *WebSocketCommon
}

func NewWebsocketStreams

func NewWebsocketStreams(cfg *ConfigurationWebsocketStreams) (*WebsocketStreams, error)

NewWebsocketStreams creates a new instance of WebsocketStreams.

@param cfg The configuration for the WebSocket streams. @return A pointer to the WebsocketStreams instance or an error if initialization fails.

func (*WebsocketStreams) CloseWebSocketStreamConnection

func (w *WebsocketStreams) CloseWebSocketStreamConnection() error

CloseWebSocketStreamConnection closes all active WebSocket connections in the WebsocketStreams instance.

@return An error if any connection fails to close, otherwise nil.

func (*WebsocketStreams) Connect

func (w *WebsocketStreams) Connect(userAgent string) error

func (*WebsocketStreams) IsSubscribed

func (w *WebsocketStreams) IsSubscribed(stream string) bool

IsSubscribed checks if the specified stream is currently subscribed.

@param stream The name of the stream to check. @return True if the stream is subscribed, otherwise false.

func (*WebsocketStreams) ListSubscriptions

func (w *WebsocketStreams) ListSubscriptions(streamId string) (map[string]interface{}, error)

ListSubscriptions lists the current subscriptions for the specified stream ID.

@param streamId The stream ID to list subscriptions for. If empty, a new UUID will be generated. @return A map containing the subscription details or an error if the operation fails.

func (*WebsocketStreams) On

func (w *WebsocketStreams) On(stream string, callback func(map[string]interface{})) error

On registers a callback function for the specified stream.

@param stream The name of the stream to register the callback for. @param callback The callback function to be invoked when a message is received for the specified stream. @return An error if the stream is not subscribed, otherwise nil.

func (*WebsocketStreams) Subscribe

func (w *WebsocketStreams) Subscribe(streams []string, id []any, strictInt bool) error

Subscribe subscribes to the specified streams.

@param streams A slice of stream names to subscribe to. @param id A slice of IDs corresponding to each stream. If empty, new UUIDs will be generated. @return An error if any subscription fails, otherwise nil.

func (*WebsocketStreams) Unsubscribe

func (w *WebsocketStreams) Unsubscribe(streams []string) error

Unsubscribe unsubscribes from the specified streams.

@param streams A slice of stream names to unsubscribe from. @return An error if any unsubscription fails, otherwise nil.

Jump to

Keyboard shortcuts

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