Genesis Arbitrage

Genesis Arbitrage · · 13 min read

Automation risks: data, errors, keys and AI

In short

  • Check the data before any alert: snapshot age (current time minus meta.updated_at), the stale flag on order books, the spread at best quotes and a shared contract on both exchanges of a pair.
  • A 503 means there is no data, while an empty data with a 200 means nothing matched the filter. The bot tells the two apart and reports a failure after three cycles without data.
  • Code breaks on edge cases: retrying without a pause runs into 429, a null in a comparison crashes Python, division by zero in JavaScript yields Infinity and a false alert, and local time instead of UTC shifts a funding payout by hours.
  • A Genesis API key is read-only, so a leak burns your quota. An exchange key with withdrawal rights puts money at risk, and a trading bot does not need that right.
  • An AI model mixes up numbers and may follow a command hidden in someone else's text: code inserts the numbers into messages, outside fields reach the model as data, code enforces trade limits and a human confirms each order.

Trading bot risks on a crypto API fall into four groups: the data is stale or shows a spread that does not exist; the code loops or crashes on an edge case; the key leaks; an AI model gets a number wrong or follows someone else's command. Each risk has a check in code or a working rule, and all of them fit into the monitor from lesson 4 too.

Data risks

A stale snapshot

A Genesis API snapshot is built at meta.updated_at, and your plan refreshes it every meta.freshness_sec seconds: 60 on Trial, 30 on Start, 10 on Pro and 5 on Max. The snapshot's age is the current time minus meta.updated_at, which is its data freshness. One or two plan intervals is normal; more than three means the snapshot is stuck.

Hypothetical example: on Pro the threshold is 3 × 10 = 30 s. A response arrives at 1783802470 with meta.updated_at = 1783802410: the age is 1783802470 − 1783802410 = 60 s, so the bot sends no alerts from it. The full latency from the exchange to your code is even larger, and the age is measured by your server clock, so keep it synced with NTP.

Order books and prediction platforms

Order books have their own clock: /orderbooks/book returns book_ts, age_sec and a stale flag that is true when the book is older than 30 seconds. Books lag the exchange by 5–20 seconds. In Order-book Δ, check order_delta.status: ok means computed, no_book means there is no book, exhausted means the book could not fill the size.

For prediction markets there is /predictions/platforms: skip pairs that involve a platform in mode = down, a platform with an old quotes_at, or a bookmaker with ok = false.

An empty response on 503

An empty list and missing data are different states. A 200 with meta.count = 0 means no row matched the filter. A 503 snapshot_not_ready means the data is being rebuilt: the market may still have pairs, and you retry after Retry-After seconds.

The fetch function returns (data, meta), or None when there is no data. It retries 429 and 503 after Retry-After, other 5xx errors and network failures after pauses of 5, 10 and 20 seconds, and stops on everything else.

import os
import time

import requests

BASE = "https://api.genesisarbitrage.com/v1"
HEADERS = {"X-API-Key": os.environ["GENESIS_API_KEY"]}


def fetch(path, params=None, tries=4):
    """(data, meta), or None: no data, which is not "no pairs"."""
    for attempt in range(tries):
        try:
            r = requests.get(BASE + path, headers=HEADERS,
                             params=params, timeout=15)
            code = r.status_code
        except requests.RequestException:
            code = 0  # network error or timeout: retry after a pause
        if code == 200:
            body = r.json()
            return body["data"], body["meta"]
        wait = 5 * 2 ** attempt  # 5, 10, 20 s: the pause grows
        if code in (429, 503):
            wait = int(r.headers.get("Retry-After", wait))
            if wait > 60:  # never wait more than a minute
                raise RuntimeError(f"wait {wait} s: check your quota")
        elif 400 <= code < 500:
            # 400, 401, 403, 404, 410: a retry will not fix these
            raise RuntimeError(f"{code}: {r.text[:200]}")
        if attempt < tries - 1:
            time.sleep(wait)
    return None

A long Retry-After also comes when the period's quota is used up: the reset may be days away, and fetch never waits more than a minute. Retries, ETag and filters are covered in the article on polling an API without hitting limits.

A false spread: thin books and look-alike tokens

spread_pct is computed from last trades, while you can only buy at the ask and sell at the bid. In the FUEL example from the arbitrage endpoints guide, the spread is 0.11% by last trades and −0.11% at best quotes. The ask_buy and bid_sell fields come in every Spot – Spot row on any plan, and quote_spread below uses them to compute the spread at best quotes.

A thin order book inflates the gap. Hypothetical example: the last trade printed at $1.18 an hour ago, the best bid is now $1.02 and the ask on the buy exchange is $1.00. The spread is 18% by last trades and 2% at best quotes, and $1,000 may not fill at all: on Pro and Max, order_delta.status = exhausted at volume=1000 shows exactly that.

The second source of false spreads is one ticker shared by different tokens, such as a token on BSC and an unrelated project on Solana. For a token with a contract, query /coins/search with the ticker in query: contracts[] must have an entry whose exchanges lists both exchanges of the pair (compare names case-insensitively). No such entry means no direct transfer: these are different tokens, or the route goes through a bridge with its own risks.

def is_fresh(meta, k=3):
    """The snapshot is no older than k plan intervals."""
    age = time.time() - meta["updated_at"]
    return age <= k * meta["freshness_sec"]


def quote_spread(row):
    """Spread at best quotes: buy at the ask, sell at the bid."""
    ask, bid = row.get("ask_buy"), row.get("bid_sell")
    if ask is None or bid is None or ask <= 0:
        return None  # no price or a zero price: skip the row
    return (bid - ask) / ask * 100


pause, fails = 60, 0
while True:
    got = fetch("/arbitrage/spot-spot", {"min_spread": 1})
    if got is None or not is_fresh(got[1]):
        fails += 1  # no data or stale data: no alerts
        if fails == 3:
            print("3 cycles without fresh data")  # alert yourself
    else:
        rows, meta = got
        fails, pause = 0, meta["freshness_sec"]
        for row in rows:
            s = quote_spread(row)
            if s is not None and s >= 0.5:
                print(row["coin"], row["exchange_buy"], "→",
                      row["exchange_sell"], f"{s:.2f}%")
    time.sleep(pause)  # the pause runs on every path

An exception from fetch stops the loop: a production bot messages its owner before it exits.

Code risks

Retries without a pause and endless loops

A first bot often retries right after an error: if r.status_code != 200: continue. On a 503 such a loop fires requests back to back with no pause: errors do not use quota but do count against the requests-per-second limit, so a 429 with Retry-After: 1 follows. Once the subscription expires, the same loop gets 401 forever. And a continue before time.sleep() skips the pause on every empty response, which is why the pause is the last line of the loop above.

The opposite mistake is waiting forever. time.sleep(int(r.headers["Retry-After"])) on an exhausted quota sleeps for days: for example, Retry-After: 259200 is 259,200 / 86,400 = 3 days. A request without timeout can also hang indefinitely, as the requests documentation warns.

null and division by zero

Genesis API uses null for empty values, and Python turns it into None. Comparing row["volume_24h_sell"] > 10000 with None raises TypeError, and one row takes down the whole loop. JavaScript raises nothing: null > 0.5 is false, null < 1 is true, and the filter fails silently.

null means "no data", and replacing it with zero via or 0 is dangerous: in DEX slippage, tax_sell_pct = null means there is no tax source, and or 0 turns that into 0%. Per the documentation, null appears in bid_* and ask_*, volume_24h_*, max_position_usd, next_payout, in profit_usd for pairs with a bookmaker leg and in apr_pct when less than a day is left.

Division by zero is the same trap. A zero ask raises ZeroDivisionError in Python, while in JavaScript 1 / 0 is Infinity and Infinity > 0.5 is true: the bot sends a pair with an infinite spread. Check the denominator before dividing, as quote_spread checks ask <= 0.

Time zones

Genesis API times are unix seconds and UTC strings: next_payout in funding rates comes as HH:MM UTC. datetime.fromtimestamp(ts) without a time zone returns the server's local time, and datetime.utcnow() has been deprecated since Python 3.12; the Python documentation points to datetime.now(timezone.utc) instead.

Hypothetical example: the server runs at UTC+3 and its clock shows 09:30, which is 06:30 UTC. The 08:00 payout is 1 h 30 min away, but code that compares 08:00 with local time decides the payout has passed and counts 22 h 30 min to the next one, 21 hours off.

from datetime import datetime, timedelta, timezone


def until_payout(hhmm, now=None):
    """Time until next_payout, an HH:MM string in UTC."""
    if hhmm is None:
        return None  # null: no payout time
    now = now or datetime.now(timezone.utc)
    h, m = map(int, hhmm.split(":"))
    t = now.replace(hour=h, minute=m, second=0, microsecond=0)
    if t <= now:
        t += timedelta(days=1)  # "00:00" at 23:50 means tomorrow
    return t - now


now = datetime(2026, 11, 15, 6, 30, tzinfo=timezone.utc)
print(until_payout("08:00", now))  # 1:30:00

Key risks

A Genesis API key is read-only: it cannot place orders or withdraw funds. A leak hits your quota and requests-per-second limit, and your bot gets 429 before the period ends. Warning signs: "Calls used" in your profile grows faster than your code accounts for, or "used …" shows a recent time while the bot is stopped.

The key is shown once and Genesis Arbitrage stores only its hash, so a leaked key gets reissued: "Reissue" disables the old key at once and issues a new one. Keys leak from places they were put by mistake: a public repository, a request URL, page code, a screenshot, a log with request headers. Log the status code and X-Request-Id instead; the storage rules are in the API key glossary entry.

An exchange key is a different class of risk: with withdrawal rights it can move coins off the account. A trading bot does not need that right, so create the key without withdrawals, bound to your server's IP and separate for each service. Details are in How to secure your crypto exchange account.

AI agents: numbers, injected commands, confirmation

An agent calls Genesis API through your server: the model picks the endpoint and arguments, and the server makes the request with the key. Setup is in the Genesis API for AI agents guide, and the overall design is in the article on crypto market data for AI agents.

Wrong numbers

A model may read 0.92 as 92% instead of 0.92%, confuse the per-interval funding_pct with the 8-hour funding_8h_pct, or quote a price that is not in the response. Code inserts the numbers into alerts straight from the API response, and the model is left with selection and explanation. If the model writes numbers itself, check each one against the tool result.

Commands in outside text

Some fields are written by other people: title and outcome of prediction markets, trader name, the token_name of on-chain events, and the message_ru and message_en of signals. Anyone can name a token "Ignore previous instructions and…", and a model that reads the name as part of its prompt may follow it. This is prompt injection, the first entry in the OWASP Top 10 for LLM Applications 2025: LLM01:2025.

Pass such fields only inside the tool result, cap their length and state in the system prompt that they are data. The key stays in the server-side handler.

Human confirmation

Genesis API only reads data: an agent built on it finds a pair and writes about it, but does not trade. An exchange trading API wired to the agent is outside Genesis API and at your own risk. Among its mitigations, OWASP lists human-in-the-loop control for privileged operations: an order goes out only after a "yes" from a trader who sees the pair, the prices and the data time.

Pre-launch checklist

  1. The key is in GENESIS_API_KEY on the server and nowhere in code, request URLs, the browser, logs or prompts.
  2. Every request has a timeout.
  3. Only 429, 503, other 5xx errors and network failures are retried, with a pause and at most three times.
  4. 400, 401, 403, 404, 410 and a Retry-After over a minute stop the bot with a message.
  5. The pause between polls is at least meta.freshness_sec and runs on every path of the loop.
  6. Snapshot age is checked before any alert, and for order books so are stale and order_delta.status.
  7. "No data" and "no pairs" are separate states, and three cycles without data trigger a failure message.
  8. null is checked against None, denominators against zero, and time is handled in UTC.
  9. A pair passes on its spread at best quotes, a shared contract, withdraw_enabled_buy and deposit_enabled_sell.
  10. Code inserts the numbers into messages, outside text reaches the model as data, and a human confirms each order.

Course wrap-up: where to go next

The course has five lessons: concepts, a first request, data for decisions, a Python monitor and its risks; the basics are in lesson 1. Details on each step:

Try it yourself

  1. Find your plan's freshness

    Call /account/usage and note freshness_sec and calls_used: this request does not count as a call.

  2. Measure the snapshot age

    Get /arbitrage/spot-spot through fetch, print time.time() - meta["updated_at"] and compare it with the 3 × freshness_sec threshold.

  3. Compare two spreads

    Print spread_pct and quote_spread(row) for five rows and count how many pairs stay positive at best quotes.

  4. Test the error path

    Run the bot with the placeholder GENESIS_API_KEY=gns_live_XXXXXXXXXXXXXXXX: the 401 invalid_key response should stop it with a clear message.

  5. Go through the checklist

    Add whatever your code is missing before you run the bot around the clock.