python-binance icon indicating copy to clipboard operation
python-binance copied to clipboard

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

Open Roibal opened this issue 8 years ago • 26 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.

Roibal avatar Apr 13 '18 10:04 Roibal

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

i3wangyi avatar Apr 14 '18 05:04 i3wangyi

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

Roibal avatar Apr 14 '18 05:04 Roibal

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.

i3wangyi avatar Apr 14 '18 05:04 i3wangyi

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?

Roibal avatar Apr 14 '18 05:04 Roibal

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.

i3wangyi avatar Apr 14 '18 05:04 i3wangyi

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.

Roibal avatar Apr 14 '18 06:04 Roibal

Try manually syncing your computer time to internet time. Details here for Windows: https://github.com/ccxt/ccxt/issues/850#issuecomment-381308373

ShervinDD avatar Apr 15 '18 01:04 ShervinDD

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.

Roibal avatar Apr 15 '18 04:04 Roibal

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?

Roibal avatar Apr 15 '18 22:04 Roibal

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.

ShervinDD avatar Apr 16 '18 00:04 ShervinDD

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.

Technorocker avatar Apr 30 '18 18:04 Technorocker

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.

ale316 avatar May 29 '18 13:05 ale316

Thanks @ale316. That's a helpful solution.

ShervinDD avatar Jun 08 '18 03:06 ShervinDD

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.

madranet avatar Sep 21 '18 13:09 madranet

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?

normanlmfung avatar Nov 11 '18 10:11 normanlmfung

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

MrRobotXX avatar May 31 '19 21:05 MrRobotXX

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

amitkalo avatar Jun 22 '19 16:06 amitkalo

@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.

wiseinvoker avatar Jan 30 '21 06:01 wiseinvoker

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

normanlmfung avatar Feb 22 '21 07:02 normanlmfung

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.

RobertoGarridoTrillo avatar Jul 06 '21 07:07 RobertoGarridoTrillo