Atualização da API Bitmex no sgcWebSockets

· Recursos
BitMEX WebSocket e REST API Integration em Delphi

BitMEX is um leading cryptocurrency derivatives exchange specializing em leveraged trading de futures e perpetual contracts. The TsgcWSAPI_Bitmex component provides desenvolvedores Delphi com both WebSocket e REST API access, enabling em tempo real dados de mercado streaming, order execution, position management, e comprehensive account operations um partir de um single component.

Sumário

Visão Geral

Unlike many exchange components that somente support WebSocket, o TsgcWSAPI_Bitmex component offers um dual-interface approach. The WebSocket API provides em tempo real streaming de trades, livro de ordens updates, quotes, e account data through topic-based inscrições. The REST API (accessed via o REST_API property) provides synchronous request-response métodos para placing orders, managing positions, e querying dados de mercado. This combination is ideal para building completo trading applications that need both live data feeds e precise order execution.

Primeiros passos

Create um TsgcWebSocketClient e um TsgcWSAPI_Bitmex component, link them, e configure your credentials. The WebSocket conexão is activated through o cliente, while o REST API is accessed through o REST_API property.

oClient := TsgcWebSocketClient.Create(nil);
oBitmex := TsgcWSAPI_Bitmex.Create(nil);
oBitmex.Client := oClient;
oBitmex.Bitmex.ApiKey := 'your_api_key';
oBitmex.Bitmex.ApiSecret := 'your_api_secret';
oClient.Active := True;
Note: Public WebSocket inscrições e public REST endpoints do not require API credentials. Autenticação is somente needed para private topics (execution, margin, order, position) e trading/position REST métodos.

WebSocket API

The BitMEX WebSocket API uses um topic-based inscrição model. You inscreva-se em um topic (optionally filtered por instrument) e receive um continuous stream de updates. The component provides three core WebSocket métodos.

Method Description
Subscribe Inscreva-se em um topic stream, optionally filtered por instrument symbol.
Unsubscribe Unsubscribe um partir de um previously subscribed topic stream.
Authenticate Autenticar o WebSocket session para private topic access.

Disponível Topics

Topics define o tipo de data you receive. Você pode inscreva-se em multiple topics simultaneously. The inscrição format is topic:symbol where o symbol filter is optional.

Topic Auth Required Description
trade No Live trade executions no exchange.
instrument No Instrument data incluindo funding rates e settlement info.
orderBookL2 No Full Level 2 livro de ordens com incremental updates.
quote No Top-of-book best bid e ask quotes.
execution Yes Your account's trade executions e fills.
margin Yes Account margin balance e available balance updates.
order Yes Your abrir orders e order status updates.
position Yes Your abrir positions e unrealized P&L updates.

WebSocket Inscrição Exemplos

// Subscribe to XBTUSD trades
oBitmex.Subscribe('trade:XBTUSD');
// Subscribe to the Level 2 order book
oBitmex.Subscribe('orderBookL2:XBTUSD');
// Subscribe to best bid/ask quotes
oBitmex.Subscribe('quote:XBTUSD');
// Authenticate for private topics
oBitmex.Authenticate;
// Subscribe to your order updates (requires auth)
oBitmex.Subscribe('order');
// Subscribe to your position updates (requires auth)
oBitmex.Subscribe('position');
// Unsubscribe from trades
oBitmex.Unsubscribe('trade:XBTUSD');

REST API: Dados de Mercado

The REST API is accessed through o REST_API property de o componente. Dados de mercado métodos return JSON strings that você pode parse em your application. These are synchronous calls that return immediately com o requested data.

Method Description
GetInstruments Retrieve uma lista de all instruments available no exchange.
GetInstrumentsActive Retrieve somente actively traded instruments.
GetOrderBook Retrieve o current livro de ordens snapshot para um instrument.
GetQuotes Retrieve recent quote (bid/ask) data.
GetTrades Retrieve recent public trade data.
GetExecutions Retrieve your account's raw execution data.
GetExecutionsTradeHistory Retrieve your account's trade execution history.
// Get the order book for XBTUSD
ShowMessage(oBitmex.REST_API.GetOrderBook('XBTUSD'));
// Get all active instruments
ShowMessage(oBitmex.REST_API.GetInstrumentsActive);
// Get recent trades
ShowMessage(oBitmex.REST_API.GetTrades('XBTUSD'));
// Get recent quotes
ShowMessage(oBitmex.REST_API.GetQuotes('XBTUSD'));

REST API: Negociação

Trading métodos permite que você place, amend, e cancelar orders. The REST API suporta multiple order types incluindo market, limit, parar, e parar-limit orders. All trading métodos require autenticação.

Method Description
PlaceOrder Place um novo order com full parameter control.
PlaceMarketOrder Place um market order that executes immediately no best price.
PlaceLimitOrder Place um limit order em um specified price.
PlaceStopOrder Place um parar (market) order triggered em um parar price.
PlaceStopLimitOrder Place um parar-limit order com both trigger e limit prices.
AmendOrder Modificar um existing order's price, quantity, ou other parâmetros.
CancelOrder Cancelar um specific order por its identifier.
CancelAllOrders Cancelar all abrir orders em once.
CancelAllOrdersAfter Set um dead man's switch that cancels all orders after um timeout.
GetOrders Retrieve all orders, optionally filtered por status.

Order Placement Exemplos

// Place a limit order: Buy 100 contracts of XBTUSD at $30,000
ShowMessage(oBitmex.REST_API.PlaceLimitOrder(bmsBuy, 'XBTUSD', 100, 30000));
// Place a market order: Sell 50 contracts of XBTUSD
ShowMessage(oBitmex.REST_API.PlaceMarketOrder(bmsSell, 'XBTUSD', 50));
// Place a stop order: triggers when price reaches $28,000
ShowMessage(oBitmex.REST_API.PlaceStopOrder(bmsSell, 'XBTUSD', 100, 28000));
// Place a stop-limit order: triggers at $28,000, limit price $27,500
ShowMessage(oBitmex.REST_API.PlaceStopLimitOrder(bmsSell, 'XBTUSD', 100, 28000, 27500));
// Cancel a specific order
ShowMessage(oBitmex.REST_API.CancelOrder('order-id-here'));
// Cancel all open orders
ShowMessage(oBitmex.REST_API.CancelAllOrders);
Note: The CancelAllOrdersAfter method acts como um dead man's switch. It cancels all orders caso contrário renewed within o specified timeout. This is useful como um safety mechanism para prevent runaway orders if your application loses connectivity.

REST API: Posições

Position management métodos permite que você query, fechar, e configure your abrir positions, incluindo leverage e margin settings.

Method Description
GetPosition Retrieve o current position para um instrument.
ClosePosition Fechar um abrir position por placing um closing market order.
SetPositionIsolate Toggle entre cross e isolated margin mode para um position.
SetPositionLeverage Set o leverage multiplier para um position.
SetPositionRiskLimit Set o risk limit para um position.
SetPositionTransferMargin Transfer margin para ou um partir de um isolated position.

Position Management Exemplos

// Get current position for XBTUSD
ShowMessage(oBitmex.REST_API.GetPosition('XBTUSD'));
// Set leverage to 10x
ShowMessage(oBitmex.REST_API.SetPositionLeverage('XBTUSD', 10));
// Switch to isolated margin mode
ShowMessage(oBitmex.REST_API.SetPositionIsolate('XBTUSD', True));
// Close the position at market price
ShowMessage(oBitmex.REST_API.ClosePosition('XBTUSD'));

Exemplo de Código

The exemplo um seguir demonstrates um completo workflow combining both WebSocket inscrições e REST API calls: connecting, subscribing para live trades, querying o livro de ordens, e placing um limit order.

oClient := TsgcWebSocketClient.Create(nil);
oBitmex := TsgcWSAPI_Bitmex.Create(nil);
oBitmex.Client := oClient;
oBitmex.Bitmex.ApiKey := 'your_api_key';
oBitmex.Bitmex.ApiSecret := 'your_api_secret';
oClient.Active := True;
// Subscribe to trades
oBitmex.Subscribe('trade:XBTUSD');
// REST: Get order book
ShowMessage(oBitmex.REST_API.GetOrderBook('XBTUSD'));
// REST: Place a limit order
ShowMessage(oBitmex.REST_API.PlaceLimitOrder(bmsBuy, 'XBTUSD', 100, 30000));

Configuração e Observações

API Credentials

Generate your chave de API e secret do BitMEX account settings. Você pode create keys com specific permissions (order, withdraw, etc.). For trading bots, create um key com somente o permissions you need e avoid enabling withdrawal permissions unless absolutely necessary.

Testnet Support

BitMEX provides um testnet environment em testnet.bitmex.com para development e testing. Configurar o componente para usar o testnet endpoint para test your integration com simulated funds before going live. The Bitmex property group inclui settings para selecting entre production e testnet environments.

Important: Sempre test your trading logic no BitMEX testnet before deploying para production. Testnet API keys are generated separately do testnet interface e are not interchangeable com production keys.

Order Side Enumeration

Trading métodos use o bmsBuy e bmsSell enumeration values para specify order direction. These are specific para o BitMEX component.

WebSocket vs REST Usage

Use WebSocket inscrições para em tempo real data streaming where low latency is critical (live price displays, livro de ordens visualization, execution monitoring). Use o REST API para on-demand operations like placing orders, querying positions, e fetching historical data. The two interfaces complement each other e pode ser used simultaneously.

Rate Limits

BitMEX enforces rate limits em REST API calls. The limits vary por endpoint but are typically 60 requests per minute para most trading endpoints e 30 requests per minute para order amendment e cancellation. Monitor o rate limit headers em responses para avoid being temporarily blocked. WebSocket inscrições are not subject para REST rate limits.

Instrument Symbols

BitMEX uses its own instrument symbol format. The perpetual Bitcoin contract is XBTUSD, while futures contracts include um expiry date suffix (e.g., XBTM25). Use GetInstrumentsActive para discover all atualmente tradeable instruments e their symbols.

Tip: Combine o CancelAllOrdersAfter method com um periodic timer em your application como um safety net. If your application crashes ou loses connectivity, all orders será automaticamente cancelled after o specified timeout, protecting you um partir de unexpected market movements.