Node.js SDK for the Coinbase APIs and WebSockets, with TypeScript & browser support.
Installations
npm install coinbase-api
Developer Guide
Typescript
Yes
Module System
ESM
Node Version
20.17.0
NPM Version
10.8.2
Score
63
Supply Chain
99.6
Quality
87.1
Maintenance
100
Vulnerability
98.6
License
Releases
Unable to fetch releases
Contributors
Languages
TypeScript (99.55%)
JavaScript (0.35%)
Shell (0.1%)
Developer
Download Statistics
Total Downloads
19,059
Last Day
1,087
Last Week
6,795
Last Month
17,604
Last Year
19,059
GitHub Statistics
7 Stars
159 Commits
3 Forks
1 Watching
1 Branches
2 Contributors
Sponsor this package
Package Meta Information
Latest Version
1.0.6
Package Id
coinbase-api@1.0.6
Unpacked Size
919.05 kB
Size
104.50 kB
File Count
214
NPM Version
10.8.2
Node Version
20.17.0
Publised On
11 Dec 2024
Total Downloads
Cumulative downloads
Total Downloads
19,059
Last day
38.6%
1,087
Compared to previous day
Last week
36.7%
6,795
Compared to previous week
Last month
1,474.6%
17,604
Compared to previous month
Last year
0%
19,059
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
5
Node.js & JavaScript SDK for Coinbase REST APIs & WebSockets
Updated & performant JavaScript & Node.js SDK for the Coinbase REST APIs and WebSockets:
- Supports both retail and institutional REST clients and Websockets:
- Complete integration with all REST APIs and WebSockets.
- TypeScript support (with type declarations for most API requests & responses)
- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
- Automatically supports both ESM and CJS projects.
- Proxy support via axios integration.
- 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/.
Installation
npm install --save coinbase-api
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 my related JavaScript/TypeScript/Node.js projects:
- Try my REST API & WebSocket SDKs:
- Try my misc utilities:
- Check out my examples:
Documentation
Most methods accept JS objects. These can be populated using parameters specified by Coinbase's API documentation.
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
REST API
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
- CBAppClient
- CBExchangeClient
- CBInternationalClient
- CBPrimeClient
- CBCommerceClient
CBAdvancedTradeClient
1const { CBAdvancedTradeClient } = require('coinbase-api'); 2/** 3 * Or, with import: 4 * import { CBAdvancedTradeClient } from 'coinbase-api'; 5 */ 6 7// insert your API key details here from Coinbase API Key Management 8const advancedTradeCdpAPIKey = { 9 // dummy example keys to understand the structure 10 name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2', 11 privateKey: 12 '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n', 13}; 14 15const client = new CBAdvancedTradeClient({ 16 // Either pass the full JSON object that can be downloaded when creating your API keys 17 // cdpApiKey: advancedTradeCdpAPIKey, 18 19 // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret" 20 apiKey: advancedTradeCdpAPIKey.name, 21 apiSecret: advancedTradeCdpAPIKey.privateKey, 22}); 23 24async function doAPICall() { 25 // Example usage of the CBAdvancedTradeClient 26 try { 27 const accounts = await client.getAccounts(); 28 console.log('Get accounts result: ', accounts); 29 } catch (e) { 30 console.error('Exception: ', JSON.stringify(e)); 31 } 32} 33 34doAPICall();
CBAppClient
1const { CBAppClient } = require('coinbase-api'); 2/** 3 * Or, with import: 4 * import { CBAppClient } from 'coinbase-api'; 5 */ 6 7// insert your API key details here from Coinbase API Key Management 8const CBAppKeys = { 9 // dummy example keys to understand the structure 10 name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2', 11 privateKey: 12 '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n', 13}; 14 15const client = new CBAppClient({ 16 // Either pass the full JSON object that can be downloaded when creating your API keys 17 // cdpApiKey: CBAppCdpAPIKey, 18 19 // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret" 20 apiKey: CBAppKeys.name, 21 apiSecret: CBAppKeys.privateKey, 22}); 23 24async function doAPICall() { 25 try { 26 // Transfer money between your own accounts 27 const transferMoneyResult = await client.transferMoney({ 28 account_id: 'your_source_account_id', 29 type: 'transfer', 30 to: 'your_destination_account_id', 31 amount: '0.01', 32 currency: 'BTC', 33 }); 34 console.log('Transfer Money Result: ', transferMoneyResult); 35 } catch (e) { 36 console.error('Error: ', e); 37 } 38} 39 40doAPICall();
CBInternationalClient
1const { CBInternationalClient } = require('coinbase-api'); 2/** 3 * Or, with import: 4 * import { CBInternationalClient } from 'coinbase-api'; 5 */ 6 7// insert your API key details here from Coinbase API Key Management 8const client = new CBInternationalClient({ 9 apiKey: 'insert_api_key_here', 10 apiSecret: 'insert_api_secret_here', 11 apiPassphrase: 'insert_api_passphrase_here', 12 // Set "useSandbox" to use the CoinBase International API sandbox environment 13 // useSandbox: true, 14}); 15 16async function doAPICall() { 17 try { 18 // Get asset details 19 const assetDetails = await client.getAssetDetails({ asset: 'BTC' }); 20 console.log('Asset Details: ', assetDetails); 21 } catch (e) { 22 console.error('Exception: ', JSON.stringify(e, null, 2)); 23 } 24} 25 26doAPICall();
CBExchangeClient
1const { CBExchangeClient } = require('coinbase-api'); 2/** 3 * Or, with import: 4 * import { CBExchangeClient } from 'coinbase-api'; 5 */ 6 7// insert your API key details here from Coinbase API Key Management 8const client = new CBExchangeClient({ 9 apiKey: 'insert_api_key_here', 10 apiSecret: 'insert_api_secret_here', 11 apiPassphrase: 'insert_api_passphrase_here', 12 // Set "useSandbox" to use the CoinBase International API sandbox environment 13 // useSandbox: true, 14}); 15 16async function doAPICall() { 17 try { 18 // Get a single currency by id 19 const currency = await client.getCurrency('BTC'); 20 console.log('Currency: ', currency); 21 } catch (e) { 22 console.error('Exception: ', JSON.stringify(e, null, 2)); 23 } 24} 25 26doAPICall();
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 unique connection (one per server URL) 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
1const { WebsocketClient } = require('coinbase-api'); 2/** 3 * Or, with import: 4 * import { WebsocketClient } from 'coinbase-api'; 5 */ 6 7// public ws client, doesnt need any api keys to run 8const client = new WebsocketClient(); 9 10// The WS Key (last parameter) dictates which WS feed this request goes to (aka if auth is required). 11// As long as the WS feed doesn't require auth, you should be able to subscribe to channels without api credentials. 12client.subscribe( 13 { 14 topic: 'status', 15 payload: { 16 product_ids: ['XRP-USD'], 17 }, 18 }, 19 'advTradeMarketData', 20);
Private Websocket
1const { WebsocketClient } = require('coinbase-api'); 2/** 3 * Or, with import: 4 * import { WebsocketClient } from 'coinbase-api'; 5 */ 6 7// key name & private key, as returned by coinbase when creating your API keys. 8// Note: the below example is a dummy key and won't actually work 9const advancedTradeCdpAPIKey = { 10 name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2', 11 privateKey: 12 '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n', 13}; 14 15const client = new WebsocketClient({ 16 // Either pass the full JSON object that can be downloaded when creating your API keys 17 // cdpApiKey: advancedTradeCdpAPIKey, 18 19 // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret" 20 apiKey: advancedTradeCdpAPIKey.name, 21 apiSecret: advancedTradeCdpAPIKey.privateKey, 22});
Listening and subscribing to Websocket events
1// add event listeners for websocket clients 2 3client.on('open', (data) => { 4 console.log('open: ', data?.wsKey); 5}); 6 7// Data received 8client.on('update', (data) => { 9 console.info(new Date(), 'data received: ', JSON.stringify(data)); 10}); 11 12// Something happened, attempting to reconenct 13client.on('reconnect', (data) => { 14 console.log('reconnect: ', data); 15}); 16 17// Reconnect successful 18client.on('reconnected', (data) => { 19 console.log('reconnected: ', data); 20}); 21 22// Connection closed. If unexpected, expect reconnect -> reconnected. 23client.on('close', (data) => { 24 console.error('close: ', data); 25}); 26 27// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" 28client.on('response', (data) => { 29 console.info('response: ', JSON.stringify(data, null, 2)); 30 // throw new Error('res?'); 31}); 32 33client.on('exception', (data) => { 34 console.error('exception: ', data); 35}); 36 37/** 38 * Use the client subscribe(topic, market) pattern to subscribe to any websocket topic. 39 * 40 * You can subscribe to topics one at a time or many in one request. 41 * 42 * Topics can be sent as simple strings, if no parameters are required: 43 */ 44 45// market data 46client.subscribe('heartbeats', 'advTradeMarketData'); 47// This is the same as above, but using WS_KEY_MAP like an enum to reduce any uncertainty on what value to use: 48// client.subscribe('heartbeats', WS_KEY_MAP.advTradeMarketData); 49 50// user data 51client.subscribe('futures_balance_summary', 'advTradeUserData'); 52client.subscribe('user', 'advTradeUserData'); 53 54/** 55 * Or send a more structured object with parameters, e.g. if parameters are required 56 */ 57const tickerSubscribeRequest = { 58 topic: 'ticker', 59 /** 60 * Anything in the payload will be merged into the subscribe "request", 61 * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`) 62 */ 63 payload: { 64 product_ids: ['ETH-USD', 'BTC-USD'], 65 }, 66}; 67client.subscribe(tickerSubscribeRequest, 'advTradeMarketData'); 68 69/** 70 * Other adv trade public websocket topics: 71 */ 72client.subscribe( 73 [ 74 { 75 topic: 'candles', 76 payload: { 77 product_ids: ['ETH-USD'], 78 }, 79 }, 80 { 81 topic: 'market_trades', 82 payload: { 83 product_ids: ['ETH-USD', 'BTC-USD'], 84 }, 85 }, 86 { 87 topic: 'ticker', 88 payload: { 89 product_ids: ['ETH-USD', 'BTC-USD'], 90 }, 91 }, 92 { 93 topic: 'ticker_batch', 94 payload: { 95 product_ids: ['ETH-USD', 'BTC-USD'], 96 }, 97 }, 98 { 99 topic: 'level2', 100 payload: { 101 product_ids: ['ETH-USD', 'BTC-USD'], 102 }, 103 }, 104 ], 105 'advTradeMarketData', 106);
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.
1const { WebsocketClient, DefaultLogger } = require('coinbase-api'); 2/** 3 * Or, with import: 4 * import { WebsocketClient, DefaultLogger } from 'coinbase-api'; 5 */ 6 7// E.g. customise logging for only the trace level: 8const logger = { 9 // Inherit existing logger methods, using an object spread 10 ...DefaultLogger, 11 // Define a custom trace function to override only that function 12 trace: (...params) => { 13 if ( 14 [ 15 'Sending ping', 16 'Sending upstream ws message: ', 17 'Received pong, clearing pong timer', 18 'Received ping, sending pong frame', 19 ].includes(params[0]) 20 ) { 21 return; 22 } 23 console.log('trace', params); 24 }, 25}; 26 27const ws = new WebsocketClient( 28 { 29 apiKey: 'apiKeyHere', 30 apiSecret: 'apiSecretHere', 31 apiPassphrase: 'apiPassPhraseHere', 32 }, 33 logger, 34);
Contributions & Thanks
Have my projects helped you? Share the love, there are many ways you can show your thanks:
- Star & share my projects.
- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler
- Have an interesting project? Get in touch & invite me to it.
- Or buy me all the coffee:
- ETH(ERC20):
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
- ETH(ERC20):
Contributions & Pull Requests
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
Star History
No vulnerabilities found.
No security vulnerabilities found.