Skip to content

Bun quickstart ​

Read a public BTC-USD price with coinbase-api. No API key is needed. Prices are BTC-USD last traded prices.

Install Bun first. You can also view the complete Coinbase Bun example on GitHub.

This project uses Advanced Trade public market data. Keep credentialed account and trading calls in a server-side application.

Create the project ​

sh
mkdir coinbase-bun-quickstart
cd coinbase-bun-quickstart
bun add coinbase-api

Read a price ​

Create price.js to make a public REST request.

js
import { CBAdvancedTradeClient } from 'coinbase-api';

const client = new CBAdvancedTradeClient();
const ticker = await client.getPublicProduct({ product_id: 'BTC-USD' });
const price = ticker.price;

if (!price) {
  throw new Error('No BTC-USD price was returned.');
}

console.log('BTC-USD REST price:', price);

Run it:

sh
bun price.js
text
BTC-USD REST price: 65000.5

Stream a price (optional) ​

Create stream.js to stream WebSocket prices until Ctrl+C.

js
import { WebsocketClient } from 'coinbase-api';
import process from 'node:process';

const ws = new WebsocketClient();

ws.on('update', (message) => {
  if (message.channel !== 'ticker') {
    console.log('WebSocket update:', message);
    return;
  }

  let price;
  for (const event of message.events ?? []) {
    for (const ticker of event.tickers ?? []) {
      if (ticker.product_id === 'BTC-USD') {
        price = ticker.price;
      }
    }
  }
  if (!price) {
    console.log('WebSocket update:', message);
  }

  if (price) {
    console.log('BTC-USD WebSocket price:', String(price));
  }
});

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

function stop() {
  ws.closeAll();
  console.log('WebSocket closed.');
}

process.once('SIGINT', stop);
process.once('SIGTERM', stop);

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

Run it:

sh
bun stream.js

The script keeps streaming until Ctrl+C. Exceptions and reconnections are logged; signal handlers close the client. SDK connection logs may also appear:

text
BTC-USD WebSocket price: 65001.2
WebSocket closed.

Troubleshooting ​

  • Run bun install in the directory containing package.json if the SDK import cannot be resolved.

  • If a request fails or no stream updates arrive, check HTTPS and WSS access to the exchange from your network and region.

  • See Runtime setup for the other project recipes and WebSocket subscriptions for continuous streams.

Built by Siebly. Open source SDKs for exchange APIs.