pythonpython-3.xpoloniex

Why am I getting 'invalid command' from Poloniex API with Python 3?


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'

Solution

  • 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)