Reputation: 1380
I'm trying to make this work
Here's the error I get:
data: { code: -1022, msg: 'Signature for this request is not valid.' }
Functions
const crypto = require('crypto')
export async function signature (query_string) {
return crypto.createHmac('sha256', apiSecret).update(query_string).digest('hex')
}
export async function order (symbol, quantity, price) {
const query = '?symbol=' + symbol + '&isIsolated=TRUE&side=BUY&quantity=' + quantity + '&price=' + price + '&type=LIMIT&sideEffectType=MARGIN_BUY&recvWindow=5000×tamp=' + Date.now()
const querySigned = await signature(query)
const sendingQuery = query + '&signature=' + querySigned
const queryConfig = {
method: 'POST',
url: 'https://api.binance.com/sapi/v1/margin/order/' + sendingQuery,
headers: {
'X-MBX-APIKEY': apiKey,
},
}
const response = await axios(queryConfig)
return response.data
}
Upvotes: 1
Views: 1383
Reputation: 43481
Don't include the question mark in the input for signature.
const query = 'symbol=' + symbol + // removed the question mark
const queryConfig = {
method: 'POST',
url: 'https://api.binance.com/sapi/v1/margin/order/?' + sendingQuery, // added the question mark
headers: {
'X-MBX-APIKEY': apiKey,
},
}
Source: I looked up my old code from a year ago that was also using the Binance API and found a difference in the question mark (not) passed as the signature input.
I used it for a spot order but I'll still include it. Maybe it will help you debug further if this is not a correct solution.
let query = 'recvWindow=5000×tamp='+(new Date().getTime()) + "&symbol=" + baseAsset + quoteAsset + "&side=" + side + "&quantity=" + baseAmount + "&type=market";
const signature = crypto.createHmac('sha256', apiSecret).update(query).digest("hex");
query += '&signature='+signature;
const result = await axios({
'method': 'POST',
'url': 'https://api.binance.com/api/v3/order?'+query,
'headers': {
'X-MBX-APIKEY': apiKey
}
});
Upvotes: 2