Samuel
Samuel

Reputation: 27

Python3: Custom Encrypted Headers URLLIB - KrakenAPI

Alright, so I'm a little outside of my league on this one I think. I'm attempting to facilitate custom HTTP headers what is noted here:

    API-Key = API key
    API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key

from https://www.kraken.com/help/api

I'm trying to work solely out of urllib if at all possible.

Below is one of many attempts to get it encoded like required:

    import os
    import sys
    import time
    import datetime
    import urllib.request
    import urllib.parse
    import json
    import hashlib
    import hmac
    import base64

    APIKey = 'ThisKey'
    secret = 'ThisSecret'

    data = {}

    data['nonce'] = int(time.time()*1000)

    data['asset'] = 'ZUSD'

    uripath = '/0/private/TradeBalance'

    postdata = urllib.parse.urlencode(data)

    encoded = (str(data['nonce']) + postdata).encode()
    message = uripath.encode() + hashlib.sha256(encoded).digest()

    signature = hmac.new(base64.b64decode(secret),
                    message, hashlib.sha512)
    sigdigest = base64.b64encode(signature.digest())

    #this is purely for checking how things are coming along.
    print(sigdigest.decode())

    headers = {
    'API-Key': APIKey,
    'API-Sign': sigdigest.decode()
    }

The above may be working just fine, where I'm struggling now is appropriately getting it to the site. This is my most recent attempt:

    myBalance = urllib.urlopen('https://api.kraken.com/0/private/TradeBalance', urllib.parse.urlencode({'asset': 'ZUSD'}).encode("utf-8"), headers)

Any help is greatly appreciated. Thanks!

Upvotes: 0

Views: 562

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55913

urlopen doesn't support adding headers, so you need to create a Request object and pass it to urlopen:

url = 'https://api.kraken.com/0/private/TradeBalance'
body = urllib.parse.urlencode({'asset': 'ZUSD'}).encode("utf-8")
headers = {
    'API-Key': APIKey,
    'API-Sign': sigdigest.decode()
}

request = urllib.request.Request(url, data=body, headers=headers)
response = urllib.request.urlopen(request)

Upvotes: 1

Related Questions