Timestamp for this request is outside of the recvWindow.

Hi guys, i am experiencing issues with server timestamp when i call the accountInfo function but not when i call the trade function. can someone help me figure out what is wrong?

export async function GET(request:Request) {
  try {
    const time = await client2.time();
    console.log(time);
    //  const connectTest = await client2.accountInfo({useServerTime:true});
     //console.log(connectTest);
    const trades = await client2.trades( {symbol: 'BTCBUSD', limit: 5});
    //const orders = await client2.openOrders({symbol: 'BTCBUSD'});

    console.log(trades)
    return new Response(JSON.stringify(trades));
  
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: error})
  }
}
const timeOffset = 100;

const client2 = Binance({
  apiKey: apiKey,
  apiSecret: apiSecret,
  getTime: () => Math.floor(Date.now()/ timeOffset),
})

Please consult Error "Timestamp for this request is outside of the recvWindow"

1 Like

Hmm not sure what client are you using but with Mida it’s just one liner and I never got this issue

import { login, } from "@reiryoku/mida";

const myAccount = await login("Binance/Spot", {
    apiKey: "***",
    apiSecret: "***",
});

const trades = await myAccount.getTrades("BTCBUSD");

It’s free package GitHub - Reiryoku-Technologies/Mida: The open-source and cross-platform trading framework

1 Like

Hi guys, thanks for coming around to help, i realised i was not using the right library. however now i am doing it with the correct one, i am still struggling to get the data like i want to.

 
export async function GET() {
  const res = await fetch('https://api.binance.com/api/v3/account', {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': apiKey,
      'API-Secret': apiSecret,
      'signature': null,
      'timestamp': Date.now(),
      'recvWindow': '60000'
    },
  });
  const data = await res.json();
 
  return NextResponse.json({ data });
}

i get error message data": {
“code”: -1102,
“msg”: “Mandatory parameter ‘signature’ was not sent, was empty/null, or malformed.”
} any clue of what value is expected in signature, please?

1 Like

Please see SIGNED Endpoint Examples for POST /api/v3/order in documentation for signature computation algorithm.

Binance has a connector library for Node.js (@binance/connector), but it won’t work on the Web. You’ll need to use Web Cryptography API for signatures.

Example code
async function signHMAC(requestBody, secret) {
  const encoder = new TextEncoder()
  const requestBodyBytes = encoder.encode(requestBody)
  const secretBytes = encoder.encode(secret)

  const subtle = window.crypto.subtle
  const key = await subtle.importKey(
    'raw',				// key format
    secretBytes,  // key data
    {							// HMAC parameters
      name: 'HMAC',
	    hash: 'SHA-256'
  	},
		false,				// not extractable key
    ['sign']			// allowed uses
  )
  const signatureBytes = await subtle.sign('HMAC', key, requestBodyBytes)

  const signatureHex = [...new Uint8Array(signatureBytes)]
  	.map(b => b.toString(16).padStart(2, '0'))
  	.join('')
  return signatureHex
}

const exampleBody = 'symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559'
const exampleSecret = 'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j'

console.log(await signHMAC(exampleBody, exampleSecret))
// c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71
1 Like

i did refer to the documentation Binance signature documentation link for signature then implemented it as below however i am having error message ““data”: {
“code”: -1102,
“msg”: “Mandatory parameter ‘signature’ was not sent, was empty/null, or malformed.”
}”

export async function GET() {

  if (!apiSecret) {
    throw new Error('API secret is not defined!');
  }
  const timestamp = Date.now();
  const signature = (timestamp:any) => {
    return crypto.createHmac('sha256',  apiSecret)
  .update(`timestamp=${timestamp}`)
  .digest('hex');
} 

const  computedSignature = signature(timestamp);
  
console.log(typeof(computedSignature))
console.log("hashing the string: ");
console.log(`timestamp=${timestamp}`);
console.log("and return:");

 
  const res = await fetch('https://api.binance.com/api/v3/account', {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': apiKey,
      'X-MBX-APIKEY': apiSecret,
      'signature': computedSignature,
      'recvWindow': '60000'
    },
  });
  const data = await res.json();
 
  return NextResponse.json({ data });
}```
1 Like

'API-Key': apiKey

You don’t need this header, only X-MBX-APIKEY which should contain apiKey, not the secret.

'signature': computedSignature,
'recvWindow': '60000'

These parameters should be passed in the query string, not as headers. Add them to the URL. You also need to include timestamp as a parameter, and sign all the parameters.

const parameters = `recvWindow=60000&timestamp=${timestamp}`;

const signature = crypto.createHmac('sha256',  apiSecret)
  .update(parameters)
  .digest('hex');

const url = `https://api.binance.com/api/v3/account?${parameters}&signature=${signature}`

const res = await fetch(url, {
  headers: {
    'Content-Type': 'application/json',
    'X-MBX-APIKEY': apiKey
  }
});

thanks for this, i made the correction but it is now back to recvwindow error

export async function GET() {

  if (!apiSecret) {
    throw new Error('API secret is not defined!');
  }

   // Fetch server time from Binance
   const timeRes = await fetch('https://api.binance.com/api/v3/time');
   const timeData = await timeRes.json();
   const timestamp = timeData.serverTime;
 
   const recvWindow = '60000';
   const queryString = `recvWindow=${recvWindow}&timestamp=${timestamp}`;
   const signature = crypto.createHmac('sha256', apiSecret)
    .update(queryString)
    .digest('hex');
  
console.log(timestamp)
console.log("hashing the string: ");
console.log(`timestamp=${queryString}`);
console.log("and return:", signature);

 
  const res = await fetch(`https://api.binance.com/api/v3/account?${queryString}&signature=${signature}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'X-MBX-APIKEY': apiKey,
  
    },
  });
  const data = await res.json();
 
  return NextResponse.json({ data });
}

Why you don’t Use Mida? You find it free on Github

It’s caused by your system clock, 99% of the time. More info here, including how to sync your system clock: