Binance订单:此请求的时间戳比服务器时间早1000毫秒

发布于 2025-01-15 09:42:59 字数 881 浏览 1 评论 0原文

我正在编写一些Python代码来使用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)

不幸的是,我收到以下错误消息:

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

我已经检查了Binance服务器时间和我的本地时间之间的差异(以毫秒为单位):

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

看来60000的recvWindow是还是不够(但不能超过60K)。我仍然遇到同样的错误。 有人知道我该如何解决这个问题吗?

非常感谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

女中豪杰 2025-01-22 09:42:59

可能是电脑时间不同步。

您可以使用 Windows -> 来完成此操作设置->时间与时间语言->日期和时间时间-> “立即同步”。

屏幕截图:

我也分享图片

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

几味少女 2025-01-22 09:42:59

我实际上使用了公认的解决方案,因为在任何情况下都希望拥有正确的窗口时间。

尽管如此,这里有一个替代代码解决方案(它创建一个 Binance 类并计算时间偏移):

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)

然后调用如下函数:

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

完整线程的链接在这里: https://github.com/sammchardy/python-binance/issues/249

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

南笙 2025-01-22 09:42:59

手动将时钟调慢 1 秒,确保所有时间更新均已关闭。夏令时、自动同步等。

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

め可乐爱微笑 2025-01-22 09:42:59

我在linux上找到了答案!

我在 kali linux 上的一个我正在学习开发的 python 交易应用程序上遇到了同样的问题!

当记录运行 main.py 文件的错误信息警告和调试日志时,我最初得到了这个响应!

***

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

***

在 Linux 上设置时间与在 Windows 上设置时间的过程不同,我仍在探索该选项!

通过在命令提示符中执行此操作,这对我有用!

输入 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 服务处于非活动状态,因此将该值设置为 true 将更正时间:

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

仔细检查以确保其处于活动状态:

┌──(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)-[~]
└─$ 

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)-[~]
└─$ 
如痴如狂 2025-01-22 09:42:59

Binance服务器时间落后于您的服务器时间,因为Binance服务器不经常与ntp服务器同步。

解决方法:

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

如果您使用:npm binance

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

预谋 2025-01-22 09:42:59

对于 C#,我创建了此方法来运行命令行以在 Windows 上重新同步时间,然后再在 Binance 上运行 API:

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();
    }
}

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();
    }
}
素手挽清风 2025-01-22 09:42:59

将以下脚本保存为 SyncWindowsTimeWithBinance.ps1 并以管理员身份运行。它从 Binance 获取当前日期时间,添加时区差异(此处为 +4),并相应地调整(同步)Windows 时间。

# 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

当 Windows 时间同步不起作用或者您想借助代码同步数据时,它非常有用。

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.

海拔太高太耀眼 2025-01-22 09:42:59

确保没有服务以某种方式阻止同步。


在我的特定课程中,FortiClient VPN 的自动启动遇到了麻烦。

  • Windows 10 x64bi 上的 FortiClient 7

我添加了禁用它的具体步骤:

  1. 右键单击任务栏上的 FortiClient 图标,然后选择“关闭 FortiClient”。

  2. 转到命令提示符并输入:net stop fortishield [ENTER]

  3. RUN -> msconfig 并转到“服务”选项卡。取消选中服务 FortiClient Service Scheduler 并[应用] - 现在不要重新启动 PC。

  4. 运行->服务并搜索 FortiClient 服务调度程序。右键->属性并将启动类型更改为:手动

    “在此处输入图像描述"

  5. 重新启动。它也适用于 Win 7 32 位。问候

  6. 然后按照此问题所选答案中的说明进行操作:https://stackoverflow.com/a/72763542/7389293< /a>


  7. < p>现在应该可以工作了:

    “在此处输入图像描述"

来源:https://community.fortinet.com/t5/Support-Forum/Cant-stop-FortiClient-from-starting-on-startup/mp/5078/highlight/true#M4988

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://stackoverflow.com/a/72763542/7389293

  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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文