0

I am quite new to Python and using version 3.6.

I wish i can write code of Python 3.6.1 Post request with HMAC-SHA512 for poloniex trading api

Here is poloniex documentation: https://poloniex.com/support/api/

Apparently, it is different from normal api get request. Here are my parameters.

import urllib.request
import urllib.parse
import hmac
import hashlib
import time

key = '<api key>'
secret = '<secret>' #must sign by your key's "secret" according to the HMAC-SHA512 method
command = 'returnBalances'
nonce = int(time.time())

What to do next? I don't understand how to sign with HMAC-SHA512 & how to properly send POST request. Thanks.

Khit TV
  • 1
  • 2
  • Maybe helpful is in the documentatio, from the API link you provided, around Line 44, https://pastebin.com/fbkheaRb in the `api_query` method `sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()`.. – chickity china chinese chicken Apr 17 '17 at 16:59

2 Answers2

0

Do yourself a favor, and use the requests module for HTTP.

Using requests, this answer shows you how to use HMAC-SHA512 with requests in Python.

Community
  • 1
  • 1
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
0

I have tried to reproduce as follow. However, it looks like i encounter the error.

{'command': 'returnBalances', 'nonce': 1492523610}
command=returnBalances&nonce=1492523610
Traceback (most recent call last):
  File "C:/Users/draft/Desktop/test3.py", line 21, in <module>
    signing = hmac.new(secret, post_data, hashlib.sha512).hexdigest()
  File "C:\Users\draft\AppData\Local\Programs\Python\Python36-32\lib\hmac.py", line 144, in new
    return HMAC(key, msg, digestmod)
  File "C:\Users\draft\AppData\Local\Programs\Python\Python36-32\lib\hmac.py", line 84, in __init__
    self.update(msg)
  File "C:\Users\draft\AppData\Local\Programs\Python\Python36-32\lib\hmac.py", line 93, in update
    self.inner.update(msg)
TypeError: Unicode-objects must be encoded before hashing

Here is my full code after doing study from your help.

import urllib.request
import urllib.parse
import hmac
import hashlib
import time
import json

t = int(time.time())
secret = b'<secret>'
headers = { 'Key' : '<api key>',
            'Sign': ''}
url = 'https://poloniex.com/tradingApi'
req={}

req['command'] = 'returnBalances'
req['nonce'] = int(time.time())
#print (req)

post_data =  urllib.parse.urlencode(req)
#print (post_data)
signing = hmac.new(secret, post_data, hashlib.sha512).hexdigest()
#print (signing)
headers['Sign'] = signing

ret = urllib.request.Request(url, data, headers)
#print (ret)


ret = urllib.request.urlopen(ret)
a = json.loads(ret.read())
#print (a)

Can anyone please check my code? I believe i do the encoding with "urllib.parse.urlencode"
Thank you very much.

Khit TV
  • 1
  • 2