Lars L. Christensen
Lars L. Christensen

Reputation: 21

Binance futures with python, requests and signature

I am trying to trade futures on binance with python using the requests module.

I have the following code:

import requests
import time
API_KEY ="your key"
SECRET_KEY="your secret key"

base_url = "https://fapi.binance.com"
api_path = "/fapi/v1/order"

headers={
'X-MBX-APIKEY': API_KEY
}

my_time=int(time.time() * 1000)
my_timestamp="timestamp="+str(my_time)

url_open=base_url+api_path+"?symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp+"&signature="+SECRET_KEY

response = requests.get(url_open,headers=headers)

This code returns the following error: {"code":-1022,"msg":"Signature for this request is not valid."}

I have also tried hashing the signature:

import hmac
import hashlib
query_string="symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp
HashSig=hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

url_open=base_url+api_path+"?symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp+"&signature="+HashSig

response = requests.get(url_open,headers=headers)

This too returns the error: {"code":-1022,"msg":"Signature for this request is not valid."}

and I have tried the following code:

query_string=my_timestamp
HashSig=hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

url_open=base_url+api_path+"?symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp+"&signature="+HashSig

response = requests.get(url_open,headers=headers)

and this gives the same error: {"code":-1022,"msg":"Signature for this request is not valid."}

I don't know how to make the signature, can someone please help me I have searched a lot on google but I have not been able to find a solution. My goal is to trade futures on binance with python

Upvotes: 2

Views: 1829

Answers (1)

Tarique
Tarique

Reputation: 1461

first of all, I think you need to make a post request not get request for creating an order. check the API doc: https://binance-docs.github.io/apidocs/futures/en/#new-order-trade

I also faced similar issue with Binance API.

this is what finally worked for me:

from urllib.parse import urlencode
import hmac

params = {'symbol':'MATICUSDT', 
'side':'BUY',
'type':'MARKET',
'quantity':40, 
'timestamp': int(time.time() * 1000) - 3000
}

signature_payload = urlencode(params)
signature = hmac.new(SECRET_KEY.encode(), signature_payload.encode(), 'sha256').hexdigest()
params['signature'] = signature

# pass the params to requests.post
# I took a different approach though

Also I had to subtract 3000 from timestamp otherwise Server kept complaining.

Upvotes: 1

Related Questions