Public market-data endpoints are free to call, so it's easy to poll them in a tight loop and forget that each call has a cost. MEXC's spot v3 REST API limits unauthenticated calls by weight, and that weight is shared across every call your IP makes. Go over it and you lose access for a while, sometimes much longer. Here I build a small local weight budget in standard-library Python so the script spends its allowance on purpose.

What the docs say about weight

The introduction page sets the rules. Endpoints without an API key are limited per IP, and IP-weighted endpoints share one window of 300 weight over 10 seconds. Each endpoint's weight comes from that endpoint's own page: the bookTicker page gives a weight of 10 for /api/v3/ticker/bookTicker, and the order book page gives a weight of 3 for /api/v3/depth. The introduction is where the window and the HTTP codes are described.

The status codes matter as much as the numbers. HTTP 429 means you went over the limit and your IP may be banned soon. HTTP 403 comes from the web application firewall. Other 4XX codes point at the client, and 5XX codes come from MEXC's servers. A 418 or 429 response carries a Retry-After header in seconds. After a 429 the docs say to stop sending requests, because carrying on can end in an IP ban. Repeated violations lengthen the ban, which runs from a minimum of two minutes up to three days. The FAQ adds that once you exceed the frequency limit, the interface comes back after ten minutes if you stay below the limit.

The script does not need to know the ban rules to be useful. It needs to stop counting on the server's patience and count for itself.

Building the budget

A fixed ten-second bucket is simple, but it can let two bursts land on either side of a bucket boundary and roughly double the effective rate. I use a sliding window instead. Every call is recorded with its timestamp and weight, and entries older than the window drop out. Before a call goes out, the budget checks whether the weight still fits. If it doesn't, the code sleeps until the oldest entry expires.

The second part is the 429 path. When the server answers 418 or 429, the budget is blocked until the Retry-After time has passed, and the client raises an exception instead of retrying in a loop. Retrying immediately is exactly the behaviour the docs warn about.

from __future__ import annotations import argparse import json import sys import time import urllib.error import urllib.parse import urllib.request from collections import deque BASE_URL = "https://api.mexc.com" IP_WEIGHT_LIMIT = 300 # shared IP-weighted budget WINDOW_SECONDS = 10.0 # window length for the budget BOOK_TICKER_WEIGHT = 10 # from the bookTicker endpoint page DEPTH_WEIGHT = 3 # from the order book endpoint page DEFAULT_RETRY_AFTER = 60.0 # local fallback when the header is missing class RateLimitStop(RuntimeError): """Raised after HTTP 418/429: the client must stop sending requests.""" def __init__(self, status: int, retry_after: float) -> None: super().__init__(f"HTTP {status}: stop sending for {retry_after:.0f} s") self.status = status self.retry_after = retry_after class WeightBudget: """Sliding-window counter for IP weight.""" def __init__(self, limit: int = IP_WEIGHT_LIMIT, window: float = WINDOW_SECONDS) -> None: self.limit = limit self.window = window self._events: deque[tuple[float, int]] = deque() self._blocked_until = 0.0 def _prune(self, now: float) -> int: while self._events and now - self._events[0][0] >= self.window: self._events.popleft() return sum(weight for _, weight in self._events) def acquire(self, weight: int) -> None: if weight > self.limit: raise ValueError("a single request cannot exceed the whole window") while True: now = time.monotonic() if now < self._blocked_until: time.sleep(self._blocked_until - now) continue if self._prune(now) + weight <= self.limit: self._events.append((now, weight)) return wait = self._events[0][0] + self.window - now time.sleep(max(wait, 0.0)) def block(self, seconds: float) -> None: self._blocked_until = max(self._blocked_until, time.monotonic() + seconds) def remaining(self) -> int: return self.limit - self._prune(time.monotonic()) def parse_retry_after(value: str | None) -> float: if value is None: return DEFAULT_RETRY_AFTER try: return max(float(value), 0.0) except ValueError: return DEFAULT_RETRY_AFTER def get_json(path: str, params: dict[str, str], budget: WeightBudget, weight: int) -> object: budget.acquire(weight) query = urllib.parse.urlencode(params) url = f"{BASE_URL}{path}" + (f"?{query}" if query else "") request = urllib.request.Request(url, headers={"Accept": "application/json"}) try: with urllib.request.urlopen(request, timeout=10) as response: return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: if exc.code in (418, 429): retry_after = parse_retry_after(exc.headers.get("Retry-After")) budget.block(retry_after) raise RateLimitStop(exc.code, retry_after) from exc raise def book_ticker(symbol: str, budget: WeightBudget) -> dict[str, str]: data = get_json("/api/v3/ticker/bookTicker", {"symbol": symbol}, budget, BOOK_TICKER_WEIGHT) if not isinstance(data, dict): raise TypeError(f"unexpected bookTicker payload: {type(data).__name__}") return data def depth(symbol: str, limit: int, budget: WeightBudget) -> dict[str, object]: if not 1 <= limit <= 5000: raise ValueError("limit must be between 1 and 5000") data = get_json( "/api/v3/depth", {"symbol": symbol, "limit": str(limit)}, budget, DEPTH_WEIGHT, ) if not isinstance(data, dict): raise TypeError(f"unexpected depth payload: {type(data).__name__}") # Keep only the documented fields. return {"lastUpdateId": data["lastUpdateId"], "bids": data["bids"], "asks": data["asks"]} def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Poll MEXC public endpoints inside a local weight budget.") parser.add_argument("--symbol", default="BTCUSDT") parser.add_argument("--polls", type=int, default=5) args = parser.parse_args(argv) budget = WeightBudget() try: for i in range(1, args.polls + 1): ticker = book_ticker(args.symbol, budget) book = depth(args.symbol, 5, budget) print( f"[{i}] {ticker['symbol']} bid={ticker['bidPrice']} ask={ticker['askPrice']} " f"lastUpdateId={book['lastUpdateId']} remaining_weight={budget.remaining()}" ) except RateLimitStop as exc: print(f"stopped: {exc}", file=sys.stderr) return 2 return 0 if __name__ == "__main__": raise SystemExit(main()) 

Running it

Run the script with python3 budget_poll.py --symbol BTCUSDT --polls 5. Each poll costs 13 weight, a bookTicker call plus a depth call. The output looks roughly like this (illustrative values, not real market data):

[1] BTCUSDT bid=65000.12 ask=65000.13 lastUpdateId=1234567 remaining_weight=287 [2] BTCUSDT bid=65000.12 ask=65000.14 lastUpdateId=1234590 remaining_weight=274 

The remaining_weight figure is the value that matters. It tells you how much room is left before the script has to wait.

The arithmetic

With nothing else running from the same IP, the window allows 30 bookTicker calls per 10 seconds (300 divided by 10), or 100 depth calls at weight 3. A mixed loop that does one of each per cycle costs 13, so about 23 cycles fit in one window. Those numbers are just division on the documented weights, and they assume no other process shares the IP.

Caveats

The budget only sees calls made by this process. If another script or a second terminal uses the same IP, the server's window is shared with it, and my counter cannot see that traffic. Run one budget per IP, or keep the limit well below 300 to leave headroom.

The weights and windows above are the ones written in the docs when I read them. Check the endpoint pages before you rely on the numbers, and treat the local budget as a courtesy layer, not a guarantee. A 429 still has to be handled, which is why the code stops instead of retrying.

Referral code

If you sign up for MEXC, you can enter the referral code mexc-bonus2027 in the Referral Code (Optional) field. The code gives a 20% discount on fees and a bonus of up to 10,000 USD. The 10,000 USD is a maximum, not a guarantee, and the bonus details are in the MEXC panel after you register. Sign-up link: https://www.mexc.com/acquisition/custom-sign-up?shareCode=mexc-bonus2027. This is an affiliate link.

Check the current terms and the risks where you live before you sign up. This is not investment advice.