0

I'm trying to use my Poloniex API secret and key to check balances on my account. However, I keep getting "invalid command" returned as a response.

Below is my code in Python3:

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

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

        print(post_data)
        req = urllib.request.Request(url='https://poloniex.com/tradingApi', headers=headers)
        res = urllib.request.urlopen(req, timeout=20)

        jsonRet = json.loads(res.read().decode('utf-8'))
        return self.post_process(jsonRet)

print(post_data) returns what i would expect to see:

b'nonce=1491334646563&command=returnBalances'
dot.Py
  • 5,007
  • 5
  • 31
  • 52
Olgo
  • 35
  • 1
  • 6

2 Answers2

8

Send Content-Type header

This excellent article pointed me to the right direction. It appears python 3's request library skips sending Content-Type header, which causes Polo to reject the request.

'Content-Type': 'application/x-www-form-urlencoded'

headers:

headers = {
    'Sign': hmac.new(SECRET.encode(), post_data, hashlib.sha512).hexdigest(),
    'Key': API_KEY,
    'Content-Type': 'application/x-www-form-urlencoded'
}
typoerrpr
  • 1,626
  • 21
  • 18
0

I guess you must send the post_data with the request. I like to use the requests library instead of urllib directly, but it should be something like this with plain urllib:

req = urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers)
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
  • Thanks! i thought post_data was included with the header in the "sign=" line. I'm very new with this urllib stuff and im just trying to hack a preexisting API wrapper to work with python 3. – Olgo Apr 04 '17 at 20:25