Integración de la API spot y de futuros de KuCoin en Delphi
Los componentes TsgcWSAPI_Kucoin y TsgcWSAPI_Kucoin_Futures ofrecen acceso completo desde Delphi al exchange KuCoin, abarcando datos de mercado WebSocket en tiempo real, streams privados de cuenta y una API REST completa para trading, retiradas y consultas de mercado. Esta guía cubre todos los métodos disponibles tanto en spot como en futuros, con detalles de configuración y ejemplos de código funcionales.
Índice
API WebSocket Spot
La API WebSocket spot proporciona streaming en tiempo real para datos de mercado y eventos privados de cuenta. Los canales públicos están disponibles sin autenticación, mientras que los canales privados requieren credenciales de API válidas.
Canales públicos
Los canales públicos hacen streaming de datos de mercado a todos los clientes conectados sin requerir autenticación. Cada método subscribe tiene su correspondiente método unsubscribe.
| Method |
Description |
SubscribeSymbolTicker |
Subscribes to real-time ticker updates for a specific trading symbol. |
SubscribeAllSymbolsTicker |
Subscribes to ticker updates for all symbols on the exchange. |
SubscribeSymbolSnapshot |
Subscribes to snapshot data for a specific symbol, including 24h statistics. |
SubscribeMarketSnapshot |
Subscribes to market-wide snapshot updates. |
SubscribeLevel2MarketData |
Subscribes to Level 2 order book changes (full depth). |
SubscribeLevel2_5BestAskBid |
Subscribes to the top 5 best ask and bid levels of the order book. |
SubscribeLevel2_50BestAskBid |
Subscribes to the top 50 best ask and bid levels of the order book. |
SubscribeKlines |
Subscribes to candlestick/kline data for a symbol at the specified interval. |
SubscribeMatchExecutionData |
Subscribes to real-time match/execution data for trades on a symbol. |
SubscribeIndexPrice |
Subscribes to index price updates for a symbol. |
SubscribeMarkPrice |
Subscribes to mark price updates for a symbol. |
SubscribeOrderBookChanged |
Subscribes to order book change events for a symbol. |
Nota: Cada método Subscribe listado arriba tiene un homólogo
UnSubscribe (p. ej.,
UnSubscribeSymbolTicker) para dejar de recibir actualizaciones de ese canal.
Canales privados
Los canales privados requieren credenciales de API válidas y proporcionan actualizaciones en tiempo real sobre tus órdenes, saldos, posiciones y actividad de margen.
| Method |
Description |
SubscribeTradeOrders |
Subscribes to real-time updates on your trade orders (open, filled, cancelled). |
SubscribeAccountBalance |
Subscribes to real-time account balance changes. |
SubscribePositionStatus |
Subscribes to position status updates for margin trading. |
SubscribeMarginTradeOrders |
Subscribes to margin trade order updates. |
SubscribeStopOrder |
Subscribes to stop order trigger and status updates. |
API REST Spot
A la API REST spot se accede mediante la propiedad REST_API de TsgcWSAPI_Kucoin. Todos los métodos devuelven strings JSON. La API cubre cuentas, retiradas, gestión de órdenes, stop orders y datos de mercado.
Cuentas
| Method |
Description |
GetAccounts |
Returns a list of all accounts (main, trade, margin). |
GetAccount |
Returns details for a specific account by account ID. |
GetAccountBalanceSubAccount |
Returns the balance of a sub-account. |
InnerTransfer |
Transfers funds between your internal accounts (e.g., main to trade). |
Retiradas
| Method |
Description |
GetWithdrawalsList |
Returns a list of recent withdrawal records. |
GetHistoricalWithdrawalsList |
Returns historical withdrawal records beyond the recent window. |
GetWithdrawalsQuotas |
Returns the withdrawal quota and limits for a given currency. |
ApplyWithdraw |
Initiates a withdrawal to an external address. |
CancelWithdraw |
Cancels a pending withdrawal by its ID. |
Órdenes
| Method |
Description |
PlaceOrder |
Places a new spot order (market or limit, buy or sell). |
PlaceMarginOrder |
Places a margin order with borrowed funds. |
CancelOrderByClientOid |
Cancels an order using the client-assigned order ID. |
GetOrder |
Returns details for a specific order by its exchange-assigned ID. |
GetOrderByClientOid |
Returns details for a specific order by its client-assigned ID. |
ListFills |
Returns a list of filled orders (trade executions). |
GetRecentFills |
Returns the most recent fill records. |
Stop Orders
| Method |
Description |
PlaceStopOrder |
Places a stop order that triggers when the stop price is reached. |
PlaceStopMarketOrder |
Places a stop-market order that executes at market price once triggered. |
PlaceStopLimitOrder |
Places a stop-limit order that creates a limit order once triggered. |
CancelStopOrder |
Cancels a stop order by its exchange-assigned ID. |
CancelStopOrderByClientOid |
Cancels a stop order by its client-assigned ID. |
CancelAllStopOrders |
Cancels all active stop orders, optionally filtered by symbol. |
GetStopOrder |
Returns details for a specific stop order by its exchange-assigned ID. |
GetStopOrderByClientOid |
Returns details for a specific stop order by its client-assigned ID. |
ListStopOrders |
Returns a list of all active stop orders. |
Datos de mercado
| Method |
Description |
GetSymbolList |
Returns a list of available trading symbols. |
GetAllTickers |
Returns ticker data for all trading pairs. |
GetMarketList |
Returns a list of available markets. |
GetPartOrderBook100 |
Returns the top 100 entries of the order book for a symbol. |
GetFullOrderBook |
Returns the full order book for a symbol (Level 3 data). |
GetHistories |
Returns recent trade history for a symbol. |
GetKLines |
Returns candlestick/kline data for a symbol at a given interval. |
GetCurrencies |
Returns a list of all supported currencies. |
GetCurrencyDetail |
Returns details for a specific currency (chain info, precision, etc.). |
GetFiatPrice |
Returns the fiat price for specified currencies (e.g., USD value of BTC). |
API WebSocket de Futuros
La API WebSocket de futuros la proporciona TsgcWSAPI_Kucoin_Futures y ofrece streaming en tiempo real de datos de contratos de futuros y eventos privados de cuenta.
Canales públicos
| Method |
Description |
SubscribeSymbolTickerV2 |
Subscribes to V2 ticker updates for a futures contract symbol. |
SubscribeSymbolTicker |
Subscribes to ticker updates for a futures contract symbol. |
SubscribeLevel2MarketData |
Subscribes to Level 2 order book data for a futures contract. |
SubscribeExecutionData |
Subscribes to real-time match/execution data for futures trades. |
SubscribeLevel2_5BestAskBid |
Subscribes to the top 5 best ask/bid levels for a futures contract. |
SubscribeLevel2_50BestAskBid |
Subscribes to the top 50 best ask/bid levels for a futures contract. |
SubscribeContractMarketData |
Subscribes to contract-level market data (funding rate, mark price, etc.). |
SubscribeSystemAnnouncements |
Subscribes to system-wide announcements and maintenance notices. |
SubscribeTransactionStatistics |
Subscribes to aggregated transaction statistics for a futures contract. |
Nota: Cada método Subscribe listado en las tablas de futuros tiene un homólogo
UnSubscribe para dejar de recibir actualizaciones de ese canal.
Canales privados
| Method |
Description |
SubscribeTradeOrders |
Subscribes to real-time updates on your futures trade orders. |
SubscribeStopOrder |
Subscribes to stop order trigger and status updates for futures. |
SubscribeAccountBalance |
Subscribes to real-time futures account balance changes. |
SubscribePositionChange |
Subscribes to position change events (open, close, liquidation). |
API REST de Futuros
A la API REST de futuros se accede mediante la propiedad REST_API de TsgcWSAPI_Kucoin_Futures. Estos métodos cubren gestión de margen, límites de riesgo, historial de funding y consultas del order book.
| Method |
Description |
AddMarginManually |
Manually adds margin to a futures position. |
ObtainFuturesRiskLimitLevel |
Returns the current risk limit level for a futures contract. |
AdjustRiskLimitLevel |
Adjusts the risk limit level for a futures contract. |
GetFundingHistory |
Returns the funding rate history for a futures contract. |
GetPartOrderBook100 |
Returns the top 100 entries of the futures order book. |
GetFullOrderBook |
Returns the full futures order book. |
GetLevel2PullingMessages |
Returns Level 2 pulling messages for incremental order book updates. |
GetInterestRateList |
Returns the interest rate list used for funding calculations. |
GetIndexList |
Returns the index composition list for a futures contract. |
Ejemplo de código
El siguiente ejemplo muestra cómo crear y configurar el componente TsgcWSAPI_Kucoin para trading spot, autenticarse con la API, recuperar tickers mediante REST, enviar una orden y suscribirse a un stream de ticker en tiempo real mediante WebSocket.
var
oClient: TsgcWebSocketClient;
oKucoin: TsgcWSAPI_Kucoin;
begin
// Create the WebSocket client
oClient := TsgcWebSocketClient.Create(nil);
oKucoin := TsgcWSAPI_Kucoin.Create(nil);
oKucoin.Client := oClient;
// Configure API credentials
oKucoin.Kucoin.ApiKey := 'your_api_key';
oKucoin.Kucoin.ApiSecret := 'your_api_secret';
oKucoin.Kucoin.Passphrase := 'your_passphrase';
// Connect to KuCoin
oClient.Active := True;
// REST: Get all tickers
ShowMessage(oKucoin.REST_API.GetAllTickers);
// REST: Place a limit order
ShowMessage(oKucoin.REST_API.PlaceOrder(myOrder));
// WebSocket: Subscribe to BTC-USDT ticker
oKucoin.SubscribeSymbolTicker('BTC-USDT');
end;
Gestión de eventos WebSocket
Asigna un manejador de eventos para procesar los mensajes entrantes. El evento proporciona el topic, subject y datos JSON para cada actualización.
procedure TForm1.OnKucoinEvent(Sender: TObject;
const aTopic, aSubject, aData: string);
begin
// aTopic identifies the channel
// aSubject provides the specific symbol or identifier
// aData contains the JSON payload
Memo1.Lines.Add(aTopic + ' [' + aSubject + ']: ' + aData);
end;
Configuración y notas
Propiedades de configuración
Tanto TsgcWSAPI_Kucoin (spot) como TsgcWSAPI_Kucoin_Futures (futuros) comparten las mismas propiedades de autenticación, accesibles mediante la propiedad Kucoin.
| Property |
Type |
Description |
Kucoin.ApiKey |
String |
Your KuCoin API key. Generate this from the KuCoin API Management page. |
Kucoin.ApiSecret |
String |
Your KuCoin API secret. Keep this value secure and never expose it in client-side code. |
Kucoin.Passphrase |
String |
The passphrase you set when creating the API key. Required for all authenticated requests. |
Notas importantes
Seguridad: Nunca dejes hardcodeados tu API key, secret o passphrase directamente en código de producción. Usa un archivo de configuración seguro o una variable de entorno para almacenar las credenciales.
- Usa
TsgcWSAPI_Kucoin para trading spot y TsgcWSAPI_Kucoin_Futures para trading de futuros. Cada componente se conecta a un endpoint diferente de KuCoin.
- La propiedad
Passphrase es obligatoria para KuCoin y se establece al crear la API key en el sitio web de KuCoin.
- Todos los métodos REST devuelven strings JSON. Usa un parser JSON (como
TJSONObject de System.JSON) para parsear las respuestas.
- Los canales WebSocket públicos no requieren autenticación y pueden usarse para datos de mercado sin establecer credenciales de API.
- Los canales WebSocket privados y todos los métodos REST que modifican el estado de la cuenta requieren credenciales de API válidas.
- KuCoin aplica límites de tasa tanto en las APIs REST como WebSocket. Consulta la documentación oficial de KuCoin para los límites actuales.
- Las conexiones WebSocket usan un sistema de autenticación basado en tokens. El componente gestiona la adquisición y renovación de tokens automáticamente.