Olgo
Olgo

Reputation: 35

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'

Upvotes: 0

Views: 2559

Answers (2)

typoerrpr
typoerrpr

Reputation: 1667

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'
}

Upvotes: 8

Paulo Scardine
Paulo Scardine

Reputation: 77359

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)

Upvotes: 0

Related Questions