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

问题描述 投票:0回答:7

我正在编写一些 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."

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

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)。我仍然遇到同样的错误。 有人知道我该如何解决这个问题吗?

提前非常感谢!

python datetime cryptoapi binance-api-client
7个回答
26
投票

可能是电脑时间不同步。

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

截图:

I share the picture as well


2
投票

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


2
投票

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

尽管如此,这里有一个替代代码解决方案(它创建一个 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


0
投票

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

解决方法:

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

如果您使用:npm binance


0
投票

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

0
投票

我在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 上的程序,我仍在探索该选项!

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

输入时间日期控制

┌──(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: 

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)-[~]

└─$


0
投票

将以下脚本保存为 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时间同步不起作用或者您想借助代码同步数据时,它非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.