### Full Quickstart Code Example Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-rest-api This snippet provides a comprehensive example of setting up the client, retrieving product information, placing a limit-buy order, and canceling it. It includes API key setup, price adjustment, order placement, and error handling. ```python # This is a summary of all the code for this tutorial from coinbase.rest import RESTClient from json import dumps import math api_key = "organizations/{org_id}/apiKeys/{key_id}" api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n" client = RESTClient(api_key=api_key, api_secret=api_secret) product = client.get_product("BTC-USD") btc_usd_price = float(product["price"]) adjusted_btc_usd_price = str(math.floor(btc_usd_price - (btc_usd_price * 0.05))) order = client.limit_order_gtc_buy( client_order_id="00000002", product_id="BTC-USD", base_size="0.0002", limit_price=adjusted_btc_usd_price ) if order['success']: order_id = order['success_response']['order_id'] client.cancel_orders(order_ids=[order_id]) else: error_response = order['error_response'] print(error_response) ``` -------------------------------- ### Simple GET Request Example Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/cors Demonstrates a simple GET request to fetch Bitcoin price data. Simple requests do not require a preflight request. ```javascript fetch("https://api.coinbase.com/v2/prices/BTC-USD/spot") .then((response) => response.json()) .then((data) => console.log(data)); ``` -------------------------------- ### Install the SDK Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-websocket Install the Coinbase Advanced API Python SDK using pip. ```bash pip3 install coinbase-advanced-py ``` -------------------------------- ### Response for Get Buy Price Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example JSON response structure for a successful buy price request, showing the amount and currency. ```json { "data": { "amount": "1020.25", "currency": "USD" } } ``` -------------------------------- ### Withdraw Funds Request Examples Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/withdraw-fiat Examples of how to initiate a fiat withdrawal using the Coinbase API. These examples demonstrate the request payload and authentication methods for different programming languages. ```shell curl https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/withdrawals \ -X POST \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' \ -d '{ "amount": "10", "currency": "USD", "payment_method": "83562370-3e5c-51db-87da-752af5ab9559" }' ``` ```ruby require 'coinbase/wallet' client = Coinbase::Wallet::Client.new(api_key: , api_secret: ) withdrawal = client.withdraw('2bbf394c-193b-5b2a-9155-3b4732659ede', {"amount" => "10", "currency" => "USD", "payment_method" => "83562370-3e5c-51db-87da-752af5ab9559"}) ``` ```python import requests # For instructions generating JWT, check the "API Key Authentication" section JWT_TOKEN = "" # Coinbase API base URL ENDPOINT_URL = "https://api.coinbase.com/v2/accounts/:account_id/withdrawals" def withdraw(): # Generate headers with JWT for authentication headers = { "Authorization": f"Bearer {JWT_TOKEN}" } data = { "amount": "10", "currency": "USD", "payment_method": "83562370-3e5c-51db-87da-752af5ab9559" } # Make the API request response = requests.post(ENDPOINT_URL, data=data, headers=headers) return response.json() # Return the JSON response withdraw = withdraw() print(withdraw) ``` ```javascript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getAccount('2bbf394c-193b-5b2a-9155-3b4732659ede', function(err, account) { account.withdraw({"amount": "10", "currency": "USD", "payment_method": "83562370-3e5c-51db-87da-752af5ab9559"}, function(err, tx) { console.log(tx); }); }); ``` -------------------------------- ### Install Python SDK Source: https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication Install the required package to use the Python SDK for JWT generation. ```shell pip3 install coinbase-advanced-py ``` -------------------------------- ### C++ Dependency Installation and Compilation Source: https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication Commands to install required libraries and compile the C++ application. ```bash apt-get update apt-get install libcurlpp-dev libssl-dev git clone https://github.com/Thalhammer/jwt-cpp cd jwt-cpp mkdir build && cd build cmake .. make make install ``` ```bash g++ main.cpp -o myapp -lcurlpp -lcurl -lssl -lcrypto -I/usr/local/include -L/usr/local/lib -ljwt -std=c++17 ``` ```bash export JWT=$(./myapp) ``` ```bash curl -H "Authorization: Bearer $JWT" 'https://api.coinbase.com/api/v3/brokerage/accounts' ``` -------------------------------- ### Response for Get Sell Price Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example JSON response for a successful sell price request, detailing the amount and currency. ```json { "data": { "amount": "1010.25", "currency": "USD" } } ``` -------------------------------- ### Show Account Request Examples Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/accounts Examples of how to request a specific user account using cURL, Ruby, Python, and JavaScript. Ensure you replace placeholders with your actual API credentials or JWT token. ```shell curl https://api.coinbase.com/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede \ -H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' ``` ```ruby require 'coinbase/wallet' client = Coinbase::Wallet::Client.new(api_key: , api_secret: ) account = client.account("2bbf394c-193b-5b2a-9155-3b4732659ede") ``` ```python import requests # For instructions generating JWT, check the "API Key Authentication" section JWT_TOKEN = "" # Coinbase API base URL ENDPOINT_URL = "https://api.coinbase.com/v2/accounts/:account_id" def get_account(): # Generate headers with JWT for authentication headers = { "Authorization": f"Bearer {JWT_TOKEN}" } # Make the API request response = requests.get(ENDPOINT_URL, headers=headers) return response.json() # Return the JSON response account = get_account() print(account) ``` ```javascript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getAccount("2bbf394c-193b-5b2a-9155-3b4732659ede", function(err, account) { console.log(account); }); ``` -------------------------------- ### Get Exchange Rates using Coinbase Wallet JavaScript Client Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/exchange-rates This example demonstrates fetching exchange rates for a specified currency using the Coinbase Wallet JavaScript client. Provide your API key and secret for authentication. ```JavaScript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getExchangeRates({'currency': 'BTC'}, function(err, rates) { console.log(rates); }); ``` -------------------------------- ### Install JWT dependencies Source: https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication Commands to install necessary packages for JWT generation. ```bash npm install jsonwebtoken ``` ```bash composer require firebase/php-jwt composer require vlucas/phpdotenv ``` -------------------------------- ### Montgomery Modulo Reduction Setup Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/files/coinbase_developer_platform.postman_environment.json Sets up the Montgomery reduction method for a given modulus. ```javascript function Montgomery(a){this.m=a;this.mp=a.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<(a.DB-15))-1;this.mt2=2*a.t} ``` -------------------------------- ### Get Cryptocurrencies Response Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/currencies Example JSON response for the Get Cryptocurrencies endpoint, listing cryptocurrency details. ```json [ { "code": "BTC", "name": "Bitcoin", "color": "#F7931A", "sort_index": 100, "exponent": 8, "type": "crypto", "address_regex": "^(13[a-km-zA-HJ-NP-Z1-9]{25,34})|(^bc1[qzry9x8gf2tvdw0s3jn54khce6mua7l]([qpzry9x8gf2tvdw0s3jn54khce6mua7l]{38}|[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{58}))$", "asset_id": "5b71fc48-3dd3-540c-809b-f8c94d0e68b5" }, { "code": "ETH", "name": "Ethereum", "color": "#627EEA", "sort_index": 102, "exponent": 8, "type": "crypto", "address_regex": "^(?:0x)?[0-9a-fA-F]{40}$", "asset_id": "d85dce9b-5b73-5c3c-8978-522ce1d1c1b4" }, { "code": "ETH2", "name": "Ethereum 2", "color": "#8E76FF", "sort_index": 161, "exponent": 8, "type": "crypto", "address_regex": "^(?:0x)?[0-9a-fA-F]{40}$", "asset_id": "3bec5bf3-507a-51ba-8e41-dc953b1a5c4d" }, { "code": "ETC", "name": "Ethereum Classic", "color": "#59D4AF", "sort_index": 103, "exponent": 8, "type": "crypto", "address_regex": "^(?:0x)?[0-9a-fA-F]{40}$", "asset_id": "c16df856-0345-5358-8a70-2a78c804e61f" } ] ``` -------------------------------- ### Get Fiat Currencies Response Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/currencies Example JSON response for the Get Fiat Currencies endpoint, listing currency details. ```json { "data": [ { "id": "AED", "name": "United Arab Emirates Dirham", "min_size": "0.01000000" }, { "id": "AFN", "name": "Afghan Afghani", "min_size": "0.01000000" }, { "id": "ALL", "name": "Albanian Lek", "min_size": "0.01000000" }, { "id": "AMD", "name": "Armenian Dram", "min_size": "0.01000000" } ], ... } ``` -------------------------------- ### Initialize .NET Console Project Source: https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication Commands to create, configure, and build a .NET console application for API authentication. ```bash dotnet new console ``` ```bash dotnet add package Microsoft.IdentityModel.Tokens dotnet add package System.IdentityModel.Tokens.Jwt dotnet add package Jose-JWT ``` ```bash dotnet build ``` ```bash dotnet run ``` -------------------------------- ### Get Current Time using Coinbase Wallet Ruby Client Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/time Instantiate the Coinbase Wallet client with your API key and secret, then call the time method to get the API server time. Ensure you have the 'coinbase/wallet' gem installed. ```ruby require 'coinbase/wallet' client = Coinbase::Wallet::Client.new(api_key: , api_secret: ) time = client.time ``` -------------------------------- ### Full Integration: Place Order and Monitor via WebSocket Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-websocket This comprehensive example integrates REST and WebSocket clients. It places a limit buy order and then uses the WebSocket client to monitor for the order's fill status in real-time. ```python from coinbase.rest import RESTClient from coinbase.websocket import WSClient import json import math api_key = "organizations/{org_id}/apiKeys/{key_id}" api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY -----END EC PRIVATE KEY----- " limit_order_id = "" order_filled = False def on_message(msg): global order_filled global limit_order_id message_data = json.loads(msg) if 'channel' in message_data and message_data['channel'] == 'user': orders = message_data['events'][0]['orders'] for order in orders: order_id = order['order_id'] if order_id == limit_order_id and order['status'] == 'FILLED': order_filled = True # initialize REST and WebSocket clients rest_client = RESTClient(api_key=api_key, api_secret=api_secret, verbose=True) ws_client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message, verbose=True) # open WebSocket connection and subscribe to channels ws_client.open() ws_client.subscribe(["BTC-USD"], ["heartbeats", "user"]) # get current price of BTC-USD and place limit-buy order 5% below product = rest_client.get_product("BTC-USD") btc_usd_price = float(product["price"]) adjusted_btc_usd_price = str(math.floor(btc_usd_price - (btc_usd_price * 0.05))) limit_order = rest_client.limit_order_gtc_buy( client_order_id="00000003", product_id="BTC-USD", base_size="0.0002", limit_price=adjusted_btc_usd_price ) limit_order_id = limit_order["order_id"] # wait for order to fill while not order_filled: ws_client.sleep_with_exception_check(1) print(f"order {limit_order_id} filled!") ws_client.close() ``` -------------------------------- ### Handle OAuth2 Redirect Callback Source: https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/integrations Example of the GET request received at the redirect URI containing the temporary code and state parameters. ```http GET https://example.com/oauth/callback?code=4c666b5c0c0d9d3140f2e0776cbe245f3143011d82b7a2c2a590cc7e20b79ae8&state=134ef5504a94 ``` -------------------------------- ### Initialize SigningCertificateV2 Class Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/files/coinbase_developer_platform.postman_environment.json Initializes the KJUR.asn1.cms.SigningCertificateV2 class, extending KJUR.asn1.cms.Attribute. ```javascript extendClass(KJUR.asn1.cms.SigningCertificateV2,KJUR.asn1.cms.Attribute); ``` -------------------------------- ### RSA Private Key Setup (JavaScript) Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/files/coinbase_developer_platform.postman_environment.json Provides JavaScript functions for setting up RSA private keys. Use this to initialize your private key object for decryption or signing operations. ```javascript function RSASetPrivate(c,a,b){this.isPrivate=true;if(typeof c!=="string"){this.n=c;this.e=a;this.d=b}else{if(c!=null&&a!=null&&c.length>0&&a.length>0){this.n=parseBigInt(c,16);this.e=parseInt(a,16);this.d=parseBigInt(b,16)}else{throw"Invalid RSA private key"}}} function RSASetPrivateEx(g,d,e,c,b,a,h,f){this.isPrivate=true;this.isPublic=false;if(g==null){throw"RSASetPrivateEx N == null"} if(d==null){throw"RSASetPrivateEx E == null"} if(g.length==0){throw"RSASetPrivateEx N.length == 0"} if(d.length==0){throw"RSASetPrivateEx E.length == 0"} if(g!=null&&d!=null&&g.length>0&&d.length>0){this.n=parseBigInt(g,16);this.e=parseInt(d,16);this.d=parseBigInt(e,16);this.p=parseBigInt(c,16);this.q=parseBigInt(b,16);this.dmp1=parseBigInt(a,16);this.dmq1=parseBigInt(h,16);this.coeff=parseBigInt(f,16)}else{throw"Invalid RSA private key"}}; ``` -------------------------------- ### Get Product Candles Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json Retrieves historical candle data for a specific product. Requires ProductID and optional start, end, and granularity parameters. ```javascript https://api.coinbase.com/api/v3/brokerage/products/{ProductID-HERE}/candles?start&end&granularity ``` -------------------------------- ### Initialize Signature Provider with Parameters Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/files/coinbase_developer_platform.postman_environment.json Initializes the signature provider with parameters like algorithm, provider, salt length, and private key. ```javascript this.initParams=o;if(o!==undefined){if(o.alg!==undefined){this.algName=o.alg;if(o.prov===undefined){this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]}else{this.provName=o.prov}this.algProvName=this.algName+":"+this.provName;this.setAlgAndProvider(this.algName,this.provName);this._setAlgNames()}if(o.psssaltlen!==undefined){this.pssSaltLen=o.psssaltlen}if(o.prvkeypem!==undefined){if(o.prvkeypas!==undefined){throw"both prvkeypem and prvkeypas parameters not supported"}else{try{var q=KEYUTIL.getKey(o.prvkeypem);this.init(q)}catch(m){throw"fatal error to load pem private key: "+m}}}}}; ``` -------------------------------- ### Get Transaction Details (JavaScript) Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/transactions This JavaScript example uses the Coinbase Node.js client to fetch transaction data. You need to provide your API key and secret for authentication. ```javascript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getAccount('2bbf394c-193b-5b2a-9155-3b4732659ede', function(err, account) { account.getTransaction('57ffb4ae-0c59-5430-bcd3-3f98f797a66c', function(err, tx) { console.log(tx); }); }); ``` -------------------------------- ### Fetching Accounts with Pagination Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/pagination Example of how to fetch a list of accounts using the API, demonstrating the `pagination` object in the response. ```APIDOC ## GET /v2/accounts ### Description Fetches a list of accounts with support for cursor-based pagination. ### Method GET ### Endpoint /v2/accounts ### Query Parameters - **limit** (integer) - Optional - Number of results per call. Accepted values: 0 - 100 (default 25) - **order** (string) - Optional - Result order. Accepted values: `asc`, `desc` (default) - **starting_after** (string) - Optional - Pagination cursor. Resource ID that defines your place in the list. - **ending_before** (string) - Optional - Pagination cursor. Resource ID that defines your place in the list. ### Request Example ```shell curl https://api.coinbase.com/v2/accounts \ -H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' ``` ### Response #### Success Response (200) - **pagination** (object) - Contains pagination details. - **ending_before** (string or null) - The ID of the last resource in the current page. - **starting_after** (string or null) - The ID of the first resource in the current page. - **limit** (integer) - The maximum number of resources to return. - **order** (string) - The order of the resources ('asc' or 'desc'). - **previous_uri** (string or null) - URI for the previous page of results. - **next_uri** (string or null) - URI for the next page of results. - **data** (array) - The list of account objects. #### Response Example ```json { "pagination": { "ending_before": null, "starting_after": null, "limit": 25, "order": "desc", "previous_uri": null, "next_uri": "/v2/accounts?&limit=25&starting_after=5d5aed5f-b7c0-5585-a3dd-a7ed9ef0e414" }, "data": [ ... ] } ``` ``` -------------------------------- ### Request with Credentials Example Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/cors Demonstrates how to include credentials like cookies or authentication tokens in a fetch request. This requires the 'credentials' option to be set to 'include'. ```javascript fetch("https://api.coinbase.com/v2/secure-data", { credentials: "include", }).then((response) => console.log(response)); ``` -------------------------------- ### Commit Fiat Withdrawal (JavaScript) Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/withdraw-fiat Commit a fiat withdrawal using the Coinbase JavaScript client. This example shows how to authenticate and chain calls to get account and withdrawal details before committing. ```javascript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getAccount('2bbf394c-193b-5b2a-9155-3b4732659ede', function(err, account) { account.getWithdrawal('a333743d-184a-5b5b-abe8-11612fc44ab5', function(err, tx) { tx.commit(function(err, resp) { console.log(resp); }); }); }); ``` -------------------------------- ### Set up WebSocket User Client Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-websocket Initialize the WSUserClient for connecting to user-specific channels. This client is used for heartbeats, user, and futures_balance_summary channels. ```python from coinbase.websocket import WSUserClient api_key = "organizations/{org_id}/apiKeys/{key_id}" api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n" def on_message(msg): print(msg) client = WSUserClient(api_key=api_key, api_secret=api_secret, on_message=on_message, verbose=True) ``` -------------------------------- ### Get Exchange Rates using Coinbase Wallet Ruby Client Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/exchange-rates This snippet demonstrates how to fetch exchange rates for a specified currency using the Coinbase Wallet Ruby client. Ensure you have the client installed and authenticated. ```Ruby require 'coinbase/wallet' client = Coinbase::Wallet::Client.new(api_key: , api_secret: ) rates = client.exchange_rates({currency: 'BTC'}) ``` -------------------------------- ### RSA Private Key Setup with Extended Parameters Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_developer_platform.postman_environment.json Initializes an RSA key object with all private and public parameters, including prime factors (p, q) and precomputed values for faster decryption (dmp1, dmq1, coeff). ```javascript function RSASetPrivateEx(g,d,e,c,b,a,h,f){ this.isPrivate=true; this.isPublic=false; if(g==null){throw"RSASetPrivateEx N == null"} if(d==null){throw"RSASetPrivateEx E == null"} if(g.length==0){throw"RSASetPrivateEx N.length == 0"} if(d.length==0){throw"RSASetPrivateEx E.length == 0"} if(g!=null&&d!=null&&g.length>0&&d.length>0){ this.n=parseBigInt(g,16); this.e=parseInt(d,16); ``` -------------------------------- ### RSA Private Key Setup Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/files/coinbase_developer_platform.postman_environment.json Initializes an RSA private key object with provided components. Used for cryptographic operations. ```javascript function RSASetPrivate(b,a,c,d,e,f,g){this.n=parseBigInt(b,16);this.e=parseInt(a,16);this.d=parseBigInt(c,16);this.p=parseBigInt(d,16);this.q=parseBigInt(e,16);this.dmp1=parseBigInt(f,16);this.dmq1=parseBigInt(g,16)} function RSASetPrivateEx(b,a,c,d,e,f,h){this.n=parseBigInt(b,16);this.e=parseInt(a,16);var g=parseInt(c,16);var i=parseInt(d,16);var j=parseInt(e,16);var k=parseInt(f,16);var l=parseInt(h,16);if(g!=null&&i!=null&&j!=null&&k!=null&&l!=null){var m=parseBigInt(g,16);var n=parseBigInt(i,16);var o=parseBigInt(j,16);var p=parseBigInt(k,16);var q=parseBigInt(l,16);this.dmp1=o;this.dmq1=p;this.coeff=q}else{var r=this.n.subtract(BigInteger.ONE);var s=this.e.modInverse(r);this.d=s;this.p=null;this.q=null;this.dmp1=null;this.dmq1=null;this.coeff=null}}} ``` -------------------------------- ### Show Withdrawal using Coinbase JavaScript Client Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/withdraw-fiat This JavaScript example demonstrates how to get details for a specific withdrawal using the Coinbase client library. You need to provide your API key, secret, account ID, and withdrawal ID. ```javascript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getAccount('2bbf394c-193b-5b2a-9155-3b4732659ede', function(err, account) { account.getWithdrawal('dd3183eb-af1d-5f5d-a90d-cbff946435ff', function(err, tx) { console.log(tx); }); }); ``` -------------------------------- ### Subscribe to Channels Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-overview This example demonstrates how to subscribe to the 'level2' channel for ETH-USD and ETH-EUR trading pairs. ```APIDOC ## Subscribe to Channels ### Description Use this message to subscribe to specific channels for market data. ### Message Type `subscribe` ### Request Body - **type** (string) - Required - The type of message, should be `subscribe`. - **product_ids** (array of strings) - Required - A list of product IDs to subscribe to. - **channel** (string) - Required - The channel to subscribe to (e.g., `level2`). ### Request Example ```json { "type": "subscribe", "product_ids": ["ETH-USD", "ETH-EUR"], "channel": "level2" } ``` ``` -------------------------------- ### Get API Key Permissions GET Request Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json This snippet defines a GET request to retrieve the permissions associated with the API key used for authentication. This is useful for verifying access levels. ```json { "name": "Get API Key Permissions", "request": { "method": "GET", "header": [], "url": { "raw": "https://api.coinbase.com/api/v3/brokerage/key_permissions", "protocol": "https", "host": [ "api", "coinbase", "com" ], "path": [ "api", "v3", "brokerage", "key_permissions" ] } }, "response": [] } ``` -------------------------------- ### Get Payment Method GET Request Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json This snippet defines a GET request to retrieve details for a specific payment method. It requires the payment method ID as a query parameter and authentication. ```json { "name": "Get Payment Method", "request": { "method": "GET", "header": [], "url": { "raw": "https://api.coinbase.com/api/v3/brokerage/payment_methods/?payment_method_id", "protocol": "https", "host": [ "api", "coinbase", "com" ], "path": [ "api", "v3", "brokerage", "payment_methods", "" ], "query": [ { "key": "payment_method_id", "value": null, "description": "The ID of the payment method. Refer to List Payment Methods for the list of all available payment methods and their corresponding IDs. required\n" } ] } }, "response": [] } ``` -------------------------------- ### Show Account Response Example Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/accounts This JSON object shows the detailed information for a specific account, including its ID, name, type, currency details, and current balance. ```json { "data": { "id": "2bbf394c-193b-5b2a-9155-3b4732659ede", "name": "My Wallet", "primary": true, "type": "wallet", "currency" : { "address_regex" : "^([13][a-km-zA-HJ-NP-Z1-9]{25,34})|^(bc1[qzry9x8gf2tvdw0s3jn54khce6mua7l]([qpzry9x8gf2tvdw0s3jn54khce6mua7l]{38}|[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{58))$", "asset_id" : "5b71fc48-3dd3-540c-809b-f8c94d0e68b5", "code" : "BTC", "color" : "#F7931A", "exponent" : 8, "name" : "Bitcoin", "slug" : "bitcoin", "sort_index" : 100, "type" : "crypto" } "balance": { "amount": "39.59000000", "currency": "BTC" }, "created_at": "2024-01-31T20:49:02Z", "updated_at": "2024-01-31T20:49:02Z", "resource": "account", "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede" } } ``` -------------------------------- ### Set up WebSocket Client Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-websocket Initialize the WSClient with API credentials and an on_message handler. The on_message function is called when a message is received from the WebSocket API. ```python from coinbase.websocket import WSClient api_key = "organizations/{org_id}/apiKeys/{key_id}" api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n" def on_message(msg): print(msg) ws_client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message, verbose=True) ``` -------------------------------- ### Place Market-Buy Order Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-rest-api Execute a market-buy order for a specified product ID and quote size. This example demonstrates placing a $10 market-buy order on BTC-USD and retrieving fill information or error details. ```python order = client.market_order_buy( client_order_id="00000001", product_id="BTC-USD", quote_size="10" ) if order['success']: order_id = order['success_response']['order_id'] fills = client.get_fills(order_id=order_id) print(json.dumps(fills.to_dict(), indent=2)) else: error_response = order['error_response'] print(error_response) ``` -------------------------------- ### Signature Provider Initialization (Unsupported) Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_developer_platform.postman_environment.json Throws an error indicating that initialization is not supported for this algorithm/provider combination. ```javascript this.init=function(s,t){throw"init(key, pass) not supported for this alg:prov="+this.algProvName} ``` -------------------------------- ### Deposit Response Example Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/deposit-fiat Example JSON response for a fiat deposit request, detailing the transaction status, amounts, and timestamps. ```json { "data": { "id": "67e0eaec-07d7-54c4-a72c-2e92826897df", "status": "completed", "payment_method": { "id": "83562370-3e5c-51db-87da-752af5ab9559", "resource": "payment_method", "resource_path": "/v2/payment-methods/83562370-3e5c-51db-87da-752af5ab9559" }, "transaction": { "id": "441b9494-b3f0-5b98-b9b0-4d82c21c252a", "resource": "transaction", "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/transactions/441b9494-b3f0-5b98-b9b0-4d82c21c252a" }, "amount": { "amount": "10.00", "currency": "USD" }, "subtotal": { "amount": "10.00", "currency": "USD" }, "created_at": "2015-01-31T20:49:02Z", "updated_at": "2015-02-11T16:54:02-08:00", "resource": "deposit", "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/deposits/67e0eaec-07d7-54c4-a72c-2e92826897df", "committed": true, "fee": { "amount": "0.00", "currency": "USD" }, "payout_at": "2015-02-18T16:54:00-08:00" } } ``` -------------------------------- ### Install Dependencies for TypeScript JWT Authentication Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Instructions for installing the necessary Node.js packages for JWT authentication in a TypeScript project. ```bash npm install jsonwebtoken npm install @types/jsonwebtoken npm install -g typescript ``` -------------------------------- ### Initialize Signature Provider Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_developer_platform.postman_environment.json Initializes a signature provider with algorithm and provider details. Throws an error if initialization parameters are invalid or if private key loading fails. ```javascript this.initParams=o;if(o!==undefined){if(o.alg!==undefined){this.algName=o.alg;if(o.prov===undefined){this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]}else{this.provName=o.prov}this.algProvName=this.algName+":"+this.provName;this.setAlgAndProvider(this.algName,this.provName);this._setAlgNames()}if(o.psssaltlen!==undefined){this.pssSaltLen=o.psssaltlen}if(o.prvkeypem!==undefined){if(o.prvkeypas!==undefined){throw"both prvkeypem and prvkeypas parameters not supported"}else{try{var q=KEYUTIL.getKey(o.prvkeypem);this.init(q)}catch(m){throw"fatal error to load pem private key: "+m}}}} ``` -------------------------------- ### Canada: Self-Hosted Wallet Example Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/travel-rule Example of Travel Rule data for a transfer to a self-hosted wallet in Canada. Only the beneficiary wallet type is required in this scenario. ```json { "beneficiary_wallet_type": "WALLET_TYPE_SELF_HOSTED" } ``` -------------------------------- ### Send Crypto Request (Shell) Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/send-crypto Use this example to send cryptocurrency to a specified address. Ensure you include the correct account ID, recipient address, amount, currency, and an idempotency key. The `network` parameter is optional and defaults to the currency's default network. ```sh curl https://api.coinbase.com/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732699ede/transactions \ -X POST \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ab09d9f5f27a7b170cd775abf89632b35b07c1e9d53e08b340cd9832ce52c2c' \ -d '{ "type": "send", "to": "1AUJ8z5RuHkTPQ1eikyfUUetzGmdwLGkpT", "amount": "0.1", "currency": "BTC", "idem": "df087dce-92a8-45cf-b112-60aad22c0976", "network": "bitcoin" }' ``` -------------------------------- ### TypeScript JWT Authentication Setup Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Basic setup for generating a JWT in TypeScript using the jsonwebtoken library. This includes defining key information and the algorithm. ```typescript import * as jwt from 'jsonwebtoken'; import * as crypto from 'crypto'; const keyName = 'organizations/{org_id}/apiKeys/{key_id}'; const keySecret = `-----BEGIN EC PRIVATE KEY----- YOUR PRIVATE KEY -----END EC PRIVATE KEY----- `; const algorithm = 'ES256'; ``` -------------------------------- ### List Payment Methods GET Request Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json This snippet defines a GET request to list all available payment methods associated with the brokerage account. It requires authentication. ```json { "name": "List Payment Methods", "request": { "method": "GET", "header": [], "url": { "raw": "https://api.coinbase.com/api/v3/brokerage/payment_methods", "protocol": "https", "host": [ "api", "coinbase", "com" ], "path": [ "api", "v3", "brokerage", "payment_methods" ] } }, "response": [] } ``` -------------------------------- ### Get Current Time using cURL Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/time Use cURL to make a GET request to the /v2/time endpoint to retrieve the API server time. This method does not require authentication. ```shell curl https://api.coinbase.com/v2/time ``` -------------------------------- ### Initialize Signature Algorithm Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/files/coinbase_developer_platform.postman_environment.json Initializes a signature algorithm with a given key and optional password. Supports RSA and ECDSA keys. ```javascript this.init=function(w,x){var y=null;try{if(x===undefined){y=KEYUTIL.getKey(w)}else{y=KEYUTIL.getKey(w,x)}}catch(v){throw"init failed:"+v}if(y.isPrivate===true){this.prvKey=y;this.state="SIGN"}else{if(y.isPublic===true){this.pubKey=y;this.state="VERIFY"}else{throw"init failed.:"+y}}}; ``` -------------------------------- ### Example Travel Rule Data Structure Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/travel-rule Provides a standalone example of the Travel Rule data object, detailing beneficiary information and transfer purpose. This structure is used when sending funds. ```json { "beneficiary_wallet_type": "WALLET_TYPE_EXCHANGE", "is_self": "IS_SELF_TRUE", "beneficiary_name": "San Francisco City Hall", "beneficiary_address": { "address1": "1 Dr Carlton B Goodlett Pl", "address2": "Unit 201", "address3": "", "city": "San Francisco", "state": "CA", "postal_code": "94102", "country": "US" }, "beneficiary_financial_institution": "009BBC11-03FB-4224-8CC7-CCE7CCDE4706", "transfer_purpose": "Test" } ``` -------------------------------- ### Go OAuth2 Authorization Code Flow Source: https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/oauth2-code-samples This Go sample demonstrates the OAuth2 authorization code flow. It handles initiating the login, generating PKCE parameters, and exchanging the authorization code for an access token upon callback. Ensure your client ID, client secret, and redirect URI are correctly configured. ```go package main import ( "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "log" "net/http" "net/url" ) // Replace these with your Coinbase App credentials and desired configuration. var ( clientID = "YOUR_CLIENT_ID" clientSecret = "YOUR_CLIENT_SECRET" // Make sure your redirect URI is registered with your OAuth2 client. redirectURI = "http://localhost:8000/callback" // Coinbase OAuth2 endpoints authURL = "https://login.coinbase.com/oauth2/auth" tokenURL = "https://login.coinbase.com/oauth2/token" ) // TokenResponse models the response received after exchanging the code. type TokenResponse struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` ExpiresIn int `json:"expires_in"` RefreshToken string `json:"refresh_token"` Scope string `json:"scope"` } func main() { http.HandleFunc("/login", loginHandler) http.HandleFunc("/callback", callbackHandler) log.Println("Starting server on :8000") log.Fatal(http.ListenAndServe(":8000", nil)) } // loginHandler initiates the OAuth2 flow. func loginHandler(w http.ResponseWriter, r *http.Request) { state, err := generateState() if err != nil { http.Error(w, "Error generating state", http.StatusInternalServerError) return } // Generate PKCE parameters for additional security codeVerifier, err := generateCodeVerifier() if err != nil { http.Error(w, "Error generating code verifier", http.StatusInternalServerError) return } codeChallenge := generateCodeChallenge(codeVerifier) // For demo purposes, we store the state and code verifier in cookies. http.SetCookie(w, &http.Cookie{ Name: "oauthstate", Value: state, Path: "/", }) http.SetCookie(w, &http.Cookie{ Name: "code_verifier", Value: codeVerifier, Path: "/", }) // Build the authorization URL. params := url.Values{} params.Add("response_type", "code") params.Add("client_id", clientID) params.Add("redirect_uri", redirectURI) // Adjust the scope as needed per Coinbase’s documentation. params.Add("scope", "wallet:user:read") params.Add("state", state) params.Add("code_challenge", codeChallenge) params.Add("code_challenge_method", "S256") http.Redirect(w, r, authURL+"?"+params.Encode(), http.StatusFound) } // callbackHandler handles the OAuth2 callback and exchanges the code for an access token. func callbackHandler(w http.ResponseWriter, r *http.Request) { // Retrieve state and code from the query parameters. query := r.URL.Query() state := query.Get("state") code := query.Get("code") // Validate the state using the stored cookie. cookie, err := r.Cookie("oauthstate") if err != nil || cookie.Value != state { http.Error(w, "Invalid state", http.StatusBadRequest) return } // Retrieve the code verifier from the cookie. verifierCookie, err := r.Cookie("code_verifier") if err != nil { http.Error(w, "Missing code verifier", http.StatusBadRequest) return } // Exchange the code for an access token. token, err := exchangeCodeForToken(code, verifierCookie.Value) if err != nil { http.Error(w, fmt.Sprintf("Error exchanging token: %v", err), http.StatusInternalServerError) return } // For demo purposes, we simply output the access token. fmt.Fprintf(w, "Access token: %s\n", token.AccessToken) fmt.Fprintf(w, "Refresh token: %s\n", token.RefreshToken) } // exchangeCodeForToken makes a POST request to Coinbase's token endpoint to exchange the authorization code for an access token. func exchangeCodeForToken(code, codeVerifier string) (*TokenResponse, error) { data := url.Values{} data.Set("grant_type", "authorization_code") ```