### Execute WebSocket Public Example with ts-node Source: https://github.com/tiagosiebler/coinbase-api/blob/master/examples/README.md Run the WebSocket public example script using ts-node. Ensure ts-node is installed. ```bash ts-node ./examples/ws-public.ts ``` -------------------------------- ### Execute Spot Get Tickers Example with Node.js Source: https://github.com/tiagosiebler/coinbase-api/blob/master/examples/README.md Run the spot get tickers example script using Node.js after renaming the file to .js. This works for minimal TypeScript examples. ```bash node ./examples/spot/getTickers.js ``` -------------------------------- ### Install coinbase-api Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Install the coinbase-api package using npm. ```bash npm install coinbase-api ``` -------------------------------- ### Coinbase Commerce API Operations with CBCommerceClient Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt This example demonstrates creating charges, retrieving charges, listing all charges, creating checkouts, retrieving checkouts, listing all checkouts, listing webhook events, and getting specific event details. Ensure you have your Commerce API key configured. ```typescript import { CBCommerceClient } from 'coinbase-api'; const client = new CBCommerceClient({ apiKey: 'your-commerce-api-key', }); async function commerceExamples() { try { // Create a charge (fixed price) const charge = await client.createCharge({ local_price: { amount: '9.99', currency: 'USD' }, pricing_type: 'fixed_price', redirect_url: 'https://example.com/success', cancel_url: 'https://example.com/cancel', metadata: { customer_id: 'user-123', order_id: 'order-456' }, }); console.log('Charge created:', charge); console.log('Pay with this URL:', charge.data?.hosted_url); // Retrieve a charge by code or ID const fetchedCharge = await client.getCharge({ charge_code_or_charge_id: charge.data?.code, }); console.log('Charge details:', fetchedCharge); // List all charges const allCharges = await client.getAllCharges(); console.log('All charges:', allCharges); // Create a checkout (reusable payment page) const checkout = await client.createCheckout({ total_price: { amount: '49.99', currency: 'USD' }, pricing_type: 'fixed_price', requested_info: ['email', 'name'], metadata: { product_id: 'premium-plan' }, }); console.log('Checkout created:', checkout); // Get a specific checkout session const fetchedCheckout = await client.getCheckout({ checkout_id: checkout.data?.id, }); console.log('Checkout details:', fetchedCheckout); // List all checkout sessions const allCheckouts = await client.getAllCheckouts(); console.log('All checkouts:', allCheckouts); // List webhook events const events = await client.listEvents({ 'X-CC-Version': '2018-03-22' }); console.log('Events:', events); // Get a specific event const event = await client.showEvent( { event_id: 'event-uuid' }, { 'X-CC-Version': '2018-03-22' }, ); console.log('Event details:', event); } catch (e) { console.error('Error:', e); } } commerceExamples(); ``` -------------------------------- ### Get Products Source: https://github.com/tiagosiebler/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves a list of available products on the exchange. ```APIDOC ## GET /api/v3/brokerage/products ### Description Retrieves a list of available products on the exchange. ### Method GET ### Endpoint /api/v3/brokerage/products ### Authentication Requires authentication. ### Response #### Success Response (200) - Returns a list of product objects. ``` -------------------------------- ### CBAdvancedTradeClient - Get Accounts Source: https://github.com/tiagosiebler/coinbase-api/blob/master/README.md Demonstrates how to initialize the CBAdvancedTradeClient and retrieve account information. ```APIDOC ## CBAdvancedTradeClient - Get Accounts ### Description Initializes the `CBAdvancedTradeClient` with API credentials and retrieves a list of accounts associated with the API key. ### Method `getAccounts()` ### Parameters None ### Request Example ```javascript const { CBAdvancedTradeClient } = require('coinbase-api'); const advancedTradeCdpAPIKey = { 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' }; const client = new CBAdvancedTradeClient({ apiKey: advancedTradeCdpAPIKey.name, apiSecret: advancedTradeCdpAPIKey.privateKey }); async function doAPICall() { try { const accounts = await client.getAccounts(); console.log('Get accounts result: ', accounts); } catch (e) { console.error('Exception: ', JSON.stringify(e)); } } doAPICall(); ``` ### Response #### Success Response (200) - **accounts** (array) - A list of account objects. #### Response Example ```json { "accounts": [ { "id": "account_id_1", "currency": "BTC", "balance": { "amount": "1.0", "currency": "BTC" } }, { "id": "account_id_2", "currency": "USD", "balance": { "amount": "100.0", "currency": "USD" } } ] } ``` ``` -------------------------------- ### getProductStats Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Gets 30-day and 24-hour stats for a product. ```APIDOC ## GET /products/{product_id}/stats ### Description Retrieves the 30-day and 24-hour statistics for a specific trading product. ### Method GET ### Endpoint /products/{product_id}/stats ### Parameters #### Path Parameters - **product_id** (string) - Required - The unique identifier of the product. #### Query Parameters - **params** (optional) - Parameters for retrieving product statistics. ``` -------------------------------- ### getAllProductVolume Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Gets 30-day and 24-hour volume for all products and market types. ```APIDOC ## GET /products/volume ### Description Retrieves the 30-day and 24-hour trading volume for all available products and market types. ### Method GET ### Endpoint /products/volume ### Response #### Success Response (200) - **any** - Volume data for all products. ``` -------------------------------- ### Get Wallet Deposit Instructions Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Retrieves deposit instructions for a specific wallet. ```APIDOC ## Get Wallet Deposit Instructions ### Description Retrieves deposit instructions for a specific wallet. ### Method `client.getWalletDepositInstructions(params)` ### Endpoint GET /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 - **deposit_type** (string) - Required - The type of deposit (e.g., 'CRYPTO'). ### Response #### Success Response (200) - **depositInstructions** (object) - An object containing deposit instructions. ### Request Example ```typescript const depositInstructions = await client.getWalletDepositInstructions({ portfolio_id: 'your-portfolio-id', wallet_id: 'your-wallet-id', deposit_type: 'CRYPTO', }); console.log('Deposit instructions:', depositInstructions); ``` ``` -------------------------------- ### Get All Conversions Source: https://github.com/tiagosiebler/coinbase-api/blob/master/docs/endpointFunctionList.md Retrieves a list of all currency conversions. Requires authentication. ```APIDOC ## GET /conversions ### Description Retrieves a list of all currency conversions performed by the user. ### Method GET ### Endpoint /conversions ### Parameters None ### Request Example None ### Response #### Success Response (200) - **conversions** (array) - A list of conversion objects. #### Response Example ```json { "conversions": [ { "id": "string", "from_account_id": "string", "to_account_id": "string", "amount": { "amount": "string", "currency": "string" }, "total_fees": { "amount": "string", "currency": "string" }, "status": "string", "created_at": "string", "completed_at": "string", "unit_price": { "amount": "string", "currency": "string" }, "amount_received": { "amount": "string", "currency": "string" } } ] } ``` ``` -------------------------------- ### Get All Orders using CBAdvancedTradeClient Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Use this to retrieve all orders. Ensure the client is initialized. ```typescript async function getOrders() // Get all orders ``` -------------------------------- ### Get All Wrapped Assets Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Retrieves a list of all supported wrapped assets and their details. No specific setup is required beyond API authentication. ```typescript getAllWrappedAssets(): Promise ``` -------------------------------- ### CBAdvancedTradeClient Initialization with RestClientOptions Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Demonstrates how to initialize the CBAdvancedTradeClient with different authentication methods and optional configurations like sandbox mode, proxy, and custom base URLs. ```APIDOC ## CBAdvancedTradeClient Initialization ### Description Initialize the `CBAdvancedTradeClient` with `RestClientOptions` to configure authentication, sandbox mode, proxy settings, and other client-specific options. ### Method `new CBAdvancedTradeClient(options, axiosConfig)` ### Parameters #### `options` (RestClientOptions) - **apiKey** (string) - Required - Your API key. - **apiSecret** (string) - Required - Your private API key or Base64 encoded ED25519 secret. - **cdpApiKey** (object) - Optional - An object containing `name` and `privateKey` for CDP API keys. - **apiPassphrase** (string) - Optional - Passphrase for Exchange, INTX, and Prime clients. - **useSandbox** (boolean) - Optional - Set to `true` to use the sandbox environment (supported for Exchange and INTX only). - **baseUrl** (string) - Optional - Customize the base URL for the API. #### `axiosConfig` (object) - **timeout** (number) - Optional - Request timeout in milliseconds. - **proxy** (object) - Optional - Proxy configuration for requests. - **host** (string) - Required - Proxy host. - **port** (number) - Required - Proxy port. ### Request Example ```typescript import { CBAdvancedTradeClient } from 'coinbase-api'; const client = new CBAdvancedTradeClient( { apiKey: 'organizations/org-id/apiKeys/key-id', apiSecret: '-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n', useSandbox: true, baseUrl: 'https://custom-proxy.example.com', }, { timeout: 10000, proxy: { host: '127.0.0.1', port: 8080, }, } ); ``` ``` -------------------------------- ### Get Product Candles (OHLCV) Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Retrieves historical candle (Open, High, Low, Close, Volume) data for a given product ID and time range. Requires start and end timestamps and a granularity. ```typescript // Get product candles (OHLCV) const candles = await client.getProductCandles({ product_id: 'BTC-USD', start: '1700000000', end: '1700003600', granularity: 'ONE_HOUR', }); console.log('Candles:', candles.candles); ``` -------------------------------- ### Get Prime Portfolio Fills Request Interface Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Defines the structure for retrieving portfolio fills from the Coinbase Prime API. Requires portfolio ID and start date, with optional end date, limit, and sort direction. ```typescript export interface GetPrimePortfolioFillsRequest { portfolio_id: string; start_date: string; end_date?: string; limit?: number; cursor?: string; sort_direction?: 'DESC' | 'ASC'; } ``` -------------------------------- ### Configure Coinbase REST Client with Options Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Demonstrates how to initialize a CBAdvancedTradeClient with various configuration options including API keys, sandbox mode, and custom base URLs. It also shows how to use utility functions for generating order IDs and fetching latency information. ```typescript import { CBAdvancedTradeClient } from 'coinbase-api'; // Full configuration example const client = new CBAdvancedTradeClient( { // Option 1: separate key name + private key apiKey: 'organizations/org-id/apiKeys/key-id', apiSecret: '-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n', // Option 2: ED25519 keys // apiKey: 'your-ed25519-key-id', // apiSecret: 'yourBase64EncodedEd25519SecretKey==', // Option 3: pass the downloaded cdp_api_key.json as an object // cdpApiKey: { name: '...', privateKey: '...' }, // For Exchange, INTX, and Prime clients only: // apiPassphrase: 'your-passphrase', // Connect to sandbox (supported for Exchange and INTX only) // useSandbox: true, // Optional: customize the base URL // baseUrl: 'https://custom-proxy.example.com', }, // Optional axios config: e.g., proxy, timeout, headers { timeout: 10000, proxy: { host: '127.0.0.1', port: 8080, }, }, ); // Utility: generate a unique client order ID (nanoid-based) const orderId = client.generateNewOrderId(); console.log('Generated order ID:', orderId); // Utility: measure latency and clock drift to Coinbase servers const latencyInfo = await client.fetchLatencySummary(); // Output: // { // localTime: 1700000000000, // serverTime: 1700000000010, // roundTripTime: 45, // estimatedOneWayLatency: 22, // adjustedServerTime: 1700000000032, // timeDifference: 32 // } ``` -------------------------------- ### Initialize CBAppClient and perform various operations Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Demonstrates initializing the CBAppClient with API keys and performing common operations like listing accounts, creating addresses, sending/transferring crypto, managing fiat deposits/withdrawals, fetching prices, and getting server time. Ensure your API keys are correctly configured and account/payment method IDs are valid. ```typescript import { CBAppClient } from 'coinbase-api'; const client = new CBAppClient({ apiKey: 'organizations/your-org-id/apiKeys/your-key-id', apiSecret: '-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n', }); async function appClientExamples() { try { // List accounts (paginated) const accountsPage1 = await client.getAccounts(); console.log('Accounts:', accountsPage1.data); // Get next page using pagination URL if (accountsPage1.pagination?.next_uri) { const accountsPage2 = await client.getAccounts({ paginationURL: accountsPage1.pagination.next_uri, }); console.log('Page 2:', accountsPage2.data); } // Show a single account by ID or currency string (e.g., 'BTC') const btcAccount = await client.getAccount({ account_id: 'BTC' }); console.log('BTC account:', btcAccount.data); // Create a crypto receive address for an account const newAddress = await client.createAddress({ account_id: 'your-account-uuid', name: 'My BTC Deposit Address', }); console.log('New address:', newAddress.data); // Send crypto to an external address const sendResult = await client.sendMoney({ account_id: 'your-btc-account-uuid', type: 'send', to: '1A1zP1eP5QGefi2DMPTfTL5SLmv7Divf2', // Bitcoin address amount: '0.001', currency: 'BTC', description: 'Payment for services', idem: 'unique-idempotency-key-123', // Prevents duplicate sends }); console.log('Send result:', sendResult.data); // Transfer crypto between own accounts const transferResult = await client.transferMoney({ account_id: 'source-account-uuid', type: 'transfer', to: 'destination-account-uuid', amount: '0.01', currency: 'BTC', }); console.log('Transfer result:', transferResult.data); // Deposit fiat funds (two-step: create then commit) const deposit = await client.depositFunds({ account_id: 'your-fiat-account-uuid', amount: '100', currency: 'USD', payment_method: 'payment-method-uuid', commit: false, }); const committedDeposit = await client.commitDeposit({ account_id: 'your-fiat-account-uuid', deposit_id: deposit.data.id, }); console.log('Deposit committed:', committedDeposit); // Withdraw fiat funds const withdrawal = await client.withdrawFunds({ account_id: 'your-fiat-account-uuid', amount: '50', currency: 'USD', payment_method: 'payment-method-uuid', commit: true, }); console.log('Withdrawal:', withdrawal); // Get spot price for BTC-USD const spot = await client.getSpotPrice({ currencyPair: 'BTC-USD' }); console.log('BTC spot price:', spot.data.amount, spot.data.currency); // Get buy and sell prices const buyPrice = await client.getBuyPrice({ currencyPair: 'ETH-USD' }); const sellPrice = await client.getSellPrice({ currencyPair: 'ETH-USD' }); console.log('ETH Buy:', buyPrice.data.amount, '| Sell:', sellPrice.data.amount); // Get exchange rates (base: USD) const rates = await client.getExchangeRates({ currency: 'USD' }); console.log('BTC rate:', rates.data.rates['BTC']); // List all known cryptocurrencies const cryptos = await client.getCryptocurrencies(); console.log('Cryptocurrencies count:', cryptos.length); // Server time const time = await client.getCurrentTime(); console.log('Server time:', time.data.iso); } catch (e) { console.error('Error:', e); } } appClientExamples(); ``` -------------------------------- ### CBAdvancedTradeClient Initialization Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Demonstrates how to initialize the CBAdvancedTradeClient with API credentials. ```APIDOC ## CBAdvancedTradeClient Initialization ### Description Initialize the client with your API key and secret. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **apiKey** (string) - Required - Your Coinbase API key. - **apiSecret** (string) - Required - Your Coinbase API secret. - **cdpApiKey** (object) - Optional - An object containing the API key name and private key. - **name** (string) - Required - The name of the API key. - **privateKey** (string) - Required - The private key associated with the API key. ### Request Example ```typescript import { CBAdvancedTradeClient } from 'coinbase-api'; const client = new CBAdvancedTradeClient({ apiKey: 'organizations/your-org-id/apiKeys/your-key-id', apiSecret: '-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n', // Or pass the full exported JSON object: // cdpApiKey: { name: '...', privateKey: '...' } }); ``` ### Response None (Client initialization does not return a response). ``` -------------------------------- ### Get Single Order Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Get a single order by id. ```APIDOC ## GET /orders/{order_id} ### Description Get a single order by id. ### Method GET ### Endpoint /orders/{order_id} ### Parameters #### Path Parameters - **order_id** (string) - Required - The ID of the order to retrieve. ``` -------------------------------- ### Initialize CBPrimeClient and Perform Prime Operations Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Demonstrates how to initialize the CBPrimeClient with API credentials and perform various operations including listing portfolios, checking buying power, managing balances, submitting orders, and handling wallets. Ensure you replace placeholder values with your actual API keys and IDs. ```typescript import { CBPrimeClient } from 'coinbase-api'; const client = new CBPrimeClient({ apiKey: 'your-prime-api-key', apiSecret: 'your-prime-api-secret', apiPassphrase: 'your-prime-passphrase', }); async function primeExamples() { try { // List all portfolios const portfolios = await client.getPortfolios(); console.log('Portfolios:', portfolios); // Get portfolio buying power const buyingPower = await client.getPortfolioBuyingPower({ portfolio_id: 'your-portfolio-id', symbol: 'BTC', side: 'BUY', }); console.log('Buying power:', buyingPower); // Get portfolio balances const balances = await client.getPortfolioBalances({ portfolio_id: 'your-portfolio-id', }); console.log('Balances:', balances); // List open orders const openOrders = await client.getOpenOrders({ portfolio_id: 'your-portfolio-id', }); console.log('Open orders:', openOrders); // Preview an order const preview = await client.getOrderPreview({ portfolio_id: 'your-portfolio-id', product_id: 'BTC-USD', side: 'BUY', type: 'MARKET', quote_value: '1000', }); console.log('Order preview:', preview); // Submit an order const order = await client.submitOrder({ portfolio_id: 'your-portfolio-id', product_id: 'BTC-USD', side: 'BUY', type: 'MARKET', quote_value: '1000', client_order_id: 'my-order-id', }); console.log('Submitted order:', order); // List wallets for the portfolio const wallets = await client.getPortfolioWallets({ portfolio_id: 'your-portfolio-id', type: 'VAULT', }); console.log('Wallets:', wallets); // Create a new wallet const newWallet = await client.createWallet({ portfolio_id: 'your-portfolio-id', symbol: 'BTC', wallet_type: 'VAULT', }); console.log('New wallet:', newWallet); // Get deposit instructions for a wallet const depositInstructions = await client.getWalletDepositInstructions({ portfolio_id: 'your-portfolio-id', wallet_id: 'your-wallet-id', deposit_type: 'CRYPTO', }); console.log('Deposit instructions:', depositInstructions); // Create a withdrawal const withdrawal = await client.createWithdrawal({ portfolio_id: 'your-portfolio-id', wallet_id: 'source-wallet-id', amount: '0.1', destination_type: 'DESTINATION_BLOCKCHAIN', blockchain_address: { address: '0xYourDestAddress' }, idempotency_key: 'unique-withdrawal-key', currency_symbol: 'ETH', }); console.log('Withdrawal:', withdrawal); // List portfolio activities const activities = await client.getActivities({ portfolio_id: 'your-portfolio-id', page_size: 25, }); console.log('Activities:', activities); // Get invoices for the entity const invoices = await client.getInvoices({ entity_id: 'your-entity-id', states: ['UNPAID'], }); console.log('Invoices:', invoices); } catch (e) { console.error('Error:', e); } } primeExamples(); ``` -------------------------------- ### Get Product Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Retrieves detailed information about a single product using its product ID. ```APIDOC ## GET /products/{product_id} ### Description Get information on a single product by product ID. ### Method GET ### Endpoint /products/{product_id} ### Parameters #### Query Parameters - **get_tradability_status** (boolean) - Optional - Whether to include tradability status. #### Path Parameters - **product_id** (string) - Required - The ID of the product. ``` -------------------------------- ### Public GET Request Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Makes a public GET request to a specified endpoint with optional parameters. ```APIDOC ## GET /endpoint ### Description Makes a public GET request to a specified endpoint. ### Method GET ### Endpoint /endpoint ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters to be sent with the request. ``` -------------------------------- ### Initialize CBAppClient in JavaScript Source: https://github.com/tiagosiebler/coinbase-api/blob/master/README.md Shows how to set up the CBAppClient for application-specific tasks, including transferring money between accounts. Requires API keys and specifies the type of transfer. ```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 Entity Payment Method Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Gets payment method details by ID for a given entity. ```APIDOC ## GET /entities/:entity_id/payment_methods/:payment_method_id ### Description Get payment method details by id for a given entity. ### Method GET ### Endpoint /entities/:entity_id/payment_methods/:payment_method_id ### Parameters #### Path Parameters - **entity_id** (string) - Required - The ID of the entity. - **payment_method_id** (string) - Required - The ID of the payment method. ``` -------------------------------- ### WebsocketClient Initialization and Event Handling Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Demonstrates how to initialize the WebsocketClient with API credentials and set up event handlers for connection status, data updates, and errors. ```APIDOC ## WebsocketClient Initialization and Event Handling ### Description Initialize the `WebsocketClient` with your API credentials and configure event listeners to manage connection states and data streams. ### Usage ```typescript import { WebsocketClient, WS_KEY_MAP, DefaultLogger } from 'coinbase-api'; // Optional: Configure a custom logger to filter out specific trace messages const logger = { ...DefaultLogger, trace: (...params: unknown[]) => { if (['Sending ping', 'Received pong, clearing pong timer'].includes(params[0] as string)) return; console.log('trace', params); }, }; // Initialize the client with API credentials and logger const wsClient = new WebsocketClient( { apiKey: 'organizations/your-org-id/apiKeys/your-key-id', apiSecret: '-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n', // For Exchange/INTX/Prime, use: apiKey, apiSecret, apiPassphrase }, logger, ); // --- Event Handlers --- wsClient.on('open', ({ wsKey }) => console.log('Connected:', wsKey)); wsClient.on('update', (data) => console.info('Market update:', JSON.stringify(data))); wsClient.on('response', (data) => console.info('Response:', JSON.stringify(data, null, 2))); wsClient.on('reconnect', (data) => console.warn('Reconnecting...', data)); wsClient.on('reconnected', (data) => console.log('Reconnected:', data)); wsClient.on('close', (data) => console.error('Connection closed:', data)); wsClient.on('exception', (data) => console.error('Exception:', data)); ``` ``` -------------------------------- ### Get Entity Locate Availabilities Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Gets currencies available to be located with their corresponding amount and rate. ```APIDOC ## GET /entities/:entity_id/locate_availabilities ### Description Get currencies available to be located with their corresponding amount and rate. ### Method GET ### Endpoint /entities/:entity_id/locate_availabilities ### Parameters #### Path Parameters - **entity_id** (string) - Required - The ID of the entity. #### Query Parameters - **params** (GetPrimeEntityLocateAvailabilitiesRequest) - Required - Parameters for retrieving entity locate availabilities. ``` -------------------------------- ### Connecting All WebSocket Feeds Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Shows how to initiate connections to all configured WebSocket feeds simultaneously using `connectAll`. ```APIDOC ## Connecting All WebSocket Feeds ### Description Eagerly connect to all WebSocket feeds that have been subscribed to. This method returns a promise that resolves with the results of the connection attempts. ### Usage ```typescript wsClient.connectAll().then((results) => { console.log('All connections initiated:', results.length); }); ``` ``` -------------------------------- ### HTTP GET Request Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Makes a public HTTP GET request to a specified endpoint with optional parameters. ```typescript get(endpoint: string, params?: object) ``` -------------------------------- ### Get All Wrapped Assets Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Retrieves a list of all supported wrapped assets, including their details. ```APIDOC ## GET /wrapped_assets ### Description Returns a list of all supported wrapped assets details objects. ### Method GET ### Endpoint /wrapped_assets ### Response #### Success Response (200) - **data** (array) - List of wrapped asset objects. ### Response Example { "data": [ { "id": "string", "asset": "string", "blockchain": "string", "symbol": "string", "name": "string", "decimals": 0, "logo_url": "string" } ] } ``` -------------------------------- ### Initialize CBExchangeClient and Perform Exchange Operations Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Demonstrates initializing the CBExchangeClient with API credentials and executing various API calls such as fetching accounts, ledger activity, trading pairs, order books, candles, submitting and managing orders, retrieving fills, fees, performing deposits and conversions, generating crypto addresses, and fetching oracle prices. Requires API key, secret, and passphrase. Sandbox mode can be enabled. ```typescript import { CBExchangeClient } from 'coinbase-api'; const client = new CBExchangeClient({ apiKey: 'your-exchange-api-key', apiSecret: 'your-exchange-api-secret', apiPassphrase: 'your-api-passphrase', // set when creating the key // useSandbox: true, // connect to https://api-public.sandbox.exchange.coinbase.com }); async function exchangeExamples() { try { // Get all trading accounts const accounts = await client.getAccounts(); console.log('Accounts:', accounts); // Get ledger activity for an account const ledger = await client.getAccountLedger({ account_id: 'your-account-id', start_date: '2024-01-01T00:00:00Z', end_date: '2024-12-31T23:59:59Z', }); console.log('Ledger:', ledger); // List all available trading pairs const products = await client.getAllTradingPairs(); console.log('Products:', products); // Get order book depth (level 2) const book = await client.getProductBook({ product_id: 'BTC-USD', level: 2 }); console.log('Order book:', book); // Get product candles (OHLCV) const candles = await client.getProductCandles({ product_id: 'ETH-USD', start: '2024-01-01T00:00:00Z', end: '2024-01-02T00:00:00Z', granularity: 3600, }); console.log('Candles:', candles); // Submit a limit order const order = await client.submitOrder({ product_id: 'BTC-USD', side: 'buy', type: 'limit', price: '45000', size: '0.001', }); console.log('Order submitted:', order); // Get a specific order const fetchedOrder = await client.getOrder({ order_id: order.id }); console.log('Order details:', fetchedOrder); // Cancel an order const cancelled = await client.cancelOrder({ order_id: order.id, product_id: 'BTC-USD', }); console.log('Cancelled:', cancelled); // Get recent fills const fills = await client.getFills({ product_id: 'BTC-USD', limit: 25 }); console.log('Fills:', fills); // Get current maker/taker fees const fees = await client.getFees(); console.log('Fees:', fees); // Deposit from a linked Coinbase wallet const deposit = await client.depositFromCoinbaseAccount({ amount: '100', currency: 'USD', coinbase_account_id: 'your-coinbase-account-uuid', }); console.log('Deposit:', deposit); // Convert USD to USDC const conversion = await client.convertCurrency({ from: 'USD', to: 'USDC', amount: '100', }); console.log('Conversion:', conversion); // Generate a crypto deposit address const cryptoAddress = await client.createNewCryptoAddress({ account_id: 'your-coinbase-wallet-id', }); console.log('Crypto address:', cryptoAddress); // Get signed oracle prices (on-chain ready) const oracle = await client.getSignedPrices(); console.log('Oracle prices:', oracle); } catch (e) { console.error('Error:', JSON.stringify(e, null, 2)); } } exchangeExamples(); ``` -------------------------------- ### Get Fee Estimate for Crypto Withdrawal Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Gets the fee estimate for a crypto withdrawal to a crypto address. ```APIDOC ## GET /fees/crypto/withdrawal ### Description Gets the fee estimate for the crypto withdrawal to a crypto address. ### Method GET ### Endpoint /fees/crypto/withdrawal ### Parameters #### Query Parameters - **currency** (string) - Required - The currency to withdraw. - **address** (string) - Required - The destination address. - **amount** (string) - Required - The amount to withdraw. - **network_code** (string) - Optional - The network code for the withdrawal. ``` -------------------------------- ### Get Margin Information Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Gets real-time evaluation of the margin model based on current positions and spot rates. ```APIDOC ## GET /entities/:entity_id/margin ### Description Gets real-time evaluation of the margin model based on current positions and spot rates. ### Method GET ### Endpoint /entities/:entity_id/margin ### Parameters #### Path Parameters - **entity_id** (string) - Required - The ID of the entity. #### Query Parameters - **params** (any) - Required - Parameters for retrieving entity margin information. ``` -------------------------------- ### Initialize CBInternationalClient in JavaScript Source: https://github.com/tiagosiebler/coinbase-api/blob/master/README.md Demonstrates initializing the CBInternationalClient for international trading operations. Requires API key, secret, and passphrase. Includes an option to use the sandbox environment. ```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(); ``` -------------------------------- ### Private GET Request Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Makes a private GET request to a specified endpoint with optional parameters. These requests are automatically signed. ```APIDOC ## GET /endpoint (Private) ### Description Makes a private GET request to a specified endpoint. The request is automatically signed. ### Method GET ### Endpoint /endpoint ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters to be sent with the request. ``` -------------------------------- ### CBPrimeClient Initialization Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Initializes the CBPrimeClient with API credentials. ```APIDOC ## CBPrimeClient Initialization ### Description Initializes the CBPrimeClient with your Coinbase Prime API credentials. ### Method Constructor ### Parameters - **apiKey** (string) - Required - Your Coinbase Prime API key. - **apiSecret** (string) - Required - Your Coinbase Prime API secret. - **apiPassphrase** (string) - Required - Your Coinbase Prime API passphrase. ### Request Example ```typescript import { CBPrimeClient } from 'coinbase-api'; const client = new CBPrimeClient({ apiKey: 'your-prime-api-key', apiSecret: 'your-prime-api-secret', apiPassphrase: 'your-prime-passphrase', }); ``` ``` -------------------------------- ### Private GET Request Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Makes a private HTTP GET request to a specified endpoint. Private endpoints are automatically signed. ```typescript getPrivate(endpoint: string, params?: object) ``` -------------------------------- ### Initialize CBInternationalClient Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Instantiate the client with API credentials. Optionally enable the sandbox environment for testing. ```typescript import { CBInternationalClient } from 'coinbase-api'; const client = new CBInternationalClient({ apiKey: 'your-intx-api-key', apiSecret: 'your-intx-api-secret', apiPassphrase: 'your-intx-passphrase', // useSandbox: true, // connects to https://api-n5e1.coinbase.com }); ``` -------------------------------- ### Get Account Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Get information about a single account using its UUID. It is recommended to use the List Accounts function to find account UUIDs. ```APIDOC ## GET /api/v3/brokerage/accounts/{accountId} ### Description Get a list of information about single account, given an account UUID. Tip: Use List Accounts (getAccounts funcion) to find account UUIDs. ### Method GET ### Endpoint /api/v3/brokerage/accounts/{accountId} ### Parameters #### Path Parameters - **accountId** (string) - Required - The UUID of the account to retrieve. ``` -------------------------------- ### Get Lending Overview Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt This API summarizes lending for a given client. It calculates the overall loan balance, collateral level, and amounts available to borrow. It also returns any withdrawal restrictions in force on the client. Get lending overview returns all amounts in USD notional values, except available_per_asset mappings which are returned in both notional and native values. ```APIDOC ## GET /lending-overview ### Description This API summarizes lending for a given client. It calculates the overall loan balance, collateral level, and amounts available to borrow. It also returns any withdrawal restrictions in force on the client. Get lending overview returns all amounts in USD notional values, except available_per_asset mappings which are returned in both notional and native values. ### Method GET ### Endpoint /lending-overview ``` -------------------------------- ### Get All Fills Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Get a list of recent fills of the API key's profile. A fill is a partial or complete match on a specific order. ```APIDOC ## GET /fills ### Description Get a list of recent fills of the API key's profile. A fill is a partial or complete match on a specific order. ### Method GET ### Endpoint /fills ### Parameters #### Query Parameters - **order_id** (string) - Optional - If specified, returns fills for the order. - **product_id** (string) - Optional - If specified, returns fills for the product. - **start_date** (string) - Optional - If specified, returns fills on or after this date. - **end_date** (string) - Optional - If specified, returns fills on or before this date. - **limit** (string) - Optional - Maximum number of fills to return. ``` -------------------------------- ### Get Trade Finance Tiered Pricing Fees Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Gets trade finance tiered pricing fees for a given entity at a specific time, defaulting to the current time. ```APIDOC ## GET /entities/:entity_id/tf_tiered_fees ### Description Get trade finance tiered pricing fees for a given entity at a specific time, default to current time. ### Method GET ### Endpoint /entities/:entity_id/tf_tiered_fees ### Parameters #### Path Parameters - **entity_id** (string) - Required - The ID of the entity. #### Query Parameters - **params** (GetPrimeEntityTFTieredFeesRequest) - Required - Parameters for retrieving entity tiered fees. ``` -------------------------------- ### CBAppClient Initialization Source: https://context7.com/tiagosiebler/coinbase-api/llms.txt Initialize the CBAppClient with your API keys. Ensure your API secret is correctly formatted as a private key. ```APIDOC ## CBAppClient Initialization ### Description Initialize the CBAppClient with your API keys. Ensure your API secret is correctly formatted as a private key. ### Parameters #### Request Body - **apiKey** (string) - Required - Your Coinbase API key. - **apiSecret** (string) - Required - Your Coinbase API secret key, formatted as a private key. ### Request Example ```typescript import { CBAppClient } from 'coinbase-api'; const client = new CBAppClient({ apiKey: 'organizations/your-org-id/apiKeys/your-key-id', apiSecret: '-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n', }); ``` ``` -------------------------------- ### CBInternationalClient - Get Asset Details Source: https://github.com/tiagosiebler/coinbase-api/blob/master/README.md Demonstrates how to initialize the CBInternationalClient and retrieve details for a specific asset. ```APIDOC ## CBInternationalClient - Get Asset Details ### Description Initializes the `CBInternationalClient` with API credentials and retrieves detailed information about a specified asset. ### Method `getAssetDetails(params)` ### Parameters #### Request Body - **asset** (string) - Required - The symbol of the asset for which to retrieve details (e.g., 'BTC'). ### Request Example ```javascript const { CBInternationalClient } = require('coinbase-api'); const client = new CBInternationalClient({ apiKey: 'insert_api_key_here', apiSecret: 'insert_api_secret_here', apiPassphrase: 'insert_api_passphrase_here', // useSandbox: true, }); async function doAPICall() { try { const assetDetails = await client.getAssetDetails({ asset: 'BTC' }); console.log('Asset Details: ', assetDetails); } catch (e) { console.error('Exception: ', JSON.stringify(e, null, 2)); } } doAPICall(); ``` ### Response #### Success Response (200) - **asset_details** (object) - An object containing detailed information about the asset. #### Response Example ```json { "asset_details": { "symbol": "BTC", "name": "Bitcoin", "min_order_size": "0.00001", "max_order_size": "1000000" } } ``` ``` -------------------------------- ### Get Fees Source: https://github.com/tiagosiebler/coinbase-api/blob/master/llms.txt Get fee rates and 30 days trailing volume. This request returns your current maker & taker fee rates, as well as your 30-day trailing volume. Quoted rates are subject to change. ```APIDOC ## GET /fees ### Description Get fee rates and 30 days trailing volume. This request returns your current maker & taker fee rates, as well as your 30-day trailing volume. Quoted rates are subject to change. ### Method GET ### Endpoint /fees ```