Skip to content

Instantly share code, notes, and snippets.

@whittlem
Created November 17, 2020 12:42
Show Gist options
  • Save whittlem/4d49b5b47ab700cb62beba5b015651a9 to your computer and use it in GitHub Desktop.
Save whittlem/4d49b5b47ab700cb62beba5b015651a9 to your computer and use it in GitHub Desktop.
Trading using Python - Coinbase Pro Historic Rates
import re
import requests
from datetime import datetime
def cbpGetHistoricRates(market='BTC-GBP', granularity=86400, iso8601start='', iso8601end=''):
if not isinstance(market, str):
raise Exception('Market string input expected')
if not isinstance(granularity, int):
raise Exception('Granularity integer input expected')
granularity_options = [60, 300, 900, 3600, 21600, 86400]
if not granularity in granularity_options:
raise Exception(
'Invalid granularity: 60, 300, 900, 3600, 21600, 86400')
if not isinstance(iso8601start, str):
raise Exception('ISO8601 date string input expected')
if not isinstance(iso8601end, str):
raise Exception('ISO8601 date string input expected')
# iso8601 regex
regex = r'^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$'
if len(iso8601start) < 0:
match_iso8601 = re.compile(regex).match
if match_iso8601(iso8601start) is None:
raise Exception('iso8601 start date is invalid')
if len(iso8601end) < 0:
match_iso8601 = re.compile(regex).match
if match_iso8601(iso8601end) is None:
raise Exception('iso8601 end date is invalid')
api = 'https://api.pro.coinbase.com/products/' + market + '/candles?granularity=' + \
str(granularity) + '&start=' + iso8601start + '&end=' + iso8601end
resp = requests.get(api)
if resp.status_code != 200:
raise Exception('GET ' + api + ' {}'.format(resp.status_code))
data = {}
for price in reversed(resp.json()):
# time, low, high, open, close, volume
iso8601 = datetime.fromtimestamp(price[0])
timestamp = datetime.strftime(iso8601, "%d/%m/%Y %H:%M:%S")
data[timestamp] = price[4]
return data
print (cbpGetHistoricRates('BTC-GBP', 86400))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment