Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (2024)

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.

Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (1)

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

Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (2)

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.

Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (3)

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 cbproimport pandas as pdc = cbpro.PublicClient()data = pd.DataFrame(c.get_products())data.tail().T
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (4)

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 requeststicker = 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
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (5)

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()
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (6)

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

import plotly.graph_objects as gofig = 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
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (7)

Now we create the two data frames:

bids = pd.DataFrame(order_book['bids'])asks = pd.DataFrame(order_book['asks'])bids.head()
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (8)

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()
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (9)

How to use Coinbase Pro WebSockets?

Coinbase Pro WebSockets can be accessed via the Websco*ketClient 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 cbprowsc = 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, cbproclass 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"], "\[emailprotected] {:.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()
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (10)

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 cbproimport base64import jsonfrom time import sleepkey = ''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)
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (11)

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}')
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog (2024)
Top Articles
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5511

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.