CEX.IO is um well-established cryptocurrency exchange offering em tempo real dados de mercado e trading capabilities through its WebSocket API. The TsgcWSAPI_Cex component provides um nativo Delphi interface para connecting para CEX.IO, enabling developers para inscreva-se em live ticker updates, manage order books, place e cancelar orders, e handle account positions — all over um persistent WebSocket conexão.
Sumário
- Overview
- Primeiros passos
- Public WebSocket Methods
- Private WebSocket Methods (Authenticated)
- Code Exemplo
- Events e Callbacks
- Configuração e Notes
Visão Geral
The CEX.IO WebSocket API provides two categories de functionality: public channels that stream dados de mercado sem autenticação, e private métodos that require chave de API autenticação para trading e account management. The TsgcWSAPI_Cex component wraps both categories, giving you um single componente Delphi para handle everything um partir de live price feeds para order execution.
Primeiros passos
To conectar um CEX.IO, drop um TsgcWebSocketClient e um TsgcWSAPI_Cex component em your form ou create them em code. Assign o cliente para um API component, configure your credentials, e activate o conexão.
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;
Note: Public métodos como ticker inscrições do not require API credentials. You somente precisa set ApiKey e ApiSecret if you intend para usar private (authenticated) métodos like placing orders ou checking balances.
Métodos WebSocket Públicos
Public métodos allow you para receber em tempo real dados de mercado sem autenticação. These are ideal para building dashboards, charting tools, ou price alert systems.
| Method | Description |
|---|---|
SubscribeTickers |
Inscreva-se em em tempo real ticker updates para um currency pair (e.g., BTC/USD). |
SubscribeChart |
Inscreva-se em chart/candle data para um given trading pair. |
SubscribePair |
Inscreva-se em updates para um specific trading pair. |
UnSubscribePair |
Unsubscribe um partir de um previously subscribed trading pair. |
SubscribeOrderBook |
Inscreva-se em livro de ordens snapshots e incremental updates para um pair. |
UnSubscribeOrderBook |
Unsubscribe um partir de livro de ordens updates. |
Subscribing para Tickers
The SubscribeTickers method opens um live stream de price data para um currency pair. The first parameter is o base currency e o second is o quote currency.
// Subscribe to BTC/USD ticker updates
oCex.SubscribeTickers('BTC', 'USD');
Working com o Livro de Ordens
Livro de ordens inscrições deliver both o initial snapshot e subsequent incremental updates. Use SubscribeOrderBook para iniciar receiving data e UnSubscribeOrderBook quando você 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');
Métodos WebSocket Privados (Autenticados)
Private métodos require autenticação via your CEX.IO chave de API e secret. The component handles o autenticação handshake automaticamente, but você deve chamar Authenticate before invoking any private method.
| Method | Description |
|---|---|
Authenticate |
Autenticar o WebSocket session using your chave de API e secret. |
GetTicker |
Retrieve o current ticker para um specific currency pair. |
GetBalance |
Retrieve o account balance across all currencies. |
Ping |
Send um keepalive ping para maintain o WebSocket conexão. |
GetOpenOrders |
Retrieve all atualmente abrir orders no account. |
PlaceOrder |
Place um novo buy ou sell order com specified amount e price. |
CancelReplaceOrder |
Cancelar um existing order e replace it com um novo one atomically. |
GetOrderRequest |
Retrieve details de um specific order por its identifier. |
CancelOrderRequest |
Cancelar um specific order por its identifier. |
GetArchivedOrders |
Retrieve historical (completed/cancelled) orders. |
OpenPosition |
Abrir um novo margin trading position. |
GetPosition |
Retrieve details de um specific abrir position. |
GetOpenPositions |
Retrieve all atualmente abrir margin positions. |
ClosePosition |
Fechar um existing margin trading position. |
Exemplo de Código
The exemplo um seguir demonstrates um completo workflow: connecting para CEX.IO, subscribing para um ticker, placing um buy order, e retrieving o 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 o base currency, quote currency, amount, price, e order type. The order type parameter uses o ctBuy ou 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 suporta margin trading through position management métodos. Você pode abrir, query, e fechar positions directly via o WebSocket conexão.
// Retrieve all open positions
oCex.GetOpenPositions;
// Close a specific position by ID
oCex.ClosePosition(positionId);
Eventos e Callbacks
The TsgcWSAPI_Cex component fires events when data is received do exchange. Assign handlers para process incoming messages como ticker updates, order confirmations, e balance information.
| Event | Triggered When |
|---|---|
OnCexMessage |
Any message is received do CEX.IO servidor WebSocket. |
OnCexConnect |
The WebSocket conexão para CEX.IO is established. |
OnCexDisconnect |
The WebSocket conexão is closed. |
OnCexError |
An error response is received do exchange. |
Configuração e Notes
API Credentials
Obtain your chave de API e secret do CEX.IO account settings. Store credentials securely e nunca hardcode them em production code. Consider loading them um partir de um encrypted configuração file ou environment variables.
Conexão Management
The WebSocket conexão is managed por o TsgcWebSocketClient component. Set Active := True para connect e Active := False para desconectar. The component suporta automático reconnection if configured through o cliente's reconnection properties.
Autenticação Flow
Autenticação deve ser completed before calling any private method. Call Authenticate after o conexão is established, ou handle it within o OnCexConnect event. The component generates o required HMAC signature automaticamente um partir de your chave de API e secret.
Keepalive
Use o Ping method periodically para keep o authenticated session alive. CEX.IO may desconectar idle sessions after um timeout period.
