Package: coinbase-advanced-py
Coinbase Advanced API Python SDKWelcome to the official Coinbase Advanced API Python SDK. This python project was created to allow coders to easily plug into theCoinbase Advanced API.
This SDK also supports easy connection to theCoinbase Advanced Trade WebSocket API.For thorough documentation of all available functions, refer to the following link:https://coinbase.github.io/coinbase-advanced-pyInstallationpip3installcoinbase-advanced-pyCloud API KeysThis SDK uses the Coinbase Cloud API keys. To use this SDK, you will need to create a Coinbase Cloud API key and secret by following the instructionshere.
Make sure to save your API key and secret in a safe place. You will not be able to retrieve your secret again.WARNING: We do not recommend that you save your API secrets directly in your code outside of testing purposes. Best practice is to use a secrets manager and access your secrets that way. You should be careful about exposing your secrets publicly if posting code that leverages this library.Optional: Set your API key and secret in your environment (make sure to put these in quotation marks). For example:exportCOINBASE_API_KEY="organizations/{org_id}/apiKeys/{key_id}"exportCOINBASE_API_SECRET="-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"REST API ClientIn your code, import the RESTClient class and instantiate it:fromcoinbase.restimportRESTClientclient=RESTClient()# Uses environment variables for API key and secretIf you did not set your API key and secret in your environment, you can pass them in as arguments:fromcoinbase.restimportRESTClientapi_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)After creating your API key, a json file will be downloaded to your computer. It's possible to  pass in the path to this file as an argument:client=RESTClient(key_file="path/to/coinbase_cloud_api_key.json")We also support passing a file-like object as thekey_fileargument:fromioimportStringIOclient=RESTClient(key_file=StringIO('{"name": "key-name", "privateKey": "private-key"}'))You can also set a timeout in seconds for your REST requests like so:client=RESTClient(api_key=api_key,api_secret=api_secret,timeout=5)Using the REST ClientYou are able to use any of the API hooks to make calls to the Coinbase API. For example:fromjsonimportdumpsaccounts=client.get_accounts()print(dumps(accounts,indent=2))order=client.market_order_buy(client_order_id="clientOrderId",product_id="BTC-USD",quote_size="1")print(dumps(order,indent=2))This code calls theget_accountsandmarket_order_buyendpoints.Refer to theAdvanced API Referencefor detailed information on each exposed endpoint.
Look in thecoinbase.restmodule to see the API hooks that are exposed.Passing in additional parametersUsekwargsto pass in any additional parameters. For example:kwargs={"param1":10,"param2":"mock_param"}product=client.get_product(product_id="BTC-USD",**kwargs)Generic REST CallsYou can make generic REST calls using theget,post,put, anddeletemethods. For example:market_trades=client.get("/api/v3/brokerage/products/BTC-USD/ticker",params={"limit":5})portfolio=client.post("/api/v3/brokerage/portfolios",data={"name":"TestPortfolio"})Here we are calling theGetMarketTradesandCreatePortfolioendpoints through the generic REST functions.
Once again, the built-in way to query these through the SDK would be:market_trades=client.get_market_trades(product_id="BTC-USD",limit=5)portfolio=client.create_portfolio(name="TestPortfolio")WebSocket API ClientWe offer a WebSocket API client that allows you to connect to theCoinbase Advanced Trade WebSocket API.
Refer to theAdvanced Trade WebSocket Channelspage for detailed information on each offered channel.In your code, import the WSClient class and instantiate it. The WSClient requires an API key and secret to be passed in as arguments. You can also use a key file or environment variables as described in the RESTClient instructions above.You must specify anon_messagefunction that will be called when a message is received from the WebSocket API. This function must take in a single argument, which will be the raw message received from the WebSocket API. For example:fromcoinbase.websocketimportWSClientapi_key="organizations/{org_id}/apiKeys/{key_id}"api_secret="-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"defon_message(msg):print(msg)client=WSClient(api_key=api_key,api_secret=api_secret,on_message=on_message)In this example, theon_messagefunction simply prints the message received from the WebSocket API.You can also set atimeoutin seconds for your WebSocket connection, as well as amax_sizein bytes for the messages received from the WebSocket API.client=WSClient(api_key=api_key,api_secret=api_secret,on_message=on_message,timeout=5,max_size=65536)# 64 KB max_sizeOther configurable fields are theon_openandon_closefunctions. If provided, these are called when the WebSocket connection is opened or closed, respectively. For example:defon_open():print("Connection opened!")client=WSClient(api_key=api_key,api_secret=api_secret,on_message=on_message,on_open=on_open)Using the WebSocket ClientOnce you have instantiated the client, you can connect to the WebSocket API by calling theopenmethod, and disconnect by calling theclosemethod.
Thesubscribemethod allows you to subscribe to specific channels, for specific products. Similarly, theunsubscribemethod allows you to unsubscribe from specific channels, for specific products. For example:# open the connection and subscribe to the ticker and heartbeat channels for BTC-USD and ETH-USDclient.open()client.subscribe(product_ids=["BTC-USD","ETH-USD"],channels=["ticker","heartbeats"])# wait 10 secondstime.sleep(10)# unsubscribe from the ticker channel and heartbeat channels for BTC-USD and ETH-USD, and close the connectionclient.unsubscribe(product_ids=["BTC-USD","ETH-USD"],channels=["ticker","heartbeats"])client.close()We also provide channel specific methods for subscribing and unsubscribing. For example, the below code is equivalent to the example from above:client.open()client.ticker(product_ids=["BTC-USD","ETH-USD"])client.heartbeats(product_ids=["BTC-USD","ETH-USD"])# wait 10 secondstime.sleep(10)client.ticker_unsubscribe(product_ids=["BTC-USD","ETH-USD"])client.heartbeats_unsubscribe(product_ids=["BTC-USD","ETH-USD"])client.close()Automatic Reconnection to the WebSocket APIThe WebSocket client will automatically attempt to reconnect the WebSocket API if the connection is lost, and will resubscribe to any channels that were previously subscribed to.The client uses an exponential backoff algorithm to determine how long to wait before attempting to reconnect, with a maximum number of retries of 5.If you do not want to automatically reconnect, you can set theretryargument toFalsewhen instantiating the client.client=WSClient(api_key=api_key,api_secret=api_secret,on_message=on_message,retry=False)Catching WebSocket ExceptionsThe WebSocket API client will raise exceptions if it encounters an error. On forced disconnects it will raise aWSClientConnectionClosedException, otherwise it will raise aWSClientException.NOTE: Errors on forced disconnects, or within logic in the message handler, will not be automatically raised since this will be running on its own thread.We provide thesleep_with_exception_checkandrun_forever_with_exception_checkmethods to allow you to catch these exceptions.sleep_with_exception_checkwill sleep for the specified number of seconds, and will check for any exception raised during that time.run_forever_with_exception_checkwill run forever, checking for exceptions every second. For example:fromcoinbase.websocketimport(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()exceptWSClientConnectionClosedExceptionase:print("Connection closed! Retry attempts exhausted.")exceptWSClientExceptionase:print("Error encountered!")This code will open the connection, subscribe to the ticker and heartbeat channels for BTC-USD and ETH-USD, and will sleep forever, checking for exceptions every second. If an exception is raised, it will be caught and handled appropriately.If you only want to run for 5 seconds, you can usesleep_with_exception_check:client.sleep_with_exception_check(sleep=5)Note that if the automatic reconnection fails after the retry limit is reached, aWSClientConnectionClosedExceptionwill be raised.If you wish to implement your own reconnection logic, you can catch theWSClientConnectionClosedExceptionand handle it appropriately. For example:client=WSClient(api_key=api_key,api_secret=api_secret,on_message=on_message,retry=False)defconnect_and_subscribe():try:client.open()client.subscribe(product_ids=["BTC-USD","ETH-USD"],channels=["ticker","heartbeats"])client.run_forever_with_exception_check()exceptWSClientConnectionClosedExceptionase:print("Connection closed! Sleeping for 20 seconds before reconnecting...")time.sleep(20)connect_and_subscribe()Async WebSocket ClientThe functions described above handle the asynchronous nature of WebSocket connections for you. However, if you wish to handle this yourself, you can use theasync_open,async_subscribe,async_unsubscribe, andasync_closemethods.We similarly provide async channel specific methods for subscribing and unsubscribing such asticker_async,ticker_unsubscribe_async, etc.Debugging the ClientsYou can enable debug logging for the REST and WebSocket clients by setting theverbosevariable toTruewhen initializing the clients. This will log useful information throughout the lifecycle of the REST request or WebSocket connection, and is highly recommended for debugging purposes.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)AuthenticationAuthentication of Cloud API Keys is handled automatically by the SDK when making a REST request or sending a WebSocket message.However, if you wish to handle this yourself, you must create a JWT token and attach it to your request as detailed in the Cloud API docshere. Use the built injwt_generatorto create your JWT token. For example:fromcoinbaseimportjwt_generatorapi_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)This will create a JWT token for the POST/api/v3/brokerage/ordersendpoint. Pass this JWT token in theAuthorizationheader of your request as:"Authorization": "Bearer " + jwtYou can also generate JWTs to use with the Websocket API. These do not require passing a specific URI. For example:fromcoinbaseimportjwt_generatorapi_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)Use this JWT to connect to the Websocket API by setting it in the "jwt" field of your subscription requests. See the docsherefor more details.ChangelogFor a detailed list of changes, see theChangelog.ContributingIf you've found a bug within this project, open an issue on this repo and add the "bug" label to it.
If you would like to request a new feature, open an issue on this repo and add the "enhancement" label to it.
Direct concerns or questions on the API to theAdvanced API Developer Forum.