Building a Crypto Trading Bot

auto-manage your portfolio with RESTful APIs

Automating your Trading

Keys to the Kingdom

Requesting Gets

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 =, message, hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest())
'CB-ACCESS-SIGN': signature_b64,
'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 = ''
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

A Bot Buys some Bitcoin

import cbpro
# 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')

Welcome to the Machine

data scientist, machine learning engineer. passionate about ecology, biotech and AI.

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