Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binance API call with SHA56 and Python requests

Haven't worked in Python much and I'm obviously not sending the proper signature being asked for. How do I hash it and pass it in properly?

SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation.
The signature is not case sensitive.
totalParams is defined as the query string concatenated with the request body.

Full Documentation: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md

import requests, json, time, hashlib


apikey = "myactualapikey"
secret = "myrealsecret"
test = requests.get("https://api.binance.com/api/v1/ping")
servertime = requests.get("https://api.binance.com/api/v1/time")

servertimeobject = json.loads(servertime.text)
servertimeint = servertimeobject['serverTime']

hashedsig = hashlib.sha256(secret)

userdata = requests.get("https://api.binance.com/api/v3/account",
    params = {
        "signature" : hashedsig,
        "timestamp" : servertimeint,
    },
    headers = {
        "X-MBX-APIKEY" : apikey,
    }
)
print(userdata)

I am getting

{"code":-1100,"msg":"Illegal characters found in parameter 'signature'; legal range is '^[A-Fa-f0-9]{64}$'."}
like image 878
William Avatar asked Feb 02 '18 23:02

William


1 Answers

This:

hashedsig = hashlib.sha256(secret)

Gives you a hash object, not a string. You need to get the string in hex form:

hashedsig = hashlib.sha256(secret).hexdigest()

You could have figured this out by comparing the documentation you linked (which shows they require hex strings) with your original hashedsig and the functions it provides.

Secondly, as a commenter pointed out, you need to apply HMAC, not just SHA256:

params = urlencode({
    "signature" : hashedsig,
    "timestamp" : servertimeint,
})
hashedsig = hmac.new(secret.encode(), params.encode(), hashlib.sha256).hexdigest()

You can find similar code here: http://python-binance.readthedocs.io/en/latest/_modules/binance/client.html

like image 73
John Zwinck Avatar answered Sep 29 '22 03:09

John Zwinck