9

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!

Barry
  • 185
  • 1
  • 3
  • 10
  • 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. – furas Mar 19 '22 at 05:09
  • maybe your problem is date and time in your computer. Your second code gives me negative value `-250` but you have positive value – furas Mar 19 '22 at 05:18
  • [documentation](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#timing-security) 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 time` – furas Mar 19 '22 at 05:33
  • 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. – furas Mar 19 '22 at 05:36

6 Answers6

19

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

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
oguzk
  • 306
  • 2
  • 3
2

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

Jay
  • 23
  • 3
2

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

D.L
  • 4,339
  • 5
  • 22
  • 45
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

jmp
  • 2,456
  • 3
  • 30
  • 47
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();
    }
}
Desolator
  • 22,411
  • 20
  • 73
  • 96
0

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

NTP service was Inactive so setting value to true will correct the time

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

double check to make sure its 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)-[~]

└─$