×
Create a new article
Write your page title here:
We currently have 3,187 articles on s23. Type your article name above or create one of the articles listed here!



    s23
    3,187Articles

    Coinbase is a crypto currency exchange (http://coinbase.com/)

    Here is some Python code to connect to its API with your own API key and secret you can generate on their site.

    The auth part is taken from the official example [1] but fixed to work on Python 3, original code causes error with the hmac part when creating the signature. It also adds the missing CB-VERSION header and shows an example how to get balance from the primary account.


    # Create custom authentication for Coinbase API
    # official docs fixed to work on Python3 (encode('utf-8')
    # and added needed CB-VERSION headers
    class CoinbaseWalletAuth(AuthBase):
        def __init__(self, api_key, secret_key):
            self.api_key = api_key
            self.secret_key = secret_key
    
        def __call__(self, request):
            timestamp = str(int(time.time()))
            message = timestamp + request.method + request.path_url + (request.body or '')
            realsecret_key=self.secret_key.encode('utf-8')
            signature = hmac.new(realsecret_key, message.encode('utf-8'), hashlib.sha256).hexdigest()
    
            request.headers.update({
                'CB-ACCESS-SIGN': signature,
                'CB-ACCESS-TIMESTAMP': timestamp,
                'CB-ACCESS-KEY': self.api_key,
                'CB-VERSION': '2018-12-22',
            })
            return request
    
    # FIXME: add your API key and secret generated on Coinbase
    API_KEY = ''
    API_SECRET = ''
    
    api_url = 'https://api.coinbase.com/v2/'
    
    auth = CoinbaseWalletAuth(API_KEY, API_SECRET)
    
    # get the user name on Coinbase
    try:
        r = requests.get(api_url + 'user', auth=auth)
    except Exception as err:
        print('failed to talk to Coinbase - {0} - {1}'.format(err.message, err.args))
        sys.exit(2)
    
    username = r.json()['data']['name']
    
    print('Coinbase user: ' + str(username))
    
    # get balance (amount and currency) from the primary Coinbase account
    try:
        r = requests.get(api_url + 'accounts', auth=auth)
    except Exception as err:
        print('failed to talk to Coinbase - {0} - {1}'.format(err.message, err.args))
        sys.exit(2)
    
    resp = r.json()
    
    amount=resp['data'][0]['balance']['amount']
    currency=resp['data'][0]['balance']['currency']
    
    print(str(amount) + ' ' + str(currency))
    
    Cookies help us deliver our services. By using our services, you agree to our use of cookies.
    Cookies help us deliver our services. By using our services, you agree to our use of cookies.