Building a Crypto Trading Bot

auto-manage your portfolio with RESTful APIs

  1. Built a more nuanced algorithm

Automating your Trading

If you’ve ever invested in a mutual fund, you delegated the process of trading your portfolio to a fund manager who’ll make decisions for you as new data streams in. I would argue that this is a form of automation, not in the least because many of them won’t get you the results you desire.

  1. Extremely low exchange fees (0 to 0.5% for taker trades)
  2. Relatively streamlined RESTful API access
  3. Neat graphs

Keys to the Kingdom

So you’ve moved $10 into Pro to start trading. To access your portfolio without logging in and clicking through the website, you’ll need personal API keys. Click your dropdown menu at the top right, then click “API” and then “New API Key”.

Requesting Gets

Writing the connection script is fairly enjoyable. I recommend reading through the documentation beforehand; they have tutorial code in several languages. The Python initial example caused me some crashes, however, not including version mismatches.
Fortunately someone wrote a wrapper library that simplifies many of the functions; I’ll still walk through the initial authorization functions so we know what we’re dealing with.

import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase
import secrets # passwords file
# authorization class to access portfolio API
class CoinbaseExchangeAuth(AuthBase):

def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase

def __call__(self, request): # format call for Coinbase API
timestamp = str(time.time())
message = (timestamp + request.method + request.path_url + (request.body or ''))
message = message.encode('ascii')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest())
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
'Content-Type': 'application/json'})
return request
# create API auth using your keys
api_url = 'https://api.pro.coinbase.com/'
auth = CoinbaseExchangeAuth(secrets.pro_api_key, secrets.pro_secret_key, secrets.passphrase)
# Get accounts data
r = requests.get(api_url + 'accounts', auth=auth)
# print json formatte accounts info
r.json()

A Bot Buys some Bitcoin

The requests.get(accounts) in the above code will get you a JSON of all crypto accounts in your portfolio.

import cbpro
# https://github.com/danpaquin/coinbasepro-python
# create authorization obj wrapper with keys
auth = cbpro.AuthenticatedClient(secrets.pro_api_key, secrets.pro_secret_key, secrets.passphrase)
# market order function: specifying currency pair, direction, magnitude
auth.place_market_order(product_id='BTC-USD', side='buy', funds='5.00')
auth.place_stop_order(product_id='BTC-USD', 
side='buy',
price='200.00',
funds='5')

Welcome to the Machine

This whole process was much easier than I imagined it would be. Coinbase is a pretty great exchange to work with, especially with low exchange rates (since our algorithm may very well end up trading quite often).

data scientist, machine learning engineer. passionate about ecology, biotech and AI. https://www.linkedin.com/in/mark-s-cleverley/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store