Atualização da API Coinbase no sgcWebSockets

· Recursos
Coinbase Advanced Trade API Integration em Delphi

Coinbase Advanced Trade is o professional trading platform um partir de one do world's most widely used cryptocurrency exchanges. The TsgcWSAPI_Coinbase component para Delphi provides completo access para both o WebSocket e REST APIs, enabling em tempo real dados de mercado streaming, order management, account monitoring, e futures balance tracking um partir de um unified Delphi interface.

Sumário

Visão Geral

The Coinbase Advanced Trade API replaces o legacy Coinbase Pro API e provides um modern interface para professional cryptocurrency trading. It suporta both spot trading para um wide range de crypto assets e futures contracts. The API uses two transport mechanisms:

Transport Use Case Autenticação
WebSocket Em tempo real streaming de dados de mercado, user events, e futures balances Required para private channels, optional para public
REST Account queries, order placement, product data, e fill retrieval Required para all private endpoints

Configuração

Configurar o TsgcWSAPI_Coinbase component com your API credentials para acessar private endpoints. Dados públicos de mercado endpoints pode ser accessed sem autenticação.

Property Type Description
Coinbase.ApiKey String Your Coinbase Advanced Trade chave de API
Coinbase.ApiSecret String Your Coinbase Advanced Trade API secret, used para request signing
Note: Generate your API credentials do Coinbase Developer Platform. When creating um key, select o Advanced Trade API type e assign somente o permissions your application needs. For market-data-somente applications, você pode skip creating API keys entirely e use somente o public endpoints.
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 em tempo real streaming channels para dados de mercado e private account events. Public channels deliver market-wide data sem autenticação, while private channels stream account-specific events.

Public Channels

Method Description
SubscribeHeartBeat / UnSubscribeHeartBeat Conexão health monitoring via periodic heartbeat messages para um given product
SubscribeStatus / UnSubscribeStatus Product status updates incluindo trading status e auction info
SubscribeTicker / UnSubscribeTicker Em tempo real ticker data incluindo price, 24h volume, e best bid/ask
SubscribeTickerBatch / UnSubscribeTickerBatch Batched ticker updates delivered em reduced frequency para lower bandwidth usage
SubscribeLevel2 / UnSubscribeLevel2 Full Level 2 livro de ordens snapshots e incremental updates
SubscribeCandles / UnSubscribeCandles Em tempo real OHLCV candle data para charting
SubscribeMarketTrades / UnSubscribeMarketTrades Em tempo real feed de all trades executed no exchange para um given product

Private Channels

Method Description
SubscribeUser / UnSubscribeUser Em tempo real updates em your orders (new, filled, cancelled) e account activity
SubscribeFuturesBalanceSummary / UnSubscribeFuturesBalanceSummary Em tempo real updates em your futures account balance, margin, e 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 - Contas

The Accounts endpoints let you query your Coinbase portfolio. Each account represents um single currency ou asset em your portfolio com its available e held balances.

Method Description
ListAccounts Retorna um paginated list de all accounts em your portfolio com balances
GetAccount Retorna details para um single account por 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 - Produtos e Dados de Mercado

The Products endpoints provide dados de mercado incluindo available trading pairs, livro de ordens snapshots, historical candle data, recent trades, e o current server time. These are all public endpoints e do not require autenticação.

Method Description
GetPublicProducts Retorna um list de todos os disponíveis products (trading pairs) com their details
GetPublicProduct Retorna details para um single product por its ID (e.g., BTC-USD)
GetPublicProductBook Retorna o current livro de ordens para um given product
GetPublicProductCandles Retorna OHLCV candle data para um product within um date range e granularity
GetTrades Retorna recent trades para um given product
GetTime Retorna o 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 - Ordens

The Orders endpoints provide full order lifecycle management. Você pode place new orders (market, limit, ou parar), query existing orders, cancelar orders, e preview order outcomes before execution.

Method Description
PlaceNewOrder Place um novo order com full parameter control
PlaceMarketOrder Convenience method para placing um market order (buy ou sell em current price)
PlaceLimitOrder Convenience method para placing um limit order em um specified price
PlaceStopOrder Convenience method para placing um parar order that triggers em um specified price
ListOrders Retorna um paginated list de orders, optionally filtered por status ou product
GetOrder Retorna details para um single order por its ID
CancelOrder Cancelar one ou more abrir orders por their IDs
EditOrder Modificar um existing order (e.g., change price ou size)
EditOrderPreview Preview o resultado de um order edit sem executing it
PreviewOrder Preview o resultado de um novo order sem 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');
Tip: Use PreviewOrder before placing live orders para see estimated fees e execution results sem risking real funds. This is especially useful para market orders where o final execution price depends em livro de ordens depth.

REST API - Execuções

Fills represent o individual executions that make up um completed ou partially filled order. A single order may result em multiple fills if it is matched against several resting orders no book. Você pode query fills por order ID, product ID, ou trade ID.

Method Description
GetFillsByOrderId Retorna all fills para um specific order
GetFillsByProductId Retorna all fills para um specific product (e.g., BTC-USD)
GetFillsByTradeId Retorna fill details para um 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 - Posições

The Positions endpoint é usado para managing futures positions. It permite que você fechar um abrir futures position.

Method Description
ClosePosition Closes um abrir futures position para um given product

Exemplo de Código Completo

The exemplo um seguir demonstrates um completo workflow: connecting para Coinbase, listing accounts, retrieving historical candle data, subscribing para um em tempo real ticker, e placing um 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;

Observações e Boas Práticas

Chave de API Permissions

When generating API keys no Coinbase Developer Platform, follow o principle de least privilege. For um read-somente dashboard, enable somente o View permission. For um trading bot, adicionar Trade permission but leave Transfer disabled unless your application needs para move funds entre accounts.

Order Side Constants

When placing orders, use o Delphi enumeration constants para o order side:

Constant Description
cosBuy Buy order (acquire o base currency)
cosSell Sell order (sell o base currency)

Ticker vs. TickerBatch

Use SubscribeTicker quando você need every price update em tempo real (e.g., para um order execution engine). Use SubscribeTickerBatch quando você somente need periodic snapshots (e.g., para um dashboard) -- it delivers o same data em um reduced frequency, saving bandwidth e processing overhead.

Rate Limits

Coinbase Advanced Trade imposes rate limits em REST API calls. The limits vary por endpoint category (public vs. private, read vs. write). Avoid polling REST endpoints em tight loops; instead, use WebSocket inscrições para em tempo real data e reserve REST calls para on-demand queries e order operations.

Tip: For um robust trading application, combine o SubscribeUser channel para em tempo real order state updates com SubscribeTicker para live market prices. Use o REST PlaceMarketOrder ou PlaceLimitOrder métodos para execute trades, e confirm execution through o usuário channel rather than polling GetOrder.