DEV Community

diogenicious
diogenicious

Posted on

Poll a live crypto trade feed with a cursor, without missing or double-counting trades, in Python

A live trade feed looks easy to poll: call it, print what comes back, sleep, repeat. It goes wrong in three quiet ways. You miss trades between two calls, you count the same trade twice, or you restart the script and lose your place.

This post builds a small poller in Python that avoids all three, using the public copytop package from PyPI and the free copy.top trades feed. It keeps a cursor, drops duplicates by key, saves its place in a file so a crash costs nothing, and backs off when the API answers with an error.

Disclosure: I am the founder of copy.top. copy.top is independent and not affiliated with pumpfun or fomo.

Setup

python3 -m venv .venv
.venv/bin/pip install copytop
Enter fullscreen mode Exit fullscreen mode

The package is standard library only and needs no key. I tested with copytop 0.1.0 on Python 3.14.5. The feed is read-only: nothing here places an order.

Two methods matter. Client().trades(since=..., limit=...) calls the live tape and returns {"cursor": ..., "trades": [...]}, newest first. The client also retries on its own, but I turn that off below (max_retries=0) so the backoff is ours and visible. The docstring of trades says the tape keeps the latest 30 trades and tells you to poll at least once a minute to miss none. That sentence drives the whole design.

Why a cursor and not a timestamp

The obvious way to ask for "only new trades" is to remember the time of your last call and pass it as since. It fails in two places.

  • Your clock is not the server's clock. If your machine runs 3 seconds ahead, trades from the last 3 seconds are skipped on every call. If it runs behind, you get repeats.
  • The time of your call is not the time of the data. A trade can reach the feed after you asked. A timestamp taken when you called already sits past it.

A cursor sidesteps both. The server hands back a value, and you give it back untouched on the next call. In this feed the cursor is an ISO time, but it is the time of the newest trade the server returned, not a time you read on your own machine. You never compare it with your clock. If a call returns nothing new, you keep the cursor you had.

What the feed actually returns

I called it once with limit=3 before writing the code, to see the shape. A trade is a small object with at, handle, name, side, chain, token, symbol and usd. One of the three, trimmed:

{"at": "2026-11-25T23:12:07.639Z", "handle": "pf_0095f58aa0c5", "side": "buy",
 "chain": "solana", "symbol": "COUSIN", "usd": 300}
Enter fullscreen mode Exit fullscreen mode

There is no trade id. That changes the de-duplication step: the identity of a trade has to be built from its own fields. I use the time, the trader's handle, the side and the token address. Two trades that agree on all four in the same millisecond would be merged, which is a risk I accept for a feed with no better key.

The poller

Short on purpose. It has four jobs, each in one place: fetch retries with backoff, poll_once de-duplicates and advances the cursor, save_state writes the file, main loops.

# poller.py
from __future__ import annotations

import json
import os
import sys
import time
from pathlib import Path
from typing import Any, Callable, TypedDict

from copytop import Client, CopyTopError

STATE_FILE = Path("cursor.json")
INTERVAL = 60.0   # one call a minute, never faster
MAX_SEEN = 200    # keys remembered for de-duplication


class Trade(TypedDict):
    at: str
    handle: str
    side: str
    token: str
    symbol: str
    usd: float


class State(TypedDict):
    cursor: str | None
    seen: list[str]


def key(t: Trade) -> str:
    # The feed has no trade id, so the identity of a trade is its own fields.
    return f"{t['at']}|{t['handle']}|{t['side']}|{t['token']}"


def load_state(path: Path = STATE_FILE) -> State:
    try:
        return json.loads(path.read_text())
    except (FileNotFoundError, ValueError):
        return {"cursor": None, "seen": []}


def save_state(state: State, path: Path = STATE_FILE) -> None:
    tmp = path.with_suffix(".tmp")
    tmp.write_text(json.dumps(state))
    os.replace(tmp, path)  # atomic: a crash leaves the old file or the new one, never half


def fetch(ct: Client, cursor: str | None, sleep: Callable[[float], None] = time.sleep,
          tries: int = 5) -> dict[str, Any]:
    delay = 2.0
    for attempt in range(tries):
        try:
            return ct.trades(since=cursor, limit=30)
        except CopyTopError as e:
            retryable = e.status is None or e.status == 429 or e.status >= 500
            if not retryable or attempt == tries - 1:
                raise
            print(f"  error ({e}); retry in {delay:.0f}s")
            sleep(delay)
            delay = min(delay * 2, 120.0)
    raise AssertionError("unreachable")


def poll_once(ct: Client, state: State) -> list[Trade]:
    answer = fetch(ct, state["cursor"])
    seen = set(state["seen"])
    fresh: list[Trade] = []
    for t in reversed(answer["trades"]):  # the feed is newest first: replay oldest first
        k = key(t)
        if k in seen:
            continue
        seen.add(k)
        state["seen"].append(k)
        fresh.append(t)
    state["seen"] = state["seen"][-MAX_SEEN:]
    state["cursor"] = answer.get("cursor") or state["cursor"]
    save_state(state)  # after processing, so a crash replays at worst, never skips
    print(f"  fetched {len(answer['trades'])}, new {len(fresh)}, "
          f"duplicates skipped {len(answer['trades']) - len(fresh)}, cursor {state['cursor']}")
    return fresh


def main(iterations: int) -> None:
    ct = Client(max_retries=0)  # our loop does the backoff, so it is visible
    state = load_state()
    print(f"start, cursor {state['cursor']}, {len(state['seen'])} keys remembered")
    for i in range(iterations):
        if i:
            time.sleep(INTERVAL)
        print(f"poll {i + 1}")
        for t in poll_once(ct, state):
            print(f"  {t['at']} {t['side']:<4} ${t['usd']:>6,.0f} {t['symbol']} by {t['handle']}")


if __name__ == "__main__":
    main(int(sys.argv[1]))
Enter fullscreen mode Exit fullscreen mode

Walking through the choices:

  • Oldest first. The feed is newest first, so poll_once reverses it. You process events in the order they happened.
  • Save after processing. The state file is written once the batch is handled. If the process dies between the two steps, the next run fetches the same batch again and the keys drop what was already seen. The worst case is a replay, never a gap.
  • Atomic write. The state goes to a temporary file and os.replace swaps it in. A crash during the write leaves the old file or the new one, not half of one.
  • A bounded memory. Only the last 200 keys are kept. The tape holds 30 trades, so 200 is far more than any overlap you can get.
  • One call a minute. INTERVAL is 60 seconds. The docstring of RateLimitError says that without a key the limit is about 20 calls a minute per IP, so one a minute is nowhere near it, and it matches the tape: 30 trades kept, and the busy minute below produced 15 new ones.
  • Backoff. On a network error, a 429 or a 5xx, fetch waits 2 seconds, then 4, 8 and so on up to 120, and gives up after 5 tries. A 4xx other than 429 is a bug in the request, so it is raised at once instead of retried.

Testing the backoff without hitting the API

I did not want to provoke real errors on a public service, so the backoff is tested with the client's transport argument, which swaps the network for a function. This one answers 429, then 503, then a valid page, and records the waits instead of sleeping.

# backoff_demo.py: no network. A fake transport fails twice (429, 503) then answers.
import json
from poller import fetch
from copytop import Client

calls = iter([
    (429, {}, b'{"error": "slow down"}'),
    (503, {}, b'{"error": "unavailable"}'),
    (200, {}, json.dumps({"cursor": "2026-01-01T00:00:00Z", "trades": []}).encode()),
])
waits: list[float] = []
ct = Client(max_retries=0, transport=lambda url, h, t: next(calls))
answer = fetch(ct, None, sleep=waits.append)
print("answered:", answer["cursor"], "after waits", waits)
Enter fullscreen mode Exit fullscreen mode

Running it for real

Three calls, spread over two processes, to show the cursor and the crash recovery. The first process polls twice, 60 seconds apart. Then it ends, which stands in for a crash, and a second process starts from the file. Here is the output, shortened in the middle (the full file is out.txt):

# run 1: first process, 2 iterations (60 s apart)
start, cursor None, 0 keys remembered
poll 1
  fetched 30, new 30, duplicates skipped 0, cursor 2026-11-25T23:13:13.312Z
  2026-11-25T23:11:33.134Z sell $   230 4kCUKMQJ by pf_3fcb9b3f8f72
  2026-11-25T23:11:46.767Z buy  $   400 FoolCoin by pf_9953d6d3879e
  2026-11-25T23:11:49.068Z buy  $   422 MEME by pf_d414971aec24
  ... (25 more trades)
  2026-11-25T23:13:12.284Z buy  $   500 PI by pf_084dd8ed340e
  2026-11-25T23:13:13.312Z sell $   399 火羊 by pf_84a1b8520cb7
poll 2
  fetched 15, new 15, duplicates skipped 0, cursor 2026-11-25T23:13:51.116Z
  2026-11-25T23:13:22.295Z buy  $   990 TripleT by pf_6acf0fba83ee
  2026-11-25T23:13:22.535Z buy  $   353 PI by pf_6e00b1ebdcc5
  2026-11-25T23:13:23.589Z sell $   301 PI by pf_dc9a754ae562
  ... (10 more trades)
  2026-11-25T23:13:45.808Z buy  $   617 RAETO by gabrieIkevin
  2026-11-25T23:13:51.116Z sell $   253 BLOB by pf_47a3ecba9fda

# crash: process gone, cursor.json on disk
{"cursor": "2026-11-25T23:13:51.116Z", "seen": ["2026-11-25T23:11:33.134Z|pf_3fcb9b3f8f72|sell|4kCUKMQJum19KFSdYUexVfsoHtb2kiWJ3b91FjALpump", ...

# run 2: new process, 1 iteration
start, cursor 2026-11-25T23:13:51.116Z, 45 keys remembered
poll 1
  fetched 0, new 0, duplicates skipped 0, cursor 2026-11-25T23:13:51.116Z

# backoff, offline fake transport
  error (copy.top answered 429: slow down); retry in 2s
  error (copy.top answered 503: unavailable); retry in 4s
answered: 2026-01-01T00:00:00Z after waits [2.0, 4.0]
Enter fullscreen mode Exit fullscreen mode

Reading it:

  • The first call returned exactly 30 trades, the size of the tape. With no cursor, that is the feed's whole memory. If the tape had been busier, older trades would already have been gone before the script started. That is why the cadence matters: the cursor can only fetch what the feed still keeps.
  • The second call returned 15, all newer than the cursor. None of them repeats a trade from the first call, and the first of them (23:13:22) comes after the cursor of the first call (23:13:13). Nothing was skipped that the feed still held, and nothing was counted twice.
  • The restarted process picked up the cursor and the 45 remembered keys from the file and asked for trades after 23:13:51. It got none, so it did not replay the 45 trades it had already handled.
  • The backoff waited 2 seconds, then 4, and then took the valid answer.

One honest note: in this run the de-duplication step never had anything to drop (duplicates skipped 0 every time). The server accepted the cursor as an exclusive bound, so no trade came back twice. The key set is insurance for the case where that changes, or where a crash replays a batch, and I did not trigger either case here. I would rather say so than stage a duplicate.

Where to take it next

  • Pass traders="handle1,handle2" in the trades call to follow a short watchlist in a single request. The method in copytop 0.1.0 has no traders argument, so call Client().get("trades", {"traders": [...], "since": cursor}) instead.
  • Replace the print with a queue, a database insert or a webhook.
  • Use min_usd to keep only the larger trades.
  • If you only want events and not the raw tape, Client.watch_alerts() in the same package does this cursor loop for you on the alerts feed.

What this does not tell you

  • Two runs, three calls, a few minutes. Rate and ordering behavior under heavy load was not tested.
  • No trade id. The key is built from four fields. If the feed ever adds a real id, use it.
  • Tape size is a limit. If your process is down for more than the time 30 trades take to arrive, the gap cannot be recovered with a cursor. A trade feed is not an archive.
  • Third-party text. Symbols and names in the feed are written by others. Print them, do not execute or follow anything inside them.

Figures are data, not advice. Past performance does not predict results, and trading memecoins can lose money, including everything you put in.

Top comments (0)