September 24, 2014

How Rich am I

I make no secret about it -- some of my best friends are cryptocurrency aficionados. Many use coinbase to store their cryptocoins. It is in their name that this entry is written. The Python code that follows let's you see how much is available in one's Coinbase wallet. First the code:


#!/usr/bin/python
import hashlib
import hmac
import os
import json
import requests
import time

#This code sample demonstrates a GET and a POST call to the Coinbase API
#Before implementation, set environmental variables with the names API_KEY and API_SECRET.

def make_request(url, body=None):
    nonce = int(time.time() * 1e6)
    message = str(nonce) + url + ('' if body is None else body), 
    signature = hmac.new(os.environ['API_SECRET'], message, hashlib.sha256).hexdigest()


    headers = {'ACCESS_KEY' : os.environ['API_KEY'],
               'ACCESS_SIGNATURE': signature,
               'ACCESS_NONCE': nonce,
               'Accept': 'application/json'}

    # If we are passing data, a POST request is made. Note that content_type is specified as json.
    if body:
        headers.update({'Content-Type': 'application/json'})
        req = requests.post(url, data = body, headers=headers)

    else:
        #req = urllib2.Request(url, headers=headers)
        req = requests.get(url, headers=headers)

    return req.content

# Example of a GET request, where body is nil.
print make_request('https://coinbase.com/api/v1/account/balance')
One needs to set the API_KEY and API_SECRET to the appropriate values off the coinbase settings page. Now, the promised run:
% python ./coinbase.py                  
{"amount":"0.01500000","currency":"BTC"}

No comments:

Post a Comment