Gathering detailed insights and metrics for coinbase-api
Gathering detailed insights and metrics for coinbase-api
Gathering detailed insights and metrics for coinbase-api
Gathering detailed insights and metrics for coinbase-api
Node.js SDK for the Coinbase APIs and WebSockets, with TypeScript & browser support.
npm install coinbase-api
Typescript
Module System
Node Version
NPM Version
63
Supply Chain
99.6
Quality
87.7
Maintenance
100
Vulnerability
98.6
License
Updated on 03 Dec 2024
TypeScript (99.55%)
JavaScript (0.35%)
Shell (0.1%)
Cumulative downloads
Total Downloads
Last day
81.6%
Compared to previous day
Last week
104.1%
Compared to previous week
Last month
652.6%
Compared to previous month
Last year
0%
Compared to previous year
5
Updated & performant JavaScript & Node.js SDK for the Coinbase REST APIs and WebSockets:
npm install --save coinbase-api
Check out my related JavaScript/TypeScript/Node.js projects:
Most methods accept JS objects. These can be populated using parameters specified by Coinbase's API documentation.
This project uses typescript. Resources are stored in 2 key structures:
Create API credentials
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:
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();
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();
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();
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!
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:
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);
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});
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.
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);
Have my projects helped you? Share the love, there are many ways you can show your thanks:
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
No vulnerabilities found.
No security vulnerabilities found.