Binance error -1021 in Node.js: two messages, two different fixes
programming.dev
Binance error -1021 in Node.js: two messages, two different fixes
Binance error -1021 looks like one problem, but it comes in two messages that need different fixes: - “Timestamp for this request was 1000ms ahead of the server’s time.” - “Timestamp for this request is outside of the recvWindow.” Binance accepts a signed request only if timestamp < serverTime + 1000 and serverTime - timestamp <= recvWindow. So there is a fixed one-second tolerance for clocks that run fast, and a configurable window (5000 ms by default, 60000 ms at most) for requests that arrive late. “1000ms ahead” is a clock problem. Increasing recvWindow does nothing for it. Sync the machine’s clock with NTP (on Linux, check timedatectl; on Windows, resync the time service), then try again. “Outside of the recvWindow” means the request took too long between signing and arriving, or your clock runs slow. Fix the clock first. Only then consider a slightly larger recvWindow, and keep it small, because Binance recommends 5000 ms or less. Two common bugs cause both messages in Node.js: - Sending seconds instead of milliseconds. Use Date.now(), not Math.floor(Date.now() / 1000). - Building the timestamp once and reusing it for later requests. Create it for each request. If you use the binance npm package (an open-source SDK we maintain, from the same maintainers as the bybit-api and okx-api JavaScript SDKs, with over 4.5 million npm downloads across 10+ SDKs), it adds the timestamp and signature for you, with recvWindow set to 5000 by default. You can change it per client: ts import { MainClient } from 'binance'; const client = new MainClient({ api_key: process.env.BINANCE_API_KEY, api_secret: process.env.BINANCE_API_SECRET, recvWindow: 5000, // the default; raise it only for a genuinely slow link }); const account = await client.getAccountInformation(); console.log(account.balances.length); The SDK also has an optional time-sync mechanism (disableTimeSync: false), but it is off by default and we don’t recommend it. A correct system clock is the real fix. More detail: - Troubleshooting note on the recvWindow error [https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow] - Binance API JavaScript tutorial for Node.js [https://siebly.io/sdk/binance/javascript/tutorial] - Binance JavaScript SDK MainClient reference [https://sieblyio.github.io/docs/binance/api/classes/MainClient.html] Disclosure: we maintain the binance SDK.
0 comments
No comments yet.