API: New Order (POST /fapi/v1/order (HMAC SHA256))

Disclaimer: I’m learing programming. Please be nice :slight_smile:

I’m trying to create a correct POST query for new order using python. I think I followed the documentation, but still something is wrong and I can’t figure it out - anyone knows what might be the issue?
(no worries, api keys are from binance test net)

import requests
import time
import base64
import hmac
import hashlib
import json

def get_sign(data):
    m = hmac.new(api_secret.encode("utf-8"), data.encode("utf-8"), hashlib.sha256)
    return m.hexdigest()


base_url = 'https://testnet.binancefuture.com'
url_path = '/fapi/v1/order'
api_key = 'e51248a69b573171079c0b163df7afe586a6af07682e3563c7d74e1f0a48f467'
api_secret = 'f27c4abde33dfdde5aca2c70877cac04d3345a12571991cbe12c1eeb3117006e'

time=int(time.time() * 1000)

payload = {
    'symbol': 'BTCUSDT',
    'side': 'BUY',
    'type': 'MARKET',
    'quantity': 1,
    'recvWindow': 5000,
    'timestamp': time
}
payload_json = json.dumps(payload)
signature = get_sign(payload_json)

payload['signature'] = signature

header = {
"X-MBX-APIKEY": api_key
}

url = base_url+url_path

response = requests.post(url=url, data=payload, headers=header)

print(response.request.url)
print(response.request.body)
print(response.request.headers)
print(response)

print outputs for reference:
https://testnet.binancefuture.com/fapi/v1/order

symbol=BTCUSDT&side=BUY&type=MARKET&quantity=1&recvWindow=5000&timestamp=1669893333386&signature=7abb0259803ec2b0dbe226c648f56761d0a29af2016d56f6d8b01b9bb5d9cfac

{‘User-Agent’: ‘python-requests/2.28.1’, ‘Accept-Encoding’: ‘gzip, deflate’, ‘Accept’: ‘/’, ‘Connection’: ‘keep-alive’, ‘X-MBX-APIKEY’: ‘e51248a69b573171079c0b163df7afe586a6af07682e3563c7d74e1f0a48f467’, ‘Content-Length’: ‘161’, ‘Content-Type’: ‘application/x-www-form-urlencoded’}

<Response [400]>
Error: b’{“code”:-1022,“msg”:“Signature for this request is not valid.”}’

Hi @Lukas, you need to use urlencode() to convert dictionaries into query strings not the json.dumps()

just change this 2 line

payload_json = json.dumps(payload)
signature = get_sign(payload_json)

to

from urllib.parse import urlencode
query_string=urlencode(payload,True)
signature = get_sign(query_string)

1 Like