I'm writing a bot for https://poloniex.com/support/api/
The public methods all work fine, but the Trading API Methods require some extra tricks:
All calls to the trading API are sent via HTTP POST to https://poloniex.com/tradingApi and must contain the following headers:
Key - Your API key.
Sign - The query's POST data signed by your key's "secret" according to the HMAC-SHA512 method.
Additionally, all queries must include a "nonce" POST parameter. The nonce parameter is an integer which must always be greater than the previous nonce used.
All responses from the trading API are in JSON format.
My code for returnBalances looks like this:
import hashlib
import hmac
from time import time
import requests
class Poloniex:
def __init__(self, APIKey, Secret):
self.APIKey = APIKey
self.Secret = Secret
def returnBalances(self):
url = 'https://poloniex.com/tradingApi'
payload = {
'command': 'returnBalances',
'nonce': int(time() * 1000),
}
headers = {
'Key': self.APIKey,
'Sign': hmac.new(self.Secret, payload, hashlib.sha512).hexdigest(),
}
r = requests.post(url, headers=headers, data=payload)
return r.json()
trading.py:
APIkey = 'AAA-BBB-CCC'
secret = b'123abc'
polo = Poloniex(APIkey, secret)
print(polo.returnBalances())
And I got the following error:
Traceback (most recent call last):
File "C:/Python/Poloniex/trading.py", line 5, in <module>
print(polo.returnBalances())
File "C:\Python\Poloniex\poloniex.py", line 22, in returnBalances
'Sign': hmac.new(self.Secret, payload, hashlib.sha512).hexdigest(),
File "C:\Users\Balazs91\AppData\Local\Programs\Python\Python35-32\lib\hmac.py", line 144, in new
return HMAC(key, msg, digestmod)
File "C:\Users\Balazs91\AppData\Local\Programs\Python\Python35-32\lib\hmac.py", line 84, in __init__
self.update(msg)
File "C:\Users\Balazs91\AppData\Local\Programs\Python\Python35-32\lib\hmac.py", line 93, in update
self.inner.update(msg)
TypeError: object supporting the buffer API required
Process finished with exit code 1
I've also tried to implement the following, but it didn't help: https://mcmap.net/q/1328655/-hash_hmac-sha512-authentication-in-python
Any help is highly appreciated!
payload
inreturnBalances
is a dict, which does not support the buffer API (read: a cheap bytes-like representation). You probably want `payload = str(dict(command='returnBalances', nonce=...))' as the string representation of a dict like that happens to equal the JSON-representation; it's bytes-encoded form can be sent to to HMAC. – Holocaine