Hi, I’m trying to send balance requests with my python code. However, I found that the code only works for the first time. When I send the request second time, I’ll get the 1022 Signature for this request is not valid error. Is there any idea that cause the error?
My code:
import requests
import json
import hashlib, hmac
from urllib.parse import urlencode
class BinanceFutures():
def __init__(self, testing = True):
self._apiSecret = "I'm sure it is correct"
self._defaultHeaders = {"X-MBX-APIKEY": "I'm sure it is correct"}
self.apiBaseUrl = "https://testnet.binancefuture.com" if testing else "https://fapi.binance.com"
def _getServerTime(self):
serverTime = requests.get("https://api.binance.com/api/v1/time")
serverTimeObject = json.loads(serverTime.text)
return serverTimeObject['serverTime']
def _signQuery(self, query):
return hmac.new(self._apiSecret.encode('utf-8'), query.encode('utf-8'), hashlib.sha256).hexdigest()
### GET REQUESTS
def _simpleGetRequest(self, urlPath, params = {}):
params['timestamp'] = self._getServerTime()
params['signature'] = self._signQuery( urlencode(params) )
# I'd tried both of these, same error occurred
# res = requests.get(f'{self.apiBaseUrl}{urlPath}', params = params, headers = self._defaultHeaders)
res = requests.get(f'{self.apiBaseUrl}{urlPath}?{urlencode(params)}', headers = self._defaultHeaders)
return res.status_code, res.text
# Get Account Info
def account(self):
return self._simpleGetRequest('/fapi/v2/account')
# Get Current Balance
def balance(self):
return self._simpleGetRequest('/fapi/v2/balance')
Additional:
I’ve confirmed these steps:
- My Api Key is correctly set
- My Api Secret is correctly set
- The parameters of url is in correct order: Both request url is in the format of https://testnet.binancefuture.com/fapi/v2/balance?timestamp=XXXXX&signature=XXXXX
- The Signature Algo is SHA256