Jo3Dirt
Jo3Dirt

Reputation: 109

Python Poloniex API Call

I have the following code that I am trying to make an API call to Poloniex according to their instructions

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


Key = "whatever your key is"
Sign = "whatever your secret is"

def returnBalances(balances):
    nonce = int(round(time.time()-599900000)*10)
    parms = {"returnBalances":balances,
             "nonce":nonce}

    parms = urllib.parse.urlencode(parms)
    hashed = hmac.new(b'Sign',digestmod=hashlib.sha512)
    signature = hashed.hexdigest()

    headers = {"Content-type":"application/x-www-form-urlencoded",
               "Key":Key,
               "Sign":signature}

    conn = urllib.request.urlopen("https://poloniex.com")
    conn.request("POST","/tradingApi",parms,headers)

    response = conn.getresponse()
    print(response.status,response.reason)

returnBalances('balances')

When I run this I get this error message

HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

Can someone please help?

Upvotes: 2

Views: 695

Answers (1)

t.m.adam
t.m.adam

Reputation: 15376

  • You can catch HTTP errors with urllib.error.HTTPError
  • POST data should be bytes, so you have to encode parms
  • urllib.request.urlopen returns a HTTPResponse object, which has no request method.
    If you want to set headers and other parameters you should use urllib.request.Request
  • According to the api docs the post parameters should be 'nonce' and 'command', so i modified your function to accept 'returnBalances' as a parameter and use it in parms["command"]

def api_call(command):
    nonce = int(round(time.time()-599900000)*10)
    parms = {"command":command, "nonce":nonce}
    parms = urllib.parse.urlencode(parms).encode()

    hashed = hmac.new(Sign.encode(), parms, digestmod=hashlib.sha512)
    signature = hashed.hexdigest()
    headers = {"Key":Key, "Sign":signature}

    req = urllib.request.Request("https://poloniex.com/tradingApi", headers=headers)
    try:
        conn = urllib.request.urlopen(req, data=parms)
    except urllib.error.HTTPError as e:
        conn = e
    print(conn.status,conn.reason)
    return json.loads(conn.read().decode())

balances = api_call("returnBalances")

Upvotes: 2

Related Questions