Skip to content

Repository files navigation

Node.js & JavaScript SDK for Coinbase's Advanced Trade, App, Exchange, International, Prime & Commerce REST APIs and WebSockets

SDK Logo

npm version npm size npm downloads Build & Test last commit Telegram Ask DeepWiki

Updated & performant JavaScript & Node.js SDK for Coinbase's Advanced Trade, App, Exchange, International, Prime & Commerce REST APIs and WebSockets:

  • Professional, robust & performant Coinbase SDK with extensive production use in live trading environments.
  • Complete integration with all Coinbase APIs - supports both retail and institutional REST clients and WebSockets:
  • Complete TypeScript support (with type declarations for most API requests & responses).
    • Strongly typed requests and responses.
    • Automated end-to-end tests ensuring reliability.
  • Actively maintained with a modern, promise-driven interface.
  • Supports both ECDSA and ED25519 API keys with automatic key type detection.
  • Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
    • Event driven messaging.
    • Smart WebSocket persistence with automatic reconnection handling.
    • Emit reconnected event when dropped connection is restored.
    • Support for both public and private WebSocket streams across all platforms.
  • Automatically supports both ESM and CJS projects.
  • Proxy support via axios integration.
  • Heavy automated end-to-end testing with real API calls.
  • Active community support & collaboration in telegram: Node.js Algo Traders.
  • Extensive examples for interacting with the Coinbase API offering in Node.js/JavaScript/TypeScript: /examples/.
  • QuickStart Guide: Coinbase JavaScript QuickStart Guide
  • Coinbase JavaScript Tutorial: Coinbase JavaScript REST API and WebSocket Tutorial

Table of Contents

Installation

npm install --save coinbase-api

Examples

Refer to the examples folder for implementation examples.

Issues & Discussion

  • Issues? Check the issues tab.
  • Discuss & collaborate with other node devs? Join our Node.js Algo Traders engineering community on telegram.
  • Follow our announcement channel for real-time updates on X/Twitter

Related Projects

Check out our JavaScript/TypeScript/Node.js SDKs & Projects:

Documentation

Most methods accept JS objects. These can be populated using parameters specified by Coinbase's API documentation, or check the type definition in each class within this repository.

API Documentation Links

Structure

This project uses typescript. Resources are stored in 2 key structures:

  • src - the whole connector written in typescript
  • examples - some implementation examples & demonstrations. Contributions are welcome!

Usage

Create API credentials on Coinbase's website:

REST API

The SDK provides dedicated REST clients for each of Coinbase's API groups. Each client is designed for specific use cases and user types:

To use any of Coinbase's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the client you want to use. We currently support the following clients:

CBAdvancedTradeClient

Note

Advanced Trade international derivatives moved from INTX to the Deribit-powered Starbase gateway on October 1, 2026. Use CBAdvancedTradeGlobalClient for these markets. CBAdvancedTradeClient continues to support spot and US futures. See Coinbase's migration guide.

const { CBAdvancedTradeClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const advancedTradeCdpAPIKey = {
  // dummy example keys to understand the structure
  name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2',
  privateKey:
    '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n',
};

/*
 * You can add ECDSA keys like the example above, or ED25519 keys like the example below.
 * Client will recognize both types of keys automatically.
 * ED25519:
 * {
 *   name: 'your-api-key-id',
 *   privateKey: 'yourExampleApiSecretEd25519Version==',
 * }
 */

const client = new CBAdvancedTradeClient({
  // Either pass the full JSON object that can be downloaded when creating your API keys
  // cdpApiKey: advancedTradeCdpAPIKey,

  // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret"
  apiKey: advancedTradeCdpAPIKey.name,
  apiSecret: advancedTradeCdpAPIKey.privateKey,
});

async function doAPICall() {
  // Example usage of the CBAdvancedTradeClient
  try {
    const accounts = await client.getAccounts();
    console.log('Get accounts result: ', accounts);
  } catch (e) {
    console.error('Exception: ', JSON.stringify(e));
  }
}

doAPICall();

CBAdvancedTradeGlobalClient

International derivatives REST API endpoints, sometimes referred to as "Advanced Trade Global", are available via the dedicated CBAdvancedTradeGlobalClient class.

Under the hood, it talks JSON-RPC 2.0 to https://drb.coinbase.com/api/v2. Spot and US futures stay on CBAdvancedTradeClient.

The table below only says which method replaces which old endpoint. Parameters and responses are not the same shape. The breaks that matter:

  • The client returns the JSON-RPC result. Errors use the SDK's standard exception handling, with JSON-RPC details in body.error by default (response.data.error when parseExceptions: false). You do not read result or id off a successful return value.
  • Prices and sizes are JSON numbers, not decimal strings. amount: 0.001 is 0.001 of the base coin on these USDC perpetuals.
  • instrument_name replaces the old product id. BTC-PERP-INTX becomes BTC_USDC-PERPETUAL.
  • label replaces client_order_id. It is not guaranteed unique, so do not use it as an idempotency key.
  • Order type, time in force, and status are lowercase (limit, good_til_cancelled, open), not LIMIT or OPEN.

Coinbase's source table: Endpoint mapping.

Action Current API New API CBAdvancedTradeGlobalClient
Place order
Side becomes the method
POST /orders private/buy, private/sell buy(), sell()
Edit order
Edit by label supported
POST /orders/edit private/edit, private/edit_by_label edit(), editByLabel()
Cancel orders
No cancel-by-ID-list; loop, or cancel all
POST /orders/batch_cancel private/cancel, private/cancel_all_* cancel(), cancelByLabel(), cancelAll(), cancelAllByCurrency(), cancelAllByCurrencyPair(), cancelAllByInstrument(), cancelAllByKindOrType()
Close position POST /orders/close_position private/close_position closePosition()
Order preview
No simulated fills
POST /orders/preview -- --
Order history GET /orders/historical/batch private/get_order_history_* getOrderHistoryByCurrency(), getOrderHistoryByInstrument()
Order status GET /orders/historical/{id} private/get_order_state getOrderState(), getOrderStateByLabel()
Fills
Deribit calls fills "user trades"
GET /orders/historical/fills private/get_user_trades_* getUserTradesByCurrency(), getUserTradesByCurrencyAndTime(), getUserTradesByInstrument(), getUserTradesByInstrumentAndTime(), getUserTradesByOrder()
Positions
Filter by currency and kind
GET /intx/positions/{uuid} private/get_positions getPositions(), getPosition()
Account summary GET /intx/portfolio/{uuid} private/get_account_summary getAccountSummary(), getAccountSummaries()
Margin model POST /intx/multi_asset_collateral private/change_margin_model changeMarginModel()
Instruments
Filter by currency and kind
GET /products public/get_instruments getInstruments(), getInstrument()
Order book GET /product_book public/get_order_book getOrderBook(), getOrderBookByInstrumentId()
Ticker GET /best_bid_ask public/ticker getTicker()
Candles GET /products/{id}/candles public/get_tradingview_chart_data getTradingviewChartData()

Method names shown with * are a family. For example, private/get_order_history_by_currency and private/get_order_history_by_instrument.

CBAppClient

const { CBAppClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBAppClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const CBAppKeys = {
  // dummy example keys to understand the structure
  name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2',
  privateKey:
    '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n',
};

/*
 * You can add ECDSA keys like the example above, or ED25519 keys like the example below.
 * Client will recognize both types of keys automatically.
 * ED25519:
 * {
 *   name: 'your-api-key-id',
 *   privateKey: 'yourExampleApiSecretEd25519Version==',
 * }
 */

const client = new CBAppClient({
  // Either pass the full JSON object that can be downloaded when creating your API keys
  // cdpApiKey: CBAppCdpAPIKey,

  // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret"
  apiKey: CBAppKeys.name,
  apiSecret: CBAppKeys.privateKey,
});

async function doAPICall() {
  try {
    // Transfer money between your own accounts
    const transferMoneyResult = await client.transferMoney({
      account_id: 'your_source_account_id',
      type: 'transfer',
      to: 'your_destination_account_id',
      amount: '0.01',
      currency: 'BTC',
    });
    console.log('Transfer Money Result: ', transferMoneyResult);
  } catch (e) {
    console.error('Error: ', e);
  }
}

doAPICall();

CBInternationalClient

const { CBInternationalClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBInternationalClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const client = new CBInternationalClient({
  apiKey: 'insert_api_key_here',
  apiSecret: 'insert_api_secret_here',
  apiPassphrase: 'insert_api_passphrase_here',
  // Set "useSandbox" to use the CoinBase International API sandbox environment
  // useSandbox: true,
});

async function doAPICall() {
  try {
    // Get asset details
    const assetDetails = await client.getAssetDetails({ asset: 'BTC' });
    console.log('Asset Details: ', assetDetails);
  } catch (e) {
    console.error('Exception: ', JSON.stringify(e, null, 2));
  }
}

doAPICall();

CBExchangeClient

const { CBExchangeClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBExchangeClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const client = new CBExchangeClient({
  apiKey: 'insert_api_key_here',
  apiSecret: 'insert_api_secret_here',
  apiPassphrase: 'insert_api_passphrase_here',
  // Set "useSandbox" to use the CoinBase International API sandbox environment
  // useSandbox: true,
});

async function doAPICall() {
  try {
    // Get a single currency by id
    const currency = await client.getCurrency('BTC');
    console.log('Currency: ', currency);
  } catch (e) {
    console.error('Exception: ', JSON.stringify(e, null, 2));
  }
}

doAPICall();

See all clients here for more information on all the functions or the examples for lots of usage examples. You can also check the endpoint function list here to find all available functions!

WebSockets

All available WebSockets can be used via a shared WebsocketClient. The WebSocket client will automatically open/track/manage connections as needed. Each connection is tracked using a WsKey (each WsKey is a string - see WS_KEY_MAP for a list of supported values - WS_KEY_MAP can also be used like an enum).

Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the examples folder on GitHub.

Data events are emitted from the WebsocketClient via the update event, see example below:

Public Websocket

const { WebsocketClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { WebsocketClient } from 'coinbase-api';
 */

// public ws client, doesnt need any api keys to run
const client = new WebsocketClient();

// The WS Key (last parameter) dictates which WS feed this request goes to (aka if auth is required).
// As long as the WS feed doesn't require auth, you should be able to subscribe to channels without api credentials.
client.subscribe(
  {
    topic: 'status',
    payload: {
      product_ids: ['XRP-USD'],
    },
  },
  'advTradeMarketData',
);

Global Derivatives Public WebSocket

Use WS_KEY_MAP.advTradeGlobalMarketData for the Global Derivatives public feed. Pass complete channel names, including their instrument and interval, through the same subscription interface:

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

const client = new WebsocketClient();

client.on('update', (event) => {
  console.log(event.params.channel, event.params.data);
});

client.subscribe(
  ['quote.BTC-PERPETUAL', 'ticker.BTC-PERPETUAL.100ms'],
  WS_KEY_MAP.advTradeGlobalMarketData,
);

// client.unsubscribe('quote.BTC-PERPETUAL', WS_KEY_MAP.advTradeGlobalMarketData);

No credentials are required. The client handles liveness checks and restores subscribed topics after reconnecting, if a connection for any reason needs to be automatically replaced. Updates preserve the JSON-RPC envelope, with data under params.data; acknowledgements use response and API errors use exception. Public intervals are 100ms and agg2; raw requires authentication. See the public example and channel/event types.

Global connections open on demand and are excluded from connectAll(). To preconnect a Global subscription feed, call connect(WS_KEY_MAP.advTradeGlobalMarketData) or connect(WS_KEY_MAP.advTradeGlobalUserData). Use connectWSAPI() to preconnect and authenticate the Global WS API.

Global Derivatives Private WebSocket

Use WS_KEY_MAP.advTradeGlobalUserData for account, order, trade, position and portfolio updates:

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

const client = new WebsocketClient({ apiKey, apiSecret });

client.on('authenticated', ({ wsKey }) => console.log('authenticated:', wsKey));
client.on('update', (event) =>
  console.log(event.params.channel, event.params.data),
);
client.on('exception', (event) => console.error(event));

client.subscribe(
  ['user.orders.future.USDC.100ms', 'user.portfolio.USDC'],
  WS_KEY_MAP.advTradeGlobalUserData,
);

The client authenticates with a CDP JWT before subscribing, renews the session before expiry, and authenticates again before restoring subscriptions after reconnecting. Both ECDSA and Ed25519 CDP keys are supported. Private updates preserve the JSON-RPC envelope. Order notifications use arrays for 100ms/agg2 and individual objects for raw. See the private example and channel/event types.

Global Derivatives WebSocket API

Use WebsocketAPIClient for promise-based Global API requests over WebSocket. Its named methods follow CBAdvancedTradeGlobalClient, reusing the REST parameter and result types. Responses preserve the JSON-RPC envelope, with the method's data under result:

import { WebsocketAPIClient, WS_KEY_MAP } from 'coinbase-api';

const client = new WebsocketAPIClient({ apiKey, apiSecret });

const time = await client.getTime(); // Public methods need no credentials.
const positions = await client.getPositions({ currency: 'USDC' });
console.log(time.result, positions.result);

// Alternatively, use the underlying WebsocketClient's typed request interface:
const response = await client
  .getWSClient()
  .sendWSAPIRequest(WS_KEY_MAP.advTradeGlobalWSAPI, 'private/get_positions', {
    currency: 'USDC',
  });
console.log(response.result);

// When finished:
await client.logout({ invalidate_token: false });

The dedicated WS_KEY_MAP.advTradeGlobalWSAPI connection uses wss://drb.coinbase.com/ws/api/v2. Private calls authenticate automatically, concurrent calls share authentication, and sessions renew before expiry. connectWSAPI() optionally warms up an authenticated connection. Reauthentication after reconnect is enabled by default; subscriptions use their existing separate connections.

API errors, timeouts and disconnects reject the affected promises. Requests are never replayed automatically. wsAPITimeout defaults to 10,000 milliseconds waiting for the RPC reply after sending; individual sendWSAPIRequest() calls can override it with { requestTimeout: 15000 } as the fourth argument. Connection and authentication use their own lifecycle handling; public/auth uses the authentication timeout. Responses and API errors also emit response and exception events on getWSClient().

Session methods include heartbeat configuration, cancel-on-disconnect and logout. Connection-scoped settings must be reapplied after reconnecting. Logout waits for the server's normal close because it sends no JSON-RPC response, and prevents automatic reconnect. See the WS API example, named methods and request/response maps. Block/RFQ methods remain outside this interface for now.

Private Websocket

const { WebsocketClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { WebsocketClient } from 'coinbase-api';
 */

// key name & private key, as returned by coinbase when creating your API keys.
// Note: the below example is a dummy key and won't actually work
const advancedTradeCdpAPIKey = {
  name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2',
  privateKey:
    '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n',
};

/*
 * You can add ECDSA keys like the example above, or ED25519 keys like the example below.
 * Client will recognize both types of keys automatically.
 * ED25519:
 * {
 *   name: 'your-api-key-id',
 *   privateKey: 'yourExampleApiSecretEd25519Version==',
 * }
 */

const client = new WebsocketClient({
  // Either pass the full JSON object that can be downloaded when creating your API keys
  // cdpApiKey: advancedTradeCdpAPIKey,

  // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret"
  apiKey: advancedTradeCdpAPIKey.name,
  apiSecret: advancedTradeCdpAPIKey.privateKey,
});

Listening and subscribing to Websocket events

// add event listeners for websocket clients

client.on('open', (data) => {
  console.log('open: ', data?.wsKey);
});

// Data received
client.on('update', (data) => {
  console.info(new Date(), 'data received: ', JSON.stringify(data));
});

// Something happened, attempting to reconenct
client.on('reconnect', (data) => {
  console.log('reconnect: ', data);
});

// Reconnect successful
client.on('reconnected', (data) => {
  console.log('reconnected: ', data);
});

// Connection closed. If unexpected, expect reconnect -> reconnected.
client.on('close', (data) => {
  console.error('close: ', data);
});

// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
client.on('response', (data) => {
  console.info('response: ', JSON.stringify(data, null, 2));
  // throw new Error('res?');
});

client.on('exception', (data) => {
  console.error('exception: ', data);
});

/**
 * Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
 *
 * You can subscribe to topics one at a time or many in one request.
 *
 * Topics can be sent as simple strings, if no parameters are required:
 */

// market data
client.subscribe('heartbeats', 'advTradeMarketData');
// This is the same as above, but using WS_KEY_MAP like an enum to reduce any uncertainty on what value to use:
// client.subscribe('heartbeats', WS_KEY_MAP.advTradeMarketData);

// user data
client.subscribe('futures_balance_summary', 'advTradeUserData');
client.subscribe('user', 'advTradeUserData');

/**
 * Or send a more structured object with parameters, e.g. if parameters are required
 */
const tickerSubscribeRequest = {
  topic: 'ticker',
  /**
   * Anything in the payload will be merged into the subscribe "request",
   * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`)
   */
  payload: {
    product_ids: ['ETH-USD', 'BTC-USD'],
  },
};
client.subscribe(tickerSubscribeRequest, 'advTradeMarketData');

/**
 * Other adv trade public websocket topics:
 */
client.subscribe(
  [
    {
      topic: 'candles',
      payload: {
        product_ids: ['ETH-USD'],
      },
    },
    {
      topic: 'market_trades',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
    {
      topic: 'ticker',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
    {
      topic: 'ticker_batch',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
    {
      topic: 'level2',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
  ],
  'advTradeMarketData',
);

See WebsocketClient for further information and make sure to check the examples folder for much more usage examples, especially publicWs.ts and privateWs.ts, which explains a lot of small details.


Customise Logging

Pass a custom logger which supports the log methods trace, info and error, or override methods from the default logger as desired.

const { WebsocketClient, DefaultLogger } = require('coinbase-api');
/**
 * Or, with import:
 * import { WebsocketClient, DefaultLogger } from 'coinbase-api';
 */

// E.g. customise logging for only the trace level:
const logger = {
  // Inherit existing logger methods, using an object spread
  ...DefaultLogger,
  // Define a custom trace function to override only that function
  trace: (...params) => {
    if (
      [
        'Sending ping',
        'Sending upstream ws message: ',
        'Received pong, clearing pong timer',
        'Received ping, sending pong frame',
      ].includes(params[0])
    ) {
      return;
    }
    console.log('trace', params);
  },
};

const ws = new WebsocketClient(
  {
    apiKey: 'apiKeyHere',
    apiSecret: 'apiSecretHere',
    apiPassphrase: 'apiPassPhraseHere',
  },
  logger,
);

Browser/Frontend Usage

Webpack

Build a bundle using webpack:

  • npm install
  • npm run build
  • npm run pack

The bundle can be found in dist/. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.

Use with LLMs & AI

This SDK includes a bundled llms.txt file in the root of the repository. If you're developing with LLMs, use the included llms.txt with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK.

This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence.


Used By

Repository Users Preview Image


Contributions & Thanks

Have my projects helped you? Share the love, there are many ways you can show your thanks:

Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.

Star History

Star History Chart

Releases

Sponsor this project

Used by

Contributors

Languages