sammchardy/python-binance

APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server's time.

Roibal opened this issue ยท 25 comments

Hello - first off great program. when I run the example code (from readme):

# place a test market buy order, to place an actual order use the create_order function
order = client.create_test_order(
    symbol='BNBBTC',
    side=Client.SIDE_BUY,
    type=Client.ORDER_TYPE_MARKET,
    quantity=100)

I receive the following error:

line 199, in _handle_response
raise BinanceAPIException(response)
binance.exceptions.BinanceAPIException: APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server's time.

I am able to successfully run the previous example:

# get market depth
depth = client.get_order_book(symbol='BNBBTC')

with no problems. How can I fix this issue? I know it has to do with my computer being different than the binance server time, but I thought that this was automatically handled by python-binance? Thanks in advance.

I've experienced this issue a lot (specially in docker environment). I solved the problem by updating the system time either manually or using ntp service

I tried using time.clock_settime() but received an error. What's NTP service? Did you solve it like this (nadir dogan comment): yasinkuyu/binance-trader#63 (comment)

Hi @Roibal NTP is a linux service you can google more about it. Basically I will run
ntpdate -s ntp.ubuntu.com to sync the system time.

No I saw the comment but I didn't succeed with it. I'm developing using Mac, which has the problem but under ubuntu (where my server is) it's totally fine.

Thank you for the info. I'm using Windows, I may try this on a different machine. Have you been able to get a bot working with this library?

I'm not familiar with Windows, but it should have similar service though.
Yes. I'm currently building one with it, have minor issues but overall it's good to me.

From my other comment thread, and thanks to nadir for code:

when I try to run win32api as suggested by nadir's code, I receive following error:

line 19, in <module> win32api.SetSystemTime(tt[0],tt[1],0,tt[2],tt[3],tt[4],tt[5],0) pywintypes.error: (1314, 'SetSystemTime', 'A required privilege is not held by the client.')

I understand this has to do with permissions on my Windows machine.

When I run this code:

gt = client.get_server_time()
print(gt)
print(time.localtime())
aa = str(gt)
bb = aa.replace("{'serverTime': ","")
aa = bb.replace("}","")
gg=int(aa)
ff=gg-10799260
uu=ff/1000
yy=int(uu)
tt=time.localtime(yy)
print(tt)

I receive the following output:

{'serverTime': 1523688379266}
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=14, tm_hour=0, tm_min=46, tm_sec=19, tm_wday=5, tm_yday=104, tm_isdst=1)
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=13, tm_hour=21, tm_min=46, tm_sec=20, tm_wday=4, tm_yday=103, tm_isdst=1)

The first time struct is my local time, the second is the time formatted, which seems to be off by 3 hours and 1 second.

Try manually syncing your computer time to internet time. Details here for Windows: ccxt/ccxt#850 (comment)

hi @ShervinDD , thank you for the suggestion. I was able to 'sync' with Nist.gov internet time, and the 1000 ms error went away. Here's how I did it on Windows 10:

Date & Time -> Internet Time (tab) -> sync with nist.gov

it now says it will sync tomorrow at 7:31 A.M.

hi @ShervinDD - this solution worked for me last night, however, when I tried to run the script today I received the same error (1000ms ahead of server time), and I synchronized it 10 minutes previously (automatically). when I re-synced it (manually) the program worked for a few minutes, but once again it is giving same error message. Is there anyway to fix this inside the program, such as setting request time = binance server time?

I'm not sure. If your system time is constantly out of sync with internet time, then there's something wrong with your system. Try to fix that first.

I use windows myself and havent been getting the timestamp error in a while. Now today out of the blue I cant start my bot. The previous fix was to go into regedit on windows and change the time update interval so it updates every 5 min from the default of once a day. I cant recall exactly the location of the time to change it but its easily found on the internet. Google changing time interval registry settings and it should take you where you need to go.

Yet today I restarted my PC AND went into date/time -> internet time and synced and its still saying timestamp error. so its finicky sometimes.

Sorry for posting on a closed issue, but, having awful internet here I am often burdened with getting rid of this issue in order to interact with Binance's private API methods.

This, for posterity, is my solution. I create wrapper around the client object, with an extra function synced.

import time
from binance.client import Client

class Binance:
    def __init__(self, public_key = '', secret_key = '', sync = False):
        self.time_offset = 0
        self.b = Client(public_key, secret_key)

        if sync:
            self.time_offset = self._get_time_offset()

    def _get_time_offset(self):
        res = self.b.get_server_time()
        return res['serverTime'] - int(time.time() * 1000)

    def synced(self, fn_name, **args):
        args['timestamp'] = int(time.time() - self.time_offset)
        return getattr(self.b, fn_name)(**args)

I then instantiate it and call my private account functions with synced

binance = Binance(public_key = 'my_pub_key', secret_key = 'my_secret_key', sync=True)
binance.synced('order_market_buy',  symbol='BNBBTC', quantity=10)

Hope this is of help.

Thanks @ale316. That's a helpful solution.

I've just had a similar problem [also using OSX]. I'm in Europe and my OSX SystemPreferences for Date & Time are already set to use sync via the internet using Apple's Europe time servers. As an experiment, I changed the prefs to use Apple's US time servers instead and ran the example code again and the error went away.

Interestingly, I've just reset the prefs back to use Apple's Europe time servers again and the error has [so far!] not returned. Seems, on that basis, to be a problem with Apple's time servers.

order_market_buy

hello hello,

args[timestamp] should be in seconds or ms? I suspect ms?

So we should correct from:
def synced(self, fn_name, **args):
args['timestamp'] = int(time.time() - self.time_offset)
return getattr(self.b, fn_name)(**args)

To...
def synced(self, fn_name, **args):
args['timestamp'] = int(time.time() *1000 - self.time_offset)
return getattr(self.b, fn_name)(**args)

Right?

from control panel > date and time > internet time
change the server to >>>> time.nist.gov
it worked with me

Sorry for posting on a closed issue, but, having awful internet here I am often burdened with getting rid of this issue in order to interact with Binance's private API methods.

This, for posterity, is my solution. I create wrapper around the client object, with an extra function synced.

import time
from binance.client import Client

class Binance:
    def __init__(self, public_key = '', secret_key = '', sync = False):
        self.time_offset = 0
        self.b = Client(public_key, secret_key)

        if sync:
            self.time_offset = self._get_time_offset()

    def _get_time_offset(self):
        res = self.b.get_server_time()
        return res['serverTime'] - int(time.time() * 1000)

    def synced(self, fn_name, **args):
        args['timestamp'] = int(time.time() - self.time_offset)
        return getattr(self.b, fn_name)(**args)

I then instantiate it and call my private account functions with synced

binance = Binance(public_key = 'my_pub_key', secret_key = 'my_secret_key', sync=True)
binance.synced('order_market_buy',  symbol='BNBBTC', quantity=10)

Hope this is of help.

can you explain the solution? seems like its not work for me

@ale316 Your idea looks great, but I have add some changes to your code.

class Binance:
    def __init__(self, public_key = '', secret_key = '', sync = False):
        self.time_offset = 0
        self.b = Client(public_key, secret_key)
        self.b.API_URL = 'https://testnet.binance.vision/api' # for testnet

        if sync:
            self.time_offset = self._get_time_offset()
            print( "Offset: %s ms" % (self.time_offset) )

    def _get_time_offset(self):
        res = self.b.get_server_time()
        return res['serverTime'] - int(time.time() * 1000)

    def synced(self, fn_name, **args):
        args['timestamp'] = int(time.time() * 1000 + self.time_offset)
        return getattr(self.b, fn_name)(**args)

my_binance = Binance(API_KEY, SECRET_KEY, True)
# my_binance.synced('order_market_buy',  symbol='BNBBTC', quantity=10)
acc_info = my_binance.synced('get_account', recvWindow=60000)
print(acc_info)

After adding this change, I am able to bypass this issue by removing this line from the pyhon-binance library code.

For Windows, try this: https://steemit.com/crypto/@biyi/how-to-resolve-binance-s-timestamp-ahead-of-server-s-time-challenge
net stop w32time
w32tm /unregister
w32tm /register
net start w32time
w32tm /resync

In my case, I use Windows and from Settings -> Date & Time, with the switch "Set the time automatically" and "Set the time zone automatically" both on, them pressed the "Sync now" button, and that worked for me.

binance.exceptions.BinanceAPIException: APIError(code=-1021): Timestamp for this request is outside of the recvWindow.

I had the same error, I'm using MacOS Catalina Version 10.15.7 If some one had news about this issues please and Thx

Press Windows button -> Data and Time -> Set time automatically + set date automatically; Worked for me perfectly.

In my case, I use Windows and from Settings -> Date & Time, with the switch "Set the time automatically" and "Set the time zone automatically" both on, them pressed the "Sync now" button, and that worked for me.

it worked for me ....

On Windows 10, just go to date/time settings and click on "Synchronize now" (or in french "Synchroniser maintenant").

I was running into this issue when running commands out of a docker container. I run windows wsl2 and found that the linux kernel had a time sync bug. I was able to fix my issue by updating the wsl linux kernel. Here are the steps

windows docker fix

fixed in 5.10.16.3 WSL 2 Linux kernel
Shows issue for Clock Sync is resolved
https://devblogs.microsoft.com/commandline/servicing-the-windows-subsystem-for-linux-wsl-2-linux-kernel/

How to update WSL linux kernel
https://winaero.com/how-to-install-linux-kernel-update-for-wsl-2-in-windows-10/