Documentation
¶
Overview ¶
Package exchanges provides a unified Go SDK for interacting with multiple cryptocurrency exchanges. It offers both low-level SDK clients (REST + WebSocket) and high-level adapters implementing a common Exchange interface.
Quick Start ¶
adp, err := binance.NewAdapter(ctx, binance.Options{
APIKey: "your-api-key",
SecretKey: "your-secret-key",
})
if err != nil {
log.Fatal(err)
}
defer adp.Close()
ticker, err := adp.FetchTicker(ctx, "BTC")
Architecture ¶
The package is organized into several layers:
- Root package (exchanges): Unified interfaces, models, errors, and utilities
- Exchange packages (binance/, okx/, ...): Exchange-specific adapters and SDK clients
- Ratelimit package: Declarative sliding-window rate limiter
- Testsuite package: Adapter compliance test suite
Logger ¶
All adapters accept an optional Logger interface for structured logging. The interface is compatible with *zap.SugaredLogger. If no logger is provided, NopLogger is used (all output discarded).
Symbol Convention ¶
All Exchange methods accept a base currency symbol (e.g. "BTC", "ETH"). The adapter handles conversion to exchange-specific formats internally.
Index ¶
- Variables
- func CountDecimalPlaces(s string) int32
- func FloorToPrecision(value decimal.Decimal, precision int32) decimal.Decimal
- func FormatDecimal(d decimal.Decimal) string
- func GenerateID() string
- func Register(name string, ctor AdapterConstructor)
- func RegisteredExchanges() []string
- func RoundToPrecision(value decimal.Decimal, precision int32) decimal.Decimal
- func RoundToSignificantFigures(value decimal.Decimal, sigFigs int32) decimal.Decimal
- func ValidateAndFormatParams(params *OrderParams, details *SymbolDetails) error
- type Account
- type AccountManager
- func (m *AccountManager) Close()
- func (m *AccountManager) ForceRefresh(ctx context.Context) error
- func (m *AccountManager) GetAllPositions() []*Position
- func (m *AccountManager) GetLocalBalance() decimal.Decimal
- func (m *AccountManager) GetOrder(orderID string) (*Order, bool)
- func (m *AccountManager) GetOrderStream() <-chan *Order
- func (m *AccountManager) GetPosition(symbol string) (*Position, bool)
- func (m *AccountManager) GetPositionStream() <-chan *Position
- func (m *AccountManager) Start(ctx context.Context, syncInterval time.Duration) error
- type AccountType
- type AdapterConstructor
- type BanState
- type BaseAdapter
- func (b *BaseAdapter) AcquireRate(ctx context.Context, method string) error
- func (b *BaseAdapter) ApplySlippage(ctx context.Context, params *OrderParams, ...) error
- func (b *BaseAdapter) BanStatus() (banned bool, until time.Time)
- func (b *BaseAdapter) GetExchange() string
- func (b *BaseAdapter) GetLocalOrderBook(symbol string, depth int) *OrderBook
- func (b *BaseAdapter) GetLocalOrderBookImplementation(symbol string) (LocalOrderBook, bool)
- func (b *BaseAdapter) GetMarketType() MarketType
- func (b *BaseAdapter) GetOrderMode() OrderMode
- func (b *BaseAdapter) GetSymbolDetail(symbol string) (*SymbolDetails, error)
- func (b *BaseAdapter) IsAccountConnected() bool
- func (b *BaseAdapter) IsMarketConnected() bool
- func (b *BaseAdapter) IsOrderConnected() bool
- func (b *BaseAdapter) IsRESTMode() bool
- func (b *BaseAdapter) ListSymbols() []string
- func (b *BaseAdapter) MarkAccountConnected()
- func (b *BaseAdapter) MarkMarketConnected()
- func (b *BaseAdapter) MarkOrderConnected()
- func (b *BaseAdapter) RateLimitStats() []ratelimit.BucketStats
- func (b *BaseAdapter) RecordBan(err error) bool
- func (b *BaseAdapter) RemoveLocalOrderBook(symbol string)
- func (b *BaseAdapter) SetLocalOrderBook(symbol string, ob LocalOrderBook)
- func (b *BaseAdapter) SetOrderMode(mode OrderMode)
- func (b *BaseAdapter) SetSymbolDetails(details map[string]*SymbolDetails)
- func (b *BaseAdapter) ValidateOrder(params *OrderParams) error
- func (b *BaseAdapter) WaitOrderBookReady(ctx context.Context, symbol string) error
- func (b *BaseAdapter) WithRateLimiter(rules []ratelimit.RateLimitRule, weights map[string][]ratelimit.CategoryWeight)
- type ErrBanned
- type Exchange
- type ExchangeError
- type FeeRate
- type FundingRate
- type Interval
- type IsolatedMarginAccount
- type IsolatedMarginAsset
- type IsolatedMarginSymbol
- type Kline
- type KlineCallback
- type KlineOpts
- type Level
- type LocalOrderBook
- type LocalStateManager
- func (m *LocalStateManager) ApplyOrderUpdate(o *Order)
- func (m *LocalStateManager) ApplyPositionUpdate(p *Position)
- func (m *LocalStateManager) Close()
- func (m *LocalStateManager) GetAllOpenOrders() []Order
- func (m *LocalStateManager) GetAllPositions() []Position
- func (m *LocalStateManager) GetBalance() decimal.Decimal
- func (m *LocalStateManager) GetOrder(orderID string) (*Order, bool)
- func (m *LocalStateManager) GetOrderStream() <-chan *Order
- func (m *LocalStateManager) GetPosition(symbol string) (*Position, bool)
- func (m *LocalStateManager) GetPositionStream() <-chan *Position
- func (m *LocalStateManager) IsInitialized() bool
- func (m *LocalStateManager) SetInitialState(balance decimal.Decimal, positions []Position, orders []Order)
- func (m *LocalStateManager) UpdateBalance(balance decimal.Decimal)
- type Logger
- type Manager
- type MarginAccount
- type MarginAsset
- type MarginType
- type MarketType
- type ModifyOrderParams
- type Order
- func PlaceLimitOrder(ctx context.Context, adp Exchange, symbol string, side OrderSide, ...) (*Order, error)
- func PlaceMarketOrder(ctx context.Context, adp Exchange, symbol string, side OrderSide, ...) (*Order, error)
- func PlaceMarketOrderWithSlippage(ctx context.Context, adp Exchange, symbol string, side OrderSide, ...) (*Order, error)
- type OrderBook
- type OrderBookCallback
- type OrderMode
- type OrderParams
- type OrderSide
- type OrderStatus
- type OrderType
- type OrderUpdateCallback
- type PerpExchange
- type Position
- type PositionSide
- type PositionUpdateCallback
- type SpotBalance
- type SpotExchange
- type Streamable
- type SymbolDetails
- type Ticker
- type TickerCallback
- type TimeInForce
- type Trade
- type TradeCallback
- type TradeSide
- type TransferParams
Constants ¶
This section is empty.
Variables ¶
var ( ErrInsufficientBalance = errors.New("insufficient balance") ErrRateLimited = errors.New("rate limited") ErrInvalidPrecision = errors.New("invalid precision") ErrOrderNotFound = errors.New("order not found") ErrSymbolNotFound = errors.New("symbol not found") ErrMinNotional = errors.New("below minimum notional") ErrMinQuantity = errors.New("below minimum quantity") ErrAuthFailed = errors.New("authentication failed") ErrNetworkTimeout = errors.New("network timeout") ErrNotSupported = errors.New("not supported") )
Functions ¶
func CountDecimalPlaces ¶
CountDecimalPlaces returns how many significant decimal places a string representation has. Trailing zeros are not counted: "0.00010" → 4, "0.10" → 1.
func FloorToPrecision ¶
FloorToPrecision truncates (floors) a decimal value to the given number of decimal places.
func FormatDecimal ¶
FormatDecimal formats a decimal to string, stripping trailing zeros.
func GenerateID ¶
func GenerateID() string
GenerateID returns a unique numeric string safe for concurrent use. Values stay within [1, 2^48-1] range required by Lighter; other exchanges accept any numeric string.
func Register ¶
func Register(name string, ctor AdapterConstructor)
Register adds an exchange adapter constructor to the global registry. Call this from each exchange adapter's init() function:
func init() {
exchanges.Register("BINANCE", func(ctx context.Context, mt exchanges.MarketType, opts map[string]string) (exchanges.Exchange, error) {
return NewPerpAdapter(ctx, Options{
APIKey: opts["api_key"],
SecretKey: opts["secret_key"],
})
})
}
func RegisteredExchanges ¶
func RegisteredExchanges() []string
RegisteredExchanges returns the names of all registered exchanges.
func RoundToPrecision ¶
RoundToPrecision rounds a decimal value to the given number of decimal places.
func RoundToSignificantFigures ¶
RoundToSignificantFigures rounds a decimal to n significant figures.
func ValidateAndFormatParams ¶
func ValidateAndFormatParams(params *OrderParams, details *SymbolDetails) error
ValidateAndFormatParams validates and formats order parameters using cached symbol details. It rounds price and truncates quantity to the correct precision.
Types ¶
type Account ¶
type Account struct {
TotalBalance decimal.Decimal `json:"total_balance"`
AvailableBalance decimal.Decimal `json:"available_balance"`
Positions []Position `json:"positions"`
Orders []Order `json:"orders"` // Open orders
UnrealizedPnL decimal.Decimal `json:"unrealized_pnl"`
RealizedPnL decimal.Decimal `json:"realized_pnl"`
}
Account represents a trading account summary.
type AccountManager ¶
type AccountManager struct {
// contains filtered or unexported fields
}
AccountManager automates local state management for a perp adapter. It synchronizes Positions, Orders, and Balance via WebSocket and exposes read-only channels. It requires the adapter to implement both PerpExchange and Streamable.
func NewAccountManager ¶
func NewAccountManager(adapter PerpExchange, logger Logger) (*AccountManager, error)
NewAccountManager creates a new manager for the given perp adapter. The adapter must implement both PerpExchange and Streamable.
func (*AccountManager) ForceRefresh ¶
func (m *AccountManager) ForceRefresh(ctx context.Context) error
ForceRefresh manually re-fetches full state from REST API.
func (*AccountManager) GetAllPositions ¶
func (m *AccountManager) GetAllPositions() []*Position
GetAllPositions returns a copy of all current positions.
func (*AccountManager) GetLocalBalance ¶
func (m *AccountManager) GetLocalBalance() decimal.Decimal
GetLocalBalance returns the last known balance.
func (*AccountManager) GetOrder ¶
func (m *AccountManager) GetOrder(orderID string) (*Order, bool)
GetOrder returns a copy of the order if found.
func (*AccountManager) GetOrderStream ¶
func (m *AccountManager) GetOrderStream() <-chan *Order
GetOrderStream returns the read-only channel for order updates.
func (*AccountManager) GetPosition ¶
func (m *AccountManager) GetPosition(symbol string) (*Position, bool)
GetPosition returns a copy of the position for the symbol.
func (*AccountManager) GetPositionStream ¶
func (m *AccountManager) GetPositionStream() <-chan *Position
GetPositionStream returns the read-only channel for position updates.
type AccountType ¶
type AccountType string
AccountType represents an account type for asset transfers.
const ( AccountTypeSpot AccountType = "SPOT" // Spot account AccountTypePerp AccountType = "PERP" // Perpetual futures account AccountTypeUnified AccountType = "UNIFIED" // Unified account )
type AdapterConstructor ¶
type AdapterConstructor func(ctx context.Context, marketType MarketType, opts map[string]string) (Exchange, error)
AdapterConstructor is the function signature that each exchange registers. It receives an options map and creates an adapter for the requested market type.
func LookupConstructor ¶
func LookupConstructor(name string) (AdapterConstructor, error)
LookupConstructor finds a registered constructor by name.
type BanState ¶
type BanState struct {
// contains filtered or unexported fields
}
BanState tracks IP ban status using an atomic timestamp for lock-free access. Zero means not banned; non-zero is the unix-ms expiry time.
func (*BanState) IsBanned ¶
IsBanned returns the current ban status and expiry time. Returns (false, zero) if not banned or ban has expired.
func (*BanState) ParseAndSetBan ¶
ParseAndSetBan checks if an error contains a "banned until" message. If found, records the ban and returns true.
type BaseAdapter ¶
type BaseAdapter struct {
*LocalStateManager // Embed state manager for Orders/Positions/Balance
Name string
MarketType MarketType
Logger Logger // Logger for this adapter
// contains filtered or unexported fields
}
BaseAdapter is designed to be embedded in specific exchange adapters. It provides a unified implementation for common adapter requirements: - Connection tracking (WS Market, WS Order, WS Account) - Local OrderBook mapping and readiness waiting - Symbol detail caching - Local state management (Orders, Positions, Balance) via embedding LocalStateManager - Automatic order validation and slippage handling
func NewBaseAdapter ¶
func NewBaseAdapter(name string, marketType MarketType, logger Logger) *BaseAdapter
NewBaseAdapter creates a new initialized BaseAdapter
func (*BaseAdapter) AcquireRate ¶
func (b *BaseAdapter) AcquireRate(ctx context.Context, method string) error
AcquireRate blocks until the rate limit allows this method to proceed. Checks ban status first — if banned, blocks until ban expires or ctx is cancelled. If no rateLimiter is configured, still checks ban status. Concrete adapters call this at the start of each REST method.
func (*BaseAdapter) ApplySlippage ¶
func (b *BaseAdapter) ApplySlippage( ctx context.Context, params *OrderParams, fetchTicker func(ctx context.Context, symbol string) (*Ticker, error), ) error
ApplySlippage converts a MARKET order with Slippage>0 into a LIMIT IOC order. The fetchTicker function is injected by the concrete adapter.
func (*BaseAdapter) BanStatus ¶
func (b *BaseAdapter) BanStatus() (banned bool, until time.Time)
BanStatus returns current ban status for monitoring.
func (*BaseAdapter) GetExchange ¶
func (b *BaseAdapter) GetExchange() string
GetExchange returns the exchange name
func (*BaseAdapter) GetLocalOrderBook ¶
func (b *BaseAdapter) GetLocalOrderBook(symbol string, depth int) *OrderBook
GetLocalOrderBook returns the standard OrderBook struct from the local WS-maintained orderbook. This satisfies the Exchange interface requirement.
func (*BaseAdapter) GetLocalOrderBookImplementation ¶
func (b *BaseAdapter) GetLocalOrderBookImplementation(symbol string) (LocalOrderBook, bool)
GetLocalOrderBookImplementation returns the underlying LocalOrderBook implementation
func (*BaseAdapter) GetMarketType ¶
func (b *BaseAdapter) GetMarketType() MarketType
GetMarketType returns the market type
func (*BaseAdapter) GetOrderMode ¶
func (b *BaseAdapter) GetOrderMode() OrderMode
GetOrderMode returns the current order mode (defaults to WS).
func (*BaseAdapter) GetSymbolDetail ¶
func (b *BaseAdapter) GetSymbolDetail(symbol string) (*SymbolDetails, error)
GetSymbolDetail returns the cached detail for a symbol
func (*BaseAdapter) IsAccountConnected ¶
func (b *BaseAdapter) IsAccountConnected() bool
IsAccountConnected checks if account WS is connected
func (*BaseAdapter) IsMarketConnected ¶
func (b *BaseAdapter) IsMarketConnected() bool
IsMarketConnected checks if market WS is connected
func (*BaseAdapter) IsOrderConnected ¶
func (b *BaseAdapter) IsOrderConnected() bool
IsOrderConnected checks if order WS is connected
func (*BaseAdapter) IsRESTMode ¶
func (b *BaseAdapter) IsRESTMode() bool
IsRESTMode returns true if orders should use REST/HTTP transport.
func (*BaseAdapter) ListSymbols ¶
func (b *BaseAdapter) ListSymbols() []string
ListSymbols returns all symbols in the symbol details cache. These are base currency symbols (e.g. "BTC", "ETH") loaded at adapter init.
func (*BaseAdapter) MarkAccountConnected ¶
func (b *BaseAdapter) MarkAccountConnected()
MarkAccountConnected marks the account websocket as connected
func (*BaseAdapter) MarkMarketConnected ¶
func (b *BaseAdapter) MarkMarketConnected()
MarkMarketConnected marks the market websocket as connected
func (*BaseAdapter) MarkOrderConnected ¶
func (b *BaseAdapter) MarkOrderConnected()
MarkOrderConnected marks the order websocket as connected
func (*BaseAdapter) RateLimitStats ¶
func (b *BaseAdapter) RateLimitStats() []ratelimit.BucketStats
RateLimitStats returns current rate limit usage for monitoring. Returns nil if no rate limiter is configured.
func (*BaseAdapter) RecordBan ¶
func (b *BaseAdapter) RecordBan(err error) bool
RecordBan checks if an error indicates an IP ban and records it. Call this after any REST method that returns an error. Returns true if a ban was detected.
func (*BaseAdapter) RemoveLocalOrderBook ¶
func (b *BaseAdapter) RemoveLocalOrderBook(symbol string)
RemoveLocalOrderBook removes a local orderbook
func (*BaseAdapter) SetLocalOrderBook ¶
func (b *BaseAdapter) SetLocalOrderBook(symbol string, ob LocalOrderBook)
SetLocalOrderBook registers an instantiated LocalOrderBook implementation
func (*BaseAdapter) SetOrderMode ¶
func (b *BaseAdapter) SetOrderMode(mode OrderMode)
SetOrderMode sets whether order operations use WS or REST transport.
func (*BaseAdapter) SetSymbolDetails ¶
func (b *BaseAdapter) SetSymbolDetails(details map[string]*SymbolDetails)
SetSymbolDetails replaces the entire symbol details cache
func (*BaseAdapter) ValidateOrder ¶
func (b *BaseAdapter) ValidateOrder(params *OrderParams) error
ValidateOrder validates and auto-formats order params using cached symbol details. Call this at the start of PlaceOrder in every adapter.
func (*BaseAdapter) WaitOrderBookReady ¶
func (b *BaseAdapter) WaitOrderBookReady(ctx context.Context, symbol string) error
WaitOrderBookReady waits for a specific subscribed orderbook to be ready.
func (*BaseAdapter) WithRateLimiter ¶
func (b *BaseAdapter) WithRateLimiter(rules []ratelimit.RateLimitRule, weights map[string][]ratelimit.CategoryWeight)
WithRateLimiter configures rate limiting for this adapter. Called by each exchange's constructor with exchange-specific rules and weights.
type Exchange ¶
type Exchange interface {
// === Identity ===
GetExchange() string
GetMarketType() MarketType
Close() error
// === Symbol Mapping ===
// FormatSymbol converts a base symbol (e.g. "BTC") to exchange-specific format.
FormatSymbol(symbol string) string
// ExtractSymbol converts an exchange-specific symbol back to base symbol.
ExtractSymbol(symbol string) string
// ListSymbols returns all symbols supported by this adapter.
ListSymbols() []string
// === Market Data (REST) ===
FetchTicker(ctx context.Context, symbol string) (*Ticker, error)
FetchOrderBook(ctx context.Context, symbol string, limit int) (*OrderBook, error)
FetchTrades(ctx context.Context, symbol string, limit int) ([]Trade, error)
FetchKlines(ctx context.Context, symbol string, interval Interval, opts *KlineOpts) ([]Kline, error)
// === Trading ===
PlaceOrder(ctx context.Context, params *OrderParams) (*Order, error)
CancelOrder(ctx context.Context, orderID, symbol string) error
CancelAllOrders(ctx context.Context, symbol string) error
FetchOrder(ctx context.Context, orderID, symbol string) (*Order, error)
FetchOpenOrders(ctx context.Context, symbol string) ([]Order, error)
// === Account ===
FetchAccount(ctx context.Context) (*Account, error)
FetchBalance(ctx context.Context) (decimal.Decimal, error)
FetchSymbolDetails(ctx context.Context, symbol string) (*SymbolDetails, error)
FetchFeeRate(ctx context.Context, symbol string) (*FeeRate, error)
// === Local OrderBook (WS-maintained) ===
// WatchOrderBook subscribes to orderbook updates and maintains a local copy.
// The callback is called on every update; pass nil for pull-only mode.
// This method blocks until the initial snapshot is synced.
WatchOrderBook(ctx context.Context, symbol string, cb OrderBookCallback) error
GetLocalOrderBook(symbol string, depth int) *OrderBook
StopWatchOrderBook(ctx context.Context, symbol string) error
// === WebSocket Streaming ===
Streamable
}
Exchange is the primary interface for strategy developers. It provides a unified, CCXT-inspired API for interacting with any exchanges.
Symbol convention: all methods accept a **base currency** symbol (e.g. "BTC", "ETH"). The adapter handles conversion to echange-specific formats internally.
Method naming convention: Fetch* = REST query, Watch* = WebSocket subscription.
type ExchangeError ¶
type ExchangeError struct {
Exchange string // Exchange name, e.g. "BINANCE"
Code string // Exchange-specific error code
Message string // Original error message from exchange
Err error // Sentinel error for errors.Is matching
}
ExchangeError wraps an exchange-specific error with a sentinel cause. Use errors.Is(err, adapter.ErrInsufficientBalance) for structured handling.
func NewExchangeError ¶
func NewExchangeError(exchange, code, message string, sentinel error) *ExchangeError
NewExchangeError creates a new ExchangeError.
func (*ExchangeError) Error ¶
func (e *ExchangeError) Error() string
func (*ExchangeError) Unwrap ¶
func (e *ExchangeError) Unwrap() error
type FundingRate ¶
type FundingRate struct {
Symbol string `json:"symbol"`
FundingRate decimal.Decimal `json:"funding_rate"`
FundingIntervalHours int64 `json:"funding_interval_hours"`
FundingTime int64 `json:"funding_time"`
NextFundingTime int64 `json:"next_funding_time"`
UpdateTime int64 `json:"update_time"`
}
FundingRate represents the funding rate for a perpetual futures symbol.
type Interval ¶
type Interval string
Interval represents the candlestick/kline time period.
const ( Interval1m Interval = "1m" Interval3m Interval = "3m" Interval5m Interval = "5m" Interval15m Interval = "15m" Interval30m Interval = "30m" Interval1h Interval = "1h" Interval2h Interval = "2h" Interval4h Interval = "4h" Interval6h Interval = "6h" Interval8h Interval = "8h" Interval12h Interval = "12h" Interval1d Interval = "1d" Interval3d Interval = "3d" Interval1w Interval = "1w" Interval1M Interval = "1M" )
type IsolatedMarginAccount ¶
type IsolatedMarginAccount struct {
Assets []IsolatedMarginSymbol `json:"assets"`
TotalAssetBTC decimal.Decimal `json:"total_asset_btc"`
TotalLiabilityBTC decimal.Decimal `json:"total_liability_btc"`
TotalNetAssetBTC decimal.Decimal `json:"total_net_asset_btc"`
}
IsolatedMarginAccount represents an isolated margin account summary.
type IsolatedMarginAsset ¶
type IsolatedMarginAsset struct {
Asset string `json:"asset"`
BorrowEnabled bool `json:"borrow_enabled"`
Borrowed decimal.Decimal `json:"borrowed"`
Free decimal.Decimal `json:"free"`
Interest decimal.Decimal `json:"interest"`
Locked decimal.Decimal `json:"locked"`
NetAsset decimal.Decimal `json:"net_asset"`
TotalAsset decimal.Decimal `json:"total_asset"`
}
IsolatedMarginAsset represents a single asset in an isolated margin account.
type IsolatedMarginSymbol ¶
type IsolatedMarginSymbol struct {
Symbol string `json:"symbol"`
BaseAsset IsolatedMarginAsset `json:"base_asset"`
QuoteAsset IsolatedMarginAsset `json:"quote_asset"`
MarginLevel decimal.Decimal `json:"margin_level"`
MarginRatio decimal.Decimal `json:"margin_ratio"`
IndexPrice decimal.Decimal `json:"index_price"`
LiquidatePrice decimal.Decimal `json:"liquidate_price"`
LiquidateRate decimal.Decimal `json:"liquidate_rate"`
Enabled bool `json:"enabled"`
}
IsolatedMarginSymbol represents an isolated margin trading pair.
type Kline ¶
type Kline struct {
Symbol string `json:"symbol"`
Interval Interval `json:"interval"`
Open decimal.Decimal `json:"open"`
High decimal.Decimal `json:"high"`
Low decimal.Decimal `json:"low"`
Close decimal.Decimal `json:"close"`
Volume decimal.Decimal `json:"volume"` // Base currency volume
QuoteVol decimal.Decimal `json:"quote_vol"` // Quote currency volume
Timestamp int64 `json:"timestamp"` // Open time in milliseconds
}
Kline represents a single candlestick/OHLCV bar.
type KlineCallback ¶
type KlineCallback func(*Kline)
type Level ¶
type Level struct {
Price decimal.Decimal `json:"price"`
Quantity decimal.Decimal `json:"quantity"`
}
Level represents a single price level in the order book.
type LocalOrderBook ¶
type LocalOrderBook interface {
// GetDepth returns the sorted top `limit` depth levels.
// Bids are sorted descending (highest price first).
// Asks are sorted ascending (lowest price first).
GetDepth(limit int) ([]Level, []Level)
// WaitReady blocks until the orderbook is initialized or the timeout expires.
WaitReady(ctx context.Context, timeout time.Duration) bool
// Timestamp returns the Unix millisecond timestamp of the last update.
Timestamp() int64
}
LocalOrderBook interface standardizes the output of locally maintained orderbooks. This allows the BaseAdapter and upper logic layers to consume depth data uniformly, regardless of whether the internal sync uses delta snapshots, buffer timestamps, or gapless polling.
Each exchange implements this interface in its own orderbook.go file because synchronization protocols differ (Binance: diff+snapshot, Nado: gap detection, OKX: checksum validation, etc.).
type LocalStateManager ¶
type LocalStateManager struct {
// contains filtered or unexported fields
}
LocalStateManager provides thread-safe local state management for adapters. It tracks Orders, Positions, and Balances, typically updated via WebSocket streams. Unlike LocalOrderBook (which is per-exchange), this is a shared concrete implementation because order/position state management logic is identical across all exchanges.
func NewLocalStateManager ¶
func NewLocalStateManager(logger Logger) *LocalStateManager
NewLocalStateManager initializes a new LocalStateManager
func (*LocalStateManager) ApplyOrderUpdate ¶
func (m *LocalStateManager) ApplyOrderUpdate(o *Order)
ApplyOrderUpdate applies an incremental order update
func (*LocalStateManager) ApplyPositionUpdate ¶
func (m *LocalStateManager) ApplyPositionUpdate(p *Position)
ApplyPositionUpdate applies an incremental position update
func (*LocalStateManager) Close ¶
func (m *LocalStateManager) Close()
Close closes the LocalStateManager (channels cleaned up by GC).
func (*LocalStateManager) GetAllOpenOrders ¶
func (m *LocalStateManager) GetAllOpenOrders() []Order
GetAllOpenOrders returns a list of all current open orders
func (*LocalStateManager) GetAllPositions ¶
func (m *LocalStateManager) GetAllPositions() []Position
GetAllPositions returns a list of all positions
func (*LocalStateManager) GetBalance ¶
func (m *LocalStateManager) GetBalance() decimal.Decimal
GetBalance returns the cached total balance
func (*LocalStateManager) GetOrder ¶
func (m *LocalStateManager) GetOrder(orderID string) (*Order, bool)
GetOrder returns a copy of the desired order if it exists locally
func (*LocalStateManager) GetOrderStream ¶
func (m *LocalStateManager) GetOrderStream() <-chan *Order
GetOrderStream gets the read-only channel for order updates
func (*LocalStateManager) GetPosition ¶
func (m *LocalStateManager) GetPosition(symbol string) (*Position, bool)
GetPosition returns a copy of the desired position if it exists locally
func (*LocalStateManager) GetPositionStream ¶
func (m *LocalStateManager) GetPositionStream() <-chan *Position
GetPositionStream gets the read-only channel for position updates
func (*LocalStateManager) IsInitialized ¶
func (m *LocalStateManager) IsInitialized() bool
IsInitialized returns whether state has been populated
func (*LocalStateManager) SetInitialState ¶
func (m *LocalStateManager) SetInitialState(balance decimal.Decimal, positions []Position, orders []Order)
SetInitialState populates the state from a REST API snapshot
func (*LocalStateManager) UpdateBalance ¶
func (m *LocalStateManager) UpdateBalance(balance decimal.Decimal)
UpdateBalance applies an incremental balance update
type Logger ¶
type Logger interface {
Debugw(msg string, keysAndValues ...any)
Infow(msg string, keysAndValues ...any)
Warnw(msg string, keysAndValues ...any)
Errorw(msg string, keysAndValues ...any)
}
Logger is the logging interface used throughout the library. It is compatible with *zap.SugaredLogger out of the box.
Usage:
// With zap:
logger := zap.NewProduction().Sugar()
adp, err := binance.NewAdapter(ctx, binance.Options{Logger: logger})
// With NopLogger (default when no logger is provided):
adp, err := binance.NewAdapter(ctx, binance.Options{})
var NopLogger Logger = nopLogger{}
NopLogger discards all log output. This is the default when no logger is provided.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages multiple exchange adapters
func (*Manager) GetAdapter ¶
GetAdapter gets the adapter for a specific exchange
func (*Manager) GetAllAdapters ¶
GetAllAdapters returns all registered adapters
func (*Manager) GetExchangeNames ¶
GetExchangeNames returns sorted list of registered exchange names
type MarginAccount ¶
type MarginAccount struct {
MarginLevel decimal.Decimal `json:"margin_level"`
TotalAssetBTC decimal.Decimal `json:"total_asset_btc"`
TotalLiabilityBTC decimal.Decimal `json:"total_liability_btc"`
TotalNetAssetBTC decimal.Decimal `json:"total_net_asset_btc"`
UserAssets []MarginAsset `json:"user_assets"`
}
MarginAccount represents a cross-margin account summary.
type MarginAsset ¶
type MarginAsset struct {
Asset string `json:"asset"`
Borrowed decimal.Decimal `json:"borrowed"`
Free decimal.Decimal `json:"free"`
Interest decimal.Decimal `json:"interest"`
Locked decimal.Decimal `json:"locked"`
NetAsset decimal.Decimal `json:"net_asset"`
}
MarginAsset represents a single asset in a margin account.
type MarginType ¶
type MarginType string
const ( MarginTypeCrossed MarginType = "CROSSED" MarginTypeIsolated MarginType = "ISOLATED" MarginTypeCash MarginType = "CASH" )
type MarketType ¶
type MarketType string
MarketType represents the type of trading market.
const ( MarketTypeSpot MarketType = "spot" // Spot trading MarketTypePerp MarketType = "perp" // Perpetual futures )
type ModifyOrderParams ¶
ModifyOrderParams specifies parameters for modifying an existing order.
type Order ¶
type Order struct {
OrderID string `json:"order_id"`
Symbol string `json:"symbol"`
Side OrderSide `json:"side"`
Type OrderType `json:"type"`
Quantity decimal.Decimal `json:"quantity"`
Price decimal.Decimal `json:"price,omitempty"`
Status OrderStatus `json:"status"`
FilledQuantity decimal.Decimal `json:"filled_quantity"`
Timestamp int64 `json:"timestamp"`
Fee decimal.Decimal `json:"fee,omitempty"`
ClientOrderID string `json:"client_order_id,omitempty"`
ReduceOnly bool `json:"reduce_only,omitempty"`
TimeInForce TimeInForce `json:"time_in_force,omitempty"`
}
Order represents a trading order with its current state.
func PlaceLimitOrder ¶
func PlaceLimitOrder(ctx context.Context, adp Exchange, symbol string, side OrderSide, price, qty decimal.Decimal) (*Order, error)
PlaceLimitOrder is a convenience function for placing a limit order.
type OrderBook ¶
type OrderBook struct {
Symbol string `json:"symbol"`
Bids []Level `json:"bids"` // Sorted descending by price
Asks []Level `json:"asks"` // Sorted ascending by price
Timestamp int64 `json:"timestamp"`
}
OrderBook represents a snapshot of the order book.
type OrderBookCallback ¶
type OrderBookCallback func(*OrderBook)
type OrderMode ¶
type OrderMode string
OrderMode controls whether trading operations (PlaceOrder, CancelOrder, etc.) use WebSocket or REST/HTTP transport.
type OrderParams ¶
type OrderParams struct {
Symbol string
Side OrderSide
Type OrderType // MARKET or LIMIT
Quantity decimal.Decimal
Price decimal.Decimal // Required for LIMIT; ignored for MARKET (unless Slippage > 0)
TimeInForce TimeInForce // Default: GTC for LIMIT
ReduceOnly bool
Slippage decimal.Decimal // If > 0 and Type == MARKET, auto-applies slippage logic
ClientID string // Client-defined order ID
}
OrderParams is the unified parameter struct for PlaceOrder.
type OrderSide ¶
type OrderSide string
OrderSide represents the direction of an order (buy or sell).
type OrderStatus ¶
type OrderStatus string
OrderStatus represents the state of an order.
const ( OrderStatusPending OrderStatus = "PENDING" OrderStatusPartiallyFilled OrderStatus = "PARTIALLY_FILLED" OrderStatusFilled OrderStatus = "FILLED" OrderStatusCancelled OrderStatus = "CANCELLED" OrderStatusRejected OrderStatus = "REJECTED" OrderStatusNew OrderStatus = "NEW" OrderStatusUnknown OrderStatus = "UNKNOWN" )
type OrderType ¶
type OrderType string
OrderType represents the type of an order.
const ( OrderTypeLimit OrderType = "LIMIT" OrderTypeMarket OrderType = "MARKET" OrderTypeStopLossLimit OrderType = "STOP_LOSS_LIMIT" OrderTypeTakeProfitLimit OrderType = "TAKE_PROFIT_LIMIT" OrderTypeStopLossMarket OrderType = "STOP_LOSS_MARKET" OrderTypeTakeProfitMarket OrderType = "TAKE_PROFIT_MARKET" OrderTypePostOnly OrderType = "POST_ONLY" OrderTypeUnknown OrderType = "UNKNOWN" )
type OrderUpdateCallback ¶
type OrderUpdateCallback func(*Order)
type PerpExchange ¶
type PerpExchange interface {
Exchange
FetchPositions(ctx context.Context) ([]Position, error)
SetLeverage(ctx context.Context, symbol string, leverage int) error
FetchFundingRate(ctx context.Context, symbol string) (*FundingRate, error)
FetchAllFundingRates(ctx context.Context) ([]FundingRate, error)
ModifyOrder(ctx context.Context, orderID, symbol string, params *ModifyOrderParams) (*Order, error)
}
PerpExchange extends Exchange with perpetual futures capabilities. Use type assertion: if perp, ok := adp.(adapter.PerpExchange); ok { ... }
type Position ¶
type Position struct {
Symbol string `json:"symbol"`
Side PositionSide `json:"side"`
Quantity decimal.Decimal `json:"quantity"`
EntryPrice decimal.Decimal `json:"entry_price"`
UnrealizedPnL decimal.Decimal `json:"unrealized_pnl"`
RealizedPnL decimal.Decimal `json:"realized_pnl"`
LiquidationPrice decimal.Decimal `json:"liquidation_price,omitempty"`
Leverage decimal.Decimal `json:"leverage,omitempty"`
MaintenanceMargin decimal.Decimal `json:"maintenance_margin,omitempty"`
MarginType string `json:"margin_type,omitempty"` // ISOLATED or CROSSED
}
Position represents an open position in a perpetual futures market.
type PositionSide ¶
type PositionSide string
PositionSide represents the direction of a position.
const ( PositionSideLong PositionSide = "LONG" PositionSideShort PositionSide = "SHORT" PositionSideBoth PositionSide = "BOTH" // For one-way mode )
type PositionUpdateCallback ¶
type PositionUpdateCallback func(*Position)
type SpotBalance ¶
type SpotBalance struct {
Asset string `json:"asset"` // Currency symbol, e.g. "BTC", "USDT"
Free decimal.Decimal `json:"free"` // Available balance
Locked decimal.Decimal `json:"locked"` // Frozen/locked balance
Total decimal.Decimal `json:"total"` // Total balance (Free + Locked)
}
SpotBalance represents the balance of a single asset in a spot account.
type SpotExchange ¶
type SpotExchange interface {
Exchange
FetchSpotBalances(ctx context.Context) ([]SpotBalance, error)
TransferAsset(ctx context.Context, params *TransferParams) error
}
SpotExchange extends Exchange with spot-specific capabilities.
type Streamable ¶
type Streamable interface {
WatchOrders(ctx context.Context, cb OrderUpdateCallback) error
WatchPositions(ctx context.Context, cb PositionUpdateCallback) error
WatchTicker(ctx context.Context, symbol string, cb TickerCallback) error
WatchTrades(ctx context.Context, symbol string, cb TradeCallback) error
WatchKlines(ctx context.Context, symbol string, interval Interval, cb KlineCallback) error
StopWatchOrders(ctx context.Context) error
StopWatchPositions(ctx context.Context) error
StopWatchTicker(ctx context.Context, symbol string) error
StopWatchTrades(ctx context.Context, symbol string) error
StopWatchKlines(ctx context.Context, symbol string, interval Interval) error
}
Streamable provides WebSocket streaming capabilities. All Watch methods accept a callback. Not all exchanges support all stream types.
type SymbolDetails ¶
type SymbolDetails struct {
Symbol string `json:"symbol"`
PricePrecision int32 `json:"price_precision"` // Decimal places for price
QuantityPrecision int32 `json:"quantity_precision"` // Decimal places for quantity
MinQuantity decimal.Decimal `json:"min_quantity"` // Minimum order quantity
MinNotional decimal.Decimal `json:"min_notional"` // Minimum notional value (price * qty)
}
SymbolDetails provides trading rules and precision for a symbol.
type Ticker ¶
type Ticker struct {
Symbol string `json:"symbol"`
LastPrice decimal.Decimal `json:"last_price"`
IndexPrice decimal.Decimal `json:"index_price"`
MarkPrice decimal.Decimal `json:"mark_price"`
MidPrice decimal.Decimal `json:"mid_price"`
Bid decimal.Decimal `json:"bid"` // Best Bid
Ask decimal.Decimal `json:"ask"` // Best Ask
Volume24h decimal.Decimal `json:"volume_24h"`
QuoteVol decimal.Decimal `json:"quote_vol"` // Quote Volume
High24h decimal.Decimal `json:"high_24h"`
Low24h decimal.Decimal `json:"low_24h"`
Timestamp int64 `json:"timestamp"`
}
Ticker represents real-time market data for a symbol.
type TickerCallback ¶
type TickerCallback func(*Ticker)
type TimeInForce ¶
type TimeInForce string
TimeInForce specifies how long an order remains active.
const ( TimeInForceGTC TimeInForce = "GTC" // Good Till Cancel TimeInForceIOC TimeInForce = "IOC" // Immediate Or Cancel TimeInForceFOK TimeInForce = "FOK" // Fill Or Kill TimeInForcePO TimeInForce = "PO" // Post Only )
type Trade ¶
type Trade struct {
ID string `json:"id"`
Symbol string `json:"symbol"`
Price decimal.Decimal `json:"price"`
Quantity decimal.Decimal `json:"quantity"`
Side TradeSide `json:"side"`
Timestamp int64 `json:"timestamp"` // Milliseconds
}
Trade represents a single market trade.
type TradeCallback ¶
type TradeCallback func(*Trade)
type TransferParams ¶
type TransferParams struct {
Asset string // Currency symbol
Amount decimal.Decimal // Transfer amount
FromAccount AccountType // Source account type
ToAccount AccountType // Destination account type
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ratelimit provides a generic, declarative rate limiting engine.
|
Package ratelimit provides a generic, declarative rate limiting engine. |