Kucoin API Update sgcWebSockets

· Recursos
Integração da API KuCoin Spot e Futures em Delphi

Os componentes TsgcWSAPI_Kucoin e TsgcWSAPI_Kucoin_Futures oferecem acesso completo em Delphi à exchange KuCoin, abrangendo dados de mercado em tempo real via WebSocket, streams de conta privada e uma API REST completa para negociação, saques e consultas de mercado. Este guia cobre todos os métodos disponíveis nas versões spot e futuros, com detalhes de configuração e exemplos de código funcionais.

Índice

Spot WebSocket API

A Spot WebSocket API oferece streaming em tempo real para dados de mercado e eventos de conta privada. Os canais públicos estão disponíveis sem autenticação, enquanto os canais privados exigem credenciais de API válidas.

Canais Públicos

Os canais públicos transmitem dados de mercado para todos os clientes conectados sem exigir autenticação. Cada método de inscrição possui um método de cancelamento correspondente.

Método Descrição
SubscribeSymbolTicker Assina atualizações de ticker em tempo real para um símbolo de negociação específico.
SubscribeAllSymbolsTicker Assina atualizações de ticker para todos os símbolos da exchange.
SubscribeSymbolSnapshot Assina dados de snapshot para um símbolo específico, incluindo estatísticas de 24h.
SubscribeMarketSnapshot Assina atualizações de snapshot do mercado como um todo.
SubscribeLevel2MarketData Assina alterações no livro de ordens Level 2 (profundidade total).
SubscribeLevel2_5BestAskBid Assina os 5 melhores níveis de venda e compra do livro de ordens.
SubscribeLevel2_50BestAskBid Assina os 50 melhores níveis de venda e compra do livro de ordens.
SubscribeKlines Assina dados de candlestick/kline para um símbolo no intervalo especificado.
SubscribeMatchExecutionData Assina dados de execução de negociações em tempo real para um símbolo.
SubscribeIndexPrice Assina atualizações de preço do índice para um símbolo.
SubscribeMarkPrice Assina atualizações do preço de marcação para um símbolo.
SubscribeOrderBookChanged Assina eventos de alteração no livro de ordens de um símbolo.
Nota: Todo método Subscribe listado acima possui um método UnSubscribe correspondente (ex.: UnSubscribeSymbolTicker) para interromper o recebimento de atualizações daquele canal.

Canais Privados

Os canais privados exigem credenciais de API válidas e fornecem atualizações em tempo real sobre suas ordens, saldos, posições e atividades de margem.

Método Descrição
SubscribeTradeOrders Assina atualizações em tempo real das suas ordens de negociação (abertas, executadas, canceladas).
SubscribeAccountBalance Assina alterações de saldo da conta em tempo real.
SubscribePositionStatus Assina atualizações de status de posição para negociação com margem.
SubscribeMarginTradeOrders Assina atualizações de ordens de negociação com margem.
SubscribeStopOrder Assina atualizações de acionamento e status de ordens stop.

Spot REST API

The spot REST API is accessed via the REST_API property of TsgcWSAPI_Kucoin. All methods return JSON strings. The API covers accounts, withdrawals, order management, stop orders, and market data.

Accounts

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).

Withdrawals

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.

Orders

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.

Market Data

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).

Futures WebSocket API

The futures WebSocket API is provided by TsgcWSAPI_Kucoin_Futures and offers real-time streaming for futures contract data and private account events.

Public Channels

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.
Note: Every Subscribe method listed in the futures tables has a corresponding UnSubscribe counterpart to stop receiving updates for that channel.

Private Channels

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).

Futures REST API

The futures REST API is accessed via the REST_API property of TsgcWSAPI_Kucoin_Futures. These methods cover margin management, risk limits, funding history, and order book queries.

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.

Code Example

The following example demonstrates how to create and configure the TsgcWSAPI_Kucoin component for spot trading, authenticate with the API, retrieve tickers via REST, place an order, and subscribe to a real-time ticker stream via 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;

Handling WebSocket Events

Assign an event handler to process incoming messages. The event provides the topic, subject, and JSON data for each update.

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;

Configuration & Notes

Configuration Properties

Both TsgcWSAPI_Kucoin (spot) and TsgcWSAPI_Kucoin_Futures (futures) share the same authentication properties, accessed through the Kucoin property.

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.

Important Notes

Security: Never hard-code your API key, secret, or passphrase directly in production code. Use a secure configuration file or environment variable to store credentials.