By Admin on Thursday, 26 February 2026
Category: All

Bybit Update API sgcWebSockets

Bybit V5 WebSocket and REST API Integration in Delphi

Bybit is a major cryptocurrency derivatives and spot exchange, offering perpetual contracts, futures, spot trading, and options. The TsgcWSAPI_Bybit component delivers full Delphi integration with the Bybit V5 unified API — combining both WebSocket subscriptions for real-time market data and private events, and a comprehensive REST interface for trading, position management, and account queries. This article covers every available method and shows you how to connect, subscribe, and trade.

Table of Contents

Architecture Overview

The Bybit V5 API is a unified interface that consolidates spot, linear perpetual, inverse perpetual, inverse futures, and options under a single set of endpoints. The TsgcWSAPI_Bybit component supports both channels:

You select the product category through the BybitClient property, which determines the WebSocket endpoint: bybSpot, bybLinear, bybInverse, or bybPerpetual.

WebSocket API — Public Channels

Public channels provide real-time market data without authentication. Each subscription method has a corresponding unsubscribe method.

Subscribe Unsubscribe Description
SubscribeOrderBook UnSubscribeOrderBook Real-time order book depth snapshots and incremental updates.
SubscribeTrade UnSubscribeTrade Live trade executions as they happen on the exchange.
SubscribeTicker UnSubscribeTicker 24-hour rolling window ticker statistics (price, volume, change).
SubscribeKLine UnSubscribeKLine Real-time candlestick/kline updates for a specified interval.
SubscribeLiquidation UnSubscribeLiquidation Liquidation events across the exchange.
SubscribeLT_KLine UnSubscribeLT_KLine Leveraged token kline/candlestick updates.
SubscribeLT_Ticker UnSubscribeLT_Ticker Leveraged token ticker data.
SubscribeLT_Nav UnSubscribeLT_Nav Leveraged token net asset value updates.

WebSocket API — Private Channels

Private channels require authentication via API key and secret. They deliver real-time updates about your account activity.

Subscribe Unsubscribe Description
SubscribePosition UnSubscribePosition Real-time position updates (size, entry price, PnL, leverage).
SubscribeExecution UnSubscribeExecution Trade execution confirmations as your orders are filled.
SubscribeOrder UnSubscribeOrder Order status changes (new, partially filled, filled, cancelled).
SubscribeWallet UnSubscribeWallet Wallet balance changes across all coins.
SubscribeGreek UnSubscribeGreek Options Greeks updates (delta, gamma, theta, vega).
SubscribeDcp UnSubscribeDcp Disconnection protection events for monitoring connection health.

REST API — Market Data

Market data endpoints are public and do not require authentication. Access them through oBybit.REST_API.

Method Description
GetServerTime Returns the Bybit server timestamp.
GetKLine Returns historical kline/candlestick data for a symbol and interval.
GetMarkPriceKLine Returns mark price kline data (used for PnL and liquidation calculations).
GetIndexPriceKLine Returns index price kline data.
GetPremiumIndexPriceKLine Returns premium index price kline data for perpetual contracts.
GetInstrumentsInfo Returns instrument specifications (tick size, lot size, leverage limits, etc.).
GetOrderBook Returns the current order book snapshot at a given depth.
GetTickers Returns the latest ticker information for one or all symbols.
GetFundingRateHistory Returns historical funding rate records for perpetual contracts.
GetPublicRecentTradingHistory Returns the most recent public trades for a symbol.
GetOpenInterest Returns open interest data for derivatives contracts.
GetHistoricalVolatility Returns historical volatility for options.
GetInsurance Returns the insurance fund balance history.
GetRiskLimit Returns risk limit tiers for a given symbol.
GetDeliveryPrice Returns delivery price for expired futures and options.
GetLongShortRatio Returns the long/short ratio for a given symbol and period.

REST API — Trading

Trading endpoints require API key authentication with appropriate permissions. These methods let you place, modify, and cancel orders.

Method Description
PlaceOrder Places a new order with full parameter control (type, side, price, quantity, time-in-force, etc.).
PlaceMarketOrder Convenience method that places a market order (executes immediately at best available price).
PlaceLimitOrder Convenience method that places a limit order at a specified price.
AmendOrder Modifies an existing open order (price, quantity, or other parameters).
CancelOrder Cancels a specific open order by order ID.
GetOpenOrders Returns all currently open (unfilled) orders.
CancelAllOrders Cancels all open orders, optionally filtered by symbol or category.
GetOrderHistory Returns historical orders (filled, cancelled, rejected) within a time range.

REST API — Position Management

Position endpoints allow you to query and configure your derivative positions, including leverage, margin mode, risk limits, and stop-loss/take-profit settings.

Method Description
GetPositionInfo Returns current position details (size, entry price, unrealized PnL, margin).
SetLeverage Sets the leverage for a given symbol.
SwitchCrossIsolatedMargin Switches between cross margin and isolated margin mode.
SetTPSLMode Configures take-profit/stop-loss mode (full position or partial).
SwitchPositionMode Switches between one-way mode and hedge mode.
SetRiskLimit Sets the risk limit tier for a symbol, which affects maximum leverage.
SetTradingStop Sets trailing stop, take-profit, or stop-loss on an existing position.
SetAutoAddMargin Enables or disables auto-add margin for isolated margin positions.
AddOrReduceMargin Manually adds or removes margin from an isolated margin position.
GetExecution Returns execution/fill records for your trades.
GetClosedPNL Returns closed profit and loss records.
ConfirmNewRiskLimit Confirms a risk limit change when additional margin is required.

REST API — Account

Account endpoints provide wallet balances, account configuration, and transaction logs.

Method Description
GetWalletBalance Returns wallet balances across all coins or for a specific account type.
GetAccountInfo Returns unified account information (margin mode, account status, etc.).
GetTransactionLog Returns transaction history (deposits, withdrawals, trades, funding fees, etc.).

Getting Started — Code Example

The following example demonstrates a complete setup: connecting to the Bybit linear perpetual endpoint, querying ticker data via REST, placing a limit order, checking the wallet balance, and subscribing to real-time trade updates via WebSocket.

var
  oClient: TsgcWebSocketClient;
  oBybit: TsgcWSAPI_Bybit;
begin
  // Create the WebSocket client
  oClient := TsgcWebSocketClient.Create(nil);
  // Create the Bybit API component
  oBybit := TsgcWSAPI_Bybit.Create(nil);
  oBybit.Client := oClient;

  // Configure API credentials
  oBybit.Bybit.ApiKey := 'your_api_key';
  oBybit.Bybit.ApiSecret := 'your_api_secret';

  // Select the product category
  oBybit.BybitClient := bybLinear;

  // Connect to the WebSocket
  oClient.Active := True;

  // REST: Get ticker information for BTCUSDT
  ShowMessage(oBybit.REST_API.GetTickers('BTCUSDT'));

  // REST: Place a limit buy order
  ShowMessage(oBybit.REST_API.PlaceLimitOrder(bbsBuy, 'BTCUSDT', 0.001, 30000));

  // REST: Get wallet balance
  ShowMessage(oBybit.REST_API.GetWalletBalance);

  // WebSocket: Subscribe to real-time trades for BTCUSDT
  oBybit.SubscribeTrade('BTCUSDT');
end;

REST vs. WebSocket

Use the REST API for on-demand operations such as placing orders, querying balances, and fetching historical data. Use WebSocket subscriptions for continuous, low-latency data streams. The two can be used simultaneously — REST calls are independent of the WebSocket connection state.

Configuration Reference

Property Type Description
Bybit.ApiKey String Your Bybit API key for authenticated requests.
Bybit.ApiSecret String Your Bybit API secret for request signing.
Bybit.TestNet Boolean Set to True to connect to the Bybit testnet environment; False for mainnet.
Bybit.SignatureExpires Integer Expiration time in seconds for the HMAC signature (default is typically sufficient).
BybitClient Enum Product category: bybSpot, bybLinear, bybInverse, or bybPerpetual.

Tips and Notes

Testnet First

Always start development with Bybit.TestNet := True. The Bybit testnet provides a full simulation environment with test funds. You can create a separate testnet API key at testnet.bybit.com.

Unified V5 API

The V5 API unifies all product types under one set of endpoints. The BybitClient property determines which WebSocket stream you connect to, while the REST API automatically routes to the correct category based on your requests.

Order Convenience Methods

While PlaceOrder gives you full control over every parameter, the PlaceMarketOrder and PlaceLimitOrder convenience methods cover the most common scenarios with fewer parameters. Use the full method when you need advanced options like reduce-only, time-in-force, or conditional triggers.

Rate Limits

Bybit enforces rate limits on both REST and WebSocket endpoints. REST limits are typically per-endpoint (e.g., 10 requests per second for order placement). WebSocket subscriptions have a limit on the number of simultaneous topics. Monitor response headers and error codes to stay within bounds.

Note: Bybit WebSocket connections send periodic ping frames. The TsgcWSAPI_Bybit component handles these automatically, keeping your connection alive without additional code.

Related Posts