CEX.IO WebSocket API Integration in Delphi
CEX.IO is a well-established cryptocurrency exchange offering real-time market data and trading capabilities through its WebSocket API. The TsgcWSAPI_Cex component provides a native Delphi interface for connecting to CEX.IO, enabling developers to subscribe to live ticker updates, manage order books, place and cancel orders, and handle account positions — all over a persistent WebSocket connection.
Table of Contents
Overview
The CEX.IO WebSocket API provides two categories of functionality: public channels that stream market data without authentication, and private methods that require API key authentication for trading and account management. The TsgcWSAPI_Cex component wraps both categories, giving you a single Delphi component to handle everything from live price feeds to order execution.
Getting Started
To connect to CEX.IO, drop a TsgcWebSocketClient and a TsgcWSAPI_Cex component on your form or create them in code. Assign the client to the API component, configure your credentials, and activate the connection.
oClient := TsgcWebSocketClient.Create(nil);
oCex := TsgcWSAPI_Cex.Create(nil);
oCex.Client := oClient;
oCex.Cex.ApiKey := 'your_api_key';
oCex.Cex.ApiSecret := 'your_api_secret';
oClient.Active := True;
ApiKey and ApiSecret if you intend to use private (authenticated) methods like placing orders or checking balances.
Public WebSocket Methods
Public methods allow you to receive real-time market data without authentication. These are ideal for building dashboards, charting tools, or price alert systems.
| Method | Description |
|---|---|
SubscribeTickers |
Subscribe to real-time ticker updates for a currency pair (e.g., BTC/USD). |
SubscribeChart |
Subscribe to chart/candle data for a given trading pair. |
SubscribePair |
Subscribe to updates for a specific trading pair. |
UnSubscribePair |
Unsubscribe from a previously subscribed trading pair. |
SubscribeOrderBook |
Subscribe to order book snapshots and incremental updates for a pair. |
UnSubscribeOrderBook |
Unsubscribe from order book updates. |
Subscribing to Tickers
The SubscribeTickers method opens a live stream of price data for a currency pair. The first parameter is the base currency and the second is the quote currency.
// Subscribe to BTC/USD ticker updates
oCex.SubscribeTickers('BTC', 'USD');
Working with the Order Book
Order book subscriptions deliver both the initial snapshot and subsequent incremental updates. Use SubscribeOrderBook to start receiving data and UnSubscribeOrderBook when you no longer need it.
// Subscribe to the BTC/USD order book
oCex.SubscribeOrderBook('BTC', 'USD');
// Later, unsubscribe when no longer needed
oCex.UnSubscribeOrderBook('BTC', 'USD');
Private WebSocket Methods (Authenticated)
Private methods require authentication via your CEX.IO API key and secret. The component handles the authentication handshake automatically, but you must call Authenticate before invoking any private method.
| Method | Description |
|---|---|
Authenticate |
Authenticate the WebSocket session using your API key and secret. |
GetTicker |
Retrieve the current ticker for a specific currency pair. |
GetBalance |
Retrieve the account balance across all currencies. |
Ping |
Send a keepalive ping to maintain the WebSocket connection. |
GetOpenOrders |
Retrieve all currently open orders on the account. |
PlaceOrder |
Place a new buy or sell order with specified amount and price. |
CancelReplaceOrder |
Cancel an existing order and replace it with a new one atomically. |
GetOrderRequest |
Retrieve details of a specific order by its identifier. |
CancelOrderRequest |
Cancel a specific order by its identifier. |
GetArchivedOrders |
Retrieve historical (completed/cancelled) orders. |
OpenPosition |
Open a new margin trading position. |
GetPosition |
Retrieve details of a specific open position. |
GetOpenPositions |
Retrieve all currently open margin positions. |
ClosePosition |
Close an existing margin trading position. |
Code Example
The following example demonstrates a complete workflow: connecting to CEX.IO, subscribing to a ticker, placing a buy order, and retrieving the account balance.
oClient := TsgcWebSocketClient.Create(nil);
oCex := TsgcWSAPI_Cex.Create(nil);
oCex.Client := oClient;
oCex.Cex.ApiKey := 'your_api_key';
oCex.Cex.ApiSecret := 'your_api_secret';
oClient.Active := True;
// Subscribe to ticker
oCex.SubscribeTickers('BTC', 'USD');
// Place an order
oCex.PlaceOrder('BTC', 'USD', 0.01, 30000, ctBuy);
// Get balance
oCex.GetBalance;
Placing Orders
The PlaceOrder method accepts the base currency, quote currency, amount, price, and order type. The order type parameter uses the ctBuy or ctSell enumeration values.
// Place a buy order: 0.01 BTC at $30,000
oCex.PlaceOrder('BTC', 'USD', 0.01, 30000, ctBuy);
// Place a sell order: 0.05 ETH at $2,000
oCex.PlaceOrder('ETH', 'USD', 0.05, 2000, ctSell);
Managing Positions
CEX.IO supports margin trading through position management methods. You can open, query, and close positions directly via the WebSocket connection.
// Retrieve all open positions
oCex.GetOpenPositions;
// Close a specific position by ID
oCex.ClosePosition(positionId);
Events and Callbacks
The TsgcWSAPI_Cex component fires events when data is received from the exchange. Assign handlers to process incoming messages such as ticker updates, order confirmations, and balance information.
| Event | Triggered When |
|---|---|
OnCexMessage |
Any message is received from the CEX.IO WebSocket server. |
OnCexConnect |
The WebSocket connection to CEX.IO is established. |
OnCexDisconnect |
The WebSocket connection is closed. |
OnCexError |
An error response is received from the exchange. |
Configuration and Notes
API Credentials
Obtain your API key and secret from the CEX.IO account settings. Store credentials securely and never hardcode them in production code. Consider loading them from an encrypted configuration file or environment variables.
Connection Management
The WebSocket connection is managed by the TsgcWebSocketClient component. Set Active := True to connect and Active := False to disconnect. The component supports automatic reconnection if configured through the client's reconnection properties.
Authentication Flow
Authentication must be completed before calling any private method. Call Authenticate after the connection is established, or handle it within the OnCexConnect event. The component generates the required HMAC signature automatically from your API key and secret.
Keepalive
Use the Ping method periodically to keep the authenticated session alive. CEX.IO may disconnect idle sessions after a timeout period.