Kucoin API Update sgcWebSockets

· Funktionen
KuCoin Spot- und Futures-API-Integration in Delphi

Die Komponenten TsgcWSAPI_Kucoin und TsgcWSAPI_Kucoin_Futures bieten umfassenden Delphi-Zugriff auf die KuCoin-Börse – von Echtzeit-WebSocket-Marktdaten und privaten Kontostreams bis hin zu einer vollständigen REST-API für Trading, Auszahlungen und Marktabfragen. Dieser Leitfaden behandelt jede Methode für Spot und Futures, samt Konfigurationsdetails und funktionierenden Code-Beispielen.

Inhaltsverzeichnis

Spot-WebSocket-API

Die Spot-WebSocket-API liefert Echtzeit-Streaming für Marktdaten und private Kontoereignisse. Öffentliche Kanäle stehen ohne Authentifizierung zur Verfügung; private Kanäle erfordern gültige API-Zugangsdaten.

Öffentliche Kanäle

Öffentliche Kanäle streamen Marktdaten an alle verbundenen Clients, ohne Authentifizierung. Jede Abonnement-Methode hat eine entsprechende Methode zum Beenden des Abonnements.

Methode Beschreibung
SubscribeSymbolTicker Abonniert Echtzeit-Ticker-Updates für ein bestimmtes Trading-Symbol.
SubscribeAllSymbolsTicker Abonniert Ticker-Updates für alle Symbole der Börse.
SubscribeSymbolSnapshot Abonniert Snapshot-Daten für ein bestimmtes Symbol, einschließlich 24-Stunden-Statistiken.
SubscribeMarketSnapshot Abonniert market-wide snapshot updates.
SubscribeLevel2MarketData Abonniert Level 2 order book changes (full depth).
SubscribeLevel2_5BestAskBid Abonniert the top 5 best ask and bid levels of the order book.
SubscribeLevel2_50BestAskBid Abonniert the top 50 best ask and bid levels of the order book.
SubscribeKlines Abonniert candlestick/kline data for a symbol at the specified interval.
SubscribeMatchExecutionData Abonniert real-time match/execution data for trades on a symbol.
SubscribeIndexPrice Abonniert index price updates for a symbol.
SubscribeMarkPrice Abonniert mark price updates for a symbol.
SubscribeOrderBookChanged Abonniert order book change events for a symbol.
Hinweis: Jede oben aufgeführte Subscribe-Methode hat ein entsprechendes UnSubscribe counterpart (e.g., UnSubscribeSymbolTicker) , um den Empfang von Updates für diesen Kanal zu beenden.

Private Channels

Private Kanäle erfordern gültige API-Zugangsdaten und liefern Echtzeit-Updates zu deinen Orders, Salden, Positionen und Margin-Aktivitäten.

Methode Beschreibung
SubscribeTradeOrders Abonniert real-time updates on your trade orders (open, filled, cancelled).
SubscribeAccountBalance Abonniert real-time account balance changes.
SubscribePositionStatus Abonniert position status updates for margin trading.
SubscribeMarginTradeOrders Abonniert margin trade order updates.
SubscribeStopOrder Abonniert stop order trigger and status updates.

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

Methode Beschreibung
GetAccounts Gibt a list of all accounts (main, trade, margin).
GetAccount Gibt details for a specific account by account ID.
GetAccountBalanceSubAccount Gibt the balance of a sub-account.
InnerTransfer Überträgt funds between your internal accounts (e.g., main to trade).

Withdrawals

Methode Beschreibung
GetWithdrawalsList Gibt a list of recent withdrawal records.
GetHistoricalWithdrawalsList Gibt historical withdrawal records beyond the recent window.
GetWithdrawalsQuotas Gibt the withdrawal quota and limits for a given currency.
ApplyWithdraw Startet eine Auszahlung an eine externe Adresse.
CancelWithdraw Storniert a pending withdrawal by its ID.

Orders

Methode Beschreibung
PlaceOrder Platziert a new spot order (market or limit, buy or sell).
PlaceMarginOrder Platziert a margin order with borrowed funds.
CancelOrderByClientOid Storniert an order using the client-assigned order ID.
GetOrder Gibt details for a specific order by its exchange-assigned ID.
GetOrderByClientOid Gibt details for a specific order by its client-assigned ID.
ListFills Gibt a list of filled orders (trade executions).
GetRecentFills Gibt the most recent fill records.

Stop Orders

Methode Beschreibung
PlaceStopOrder Platziert a stop order that triggers when the stop price is reached.
PlaceStopMarketOrder Platziert a stop-market order that executes at market price once triggered.
PlaceStopLimitOrder Platziert a stop-limit order that creates a limit order once triggered.
CancelStopOrder Storniert a stop order by its exchange-assigned ID.
CancelStopOrderByClientOid Storniert a stop order by its client-assigned ID.
CancelAllStopOrders Storniert all active stop orders, optionally filtered by symbol.
GetStopOrder Gibt details for a specific stop order by its exchange-assigned ID.
GetStopOrderByClientOid Gibt details for a specific stop order by its client-assigned ID.
ListStopOrders Gibt a list of all active stop orders.

Market Data

Methode Beschreibung
GetSymbolList Gibt a list of available trading symbols.
GetAllTickers Gibt ticker data for all trading pairs.
GetMarketList Gibt a list of available markets.
GetPartOrderBook100 Gibt the top 100 entries of the order book for a symbol.
GetFullOrderBook Gibt the full order book for a symbol (Level 3 data).
GetHistories Gibt recent trade history for a symbol.
GetKLines Gibt candlestick/kline data for a symbol at a given interval.
GetCurrencies Gibt a list of all supported currencies.
GetCurrencyDetail Gibt details for a specific currency (chain info, precision, etc.).
GetFiatPrice Gibt 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

Methode Beschreibung
SubscribeSymbolTickerV2 Abonniert V2 ticker updates for a futures contract symbol.
SubscribeSymbolTicker Abonniert ticker updates for a futures contract symbol.
SubscribeLevel2MarketData Abonniert Level 2 order book data for a futures contract.
SubscribeExecutionData Abonniert real-time match/execution data for futures trades.
SubscribeLevel2_5BestAskBid Abonniert the top 5 best ask/bid levels for a futures contract.
SubscribeLevel2_50BestAskBid Abonniert the top 50 best ask/bid levels for a futures contract.
SubscribeContractMarketData Abonniert contract-level market data (funding rate, mark price, etc.).
SubscribeSystemAnnouncements Abonniert system-wide announcements and maintenance notices.
SubscribeTransactionStatistics Abonniert aggregated transaction statistics for a futures contract.
Hinweis: Every Subscribe method listed in the futures tables has a corresponding UnSubscribe counterpart , um den Empfang von Updates für diesen Kanal zu beenden.

Private Channels

Methode Beschreibung
SubscribeTradeOrders Abonniert real-time updates on your futures trade orders.
SubscribeStopOrder Abonniert stop order trigger and status updates for futures.
SubscribeAccountBalance Abonniert real-time futures account balance changes.
SubscribePositionChange Abonniert 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.

Methode Beschreibung
AddMarginManually Manually adds margin to a futures position.
ObtainFuturesRiskLimitLevel Gibt the current risk limit level for a futures contract.
AdjustRiskLimitLevel Adjusts the risk limit level for a futures contract.
GetFundingHistory Gibt the funding rate history for a futures contract.
GetPartOrderBook100 Gibt the top 100 entries of the futures order book.
GetFullOrderBook Gibt the full futures order book.
GetLevel2PullingMessages Gibt Level 2 pulling messages for incremental order book updates.
GetInterestRateList Gibt the interest rate list used for funding calculations.
GetIndexList Gibt the index composition list for a futures contract.

Code Example

Das folgende Beispiel 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: Abonniere 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.

Eigenschaft Typ Beschreibung
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.