Reputation: 355
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!
Upvotes: 14
Views: 27421
Reputation: 2382
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.
I add to follow the specific steps for disabling it:
Right-click on the FortiClient icon on the taskbar and select "Shutdown FortiClient".
Go to command prompt and enter: net stop fortishield
[ENTER]
RUN -> msconfig
and go to services tab. Uncheck the service FortiClient Service Scheduler and [APPLY] - Do not restart the PC now.
RUN -> services and search for FortiClient Service Scheduler. Right-click -> Properties and change the startup type to: Manual
Reboot. It also worked on Win 7 32bit. Regards
Then follow the instructions from the selected answer for this question: https://stackoverflow.com/a/72763542/7389293
It should work now:
Upvotes: 0
Reputation: 1
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.
Upvotes: 0
Reputation: 11
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)-[~]
└─$
Upvotes: 1
Reputation: 22739
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();
}
}
Upvotes: 0
Reputation: 5694
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
Upvotes: 4
Reputation: 2512
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
Upvotes: 0
Reputation: 456
Probably the PC's time is out of sync.
You can do it using Windows -> Setting-> Time & Language -> Date & Time -> 'Sync Now'.
Screenshot:
Upvotes: 34
Reputation: 23
Manually set your clock back 1 second, ensure that ALL time updates are off. Daylights savings, autosync etc.
Upvotes: 2