### Full Quickstart Code Example Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-rest-api A complete example showing how to initialize the RESTClient, calculate a limit price, place a GTC buy order, and cancel the order if successful. ```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) ``` -------------------------------- ### TypeScript Environment Setup Source: https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication Commands to install necessary dependencies for a TypeScript-based JWT implementation. ```bash npm install -g ts-node typescript npm install jsonwebtoken npm install @types/jsonwebtoken ``` -------------------------------- ### Get Spot Price Response Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example JSON response for the spot price request. ```JSON { "data": { "amount": "1015.00", "currency": "USD" } } ``` -------------------------------- ### Install .NET Dependencies Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Installs the required NuGet packages for JWT handling in C#. ```bash dotnet add package Microsoft.IdentityModel.Tokens dotnet add package System.IdentityModel.Tokens.Jwt dotnet add package Jose-JWT ``` -------------------------------- ### Get Buy Price Request - Python Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example using the coinbase Python library to fetch the buy price for the BTC-USD currency pair. ```python from coinbase.wallet.client import Client client = Client(, ) price = client.get_buy_price(currency_pair = 'BTC-USD') ``` -------------------------------- ### Get Buy Price Request - Shell Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example using cURL to fetch the buy price for the BTC-USD currency pair. ```shell curl https://api.coinbase.com/v2/prices/BTC-USD/buy \ -H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' ``` -------------------------------- ### Install C++ Dependencies Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Commands to install necessary libraries and build the jwt-cpp dependency. ```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 ``` -------------------------------- ### Install WebSocket dependency Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/websocket Install the required websocket library for Python. ```bash pip install websocket ``` -------------------------------- ### Get Buy Price Request - JavaScript Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example using the coinbase Node.js client to fetch the buy price for the BTC-USD currency pair. ```javascript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getBuyPrice({'currencyPair': 'BTC-USD'}, function(err, price) { console.log(price); }); ``` -------------------------------- ### Get Sell Price Response Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example JSON response for the sell price request. ```JSON { "data": { "amount": "1010.25", "currency": "USD" } } ``` -------------------------------- ### Example Authorization URL Source: https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/integrations A concrete example of an authorization URL with client ID, redirect URI, state, and requested scopes. ```http GET https://login.coinbase.com/oauth2/auth?response_type=code&client_id=1532c63424622b6e9c4654e7f97ed40194a1547e114ca1c682f44283f39dfa49&redirect_uri=https%3A%2F%2Fexample.com%2Foauth%2Fcallback&state=134ef5504a94&scope=wallet:user:read,wallet:accounts:read ``` -------------------------------- ### Install dependencies for authenticated WebSocket Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/websocket Install the required websocket and PyJWT libraries for authenticated connections. ```bash pip install websocket "pyjwt[crypto]" ``` -------------------------------- ### Get Buy Price Request - Ruby Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Example using the coinbase-wallet Ruby gem to fetch the buy price for the BTC-USD currency pair. ```ruby require 'coinbase/wallet' client = Coinbase::Wallet::Client.new(api_key: , api_secret: ) price = client.buy_price({currency_pair: 'BTC-USD'}) ``` -------------------------------- ### Install PHP JWT dependencies Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Install firebase/php-jwt and vlucas/phpdotenv using Composer. ```bash composer require firebase/php-jwt composer require vlucas/phpdotenv ``` -------------------------------- ### Install Coinbase Advanced API Python SDK Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-rest-api Command to install the required Python package for interacting with the Coinbase Advanced API. ```bash pip3 install coinbase-advanced-py ``` -------------------------------- ### Install Node.js JWT dependencies Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Install the jsonwebtoken package via npm. ```bash npm install jsonwebtoken ``` -------------------------------- ### Great Britain Self-Hosted Wallet Example Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/travel-rule Example of the required JSON structure for a self-hosted wallet transaction in Great Britain. ```json { "is_self": "IS_SELF_TRUE", "beneficiary_name": "Satoshi Nakamoto", "beneficiary_address": { "country": "US" }, "beneficiary_wallet_type": "WALLET_TYPE_SELF_HOSTED" } ``` -------------------------------- ### Install Python JWT Dependencies Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Install PyJWT and cryptography libraries to manually generate a JWT. ```bash pip install PyJWT pip install cryptography ``` -------------------------------- ### Install TypeScript Dependencies Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Commands to install the necessary npm packages for JWT generation in TypeScript. ```bash npm install jsonwebtoken npm install @types/jsonwebtoken npm install -g typescript ``` -------------------------------- ### Ruby JWT Dependency Installation Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Commands to install the required JWT and OpenSSL gems for Ruby. ```bash gem install JWT gem install OpenSSL ``` -------------------------------- ### Canada Self-Hosted Wallet Example Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/travel-rule Example of the required JSON structure for a self-hosted wallet transaction in Canada. ```json { "beneficiary_wallet_type": "WALLET_TYPE_SELF_HOSTED" } ``` -------------------------------- ### Production Startup Sequence Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/derivatives/isolated-positions Recommended initialization order to ensure a complete view of isolated positions before enabling order placement. ```APIDOC ## Production Startup Sequence ### Description Initialize in this order so you never trade on a partial view. ### Steps 1. Authenticate the HTTP and WebSocket sessions as the main account. 2. Subscribe to the `user.isolated.*` channels and verify the accepted list. 3. Snapshot with `private/get_subaccounts` (`include_isolated: true`), `private/get_positions` (`include_isolated: true`), `private/get_open_orders` (`include_isolated: true`), and `private/get_account_summaries` (`include_isolated: true`). 4. Reconcile positions and orders against slot IDs into local state. 5. Enable order placement. ``` -------------------------------- ### Initialize WSClient Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-websocket Set up the standard WebSocket client by providing your API credentials and a callback function to handle incoming messages. ```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) ``` -------------------------------- ### Create .NET Console Project Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Initializes a new C# console project. ```bash dotnet new console ``` -------------------------------- ### GET /v2/accounts Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/pagination Example of a GET request to the Coinbase API that returns a paginated list of accounts. The response includes a pagination object with cursor information and a next_uri for fetching the next page. ```APIDOC ## GET /v2/accounts ### Description Fetches a list of accounts with cursor-based pagination. The response includes a pagination object with cursors and a next_uri for subsequent requests. ### Method GET ### Endpoint /v2/accounts ### Parameters #### 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 curl https://api.coinbase.com/v2/accounts \ -H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' ### Response #### Success Response (200) - **pagination** (object) - Pagination information including ending_before, starting_after, limit, order, previous_uri, and next_uri. - **data** (array) - List of resources. #### Response Example { "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": [ ... ] } ``` -------------------------------- ### Build and Run .NET Project Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Commands to build and execute the C# console application. ```bash dotnet build ``` ```bash dotnet run ``` -------------------------------- ### Initialize RESTClient Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-rest-api Sets up the RESTClient using your API key and secret. Replace the placeholders with your actual credentials. ```python from coinbase.rest import RESTClient from json import dumps 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) ``` -------------------------------- ### Get Current User Request Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/accounts Example cURL request to fetch the current user's public profile information. ```bash curl https://api.coinbase.com/v2/user \ -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \ -H 'CB-VERSION: 2019-08-15' ``` -------------------------------- ### Get Personal Details Request Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/accounts Example cURL request to fetch the user's legal name and KYC-verified primary address. ```bash curl https://api.coinbase.com/v2/user/personal-details \ -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' ``` -------------------------------- ### GET /v2/accounts with CB-VERSION header Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/versioning Example of making an API call to the Coinbase API with the CB-VERSION header to specify the API version. ```APIDOC ## GET /v2/accounts ### Description Retrieves accounts from the Coinbase API. This example demonstrates how to include the CB-VERSION header to specify the API version. ### Method GET ### Endpoint /v2/accounts ### Headers - **CB-VERSION** (string) - Required - The API version in YYYY-MM-DD format. - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example ``` curl https://api.coinbase.com/v2/accounts \ -H "CB-VERSION: 2022-01-06" \ -H "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c" ``` ### Response No response details provided in the source. ``` -------------------------------- ### GET /api/v3/brokerage/orders/historical/batch Source: https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/available-apis Lists historical orders. This endpoint requires OAuth2 authentication with appropriate scopes as described in the OAuth2 Access Guide. ```APIDOC ## GET /api/v3/brokerage/orders/historical/batch ### Description Lists historical orders. ### Method GET ### Endpoint /api/v3/brokerage/orders/historical/batch ### Authentication OAuth2 token with required scopes (see OAuth2 Access Guide) ### Response #### Success Response (200) - **orders** (array) - List of historical orders #### Response Example { "orders": [] } ``` -------------------------------- ### Build C# Project Source: https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication Compiles the C# project. ```bash dotnet build ``` -------------------------------- ### PKCE Plain Method Implementation Source: https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/security-best-practices Example of generating a code verifier and using it directly as the code challenge with the plain method. ```APIDOC ## PKCE Plain Method Implementation ### Description Generate a code verifier and use it directly as the code challenge with the plain method. ### Method GET ### Endpoint https://login.coinbase.com/oauth2/auth ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be `code`. - **client_id** (string) - Required - Your application's client ID. - **code_challenge** (string) - Required - The code challenge (equals the code verifier). - **code_challenge_method** (string) - Optional - Defaults to `plain` if not specified. - **redirect_uri** (string) - Required - The redirect URI (must be HTTPS). ### Request Example ``` https://login.coinbase.com/oauth2/auth?response_type=code&client_id=YOUR_CLIENT_ID&code_challenge=YOUR_CODE_CHALLENGE&code_challenge_method=plain&redirect_uri=YOUR_REDIRECT_URI ``` ### Response #### Success Response (302) Redirects to the redirect URI with an authorization code. #### Response Example ``` HTTP/1.1 302 Found Location: https://your-redirect-uri.com/callback?code=AUTHORIZATION_CODE ``` ``` -------------------------------- ### Initialize WSUserClient Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/guides/sdk-websocket Use the WSUserClient class to connect to user-specific channels like heartbeats, user updates, and futures balance summaries. ```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 /api/v3/brokerage/market/products/{product_id}/ticker Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json Retrieves recent market trades for a specific product. Requires a limit parameter and optionally accepts start and end timestamps. ```APIDOC ## GET /api/v3/brokerage/market/products/{product_id}/ticker ### Description Retrieves recent market trades for a specific product. Requires a limit parameter and optionally accepts start and end timestamps. ### Method GET ### Endpoint https://api.coinbase.com/api/v3/brokerage/market/products/{product_id}/ticker ### Parameters #### Path Parameters - **product_id** (string) - Required - The trading pair (e.g., 'BTC-USD'). #### Query Parameters - **limit** (integer) - Required - The number of trades to be returned. - **start** (integer) - Optional - The UNIX timestamp indicating the start of the time interval. - **end** (integer) - Optional - The UNIX timestamp indicating the end of the time interval. ### Response #### Success Response (200) - **trades** (array) - List of trade objects. #### Response Example { "trades": [ { "trade_id": "12345", "price": "100.00", "size": "0.5", "time": "2023-01-01T00:00:00Z" } ] } ``` -------------------------------- ### Python WebSocket Subscription Example Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-overview A complete script demonstrating how to connect to the Advanced Trade WebSocket, sign messages using ES256 JWT, and manage channel subscriptions for products like BTC-USD. ```python import time import json import jwt import hashlib import os import websocket import threading from datetime import datetime, timedelta # Derived from your Coinbase CDP API Key # SIGNING_KEY: the signing key provided as a part of your API key. Also called the "SECRET KEY" # API_KEY: the api key provided as a part of your API key. also called the "API KEY NAME" API_KEY = "organizations/{org_id}/apiKeys/{key_id}" SIGNING_KEY = """-----BEGIN EC PRIVATE KEY----- YOUR PRIVATE KEY -----END EC PRIVATE KEY-----""" ALGORITHM = "ES256" if not SIGNING_KEY or not API_KEY: raise ValueError("Missing mandatory environment variable(s)") CHANNEL_NAMES = { "level2": "level2", "user": "user", "tickers": "ticker", "ticker_batch": "ticker_batch", "status": "status", "market_trades": "market_trades", "candles": "candles", } WS_API_URL = "wss://advanced-trade-ws.coinbase.com" def sign_with_jwt(message, channel, products=[]): payload = { "iss": "coinbase-cloud", "nbf": int(time.time()), "exp": int(time.time()) + 120, "sub": API_KEY, } headers = { "kid": API_KEY, "nonce": hashlib.sha256(os.urandom(16)).hexdigest() } token = jwt.encode(payload, SIGNING_KEY, algorithm=ALGORITHM, headers=headers) message['jwt'] = token return message def on_message(ws, message): data = json.loads(message) with open("Output1.txt", "a") as f: f.write(json.dumps(data) + "\n") def subscribe_to_products(ws, products, channel_name): message = { "type": "subscribe", "channel": channel_name, "product_ids": products } signed_message = sign_with_jwt(message, channel_name, products) ws.send(json.dumps(signed_message)) def unsubscribe_to_products(ws, products, channel_name): message = { "type": "unsubscribe", "channel": channel_name, "product_ids": products } signed_message = sign_with_jwt(message, channel_name, products) ws.send(json.dumps(signed_message)) def on_open(ws): products = ["BTC-USD"] subscribe_to_products(ws, products, CHANNEL_NAMES["level2"]) def start_websocket(): ws = websocket.WebSocketApp(WS_API_URL, on_open=on_open, on_message=on_message) ws.run_forever() def main(): ws_thread = threading.Thread(target=start_websocket) ws_thread.start() sent_unsub = False start_time = datetime.utcnow() try: while True: if (datetime.utcnow() - start_time).total_seconds() > 5 and not sent_unsub: # Unsubscribe after 5 seconds ws = websocket.create_connection(WS_API_URL) unsubscribe_to_products(ws, ["BTC-USD"], CHANNEL_NAMES["level2"]) ws.close() sent_unsub = True time.sleep(1) except Exception as e: print(f"Exception: {e}") if __name__ == "__main__": main() ``` -------------------------------- ### GET /api/v3/brokerage/market/products/{product_id}/candles Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json Retrieves candlestick data for a specific product over a given time interval. Requires start and end timestamps and a granularity value. ```APIDOC ## GET /api/v3/brokerage/market/products/{product_id}/candles ### Description Retrieves candlestick data for a specific product over a given time interval. Requires start and end timestamps and a granularity value. ### Method GET ### Endpoint https://api.coinbase.com/api/v3/brokerage/market/products/{product_id}/candles ### Parameters #### Path Parameters - **product_id** (string) - Required - The trading pair (e.g., 'BTC-USD'). #### Query Parameters - **start** (integer) - Required - The UNIX timestamp indicating the start of the time interval. - **end** (integer) - Required - The UNIX timestamp indicating the end of the time interval. - **granularity** (enum) - Required - The timeframe each candle represents. Allowed values: UNKNOWN_GRANULARITY, ONE_MINUTE, FIVE_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, ONE_HOUR, TWO_HOUR, SIX_HOUR, ONE_DAY. - **limit** (integer) - Optional - The number of candle buckets to be returned. By default, returns 350 (max 350). ### Response #### Success Response (200) - **candles** (array) - List of candle objects. #### Response Example { "candles": [ { "start": "2023-01-01T00:00:00Z", "low": "100.00", "high": "110.00", "open": "105.00", "close": "108.00", "volume": "1000" } ] } ``` -------------------------------- ### Create Address via Ruby Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/onchain-addresses Example of creating an address using the Coinbase Wallet Ruby client. ```ruby require 'coinbase/wallet' client = Coinbase::Wallet::Client.new(api_key: , api_secret: ) address = client.create_address('2bbf394c-193b-5b2a-9155-3b4732659ede') ``` -------------------------------- ### Run C# Project Source: https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication Executes the built C# console application. ```bash dotnet run ``` -------------------------------- ### Create Address via JavaScript Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/onchain-addresses Example of creating an address using the Coinbase Node.js client. ```javascript var Client = require('coinbase').Client; var client = new Client({'apiKey': 'API KEY', 'apiSecret': 'API SECRET'}); client.getAccount('82de7fcd-db72-5085-8ceb-bee19303080b', function(err, account) { account.createAddress(null, function(err, address) { console.log(address); }); }); ``` -------------------------------- ### Compile Java application Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication Compile the Java project using Maven. ```bash mvn compile ``` -------------------------------- ### Fetch accounts with pagination Source: https://docs.cdp.coinbase.com/coinbase-app/api-architecture/pagination Example request to the accounts endpoint using a bearer token for authentication. ```bash curl https://api.coinbase.com/v2/accounts \ -H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' ``` -------------------------------- ### GET /v2/accounts/:account_id Source: https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/available-apis Get a specific account. Requires wallet:accounts:read scope. ```APIDOC ## GET /v2/accounts/:account_id ### Description Get a specific account. ### Method GET ### Endpoint /v2/accounts/:account_id ### Path Parameters - **account_id** (string) - Required - The ID of the account to retrieve. ### Authentication Bearer token in Authorization header ### Required Scopes - wallet:accounts:read ### Request Example ``` curl https://api.coinbase.com/v2/accounts/:account_id \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ``` -------------------------------- ### GET /v2/prices/:currency_pair/spot Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Get the current spot price for a currency pair. This endpoint does not require authentication. ```APIDOC ## GET /v2/prices/:currency_pair/spot ### Description Get the current spot price for a currency pair. This endpoint does not require authentication. ### Method GET ### Endpoint https://api.coinbase.com/v2/prices/:currency_pair/spot ### Parameters #### Path Parameters - **currency_pair** (string) - Required - The currency pair, e.g., BTC-USD. ### Response #### Success Response (200) - **data.amount** (string) - The price amount. - **data.currency** (string) - The currency of the price. #### Response Example ``` { "data": { "amount": "1020.25", "currency": "USD" } } ``` ``` -------------------------------- ### PKCE S256 Method Implementation Source: https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/security-best-practices Example of generating a code verifier and code challenge using the S256 method, and constructing the authorization request URL. ```APIDOC ## PKCE S256 Method Implementation ### Description Generate a code verifier and code challenge using the S256 method, then construct the authorization request URL. ### Method GET ### Endpoint https://login.coinbase.com/oauth2/auth ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be `code`. - **client_id** (string) - Required - Your application's client ID. - **code_challenge** (string) - Required - The code challenge generated using S256. - **code_challenge_method** (string) - Required - Must be `S256`. - **redirect_uri** (string) - Required - The redirect URI (must be HTTPS). ### Request Example ``` https://login.coinbase.com/oauth2/auth?response_type=code&client_id=YOUR_CLIENT_ID&code_challenge=YOUR_CODE_CHALLENGE&code_challenge_method=S256&redirect_uri=YOUR_REDIRECT_URI ``` ### Response #### Success Response (302) Redirects to the redirect URI with an authorization code. #### Response Example ``` HTTP/1.1 302 Found Location: https://your-redirect-uri.com/callback?code=AUTHORIZATION_CODE ``` ``` -------------------------------- ### GET /v2/prices/:currency_pair/sell Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Get the total price to sell one bitcoin or ether. This endpoint does not require authentication. ```APIDOC ## GET /v2/prices/:currency_pair/sell ### Description Get the total price to sell one bitcoin or ether. This endpoint does not require authentication. ### Method GET ### Endpoint https://api.coinbase.com/v2/prices/:currency_pair/sell ### Parameters #### Path Parameters - **currency_pair** (string) - Required - The currency pair, e.g., BTC-USD. ### Response #### Success Response (200) - **data.amount** (string) - The price amount. - **data.currency** (string) - The currency of the price. #### Response Example ``` { "data": { "amount": "1020.25", "currency": "USD" } } ``` ``` -------------------------------- ### Generate JWT in Java Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/websocket/websocket-authentication This Java example demonstrates how to create and sign a JWT using the Nimbus JOSE+JWT library and BouncyCastle for key handling. ```java import com.nimbusds.jose.*; import com.nimbusds.jose.crypto.*; import com.nimbusds.jwt.*; import java.security.interfaces.ECPrivateKey; import java.util.Map; import java.util.HashMap; import java.time.Instant; import java.util.Base64; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import java.security.spec.PKCS8EncodedKeySpec; import java.security.KeyFactory; import java.io.StringReader; import java.security.PrivateKey; import java.security.Security; import io.github.cdimascio.dotenv.Dotenv; public class Main { public static void main(String[] args) throws Exception { // Register BouncyCastle as a security providerx Security.addProvider(new BouncyCastleProvider()); // Load environment variables Dotenv dotenv = Dotenv.load(); String privateKeyPEM = dotenv.get("PRIVATE_KEY").replace("\\n", "\n"); String name = dotenv.get("NAME"); // create header object Map header = new HashMap<>(); header.put("alg", "ES256"); header.put("typ", "JWT"); header.put("kid", name); header.put("nonce", String.valueOf(Instant.now().getEpochSecond())); // create data object Map data = new HashMap<>(); data.put("iss", "cdp"); data.put("nbf", Instant.now().getEpochSecond()); data.put("exp", Instant.now().getEpochSecond() + 120); data.put("sub", name); // Load private key PEMParser pemParser = new PEMParser(new StringReader(privateKeyPEM)); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); Object object = pemParser.readObject(); PrivateKey privateKey; if (object instanceof PrivateKey) { privateKey = (PrivateKey) object; } else if (object instanceof org.bouncycastle.openssl.PEMKeyPair) { privateKey = converter.getPrivateKey(((org.bouncycastle.openssl.PEMKeyPair) object).getPrivateKeyInfo()); } else { throw new Exception("Unexpected private key format"); } pemParser.close(); // Convert to ECPrivateKey KeyFactory keyFactory = KeyFactory.getInstance("EC"); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); ECPrivateKey ecPrivateKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec); // create JWT JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder(); for (Map.Entry entry : data.entrySet()) { claimsSetBuilder.claim(entry.getKey(), entry.getValue()); } JWTClaimsSet claimsSet = claimsSetBuilder.build(); JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.ES256).customParams(header).build(); SignedJWT signedJWT = new SignedJWT(jwsHeader, claimsSet); JWSSigner signer = new ECDSASigner(ecPrivateKey); signedJWT.sign(signer); String sJWT = signedJWT.serialize(); System.out.println(sJWT); } } ``` -------------------------------- ### GET /api/v3/brokerage/portfolios/{portfolio_uuid} Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json Retrieves a specific portfolio by its UUID. This endpoint is used to get details about a particular portfolio. ```APIDOC ## GET /api/v3/brokerage/portfolios/{portfolio_uuid} ### Description Retrieves a specific portfolio by its UUID. ### Method GET ### Endpoint https://api.coinbase.com/api/v3/brokerage/portfolios/{portfolio_uuid} ### Parameters #### Path Parameters - **portfolio_uuid** (string) - Required - The UUID of the portfolio to retrieve. ``` -------------------------------- ### List Accounts Response Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/accounts Example JSON response containing a list of user accounts with pagination and balance details. ```json { "pagination": { "ending_before": null, "starting_after": null, "limit": 25, "order": "desc", "previous_uri": null, "next_uri": null }, "data": [ { "id": "58542935-67b5-56e1-a3f9-42686e07fa40", "name": "My Vault", "primary": false, "type": "vault", "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": "4.00000000", "currency": "BTC" }, "created_at": "2024-01-31T20:49:02Z", "updated_at": "2024-01-31T20:49:02Z", "resource": "account", "resource_path": "/v2/accounts/58542935-67b5-56e1-a3f9-42686e07fa40", "ready": true }, { "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" }, { "id": "8d5f2c4e-7a1b-5c3d-9e6f-0a1b2c3d4e5f", "name": "USDC Wallet", "primary": true, "type": "wallet", "currency": { "asset_id": "2b92315d-eab7-5bef-84fa-089a131333f5", "code": "USDC", "exponent": 6, "name": "USDC", "type": "crypto" }, "balance": { "amount": "250.000000", "currency": "USDC" }, "available_to_send": { "amount": "200.000000", "currency": "USDC" }, "created_at": "2024-01-31T20:49:02Z", "updated_at": "2024-01-31T20:49:02Z", "resource": "account", "resource_path": "/v2/accounts/8d5f2c4e-7a1b-5c3d-9e6f-0a1b2c3d4e5f" } ] } ``` -------------------------------- ### Postman Collection: Payment Methods and Data Requests Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/files/coinbase_advanced_trading.postman_collection.json Defines the API requests in the Postman collection, including List Payment Methods, Get Payment Method, and Get API Key Permissions. The Get Payment Method request requires a payment_method_id query parameter. ```json { "name": "Payment Methods", "item": [ { "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": [] }, { "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": [] } ], "auth": { "type": "bearer", "bearer": [ { "key": "token", "value": "{{token}}", "type": "string" } ] }, "event": [ { "listen": "prerequest", "script": { "type": "text/javascript", "packages": {}, "exec": [ "" ] } }, { "listen": "test", "script": { "type": "text/javascript", "packages": {}, "exec": [ "" ] } } ] } ``` ```json { "name": "Data", "item": [ { "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": [] } ], "auth": { "type": "bearer", "bearer": [ { "key": "token", "value": "{{token}}", "type": "string" } ] }, "event": [ { "listen": "prerequest", "script": { "type": "text/javascript", "packages": {}, "exec": [ "" ] } }, { "listen": "test", "script": { "type": "text/javascript", "packages": {}, "exec": [ "" ] } } ] } ``` -------------------------------- ### Deposit Funds Request (Ruby) Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/deposit-fiat Example of using the Coinbase Ruby client to deposit funds. ```ruby require 'coinbase/wallet' client = Coinbase::Wallet::Client.new(api_key: , api_secret: ) deposit = client.deposit('2bbf394c-193b-5b2a-9155-3b4732659ede', {"amount" => "10", "currency" => "USD", "payment_method" => "83562370-3e5c-51db-87da-752af5ab9559"}) ``` -------------------------------- ### Deposit Funds Request (JavaScript) Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/deposit-fiat Example of using the Coinbase Node.js client to deposit funds. ```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.deposit({"amount": "10", "currency": "USD", "payment_method": "83562370-3e5c-51db-87da-752af5ab9559"}, function(err, tx) { console.log(tx); }); }); ``` -------------------------------- ### Get Current Time Request via cURL Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/time A simple HTTP GET request to fetch the server time using the command line. ```shell curl https://api.coinbase.com/v2/time ``` -------------------------------- ### Canada Exchange Wallet Example Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/travel-rule Example of the required JSON structure for an exchange wallet transaction in Canada when the value is 999 CAD or greater. ```json { "beneficiary_wallet_type": "WALLET_TYPE_EXCHANGE", "beneficiary_name": "Satoshi Nakamoto", "beneficiary_address": { "address1": "1 Dr Carlton B Goodlett Pl", "city": "San Francisco", "state": "CA", "postal_code": "94102", "country": "US" } } ``` -------------------------------- ### private/create_combo Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/rest-api Create a combo. ```APIDOC ## POST private/create_combo ### Description Create a combo. ### Method POST ### Endpoint private/create_combo ### Parameters #### Request Body - method (string) - Required - The method name, set to "private/create_combo". - params (object) - Required - The combo parameters. ### Request Example { "method": "private/create_combo", "params": {} } ### Response #### Success Response (200) - result (object) - The created combo. #### Response Example { "result": {} } ``` -------------------------------- ### Great Britain Exchange Wallet Example Source: https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/travel-rule Example of the required JSON structure for an exchange wallet transaction in Great Britain, including the beneficiary_financial_institution field. ```json { "is_self": "IS_SELF_TRUE", "beneficiary_name": "Satoshi Nakamoto", "beneficiary_address": { "country": "US" }, "beneficiary_wallet_type": "WALLET_TYPE_SELF_EXCHANGE", "beneficiary_financial_institution": "009BBC11-03FB-4224-8CC7-CCE7CCDE4706" } ``` -------------------------------- ### private/simulate_portfolio Source: https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/rest-scopes Simulates a portfolio based on given parameters. Requires the wallet:accounts:read scope with view permission. ```APIDOC ## private/simulate_portfolio ### Description Simulates a portfolio based on given parameters. ### Required Scope - **wallet:accounts:read** (view) ``` -------------------------------- ### GET /v2/prices/:currency_pair/spot Source: https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices Get the current market price for bitcoin. This endpoint does not require authentication and supports an optional date parameter for historical spot prices. ```APIDOC ## GET /v2/prices/:currency_pair/spot ### Description Get the current market price for bitcoin. This is usually somewhere in between the buy and sell price. You can also get historic prices with the date parameter. This endpoint does not require authentication. ### Method GET ### Endpoint https://api.coinbase.com/v2/prices/:currency_pair/spot ### Parameters #### Path Parameters - **currency_pair** (string) - Required - The currency pair, e.g., BTC-USD. #### Query Parameters - **date** (string) - Optional - For historic spot price, use format YYYY-MM-DD (UTC). ### Request Example ``` curl https://api.coinbase.com/v2/prices/BTC-USD/spot \ -H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' ``` ### Response #### Success Response (200) - **data.amount** (string) - The spot price amount. - **data.currency** (string) - The currency of the price. #### Response Example ``` { "data": { "amount": "1015.00", "currency": "USD" } } ``` ```