Coinbase Advanced Trade API Integration in Delphi
Coinbase Advanced Trade is the professional trading platform from one of the world's most widely used cryptocurrency exchanges. The TsgcWSAPI_Coinbase component for Delphi provides complete access to both the WebSocket and REST APIs, enabling real-time market data streaming, order management, account monitoring, and futures balance tracking from a unified Delphi interface.
Table of Contents
Overview
The Coinbase Advanced Trade API replaces the legacy Coinbase Pro API and provides a modern interface for professional cryptocurrency trading. It supports both spot trading for a wide range of crypto assets and futures contracts. The API uses two transport mechanisms:
| Transport | Use Case | Authentication |
|---|---|---|
| WebSocket | Real-time streaming of market data, user events, and futures balances | Required for private channels, optional for public |
| REST | Account queries, order placement, product data, and fill retrieval | Required for all private endpoints |
Configuration
Configure the TsgcWSAPI_Coinbase component with your API credentials to access private endpoints. Public market data endpoints can be accessed without authentication.
| Property | Type | Description |
|---|---|---|
Coinbase.ApiKey |
String | Your Coinbase Advanced Trade API key |
Coinbase.ApiSecret |
String | Your Coinbase Advanced Trade API secret, used for request signing |
var
oClient: TsgcWebSocketClient;
oCoinbase: TsgcWSAPI_Coinbase;
begin
oClient := TsgcWebSocketClient.Create(nil);
oCoinbase := TsgcWSAPI_Coinbase.Create(nil);
oCoinbase.Client := oClient;
// Configure API credentials
oCoinbase.Coinbase.ApiKey := 'your_api_key';
oCoinbase.Coinbase.ApiSecret := 'your_api_secret';
// Connect to Coinbase
oClient.Active := True;
end;
WebSocket API
The WebSocket API provides real-time streaming channels for market data and private account events. Public channels deliver market-wide data without authentication, while private channels stream account-specific events.
Public Channels
| Method | Description |
|---|---|
SubscribeHeartBeat / UnSubscribeHeartBeat |
Connection health monitoring via periodic heartbeat messages for a given product |
SubscribeStatus / UnSubscribeStatus |
Product status updates including trading status and auction info |
SubscribeTicker / UnSubscribeTicker |
Real-time ticker data including price, 24h volume, and best bid/ask |
SubscribeTickerBatch / UnSubscribeTickerBatch |
Batched ticker updates delivered at reduced frequency for lower bandwidth usage |
SubscribeLevel2 / UnSubscribeLevel2 |
Full Level 2 order book snapshots and incremental updates |
SubscribeCandles / UnSubscribeCandles |
Real-time OHLCV candle data for charting |
SubscribeMarketTrades / UnSubscribeMarketTrades |
Real-time feed of all trades executed on the exchange for a given product |
Private Channels
| Method | Description |
|---|---|
SubscribeUser / UnSubscribeUser |
Real-time updates on your orders (new, filled, cancelled) and account activity |
SubscribeFuturesBalanceSummary / UnSubscribeFuturesBalanceSummary |
Real-time updates on your futures account balance, margin, and liquidation price |
// Subscribe to real-time ticker for BTC-USD
oCoinbase.SubscribeTicker('BTC-USD');
// Subscribe to Level 2 order book updates
oCoinbase.SubscribeLevel2('BTC-USD');
// Subscribe to candle data for charting
oCoinbase.SubscribeCandles('ETH-USD');
// Subscribe to live market trades
oCoinbase.SubscribeMarketTrades('BTC-USD');
// Subscribe to private user channel (requires API key)
oCoinbase.SubscribeUser('BTC-USD');
// Subscribe to futures balance updates
oCoinbase.SubscribeFuturesBalanceSummary;
REST API - Accounts
The Accounts endpoints let you query your Coinbase portfolio. Each account represents a single currency or asset in your portfolio with its available and held balances.
| Method | Description |
|---|---|
ListAccounts |
Returns a paginated list of all accounts in your portfolio with balances |
GetAccount |
Returns details for a single account by its UUID |
// List all accounts in your portfolio
ShowMessage(oCoinbase.REST_API.ListAccounts);
// Get details for a specific account by UUID
ShowMessage(oCoinbase.REST_API.GetAccount('account-uuid-here'));
REST API - Products and Market Data
The Products endpoints provide market data including available trading pairs, order book snapshots, historical candle data, recent trades, and the current server time. These are all public endpoints and do not require authentication.
| Method | Description |
|---|---|
GetPublicProducts |
Returns a list of all available products (trading pairs) with their details |
GetPublicProduct |
Returns details for a single product by its ID (e.g., BTC-USD) |
GetPublicProductBook |
Returns the current order book for a given product |
GetPublicProductCandles |
Returns OHLCV candle data for a product within a date range and granularity |
GetTrades |
Returns recent trades for a given product |
GetTime |
Returns the current Coinbase server time |
Candle Granularity Options
| Value | Description |
|---|---|
ONE_MINUTE |
1-minute candles |
FIVE_MINUTE |
5-minute candles |
FIFTEEN_MINUTE |
15-minute candles |
THIRTY_MINUTE |
30-minute candles |
ONE_HOUR |
1-hour candles |
TWO_HOUR |
2-hour candles |
SIX_HOUR |
6-hour candles |
ONE_DAY |
Daily candles |
// Get all available products
ShowMessage(oCoinbase.REST_API.GetPublicProducts);
// Get details for BTC-USD
ShowMessage(oCoinbase.REST_API.GetPublicProduct('BTC-USD'));
// Get hourly candles for January 2024
ShowMessage(oCoinbase.REST_API.GetPublicProductCandles(
'BTC-USD', '2024-01-01', '2024-01-31', 'ONE_HOUR'));
// Get recent trades
ShowMessage(oCoinbase.REST_API.GetTrades('BTC-USD'));
REST API - Orders
The Orders endpoints provide full order lifecycle management. You can place new orders (market, limit, or stop), query existing orders, cancel orders, and preview order outcomes before execution.
| Method | Description |
|---|---|
PlaceNewOrder |
Place a new order with full parameter control |
PlaceMarketOrder |
Convenience method for placing a market order (buy or sell at current price) |
PlaceLimitOrder |
Convenience method for placing a limit order at a specified price |
PlaceStopOrder |
Convenience method for placing a stop order that triggers at a specified price |
ListOrders |
Returns a paginated list of orders, optionally filtered by status or product |
GetOrder |
Returns details for a single order by its ID |
CancelOrder |
Cancel one or more open orders by their IDs |
EditOrder |
Modify an existing order (e.g., change price or size) |
EditOrderPreview |
Preview the result of an order edit without executing it |
PreviewOrder |
Preview the result of a new order without placing it (estimated fees, slippage) |
// Place a market buy order for 0.001 BTC
ShowMessage(oCoinbase.REST_API.PlaceMarketOrder(cosBuy, 'BTC-USD', 0.001));
// Place a limit buy order at $40,000
ShowMessage(oCoinbase.REST_API.PlaceLimitOrder(cosBuy, 'BTC-USD', 0.001, 40000));
// List all open orders
ShowMessage(oCoinbase.REST_API.ListOrders);
// Cancel an order by ID
oCoinbase.REST_API.CancelOrder('order-id-here');
PreviewOrder before placing live orders to see estimated fees and execution results without risking real funds. This is especially useful for market orders where the final execution price depends on order book depth.
REST API - Fills
Fills represent the individual executions that make up a completed or partially filled order. A single order may result in multiple fills if it is matched against several resting orders in the book. You can query fills by order ID, product ID, or trade ID.
| Method | Description |
|---|---|
GetFillsByOrderId |
Returns all fills for a specific order |
GetFillsByProductId |
Returns all fills for a specific product (e.g., BTC-USD) |
GetFillsByTradeId |
Returns fill details for a specific trade ID |
// Get fills for a specific order
ShowMessage(oCoinbase.REST_API.GetFillsByOrderId('order-id-here'));
// Get all fills for BTC-USD
ShowMessage(oCoinbase.REST_API.GetFillsByProductId('BTC-USD'));
REST API - Positions
The Positions endpoint is used for managing futures positions. It allows you to close an open futures position.
| Method | Description |
|---|---|
ClosePosition |
Closes an open futures position for a given product |
Complete Code Example
The following example demonstrates a complete workflow: connecting to Coinbase, listing accounts, retrieving historical candle data, subscribing to a real-time ticker, and placing a market order.
var
oClient: TsgcWebSocketClient;
oCoinbase: TsgcWSAPI_Coinbase;
begin
// Create and configure the WebSocket client
oClient := TsgcWebSocketClient.Create(nil);
oCoinbase := TsgcWSAPI_Coinbase.Create(nil);
oCoinbase.Client := oClient;
// Configure API credentials
oCoinbase.Coinbase.ApiKey := 'your_api_key';
oCoinbase.Coinbase.ApiSecret := 'your_api_secret';
// Connect to Coinbase
oClient.Active := True;
// REST: List all accounts in your portfolio
ShowMessage(oCoinbase.REST_API.ListAccounts);
// REST: Get hourly candles for BTC-USD
ShowMessage(oCoinbase.REST_API.GetPublicProductCandles(
'BTC-USD', '2024-01-01', '2024-01-31', 'ONE_HOUR'));
// WebSocket: Subscribe to real-time ticker
oCoinbase.SubscribeTicker('BTC-USD');
// REST: Place a market buy order for 0.001 BTC
ShowMessage(oCoinbase.REST_API.PlaceMarketOrder(cosBuy, 'BTC-USD', 0.001));
end;
Notes and Best Practices
API Key Permissions
When generating API keys on the Coinbase Developer Platform, follow the principle of least privilege. For a read-only dashboard, enable only the View permission. For a trading bot, add Trade permission but leave Transfer disabled unless your application needs to move funds between accounts.
Order Side Constants
When placing orders, use the Delphi enumeration constants for the order side:
| Constant | Description |
|---|---|
cosBuy |
Buy order (acquire the base currency) |
cosSell |
Sell order (sell the base currency) |
Ticker vs. TickerBatch
Use SubscribeTicker when you need every price update in real time (e.g., for an order execution engine). Use SubscribeTickerBatch when you only need periodic snapshots (e.g., for a dashboard) -- it delivers the same data at a reduced frequency, saving bandwidth and processing overhead.
Rate Limits
Coinbase Advanced Trade imposes rate limits on REST API calls. The limits vary by endpoint category (public vs. private, read vs. write). Avoid polling REST endpoints in tight loops; instead, use WebSocket subscriptions for real-time data and reserve REST calls for on-demand queries and order operations.
SubscribeUser channel for real-time order state updates with SubscribeTicker for live market prices. Use the REST PlaceMarketOrder or PlaceLimitOrder methods to execute trades, and confirm execution through the user channel rather than polling GetOrder.