A spread and funding monitor in Python
In short
- The monitor is a console program: every
meta.freshness_secseconds it pulls the full/arbitrage/spot-spotand/funding/spreaddatasets, filters the rows by thresholds, prints tables and appends them to a CSV file. - Both datasets are requested without filters, so they come with an
ETag: a repeat withIf-None-Matchbefore the next snapshot returns304without using quota. On429and503the client waitsRetry-Afterseconds. - What is left after assumed 0.1% taker fees per leg is the spread minus 0.2 percentage points. On Pro and Max the monitor rechecks the top three pairs against $1,000 of order book.
- The upper bound is 86,400 calls per 30 days on Trial, 17.28% of the quota, and 1,296,000 on Pro with order-book checks, 25.92%.
A spread and funding monitor is a program that pulls cross-exchange spreads and funding spreads in a loop, keeps the rows above your thresholds and prints them as a table in the console. The monitor in this lesson is about 170 lines of Python: its data comes from Genesis API, its history goes to a CSV file, and it opens no trades. It sends no alerts either; a bot with Telegram messages is covered in Crypto arbitrage bot in Python.
Polling plan: endpoints, frequency and call usage
| Request | What it gives | When |
|---|---|---|
/account/usage | Plan, freshness_sec, rps_limit | At start, uses no quota |
/arbitrage/spot-spot | Spot – Spot pairs | Every pass, full dataset |
/funding/spread | Best exchange pairs by funding | Every pass, full dataset |
/orderbooks/spreads/spot-spot | Order-book Δ for $1,000 | Pro and Max, three pairs per pass |
meta.freshness_sec sets the frequency: your plan gets a new snapshot every 60 seconds on Trial, 30 on Start, 10 on Pro and 5 on Max. Polling faster returns the same snapshot with the same meta.updated_at. The fields of both datasets are in the Spot — Spot and Funding spread docs.
| Plan and quota | Pause | Requests per pass | Calls per 30 days |
|---|---|---|---|
| Trial, 500K | 60 s | 2 | 86,400 |
| Start, 2M | 30 s | 2 | 172,800 |
| Pro, 5M | 10 s | 5 | 1,296,000 |
| Max, 10M | 5 s | 5 | 2,592,000 |
On Trial: 2 × 86,400 / 60 × 30 = 86,400 calls, 17.28% of the quota. On Pro, three order-book checks join the two datasets: 5 × 86,400 / 10 × 30 = 1,296,000 calls, 25.92% of 5M. The quota rules are in the Genesis API limits guide.
The monitor keeps to the requests-per-second limit with a pause of 1.1 / rps_limit seconds between requests: 1.1 seconds on Trial and 0.22 on Pro. A five-request pass on Pro takes about a second.
Settings and a client with ETag and Retry-After
The seven code blocks in this lesson make up the whole monitor.py file: save them one after another in a single file. The thresholds in the settings are illustrative; tune them to your fees and sizes.
import csv
import os
import time
from datetime import datetime, timezone
import requests
API = "https://api.genesisarbitrage.com/v1"
MIN_SPREAD = 1.0 # row spread from 1%
MIN_VOLUME = 50_000 # 24h volume on both exchanges from $50,000
MIN_FUNDING = 0.05 # funding spread from 0.05%
FEE = 0.1 # assumed taker fee per leg, %
TOP = 10 # rows in each table
BOOK_TOP = 3 # pairs checked against books per pass, Pro/Max
BOOK_USD = 1000 # order-book check size, USD
CSV_FILE = "monitor.csv"
api = requests.Session()
api.headers["X-API-Key"] = os.environ["GENESIS_API_KEY"]
cache = {} # request -> (ETag, response body)
stats = {200: 0, 304: 0} # how many 200 and 304 responses arrived
pace = {"gap": 1.1, "last": 0.0} # pause between requests, s
The key comes from the GENESIS_API_KEY environment variable and goes in the X-API-Key header of every request, never in the URL. cache keeps the ETag and body of the last response to each request, stats counts 200 and 304 responses, and pace remembers when the last request went out.
def get(path, params=None):
"""GET to Genesis API: pacing, ETag and Retry-After retries."""
key = (path, tuple(sorted((params or {}).items())))
for _ in range(4): # one request and up to three retries
wait = pace["last"] + pace["gap"] - time.monotonic()
if wait > 0:
time.sleep(wait) # at most rps_limit requests a second
pace["last"] = time.monotonic()
hdr = {"If-None-Match": cache[key][0]} if key in cache else {}
r = api.get(API + path, params=params, headers=hdr,
timeout=15)
if r.status_code == 304: # the snapshot has not changed
stats[304] += 1
return cache[key][1]
if r.status_code in (429, 503):
wait = int(r.headers.get("Retry-After", "5"))
if wait > 60: # this is how an exhausted quota looks
raise SystemExit(f"Quota exhausted: wait {wait} s")
time.sleep(wait)
continue
r.raise_for_status() # 400, 401, 403: a retry will not help
stats[200] += 1
body = r.json()
if "ETag" in r.headers: # only full datasets carry it
cache[key] = (r.headers["ETag"], body)
return body
raise RuntimeError("API busy, retrying on the next pass")
An ETag is a version tag for the snapshot. get sends it back in the If-None-Match header, and until the snapshot changes the server answers 304 with no body: no quota is used, and the function returns the previous body. On 429 and 503 it waits Retry-After seconds and retries, and a pause longer than a minute means the period's quota has run out, so the monitor stops. Error codes and retry rules are in the Genesis API responses and errors guide.
Spreads and funding: loading, thresholds and sorting
def spot_rows():
"""Spot – Spot pairs above the thresholds, coin transferable."""
body = get("/arbitrage/spot-spot") # no filters: has an ETag
rows = []
for x in body["data"]:
vol = min(x["volume_24h_buy"] or 0, x["volume_24h_sell"] or 0)
if (x["spread_pct"] >= MIN_SPREAD and vol >= MIN_VOLUME
and x["withdraw_enabled_buy"]
and x["deposit_enabled_sell"]):
rows.append({**x, "net": net(x["spread_pct"])})
rows.sort(key=lambda x: x["spread_pct"], reverse=True)
return rows[:TOP], body["meta"]
def funding_rows():
"""Coins with the widest funding spread."""
body = get("/funding/spread") # no filters: has an ETag
rows = [x for x in body["data"] if x["spread_pct"] >= MIN_FUNDING]
rows.sort(key=lambda x: x["spread_pct"], reverse=True)
return rows[:TOP], body["meta"]
Both datasets are requested without parameters: the response to a request with min_spread, coin or another filter is built for that request and comes without an ETag. The monitor applies the thresholds itself: a spread of at least MIN_SPREAD, 24h volume of at least MIN_VOLUME on both exchanges, withdrawals open on the buy exchange and deposits open on the sell exchange. A null volume counts as zero, so such a row does not pass.
Rows are sorted by spread_pct in descending order, and the first TOP go into the table. In /funding/spread the MIN_FUNDING threshold is compared with the best pair's spread_pct.
What is left after fees, and the order-book check
def net(spread_pct):
"""What is left after two taker fees, approximately, %."""
return round(spread_pct - 2 * FEE, 4)
def book_net(row):
"""What is left after BOOK_USD of book and fees. Pro and Max."""
body = get("/orderbooks/spreads/spot-spot",
{"coin": row["coin"], "volume": BOOK_USD})
pair = (row["exchange_buy"], row["exchange_sell"])
for x in body["data"]:
if (x["exchange_buy"], x["exchange_sell"]) != pair:
continue
od = x["order_delta"]
if od["status"] != "ok":
return od["status"] # no_book or exhausted
return net(od["spread_pct"])
return "gone" # the pair has left the dataset
Assumed taker fees of 0.1% on the buy and 0.1% on the sell cut the spread by about 0.2 percentage points: a pair at 1.62% leaves 1.62 − 2 × 0.1 = 1.42%. Put your exchanges' fees in FEE (maker and taker). Withdrawal fees are not in the API responses, and the monitor does not account for them.
On Pro and Max, book_net rechecks the top three pairs against the order books: /orderbooks/spreads/spot-spot with the pair's coin and volume=1000 returns that coin's rows with an order_delta object, and the function takes the row with the same exchange pair (Order-book Δ). If there is no book or it ran out, you get the no_book or exhausted status instead of a number. A request with coin has no ETag and always costs a call, which is why a pass makes only three of them, set by BOOK_TOP.
The console table
def show(spot, s_meta, fund, f_meta):
now = time.time()
s_age = now - s_meta["updated_at"]
f_age = now - f_meta["updated_at"]
print(f"\nSpot – Spot, snapshot age {s_age:.0f} s")
print(f"{'Coin':<8}{'Buy → sell':<20}"
f"{'Spread':>7}{'-fees':>9}{'Book':>11}")
for x in spot:
pair = f'{x["exchange_buy"]} → {x["exchange_sell"]}'
book = x.get("book", "—")
if isinstance(book, float):
book = f"{book:.2f}"
print(f'{x["coin"]:<8}{pair:<20}{x["spread_pct"]:>7.2f}'
f'{x["net"]:>9.2f}{book:>11}')
print(f"\nFunding, snapshot age {f_age:.0f} s")
for x in fund:
b = x["best"]
legs = (f'{b["exchange_1"]} {b["interval_1"] or "?"} / '
f'{b["exchange_2"]} {b["interval_2"] or "?"}')
print(f'{x["coin"]:<8}{legs:<27}{x["spread_pct"]:>8.4f} %')
print(f"200 responses: {stats[200]}, 304: {stats[304]}")
The first table shows the coin, the exchange pair, spread_pct, what is left after fees and what is left after the book; a dash means the book was not checked. The second shows the best exchange pair by funding, with funding intervals and spread_pct. Above the tables is the snapshot age, the current time minus meta.updated_at, and below them the number of 200 and 304 responses since the start.
CSV history
def save(spot, fund):
"""Appends the pass to CSV: time, dataset, pair, spreads."""
new = not os.path.exists(CSV_FILE)
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
with open(CSV_FILE, "a", newline="", encoding="utf-8") as f:
w = csv.writer(f)
if new:
w.writerow(["time_utc", "dataset", "coin", "leg_1",
"leg_2", "spread_pct", "net_pct", "book"])
for x in spot:
w.writerow([ts, "spot-spot", x["coin"], x["exchange_buy"],
x["exchange_sell"], x["spread_pct"], x["net"],
x.get("book")]) # None becomes an empty cell
for x in fund:
b = x["best"]
w.writerow([ts, "funding", x["coin"], b["exchange_1"],
b["exchange_2"], x["spread_pct"], None, None])
The console table lasts until the next pass, while monitor.csv keeps every pass: it shows how long a pair lasts and at what hours it appears. The csv module is part of the Python standard library. Open the file with newline="", as the module documentation requires; otherwise, on systems that use \r\n line endings, an extra \r ends up in the file.
The book column holds what is left after the book, in percent, or the exhausted or no_book status. The module writes None as an empty cell, so the column stays empty for funding rows and unchecked pairs. Times are in UTC.
The main loop
def main():
usage = get("/account/usage")["data"] # does not use quota
books = usage["plan"] in ("pro", "max")
pace["gap"] = 1.1 / usage["rps_limit"]
print("Plan", usage["plan"], "| snapshot every",
usage["freshness_sec"], "s | order books:",
"yes" if books else "no")
pause = usage["freshness_sec"]
while True:
try:
spot, s_meta = spot_rows()
fund, f_meta = funding_rows()
if books:
for x in spot[:BOOK_TOP]:
x["book"] = book_net(x)
show(spot, s_meta, fund, f_meta)
save(spot, fund)
pause = s_meta.get("freshness_sec", pause)
except requests.HTTPError as e:
if e.response.status_code < 500:
raise # key, plan or parameters: a retry will not help
print("Server error, retrying:", e)
except (requests.RequestException, RuntimeError) as e:
print("No response, retrying:", e)
time.sleep(pause) # faster than freshness_sec = same snapshot
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nMonitor stopped, history is in", CSV_FILE)
At start the monitor calls /account/usage: the request uses no quota and returns the plan, freshness_sec and rps_limit (Usage). The plan tells the monitor whether to check order books, and rps_limit sets the pause between requests. The monitor rides out network failures and 5xx errors until the next pass, while 4xx errors (a wrong key, an expired subscription, a plan without the endpoint) stop it.
How to run it and read the output
python3 --version # Python 3.10 or newer is required
python3 -m pip install requests
export GENESIS_API_KEY="gns_live_XXXXXXXXXXXXXXXX"
python3 monitor.py
Output on the Pro plan, an illustrative example:
Plan pro | snapshot every 10 s | order books: yes
Spot – Spot, snapshot age 4 s
Coin Buy → sell Spread -fees Book
KLM ByBit → Gate 1.62 1.42 0.86
XYZ MEXC → Gate 1.24 1.04 exhausted
ABC BingX → HTX 1.12 0.92 0.31
QRS Gate → OKX 1.05 0.85 —
Funding, snapshot age 4 s
XYZ MEXC 4h / Bitget 8h 0.0600 %
ABC Hyper 1h / CoinEx 8h 0.0500 %
200 responses: 6, 304: 0
KLM: the row spread is 1.62%, 1.42% after two fees and 0.86% after $1,000 of order book plus fees. XYZ ran out of book at $1,000: for such a pair you cut the size or skip it. QRS is the fourth row, so its book was not requested. The funding table shows how often each exchange settles: Hyper (Hyperliquid's name in the responses) every hour and CoinEx every 8 hours. Press Ctrl+C to stop the monitor.
Of the four pair checks from lesson 3, the monitor runs the price gap and the transfer itself, the order book on Pro and Max, and shows freshness above the table. You verify the contract and the withdrawal fee.
Practice
Start the monitor
The first output line shows the plan, the snapshot step and whether books are checked; compare them with your profile.
Move the threshold
Set
MIN_SPREAD = 0.5and see how many of the new rows keep the -fees column above zero.Add a dataset
Copy
spot_rowsfor/arbitrage/futures-futures: the row format is the same. Drop the deposit and withdrawal check for futures, since no coin moves between exchanges there.Check the usage
After an hour, call
/account/usageand comparecalls_usedwith the estimate: on Trial that is up to 2 × 60 = 120 calls an hour.Find lasting pairs
Open
monitor.csvin a spreadsheet and count how many passes in a row each exchange pair lasted.
Automation risks, from stale data and errors to keys and AI agents, are covered in lesson 5, and economical polling with filters, compression and ETag in the article on polling an API without hitting limits.
Questions and answers
How is the monitor different from an arbitrage bot?
The monitor prints a table and keeps history; a bot sends alerts about new pairs and stays silent about repeats. They share the request and filtering code, and the Telegram bot is covered in Crypto arbitrage bot in Python.
Can I poll faster than freshness_sec?
You will not get new data: your plan gets a snapshot every freshness_sec seconds. A request without filters before the next snapshot returns a free 304, while a filtered request uses a call for the same data.
Why does the Book column show a dash?
Order-book Δ is only on Pro and Max, and the monitor requests it for the top three pairs (BOOK_TOP). On Trial and Start the endpoint returns 403 plan_restricted, so the monitor does not call it.