· 8 years ago · Dec 04, 2017, 02:42 AM
1# Requires python-requests. Install with pip:
2#
3# pip install requests
4#
5# or, with easy-install:
6#
7# easy_install requests
8
9import json, hmac, hashlib, time, requests, base64
10from requests.auth import AuthBase
11
12# Create custom authentication for Exchange
13class CoinbaseExchangeAuth(AuthBase):
14def __init__(self, api_key, secret_key, passphrase):
15 self.api_key = api_key
16 self.secret_key = secret_key
17 self.passphrase = passphrase
18
19def __call__(self, request):
20 timestamp = str(time.time())
21 message = timestamp + request.method + request.path_url + (request.body or '')
22 hmac_key = base64.b64decode(self.secret_key)
23 signature = hmac.new(hmac_key, message, hashlib.sha256)
24 signature_b64 = signature.digest().encode('base64').rstrip('n')
25
26 request.headers.update({
27 'CB-ACCESS-SIGN': signature_b64,
28 'CB-ACCESS-TIMESTAMP': timestamp,
29 'CB-ACCESS-KEY': self.api_key,
30 'CB-ACCESS-PASSPHRASE': self.passphrase,
31 'Content-Type': 'application/json'
32 })
33 return request
34
35api_url = 'https://api.gdax.com/'
36auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS)
37
38# Get accounts
39r = requests.get(api_url + 'accounts', auth=auth)
40print r.json()
41
42
43# Place an order
44order = {
45'size': 1.0,
46'price': 1.0,
47'side': 'buy',
48'product_id': 'BTC-USD',
49}
50r = requests.post(api_url + 'orders', json=order, auth=auth)
51print r.json()
52
53API_SECRET = base64.b64decode(b'{secret}')
54
55TypeError: Unicode-objects must be encoded before hashing