5 min read

How to Connect to Coinbase with Python 3

Learn how to retrieve candlestick data from Coinbase using the Coinbase Pro REST API and Python 3.
Depicts a robotic hand holding a stylized Bitcoin, shaped like a coin. Title image for the series Coinbase Crypto Trading Bot
Coinbase Crypto Trading Bot Image

Coinbase Crypto Trading Bot

Keen to learn how to connect your Python 3 code to Coinbase? You’ve come to exactly the right place!

If you’ve been following my series on building a Coinbase Crypto Trading Bot, welcome back!

Let’s get into it.


About the Series

In this series, I show you how to build your own crypto trading bot to detect a market signal.

The series uses Python 3 to connect to Coinbase, then implements a modified version of the well-known Engulfing Candle Trading Strategy. Throughout the project, I show you how to set up your project in a way that makes it easy to expand with your own ideas and strategies in the future.

All code for the series can be found on the project GitHub. Each episode has working code samples you can copy and paste straight into your own crypto trading bot.

In This Episode

By the end of this episode, you’ll have successfully connected to Coinbase using their Coinbase Pro API. You’ll be able to retrieve your balance and the candlesticks for “BTC-USDC”.


About Coinbase

Coinbase is one of the world’s largest centralized crypto exchanges. In many ways, it is a US-based competitor to Binance.

My observations of Coinbase are as follows:

Pros:

  • High focus on developing institutional-grade services for the crypto industry
  • Clean UI
  • Reasonably featured REST API
  • Sandbox trading area (for testing)

Cons:

  • API Documentation is somewhat confusing
  • REST API is limited compared to Binance (10 requests per second, only retrieves 300 candles at a time)
  • Confusing permissions model
  • Limited trading options — doesn’t include STOP LOSS or TAKE PROFIT options for orders (or I just haven’t found it, reference my ‘confusing API documentation note)

Regardless, it’s still an impressive API set and more than sufficient for our purposes.

By the way, if you haven’t signed up for Coinbase, feel free to use my referral link.

Sign Up

Signing up for Coinbase is relatively straightforward. You’ll need to go through some standard KYC (Know Your Customer) requirements. Follow the steps here.

API Keys

Getting API Keys

I’ll be honest. Signing up for your API Keys with Coinbase can be a bit confusing. Especially when you’re looking to do it as an individual, rather than an institution. With all the options for Coinbase Pro, Coinbase Prime and so many more, it really can be quite a challenge.

I eventually narrowed it down to the following steps:

  1. Head to your settings and find the API section (link to API section here)
  2. Sign in if not already
  3. Select ‘New API Key’
  4. Select the accounts you want to apply it to
  5. For the permissions, we need the following: wallet:accounts:read, wallet:buys:create, wallet:orders:create, wallet:sells:create, wallet:sells:read, wallet:trades:create, wallet:trades:read, wallet:transactions:read, wallet:user:read
  6. Make sure you save the following somewhere secure: api_key, api_secret

It’s also worth having a look at your security settings to make sure you’re happy with them.

Add API Keys to the Project

Let’s get these keys into our project. Update the settings.json file outlined in episode 1 so that it looks like the following (replace the key strings with the relevant keys):

{
    "coinbase": {
        "passphrase": "your_secret_passphrase",
        "secret": "your_secret_string",
        "public": "your_public_key"
    }
}

Getting Data From Coinbase

Getting data from Coinbase can be done using their official Python library and a little bit of code from us.

Account Details

Let’s retrieve some details about our Coinbase account. This will demonstrate that we can:

  • Connect successfully to Coinbase
  • Retrieve live information

To do this, navigate to the folder coinbase_lib created in episode 1, and create a file get_account_details.py. If you’re joining without having completed episode 1, simply create the file.

In this file, add the following code:

from coinbase.wallet.client import Client

# Function to retrieve account details from Coinbase
def get_account_details(project_settings):
    # Retrieve the API Key
    api_key = project_settings['coinbase']['api_key']
    api_secret = project_settings['coinbase']['api_secret']
    # Create the Coinbase Client
    client = Client(
        api_key=api_key,
        api_secret=api_secret
    )
    # Retrieve information
    accounts = client.get_accounts()
    return accounts

Now, update main.py to retrieve the account details and print them to the screen:

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # Import project settings
    project_settings = get_project_settings(import_filepath)
    # Retrieve the account details
    account_details = get_account_details.get_account_details(project_settings=project_settings)
    print(account_details)

Very nice. If you press ‘Play’ on your IDE now, you should get a nice long printout of information about your account!

Retrieve Candlestick Data

The Engulfing Candle Strategy (discussed in the next episode) is built upon candlestick analysis (also known as Klines). Therefore, our trading bot needs a way to retrieve and format this data.

The specific API call and returned format are found on Coinbase Exchange REST API page under ‘Get product candles’.

As with every exchange I’ve worked with, Coinbase has placed its own slant on the API data format, meaning our code will need to normalize this data. I’ve chosen to normalize my data gathering so that it matches my other tutorials (MetaTrader 5 and Binance), however, feel free to add your own twist.

The process we go through to retrieve and normalize the data is as follows:

  1. Convert a timeframe string into the number matching Coinbase API
  2. Retrieve the raw data with the maximum number of candles (300 for Coinbase, compared to 1000 with Binance)
  3. Iterate through the data and convert each candle into a dictionary with the fields symbol, time, low, high, open, close, volume, timeframe
  4. Append candle dictionary to an array called candlestick_data
  5. Convert candlestick_data into a Python Pandas Dataframe
  6. Return the dataframe

Here’s the code for retrieving the candlesticks:

import requests
import pandas

# Function to get candle data
def get_candlestick_data(symbol, timeframe):
    # Convert the timeframe into a Coinbase specific type. This could be done in a switch statement for Python 3.10
    if timeframe == "M1":
        timeframe_converted = 60
    elif timeframe == "M5":
        timeframe_converted = 300
    elif timeframe == "M15":
        timeframe_converted = 900
    elif timeframe == "H1":
        timeframe_converted = 3600
    elif timeframe == "H6":
        timeframe_converted = 21600
    elif timeframe == "D1":
        timeframe_converted = 86400
    else:
        return Exception
    # Construct the URL
    url = f"https://api.exchange.coinbase.com/products/{symbol}/candles?granularity={timeframe_converted}"
    # Construct the headers
    headers = {"accept": "application/json"}
    # Query the API
    response = requests.get(url, headers=headers)
    # Retrieve the data
    candlestick_raw_data = response.json()
    # Initialize an empty array
    candlestick_data = []
    # Iterate through the returned data and construct a more useful data format
    for candle in candlestick_raw_data:
        candle_dict = {
            "symbol": symbol,
            "time": candle[0],
            "low": candle[1],
            "high": candle[2],
            "open": candle[3],
            "close": candle[4],
            "volume": candle[5],
            "timeframe": timeframe
        }
        # Append to candlestick_data
        candlestick_data.append(candle_dict)
    # Convert candlestick_data to dataframe
    candlestick_dataframe = pandas.DataFrame(candlestick_data)
    # Return a dataframe
    return candlestick_dataframe

If you jump back to your __main__ function and update it as below, you’ll be able to print out a formatted Dataframe of 300 candles of the BTC-USDT trading pair for the daily candle ❤

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # Import project settings
    project_settings = get_project_settings(import_filepath)
    # Retrieve the account details
    account_details = get_account_details.get_account_details(project_settings=project_settings)
    candlestick_data = get_candlesticks.get_candlestick_data("BTC-USDC", "D1")
    print(candlestick_data)

Win!!!

What’s Next

With our data gathering and normalization sorted, it’s now time to learn how to detect Engulfing Candles.

Check out my next episode to do just that!

Say Hi!

I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.