bybit

package
v1.61.0 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2024 License: AGPL-3.0 Imports: 17 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountBalanceProvider added in v1.52.0

type AccountBalanceProvider interface {
	QueryAccountBalances(ctx context.Context) (types.BalanceMap, error)
}

AccountBalanceProvider provides a function to query all balances at streaming connected and emit balance snapshot.

type BookEvent added in v1.52.0

type BookEvent struct {
	// Symbol name
	Symbol string `json:"s"`
	// Bids. For snapshot stream, the element is sorted by price in descending order
	Bids types.PriceVolumeSlice `json:"b"`
	// Asks. For snapshot stream, the element is sorted by price in ascending order
	Asks types.PriceVolumeSlice `json:"a"`
	// Update ID. Is a sequence. Occasionally, you'll receive "u"=1, which is a snapshot data due to the restart of
	// the service. So please overwrite your local orderbook
	UpdateId fixedpoint.Value `json:"u"`
	// Cross sequence. You can use this field to compare different levels orderbook data, and for the smaller seq,
	// then it means the data is generated earlier.
	SequenceId fixedpoint.Value `json:"seq"`

	// internal use
	// Copied from WebSocketTopicEvent.Type, WebSocketTopicEvent.Ts
	// Type can be one of snapshot or delta.
	Type DataType
	// ServerTime using the websocket timestamp as server time. Since the event not provide server time information.
	ServerTime time.Time
}

func (*BookEvent) OrderBook added in v1.52.0

func (e *BookEvent) OrderBook() (snapshot types.SliceOrderBook)

type DataType added in v1.52.0

type DataType string
const (
	DataTypeSnapshot DataType = "snapshot"
	DataTypeDelta    DataType = "delta"
)

type Exchange

type Exchange struct {

	// feeRateProvider provides the fee rate and fee currency for each symbol.
	// Because the bybit exchange does not provide a fee currency on traditional SPOT accounts, we need to query the marker
	// fee rate to get the fee currency.
	// https://bybit-exchange.github.io/docs/v5/enum#spot-fee-currency-instruction
	FeeRatePoller
	// contains filtered or unexported fields
}

func New

func New(key, secret string) (*Exchange, error)

func (*Exchange) CancelOrders added in v1.51.1

func (e *Exchange) CancelOrders(ctx context.Context, orders ...types.Order) (errs error)

func (*Exchange) GetAllFeeRates added in v1.52.0

func (e *Exchange) GetAllFeeRates(ctx context.Context) (bybitapi.FeeRates, error)

func (*Exchange) IsSupportedInterval added in v1.52.0

func (e *Exchange) IsSupportedInterval(interval types.Interval) bool

func (*Exchange) Name

func (e *Exchange) Name() types.ExchangeName

func (*Exchange) NewStream added in v1.52.0

func (e *Exchange) NewStream() types.Stream

func (*Exchange) PlatformFeeCurrency

func (e *Exchange) PlatformFeeCurrency() string

PlatformFeeCurrency returns empty string. The platform does not support "PlatformFeeCurrency" but instead charges fees using the native token.

func (*Exchange) QueryAccount added in v1.52.0

func (e *Exchange) QueryAccount(ctx context.Context) (*types.Account, error)

func (*Exchange) QueryAccountBalances added in v1.52.0

func (e *Exchange) QueryAccountBalances(ctx context.Context) (types.BalanceMap, error)

func (*Exchange) QueryClosedOrders added in v1.51.1

func (e *Exchange) QueryClosedOrders(
	ctx context.Context, symbol string, since, until time.Time, _ uint64,
) (orders []types.Order, err error)

QueryClosedOrders queries closed orders by symbol, since, until, and lastOrderID. startTime and endTime are not passed, return 7 days by default Only startTime is passed, return range between startTime and startTime+7 days Only endTime is passed, return range between endTime-7 days and endTime If both are passed, the rule is endTime - startTime <= 7 days

** since and until are inclusive. ** ** sort by creation time in descending order. **

func (*Exchange) QueryKLines added in v1.52.0

func (e *Exchange) QueryKLines(
	ctx context.Context, symbol string, interval types.Interval, options types.KLineQueryOptions,
) ([]types.KLine, error)

QueryKLines queries for historical klines (also known as candles/candlesticks). Charts are returned in groups based on the requested interval.

A k-line's start time is inclusive, but end time is not(startTime + interval - 1 millisecond). e.q. 15m interval k line can be represented as 00:00:00.000 ~ 00:14:59.999

func (*Exchange) QueryMarkets added in v1.51.1

func (e *Exchange) QueryMarkets(ctx context.Context) (types.MarketMap, error)

func (*Exchange) QueryOpenOrders added in v1.51.1

func (e *Exchange) QueryOpenOrders(ctx context.Context, symbol string) (orders []types.Order, err error)

QueryOpenOrders queries open orders by symbol.

Primarily query unfilled or partially filled orders in real-time, but also supports querying recent 500 closed status (Cancelled, Filled) orders. Please see the usage of request param openOnly. UTA2.0 can query filled, canceled, and rejected orders to the most recent 500 orders for spot, linear, inverse and option categories

The records are sorted by the createdTime from newest to oldest.

func (*Exchange) QueryOrder added in v1.52.0

func (e *Exchange) QueryOrder(ctx context.Context, q types.OrderQuery) (*types.Order, error)

func (*Exchange) QueryOrderTrades added in v1.52.0

func (e *Exchange) QueryOrderTrades(ctx context.Context, q types.OrderQuery) (trades []types.Trade, err error)

QueryOrderTrades You can query by symbol, baseCoin, orderId and orderLinkId, and if you pass multiple params, the system will process them according to this priority: orderId > orderLinkId > symbol > baseCoin.

func (*Exchange) QueryTicker added in v1.51.1

func (e *Exchange) QueryTicker(ctx context.Context, symbol string) (*types.Ticker, error)

func (*Exchange) QueryTickers added in v1.51.1

func (e *Exchange) QueryTickers(ctx context.Context, symbols ...string) (map[string]types.Ticker, error)

func (*Exchange) QueryTrades added in v1.51.1

func (e *Exchange) QueryTrades(ctx context.Context, symbol string, options *types.TradeQueryOptions) (trades []types.Trade, err error)

QueryTrades queries trades by time range. ** startTime and endTime are not passed, return 7 days by default ** ** Only startTime is passed, return range between startTime and startTime+7 days ** ** Only endTime is passed, return range between endTime-7 days and endTime ** ** If both are passed, the rule is endTime - startTime <= 7 days **

func (*Exchange) SubmitOrder added in v1.51.1

func (e *Exchange) SubmitOrder(ctx context.Context, order types.SubmitOrder) (*types.Order, error)

func (*Exchange) SupportedInterval added in v1.52.0

func (e *Exchange) SupportedInterval() map[types.Interval]int

type FeeRatePoller added in v1.61.0

type FeeRatePoller interface {
	StartFeeRatePoller(ctx context.Context)
	GetFeeRate(symbol string) (SymbolFeeDetail, bool)
	PollFeeRate(ctx context.Context) error
}

type KLine added in v1.52.0

type KLine struct {
	// The start timestamp (ms)
	StartTime types.MillisecondTimestamp `json:"start"`
	// The end timestamp (ms)
	EndTime types.MillisecondTimestamp `json:"end"`
	// Kline interval
	Interval   string           `json:"interval"`
	OpenPrice  fixedpoint.Value `json:"open"`
	ClosePrice fixedpoint.Value `json:"close"`
	HighPrice  fixedpoint.Value `json:"high"`
	LowPrice   fixedpoint.Value `json:"low"`
	// Trade volume
	Volume fixedpoint.Value `json:"volume"`
	// Turnover.  Unit of figure: quantity of quota coin
	Turnover fixedpoint.Value `json:"turnover"`
	// Weather the tick is ended or not
	Confirm bool `json:"confirm"`
	// The timestamp (ms) of the last matched order in the candle
	Timestamp types.MillisecondTimestamp `json:"timestamp"`
}

type KLineEvent added in v1.52.0

type KLineEvent struct {
	KLines []KLine

	// internal use
	// Type can be one of snapshot or delta. Copied from WebSocketTopicEvent.Type
	Type DataType
	// Symbol. Copied from WebSocketTopicEvent.Topic
	Symbol string
}

type MarketInfoProvider added in v1.52.0

type MarketInfoProvider interface {
	GetAllFeeRates(ctx context.Context) (bybitapi.FeeRates, error)
	QueryMarkets(ctx context.Context) (types.MarketMap, error)
}

MarketInfoProvider calculates trade fees since trading fees are not supported by streaming.

type MarketTradeEvent added in v1.52.0

type MarketTradeEvent struct {
	// Timestamp is the timestamp (ms) that the order is filled
	Timestamp types.MillisecondTimestamp `json:"T"`
	Symbol    string                     `json:"s"`
	// Side of taker. Buy,Sell
	Side bybitapi.Side `json:"S"`
	// Quantity is the trade size
	Quantity fixedpoint.Value `json:"v"`
	// Price is the trade price
	Price fixedpoint.Value `json:"p"`
	// L is the direction of price change. Unique field for future
	Direction string `json:"L"`
	// trade ID
	TradeId string `json:"i"`
	// Whether it is a block trade order or not
	BlockTrade bool `json:"BT"`
}

type OrderEvent added in v1.52.0

type OrderEvent struct {
	bybitapi.Order

	Category bybitapi.Category `json:"category"`
}

type Stream added in v1.52.0

type Stream struct {
	types.StandardStream
	// contains filtered or unexported fields
}

func NewStream added in v1.52.0

func NewStream(key, secret string, userDataProvider StreamDataProvider) *Stream

func (*Stream) EmitBookEvent added in v1.52.0

func (s *Stream) EmitBookEvent(e BookEvent)

func (*Stream) EmitKLineEvent added in v1.52.0

func (s *Stream) EmitKLineEvent(e KLineEvent)

func (*Stream) EmitMarketTradeEvent added in v1.52.0

func (s *Stream) EmitMarketTradeEvent(e []MarketTradeEvent)

func (*Stream) EmitOrderEvent added in v1.52.0

func (s *Stream) EmitOrderEvent(e []OrderEvent)

func (*Stream) EmitTradeEvent added in v1.52.0

func (s *Stream) EmitTradeEvent(e []TradeEvent)

func (*Stream) EmitWalletEvent added in v1.52.0

func (s *Stream) EmitWalletEvent(e []bybitapi.WalletBalances)

func (*Stream) OnBookEvent added in v1.52.0

func (s *Stream) OnBookEvent(cb func(e BookEvent))

func (*Stream) OnKLineEvent added in v1.52.0

func (s *Stream) OnKLineEvent(cb func(e KLineEvent))

func (*Stream) OnMarketTradeEvent added in v1.52.0

func (s *Stream) OnMarketTradeEvent(cb func(e []MarketTradeEvent))

func (*Stream) OnOrderEvent added in v1.52.0

func (s *Stream) OnOrderEvent(cb func(e []OrderEvent))

func (*Stream) OnTradeEvent added in v1.52.0

func (s *Stream) OnTradeEvent(cb func(e []TradeEvent))

func (*Stream) OnWalletEvent added in v1.52.0

func (s *Stream) OnWalletEvent(cb func(e []bybitapi.WalletBalances))

func (*Stream) Unsubscribe added in v1.52.0

func (s *Stream) Unsubscribe()

type StreamDataProvider added in v1.52.0

type StreamDataProvider interface {
	MarketInfoProvider
	AccountBalanceProvider
	FeeRatePoller
}

type SymbolFeeDetail added in v1.61.0

type SymbolFeeDetail struct {
	bybitapi.FeeRate

	BaseCoin  string
	QuoteCoin string
}

type TopicType added in v1.52.0

type TopicType string
const (
	TopicTypeOrderBook   TopicType = "orderbook"
	TopicTypeMarketTrade TopicType = "publicTrade"
	TopicTypeWallet      TopicType = "wallet"
	TopicTypeOrder       TopicType = "order"
	TopicTypeKLine       TopicType = "kline"
	TopicTypeFastTrade   TopicType = "execution.fast"
	TopicTypeTrade       TopicType = "execution"
)

type TradeEvent added in v1.52.0

type TradeEvent struct {
	bybitapi.Trade
	// linear and inverse order id format: 42f4f364-82e1-49d3-ad1d-cd8cf9aa308d (UUID format)
	// spot: 1468264727470772736 (only numbers)
	// we only use spot trading.
	OrderLinkId string            `json:"orderLinkId"`
	Category    bybitapi.Category `json:"category"`

	// Paradigm block trade ID
	BlockTradeId string `json:"blockTradeId"`
	// 	Closed position size
	ClosedSize fixedpoint.Value `json:"closedSize"`

	// Executed type. Normal spot is not supported
	ExecType string `json:"execType"`
	// Executed order value. Normal spot is not supported
	ExecValue fixedpoint.Value `json:"execValue"`
	// Trading fee rate. Normal spot is not supported
	FeeRate fixedpoint.Value `json:"feeRate"`
	// The remaining qty not executed. Normal spot is not supported
	LeavesQty fixedpoint.Value `json:"leavesQty"`
	// Order price. Normal spot is not supported
	OrderPrice fixedpoint.Value `json:"orderPrice"`
	// Order qty. Normal spot is not supported
	OrderQty fixedpoint.Value `json:"orderQty"`
	// Stop order type. If the order is not stop order, any type is not returned. Normal spot is not supported
	StopOrderType string `json:"stopOrderType"`
	// Whether to borrow. Unified spot only. 0: false, 1: true. . Normal spot is not supported, always 0
	IsLeverage string `json:"isLeverage"`
	// Implied volatility of mark price. Valid for option
	MarkIv string `json:"markIv"`
	// The mark price of the symbol when executing. Valid for option
	MarkPrice fixedpoint.Value `json:"markPrice"`
	// The index price of the symbol when executing. Valid for option
	IndexPrice fixedpoint.Value `json:"indexPrice"`
	// The underlying price of the symbol when executing. Valid for option
	UnderlyingPrice fixedpoint.Value `json:"underlyingPrice"`
	// Implied volatility. Valid for option
	TradeIv string `json:"tradeIv"`
}

type WebSocketOpEvent added in v1.52.0

type WebSocketOpEvent struct {
	Success bool   `json:"success"`
	RetMsg  string `json:"ret_msg"`
	ReqId   string `json:"req_id,omitempty"`

	ConnId string   `json:"conn_id"`
	Op     WsOpType `json:"op"`
	Args   []string `json:"args"`
}

func (*WebSocketOpEvent) IsAuthenticated added in v1.52.0

func (w *WebSocketOpEvent) IsAuthenticated() bool

func (*WebSocketOpEvent) IsValid added in v1.52.0

func (w *WebSocketOpEvent) IsValid() error

type WebSocketTopicEvent added in v1.52.0

type WebSocketTopicEvent struct {
	Topic string   `json:"topic"`
	Type  DataType `json:"type"`
	// The timestamp (ms) that the system generates the data
	Ts   types.MillisecondTimestamp `json:"ts"`
	Data json.RawMessage            `json:"data"`
}

type WebsocketOp added in v1.52.0

type WebsocketOp struct {
	Op   WsOpType `json:"op"`
	Args []string `json:"args"`
}

type WsEvent added in v1.52.0

type WsEvent struct {
	// "op" and "topic" are exclusive.
	*WebSocketOpEvent
	*WebSocketTopicEvent
}

func (*WsEvent) IsOp added in v1.52.0

func (w *WsEvent) IsOp() bool

func (*WsEvent) IsTopic added in v1.52.0

func (w *WsEvent) IsTopic() bool

type WsOpType added in v1.52.0

type WsOpType string
const (
	WsOpTypePing        WsOpType = "ping"
	WsOpTypePong        WsOpType = "pong"
	WsOpTypeAuth        WsOpType = "auth"
	WsOpTypeSubscribe   WsOpType = "subscribe"
	WsOpTypeUnsubscribe WsOpType = "unsubscribe"
)

Directories

Path Synopsis
v3
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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