Search code examples
pythonpython-3.xapibinancebinance-api-client

binance new order api {'code': -1022, 'msg': 'Signature for this request is not valid.'}


i write below code in python for opening new spot trade from binance but when i send request to server i get this response {'code': -1022, 'msg': 'Signature for this request is not valid.'}

class Trade():
def __init__(self):
    self.url = 'https://api.binance.com'
    self.apikey = 'API_KEY'
    self.secret = 'API_SECRET'
    self.time = json.loads(requests.get(self.url+'/api/v1/time').text)['serverTime']

def generate_request_data(self, **kwargs):
    params = kwargs
    query_string = urlencode(params)
    sign = hmac.new(self.secret.encode('utf-8'),
                           query_string.encode('utf-8'),
                           hashlib.sha256).hexdigest()
    params['signature'] = sign
    params['timestamp'] = self.time
    headers = {
        'X-MBX-APIKEY': self.apikey,
        'signature': sign,
    }

    return params, headers

def buy(self, symbol, qty, price):
    params, headers = self.generate_request_data(
        symbol=symbol,
        price=price,
        quantity=qty,
        type='LIMIT',
        side='BUY'
    )
    response = requests.post(url=self.url+'/api/v3/order',
                             params=params,
                             headers=headers)
    return response.json()

Solution

  • I changed the code to below code and then error was fixed

    class Trade():
    def __init__(self):
        self.url = 'https://api.binance.com'
        self.apikey = 'API_KEY'
        self.secret = 'SECRET_KEY'
        self.time = json.loads(requests.get(self.url+'/api/v1/time').text)['serverTime']
    
    def generate_request_data(self, **kwargs):
        params = kwargs
        query_string = urlencode(params)
        sign = hmac.new(self.secret.encode('utf-8'),
                               query_string.encode('utf-8'),
                               hashlib.sha256).hexdigest()
        params['signature'] = sign
        headers = {
            'X-MBX-APIKEY': self.apikey,
            'signature': sign,
        }
    
        return params, headers
    
    def buy(self, symbol, qty, price):
        params, headers = self.generate_request_data(
            symbol=symbol,
            price=price,
            quantity=qty,
            type='LIMIT',
            side='BUY',
            timestamp=self.time,
            timeInForce='GTC'
        )
        response = requests.post(url=self.url+'/api/v3/order',
                                 params=params,
                                 headers=headers)
        return response.json()
    

    now i send timestamp and timeInForce params to generate_request_data method