Binance order: Timestamp for this request was 1000ms ahead of the server's time
Asked Answered
G

8

13

I am writing some Python code to create an order with the Binance API:

from binance.client import Client

client = Client(API_KEY, SECRET_KEY)

client.create_order(symbol='BTCUSDT',
                    recvWindow=59999, #The value can't be greater than 60K
                    side='BUY',
                    type='MARKET',
                    quantity = 0.004)

Unfortunately I get the following error message:

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

I already checked the difference (in miliseconds) between the Binance server time and my local time:

import time
import requests
import json
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)

result = json.loads(r.content)

print(int(t)-result["serverTime"]) 

OUTPUT: 6997

It seems that the recvWindow of 60000 is still not sufficient (but it may not exceed 60K). I still get the same error. Does anybody know how I can solve this issue?

Many thanks in advance!

Gayelord answered 18/3, 2022 at 17:10 Comment(4)
always put full error message (starting at word "Traceback") in question (not in comments) as text (not screenshot, not link to external portal). There are other useful information.Bozcaada
maybe your problem is date and time in your computer. Your second code gives me negative value -250 but you have positive valueBozcaada
documentation shows if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) { which can rewrite as (serverTime - recvWindow) <= timestamp < (serverTime + 1000) and maybe your timestamp satisfies (serverTime - recvWindow) <= timestamp but not satisfies timestamp < (serverTime + 1000) - and this can be in your error Timestamp for this request was 1000ms ahead of the server's timeBozcaada
you can writeh timestamp < (serverTime + 1000) as timestamp - serverTime < 1000 which is te same as your int(t)-result["serverTime"] but you get 6997 and this is not satisfies 6997 < 1000 As for me you have to correct clock/time in your system. OR maybe you need faster connection.Bozcaada
C
30

Probably the PC's time is out of sync.

You can do it using Windows -> Setting-> Time & Language -> Date & Time -> 'Sync Now'.

Screenshot:

I share the picture as well

Caledonian answered 26/6, 2022 at 16:58 Comment(4)
Thank you for this answer, Is there any way to automate this on Python3 if needed?Ario
As for the code, I don't know. I just found such solution while writing appCaledonian
this works, but I have to repeat the process. Is there a way to permanently sync in windows 11 ?Predominance
You could use w32tm /resync (needs to be run as administrator) or set the automated sync time lower: w32tm /resyncHypercorrection
P
3

I actually used the accepted solution as it is desirable to have the correct windows time in any event.

Nevertheless, here is an alternative code solution (which makes a Binance class and computes the time offset) for the same:

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)

and then call function like this:

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

The link to the full thread is here: https://github.com/sammchardy/python-binance/issues/249

Predominance answered 26/10, 2022 at 11:18 Comment(0)
A
2

Manually set your clock back 1 second, ensure that ALL time updates are off. Daylights savings, autosync etc.

Attainable answered 30/3, 2022 at 18:43 Comment(0)
T
1

I found the answer on linux!

I had the same problem in kali linux on a python trading application i am learning to develop!

When logging the error info warnings and debug logs running the main.py file I get this response intially!

***

2023-04-10 02:53:10,945 ERROR :: Error while making GET request to /fapi/v1/account/: {'code': -1021, 'msg': "Timestamp for this request was 1000ms ahead of the server's time."} (error code 400)
2023-04-10 02:53:10,949 INFO :: Binance Futures Client successfully initialized

***

Setting the time on Linux is not the procedure for windows and I am still exploring that option!

This worked for me by following this in the command prompt!

Enter timedatectl:

┌──(a37trillion㉿localhost)-[~]
└─$ timedatectl
               Local time: Mon 2023-04-10 04:07:50 UTC
           Universal time: Mon 2023-04-10 04:07:50 UTC
                 RTC time: Mon 2023-04-10 04:07:48
                Time zone: Etc/UTC (UTC, +0000)
System clock synchronized: no
              NTP service: inactive
          RTC in local TZ: no

The NTP service was inactive, so setting the value to true will correct the time:

┌──(a37trillion㉿localhost)-[~]
└─$ sudo timedatectl set-ntp true                 
[sudo] password for a37trillion: 

Double-check to make sure it's active:

┌──(a37trillion㉿localhost)-[~]
└─$ timedatectl
               Local time: Mon 2023-04-10 04:09:19 UTC
           Universal time: Mon 2023-04-10 04:09:19 UTC
                 RTC time: Mon 2023-04-10 04:09:19
                Time zone: Etc/UTC (UTC, +0000)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no
                                                                                                                                                                                                                                                                                                                                                                                        
┌──(a37trillion㉿localhost)-[~]
└─$ 
Topmost answered 10/4, 2023 at 4:25 Comment(0)
G
0

Binance server time is behind your server time, because Binance servers do not sync often with ntp servers.

Workaround:

binance.setTimeOffset(-1000); // -1 sec

its if you use: npm binance

Grunter answered 12/10, 2022 at 16:54 Comment(0)
P
0

For C#, I created this method to run command line to resync time on windows before running an API on Binance:

public static void ResyncWindowsTime()
{
    var commands = new List<string>() 
    { 
        "net stop w32time",
        "w32tm /unregister",
        "w32tm /register",
        "net start w32time",
        "w32tm /resync"
    };

    var process = new Process();
    var startInfo = new ProcessStartInfo();
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    process.StartInfo = startInfo;

    foreach (var command in commands)
    {
        startInfo.Arguments = "/C " + command;
        process.Start();
        process.WaitForExit();
    }
}
Photon answered 16/12, 2022 at 21:19 Comment(0)
M
0

Save the following script as SyncWindowsTimeWithBinance.ps1 and run it as administrator. It gets the current datetime from Binance, adds the timezone difference (+4 here), and adjusts (synchronizes) the Windows time accordingly.

# Fetch server time from Binance API
$response = Invoke-RestMethod -Uri "https://api.binance.com/api/v3/time"
$serverTime = $response.serverTime

# Convert server time (milliseconds since Unix epoch) to DateTime
$epoch = Get-Date -Date "01/01/1970" -Hour 0 -Minute 0 -Second 0
$serverDateTime = $epoch.AddMilliseconds($serverTime)

# Adjust to timezone +4
$desiredDateTime = $serverDateTime.AddHours(4)

# Format the date and time
$formattedDateTime = Get-Date -Date $desiredDateTime -Format "yyyy-MM-dd HH:mm:ss"

# Set the system's date and time (requires administrative privileges)
Set-Date -Date $formattedDateTime

It is useful when Windows time synchronization is not working or you want to synchronize data with the help of code.

Mezzo answered 17/3 at 21:10 Comment(0)
B
0

Be sure there's not a service blocking somehow the synchronization.


In my specific clase, the automatic start up of FortiClient VPN was in the way.

  • FortiClient 7 on Windows 10 x64bi

I add to follow the specific steps for disabling it:

  1. Right-click on the FortiClient icon on the taskbar and select "Shutdown FortiClient".

  2. Go to command prompt and enter: net stop fortishield [ENTER]

  3. RUN -> msconfig and go to services tab. Uncheck the service FortiClient Service Scheduler and [APPLY] - Do not restart the PC now.

  4. RUN -> services and search for FortiClient Service Scheduler. Right-click -> Properties and change the startup type to: Manual

    enter image description here

  5. Reboot. It also worked on Win 7 32bit. Regards

  6. Then follow the instructions from the selected answer for this question: https://mcmap.net/q/846979/-binance-order-timestamp-for-this-request-was-1000ms-ahead-of-the-server-39-s-time

  7. It should work now:

    enter image description here

Source: https://community.fortinet.com/t5/Support-Forum/Cant-stop-FortiClient-from-starting-on-startup/m-p/5078/highlight/true#M4988

Bury answered 14/8 at 0:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.