· 8 years ago · Dec 17, 2017, 01:54 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):
14 def __init__(self, api_key, secret_key, passphrase):
15 self.api_key = api_key
16 self.secret_key = secret_key
17 self.passphrase = passphrase
18
19 def __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# [{"id": "a1b2c3d4", "balance":...
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# {"id": "0428b97b-bec1-429e-a94c-59992926778d"}
53
54The CB-ACCESS-SIGN header is generated by creating a sha256 HMAC using the base64-decoded secret key on the prehash string timestamp + method + requestPath + body (where + represents string concatenation) and base64-encode the output. The timestamp value is the same as the CB-ACCESS-TIMESTAMP header.
55
56The body is the request body string or omitted if there is no request body (typically for GET requests).
57
58The method should be UPPER CASE.
59
60Remember to first base64-decode the alphanumeric secret string (resulting in 64 bytes) before using it as the key for HMAC. Also, base64-encode the digest output before sending in the header.
61
62Selecting a Timestamp