Atualização da API Bybit no sgcWebSockets

· Recursos
Bybit V5 WebSocket e REST API Integration em Delphi

Bybit is um major cryptocurrency derivatives e spot exchange, offering perpetual contracts, futures, spot trading, e options. The TsgcWSAPI_Bybit component delivers full Delphi integration com o Bybit V5 unified API — combining both WebSocket inscrições para em tempo real dados de mercado e private events, e um comprehensive REST interface para trading, position management, e account queries. Este artigo covers every available method e shows you como se conectar, subscribe, e trade.

Sumário

Visão Geral da Arquitetura

The Bybit V5 API is um unified interface that consolidates spot, linear perpetual, inverse perpetual, inverse futures, e options under um single conjunto de endpoints. The TsgcWSAPI_Bybit component suporta both channels:

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

WebSocket API — Canais Públicos

Public channels provide em tempo real dados de mercado sem autenticação. Each inscrição method has um corresponding unsubscribe method.

Subscribe Unsubscribe Description
SubscribeOrderBook UnSubscribeOrderBook Em tempo real livro de ordens depth snapshots e incremental updates.
SubscribeTrade UnSubscribeTrade Live trade executions como they happen no exchange.
SubscribeTicker UnSubscribeTicker 24-hour rolling window ticker statistics (price, volume, change).
SubscribeKLine UnSubscribeKLine Em tempo real candlestick/kline updates para um specified interval.
SubscribeLiquidation UnSubscribeLiquidation Liquidation events across o 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 — Canais Privados

Private channels require autenticação via chave de API e secret. They deliver em tempo real updates about your account activity.

Subscribe Unsubscribe Description
SubscribePosition UnSubscribePosition Em tempo real position updates (size, entry price, PnL, leverage).
SubscribeExecution UnSubscribeExecution Trade execution confirmations como your orders are filled.
SubscribeOrder UnSubscribeOrder Order status changes (new, partially filled, filled, cancelled).
SubscribeWallet UnSubscribeWallet Carteira balance changes across all coins.
SubscribeGreek UnSubscribeGreek Options Greeks updates (delta, gamma, theta, vega).
SubscribeDcp UnSubscribeDcp Disconnection protection events para monitoring conexão health.

REST API — Dados de Mercado

Dados de mercado endpoints are public e do not require autenticação. Access them through oBybit.REST_API.

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

REST API — Negociação

Trading endpoints require chave de API autenticação com appropriate permissions. These métodos let you place, modificar, e cancelar orders.

Method Description
PlaceOrder Places um novo order com full parameter control (type, side, price, quantity, time-in-force, etc.).
PlaceMarketOrder Convenience method that places um market order (executes immediately em best available price).
PlaceLimitOrder Convenience method that places um limit order em um specified price.
AmendOrder Modifies um existing abrir order (price, quantity, ou other parâmetros).
CancelOrder Cancels um specific abrir order por order ID.
GetOpenOrders Retorna all atualmente abrir (unfilled) orders.
CancelAllOrders Cancels all abrir orders, optionally filtered por symbol ou category.
GetOrderHistory Retorna historical orders (filled, cancelled, rejected) within um time range.

REST API — Gerenciamento de Posições

Position endpoints permite que você query e configure your derivative positions, incluindo leverage, margin mode, risk limits, e parar-loss/take-profit settings.

Method Description
GetPositionInfo Retorna current position details (size, entry price, unrealized PnL, margin).
SetLeverage Sets o leverage para um given symbol.
SwitchCrossIsolatedMargin Switches entre cross margin e isolated margin mode.
SetTPSLMode Configures take-profit/parar-loss mode (full position ou partial).
SwitchPositionMode Switches entre one-way mode e hedge mode.
SetRiskLimit Sets o risk limit tier para um symbol, which affects maximum leverage.
SetTradingStop Sets trailing parar, take-profit, ou parar-loss em um existing position.
SetAutoAddMargin Enables ou disables auto-adicionar margin para isolated margin positions.
AddOrReduceMargin Manualmente adds ou removes margin um partir de um isolated margin position.
GetExecution Retorna execution/fill records para your trades.
GetClosedPNL Retorna closed profit e loss records.
ConfirmNewRiskLimit Confirms um risk limit change when additional margin is required.

REST API — Conta

Account endpoints provide carteira balances, account configuração, e transaction logs.

Method Description
GetWalletBalance Retorna carteira balances across all coins ou para um specific account type.
GetAccountInfo Retorna unified account information (margin mode, account status, etc.).
GetTransactionLog Retorna transaction history (deposits, withdrawals, trades, funding fees, etc.).

Primeiros passos — Exemplo de Código

The exemplo um seguir demonstrates um completo setup: connecting para o Bybit linear perpetual endpoint, querying ticker data via REST, placing um limit order, checking um carteira balance, e subscribing para em tempo real 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 o REST API para on-demand operations como placing orders, querying balances, e fetching historical data. Use WebSocket inscrições para continuous, low-latency data streams. The two pode ser used simultaneously — REST calls are independent do WebSocket conexão state.

Referência de Configuração

Property Type Description
Bybit.ApiKey String Your Bybit chave de API para authenticated requests.
Bybit.ApiSecret String Your Bybit API secret para request signing.
Bybit.TestNet Boolean Set para True para conectar um o Bybit testnet environment; False para mainnet.
Bybit.SignatureExpires Integer Expiration time em seconds para o HMAC signature (default is typically sufficient).
BybitClient Enum Product category: bybSpot, bybLinear, bybInverse, ou bybPerpetual.

Dicas e Observações

Testnet Primeiro

Sempre iniciar development com Bybit.TestNet := True. The Bybit testnet provides um full simulation environment com test funds. Você pode create um separate testnet chave de API em testnet.bybit.com.

Unified V5 API

The V5 API unifies all product types under one conjunto de endpoints. The BybitClient property determines which WebSocket stream you conectar a, while o REST API automaticamente routes para o correct category baseado em your requests.

Order Convenience Methods

While PlaceOrder gives you full control over every parameter, o PlaceMarketOrder e PlaceLimitOrder convenience métodos cover o most common scenarios com fewer parâmetros. Use o full method quando você need advanced options like reduce-somente, time-in-force, ou conditional triggers.

Rate Limits

Bybit enforces rate limits em both REST e WebSocket endpoints. REST limits are typically per-endpoint (e.g., 10 requests per second para order placement). WebSocket inscrições have um limit no number de simultaneous topics. Monitor response headers e error codes para stay within bounds.

Note: Bybit WebSocket conexões send periodic ping frames. The TsgcWSAPI_Bybit component handles these automaticamente, keeping your conexão alive sem additional code.