Bitmex API Update sgcWebSockets

BitMEX WebSocket and REST API Integration in Delphi

BitMEX is a leading cryptocurrency derivatives exchange specializing in leveraged trading of futures and perpetual contracts. The TsgcWSAPI_Bitmex component provides Delphi developers with both WebSocket and REST API access, enabling real-time market data streaming, order execution, position management, and comprehensive account operations from a single component.

Overview

Unlike many exchange components that only support WebSocket, the TsgcWSAPI_Bitmex component offers a dual-interface approach. The WebSocket API provides real-time streaming of trades, order book updates, quotes, and account data through topic-based subscriptions. The REST API (accessed via the REST_API property) provides synchronous request-response methods for placing orders, managing positions, and querying market data. This combination is ideal for building complete trading applications that need both live data feeds and precise order execution.

Getting Started

Create a TsgcWebSocketClient and a TsgcWSAPI_Bitmex component, link them, and configure your credentials. The WebSocket connection is activated through the client, while the REST API is accessed through the 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 subscriptions and public REST endpoints do not require API credentials. Authentication is only needed for private topics (execution, margin, order, position) and trading/position REST methods.

WebSocket API

The BitMEX WebSocket API uses a topic-based subscription model. You subscribe to a topic (optionally filtered by instrument) and receive a continuous stream of updates. The component provides three core WebSocket methods.

Method Description
Subscribe Subscribe to a topic stream, optionally filtered by instrument symbol.
Unsubscribe Unsubscribe from a previously subscribed topic stream.
Authenticate Authenticate the WebSocket session for private topic access.

Available Topics

Topics define the type of data you receive. You can subscribe to multiple topics simultaneously. The subscription format is topic:symbol where the symbol filter is optional.

Topic Auth Required Description
trade No Live trade executions on the exchange.
instrument No Instrument data including funding rates and settlement info.
orderBookL2 No Full Level 2 order book with incremental updates.
quote No Top-of-book best bid and ask quotes.
execution Yes Your account's trade executions and fills.
margin Yes Account margin balance and available balance updates.
order Yes Your open orders and order status updates.
position Yes Your open positions and unrealized P&L updates.

WebSocket Subscription Examples

// 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: Market Data

The REST API is accessed through the REST_API property of the component. Market data methods return JSON strings that you can parse in your application. These are synchronous calls that return immediately with the requested data.

Method Description
GetInstruments Retrieve a list of all instruments available on the exchange.
GetInstrumentsActive Retrieve only actively traded instruments.
GetOrderBook Retrieve the current order book snapshot for an 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: Trading

Trading methods allow you to place, amend, and cancel orders. The REST API supports multiple order types including market, limit, stop, and stop-limit orders. All trading methods require authentication.

Method Description
PlaceOrder Place a new order with full parameter control.
PlaceMarketOrder Place a market order that executes immediately at the best price.
PlaceLimitOrder Place a limit order at a specified price.
PlaceStopOrder Place a stop (market) order triggered at a stop price.
PlaceStopLimitOrder Place a stop-limit order with both trigger and limit prices.
AmendOrder Modify an existing order's price, quantity, or other parameters.
CancelOrder Cancel a specific order by its identifier.
CancelAllOrders Cancel all open orders at once.
CancelAllOrdersAfter Set a dead man's switch that cancels all orders after a timeout.
GetOrders Retrieve all orders, optionally filtered by status.

Order Placement Examples

// 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 as a dead man's switch. It cancels all orders if not renewed within the specified timeout. This is useful as a safety mechanism to prevent runaway orders if your application loses connectivity.

REST API: Positions

Position management methods allow you to query, close, and configure your open positions, including leverage and margin settings.

Method Description
GetPosition Retrieve the current position for an instrument.
ClosePosition Close an open position by placing a closing market order.
SetPositionIsolate Toggle between cross and isolated margin mode for a position.
SetPositionLeverage Set the leverage multiplier for a position.
SetPositionRiskLimit Set the risk limit for a position.
SetPositionTransferMargin Transfer margin to or from an isolated position.

Position Management Examples

// 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'));

Code Example

The following example demonstrates a complete workflow combining both WebSocket subscriptions and REST API calls: connecting, subscribing to live trades, querying the order book, and placing a 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));

Configuration and Notes

API Credentials

Generate your API key and secret from the BitMEX account settings. You can create keys with specific permissions (order, withdraw, etc.). For trading bots, create a key with only the permissions you need and avoid enabling withdrawal permissions unless absolutely necessary.

Testnet Support

BitMEX provides a testnet environment at testnet.bitmex.com for development and testing. Configure the component to use the testnet endpoint to test your integration with simulated funds before going live. The Bitmex property group includes settings for selecting between production and testnet environments.

Important: Always test your trading logic on the BitMEX testnet before deploying to production. Testnet API keys are generated separately from the testnet interface and are not interchangeable with production keys.

Order Side Enumeration

Trading methods use the bmsBuy and bmsSell enumeration values to specify order direction. These are specific to the BitMEX component.

WebSocket vs REST Usage

Use WebSocket subscriptions for real-time data streaming where low latency is critical (live price displays, order book visualization, execution monitoring). Use the REST API for on-demand operations like placing orders, querying positions, and fetching historical data. The two interfaces complement each other and can be used simultaneously.

Rate Limits

BitMEX enforces rate limits on REST API calls. The limits vary by endpoint but are typically 60 requests per minute for most trading endpoints and 30 requests per minute for order amendment and cancellation. Monitor the rate limit headers in responses to avoid being temporarily blocked. WebSocket subscriptions are not subject to REST rate limits.

Instrument Symbols

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

Tip: Combine the CancelAllOrdersAfter method with a periodic timer in your application as a safety net. If your application crashes or loses connectivity, all orders will be automatically cancelled after the specified timeout, protecting you from unexpected market movements.
×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

AMQP 0.9.1 Delphi Client Update

Related Posts