DEV Community

mattleeee
mattleeee

Posted on Originally published at hkcode.dpdns.org

Gate.io API Pagination Trap: from+to+limit Cannot Coexist

The Symptom: A 400 That Blames the Wrong Parameter

If you've wired up Gate.io's futures candlestick endpoint, you've probably hit this: you build a request with a start time, an end time, and a page size, and the server replies HTTP 400. You strip out to, retry, and it works. You add it back, it breaks. The error message doesn't mention to at all — it usually complains about something generic like an invalid parameter or an empty result set, which sends you chasing the wrong thing for an hour.

Here's the endpoint in question (USDT-margined perpetual futures):

GET https://api.gateio.ws/api/v4/futures/usdt/candlesticks
Enter fullscreen mode Exit fullscreen mode

Query parameters that matter for history:

  • contract — e.g. BTC_USDT
  • interval — e.g. 1m, 5m, 1h
  • from — Unix timestamp in seconds
  • to — Unix timestamp in seconds
  • limit — max number of points returned

The rule the docs bury: from, to, and limit are mutually constrained. from+limit works. from+to works. to+limit works. All three together returns 400. And there's a second constraint that bites later: any single call returns at most the most recent 10,000 data points, regardless of how wide your range is.

Reproducing It

Let's pin down the failure so it's not folklore. The code below is the minimal reproduction — no retry logic, no abstractions.

import time
import requests

BASE = "https://api.gateio.ws/api/v4"
CONTRACT = "BTC_USDT"
INTERVAL = "1m"

def fetch_candles(from_ts: int, to_ts: int | None = None, limit: int | None = None):
    params = {"contract": CONTRACT, "interval": INTERVAL, "from": from_ts}
    if to_ts is not None:
        params["to"] = to_ts
    if limit is not None:
        params["limit"] = limit

    r = requests.get(f"{BASE}/futures/usdt/candlesticks", params=params, timeout=10)
    return r

now = int(time.time())
start = now - 3600  # one hour back

# Case A: from + limit -> 200
r = fetch_candles(start, limit=100)
print("from+limit        :", r.status_code)

# Case B: from + to -> 200
r = fetch_candles(start, to_ts=now)
print("from+to           :", r.status_code)

# Case C: from + to + limit -> 400
r = fetch_candles(start, to_ts=now, limit=100)
print("from+to+limit     :", r.status_code, r.text[:200])
Enter fullscreen mode Exit fullscreen mode

Typical output:

from+limit        : 200
from+to           : 200
from+to+limit     : 400 {"label":"INVALID_PARAM_VALUE","message":"..."}
Enter fullscreen mode Exit fullscreen mode

The message varies and is never "you sent too many parameters." That's the trap: the API validates combinations, not individual fields, and the error text doesn't say which combination it rejected.

One more detail worth knowing: from and to are in seconds, but the timestamps inside the returned candle objects are also in seconds. Mixing in milliseconds (easy to do if you're used to other exchanges) silently produces empty arrays or absurd ranges rather than an error.

The Correct Pattern: from + limit Paging

The fix is to pick one paging axis and stick to it. from+limit is the most robust because it's forward-only: you always ask for "the next N candles starting at timestamp T," and you advance T using the data you got back.

The rule: next page's from = last candle's timestamp + interval seconds. Not +1 second in general — +1 only works for the 1s interval. For 1m it's +60, for 1h it's +3600. If you use the interval length, you never re-request the boundary candle and you never skip one.

INTERVAL_SECONDS = {
    "10s": 10, "1m": 60, "5m": 300, "15m": 900, "30m": 1800,
    "1h": 3600, "4h": 14400, "8h": 28800, "1d": 86400,
}

def fetch_page(from_ts: int, limit: int = 1000) -> list[dict]:
    """One page of candles. Returns [] when the server has nothing more."""
    params = {
        "contract": CONTRACT,
        "interval": INTERVAL,
        "from": from_ts,
        "limit": limit,
    }
    r = requests.get(f"{BASE}/futures/usdt/candlesticks", params=params, timeout=10)
    r.raise_for_status()
    return r.json()

def fetch_range(from_ts: int, to_ts: int, interval: str, page_size: int = 1000) -> list[dict]:
    step = INTERVAL_SECONDS[interval]
    out: list[dict] = []
    cursor = from_ts

    while cursor < to_ts:
        page = fetch_page(cursor, limit=page_size)
        if not page:
            break

        # Keep only candles inside the requested window.
        page = [c for c in page if from_ts <= int(c["t"]) <= to_ts]
        if not page:
            break

        out.extend(page)
        last_t = int(page[-1]["t"])

        # Guard against a stalled cursor (server returns same page again).
        if last_t < cursor:
            break
        cursor = last_t + step

        if len(page) < page_size:
            # Short page usually means we've reached the live edge.
            break

    return out
Enter fullscreen mode Exit fullscreen mode

A few things this loop gets right that naive versions don't:

  • Cursor advances by last_t + interval, not by page_size * interval. The server may return fewer candles than requested (missing data, delisted windows, exchange downtime). Deriving the next cursor from the actual data keeps you correct.
  • Filtering by to_ts happens client-side. Since we never send to, the server can't clip the end for us, so the last page may overshoot. Trim it yourself.
  • Stall detection. If last_t < cursor, something is wrong and you should bail rather than loop forever.
  • Short-page exit. If the server returns fewer than page_size, you're at the live edge; there's no point asking again.

When the Range Exceeds the 10,000-Point Cap

The 10,000-point cap is per call, not per range, and it's applied to the most recent data in the window you asked for. This has a nasty consequence: if you request from = now - 30 days with limit = 1000 on 1m, you get the 1,000 most recent minutes of that window — not the first 1,000 minutes. Your pagination loop's first page is fine, but the semantics of "most recent within the window" mean that a naive loop which advances from will eventually get stuck asking for data older than what the server will serve in a single call.

The clean way to handle it is to split the overall range into windows of at most 10,000 intervals, and paginate inside each window. That way each from+limit call is guaranteed to fall inside the server's per-call ceiling.

MAX_POINTS_PER_CALL = 10_000

def fetch_history(from_ts: int, to_ts: int, interval: str) -> list[dict]:
    step = INTERVAL_SECONDS[interval]
    window = MAX_POINTS_PER_CALL * step

    all_candles: list[dict] = []
    win_start = from_ts

    while win_start < to_ts:
        win_end = min(win_start + window, to_ts)
        chunk = fetch_range(win_start, win_end, interval)
        all_candles.extend(chunk)
        win_start = win_end + step  # move past the window boundary

    # Deduplicate on timestamp in case windows overlap at the seam.
    seen: dict[int, dict] = {}
    for c in all_candles:
        seen[int(c["t"])] = c
    return [seen[t] for t in sorted(seen)]
Enter fullscreen mode Exit fullscreen mode

Two subtleties:

  • Window size is MAX_POINTS * step, not MAX_POINTS. The cap is in points, so the calendar span of a window depends on the interval. A 10,000-point window is ~7 days on 1m and ~277 days on 1h.
  • Deduplicate at the seam. The win_start = win_end + step line avoids an overlap in theory, but off-by-one drift is common enough that a dict keyed on t is cheap insurance. It also catches duplicates if the server ever returns a boundary candle twice.

If you're pulling months of 1m data, this is dozens of HTTP round-trips. That's expected — there is no bulk export endpoint, and hammering the server with parallel requests will get you rate-limited. Serialize, add a small sleep between windows, and cache to disk.

Debugging Unfamiliar Parameter Rules with Bisection

The Gate.io case is one instance of a general problem: undocumented parameter interactions. When you hit a 400 and the message is unhelpful, don't guess — bisect.

The idea: start with a request you know works, then add parameters one at a time, and when it breaks, remove one at a time to confirm which combination is fatal. For a small parameter set this is a few requests.

from itertools import combinations

def probe(params_pool: dict, required: dict, endpoint: str) -> dict:
    """Find the largest working subset of optional params."""
    optional = list(params_pool)
    results = {}

    # Test every subset, largest first.
    for size in range(len(optional), -1, -1):
        for combo in combinations(optional, size):
            params = {**required, **{k: params_pool[k] for k in combo}}
            r = requests.get(endpoint, params=params, timeout=10)
            results[combo] = r.status_code
            if r.status_code == 200:
                return {"ok": combo, "all": results}
    return {"ok": None, "all": results}

pool = {
    "from": int(time.time()) - 3600,
    "to":   int(time.time()),
    "limit": 100,
}
required = {"contract": "BTC_USDT", "interval": "1m"}
print(probe(pool, required, f"{BASE}/futures/usdt/candlesticks"))
Enter fullscreen mode Exit fullscreen mode

For three optional parameters this is at most 8 requests and it tells you definitively that {from, to, limit} is the failing triple and {from, limit} is the maximal working pair. That's far faster than reading docs that don't mention the rule.

When the parameter space is larger — say, ten optional query params — exhaustive subsets are 1,024 requests, which is too many. Switch to a greedy bisection: add params one at a time in the order you suspect matters; when adding one breaks the request, mark it as conflicting with the current set and try it alone against the required params. That's O(n) in practice.

def greedy_probe(pool: dict, required: dict, endpoint: str) -> dict:
    working, rejected = dict(required), []
    for k, v in pool.items():
        trial = {**working, k: v}
        r = requests.get(endpoint, params=trial, timeout=10)
        if r.status_code == 200:
            working = trial
        else:
            rejected.append(k)
    return {"working": working, "rejected": rejected}
Enter fullscreen mode Exit fullscreen mode

Run it, and you get a working parameter set plus the list of params that broke it. In the Gate.io case, rejected would contain whichever of from/to/limit was added third — which is exactly the information the error message withheld.

Practical Notes

  • Timestamps are seconds. Multiply by 1000 only for libraries that want milliseconds, and convert back before sending.
  • limit has its own ceiling. Even below 10,000, the server may cap limit at some lower value per interval. If you ask for 10,000 and get 1,000 back, that's the effective cap — treat the short page as the signal to advance, not as an error.
  • Rate limits are real. Serial paging with a short sleep between windows is the difference between a working backfill and a 429 loop.
  • Cache raw responses. When you're bisecting parameter rules, you'll re-request the same windows repeatedly. Dump each page to disk keyed on (contract, interval, from, limit) and the debugging loop gets fast and free.
  • The error message is not the diagnosis. When a 400 doesn't name the offending field, treat it as "the combination is invalid" and bisect rather than reading the message literally.

The general lesson transfers: when an API's parameters interact, the docs often describe each field in isolation and leave the constraints implicit. Build a small probe harness once, and every new endpoint becomes a five-minute investigation instead of an afternoon of guessing.

More notes like this ship every week on this site.


Daily Picks

The following pairs are selected from the multi-timeframe trend scanner (Gate.io futures) and are for technical-analysis study only — not investment advice.
Data updated: 2026-11-12 08:46:26

Short

Pair Signal Price Take Profit Stop Loss R/R
Q 短平快做空 $0.029 $0.0281 $0.0297 1:1.2

1 picks selected. Scanner runs every 15 minutes.

Top comments (0)