Kraken API Update sgcWebSockets

Kraken Spot and Futures API Integration in Delphi

Kraken is one of the longest-running and most trusted cryptocurrency exchanges, offering both spot and futures markets. The TsgcWSAPI_Kraken and TsgcWSAPI_Kraken_Futures components for Delphi provide full access to Kraken's WebSocket and REST APIs, enabling real-time market data streaming, account management, order placement, and futures trading from a single codebase.

Overview

Kraken's API is split into two distinct platforms, each with its own component:

Component Market Description
TsgcWSAPI_Kraken Spot Trade cryptocurrencies on Kraken's spot exchange with WebSocket and REST support
TsgcWSAPI_Kraken_Futures Futures Trade perpetual and fixed-maturity futures contracts with leveraged positions

Both components provide a dual-channel approach: WebSocket connections for low-latency real-time data streaming, and REST endpoints for request/response operations such as querying balances, placing orders, and retrieving historical data.

Configuration

Both the Spot and Futures components require API credentials for private (authenticated) operations. Public endpoints like market data do not require authentication.

Property Type Description
Kraken.ApiKey String Your Kraken API key, generated from the Kraken account settings page
Kraken.ApiSecret String Your Kraken API secret, used for signing private requests
Note: Generate your API keys at kraken.com > Security > API. Assign only the permissions your application requires. For read-only dashboards, disable trading and withdrawal permissions entirely.

Spot WebSocket API

The Spot WebSocket API provides real-time streaming for market data and private account events. Methods are divided into public channels (no authentication required) and private channels (require a valid WebSocket token).

Public Channels

Method Description
SubscribeTicker / UnSubscribeTicker Real-time ticker information including best bid/ask, 24h volume, and price statistics
SubscribeOHLC / UnSubscribeOHLC Real-time OHLC (candlestick) data at configurable intervals
SubscribeTrade / UnSubscribeTrade Real-time trade execution feed showing every trade on the exchange
SubscribeBook / UnSubscribeBook Order book snapshots and incremental updates at configurable depth
SubscribeSpread / UnSubscribeSpread Real-time best bid/ask spread updates
SubscribeAll / UnSubscribeAll Subscribe to or unsubscribe from all public channels for a given pair at once

Private Channels

Method Description
SubscribeOwnTrades / UnSubscribeOwnTrades Real-time feed of your own executed trades
SubscribeOpenOrders / UnSubscribeOpenOrders Real-time updates on your open orders (new, modified, cancelled, filled)
AddOrder Place a new order via WebSocket (lower latency than REST)
CancelOrder Cancel an existing order via WebSocket
// Subscribe to public ticker data for BTC/USD
oKraken.SubscribeTicker('XBT/USD');

// Subscribe to the order book with 10-level depth
oKraken.SubscribeBook('XBT/USD');

// Subscribe to real-time trades
oKraken.SubscribeTrade('ETH/USD');

// Subscribe to private channels (requires API key)
oKraken.SubscribeOwnTrades;
oKraken.SubscribeOpenOrders;

Spot REST API

The Spot REST API is accessed through the REST_API property of the TsgcWSAPI_Kraken component. It provides a comprehensive set of endpoints for market data queries, account management, trading, and fund operations.

Public REST Methods

Method Description
GetServerTime Returns the server's current time (useful for clock synchronization)
GetAssets Lists all available assets and their properties (decimals, display name)
GetAssetPairs Lists all tradeable asset pairs with fee structure and margin info
GetTicker Returns ticker data for one or more pairs (bid, ask, last, volume, VWAP)
GetOHLC Returns OHLC candle data for a given pair and interval
GetOrderBook Returns the current order book for a given pair at specified depth
GetTrades Returns recent trades for a given pair
GetSpread Returns recent spread data for a given pair

Private REST Methods - Account and Trading

Method Description
GetAccountBalance Returns balances for all assets in your account
GetTradeBalance Returns trade balance info (equity, margin, free margin, P&L)
GetOpenOrders Returns all currently open orders
GetClosedOrders Returns recently closed orders
QueryOrders Query specific orders by transaction ID
GetTradesHistory Returns your trade history
QueryTrades Query specific trades by trade ID
GetLedgers Returns ledger entries (deposits, withdrawals, trades, fees)
QueryLedgers Query specific ledger entries by ID
GetTradeVolume Returns your 30-day trading volume and fee tier
AddOrder Place a new order via REST
CancelOrder Cancel an existing order via REST
GetWebSocketsToken Generates a token required for private WebSocket subscriptions

Private REST Methods - Export and Reporting

Method Description
AddExport Request a data export (trades or ledger entries)
ExportStatus Check the status of a pending export request
RetrieveExport Download a completed export file
RemoveExport Delete an export report

Private REST Methods - Funding

Method Description
GetDepositMethods Returns available deposit methods for a given asset
GetDepositAddresses Returns deposit addresses for a given asset and method
GetStatusOfRecentDeposits Returns the status of recent deposit transactions
GetWithdrawalInformation Returns withdrawal details (fee, minimum, limit) for a given asset
WithdrawFunds Initiate a withdrawal to an external address
GetStatusOfRecentWithdraws Returns the status of recent withdrawal transactions
RequestWithdrawalCancelation Attempt to cancel a pending withdrawal
RequestWalletTransfer Transfer funds between Kraken wallets (e.g., spot to futures)
// Public REST: Get ticker data
ShowMessage(oKraken.REST_API.GetTicker('XBTUSD'));

// Public REST: Get OHLC data
ShowMessage(oKraken.REST_API.GetOHLC('XBTUSD'));

// Private REST: Get account balance
ShowMessage(oKraken.REST_API.GetAccountBalance);

// Private REST: Get open orders
ShowMessage(oKraken.REST_API.GetOpenOrders);

Futures WebSocket API

The TsgcWSAPI_Kraken_Futures component provides real-time streaming for Kraken's futures markets, including perpetual contracts and fixed-maturity futures.

Public Channels

Method Description
SubscribeTicker / UnSubscribeTicker Real-time futures ticker data including mark price, index price, and funding rate
SubscribeTrade / UnSubscribeTrade Real-time trade execution feed for futures markets
SubscribeBook / UnSubscribeBook Order book snapshots and incremental updates for futures contracts
SubscribeHeartBeat / UnSubscribeHeartBeat Connection health monitoring via periodic heartbeat messages
SubscribeTickerLite / UnSubscribeTickerLite Lightweight ticker with reduced payload for high-frequency monitoring

Private Channels

Method Description
SubscribeOpenOrdersVerbose / UnSubscribeOpenOrdersVerbose Detailed real-time open order updates with full order information
SubscribeOpenPositions / UnSubscribeOpenPositions Real-time updates on open futures positions
SubscribeAccountLog / UnSubscribeAccountLog Real-time account activity log (funding, liquidations, etc.)
SubscribeFills / UnSubscribeFills Real-time fill notifications for your futures orders
SubscribeOpenOrders / UnSubscribeOpenOrders Lightweight open order status updates
SubscribeAccountBalanceAndMargins / UnSubscribeAccountBalanceAndMargins Real-time balance and margin updates for your futures account
SubscribeNotifications / UnSubscribeNotifications System notifications and alerts for your account

Futures REST API

The Futures REST API is accessed through the REST_API property of TsgcWSAPI_Kraken_Futures. It provides endpoints for market data, order management, account queries, and fund transfers.

Public REST Methods

Method Description
GetFeeSchedules Returns the current fee schedule for futures trading
GetHistory Returns historical market data for futures contracts
GetInstruments Lists all available futures instruments and their contract specifications
GetTickers Returns ticker data for all futures contracts

Private REST Methods - Account and Orders

Method Description
GetAccounts Returns futures account balances and margin information
GetFills Returns recent fill history for your futures orders
GetHistoricalExecutions Returns historical order executions
GetHistoricalOrders Returns historical order data
GetHistoricalTriggers Returns historical trigger events for conditional orders
GetOpenPositions Returns all currently open futures positions
GetNotifications Returns account notifications

Private REST Methods - Order Management

Method Description
SendMarketOrder Place a market order at the current best price
SendLimitOrder Place a limit order at a specified price
SendStopOrder Place a stop order that triggers at a specified price
SendTakeProfit Place a take-profit order
CancelAllOrders Cancel all open futures orders at once
CancelOrderByOrderId Cancel a specific order using Kraken's order ID
CancelOrderByCliOrderId Cancel a specific order using your client order ID
EditOrderByOrderId Modify an existing order using Kraken's order ID
EditOrderByCliOrderId Modify an existing order using your client order ID

Private REST Methods - Transfers and Reporting

Method Description
Transfer Transfer funds between futures sub-accounts
WalletTransfer Transfer between wallet types
SubAccountTransfer Transfer between sub-accounts
WithdrawalToSpotWallet Move funds from futures wallet back to spot wallet
GetFeeScheduleVolumes Returns your volume for fee tier calculation
GetAccountLogCSV Download account activity log as CSV file

Complete Code Example

The following example demonstrates connecting to the Kraken Spot API, fetching market data via REST, querying your account balance, and subscribing to a real-time ticker feed via WebSocket.

var
  oClient: TsgcWebSocketClient;
  oKraken: TsgcWSAPI_Kraken;
begin
  // Create and configure the WebSocket client
  oClient := TsgcWebSocketClient.Create(nil);
  oKraken := TsgcWSAPI_Kraken.Create(nil);
  oKraken.Client := oClient;

  // Configure API credentials for private endpoints
  oKraken.Kraken.ApiKey := 'your_api_key';
  oKraken.Kraken.ApiSecret := 'your_api_secret';

  // Connect to Kraken
  oClient.Active := True;

  // REST: Get ticker data for BTC/USD
  ShowMessage(oKraken.REST_API.GetTicker('XBTUSD'));

  // REST: Get account balance (requires API key)
  ShowMessage(oKraken.REST_API.GetAccountBalance);

  // WebSocket: Subscribe to real-time ticker
  oKraken.SubscribeTicker('XBT/USD');
end;

Futures Example

Setting up the Futures component follows the same pattern, using TsgcWSAPI_Kraken_Futures instead:

var
  oClient: TsgcWebSocketClient;
  oFutures: TsgcWSAPI_Kraken_Futures;
begin
  oClient := TsgcWebSocketClient.Create(nil);
  oFutures := TsgcWSAPI_Kraken_Futures.Create(nil);
  oFutures.Client := oClient;

  // Configure API credentials
  oFutures.Kraken.ApiKey := 'your_futures_api_key';
  oFutures.Kraken.ApiSecret := 'your_futures_api_secret';

  oClient.Active := True;

  // REST: Get all available futures instruments
  ShowMessage(oFutures.REST_API.GetInstruments);

  // REST: Get account information
  ShowMessage(oFutures.REST_API.GetAccounts);

  // WebSocket: Subscribe to futures ticker
  oFutures.SubscribeTicker('PI_XBTUSD');

  // WebSocket: Subscribe to private account updates
  oFutures.SubscribeOpenPositions;
  oFutures.SubscribeAccountBalanceAndMargins;
end;

Notes and Best Practices

Spot vs. Futures API Keys

Kraken uses separate API keys for spot and futures trading. Generate dedicated keys for each platform from the Kraken settings page. Do not reuse the same key across both components.

WebSocket Token for Private Channels

Private WebSocket subscriptions on the spot exchange require a temporary token obtained via the GetWebSocketsToken REST method. The component handles this automatically when API credentials are configured, but be aware that tokens expire and will be refreshed as needed.

Rate Limits

Kraken enforces rate limits on both REST and WebSocket APIs. REST endpoints use a counter-based system where each call increments a counter, and the counter decays over time. Exceeding the limit results in temporary lockout. Use WebSocket subscriptions for real-time data instead of polling REST endpoints.

Asset Pair Naming

Note: Kraken uses different naming conventions for REST and WebSocket APIs. REST endpoints typically use concatenated names like XBTUSD, while WebSocket channels use the slash-separated format XBT/USD. The component handles this distinction, but keep it in mind when processing responses. Use GetAssetPairs to discover the exact names for all available pairs.
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

FXCM API Update sgcWebSockets

Related Posts