sammchardy / python-binance

Binance Exchange API python implementation for automated trading
https://python-binance.readthedocs.io/en/latest/
MIT License
5.98k stars 2.19k forks source link

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

Closed Roibal closed 6 years ago

Roibal commented 6 years ago

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.

i3wangyi commented 6 years ago

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

Roibal commented 6 years ago

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

i3wangyi commented 6 years ago

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.

Roibal commented 6 years ago

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?

i3wangyi commented 6 years ago

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.

Roibal commented 6 years ago

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.

ShervinDD commented 6 years ago

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

Roibal commented 6 years ago

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 commented 6 years ago

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?

ShervinDD commented 6 years ago

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.

Technorocker commented 6 years ago

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.

ale316 commented 6 years ago

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.

ShervinDD commented 6 years ago

Thanks @ale316. That's a helpful solution.

madranet commented 5 years ago

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.

normanlmfung commented 5 years ago

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?

MrRobotXX commented 5 years ago

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

amitkalo commented 5 years ago

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

wiseinvoker commented 3 years ago

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

normanlmfung commented 3 years ago

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

RobertoGarridoTrillo commented 3 years ago

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.

neiromendez commented 2 years ago

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

mujeebishaque commented 2 years ago

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

edsonquam commented 2 years ago

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

reuniware commented 2 years ago

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

JoshuaFry commented 2 years ago

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/