Coinbase WebSocket in Node.js: Advanced Trade ticker and level2 with the coinbase-api SDK
Coinbase runs two public WebSocket feeds. The Advanced Trade market
data feed at wss://advanced-trade-ws.coinbase.com serves
ticker, level2, market_trades,
candles and heartbeats without an API key. The
Coinbase Exchange feed at
wss://ws-feed.exchange.coinbase.com serves the
institutional Exchange product, where level2,
level3 and full need an authenticated
subscription.
This guide streams Advanced Trade prices and a level2 order book from Node.js with coinbase-api, an open-source TypeScript SDK for the Coinbase REST APIs and WebSockets.
Install
npm install coinbase-api
Stream ticker and level2 for BTC-USD
Save this as coinbase-ws.mjs:
import { WebsocketClient, WS_KEY_MAP } from 'coinbase-api';
const ws = new WebsocketClient();
const book = { bid: new Map(), offer: new Map() };
let tickers = 0;
let bookEvents = 0;
let done = false;
ws.on('update', (msg) => {
if (msg.channel === 'ticker' && tickers < 2) {
const t = msg.events[0].tickers[0];
console.log('ticker:', t.product_id, t.price, 'bid', t.best_bid, 'ask', t.best_ask);
tickers++;
}
if (msg.channel === 'l2_data') {
for (const event of msg.events) {
for (const u of event.updates) {
const side = book[u.side];
if (u.new_quantity === '0') side.delete(u.price_level);
else side.set(u.price_level, u.new_quantity);
}
}
if (++bookEvents === 5) {
const bestBid = Math.max(...[...book.bid.keys()].map(Number));
const bestAsk = Math.min(...[...book.offer.keys()].map(Number));
console.log('book levels:', book.bid.size, 'bids,', book.offer.size, 'asks; best bid', bestBid, 'best ask', bestAsk);
}
}
if (!done && tickers >= 2 && bookEvents >= 5) {
done = true;
ws.closeAll();
}
});
ws.on('exception', (err) => console.error('ws error:', err));
ws.subscribe(
[
{ topic: 'ticker', payload: { product_ids: ['BTC-USD'] } },
{ topic: 'level2', payload: { product_ids: ['BTC-USD'] } },
{ topic: 'heartbeats' },
],
WS_KEY_MAP.advTradeMarketData,
);
Run it with node coinbase-ws.mjs.
Example output:
ticker: BTC-USD 51128.73 bid 51128.73 ask 51128.74
ticker: BTC-USD 51128.73 bid 51128.73 ask 51128.74
book levels: 7754 bids, 27128 asks; best bid 51128.73 best ask 51128.74
Prices will differ on each run. Remove the closeAll()
block to keep the stream running.
How the Coinbase WebSocket messages fit together
- One channel per subscribe message. Coinbase expects a separate subscribe message for each channel. The SDK sends one per topic for you.
- Subscribe within five seconds. The server closes a connection that has not subscribed in time. The SDK subscribes as soon as the socket opens.
- level2 arrives as
l2_data. The first event is asnapshotand later events areupdate.new_quantityis the full size at that price, not a change, and"0"removes the level. - Sides are
bidandoffer. That is why the book above uses those two keys. - Heartbeats keep quiet products open. Some channels
close after 60 to 90 seconds without updates, so subscribe to
heartbeatsalongside them. - Reconnects resubscribe. If the connection drops, the client reconnects and sends your subscriptions again. Rebuild the book from the fresh snapshot.
Private channels with a CDP API key
The user channel (your orders) and
futures_balance_summary need a CDP API key. Each subscribe
message carries a JWT signed with that key, and a JWT expires after two
minutes. Pass the key name and private key to the client and the SDK
signs every subscription:
import { WebsocketClient, WS_KEY_MAP } from 'coinbase-api';
const ws = new WebsocketClient({
apiKey: process.env.CB_API_KEY_NAME,
apiSecret: process.env.CB_API_PRIVATE_KEY,
});
ws.on('update', (msg) => console.log(msg.channel, JSON.stringify(msg.events)));
ws.subscribe({ topic: 'user' }, WS_KEY_MAP.advTradeUserData);
Keep keys in environment variables on a server you control.
Coinbase Exchange feed
On wss://ws-feed.exchange.coinbase.com, an
unauthenticated level2 subscribe returns this error:
{"type":"error","message":"Failed to subscribe","reason":"level2, level3, and full channels now require authentication. ..."}
Use the Advanced Trade feed above for a public order book, or
level2_batch on the Exchange feed. The same
WebsocketClient also connects to the Exchange feeds when
you need them.
More Coinbase API examples
- Coinbase JavaScript SDK overview, tutorial and examples: https://siebly.io/sdk/coinbase/javascript
- npm package: https://www.npmjs.com/package/coinbase-api