Crypto arbitrage bot in Python: from spread API to Telegram alerts
In short
- A crypto arbitrage bot has four links: spread data, a filter for executable pairs, an alert and a human decision. The code handles the first three; you place the trades on the exchanges.
- Execution is the hard part of arbitrage: moving the coin, fees, slippage and time. So the bot keeps only pairs with open withdrawals and deposits, and on Pro and Max it also recomputes the spread through $1,000 of order book.
- The bot polls Genesis API no more often than
meta.freshness_sec, waits outRetry-Afteron429and503, and alerts on a pair at most once every 15 minutes. The basic version runs on the $20-a-month Trial plan.
A crypto arbitrage bot is a program that pulls spreads between exchanges on a schedule — the price gap for one coin, in percent — keeps the pairs you can actually execute and alerts you about them. A person makes the decision and places the trade. A bot like this for spot cross-exchange arbitrage takes about 140 lines of Python: spreads come from Genesis API, and messages go out through the Telegram Bot API.
What an arbitrage bot is made of
Every arbitrage bot is built from four links:
| Link | What it does | In this bot |
|---|---|---|
| Data | Pulls prices and spreads across exchanges | Genesis API GET /arbitrage/spot-spot |
| Filter | Keeps the pairs you can execute | Deposit and withdrawal status, Order-book Δ for $1,000 |
| Alert | Reports the pair | Telegram Bot API sendMessage method |
| Decision and trade | Checks the pair and trades | A person on the exchanges |
Your own data collector is the slowest link to build: every exchange has its own API, its own ticker and network names and its own deposit and withdrawal statuses, and all of it has to be merged into one format. Genesis API returns ready pairs across 20+ CEX exchanges, including Binance, OKX, Bybit, Bitget, MEXC and Gate, with prices, spread, network, contract, deposit and withdrawal status and volumes. The fields of every arbitrage endpoint are in the Genesis API arbitrage endpoints guide, and choosing a data source is covered in Crypto APIs: types and how to choose one.
Why the trades stay with a person
Finding a spread is the easy part of arbitrage. Execution is the hard part: four obstacles stand between a row in an API response and money in your account.
- Moving the coin: the withdrawal and the deposit take anywhere from minutes to hours, and an exchange can suspend deposits or withdrawals at any moment.
- Fees: both exchanges charge a trading fee, and the withdrawal fee is usually a fixed number of coins that eats the spread on a small trade.
- Slippage: the spread is computed from last trades, while a market order walks the order book, so a buy fills above the best ask and a sell below the best bid.
- Time: data arrives with your plan's delay, up to 60 seconds on Trial, and other traders see the same gap and close it.
Hypothetical example: the bot sends a pair with a 1.2% spread, which is $12 on $1,000. After walking the order books for $1,000, 0.8% is left, or $8. A 0.1% taker fee on the buy and on the sell costs about $2, and withdrawing the coin costs $3.
Code that buys and withdraws the coin by itself turns each of these failures into a trade nobody checked. That is why this bot sends a signal: it checks withdrawals, deposits and the spread after the order books itself, and a person verifies the contract, fees and transfer route before trading. Genesis API cannot trade anyway: it only reads data and places no orders. The step-by-step manual check of a pair is in Cross-exchange crypto arbitrage.
What you need
- Python 3.10 or newer and the
requestslibrary. - A Genesis API key on any plan: click "Get key" in your profile and save the
gns_live_…key — it is shown only once. Storing and reissuing it is covered in the Genesis API key guide. - A Telegram bot token: send
/newbotto @BotFather, choose a name and a username, and BotFather replies with a token like123456:ABC-DEF…. chat_id, the ID of your chat with the bot. A bot cannot message you first (Telegram docs): send it/start, then callgetUpdates; the number in"chat":{"id":…}is yourchat_id. Updates are kept for no longer than 24 hours.
python3 --version # Python 3.10 or newer is required
python3 -m pip install requests
export GENESIS_API_KEY="gns_live_XXXXXXXXXXXXXXXX"
export TG_BOT_TOKEN="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
# after /start in the bot chat, find "chat":{"id":...} in the reply
curl "https://api.telegram.org/bot$TG_BOT_TOKEN/getUpdates"
export TG_CHAT_ID="123456789"
Variables set with export last until you close the terminal. Per the Telegram docs, the token gives full control of the bot, and the key gives access to your plan, so both live only in environment variables: they never go into code or a repository.
Bot code step by step
The seven blocks below are the complete bot.py: save them into one file in this order. The thresholds in the settings are placeholders; tune them to your fees and trade size.
1. Settings
import os
import time
import requests
API = "https://api.genesisarbitrage.com/v1"
TG = "https://api.telegram.org/bot" + os.environ["TG_BOT_TOKEN"]
CHAT_ID = os.environ["TG_CHAT_ID"]
MIN_SPREAD = 1.0 # row spread from 1%
MIN_VOLUME = 50_000 # 24h volume on both exchanges from $50,000
MIN_EXEC = 0.5 # spread after $1,000 order books from 0.5%
TOP = 5 # pairs per pass, at most
REPEAT_SEC = 15 * 60 # one pair at most once every 15 minutes
RECHECK_SEC = 5 * 60 # a pair the book ate waits 5 minutes
api = requests.Session()
api.headers["X-API-Key"] = os.environ["GENESIS_API_KEY"]
cache = {} # request -> (ETag, response)
wait_until = {} # pair -> time until which it stays quiet
The key travels in the X-API-Key header of every request made through the api session and never goes into the URL. MIN_VOLUME drops pairs where the 24h volume on either exchange is below $50,000. cache holds response ETags, and wait_until holds the time until which the bot stays quiet about a pair.
2. Calling Genesis API: Retry-After and ETag
def get(path, params=None):
"""GET to Genesis API with Retry-After retries and ETag."""
key = (path, tuple(sorted((params or {}).items())))
for _ in range(4): # one request and up to three retries
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: # snapshot unchanged
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 won't help
body = r.json()
if "ETag" in r.headers: # only full datasets carry an ETag
cache[key] = (r.headers["ETag"], body)
return body
raise RuntimeError("Genesis API is busy, retrying next pass")
429 comes back when you exceed the rate limit per second or the download volume, and 503 while data is being rebuilt. Both carry Retry-After, and get waits as many seconds as the server asks. An exhausted quota also returns 429, but with Retry-After set to the reset time, sometimes days away, so the bot stops. 400, 401 and 403 won't go away on retry, so raise_for_status raises them. All limits are in the Genesis API limits guide.
3. Spreads and pair filtering
def candidates():
"""Spot – Spot pairs whose coin can actually be moved."""
body = get("/arbitrage/spot-spot",
{"min_spread": MIN_SPREAD, "min_volume": MIN_VOLUME})
# withdrawals open on the buy side, deposits on the sell side
rows = [x for x in body["data"]
if x["withdraw_enabled_buy"] and x["deposit_enabled_sell"]]
rows.sort(key=lambda x: x["spread_pct"], reverse=True)
return rows, body["meta"]["freshness_sec"]
min_spread and min_volume filter rows on the server. There are no parameters for the deposit and withdrawal flags, so the code checks them: the coin can be moved if withdrawals are open on the buy exchange (withdraw_enabled_buy) and deposits on the sell exchange (deposit_enabled_sell). The fields the bot uses, in a row from the Spot — Spot docs:
{
"coin": "FUEL",
"exchange_buy": "ByBit",
"exchange_sell": "Gate",
"spread_pct": 0.11,
"network": "ETH",
"contract": "0x675B68AA4d9c2d3BB3F0397048e62E6B7192079c",
"withdraw_enabled_buy": true,
"deposit_enabled_sell": true,
"volume_24h_buy": 17652.64,
"volume_24h_sell": 12512.51,
"trade_url_buy": "https://www.bybit.com/trade/spot/FUEL/USDT",
"trade_url_sell": "https://www.gate.io/trade/FUEL_USDT",
…
}
This row would not pass the bot's filters: a 0.11% spread and volumes under $50,000. The bot puts the network and contract into the message so you can match them against the withdrawal and deposit pages of both exchanges.
4. The $1,000 order-book check
def exec_spread(row):
"""Spread after $1,000 order books. Pro and Max only."""
body = get("/orderbooks/spreads/spot-spot",
{"coin": row["coin"], "volume": 1000})
for x in body["data"]:
od = x["order_delta"]
if (x["exchange_buy"] == row["exchange_buy"]
and x["exchange_sell"] == row["exchange_sell"]
and od["status"] == "ok"):
return od["spread_pct"]
return None # no_book, exhausted, or the pair is gone
The endpoint returns the coin's rows from the Spot – Spot dataset with an order_delta object — Order-book Δ, the spread after walking the order books: buying through the buy exchange's asks and selling into the sell exchange's bids. The function takes the row with the same exchanges and its order_delta.spread_pct when status is ok; no_book means there is no book, and exhausted that the book ran out before $1,000. Books lag the exchange by 5–20 seconds; the fields are described in the Order-book Δ docs and the order book endpoints guide.
This step exists only on Pro and Max; on Trial and Start the endpoint returns 403 plan_restricted. The bot reads your plan at startup and skips the check there: the message says the order book was not checked, and you look at depth in the exchange terminal yourself.
5. The Telegram message
def message(row, ex):
buy, sell = row["exchange_buy"], row["exchange_sell"]
if ex is None:
book = "order book not checked (Trial or Start)"
else:
book = f"after $1,000 order books: {ex:.2f}%"
return "\n".join([
f'{row["coin"]}: {buy} → {sell}',
f'Spread {row["spread_pct"]}%, {book}',
f'Network {row["network"]}, contract {row["contract"] or "—"}',
f'Buy: {row["trade_url_buy"]}',
f'Sell: {row["trade_url_sell"]}',
])
def send(text):
"""Telegram Bot API sendMessage; on 429 wait retry_after."""
for _ in range(3):
r = requests.post(TG + "/sendMessage", timeout=15, json={
"chat_id": CHAT_ID, "text": text,
"link_preview_options": {"is_disabled": True}})
if r.status_code != 429:
r.raise_for_status() # 400 or 401: wrong chat or token
return
wait = r.json().get("parameters", {}).get("retry_after", 5)
time.sleep(wait) # Telegram flood control
raise RuntimeError("Telegram did not accept the message")
sendMessage takes chat_id and text of 1 to 4096 characters, and the request goes to https://api.telegram.org/bot<token>/sendMessage (Telegram Bot API docs). link_preview_options with is_disabled turns off link previews. Under flood control Telegram returns 429 and puts the wait, in seconds, into parameters.retry_after. In a single chat Telegram asks bots to avoid sending more than one message per second (bot developer FAQ).
A message looks like this, as a hypothetical example:
XYZ: MEXC → Gate
Spread 1.4%, after $1,000 order books: 0.62%
Network ETH, contract 0x…
Buy: https://…
Sell: https://…
6. Deduplication: one pair every 15 minutes
def scan(books):
"""One pass: spreads, order books, messages."""
rows, pause = candidates()
done = 0
for row in rows:
key = (row["coin"], row["exchange_buy"], row["exchange_sell"])
if time.time() < wait_until.get(key, 0):
continue # already alerted, or the book ate the spread
if done == TOP:
break
done += 1
ex = exec_spread(row) if books else None
ok = not books or (ex is not None and ex >= MIN_EXEC)
if ok:
send(message(row, ex))
# quiet for 15 minutes after an alert, 5 if the book is thin
hold = REPEAT_SEC if ok else RECHECK_SEC
wait_until[key] = time.time() + hold
time.sleep(1) # at most one request and message per second
return pause
A pair is the triple of coin, buy exchange and sell exchange. After an alert the bot stays quiet about it for 15 minutes, even if the spread holds. If the book ate the spread, the bot returns to the pair in 5 minutes, so order-book checks don't cost a call on every pass. A pass takes at most five pairs with the widest spreads and pauses for a second after each: that keeps the bot within Telegram's advice and within the per-second limit of any plan. The dictionary lives in memory, so fresh pairs may repeat after a restart.
7. The loop: pause of at least freshness_sec
def main():
usage = get("/account/usage")["data"] # uses no quota
books = usage["plan"] in ("pro", "max")
pause = usage["freshness_sec"]
print("Plan", usage["plan"], "| polling every", pause, "s",
"| order books:", "yes" if books else "no")
while True:
try:
pause = scan(books)
except requests.HTTPError as e:
if e.response.status_code < 500:
raise # key, plan or token: a retry won't help
print("Server error, retrying:", e)
except (requests.RequestException, RuntimeError) as e:
print("No response, retrying:", e)
time.sleep(pause) # no more often than meta.freshness_sec
if __name__ == "__main__":
main()
At startup the bot calls /account/usage: the request uses no quota and returns your plan and freshness_sec. That is data freshness, the interval at which your plan gets a new snapshot: 60 seconds on Trial, 30 on Start, 10 on Pro and 5 on Max. After that the pause comes from meta.freshness_sec, since polling faster returns the same snapshot. Network failures and 5xx errors wait for the next pass, while the remaining 4xx errors — a wrong key, an expired subscription, a plan without the endpoint, a wrong token or chat_id — stop the bot. Error codes are listed in Genesis API responses and errors, and a spread monitor without Telegram is built in the lesson Spread and funding monitor in Python.
How to run and check it
python3 bot.py
# Plan trial | polling every 60 s | order books: no
Wait for the first pass
Messages arrive when the market has pairs above your thresholds. If none come within a few minutes, lower
MIN_SPREADandMIN_VOLUMEfor a while: that shows the chain from the API to Telegram works.Compare a pair with the table
Open Spot – Spot on the site: the same coin and exchange pair is in the table. The numbers may differ slightly, because the API serves the snapshot with your plan's delay.
Check deduplication
The same pair should not arrive again within 15 minutes.
Watch call usage
Look at the
calls_usedfield in/account/usageor the "Calls used" line in your profile: on Trial without order-book checks the bot uses about 1,440 calls a day.Leave the bot running
nohup python3 bot.py >> bot.log 2>&1 &runs the bot in the background; set the environment variables in the same terminal session.
Which Genesis API plan the bot needs
A pass is one /arbitrage/spot-spot call, plus up to five /orderbooks/spreads/spot-spot calls on Pro and Max; only 200 responses use quota. Upper bound for 30 days: (1 + checks per pass) × 86,400 / pause × 30.
| Plan | Polling | $1,000 order-book check | Calls per 30 days |
|---|---|---|---|
| Trial, $20/month | Every 60 s | No | 43,200 of 500,000 |
| Start, $50/month | Every 30 s | No | 86,400 of 2M |
| Pro, $100/month | Every 10 s | Yes | Up to 1,555,200 of 5M |
| Max, $200/month | Every 5 s | Yes | Up to 3,110,400 of 10M |
On Trial that is 86,400 / 60 × 30 = 43,200 calls, 8.64% of the quota. On Pro, in the worst case where every pass checks five books, it comes to 6 × 86,400 / 10 × 30 = 1,555,200 calls, or 31.1% of the quota. Quota rules are in the Plans & limits section of the docs.
Risks of an arbitrage bot
- Stale prices: the snapshot refreshes every
freshness_secand order books lag the exchange by 5–20 seconds, so check prices in the exchange terminal before trading. - Closed networks: the deposit and withdrawal flags hold at snapshot time, and an exchange can close withdrawals while you are buying. One ticker can mean different tokens on different exchanges, so match
contractandnetwork. - Fees and withdrawals:
spread_pctdoes not include them, and a fixed withdrawal fee eats the whole spread on a small amount. - False spreads on thin books: a wide last-trade spread on a rarely traded coin disappears with the first order.
min_volumeand the $1,000 check filter out some of these pairs, but not all. - Hitting limits: extra requests within a second get
429withRetry-After: 1, and an exhausted quota stops the bot until the reset. Using several keys or accounts to get around limits breaks the rules; higher plans exist for heavier load. Telegram also answers429under flood control.
No code: Genesis Arbitrage Telegram alerts
If you would rather not write and run your own bot, Genesis Arbitrage Telegram Alerts send the pairs for you. You create a bot in @BotFather, paste its token on the site and pick categories such as Spot - Spot, DEX - Futures, Crosschain and Funding arbitrage. Filters set the minimum spread, exchanges and networks, Deposit/Withdrawal status and Order spread, and Time to repeat (min) limits how often one pair comes back. The personal bot runs on the site's Pro plan, separate from Genesis API plans; setup is in the Telegram notifications guide.
Questions and answers
Can the bot trade on its own?
Not through Genesis API: the API only serves data and places no orders. Trading is added through the exchanges' own APIs with trading keys, which is separate code and your own risk: a stale spread or a closed withdrawal becomes a trade nobody checked.
How much does a bot like this cost?
The code is free, and so are the bot's messages to Telegram users. You pay for data: Genesis API starts at $20 a month on Trial, and the order-book check starts with Pro at $100. You also need a computer or server that runs around the clock.
Which Genesis API plan do I need?
Trial is enough for the basic bot: /arbitrage/spot-spot is on every plan, with a new snapshot every 60 seconds. Start refreshes data every 30 seconds. The $1,000 Order-book Δ check works only on Pro and Max.
Why did the bot send a pair with no spread left on the exchange?
Data arrives with your plan's delay, and other traders close the gap too. The row spread is also computed from last trades, while you can only buy at the ask and sell at the bid. Check prices and the order book in the exchange terminal before trading.
Can I put the bot on GitHub?
Yes: the terms allow building your own bots on Genesis API, and the only restriction is reselling the raw data as is. Keep the key and the token out of the repository. If the key ends up in public code, click "Reissue" in your profile, and the /token command in @BotFather replaces the bot token.