Skip to content

Instantly share code, notes, and snippets.

@jorilallo
Created January 29, 2015 21:16
Show Gist options
  • Save jorilallo/0cd603b691acb551b2e0 to your computer and use it in GitHub Desktop.
Save jorilallo/0cd603b691acb551b2e0 to your computer and use it in GitHub Desktop.
Coinbase Exchange signing with Python
# Requires python-requests. Install with pip:
#
# pip install requests
#
# or, with easy-install:
#
# easy_install requests
import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase
# Create custom authentication for Exchange
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):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or '')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
})
return request
api_url = 'https://api.exchange.coinbase.com/'
auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS)
# Get accounts
r = requests.get(api_url + 'accounts', auth=auth)
print r.json()
# [{"id": "a1b2c3d4", "balance":...
# Place an order
order = {
'size': 1.0,
'price': 1.0,
'side': 'buy',
'product_id': 'BTC-USD',
}
r = requests.post(api_url + 'orders', json=order, auth=auth)
print r.json()
# {"id": "0428b97b-bec1-429e-a94c-59992926778d"}
@rernst76
Copy link

This is great! In case anyone else stumbles on this I had to change the following lines (23 and 24) to get it to work in Python 3.10.0:

signature = hmac.new(hmac_key, bytes(message, encoding="utf-8"), hashlib.sha256)
 signature_b64 = base64.b64encode(signature.digest())

@cosmoscha
Copy link

I love you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment