Bybit es un importante exchange de derivados y spot de criptomonedas que ofrece contratos perpetual, futures, trading spot y options. El componente TsgcWSAPI_Bybit proporciona una integración Delphi completa con la API unificada Bybit V5 — combinando tanto suscripciones WebSocket para datos de mercado en tiempo real y eventos privados, como una interfaz REST completa para trading, gestión de posiciones y consultas de cuenta. Este artÃculo cubre cada método disponible y te muestra cómo conectarte, suscribirte y operar.
Ãndice de contenidos
- Visión general de la arquitectura
- API WebSocket — canales públicos
- API WebSocket — canales privados
- REST API — datos de mercado
- REST API — trading
- REST API — gestión de posiciones
- REST API — cuenta
- Primeros pasos — ejemplo de código
- Referencia de configuración
- Consejos y notas
Visión general de la arquitectura
La API Bybit V5 es una interfaz unificada que consolida spot, linear perpetual, inverse perpetual, inverse futures y options bajo un único conjunto de endpoints. El componente TsgcWSAPI_Bybit soporta ambos canales:
- WebSocket — datos de mercado públicos en tiempo real (order books, trades, tickers, klines, liquidations) y eventos privados de cuenta (posiciones, ejecuciones, órdenes, actualizaciones de wallet).
- REST — consultas y acciones bajo demanda mediante
oBybit.REST_API, cubriendo recuperación de datos de mercado, colocación y gestión de órdenes, configuración de posiciones e información de cuenta.
Seleccionas la categorÃa de producto mediante la propiedad BybitClient, que determina el endpoint WebSocket: bybSpot, bybLinear, bybInverse o bybPerpetual.
API WebSocket — canales públicos
Los canales públicos proporcionan datos de mercado en tiempo real sin autenticación. Cada método de suscripción tiene su correspondiente método unsubscribe.
| Subscribe | Unsubscribe | Descripción |
|---|---|---|
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. |
API WebSocket — canales privados
Los canales privados requieren autenticación mediante API key y secret. Entregan actualizaciones en tiempo real sobre la actividad de tu cuenta.
| Subscribe | Unsubscribe | Descripción |
|---|---|---|
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 — datos de mercado
Los endpoints de datos de mercado son públicos y no requieren autenticación. Accede a ellos mediante oBybit.REST_API.
| Método | Descripción |
|---|---|
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
Los endpoints de trading requieren autenticación con API key y los permisos adecuados. Estos métodos te permiten colocar, modificar y cancelar órdenes.
| Método | Descripción |
|---|---|
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 — gestión de posiciones
Los endpoints de posición te permiten consultar y configurar tus posiciones de derivados, incluyendo apalancamiento, modo de margin, risk limits y ajustes de stop-loss/take-profit.
| Método | Descripción |
|---|---|
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 — cuenta
Los endpoints de cuenta proporcionan balances de wallet, configuración de cuenta y logs de transacciones.
| Método | Descripción |
|---|---|
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.). |
Primeros pasos — ejemplo de código
El siguiente ejemplo muestra una configuración completa: conectar al endpoint Bybit linear perpetual, consultar datos de ticker mediante REST, colocar una orden limit, comprobar el wallet balance y suscribirse a actualizaciones de trade en tiempo real vÃa 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
Usa la REST API para operaciones bajo demanda como colocar órdenes, consultar balances y obtener datos históricos. Usa las suscripciones WebSocket para streams de datos continuos y de baja latencia. Ambas pueden usarse simultáneamente — las llamadas REST son independientes del estado de la conexión WebSocket.
Referencia de configuración
| Propiedad | Tipo | Descripción |
|---|---|---|
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. |
Consejos y notas
Testnet primero
Empieza siempre el desarrollo con Bybit.TestNet := True. El testnet de Bybit proporciona un entorno de simulación completo con fondos de prueba. Puedes crear una API key separada para testnet en testnet.bybit.com.
API V5 unificada
La API V5 unifica todos los tipos de producto en un único conjunto de endpoints. La propiedad BybitClient determina a qué stream WebSocket te conectas, mientras que la REST API enruta automáticamente a la categorÃa correcta según tus solicitudes.
Métodos de conveniencia para órdenes
Mientras que PlaceOrder te da control total sobre cada parámetro, los métodos de conveniencia PlaceMarketOrder y PlaceLimitOrder cubren los escenarios más comunes con menos parámetros. Usa el método completo cuando necesites opciones avanzadas como reduce-only, time-in-force o triggers condicionales.
Rate limits
Bybit aplica rate limits en endpoints REST y WebSocket. Los lÃmites REST suelen ser por endpoint (p. ej., 10 solicitudes por segundo para colocación de órdenes). Las suscripciones WebSocket tienen un lÃmite en el número de topics simultáneos. Monitoriza las cabeceras de respuesta y los códigos de error para mantenerte dentro de los lÃmites.
Nota: las conexiones WebSocket de Bybit envÃan frames ping periódicos. El componenteTsgcWSAPI_Bybit los gestiona automáticamente, manteniendo tu conexión viva sin código adicional.
