Coinbase Pro API – An Introductory Guide

9 min read

Get 10-day Free Algo Trading Course

Loading

Last Updated on April 3, 2023

Coinbase Pro API Guide

Table of contents:

  1. What is Coinbase Pro API?
  2. Is Coinbase Pro API free?
  3. Why should I use Coinbase Pro API?
  4. Why shouldn’t I use the Coinbase Pro API?
  5. Are Coinbase and Coinbase Pro the same?
  6. Is Coinbase Pro API better than Coinbase API?
  7. Is Coinbase Pro API available in my country?
  8. What are the alternatives to using the Coinbase Pro API?
  9. What clients are available for the Coinbase Pro API?
  10. How to get started with Coinbase Pro API?
  11. How to get trading pairs info with Coinbase Pro API?
  12. How to get Price Data with Coinbase Pro API?
  13. How to get historical data with Coinbase Pro API?
  14. How to access technical indicators such as the 20 SMA with the Coinbase Pro API?
  15. How to get Order Book data with Coinbase Pro API?
  16. How to get Trades data with Coinbase Pro API?
  17. How to use Coinbase Pro WebSockets?
  18. How to execute a trade on ETH when BTC hits a certain price with the Coinbase Pro API?
  19. How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Coinbase Pro API?
  20. How to cancel orders with Coinbase Pro API?
  21. Full code

What is Coinbase Pro API?

Coinbase Pro API is a method that allows us to automatically trade cryptocurrencies on Coinbase Pro via code.

Link: https://pro.coinbase.com

Is Coinbase Pro API free?

Creating an account on Coinbase Pro and using the API is free, but when it comes to trading fees start to apply. The main fee structure that Coinbase Pro follows is the usual maker/taker one with fee tiers.

The fee, also called pricing, tiers are calculated upon your 30-day USD trading volume. Some of you might wonder how exactly the maker/taker structure works and I have your back with the following examples.

If you place a market order that gets filled instantly, you are classified as a taker and a fee between 0.04% and 0.50% will be applied.

On the other hand, if your order isn’t instantly matched it will be placed on the order book. When your order gets matched by another customer you will be classified as a maker and a fee between 0.00% and 0.50% will be applied.

And finally, if your order gets partially filled upon placement you will pay a taker fee that matched the filled portion. The remainder of the order is placed on the order book and, when matched, is considered a maker order.

In the table below you can inspect the fee structure and its tiers.

Why should I use Coinbase Pro API?

  • Easy to use
  • Is intuitive
  • Features a great API
  • Fully regulated in US
  • Has high liquidity
  • Offers a decent amount of cryptocurrencies

Why shouldn’t I use Coinbase Pro API?

  • Needs more available cryptocurrencies
  • When compared to other exchanges, the fee for retail investors is high
  • Customer support can be slow
  • May get a bit confusing for begginers

Are Coinbase and Coinbase Pro the same?

Yes and No. Both of the platforms are owned by Coinbase Global Inc, but Coinbase is more like your virtual wallet while the Coinbase Pro is suited for people that are advanced in trading and ready to trade with other users.

Is Coinbase Pro API better than Coinbase API?

We can strongly argue that Coinbase Pro API is better than the plain Coinbase API as it allows for more advanced features and endpoints.

Is Coinbase Pro API available in my country?

Coinbase Pro API is available in over 100 countries and the full list can be found here. To make it easier for you, I’ve compiled all the approved countries in the picture below:

What are the alternatives to using the Coinbase Pro API?

Coinbase Pro API can be replaced with other exchanges that can be more suitable for your needs. Here are some of them:

What clients are available for the Coinbase Pro API?

Available and maintained clients for the Coinbase Pro API are the following:

How to get started with the Coinbase Pro API?

There are two ways to get started with Coinbase Pro. The first way is to create an account directly on the Coinbase Pro landing page and the second way is to integrate it with an already made Coinbase account.

Let us start with the latter first. Go over to the Coinbase Pro page that is found on the following link: Coinbase Pro | Digital Asset Exchange

When there, click the blue “Get started” button that is found in the upper right corner. Then you will need to specify your basic account details and verify your email address and authenticate via phone.

Depending on which region you’re in, you’ll be asked to provide your name, date of birth, address, intent, source of funds, occupation, and employer. You should also have your ID ready as you will be asked to provide a photo of it.

After the ID verification, you will be asked to link a bank account. You can skip this and come back to it later by selecting the Start Trading option. That’s it for the first way.

The second way involves logging in with your Coinbase account credentials that will automatically link the two and allow the transfer of funds between them.

If you want to go with the second option but don’t have a Coinbase account, you can check out our Coinbase article Getting Started section.

Now click on your account icon in the upper right corner and API and click the “+ New API Key” button. Then you will specify the API Key permissions, nickname, and passphrase.

After that, you can create your API Key. You will be prompted to enter a verification code and upon completion will be presented with your secret key that should be safely stored.

Now that our API key is created and functional we are ready to test out its features by going over the most used public and private endpoints. Be sure to install the python client with the following command:

pip install cbpro

How to get trading pairs info with Coinbase Pro API?

Trading Pairs can be obtained by using the get_products endpoint with the Coinbase Pro API python library.

Now, let’s import the library, initialize the client, obtain our products data, and put it into a pandas data frame for better observation:

import cbpro
import pandas as pd
c = cbpro.PublicClient()

data = pd.DataFrame(c.get_products())
data.tail().T

That’s a decent number of trading pairs but it could use more.

How to get Price Data with Coinbase Pro API?

Price Data can be obtained with the Coinbase Pro API by utilizing the get_product_ticker endpoint. You will need to specify the ticker parameter that you wish to obtain the data on.

Let’s obtain data for the Cardano asset:

ticker = c.get_product_ticker(product_id='ADA-USD')
ticker
{'trade_id': 15598647,
 'price': '1.7446',
 'size': '27.35',
 'time': '2021-05-26T18:24:17.9723252',
 'bid': '1.7435',
 'ask': '1.7444',
 'volume': '223045485.25'}

You can also use the Coinbase Pro REST API endpoints to obtain data in the following way:

import requests

ticker = requests.get('https://api.pro.coinbase.com/products/ADA-USD/ticker').json()
ticker
{'trade_id': 16369597,
 'price': '1.6106',
 'size': '1012.91',
 'time': '2021-05-30T08:39:31.8363332',
 'bid': '1.6106',
 'ask': '1.6111',
 'volume': '197711129.46'}

How to get historical data with Coinbase Pro API?

Historical data can be obtained by using the get_product_historic_rates endpoint with the Coinbase Pro API. You can specify the granularity, start and end date as the parameters of the API request.

Let’s obtain the historical data of ETH-USD with the default parameters and arrange it into a cleaned pandas data frame. We will rename the columns, convert the Unix time to standard time and sort the data by it.

historical = pd.DataFrame(c.get_product_historic_rates(product_id='ETH-USD'))
historical.columns= ["Date","Open","High","Low","Close","Volume"]
historical['Date'] = pd.to_datetime(historical['Date'], unit='s')
historical.set_index('Date', inplace=True)
historical.sort_values(by='Date', ascending=True, inplace=True)
historical

Now we can use this data to create a simple indicator and produce an interactive candlestick chart.

How to access technical indicators such as the 20 SMA with the Coinbase Pro API?

Coinbase Pro API doesn’t offer any preset indicators but we can make them by using some in-built pandas features for simple indicators or rely on the btalib library for more sophisticated ones.

In this case, we will create a simple 20 SMA indicator with pandas:

historical['20 SMA'] = historical.Close.rolling(20).mean()
historical.tail()

Now we have all the data we need to create a nice interactive chart with the plotly library:

import plotly.graph_objects as go
fig = go.Figure(data=[go.Candlestick(x = historical.index,
                                    open = historical['Open'],
                                    high = historical['High'],
                                    low = historical['Low'],
                                    close = historical['Close'],
                                    ),
                     go.Scatter(x=historical.index, y=historical['20 SMA'], line=dict(color='purple', width=1))])


fig.show()

How to get Order Book data with Coinbase Pro API?

Order Book data can be obtained by using the get_product_order_book Coinbase Pro API endpoint. You will need to specify the asset you want the order book on.

Let’s obtain Order Book data for BTC-USD and arrange the bids and asks into separate pandas data frames. After that, I will show you how to merge the two together.

order_book = c.get_product_order_book('BTC-USD')
order_book

Now we create the two data frames:

bids = pd.DataFrame(order_book['bids'])
asks = pd.DataFrame(order_book['asks'])

bids.head()

Now we merge the two and rename the columns to be informative:

df = pd.merge(bids, asks, left_index=True, right_index=True)
df = df.rename({"0_x":"Bid Price","1_x":"Bid Size", "2_x":"Bid Amount",
                "0_y":"Ask Price","1_y":"Ask Size", "2_y":"Ask Amount"}, axis='columns')
df.head()

How to get Trades data with Coinbase Pro API?

Trades data can be obtained with the Coinbase Pro API by using the get_product_trades endpoint. A mandatory parameter is the asset you want to obtain the data on.

As the Python library can get stuck because it makes a couple of calls we will use the REST API.

trades = pd.DataFrame(requests.get('https://api.pro.coinbase.com/products/ETH-USD/trades').json())
trades.tail()

How to use Coinbase Pro WebSockets?

Coinbase Pro WebSockets can be accessed via the WebscoketClient endpoint. With this feature you can easily stream and stay updated in the data you’re interested in.

Let’s start with a basic WebSocket connection that will obtain the ticker price data.

import cbpro

wsc = cbpro.WebsocketClient(url="wss://ws-feed.pro.coinbase.com",
                                products="ADA-USD",
                                channels=["ticker"])

To close the WebSocket you write the following command:

wsc.close()

Now, let’s create a class that will obtain ticker price data up to a certain number of WebSocket messages and print them out:

import time, cbpro
class myWebsocketClient(cbpro.WebsocketClient):
    def on_open(self):
        self.url = "wss://ws-feed.pro.coinbase.com/"
        self.products = ["ETH-USDT"]
        self.channels=["ticker"]
        self.message_count = 0
    def on_message(self, msg):
        self.message_count += 1
        if 'price' in msg and 'type' in msg:
            print ("Message type:", msg["type"],
                   "\t@ {:.3f}".format(float(msg["price"])))
    def on_close(self):
        print("Closing")

wsClient = myWebsocketClient()
wsClient.start()
print(wsClient.url, wsClient.products, wsClient.channels)
while (wsClient.message_count < 50):
    print ("\nmessage_count =", "{} \n".format(wsClient.message_count))
    time.sleep(1)
wsClient.close()

How to execute a trade on ETH when BTC hits a certain price with the Coinbase Pro API?

In this first example, I will show you how to properly and securely launch an order with specified requirements. The thing that we want to do is to launch a trade on ETH when BTC hits a certain price (e.g. $38500).

In order to make this work, we will need to set our order foundation and then create a loop that will check if the price level is hit. If the price is hit, we will execute a market order. On the contrary, we will continue looping.

When the price is executed we will wait for a few seconds and check if the order was really filled. This additional step is very important to add to your trading strategies as the exchange server may encounter some troubles.

Now that the logic is set, let’s import the relevant libraries and set up the APIs:

import cbpro
import base64
import json
from time import sleep

key = ''
secret = ''
passphrase = ''

encoded = json.dumps(secret).encode()
b64secret = base64.b64encode(encoded)
auth_client = cbpro.AuthenticatedClient(key=key, b64secret=secret, passphrase=passphrase)
c = cbpro.PublicClient()

And now for the main trading logic. Notice how we place a limit order by taking the current ETH-USD price and adding a few dollars on the top. This is done to make the order safer.

while True:
    try:
        ticker = c.get_product_ticker(product_id='BTC-USD')
    except Exception as e:
        print(f'Error obtaining ticker data: {e}')
    
    if float(ticker['price']) >= 38500.00:
        try:
            limit = c.get_product_ticker(product_id='ETH-USD')
        except Exception as e:
            print(f'Error obtaining ticker data: {e}')
        
        try:
            order=auth_client.place_limit_order(product_id='ETH-USDT', 
                              side='buy', 
                              price=float(limit['price'])+2, 
                              size='0.007')
        except Exception as e:
            print(f'Error placing order: {e}')
        
        sleep(2)
        
        try:
            check = order['id']
            check_order = auth_client.get_order(order_id=check)
        except Exception as e:
            print(f'Unable to check order. It might be rejected. {e}')
        
        if check_order['status'] == 'done':
            print('Order placed successfully')
            print(check_order)
            break
        else:
            print('Order was not matched')
            break
    else:
        print(f'The requirement is not reached. The ticker price is at {ticker["price"]}')
        sleep(10)

How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Coinbase Pro API?

The main task will be to execute an ETH trade when BTC moves 5% in the last 5 minutes. This means that we will want to create a loop that will obtain the prices of the two cryptos and calculate the percentage change between the two.

If the percentage change is less than 5%, the program will be sleeping for 5 minutes and calculating the percentage change again. If the percentage change is equal to or more than 5% the trade will execute.

After the trade execution, we will sleep for a few seconds and then check on the trade if it was filled or not. Have in mind that libraries and API setup remain the same as in the previous example.

Now that the logic is set, it is time to code it out:

while True:
    try:
        ticker_old = c.get_product_ticker(product_id='BTC-USD')
    except Exception as e:
        print(f'Error obtaining ticker data: {e}')

    sleep(300)

    try:
        ticker_new = c.get_product_ticker(product_id='BTC-USD')
    except Exception as e:
        print(f'Error obtaining ticker data: {e}')

    percent = ((float(ticker_new['price']) - float(ticker_old['price']))*100)/float(ticker_old['price'])
    
    if percent >= 5:
        try:
            limit = c.get_product_ticker(product_id='ETH-USDT')
        except Exception as e:
            print(f'Error obtaining ticker data: {e}')
        
        try:
            order=auth_client.place_limit_order(product_id='ETH-USDT', 
                              side='buy', 
                              price=float(limit['price'])+2, 
                              size='0.007')
        except Exception as e:
            print(f'Error placing order: {e}')
        
        sleep(2)
        
        try:
            check = order['id']
            check_order = auth_client.get_order(order_id=check)
        except Exception as e:
            print(f'Unable to check order. It might be rejected. {e}')
        
        if check_order['status'] == 'done':
            print('Order placed successfully')
            print(check_order)
            break
        else:
            print('Order was not matched')
            break
    else:
        print(f'The requirement is not reached. The percent change is at {percent}')

How to cancel orders with Coinbase Pro API?

To cancel orders with the Coinbase Pro API all you need to do is to access the cancel_order API endpoint and pass the order id as a parameter.

client.cancel_order(order_id = "ORDER-ID-HERE")

Full code

GitHub Link

Igor Radovanovic