### Install Coinbase Advanced Python SDK Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Command to install the official Coinbase Advanced API Python SDK using pip3. This makes the library available for use in Python projects. ```bash pip3 install coinbase-advanced-py ``` -------------------------------- ### Configuring WSClient on_open Callback - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Illustrates how to provide an optional `on_open` callback function during `WSClient` initialization. This function is executed when the WebSocket connection is successfully established, allowing for setup actions. ```python def on_open(): print("Connection opened!") client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message, on_open=on_open) ``` -------------------------------- ### Use REST Client for API Calls (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Provides examples of making API calls using the initialized RESTClient. It shows fetching user accounts and placing a market buy order, demonstrating basic interaction with the Coinbase Advanced API. ```python from json import dumps accounts = client.get_accounts() print(dumps(accounts.to_dict(), indent=2)) order = client.market_order_buy(client_order_id="clientOrderId", product_id="BTC-USD", quote_size="1") print(dumps(order.to_dict(), indent=2)) ``` -------------------------------- ### Making Generic REST Calls (GET/POST) - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Provides examples of using the generic `get` and `post` methods of the client to interact with arbitrary REST endpoints. Parameters are passed via the `params` dictionary for GET requests and the `data` dictionary for POST requests. ```python market_trades = client.get("/api/v3/brokerage/products/BTC-USD/ticker", params={"limit": 5}) portfolio = client.post("/api/v3/brokerage/portfolios", data={"name": "TestPortfolio"}) ``` -------------------------------- ### Set Coinbase API Keys as Environment Variables Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Example bash commands to set the Coinbase API key and secret as environment variables. This is a recommended practice for securely providing credentials to the SDK. ```bash export COINBASE_API_KEY="organizations/{org_id}/apiKeys/{key_id}" export COINBASE_API_SECRET="-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n" ``` -------------------------------- ### Defining Python Dependencies - requirements.txt Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/pinned_requirements.txt Specifies the necessary Python libraries and their exact versions required to run the project. This list is typically used by package managers like pip to install dependencies. ```Python requests==2.31.0 cryptography==42.0.4 PyJWT==2.8.0 websockets==12.0 backoff==2.2.1 ``` -------------------------------- ### Initializing Coinbase WSUserClient in Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates how to import the WSUserClient class and instantiate it using an API key, API secret (private key), and a callback function (`on_message`) to handle incoming messages. This sets up the client for connecting to the WebSocket API. ```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) ``` -------------------------------- ### Initialize REST Client with Key File Path (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Creates a RESTClient instance by providing the file path to a JSON file containing the API key and private key. This is an alternative way to load credentials from a file. ```python client = RESTClient(key_file="path/to/cdp_api_key.json") ``` -------------------------------- ### Initialize REST Client with File-like Object (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates initializing the RESTClient by passing a file-like object (using `io.StringIO`) containing the JSON key data. This allows loading credentials from a string or other in-memory sources. ```python from io import StringIO client = RESTClient(key_file=StringIO('{"name": "key-name", "privateKey": "private-key"}')) ``` -------------------------------- ### Managing WebSocket Connection and Subscriptions with WSUserClient in Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows how to open and close the WebSocket connection using `client.open()` and `client.close()`. It also demonstrates subscribing and unsubscribing to multiple channels and products using the generic `client.subscribe()` and `client.unsubscribe()` methods. ```python import time # open the connection and subscribe to the ticker and heartbeat channels for BTC-USD and ETH-USD client.open() client.subscribe(product_ids=["BTC-USD", "ETH-USD"], channels=["ticker", "heartbeats"]) # wait 10 seconds time.sleep(10) # unsubscribe from the ticker channel and heartbeat channels for BTC-USD and ETH-USD, and close the connection client.unsubscribe(product_ids=["BTC-USD", "ETH-USD"], channels=["ticker", "heartbeats"]) client.close() ``` -------------------------------- ### Initialize REST Client with Environment Variables (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Imports the RESTClient class and creates an instance. The client automatically uses API key and secret credentials found in environment variables if they are set. ```python from coinbase.rest import RESTClient client = RESTClient() # Uses environment variables for API key and secret ``` -------------------------------- ### Initializing WSClient with on_message - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows the basic initialization of the `WSClient` for connecting to the WebSocket API. It requires providing API credentials and defining an `on_message` callback function to process 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) client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message) ``` -------------------------------- ### Subscribing to Public WebSocket Channel (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows how to initialize the `WSClient` without API keys to subscribe to a public channel like 'ticker'. Includes defining a message handler, opening the connection, subscribing, waiting, unsubscribing, and closing. ```python import time from coinbase.websocket import WSClient def on_message(msg): print(msg) client = WSClient(on_message=on_message) client.open() client.ticker(product_ids=["BTC-USD"]) time.sleep(10) client.ticker_unsubscribe(product_ids=["BTC-USD"]) client.close() ``` -------------------------------- ### Initializing Clients with Debug Logging (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates how to enable verbose logging for the Coinbase Advanced Trade Python SDK REST and WebSocket clients by setting the `verbose` parameter to `True` during initialization. This logs detailed information about requests and connections. ```python 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) ``` -------------------------------- ### Accessing Public REST Endpoint (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates how to initialize the `RESTClient` without API keys to access public endpoints, such as `get_public_products`. Shows how to call the method and print the result. ```python from coinbase.rest import RESTClient client = RESTClient() public_products = client.get_public_products() print(json.dumps(public_products.to_dict(), indent=2)) ``` -------------------------------- ### Catching WebSocket Exceptions - Coinbase Advanced Trade - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates how to initialize the Coinbase Advanced Trade WebSocket client, open a connection, subscribe to channels, and use `run_forever_with_exception_check` within a try-except block to catch and handle potential `WSClientConnectionClosedException` or `WSClientException` errors during continuous operation. Requires `coinbase.websocket` module. ```python from coinbase.websocket import (WSClient, WSClientConnectionClosedException, WSClientException) client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message) try: client.open() client.subscribe(product_ids=["BTC-USD", "ETH-USD"], channels=["ticker", "heartbeats"]) client.run_forever_with_exception_check() except WSClientConnectionClosedException as e: print("Connection closed! Retry attempts exhausted.") except WSClientException as e: print("Error encountered!") ``` -------------------------------- ### Initialize REST Client with Explicit Keys (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Imports the RESTClient class and creates an instance by passing the API key and secret directly as arguments. This method is suitable when credentials are not stored as environment variables. ```python from coinbase.rest import RESTClient 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) ``` -------------------------------- ### Initialize REST Client with Timeout (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows how to create a RESTClient instance while specifying a timeout duration in seconds for REST API requests. This helps prevent requests from hanging indefinitely. ```python client = RESTClient(api_key=api_key, api_secret=api_secret, timeout=5) ``` -------------------------------- ### Initializing RESTClient with Rate Limit Headers - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Explains how to configure the `RESTClient` during initialization to include rate limit information in the response headers. Setting the `rate_limit_headers` parameter to `True` appends these headers as fields to the API response body. ```python client = RESTClient(api_key=api_key, api_secret=api_secret, rate_limit_headers=True) ``` -------------------------------- ### Listing Python Project Dependencies Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/requirements.txt Specifies the necessary Python libraries and their minimum or exact versions required to run the project. These are typically found in a requirements.txt file. ```Python requests>=2.31.0 cryptography>=42.0.4 PyJWT>=2.8.0 websockets>=12.0,<14.0 backoff>=2.2.1 ``` -------------------------------- ### Configuring WSClient Timeout and Max Size - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates how to set optional configuration parameters like `timeout` (connection timeout in seconds) and `max_size` (maximum message size in bytes) when initializing the `WSClient` to control connection behavior. ```python client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message, timeout=5, max_size=65536) # 64 KB max_size ``` -------------------------------- ### Importing WebsocketResponse - Coinbase Advanced Trade - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows the necessary import statement to use the `WSClient` and the custom `WebsocketResponse` object provided by the Coinbase Advanced Trade Python library for easier interaction with WebSocket feed data. ```python from coinbase.websocket import WSClient, WebsocketResponse ``` -------------------------------- ### Using Channel-Specific Subscription Methods with WSUserClient in Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Provides an alternative way to subscribe and unsubscribe using dedicated methods for specific channels like `client.ticker()` and `client.heartbeats()`, and their unsubscribe counterparts. This achieves the same result as the generic `subscribe`/`unsubscribe` methods but offers a more direct syntax. ```python import time client.open() client.ticker(product_ids=["BTC-USD", "ETH-USD"]) client.heartbeats() # wait 10 seconds time.sleep(10) client.ticker_unsubscribe(product_ids=["BTC-USD", "ETH-USD"]) client.heartbeats_unsubscribe() client.close() ``` -------------------------------- ### Passing Additional Parameters (kwargs) - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Illustrates how to include extra parameters in API calls by using the `**kwargs` syntax with a dictionary containing the desired parameters. This allows passing any additional, non-explicitly defined arguments to the underlying API call. ```python kwargs = { "param1": 10, "param2": "mock_param" } product = client.get_product(product_id="BTC-USD", **kwargs) ``` -------------------------------- ### Accessing Product Price (Dot Notation) - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates how to access a product's price field using dot-notation on the response object returned by the `get_product` endpoint. This is available for fields explicitly defined in the custom response classes. ```python product = client.get_product("BTC-USD") print(product.price) ``` -------------------------------- ### Processing Ticker Data with WebsocketResponse - Coinbase Advanced Trade - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Demonstrates how to use the `WebsocketResponse` object within the `on_message` callback to parse incoming WebSocket messages, specifically for the 'ticker' channel. It shows how to access nested data like `product_id` and `price` from ticker events and includes the full flow of opening, subscribing, waiting, unsubscribing, and closing the client connection. Requires `coinbase.websocket`, `json` (implicitly for `json.loads`), and `time` modules. ```python from coinbase.websocket import WSClient, WebsocketResponse def on_message(msg): ws_object = WebsocketResponse(json.loads(msg)) if ws_object.channel == "ticker" : for event in ws_object.events: for ticker in event.tickers: print(ticker.product_id + ": " + ticker.price) client.open() client.subscribe(product_ids=["BTC-USD", "ETH-USD"], channels=["ticker"]) time.sleep(10) client.unsubscribe(product_ids=["BTC-USD", "ETH-USD"], channels=["ticker"]) client.close() ``` -------------------------------- ### Implementing Custom Reconnection Logic - Coinbase Advanced Trade - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Illustrates how to implement custom reconnection logic for the Coinbase Advanced Trade WebSocket client by disabling automatic retries (`retry=False`), catching the `WSClientConnectionClosedException`, waiting for a period (20 seconds), and recursively calling a function to re-establish the connection and subscriptions. Requires `coinbase.websocket` and `time` modules. ```python client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message, retry=False) def connect_and_subscribe(): try: client.open() client.subscribe(product_ids=["BTC-USD", "ETH-USD"], channels=["ticker", "heartbeats"]) client.run_forever_with_exception_check() except WSClientConnectionClosedException as e: print("Connection closed! Sleeping for 20 seconds before reconnecting...") time.sleep(20) connect_and_subscribe() ``` -------------------------------- ### Sleeping with Exception Check - Coinbase Advanced Trade - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows how to use the `sleep_with_exception_check` method of the Coinbase Advanced Trade WebSocket client to pause execution for a specified duration (5 seconds in this case) while still monitoring for and allowing exceptions raised on the client's thread to be caught in the main thread. ```python client.sleep_with_exception_check(sleep=5) ``` -------------------------------- ### Generating REST API JWT Token (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows how to use the `jwt_generator` module to create a JSON Web Token (JWT) for authenticating requests to a specific Coinbase Advanced Trade REST API endpoint (e.g., POST /api/v3/brokerage/orders). Requires API key and secret. ```python from coinbase import jwt_generator api_key = "organizations/{org_id}/apiKeys/{key_id}" api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n" uri = "/api/v3/brokerage/orders" jwt_uri = jwt_generator.format_jwt_uri("POST", uri) jwt = jwt_generator.build_rest_jwt(jwt_uri, api_key, api_secret) ``` -------------------------------- ### Generating WebSocket API JWT Token (Python) Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Illustrates how to use the `jwt_generator` module to create a JSON Web Token (JWT) specifically for authenticating connections to the Coinbase Advanced Trade WebSocket API. This JWT does not require a specific URI. Requires API key and secret. ```python from coinbase import jwt_generator api_key = "organizations/{org_id}/apiKeys/{key_id}" api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n" jwt = jwt_generator.build_ws_jwt(api_key, api_secret) ``` -------------------------------- ### Accessing Nested Account Balance (Bracket Notation) - Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows how to access nested fields within a response object, specifically the account balance value, using standard bracket notation when dot-notation is not available for nested fields. This is necessary for fields not explicitly defined in the custom response classes. ```python accounts = client.get_accounts() print(accounts.accounts[0].available_balance['value']) ``` -------------------------------- ### Disabling Automatic Reconnection for WSClient in Python Source: https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md Shows how to disable the client's default automatic reconnection behavior. This is done by setting the `retry` argument to `False` during the instantiation of the `WSClient` (or `WSUserClient` as discussed in the surrounding text). ```python client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message, retry=False) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.