### Run a JavaScript example with node Source: https://github.com/sieblyio/coinbase-api/blob/master/examples/README.md Runs the getTickers.js example using node. ```shell node ./examples/spot/getTickers.js ``` -------------------------------- ### Install coinbase-api SDK Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Install the coinbase-api package via npm. The examples use standard ES module imports, but the package also supports CommonJS projects. ```bash npm install coinbase-api ``` -------------------------------- ### Install proxy agent Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Install the required packages for using a proxy with the Coinbase API. ```bash npm install coinbase-api https-proxy-agent ``` -------------------------------- ### Run a TypeScript example with ts-node Source: https://github.com/sieblyio/coinbase-api/blob/master/examples/README.md Runs the ws-public.ts example using ts-node. ```shell ts-node ./examples/ws-public.ts ``` -------------------------------- ### Install coinbase-api and socks-proxy-agent Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Install the required packages for using a SOCKS5 proxy with the Coinbase API SDK. ```bash npm install coinbase-api socks-proxy-agent ``` -------------------------------- ### GET /products Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve instruments. Filter by currency and kind. ```APIDOC ## GET /products ### Description Retrieve instruments. Filter by currency and kind. ### Method GET ### Endpoint /products ``` -------------------------------- ### GET /intx/portfolio/{uuid} Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve account summary. ```APIDOC ## GET /intx/portfolio/{uuid} ### Description Retrieve account summary. ### Method GET ### Endpoint /intx/portfolio/{uuid} ``` -------------------------------- ### GET /product_book Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve order book. ```APIDOC ## GET /product_book ### Description Retrieve order book. ### Method GET ### Endpoint /product_book ``` -------------------------------- ### GET /best_bid_ask Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve ticker. ```APIDOC ## GET /best_bid_ask ### Description Retrieve ticker. ### Method GET ### Endpoint /best_bid_ask ``` -------------------------------- ### GET /api/v3/brokerage/market/product_book Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves the public product book. This endpoint does not require authentication. ```APIDOC ## [GET] /api/v3/brokerage/market/product_book ### Description Retrieves the public product book. ### Method GET ### Endpoint /api/v3/brokerage/market/product_book ### Authentication No authentication required. ``` -------------------------------- ### CBAppClient initialization and transferMoney example Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Shows how to set up the CBAppClient with API key details and make a transfer between accounts. Supports both ECDSA and ED25519 keys, which are recognized automatically. The apiSecret must include the 'begin/end EC PRIVATE KEY' comment. ```javascript 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(); ``` -------------------------------- ### GET/POST/PUT/PATCH /api/v1/portfolios... Source: https://github.com/sieblyio/coinbase-api Manages portfolios: get user portfolios, create portfolio, update portfolio parameters, get user portfolio, update portfolio, get portfolio details, get portfolio summary, get portfolio balances, get balance for portfolio asset, loans, positions, limits, fills, cross-collateral/auto-margin/margin-override, transfers, fee rates. Private endpoint. ```APIDOC ## GET/POST/PUT/PATCH /api/v1/portfolios... ### Description Manages portfolios: get user portfolios, create portfolio, update portfolio parameters, get user portfolio, update portfolio, get portfolio details, get portfolio summary, get portfolio balances, get balance for portfolio asset, loans, positions, limits, fills, cross-collateral/auto-margin/margin-override, transfers, fee rates. Private endpoint. ### Method GET, POST, PUT, PATCH ### Endpoint `/api/v1/portfolios...`, `/api/v1/portfolios/fee-rates`, `/api/v1/portfolios/margin` ### Response #### Success Response (200) - Portfolio data (object) - Portfolio information ``` -------------------------------- ### CBInternationalClient initialization and getAssetDetails example Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Shows how to set up the CBInternationalClient with API key, secret, and passphrase. Optionally set useSandbox to true to use the CoinBase International API sandbox environment. Calls getAssetDetails to retrieve asset information. ```javascript 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 initialization and getCurrency example Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Shows how to set up the CBExchangeClient with API key, secret, and passphrase. Optionally set useSandbox to true to use the CoinBase International API sandbox environment. Calls getCurrency to retrieve a single currency by id. ```javascript 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(); ``` -------------------------------- ### getPortfolioFills Source: https://github.com/sieblyio/coinbase-api Retrieves fills for a portfolio. Requires a start date; default limit is 100, maximum 3000. ```APIDOC ## GET /v1/portfolios/{portfolio_id}/fills ### Description Retrieves fills for a portfolio. Requires a start date; default limit is 100, maximum 3000. ### Method GET ### Endpoint /v1/portfolios/{portfolio_id}/fills ### Parameters #### Path Parameters - **portfolio_id** (string) - Required - The ID of the portfolio. #### Query Parameters - **start_date** (string) - Required - The start date for fills. - **limit** (integer) - Optional - Number of fills to return (default 100, max 3000). ``` -------------------------------- ### Make Global WebSocket API calls with WebsocketAPIClient Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Use WebsocketAPIClient to make JSON-RPC requests over a separate WebSocket connection. Private calls authenticate automatically and concurrent calls share authentication. The example calls getTime() and getPositions(), then closes the connection in a finally block. API errors, timeouts, and disconnects reject the request promise; requests are not replayed automatically. wsAPITimeout defaults to 10,000 ms and starts after sending the request, not including connection or authentication time. ```javascript import { WebsocketAPIClient } from 'coinbase-api'; async function main() { const client = new WebsocketAPIClient({ apiKey: process.env.COINBASE_API_KEY_NAME, apiSecret: process.env.COINBASE_API_PRIVATE_KEY, }); try { const time = await client.getTime(); console.log('Server time:', time.result); const positions = await client.getPositions({ currency: 'USDC' }); console.log('Positions:', positions.result); } finally { client.getWSClient().closeAll(); } } main().catch((error) => console.error('Global WS API request failed:', error)); ``` -------------------------------- ### GET/POST /api/v1/transfers... Source: https://github.com/sieblyio/coinbase-api Manages transfers: get matching transfers, get transfer, withdraw to crypto address, create crypto address, create counterparty ID, validate counterparty ID, get counterparty withdrawal limit, withdraw to counterparty ID. Private endpoint. ```APIDOC ## GET/POST /api/v1/transfers... ### Description Manages transfers: get matching transfers, get transfer, withdraw to crypto address, create crypto address, create counterparty ID, validate counterparty ID, get counterparty withdrawal limit, withdraw to counterparty ID. Private endpoint. ### Method GET, POST ### Endpoint `/api/v1/transfers...` ### Response #### Success Response (200) - Transfer data (object) - Transfer information ``` -------------------------------- ### Preview a Spot Order with CBAdvancedTradeClient.previewOrder() Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Validates a market-buy order for BTC-USD and returns estimated totals, commission, market prices, warnings, and validation errors without submitting to the matching engine. Requires COINBASE_API_KEY_NAME and COINBASE_API_PRIVATE_KEY environment variables, and the preview endpoint needs 'view' permission. Check 'errs' before using any estimate; 'preview_id' identifies the preview result but does not remove the need to validate current product rules. ```javascript import { CBAdvancedTradeClient } from 'coinbase-api'; async function main() { if ( !process.env.COINBASE_API_KEY_NAME || !process.env.COINBASE_API_PRIVATE_KEY ) { console.error('Set COINBASE_API_KEY_NAME and COINBASE_API_PRIVATE_KEY.'); return; } const client = new CBAdvancedTradeClient({ apiKey: process.env.COINBASE_API_KEY_NAME, apiSecret: process.env.COINBASE_API_PRIVATE_KEY, }); let product; try { product = await client.getPublicProduct({ product_id: 'BTC-USD', }); console.log('Minimum quote size:', product.quote_min_size); } catch (error) { console.error('Product request failed:', error); return; } if ( !product.quote_min_size || !Number.isFinite(Number(product.quote_min_size)) || Number(product.quote_min_size) <= 0 ) { console.error('BTC-USD returned an invalid quote_min_size.'); return; } try { const preview = await client.previewOrder({ product_id: 'BTC-USD', side: 'BUY', order_configuration: { market_market_ioc: { quote_size: product.quote_min_size, }, }, }); console.log('Validation errors:', preview.errs); console.log('Warnings:', preview.warning); console.log('Order total:', preview.order_total); console.log('Commission total:', preview.commission_total); console.log('Best bid:', preview.best_bid); console.log('Best ask:', preview.best_ask); console.log('Preview ID:', preview.preview_id); } catch (error) { console.error('Order preview failed:', error); } } main(); ``` -------------------------------- ### generateNewOrderId usage example Source: https://github.com/sieblyio/coinbase-api Example of generating a new order ID and logging it. The output is cbnode followed by 14 random characters. ```javascript const orderId = client.generateNewOrderId(); console.log(orderId); // cbnode<14 random chars> ``` -------------------------------- ### CBAdvancedTradeClient constructor options Source: https://github.com/sieblyio/coinbase-api Example of configuring a REST client with RestClientOptions. Shows setting API credentials, JWT expiry, keep-alive, strict validation, and localization. The baseUrl option is commented out. ```javascript const client = new CBAdvancedTradeClient({ apiKey: process.env.API_KEY_NAME, apiSecret: process.env.API_PRIVATE_KEY, jwtExpiresSeconds: 120, keepAlive: true, keepAliveMsecs: 2000, strictParamValidation: true, localisation: 'en', // baseUrl: 'https://api.coinbase.com', }); ``` -------------------------------- ### Build standalone Webpack bundle Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Commands to build the standalone UMD bundle from the SDK repository. Run npm install, then npm run build, then npm run pack. The configuration writes dist/coinbaseapi.js with the global name coinbaseapi. ```sh npm install npm run build npm run pack ``` -------------------------------- ### GET /orders/historical/batch Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve order history. ```APIDOC ## GET /orders/historical/batch ### Description Retrieve order history. ### Method GET ### Endpoint /orders/historical/batch ``` -------------------------------- ### getWalletDepositInstructions Source: https://github.com/sieblyio/coinbase-api Retrieves deposit instructions for a wallet. ```APIDOC ## GET /v1/portfolios/{portfolio_id}/wallets/{wallet_id}/deposit_instructions ### Description Retrieves deposit instructions for a wallet. ### Method GET ### Endpoint /v1/portfolios/{portfolio_id}/wallets/{wallet_id}/deposit_instructions ### Parameters #### Path Parameters - **portfolio_id** (string) - Required - The ID of the portfolio. - **wallet_id** (string) - Required - The ID of the wallet. #### Query Parameters - **GetPrimeWalletDepositInstructionsRequest** (object) - Required - Request parameters for deposit instructions. ``` -------------------------------- ### Make public REST API calls with CBAdvancedTradeClient Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Public market data calls require no API key. The example calls getServerTime, getPublicProduct, getPublicProductBook, getPublicProductCandles, and getPublicMarketTrades for BTC-USD, logging results and errors. Returned objects vary by method; prices, quantities, increments, and timestamps are commonly strings, so keep them as strings until a calculation requires conversion. ```javascript import { CBAdvancedTradeClient } from 'coinbase-api'; const client = new CBAdvancedTradeClient(); async function main() { try { const serverTime = await client.getServerTime(); console.log('Server time:', serverTime.iso); } catch (error) { console.error('Server time request failed:', error); } try { const product = await client.getPublicProduct({ product_id: 'BTC-USD', }); console.log('BTC-USD price:', product.price); console.log('Base increment:', product.base_increment); console.log('Price increment:', product.price_increment); } catch (error) { console.error('Product request failed:', error); } try { const orderBook = await client.getPublicProductBook({ product_id: 'BTC-USD', limit: 5, }); console.log('Best bid:', orderBook.pricebook.bids[0]); console.log('Best ask:', orderBook.pricebook.asks[0]); } catch (error) { console.error('Order book request failed:', error); } const end = Math.floor(Date.now() / 1000); const start = end - 60 * 60; try { const candles = await client.getPublicProductCandles({ product_id: 'BTC-USD', start: String(start), end: String(end), granularity: 'FIVE_MINUTE', limit: 12, }); console.log('Latest candle:', candles.candles[0]); } catch (error) { console.error('Candles request failed:', error); } try { const marketTrades = await client.getPublicMarketTrades({ product_id: 'BTC-USD', limit: 10, }); console.log('Latest trade:', marketTrades.trades[0]); console.log('Best bid:', marketTrades.best_bid); console.log('Best ask:', marketTrades.best_ask); } catch (error) { console.error('Market trades request failed:', error); } } main(); ``` -------------------------------- ### GET /intx/positions/{uuid} Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve positions. Filter by currency and kind. ```APIDOC ## GET /intx/positions/{uuid} ### Description Retrieve positions. Filter by currency and kind. ### Method GET ### Endpoint /intx/positions/{uuid} ``` -------------------------------- ### WebsocketAPIClient example with error handling Source: https://github.com/sieblyio/coinbase-api Creates a WebsocketAPIClient, submits a market buy order for BTC_USDC-PERPETUAL, logs the order ID, and logs out. Catches errors as WSAPIErrorResponse or Error. ```typescript const client = new WebsocketAPIClient({ apiKey, apiSecret }); try { const buy = await client.submitBuy({ instrument_name: 'BTC_USDC-PERPETUAL', amount: 0.001, type: 'market', }); console.log(buy.result.order_id); await client.logout({ invalidate_token: false }); } catch (e) { console.error('order failed:', e); // WSAPIErrorResponse or Error } ``` -------------------------------- ### POST /orders/preview Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Preview an order. No simulated fills. ```APIDOC ## POST /orders/preview ### Description Preview an order. No simulated fills. ### Method POST ### Endpoint /orders/preview ``` -------------------------------- ### GET /orders/historical/{id} Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve order status by order ID. ```APIDOC ## GET /orders/historical/{id} ### Description Retrieve order status by order ID. ### Method GET ### Endpoint /orders/historical/{id} ``` -------------------------------- ### GET /v1/portfolios/{portfolio_id}/products Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves the products available for a specific portfolio. This endpoint requires authentication. ```APIDOC ## [GET] /v1/portfolios/{portfolio_id}/products ### Description Retrieves the products available for a specific portfolio. This endpoint requires authentication. ### Method GET ### Endpoint /v1/portfolios/{portfolio_id}/products ### Parameters #### Path Parameters - **portfolio_id** - Required - The ID of the portfolio to retrieve products for. ``` -------------------------------- ### Import coinbase-api with CommonJS and ES modules Source: https://github.com/sieblyio/coinbase-api Shows how to import the package using CommonJS require or ES module import syntax. Both import the CBAdvancedTradeClient and WebsocketClient classes from the package root. ```javascript // CommonJS const { CBAdvancedTradeClient, WebsocketClient } = require('coinbase-api'); // ES modules / TypeScript import { CBAdvancedTradeClient, WebsocketClient } from 'coinbase-api'; ``` -------------------------------- ### GET /orders/historical/fills Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Retrieve fills. Deribit calls fills 'user trades'. ```APIDOC ## GET /orders/historical/fills ### Description Retrieve fills. Deribit calls fills 'user trades'. ### Method GET ### Endpoint /orders/historical/fills ``` -------------------------------- ### getAnnouncements Source: https://github.com/sieblyio/coinbase-api Retrieves announcements. Optional start timestamp and count parameters. ```APIDOC ## getAnnouncements ### Description Retrieves announcements. Optional start timestamp and count parameters. ### Method JSON-RPC: `public/get_announcements` ### Parameters #### Request Body - `start_timestamp` (optional) - Start timestamp - `count` (optional) - Number of announcements to return ### Response #### Success Response - `AdvTradeGlobalGetAnnouncementsItem[]` - List of announcements ``` -------------------------------- ### getAllProductVolume Source: https://github.com/sieblyio/coinbase-api Retrieves volume summary for all products. ```APIDOC ## [GET] /products/volume-summary ### Description Retrieves volume summary for all products. ### Method GET ### Endpoint /products/volume-summary ### Response #### Success Response (200) - **volume_summary** (object) - Volume summary data ``` -------------------------------- ### connect Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Preconnect a Global subscription feed. 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)`. ```APIDOC ## connect ### Description Preconnect a Global subscription feed. 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)`. ### Method connect ### Parameters - **wsKey** (string) - Required - The WS Key for the feed to preconnect, e.g., `WS_KEY_MAP.advTradeGlobalMarketData` or `WS_KEY_MAP.advTradeGlobalUserData`. ``` -------------------------------- ### GET /v2/time Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves the current server time. ```APIDOC ## GET /v2/time ### Description Retrieves the current server time. ### Method GET ### Endpoint /v2/time ``` -------------------------------- ### GET /v2/currencies/crypto Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all cryptocurrencies supported by Coinbase. ```APIDOC ## GET /v2/currencies/crypto ### Description Retrieves all cryptocurrencies supported by Coinbase. ### Method GET ### Endpoint /v2/currencies/crypto ``` -------------------------------- ### WebsocketClient with custom options Source: https://github.com/sieblyio/coinbase-api Instantiate WebsocketClient with overridden pingInterval, pongTimeout, reconnectTimeout, and wsAPITimeout. The base client materializes defaults into WebsocketClientOptions, then applies user options. ```javascript const wsClient = new WebsocketClient({ apiKey, apiSecret, pingInterval: 5000, pongTimeout: 3000, reconnectTimeout: 1000, wsAPITimeout: 15000, // Global WS API replies }); ``` -------------------------------- ### GET /v1/portfolios Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all portfolios. This endpoint requires authentication. ```APIDOC ## GET /v1/portfolios ### Description Retrieves all portfolios. ### Method GET ### Endpoint /v1/portfolios ### Authentication :closed_lock_with_key: (Requires authentication) ``` -------------------------------- ### Create a charge Source: https://github.com/sieblyio/coinbase-api Creates a charge with a fixed price and custom metadata, then logs the hosted URL from the response. ```javascript const charge = await client.createCharge({ local_price: { amount: '10.00', currency: 'USD' }, pricing_type: 'fixed_price', metadata: { custom_field: 'order-123' }, }); console.log(charge.data.hosted_url); ``` -------------------------------- ### GET /reports Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all reports. This endpoint requires authentication. ```APIDOC ## GET /reports ### Description Retrieves all reports. This endpoint requires authentication. ### Method GET ### Endpoint `/reports` ``` -------------------------------- ### GET /v2/exchange-rates Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves exchange rates for supported currencies. ```APIDOC ## GET /v2/exchange-rates ### Description Retrieves exchange rates for supported currencies. ### Method GET ### Endpoint /v2/exchange-rates ``` -------------------------------- ### createWallet Source: https://github.com/sieblyio/coinbase-api Creates a new wallet within a portfolio. ```APIDOC ## POST /v1/portfolios/{portfolio_id}/wallets ### Description Creates a new wallet within a portfolio. ### Method POST ### Endpoint /v1/portfolios/{portfolio_id}/wallets ### Parameters #### Path Parameters - **portfolio_id** (string) - Required - The ID of the portfolio. #### Request Body - **CreatePrimeWalletRequest** (object) - Required - Wallet creation details. ``` -------------------------------- ### Instantiate CBCommerceClient with API key Source: https://github.com/sieblyio/coinbase-api Creates a new CBCommerceClient instance using an API key. No secret or passphrase is required. ```javascript import { CBCommerceClient } from 'coinbase-api'; const client = new CBCommerceClient({ apiKey: 'your_commerce_api_key' }); ``` -------------------------------- ### GET /v2/currencies Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all fiat currencies supported by Coinbase. ```APIDOC ## GET /v2/currencies ### Description Retrieves all fiat currencies supported by Coinbase. ### Method GET ### Endpoint /v2/currencies ``` -------------------------------- ### GET /api/v1/rankings/statistics Source: https://github.com/sieblyio/coinbase-api Retrieves rankings statistics. Private endpoint. ```APIDOC ## GET /api/v1/rankings/statistics ### Description Retrieves rankings statistics. Private endpoint. ### Method GET ### Endpoint `/api/v1/rankings/statistics` ### Response #### Success Response (200) - Rankings statistics (object) - Rankings data ``` -------------------------------- ### WebsocketClient constructor Source: https://github.com/sieblyio/coinbase-api Creates a new WebsocketClient instance with configurable options for authentication, connection behavior, and logging. The first argument is a WSClientConfigurableOptions object, and the second optional argument is a custom logger. ```APIDOC ## WebsocketClient constructor ### Description Creates a new WebsocketClient instance with configurable options for authentication, connection behavior, and logging. The first argument is a WSClientConfigurableOptions object, and the second optional argument is a custom logger. ### Method Constructor ### Endpoint `new WebsocketClient(options, logger?)` ### Parameters #### Options (WSClientConfigurableOptions) - `apiKey` (string) - Optional - API key name (Advanced Trade/App: API Key Name). - `apiSecret` (string) - Optional - API private key (Advanced Trade/App include PEM headers). - `apiPassphrase` (string) - Optional - Exchange/International/Prime WS auth passphrase. - `jwtExpiresSeconds` (number) - Optional - JWT expiry for Advanced Trade/App/Global WS auth (Global capped at 120). Default: `120`. - `pingInterval` (number) - Optional - ms between upstream pings. Default: `10000`. - `pongTimeout` (number) - Optional - ms to wait for a pong before terminating the socket. Default: `1000`. - `reconnectTimeout` (number) - Optional - ms delay before reconnecting a dropped socket. Default: `500`. - `wsUrl` (string) - Optional - Override the WS URL for all connections. - `wsOptions` (object) - Optional - Passed to the `WebSocket` constructor. - `useSandbox` (boolean) - Optional - Sandbox WS endpoints (Exchange, International only). Default: `false`. - `customSignMessageFn` (function) - Optional - Custom signing function (e.g. node's `createHmac`); documented in README/examples but not used by internal signing in the current source — the ws utils call `signMessage` directly. - `reauthWSAPIOnReconnect` (boolean) - Optional - Re-authenticate the Global WS API session after reconnects if it was authenticated before. Default: `true`. - `wsAPITimeout` (number) - Optional - ms to wait for a Global WS API reply after sending; override per-call via `requestFlags.requestTimeout`. Default: `10000`. #### Logger (optional) - Object matching `typeof DefaultLogger` with required keys `trace(...params)`, `info(...params)`, `error(...params)`. ### Request Example ```javascript const wsClient = new WebsocketClient({ apiKey, apiSecret, pingInterval: 5000, pongTimeout: 3000, reconnectTimeout: 1000, wsAPITimeout: 15000, // Global WS API replies }); ``` ```javascript import { DefaultLogger, WebsocketClient } from 'coinbase-api'; const logger = { ...DefaultLogger, trace: (...params) => { /* silent */ }, }; const client = new WebsocketClient({}, logger); ``` ``` -------------------------------- ### GET /api/v1/position-offsets Source: https://github.com/sieblyio/coinbase-api Retrieves position offsets. Public endpoint. ```APIDOC ## GET /api/v1/position-offsets ### Description Retrieves position offsets. Public endpoint. ### Method GET ### Endpoint `/api/v1/position-offsets` ### Response #### Success Response (200) - Position offsets (object) - Position offset data ``` -------------------------------- ### constructor(options?, logger?) Source: https://github.com/sieblyio/coinbase-api Creates a new WebsocketClient instance. Accepts optional configuration options and an optional logger. ```APIDOC ## constructor(options?, logger?) ### Description Creates a new WebsocketClient instance. Accepts optional configuration options and an optional logger. ### Method constructor ### Parameters - `options` (WSClientConfigurableOptions) - Optional - Configuration options including apiKey/apiSecret/apiPassphrase, heartbeat timing, reconnect delay, useSandbox, wsUrl, wsOptions, customSignMessageFn, reauthWSAPIOnReconnect, wsAPITimeout. - `logger` (typeof DefaultLogger) - Optional - Injectable logger with trace/info/error methods. Defaults to DefaultLogger. ### Example ```javascript import { WebsocketClient } from 'coinbase-api'; const client = new WebsocketClient({ apiKey, apiSecret }); ``` ``` -------------------------------- ### WebsocketAPIClient usage example Source: https://github.com/sieblyio/coinbase-api Shows how to instantiate the client and call public and authenticated methods. The getTime() call is public and requires no authentication, while getPositions() requires credentials. Responses preserve the JSON-RPC envelope, so read data from .result. ```typescript import { WebsocketAPIClient } from 'coinbase-api'; const client = new WebsocketAPIClient({ apiKey, apiSecret }); const time = await client.getTime(); // public — no auth needed const positions = await client.getPositions({ currency: 'USDC' }); console.log(time.result, positions.result); ``` -------------------------------- ### GET /api/v1/transfers Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves matching transfers. This endpoint requires authentication. ```APIDOC ## GET /api/v1/transfers ### Description Retrieves matching transfers. ### Method GET ### Endpoint `/api/v1/transfers` ### Authentication Requires API key authentication (closed lock icon). ``` -------------------------------- ### createConversion Source: https://github.com/sieblyio/coinbase-api Creates a conversion between assets in a wallet. ```APIDOC ## POST /v1/portfolios/{portfolio_id}/wallets/{wallet_id}/conversion ### Description Creates a conversion between assets in a wallet. ### Method POST ### Endpoint /v1/portfolios/{portfolio_id}/wallets/{wallet_id}/conversion ### Parameters #### Path Parameters - **portfolio_id** (string) - Required - The ID of the portfolio. - **wallet_id** (string) - Required - The ID of the wallet. #### Request Body - **CreatePrimeConversionRequest** (object) - Required - Conversion details. ``` -------------------------------- ### GET /api/v1/rankings/statistics Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves rankings statistics. This endpoint requires authentication. ```APIDOC ## GET /api/v1/rankings/statistics ### Description Retrieves rankings statistics. ### Method GET ### Endpoint `/api/v1/rankings/statistics` ### Authentication Requires API key authentication (closed lock icon). ``` -------------------------------- ### GET /api/v1/portfolios Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all user portfolios. This endpoint requires authentication. ```APIDOC ## GET /api/v1/portfolios ### Description Retrieves all user portfolios. ### Method GET ### Endpoint /api/v1/portfolios ### Authentication Requires authentication. ### Response #### Success Response (200) - **portfolios** (array) - List of portfolio objects. ``` -------------------------------- ### Instantiate CBAppClient with credentials Source: https://github.com/sieblyio/coinbase-api Creates a new CBAppClient instance using apiKey and apiSecret. The apiSecret is an EC private key. ```javascript import { CBAppClient } from 'coinbase-api'; const client = new CBAppClient({ apiKey: 'organizations/.../apiKeys/...', apiSecret: '-----BEGIN EC PRIVATE KEY-----\n...', }); ``` -------------------------------- ### GET /api/v1/orders Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves open orders. This endpoint requires authentication. ```APIDOC ## GET /api/v1/orders ### Description Retrieves open orders. ### Method GET ### Endpoint /api/v1/orders ### Authentication Requires authentication. ### Response #### Success Response (200) - **orders** (array) - List of open orders. ``` -------------------------------- ### Instantiate CBExchangeClient with API credentials Source: https://github.com/sieblyio/coinbase-api Shows how to create a CBExchangeClient instance using the coinbase-api package. Requires apiKey, apiSecret, and apiPassphrase for authenticated endpoints. ```javascript import { CBExchangeClient } from 'coinbase-api'; const client = new CBExchangeClient({ apiKey: 'insert_api_key_here', apiSecret: 'insert_api_secret_here', apiPassphrase: 'insert_api_passphrase_here', }); ``` -------------------------------- ### Use SocksProxyAgent with CBAdvancedTradeClient and WebsocketClient Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Configure the REST and WebSocket clients to use a SOCKS5 proxy. Requires the COINBASE_SOCKS_PROXY_URL environment variable. The example subscribes to ticker and heartbeats, and handles open, response, update, and exception events. ```javascript import { SocksProxyAgent } from 'socks-proxy-agent'; import { CBAdvancedTradeClient, WebsocketClient, WS_KEY_MAP, } from 'coinbase-api'; async function main() { if (!process.env.COINBASE_SOCKS_PROXY_URL) { console.error('Set COINBASE_SOCKS_PROXY_URL.'); return; } const proxyAgent = new SocksProxyAgent(process.env.COINBASE_SOCKS_PROXY_URL); const rest = new CBAdvancedTradeClient( {}, { httpsAgent: proxyAgent, proxy: false, }, ); const ws = new WebsocketClient({ wsOptions: { agent: proxyAgent, }, }); try { const serverTime = await rest.getServerTime(); console.log('REST API through SOCKS5:', serverTime.iso); } catch (error) { console.error('SOCKS5 REST API request failed:', error); } ws.on('open', ({ wsKey }) => { console.log('SOCKS5 WebSocket opened:', wsKey); }); ws.on('response', (response) => { console.log('SOCKS5 WebSocket response:', response.wsKey, response.channel); }); ws.on('update', (update) => { console.log( 'SOCKS5 WebSocket update:', update.wsKey, update.channel, update.events, ); }); ws.on('exception', (error) => { console.error('SOCKS5 WebSocket exception:', error); }); ws.subscribe( { topic: 'ticker', payload: { product_ids: ['BTC-USD'], }, }, WS_KEY_MAP.advTradeMarketData, ); ws.subscribe('heartbeats', WS_KEY_MAP.advTradeMarketData); process.once('SIGINT', () => { ws.closeAll(); }); } main(); ``` -------------------------------- ### GET /wrapped-assets/stake-wrap Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all stake wraps. This endpoint requires authentication. ```APIDOC ## GET /wrapped-assets/stake-wrap ### Description Retrieves all stake wraps. This endpoint requires authentication. ### Method GET ### Endpoint `/wrapped-assets/stake-wrap` ``` -------------------------------- ### GET /wrapped-assets Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all wrapped assets. This endpoint does not require authentication. ```APIDOC ## GET /wrapped-assets ### Description Retrieves all wrapped assets. This endpoint does not require authentication. ### Method GET ### Endpoint `/wrapped-assets` ``` -------------------------------- ### GET /api/v3/brokerage/market/products Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all public products. This endpoint does not require authentication. ```APIDOC ## [GET] /api/v3/brokerage/market/products ### Description Retrieves all public products. ### Method GET ### Endpoint /api/v3/brokerage/market/products ### Authentication No authentication required. ``` -------------------------------- ### Enable Advanced Trade static sandbox with useSandbox: true Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Use this to connect to the Advanced Trade static sandbox REST API, which returns predefined mock responses for a limited set of account and order endpoints. It does not run a matching engine and is not a funded trading environment. This is REST-only; there is no Advanced Trade WebSocket sandbox. ```javascript import { CBAdvancedTradeClient } from 'coinbase-api'; const sandboxRest = new CBAdvancedTradeClient({ useSandbox: true, }); ``` -------------------------------- ### Instantiate CBPrimeClient with credentials Source: https://github.com/sieblyio/coinbase-api Creates a new CBPrimeClient instance using API key, secret, and passphrase. Required for Coinbase Prime API authentication. ```javascript import { CBPrimeClient } from 'coinbase-api'; const client = new CBPrimeClient({ apiKey: 'api_key', apiSecret: 'api_secret', apiPassphrase: 'api_passphrase', }); ``` -------------------------------- ### GET /api/v1/fee-rate-tiers Source: https://github.com/sieblyio/coinbase-api Retrieves fee rate tiers. Private endpoint. ```APIDOC ## GET /api/v1/fee-rate-tiers ### Description Retrieves fee rate tiers. Private endpoint. ### Method GET ### Endpoint `/api/v1/fee-rate-tiers` ### Response #### Success Response (200) - Fee rate tiers (object) - Fee rate tier data ``` -------------------------------- ### GET /api/v1/portfolios/fee-rates Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves fee rates for a portfolio. This endpoint requires authentication. ```APIDOC ## GET /api/v1/portfolios/fee-rates ### Description Retrieves fee rates for a portfolio. ### Method GET ### Endpoint `/api/v1/portfolios/fee-rates` ### Authentication Requires API key authentication (closed lock icon). ``` -------------------------------- ### getAllProductVolume() Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves volume summary for all products. This endpoint does not require authentication. ```APIDOC ## GET /products/volume-summary ### Description Retrieves volume summary for all products. ### Method GET ### Endpoint `/products/volume-summary` ``` -------------------------------- ### GET /api/v1/portfolios/fills Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves fills across all portfolios. This endpoint requires authentication. ```APIDOC ## GET /api/v1/portfolios/fills ### Description Retrieves fills across all portfolios. ### Method GET ### Endpoint `/api/v1/portfolios/fills` ### Authentication Requires API key authentication (closed lock icon). ``` -------------------------------- ### Instantiate CBAdvancedTradeClient with options Source: https://github.com/sieblyio/coinbase-api Example of creating a CBAdvancedTradeClient with API credentials, keepAlive enabled, and a custom timeout. Requires apiKey and apiSecret to be set. ```javascript import { CBAdvancedTradeClient } from 'coinbase-api'; const client = new CBAdvancedTradeClient( { apiKey, apiSecret, keepAlive: true, keepAliveMsecs: 2000 }, { timeout: 30000 }, ); ``` -------------------------------- ### HTTP/HTTPS proxy with REST and WebSockets Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/COINBASE_SDK_QUICKSTART_GUIDE.md Configure a proxy for both REST API and WebSocket clients. Requires COINBASE_PROXY_URL environment variable. Uses HttpsProxyAgent and sets proxy: false to avoid double proxy. ```javascript import { HttpsProxyAgent } from 'https-proxy-agent'; import { CBAdvancedTradeClient, WebsocketClient, WS_KEY_MAP, } from 'coinbase-api'; async function main() { if (!process.env.COINBASE_PROXY_URL) { console.error('Set COINBASE_PROXY_URL.'); return; } const proxyAgent = new HttpsProxyAgent(process.env.COINBASE_PROXY_URL); const rest = new CBAdvancedTradeClient( {}, { httpsAgent: proxyAgent, proxy: false, }, ); const ws = new WebsocketClient({ wsOptions: { agent: proxyAgent, }, }); try { const serverTime = await rest.getServerTime(); console.log('REST API through proxy:', serverTime.iso); } catch (error) { console.error('Proxied REST API request failed:', error); } ws.on('open', ({ wsKey }) => { console.log('Proxied WebSocket opened:', wsKey); }); ws.on('response', (response) => { console.log( 'Proxied WebSocket response:', response.wsKey, response.channel, ); }); ws.on('update', (update) => { console.log( 'Proxied WebSocket update:', update.wsKey, update.channel, update.events, ); }); ws.on('exception', (error) => { console.error('Proxied WebSocket exception:', error); }); ws.subscribe( { topic: 'ticker', payload: { product_ids: ['BTC-USD'], }, }, WS_KEY_MAP.advTradeMarketData, ); ws.subscribe('heartbeats', WS_KEY_MAP.advTradeMarketData); process.once('SIGINT', () => { ws.closeAll(); }); } main(); ``` -------------------------------- ### GET /api/v1/instruments Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves a list of all trading instruments. This endpoint does not require authentication. ```APIDOC ## GET /api/v1/instruments ### Description Retrieves a list of all trading instruments. ### Method GET ### Endpoint /api/v1/instruments ### Response #### Success Response (200) - **instruments** (array) - List of instrument objects. ``` -------------------------------- ### GET /travel-rules Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves travel rule information. This endpoint requires authentication. ```APIDOC ## GET /travel-rules ### Description Retrieves travel rule information. This endpoint requires authentication. ### Method GET ### Endpoint `/travel-rules` ``` -------------------------------- ### POST /orders Source: https://github.com/sieblyio/coinbase-api/blob/master/README.md Place an order. The side becomes the method, such as submitBuy() or submitSell(). ```APIDOC ## POST /orders ### Description Place an order. The side becomes the method, such as submitBuy() or submitSell(). ### Method POST ### Endpoint /orders ``` -------------------------------- ### subscribe usage examples Source: https://github.com/sieblyio/coinbase-api Shows three ways to subscribe: with a plain string topic, with a topic object containing payload for Advanced Trade/App style, and with multiple global derivative channels in one call. ```javascript // string topic client.subscribe('heartbeats', 'advTradeMarketData'); // topic with params (Advanced Trade / App style) client.subscribe( { topic: 'ticker', payload: { product_ids: ['ETH-USD', 'BTC-USD'] } }, 'advTradeMarketData', ); // multiple global derivative channels in one call client.subscribe( ['quote.BTC-PERPETUAL', 'ticker.BTC-PERPETUAL.100ms'], WS_KEY_MAP.advTradeGlobalMarketData, ); ``` -------------------------------- ### GET /profiles/{profile_id} Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves a profile by its ID. This endpoint requires authentication. ```APIDOC ## GET /profiles/{profile_id} ### Description Retrieves a profile by its ID. This endpoint requires authentication. ### Method GET ### Endpoint `/profiles/{profile_id}` ### Parameters #### Path Parameters - **profile_id** - Required - The ID of the profile to retrieve. ``` -------------------------------- ### GET /v2/accounts Source: https://github.com/sieblyio/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves all accounts for the authenticated user. This endpoint requires authentication. ```APIDOC ## GET /v2/accounts ### Description Retrieves all accounts for the authenticated user. ### Method GET ### Endpoint /v2/accounts ### Authentication Required ```