Skip to content

Exchange ​

CBExchangeClient targets Coinbase Exchange at api.exchange.coinbase.com. Use Exchange credentials, accounts and product IDs throughout this guide.

Setup ​

Install coinbase-api with npm install coinbase-api and use Node.js 24 to run the examples. Public REST examples need no credentials. For authenticated examples, add the variables below to a private .env file excluded from Git and run node --env-file=.env filename.ts, replacing filename.ts with its filename. Keep account output private.

Public REST ​

Save as exchange-market-data.ts and run node exchange-market-data.ts:

ts
import { CBExchangeClient } from 'coinbase-api';

async function main() {
  const client = new CBExchangeClient();
  const ticker = await client.getProductTicker({ product_id: 'BTC-USD' });
  console.log(ticker);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Use getAllTradingPairs() to discover products, getProduct() for size/price increments and trading restrictions, and getProductBook() for a book snapshot. Keep price and size strings at the exchange's supported precision.

Public WebSocket prices ​

Save as exchange-stream.ts and run node exchange-stream.ts:

ts
import { WebsocketClient, WS_KEY_MAP } from 'coinbase-api';

const ws = new WebsocketClient();

ws.on('update', (event) => {
  console.log(event);
});
ws.on('response', (event) => {
  console.log(event);
});
ws.on('exception', (error) => {
  console.error(error);
});
ws.on('reconnect', (event) => {
  console.log(event);
});
ws.on('reconnected', (event) => {
  console.log(event);
});

ws.subscribe(
  { topic: 'ticker', payload: { product_ids: ['BTC-USD'] } },
  WS_KEY_MAP.exchangeMarketData,
);

function stop() {
  ws.closeAll();
}
process.once('SIGINT', stop);
process.once('SIGTERM', stop);

The stream runs until Ctrl+C. ticker updates arrive on update; inspect response for subscription confirmation and exception for errors. To maintain a book, use the Exchange level2 channel and apply its snapshot/update rules. The singular heartbeat channel is available for connection activity.

Authentication and account reads ​

Create an Exchange API key with the permissions needed by your application. Set:

dotenv
COINBASE_EXCHANGE_API_KEY=your-exchange-key
COINBASE_EXCHANGE_API_SECRET=your-exchange-secret
COINBASE_EXCHANGE_API_PASSPHRASE=your-api-passphrase

The passphrase belongs to the API key, not your account password. Save as exchange-account.ts:

ts
import { CBExchangeClient } from 'coinbase-api';

function requiredEnvVar(name: string) {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Set ${name}.`);
  }
  return value;
}

async function main() {
  const client = new CBExchangeClient({
    apiKey: requiredEnvVar('COINBASE_EXCHANGE_API_KEY'),
    apiSecret: requiredEnvVar('COINBASE_EXCHANGE_API_SECRET'),
    apiPassphrase: requiredEnvVar('COINBASE_EXCHANGE_API_PASSPHRASE'),
  });
  const accounts = await client.getAccounts();
  console.log(accounts);
  const orders = await client.getOrders();
  console.log(orders);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Balances and current orders ​

getAccounts() supplies balances and holds. getOrders() defaults to open or unsettled orders; a settled order disappearing from this list does not mean it never existed. Use getOrder({ order_id }) or getFills() for the specific history you need. Follow the endpoint's pagination rather than assuming one response is complete.

Order management ​

  1. Read product rules and available balances, then build the Exchange request: product_id, side, type, and the applicable price, size or funds fields. These are flat fields, not an order-configuration object.
  2. Generate and persist a client identifier with client.generateNewOrderId(), pass it as client_oid, and call submitOrder() only when ready to trade. This is a live operation.
  3. Save the returned exchange order ID and follow private events. Use getOrder({ order_id }) for a specific unresolved outcome, not as a routine follow-up to every submission.
  4. Call cancelOrder({ order_id }) to cancel an individual order. Cancellation can race with fills; reconcile the final state before submitting a replacement.

A timeout does not prove a submission failed. Match the original client/exchange identifiers against events and targeted reads before retrying.

Private order updates ​

Save as exchange-private-stream.ts and run with the Exchange environment variables:

ts
import { WebsocketClient, WS_KEY_MAP } from 'coinbase-api';

function requiredEnvVar(name: string) {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Set ${name}.`);
  }
  return value;
}

const ws = new WebsocketClient({
  apiKey: requiredEnvVar('COINBASE_EXCHANGE_API_KEY'),
  apiSecret: requiredEnvVar('COINBASE_EXCHANGE_API_SECRET'),
  apiPassphrase: requiredEnvVar('COINBASE_EXCHANGE_API_PASSPHRASE'),
});

ws.on('update', (event) => {
  console.log(event);
});
ws.on('response', (event) => {
  console.log(event);
});
ws.on('exception', (error) => {
  console.error(error);
});
ws.on('reconnect', (event) => {
  console.log(event);
});
ws.on('reconnected', (event) => {
  console.log(event);
});

ws.subscribe(
  { topic: 'user', payload: { product_ids: ['BTC-USD'] } },
  WS_KEY_MAP.exchangeDirectMarketData,
);

function stop() {
  ws.closeAll();
}
process.once('SIGINT', stop);
process.once('SIGTERM', stop);

This subscribes to the authenticated Exchange user channel through exchangeDirectMarketData. The SDK signs the subscription using the Exchange key, secret and passphrase. exchangeMarketData is the public route; supplying credentials alone does not turn that route into this authenticated subscription.

Load initial orders and account state, then update them from user order events. For balance updates, the authenticated balance channel takes payload.account_ids containing Exchange account IDs. Do not assume the user channel itself is a full balance ledger.

The SDK restores subscriptions automatically after reconnecting. Mark state stale on reconnect, process incoming order events when the stream resumes, and reconcile missing orders, fills or balances through targeted REST reads. Account for events received during recovery. Resume trading only when the account state it depends on is current. See Account State.

Environments and reference ​

useSandbox: true selects Exchange sandbox REST and WebSocket hosts. Use sandbox credentials for private requests. Keep separate client instances for live and sandbox accounts.

This SDK's WebsocketAPIClient does not provide Exchange order entry. Use REST for order commands and subscriptions for updates.

Exchange client reference · Exchange WebSocket channels · Choose another API

Built by Siebly. Open source SDKs for exchange APIs.