Ccxt: Binance error: Timestamp for this request was 1000ms ahead of the server's time.

Created on 14 Dec 2017  Â·  34Comments  Â·  Source: ccxt/ccxt

Trying to use Binance, I get this error trying to call fetch_total_balance (probably other methods also but I didn't test any others yet):

ccxt.base.errors.ExchangeNotAvailable: binance GET https://api.binance.com/api/v3/account?timestamp=1513233650395329&signature=.... 400 {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}

I already double checked that my system is syncing to internet time. Could it be a timezone handling issue in CCXT?

I found this thread which shows an example using the python-binance library to check the time delay and I don't see an issue with that library which is why I am guessing it could be a timezone issue in CCXT. When I run:

>>> import time
>>> from binance.client import Client
>>> client = Client(api_key, api_secret)
>>> int(time.time() * 1000) - client.get_server_time()['serverTime']

I consistently get a result around 260ms.

duplicate

Most helpful comment

@jasonmellone

I just synched my clock

Unfortunately, just synching the clock does not work. You have to set up frequent time synchronization with your system (each 10 minutes). Make sure your timezone is not DST. Unfortunately, without seeing your code and without having the info about your system it's hard to tell anything exactly. I mean these details: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue

If that does not help, you can try solutions from this issue: https://github.com/ccxt/ccxt/pull/1477

Namely, for Binance, you can update to most recent version and do this upon instantiation:

import ccxt
b = ccxt.binance({ 'options': { 'adjustForTimeDifference': True }})

It will adjust for the clock unsynchronization itself, but this is less secure.

All 34 comments

Hi! This issue was also covered here (also has an alternative solution to the problem)

https://github.com/ccxt/ccxt/issues/773

mbp:python igorkroitor$ python
Python 2.7.13 (default, Jun  5 2017, 10:04:07) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ccxt
>>> b = ccxt.binance()
>>> import time
>>> print(b.milliseconds(), b.nonce(), time.time()*1000, time.time()*1000 - b.public_get_time()['serverTime'])
(1513244780698, 1513244780698, 1513244780698.4849, -552.51513671875)
>>> print(b.milliseconds(), b.nonce(), time.time()*1000, time.time()*1000 - b.public_get_time()['serverTime'])
(1513244787223, 1513244787223, 1513244787223.836, -477.1630859375)
>>> print(b.milliseconds(), b.nonce(), time.time()*1000, time.time()*1000 - b.public_get_time()['serverTime'])
(1513244788791, 1513244788791, 1513244788791.9668, -578.031982421875)
>>> print(b.milliseconds(), b.nonce(), time.time()*1000, time.time()*1000 - b.public_get_time()['serverTime'])
(1513244790247, 1513244790247, 1513244790247.578, -492.4208984375)
>>> print(b.milliseconds(), b.nonce(), time.time()*1000, time.time()*1000 - b.public_get_time()['serverTime'])
(1513244791639, 1513244791639, 1513244791639.586, -468.4140625)
>>> print(b.milliseconds(), b.nonce(), time.time()*1000, time.time()*1000 - b.public_get_time()['serverTime'])
(1513244794183, 1513244794183, 1513244794183.464, -502.535888671875)
>>> 

I already double checked that my system is syncing to internet time.

Well, a difference of 260ms actually tells the opposite, as far as I understand... Or do I miss something? This can also be an issue with the Binance timesync itself.

You can set .verbose = True on binance instance, or pass that in constructor:

binance = ccxt.binance({'verbose': True})

This will print out the HTTP body + headers + nonces (timestamps) that get sent to Binance and you
can compare those values to actual local time on your system + against some online time service.

Does this help?

Okay, I found the problem. I am initializing with this option:

'nonce': Exchange.microseconds

I am doing this because using the default was producing errors for me with Poloniex (I was getting errors with Poloniex in the case that there was a network issue and I retry to request quickly. With the default, the server would give an error that my nonce was the same as last request because it was my re-try was so quick. But using microseconds fixes it and the 2nd attempt to Poloniex works well).

But for Binance, its means means its sending the microseconds int value which is orders of magnitude different than the real timestamp (locally and on binance server).

While the simple solution is to not include the above for Binance, it starts to get ugly for me if I need to pass certain config options only for certain exchanges.

Rather I would definitely consider this a bug in CCXT. It should not send a microsecond int nonce to Binance pretending its a timestamp, it should always send a real timestamp.

Rather I would definitely consider this a bug in CCXT.

I'm not quite getting... you redefine the nonce for microseconds for binance, you don't want to do it any other way, despite that Binance rejects that, and you consider this a bug in ccxt, despite that inside ccxt the default nonce is seconds or milliseconds (not microseconds) for most exchanges?

Moreover, this is documented in the Manual very thoroughly (at least, I thought so, until I read your previous post).

It should not send a microsecond int nonce as a timestamp to Binance, it should always send a real timestamp.

It sends whatever is returned from nonce(). If it is a seconds-timestamp, it will send seconds. If it is a milliseconds-timestamp (Binance does not accept anything else except milliseconds), it will send those. If you set it to microseconds, it will send microseconds and Binance will not like it. This is not a bug, obviously. If you redefine it, it will send your value. Otherwise it will use the value that best-fits a particular exchange by default.

I mean that a nonce is not the same thing as a timestamp. A nonce may be derived from or include a timestamp of course, but its not the same.

Some exchanges want a nonce and CCXT should use whatever is specified in the config ('nonce': Exchange.microseconds).

But Binance wants a real timestamp and it is used for different purposes than a nonce. Yes it also acts in effect like a nonce to prevent replay attacks, but its also used to ensure transaction timing. As such, it never makes sense to send anything but a real UTC epoch milliseconds timestamp. Trying to send a nonce code in place of such a timestamp is invalid and would never be accepted by Binance.

So I am just saying that CCXT should ignore the nonce config for Binance because Binance never asks for a nonce, it asks for a timestamp.

But its okay, I can just work around it on my side also..

But its okay, I can just work around it on my side also..

No, I think you're right, I've changed that from nonce = this.nonce() to nonce = this.milliseconds() in the implementation of Binance. Should be available in 5 minutes in the next version.

Cheers, and thanks for your hard work on this project, its really awesome! It has saved me lots of time.

If my projects every become profitable, I will send you some coin. :)

Running 1.10.445 and still have this issue

@shprink are you sure you have exactly the same issue? (the "1000ms ahead" one). Do you have time synch enabled on your system? Binance can also reply with "timestamp outside of recvWindow", and that's a totally different message: https://github.com/ccxt/ccxt/issues/936

Same "1000ms ahead" for me today on 1.10.459

From Binance:

Igor Kroitor, [23.12.17 21:24]
Hi, again! We're receiving reports of multiple timestamp-related errors from users who have time synch enabled, and who didn't have this problem with the same code previously. Most of the time "timestamp more than 1000ms ahead of server time" and "timestamp outside of recvWindow"... the 2nd one can probably be tackled by choosing a greater recvWindow, however, the first one is making us subtract a thousand from an otherwise-synchronized time... Is there a better way to solve these issues?

Ninj0r, [24.12.17 11:59]
Timestamp related issues on are on the users end. Synch your clocks (and keep them in sync) and you'll not have issues. Synching your clock is not a one time thing; clocks drift for a host of reasons and need to be repeatedly synced. This is why the default on ntpd is to sync clocks at least every 1024 s (17mins 4 seconds). If the user can't prove they synced their clock within that timeframe, I'm not going to investigate it.

Ninj0r, [24.12.17 12:01]
I'll look into this.

Igor Kroitor, [24.12.17 12:07]
they mostly set default time synch in windows 10

Igor Kroitor, [24.12.17 12:08]
(always on)

Ninj0r, [24.12.17 12:08]
Yeah, which typically does something like a time synch once a day if even that.

Guys, from the above, I guess, it follows, that you need to change the frequency of your time synch updates (set smaller intervals for time polling). You can either do this by googling for it or with 3rd party software. Mac users can change their ntpd settings to alter the time synch params. Hope it helps.

How do make sure time is synced on an android device? I'm using this library in an android app which I'm distributing and the users are getting time sync errors. I'm using react native and JS version of the library.

@kroitor I just synched my clock but still getting the isse:
binance.exceptions.BinanceAPIException: APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server's time.

I have:
get_account(recvWindow=6000000)

The odd thing is that this works intermittently.

I also deleted and recreated my api key already.

@jasonmellone

I just synched my clock

Unfortunately, just synching the clock does not work. You have to set up frequent time synchronization with your system (each 10 minutes). Make sure your timezone is not DST. Unfortunately, without seeing your code and without having the info about your system it's hard to tell anything exactly. I mean these details: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue

If that does not help, you can try solutions from this issue: https://github.com/ccxt/ccxt/pull/1477

Namely, for Binance, you can update to most recent version and do this upon instantiation:

import ccxt
b = ccxt.binance({ 'options': { 'adjustForTimeDifference': True }})

It will adjust for the clock unsynchronization itself, but this is less secure.

@kroitor Sorry, I realized I needed to update my library. After updating I am now getting this error

@jasonmellone Sorry, but that issue you linked isn't a ccxt error at all anymore. It's the error with some different python package of yours (maybe binance-client or dateparser). Not something we can help you with. ccxt does not use those packages at all. Just uninstall the unnecessary packages, if you don't use them (if they break your setup).

So I tried multiple approaches. For my case what worked was a reboot. lol

@jdimstrnate thanks for reporting and for a helpful hint!

For those on ubuntu thanks to awhitehouse104

His post also worked for me.. follow the link and install the ntp package as it says!
heres his message


Thanks, using ntp on ubuntu worked for me.https://www.digitalocean.com/community/tutorials/how-to-set-up-time-synchronization-on-ubuntu-16-04

Rebooting also worked for me. I use a Mac OS.

In Windows 7, manually synchronising with internet time fixed it for me. Go to date and time settings, Internet Time tab > Change settings > update now. The requests to Binance should work and no longer throw the 1021 error.

Windows 7 defaults to synchronising with internet time every week. You can manually change the sync time to daily by editing the registry. Instructions can be found here: https://superuser.com/questions/529367/automatically-sync-windows-time-more-often-than-default?#comment1385466_821537

I got this problem just now, I had rebooted my pc and synced my time but the problem persists. Also, I don't want to go with insecure solution.. Any idea how to solve this issue securely?

@jeffryhartanto

and synced my time

Unfortunately, just synching the clock once or just enabling the time-sync does not work. It should be set to sync every 10 minutes... ↑ see above

It works by adding 'options': { 'adjustForTimeDifference': true }, but you said that it's less secure.. Can you elaborate more on why it's so? Thanks in advance.

@jeffryhartanto

It works by adding 'options': { 'adjustForTimeDifference': true }, but you said that it's less secure..
Can you elaborate more on why it's so?

It is so formally or theoretically, but, most likely, for you it practically means little or it is of very little significance for common user applications.

Basically, the exchange requires the timestamps of your requests to be synced with their clock. This is a security requirement, because the synced timestamp is used during authentication. If the timestamp of a request is out of order or is too late, then the exchange can drop it as "malicious". It is an additional layer of protection, or, in other words, a layer of security. If you enable adjustment for time difference between you and their server then some late packets may be accepted by the exchange. Thus, by enabling the adjustment you violate that exchange's security requirement. And, in general, when you violate any security requirement – this is less secure. That's theory.

However, in practice, this mostly means nothing to you, as nobody will really be able to steal your money, gain access to your account, private data, do damage or anything. What it really means is that if a hacker had enough energy he would crack your secret key a little faster with adjustForTimeDifference. But because nobody is even close to having that much energy on Earth and nobody has the technology to overcome those limitations yet, your security is ok, and it's practically safe to enable the time adjustment.

One side-effect of using adjustForTimeDifference instead of setting up a proper regular/frequent timesync is that working with the same API key from different unsynched computers may throw nonce exceptions from time to time. Apart from that, the level of security mostly remains the same.

Oh, understood.. Thanks a lot for the explanation..

Just to clarify for any reader of this, the original change from Dec 2017, which changed the behaviour of binance to not use the nonce, but to always use the milliseconds, was effectively reverted in https://github.com/ccxt/ccxt/commit/36105a438375d599d52f2e057d0484b1ff223a4f - so setting {nonce: somethingCustom} on a binance instance will cause this error.

im getting {'msg': '{"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server\'s time."}', 'success': False}
how can i fix it im using python-binance #noobprogramer

@deangelo200 with ccxt this can be easily done as described above + in the linked issues, as for python-binance, I guess, you should ask here https://github.com/sammchardy/python-binance/issues instead.

from control panel > date and time > internet time
change the server to >>>> time.nist.gov

on debian do: sudo apt install ntp should fix it right away

Wouldn't adjustForTimeDifference possibly put trades in the wrong candles?

@jorisw nope, since each trade is timestamped.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

albatarnik picture albatarnik  Â·  40Comments

rbn920 picture rbn920  Â·  64Comments

janeCMD picture janeCMD  Â·  35Comments

scoshil picture scoshil  Â·  39Comments

marinsokol5 picture marinsokol5  Â·  60Comments