bybit

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BaseURL = "https://api.bybit.com"

	// Bybit V5 API unifies all products into single endpoints
	// Use "category" parameter to specify: spot, linear, inverse, option
	EndpointOrderbook     = "/v5/market/orderbook"
	EndpointKline         = "/v5/market/kline"
	EndpointWalletBalance = "/v5/account/wallet-balance"

	// HTTP API settings
	HTTPRecvWindow = "5000" // 5 seconds

	// WebSocket URLs - Bybit requires separate connections per channel type
	// Public market data streams (per category)
	BaseWsURL   = "wss://stream.bybit.com/v5/public"
	WsURLSpot   = BaseWsURL + "/spot"
	WsURLLinear = BaseWsURL + "/linear"

	WsURLInverse = BaseWsURL + "/inverse"
	WsURLOption  = BaseWsURL + "/option"

	// Private WebSocket streams (authentication required)
	// Private stream: for listening to order updates, executions, wallet updates
	WsPrivateURL = "wss://stream.bybit.com/v5/private"
	// Trade stream: for sending orders via WebSocket
	WsTradeURL = "wss://stream.bybit.com/v5/trade"

	// Testnet WebSocket URLs
	WsPrivateURLTestnet = "wss://stream-testnet.bybit.com/v5/private"
	WsTradeURLTestnet   = "wss://stream-testnet.bybit.com/v5/trade"
)

Variables

CategoryToWsURL maps categories to WebSocket URLs

View Source
var ProductSlugToCategory = map[string]Category{
	"spot":    CategorySpot,
	"linear":  CategoryLinear,
	"inverse": CategoryInverse,
	"option":  CategoryOption,
}

ProductSlugToCategory maps catalog product slugs to Bybit categories

Functions

This section is empty.

Types

type BybitDataClient

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

BybitDataClient handles Bybit market data via WebSocket and HTTP It provides a unified interface for both real-time streaming data (WebSocket) and on-demand requests (HTTP REST API)

Key difference from Binance: Bybit requires separate WebSocket connections for each channel type (spot, linear, inverse, option)

func NewBybitDataClient

func NewBybitDataClient(catalog *catalog.Catalog, msgBus *msgbus.MsgBus) *BybitDataClient

NewBybitDataClient creates a new Bybit data client

func (*BybitDataClient) Connect

func (c *BybitDataClient) Connect(ctx context.Context) error

Connect establishes WebSocket connections and starts processing

func (*BybitDataClient) Disconnect

func (c *BybitDataClient) Disconnect()

Disconnect closes all WebSocket connections

func (*BybitDataClient) HasSub

func (c *BybitDataClient) HasSub() bool

HasSub returns true if there are any subscriptions configured

func (*BybitDataClient) ReqDepthSnapshot

func (c *BybitDataClient) ReqDepthSnapshot(symbolID int, limit int) error

ReqDepthSnapshot requests a depth snapshot via HTTP REST API

func (*BybitDataClient) ReqHistoricalKline

func (c *BybitDataClient) ReqHistoricalKline(symbolID int, interval string, startTimeNs, endTimeNs uint64, limit int) error

ReqHistoricalKline requests historical klines via HTTP REST API.

func (*BybitDataClient) SubscribeAggTrade

func (c *BybitDataClient) SubscribeAggTrade(symbolID int)

SubscribeAggTrade is a no-op: Bybit has no aggregate trade stream.

func (*BybitDataClient) SubscribeDepthUpdate

func (c *BybitDataClient) SubscribeDepthUpdate(symbolID int, depthLevel int, pushRateMs int)

SubscribeDepthUpdate subscribes to depth update stream for a symbol. depthLevel maps to Bybit depth levels (1, 50, 200, 500); defaults to 50. pushRateMs is ignored (Bybit determines push rate from depth level).

func (*BybitDataClient) SubscribeKline

func (c *BybitDataClient) SubscribeKline(symbolID int, interval string)

SubscribeKline subscribes to a kline stream for a symbol. interval is a Binance-style string (e.g. "1m", "1h"); mapped to Bybit tokens.

func (*BybitDataClient) SubscribeTrade

func (c *BybitDataClient) SubscribeTrade(symbolID int)

SubscribeTrade subscribes to trade tick stream for a symbol.

type BybitExecutionClient

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

BybitExecutionClient wraps BybitPrivateStreamClient and BybitOrderEntryClient to implement the ExecutionClient interface for use with ExecutionRouter. It coordinates between the two underlying clients: - BybitPrivateStreamClient: for receiving order updates, executions, and wallet updates - BybitOrderEntryClient: for sending orders via WebSocket - BybitHTTPClient: for HTTP requests (e.g., balance snapshots)

func NewBybitExecutionClient

func NewBybitExecutionClient(catalog *catalog.Catalog, msgBus *msgbus.MsgBus, accountID int, apiKeyName string, walletID int) (*BybitExecutionClient, error)

NewBybitExecutionClient creates a new Bybit execution client that wraps both the private stream and order entry clients

func (*BybitExecutionClient) CancelAllOrders

func (c *BybitExecutionClient) CancelAllOrders(symbolID int) error

CancelAllOrders cancels all open orders for a symbol via the order entry WebSocket

func (*BybitExecutionClient) CancelOrder

func (c *BybitExecutionClient) CancelOrder(symbolID int, orderID int, clientOrderID int) error

CancelOrder cancels an order by orderID via the order entry WebSocket Note: Bybit uses string orderIDs, so we convert int to string

func (*BybitExecutionClient) Connect

func (c *BybitExecutionClient) Connect(ctx context.Context) error

Connect establishes connections for both private stream and order entry

func (*BybitExecutionClient) Disconnect

func (c *BybitExecutionClient) Disconnect()

Disconnect closes connections for both private stream and order entry

func (*BybitExecutionClient) OrderEntry

OrderEntry returns the underlying order entry client for advanced usage

func (*BybitExecutionClient) PrivateStream

func (c *BybitExecutionClient) PrivateStream() *BybitPrivateStreamClient

PrivateStream returns the underlying private stream client for advanced usage

func (*BybitExecutionClient) ReqBalanceSnapshot

func (c *BybitExecutionClient) ReqBalanceSnapshot(walletType common.WalletType) error

ReqBalanceSnapshot requests the current balance snapshot via HTTP API The response will be published as a RespBalanceSnapshot event.

func (*BybitExecutionClient) SubmitOrder

func (c *BybitExecutionClient) SubmitOrder(clientOrderID int, symbolID int, side common.Side, orderType common.OrderType, timeInForce common.TimeInForce, price float64, quantity float64) error

SubmitOrder submits a new order via the order entry WebSocket SubmitOrder submits a new order with the strategy-provided clientOrderID

func (*BybitExecutionClient) SubscribeBalance

func (c *BybitExecutionClient) SubscribeBalance() error

SubscribeBalance subscribes to wallet/balance update events Bybit: Subscribes to "wallet" topic on private stream

func (*BybitExecutionClient) SubscribeFill

func (c *BybitExecutionClient) SubscribeFill() error

SubscribeFill subscribes to execution/fill events Bybit: Subscribes to "execution" topic on private stream

func (*BybitExecutionClient) SubscribeOrderUpdate

func (c *BybitExecutionClient) SubscribeOrderUpdate() error

SubscribeOrderUpdate subscribes to order status update events Bybit: Subscribes to "order" topic on private stream

type BybitHTTPClient

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

func NewBybitHTTPClient

func NewBybitHTTPClient(catalog *catalog.Catalog, msgBus *msgbus.MsgBus) BybitHTTPClient

func (*BybitHTTPClient) ReqBalanceSnapshot

func (c *BybitHTTPClient) ReqBalanceSnapshot(accountID int, walletID int, apiKeyName string, accountType string) error

ReqBalanceSnapshot fetches account wallet balance from Bybit API Endpoint: GET /v5/account/wallet-balance This is an authenticated endpoint requiring HMAC signature

Bybit response format:

{
  "retCode": 0,
  "retMsg": "OK",
  "result": {
    "list": [{
      "accountType": "UNIFIED",
      "coin": [{
        "coin": "BTC",
        "walletBalance": "0.00000001",
        "availableToWithdraw": "0.00000001",
        "locked": "0"
      }]
    }]
  }
}

func (*BybitHTTPClient) ReqDepthSnapshot

func (c *BybitHTTPClient) ReqDepthSnapshot(symbolId int, limit int) error

ReqDepthSnapshot fetches order book depth from Bybit API Bybit V5 API unifies all products - just change the "category" parameter Uses zero-allocation approach: parses JSON directly into arena buffer

func (*BybitHTTPClient) ReqHistoricalKline

func (c *BybitHTTPClient) ReqHistoricalKline(symbolID int, interval string, startTimeNs, endTimeNs uint64, limit int) error

ReqHistoricalKline fetches historical klines via GET /v5/market/kline and publishes TopicEventRespHistoricalKline. Times are nanoseconds; 0 omits the bound.

type BybitOrderEntryClient

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

BybitOrderEntryClient handles Bybit WebSocket order entry Endpoint: wss://stream.bybit.com/v5/trade Purpose: Submit, amend, cancel orders via WebSocket Methods: order.create, order.amend, order.cancel

func NewBybitOrderEntryClient

func NewBybitOrderEntryClient(catalog *catalog.Catalog, msgBus *msgbus.MsgBus, accountID int, apiKeyName string) (*BybitOrderEntryClient, error)

NewBybitOrderEntryClient creates a new Bybit order entry client

func (*BybitOrderEntryClient) CancelAllOrders

func (c *BybitOrderEntryClient) CancelAllOrders(symbolID int) error

CancelAllOrders cancels all open orders for a symbol via WebSocket

func (*BybitOrderEntryClient) CancelOrder

func (c *BybitOrderEntryClient) CancelOrder(symbolID int, orderID string, clientOrderID int) error

CancelOrder cancels an order by orderID via WebSocket

func (*BybitOrderEntryClient) CancelOrderByLinkID

func (c *BybitOrderEntryClient) CancelOrderByLinkID(symbolID int, orderLinkID string) error

CancelOrderByLinkID cancels an order by orderLinkId (clientOrderID) via WebSocket

func (*BybitOrderEntryClient) Connect

func (c *BybitOrderEntryClient) Connect(ctx context.Context) error

Connect establishes the WebSocket connection for order entry

func (*BybitOrderEntryClient) Disconnect

func (c *BybitOrderEntryClient) Disconnect()

Disconnect closes the WebSocket connection

func (*BybitOrderEntryClient) SubmitOrder

func (c *BybitOrderEntryClient) SubmitOrder(symbolID int, clientOrderID int, side common.Side, orderType common.OrderType, timeInForce common.TimeInForce, price float64, quantity float64) error

SubmitOrder submits a new order via WebSocket Bybit order.create format:

{
  "reqId": "xxx",
  "header": {"X-BAPI-TIMESTAMP": "xxx", "X-BAPI-RECV-WINDOW": "5000"},
  "op": "order.create",
  "args": [{
    "category": "spot",
    "symbol": "BTCUSDT",
    "side": "Buy",
    "orderType": "Limit",
    "qty": "0.001",
    "price": "50000",
    "timeInForce": "GTC",
    "orderLinkId": "xxx"
  }]
}

type BybitPrivateStreamClient

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

BybitPrivateStreamClient handles Bybit private stream WebSocket connection Endpoint: wss://stream.bybit.com/v5/private Purpose: Listen to private events (order updates, executions, wallet updates) Topics: order, execution, wallet, position

func NewBybitPrivateStreamClient

func NewBybitPrivateStreamClient(catalog *catalog.Catalog, msgBus *msgbus.MsgBus, accountID int, apiKeyName string, walletID int) (*BybitPrivateStreamClient, error)

NewBybitPrivateStreamClient creates a new Bybit private stream client

func (*BybitPrivateStreamClient) Connect

Connect establishes the WebSocket connection for private stream

func (*BybitPrivateStreamClient) Disconnect

func (c *BybitPrivateStreamClient) Disconnect()

Disconnect closes the WebSocket connection

func (*BybitPrivateStreamClient) Subscribe

func (c *BybitPrivateStreamClient) Subscribe(topics []string) error

Subscribe registers topics to subscribe to. If already connected, sends the subscription immediately. If not connected, stores the topics and subscribes on Connect(). This method is idempotent - subscribing to the same topic multiple times has no effect. Topics: order, execution, wallet, position

func (*BybitPrivateStreamClient) SubscribeExecution

func (c *BybitPrivateStreamClient) SubscribeExecution() error

SubscribeExecution subscribes to execution (fill) updates

func (*BybitPrivateStreamClient) SubscribeOrderUpdate

func (c *BybitPrivateStreamClient) SubscribeOrderUpdate() error

SubscribeOrderUpdate subscribes to order updates

func (*BybitPrivateStreamClient) SubscribeWallet

func (c *BybitPrivateStreamClient) SubscribeWallet() error

SubscribeWallet subscribes to wallet (balance) updates

type Category

type Category string

Category represents Bybit product types Bybit V5 API unifies all products into one endpoint with category parameter

const (
	CategorySpot    Category = "spot"
	CategoryLinear  Category = "linear"  // USDT/USDC perpetual
	CategoryInverse Category = "inverse" // Inverse perpetual
	CategoryOption  Category = "option"
)

type DepthLevel

type DepthLevel int

DepthLevel represents the orderbook depth level for subscription Bybit supports different depths with different push frequencies

const (
	// Linear & Inverse & Spot depths
	DepthLevel1    DepthLevel = 1    // 10ms push frequency
	DepthLevel50   DepthLevel = 50   // 20ms push frequency
	DepthLevel200  DepthLevel = 200  // 100ms (linear/inverse) or 200ms (spot)
	DepthLevel1000 DepthLevel = 1000 // 200ms push frequency

	// Option-specific depths
	DepthLevel25  DepthLevel = 25  // 20ms push frequency
	DepthLevel100 DepthLevel = 100 // 100ms push frequency
)

type DepthSubscriptionOptions

type DepthSubscriptionOptions struct {
	Depth DepthLevel
}

DepthSubscriptionOptions holds options for depth subscription

type HTTPError

type HTTPError struct {
	StatusCode int
	Body       string
}

HTTPError represents an HTTP error response

func (*HTTPError) Error

func (e *HTTPError) Error() string

Jump to

Keyboard shortcuts

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