Mike Nelson
Mike Nelson

Reputation: 167

Python secret key encoding from API

I've been trying to use the Poloniex APIg. I get a key and secret from my account, exactly like this. Then, following the examples, I should use one of the following forms:

import poloniex

polo = poloniex.Poloniex('yourApiKeyHere','yourSecretKeyHere123')
# or
polo.APIKey = 'yourApiKeyHere'
polo.Secret = 'yourSecretKeyHere123'

By using either one of them, I get this error:

TypeError: key: expected bytes or bytearray, but got 'str'

I've tried:

polo.Secret = b'yourSecretKeyHere123'

And get:

TypeError: Unicode-objects must be encoded before hashing

So I tried:

polo.Secret = 'yourSecretKeyHere123'.encode('utf-8')

I'm a bit out of my depth here with the encoding and would also expect the API just take my secret key as a string. What am I missing?

Upvotes: 0

Views: 1036

Answers (1)

A. STEFANI
A. STEFANI

Reputation: 6736

This code will works (assuming both your Secret & APIKey exists and also that API are not IP or withdraw-only restricted):

import urllib
import urllib2
import json
import time
import hmac,hashlib


req={}

APIKey = "<my_API_key>"
Secret = "<my_secret>"

command="returnBalances"

req['command'] = command

req['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(req)

sign = hmac.new(Secret, post_data, hashlib.sha512).hexdigest()
#print sign
headers = {
    'Sign': sign,
    'Key': APIKey
}

ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())

print jsonRet

Upvotes: 1

Related Questions