Timestamp Ahead of Server Time: Fix Exchange API Errors
A timestamp ahead of server time error means your signed request carried a clock value later than the exchange's clock allows. Sync the system clock with NTP first, then measure offset and latency before touching recvWindow.
- Exchanges reject timestamps that are too far ahead (about 1000 ms on Binance) and too far behind (more than recvWindow); these are separate failures with different fixes.
- Measure first: offset = server_time - (local_before + local_after)/2, using the public server-time endpoint.
- Fix the OS clock with NTP before using recvWindow or ccxt's adjustForTimeDifference, because raising recvWindow only widens the replay window.
- Containers cannot set their own clock; WSL2 and VMs drift after sleep, so fix the host or resync the VM.
- Create the timestamp at send time, in milliseconds, and refresh any offset periodically in long-running bots.
Why does the exchange say my timestamp is ahead of server time?
Signed requests include a timestamp that is part of the signature. The exchange compares it to its own clock and rejects anything outside a window. This stops an attacker from replaying a captured request later.
Binance states the rule as: accept if timestamp < serverTime + 1000 and serverTime - timestamp <= recvWindow. Two different failures follow. If your clock is more than about 1 second fast, the timestamp is 'ahead'. If your clock is slow, or the request is delayed in transit, the age exceeds recvWindow and it is 'behind'.
The asymmetry matters. The future side has a fixed, tight tolerance (1000 ms) that recvWindow does not widen. So raising recvWindow cannot fix a clock that runs fast. Only correcting the clock or subtracting an offset can.
Bybit uses the same shape: timestamp - recv_window <= server_time < timestamp + 1000. OKX and KuCoin use a simple absolute-difference check instead, described in the table below.
Which error strings and tolerances does each exchange use?
Use the exact message to tell 'ahead' from 'too old'. Tolerances below are the commonly documented defaults; they can change, so treat the measured offset as the source of truth.
| Exchange | Code | Message | Tolerance |
|---|---|---|---|
| Binance | -1021 | Timestamp for this request is outside of the recvWindow. / Timestamp for this request was 1000ms ahead of the server's time. | recvWindow default 5000 ms, max 60000 ms; future side 1000 ms |
| Bybit | retCode 10002 | invalid request, please check your server timestamp or recv_window param | recv_window default 5000 ms; future side 1000 ms |
| OKX | 50102 | Timestamp request expired | Timestamp must be within 30 seconds of server time |
| KuCoin | 400002 | Invalid KC-API-TIMESTAMP | Roughly 5 seconds either way |
How do I measure how far my clock is off?
Call the public server-time endpoint, which needs no signature. Record local time before and after the call and assume the server stamped the response halfway through the round trip. Take the median of several samples, because a single slow response skews the result.
Interpretation: a negative offset means your clock is ahead of the exchange (the dangerous case for 'ahead' errors). A positive offset means you are behind. A large RTT means the network, not the clock, may be your problem.
This script measures offset and RTT against several exchanges:
import time, statistics, requests
ENDPOINTS = {
"binance": ("https://api.binance.com/api/v3/time", lambda j: j["serverTime"]),
"bybit": ("https://api.bybit.com/v5/market/time", lambda j: j["time"]),
"okx": ("https://www.okx.com/api/v5/public/time", lambda j: int(j["data"][0]["ts"])),
"kucoin": ("https://api.kucoin.com/api/v1/timestamp", lambda j: j["data"]),
}
def sample(url, extract, n=7):
s = requests.Session()
offsets, rtts = [], []
for _ in range(n):
t0 = time.time() * 1000
server = extract(s.get(url, timeout=5).json())
t1 = time.time() * 1000
rtts.append(t1 - t0)
offsets.append(server - (t0 + t1) / 2) # >0: local clock behind
time.sleep(0.2)
return statistics.median(offsets), statistics.median(rtts)
for name, (url, ex) in ENDPOINTS.items():
try:
off, rtt = sample(url, ex)
flag = "LOCAL CLOCK AHEAD" if off < -500 else ("LOCAL CLOCK BEHIND" if off > 500 else "ok")
print(f"{name:8s} offset={off:8.0f} ms rtt={rtt:6.0f} ms {flag}")
except Exception as e:
print(name, "error:", e) How do I fix the clock itself (NTP, chrony, Windows, macOS)?
This is the root-cause fix, and it should come first. Offsets of more than a second almost always mean NTP is off, blocked (UDP 123), or the machine just resumed from suspend.
- Linux with systemd: run timedatectl and check 'System clock synchronized: yes'. If not, run sudo timedatectl set-ntp true. This uses systemd-timesyncd, which is fine for second-level accuracy.
- Linux with chrony: run chronyc tracking. The 'System time' line shows the current offset from NTP time. Run sudo chronyc makestep to step the clock immediately instead of slewing slowly. Check sources with chronyc sources -v.
- Windows (admin prompt): w32tm /config /manualpeerlist:"time.windows.com pool.ntp.org" /syncfromflags:manual /update, then w32tm /resync. Verify with w32tm /query /status. The default sync interval is long, so drift of seconds is common on laptops.
- macOS: System Settings > General > Date & Time > set time automatically. From a terminal, sudo sntp -sS time.apple.com steps the clock.
- Re-run the measurement script. Offsets under roughly 100 ms mean the clock is no longer the cause.
Why does my clock drift in WSL2, Docker or a VM?
A Docker container has no clock of its own. It shares the host kernel's clock, so you cannot fix it with ntpd or date inside the container (and it normally lacks the privilege to). Fix the host, or the VM that runs Docker.
WSL2 runs in a lightweight VM. After Windows sleeps or hibernates, its clock can stay behind or jump wrong until it resyncs. The quick fix is to run wsl --shutdown from Windows and reopen the distro, which restarts the VM and picks up the host time.
Alternatively, resync from inside the distro with a working NTP client. On systemd distros, run sudo systemctl restart systemd-timesyncd, then confirm with timedatectl.
Do not rely on hwclock here. WSL2 generally has no accessible hardware clock, so sudo hwclock -s or --hctosys usually fails with 'Cannot access the Hardware Clock via any known method'. Note also that a drifting WSL2 clock is usually slow, giving 'outside of the recvWindow' rather than 'ahead'.
In VMs, enable the hypervisor's time sync (VMware Tools, Hyper-V integration services, or chrony with the host clock source) and avoid running both host sync and NTP with conflicting settings. On Docker Desktop, restarting the VM resets the clock.
Cloud instances usually have a good time source, so large drift there suggests chrony is stopped or UDP 123 is blocked.
How do I apply a server-time offset in code or ccxt?
Use an offset only when you cannot control the OS clock, or as a safety net. Compute it as server_time - (local_before + local_after)/2, add it to the local time when signing, and refresh it periodically (every few minutes) because the clock keeps drifting.
Generate the timestamp at send time, inside the function that signs and sends. If you sign at queue time, then wait on a rate limiter, retry, or block the asyncio loop, the request carries a stale value and fails as 'too old'. A retry must be re-signed with a new timestamp.
Also check units: Binance, Bybit, OKX (ISO or ms depending on endpoint) and KuCoin expect milliseconds. Sending time.time() in seconds looks like a timestamp decades in the past.
import time, requests
class Clock:
def __init__(self):
self.offset = 0
self.last = 0
def refresh(self):
t0 = time.time() * 1000
srv = requests.get("https://api.binance.com/api/v3/time", timeout=5).json()["serverTime"]
t1 = time.time() * 1000
self.offset = srv - (t0 + t1) / 2
self.last = time.time()
def now_ms(self):
if time.time() - self.last > 300: # refresh every 5 min
self.refresh()
return int(time.time() * 1000 + self.offset)
# ccxt
import ccxt
ex = ccxt.binance({
"apiKey": "...", "secret": "...",
"options": {"adjustForTimeDifference": True, "recvWindow": 10000},
})
ex.load_markets() # triggers load_time_difference()
# long-running bot: call again on a schedule
ex.load_time_difference()
print(ex.options["timeDifference"]) # local minus server, in ms
# python-binance
from binance.client import Client
c = Client("key", "secret")
c.timestamp_offset = c.get_server_time()["serverTime"] - int(time.time() * 1000) Why is adjustForTimeDifference not working in ccxt?
The option only runs when load_markets() runs, and only once per exchange instance (markets are cached). If you skip load_markets, or construct the exchange and call a private endpoint directly, no offset is loaded. Call load_time_difference() yourself, and call it again on a timer for bots that run for days.
ccxt stores the value in exchange.options['timeDifference'] as local minus server. It then subtracts this from the local time when creating the nonce. It corrects a stable offset but not jitter or a clock that is still drifting between refreshes.
If errors continue after enabling it, check these: markets loaded from a cache or a shared instance, a different exchange object doing the signing, multiple processes with separate offsets, and the true cause being latency instead of offset.
The recvWindow is sent as a query parameter and is part of the signed payload. Changing it after signing invalidates the signature. In ccxt set options['recvWindow'] or pass it in params. In binance-connector pass recvWindow=... to the call. In both cases the library signs it with the rest of the request.
When should I fix the clock, widen recvWindow, or use an offset?
Raising recvWindow (Binance max 60000 ms) hides latency and gives anyone who captures a signed request a longer window to replay it. It cannot fix the 1000 ms future limit. Treat it as a stopgap of 10000 ms or less, not a cure.
Monitor so the problem does not return: log offset and RTT every minute, alert above 500 ms, and check chronyc tracking 'System time' on servers.
| Symptom | Likely cause | Fix |
|---|---|---|
| '1000ms ahead of the server's time', offset negative | Local clock fast, NTP off | Sync clock (timedatectl set-ntp true, chronyc makestep, w32tm /resync) |
| 'outside of the recvWindow', offset positive and stable | Local clock slow | Sync clock; use ccxt offset as a backup |
| Offset small, RTT high or spiky | Slow network, VPN, distant region | Move closer to the exchange; raise recvWindow modestly |
| Errors only after laptop sleep or WSL idle | VM clock drift (WSL2 usually has no usable hardware clock, so hwclock fails) | Run wsl --shutdown from Windows and reopen the distro, or restart systemd-timesyncd inside it; fix host sync |
| Errors under load, offset fine | Timestamp created at queue time, blocked event loop, retries | Sign at send time; re-sign retries; remove blocking calls |
| Timestamp wildly in the past | Seconds sent instead of milliseconds | Multiply by 1000 and cast to int |
| Works after restart, fails after days | ccxt offset loaded once | Call load_time_difference() periodically |
Common questions
What is the maximum recvWindow on Binance?
60000 ms, with a default of 5000 ms. Even at the maximum, the request must still be less than 1000 ms ahead of the server, so a fast clock still fails.
Can I set the system time inside a Docker container?
No, in practice. Containers share the host kernel clock and normally lack the SYS_TIME capability. Fix NTP on the host or Docker's VM, since changing it inside the container would affect everything on the host.
Does a VPN or proxy cause timestamp errors?
It can, indirectly. Extra latency raises request age, which causes 'outside of the recvWindow' errors even with a perfect clock. Compare the measured RTT with the offset to see which one is responsible.
How accurate does the clock need to be for a trading bot?
Within the exchange tolerance, so well under 1 second for Binance and Bybit. Keeping the offset below a few hundred milliseconds leaves margin for network delay, and chrony normally achieves far better than that.
Is the offset method the same for WebSocket trading APIs?
Yes. Signed WebSocket requests carry a timestamp checked the same way as REST. Use the same corrected time source and sign each message at send time, not when the connection was opened.