.jpg)
TL;DR
→ Robinhood Chain runs ~100 ms blocks with a single first-come, first-served sequencer. Priority fees do not move you up the queue, so arrival time is the whole contest.
→ Uniswap v2, v3, v4 and UniswapX are all live on the chain, which gives you several venues for the same pair and therefore a spread to trade.
→ The build is five parts: feed, scanner, sizer, simulator, executor. A competent loop spends about 50 ms on work and leaves the rest of the block as margin.
→ Quote with an aggregator for breadth and with the v4 Quoter for precision, size with a local model, then confirm the winner with a single on-chain call.
→ Gas moved from 0.020 gwei to 0.511 gwei when the subsidy ended, so a two-leg cycle now carries a real cost that has to sit inside the profit model.
→ Everything below is runnable Python. The part you cannot copy from a repository is the network path to the sequencer.
This DEX arbitrage bot tutorial walks the whole path in Python: connect to the chain, read prices from two sources, find a spread, size it, simulate it, fire it, and keep it from losing money while you are asleep. Every snippet below is runnable, the addresses are the live ones on chain 4663, and the cost figures come from the chain's own data rather than from a demo environment.
Almost everything people search for under how to build a trading bot on Robinhood Chain is strategy, and almost none of the difficulty is. The arbitrage logic fits in a couple of hundred lines. The reason two operators running the same two hundred lines report different results sits underneath the code, in the path between the signing key and the sequencer.
How arbitrage bots work
An arbitrage bot buys an asset where it is cheap and sells it where it is dear, inside a single transaction. If either leg fails the whole call reverts and you lose only gas. That atomicity is the entire reason on-chain arbitrage is a sane business: you are never left holding half a position.
A simple example
USDG and WETH trade in several Uniswap pools on Robinhood Chain, at different fee tiers and with different depth. A large swap lands in one of them and moves its price. For a moment that pool quotes WETH at 0.4% below the others. Your bot buys WETH in the cheap pool, sells it in an expensive one, and returns the difference minus fees, price impact and gas. The pool is back in line and you are paid for putting it there.
That is a two-leg cycle. A triangle adds a third hop, USDG to WETH to a third token and back to USDG, which opens up pairs with no direct market. Public implementations of this loop on Robinhood Chain enumerate closed cycles of two to three legs from USDG and WETH entry points. Two and three are the useful range. Four hops multiply the gas and the failure surface faster than they add opportunity.
Why Robinhood Chain suits this strategy
Three properties of the chain matter more than anything in your code. First, blocks land about every 100 milliseconds and the sequencer is first-come, first-served with no fee priority, so an opportunity resolves within a block or two and the winner is whoever arrived first. Second, Uniswap v2, v3, v4 and UniswapX all went live on day one, which puts the same pairs in multiple venues with different curves. Third, the chain is already busy: on a single September day the main swap router processed 1.7 million transactions, and wallets doing between 101 and 1,000 swaps made up 59% of them, a signature of automated flow.
The flip side is honest and worth stating before you write a line. The same report found that eight addresses drove roughly 79% of a demand surge, and that no sampled transaction was charged a tip, because there is no tip to charge. You are entering a latency market against operators who already know that.
The profit formula
Every decision in the bot comes back to one expression. Net profit is the output of the final leg minus the input of the first, minus the gas of the whole call, minus the expected cost of the attempts that revert.
net = amount_out_final - amount_in_first - gas_cost - revert_allowance
# amount_out_final quoted through every leg, impact included
# gas_cost gas_used * gas_price, both legs, one call
# revert_allowance gas_cost * (1 - win_rate) / win_rate
# Fire only when: net > min_profit_thresholdAny honest Robinhood Chain bot profitability model starts and ends with this expression, and the revert allowance is the term beginners leave out of it. If you win one race in three, every successful cycle has to carry the gas of the two it lost, which is where the arbitrage profit calculation stops being a subtraction and starts being an expectation.
.jpg)
Bot architecture and setup
The architecture in five parts
The design below is deliberately small. Every part does one thing, and none of them calls the node when it can read memory instead.
.jpg)
The ordering is not negotiable. A liquidity pool scanner that re-reads state from the node on every candidate will spend its whole block waiting on round trips. Build the pool graph once from factory logs, hydrate it with a single Multicall3 batch, then keep it current from the feed.
Prerequisites to install
python -m venv .venv && source .venv/bin/activate
pip install web3==7.* # EVM client, async provider, signing
pip install websockets # sequencer feed subscription
pip install httpx # aggregator quotes, HTTP/2 keep-alive
pip install eth-abi eth-utils # calldata encode and decode
pip install uvloop orjson # faster event loop and JSON on Linux
# optional, for the research phase only
pip install pandas pyarrow # replay captures and backtestsA Web3.py Robinhood Chain bot needs nothing exotic. The chain is fully EVM compatible, so the standard web3.py stack works unchanged, and so do Foundry and Hardhat when you move to writing the executor contract.
Hardware and placement
A token arbitrage bot setup needs far less hardware than people expect. A four-core virtual machine with 8 GB of RAM runs this loop comfortably. The scanner is arithmetic on a few hundred pools, not a database. Where the machine sits matters far more than what it is made of, because the network hop to the sequencer is the largest single line in the time budget and it cannot be optimised in Python.
Steps 1 to 3: connect, read prices, detect spreads
Step 1: connect to the RPC endpoint
Start with constants. Hard-coding the chain id and asserting it at startup has saved more bots than any other single line, because a silent testnet connection looks exactly like a market with no opportunities.
The examples use RPC Fast's Robinhood Chain API. One key serves HTTPS and WebSocket, accepts the key in the URL or in an X-API-KEY header, and exposes eth_simulateV1 for checking a route before signing and eth_sendRawTransactionSync for getting the receipt in the same call.
from web3 import Web3
import time
RPC_URL = "https://robinhood-mainnet.rpcfast.com/?api_key=YOUR_API_KEY"
CHAIN_ID = 4663 # Robinhood Chain mainnet
FEED_WS = "wss://feed.mainnet.chain.robinhood.com"
WETH = "0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73"
POOL_MGR = "0x8366a39CC670B4001A1121B8F6A443A643e40951" # Uniswap v4
V4_QUOTER = "0x8Dc178eFB8111BB0973Dd9d722ebeFF267c98F94"
PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3"
MULTICALL = "0xcA11bde05977b3631167028862bE2a173976CA11"
w3 = Web3(Web3.HTTPProvider(RPC_URL, request_kwargs={"timeout": 2}))
assert w3.is_connected(), "endpoint unreachable"
assert w3.eth.chain_id == CHAIN_ID, f"wrong chain: {w3.eth.chain_id}"
acct = w3.eth.account.from_key(PRIVATE_KEY)
print(acct.address, w3.eth.get_balance(acct.address) / 1e18, "ETH")Then measure the endpoint before you trust it. The number that decides your win rate is the tail, not the average, and you want it in writing before the first trade.
def probe(n=200):
samples = []
for _ in range(n):
t0 = time.perf_counter()
w3.eth.block_number
samples.append((time.perf_counter() - t0) * 1000)
samples.sort()
return {
"p50": round(samples[n // 2], 1),
"p95": round(samples[int(n * 0.95)], 1),
"p99": round(samples[int(n * 0.99)], 1),
}
print(probe()) # anything with p99 above ~40 ms will lose contested cyclesPublic endpoints for the chain are published and rate limited, which makes them fine for the research phase and unusable for the live loop. The official network details list the RPC and WebSocket URLs, and the protocol contracts page carries the bridge, Permit2 and Multicall addresses.
Step 2: read prices from the aggregator and from the pool
Two sources, two purposes. The aggregator gives you breadth across every venue on the chain in one call. The Quoter gives you an exact number for one pool. The scanner uses the first to find candidates and the second to confirm them.
For breadth, the aggregator API follows a two-step pattern: a GET that returns a route summary, then a POST that encodes it into calldata. A Robinhood Chain DEX aggregator bot usually lives entirely in the first call during scanning and only reaches the second when it is about to fire.
import httpx
AGG = "https://aggregator-api.kyberswap.com/{chain}/api/v1/routes"
BUILD = "https://aggregator-api.kyberswap.com/{chain}/api/v1/route/build"
CHAIN_SLUG = "robinhood" # KyberSwap slug for chain ID 4663
HEADERS = {"X-Client-Id": "rhc-arb-bot"}
client = httpx.Client(http2=True, timeout=1.0, headers=HEADERS)
def route(token_in, token_out, amount_in):
r = client.get(AGG.format(chain=CHAIN_SLUG), params={
"tokenIn": token_in, "tokenOut": token_out,
"amountIn": str(amount_in)})
r.raise_for_status()
return r.json()["data"]["routeSummary"] # amountOut, gas, gasUsd, route
def build(route_summary, sender, slippage_bps=10):
r = client.post(BUILD.format(chain=CHAIN_SLUG), json={
"routeSummary": route_summary,
"sender": sender, "recipient": sender,
"slippageTolerance": slippage_bps,
"deadline": int(time.time()) + 20})
r.raise_for_status()
d = r.json()["data"]
return d["routerAddress"], d["data"], int(d["transactionValue"])For precision, call the v4 Quoter. It is not a view function, so you read it with eth_call and never send it. For raw pool state there is also StateView, which exposes getSlot0 and getLiquidity against a pool id computed as keccak256(abi.encode(poolKey)). That pair of reads is what lets you run the curve locally instead of paying a round trip per quote.
QUOTER_ABI = [{
"name": "quoteExactInputSingle", "type": "function",
"stateMutability": "nonpayable",
"inputs": [{"name": "params", "type": "tuple", "components": [
{"name": "poolKey", "type": "tuple", "components": [
{"name": "currency0", "type": "address"},
{"name": "currency1", "type": "address"},
{"name": "fee", "type": "uint24"},
{"name": "tickSpacing", "type": "int24"},
{"name": "hooks", "type": "address"}]},
{"name": "zeroForOne", "type": "bool"},
{"name": "exactAmount", "type": "uint128"},
{"name": "hookData", "type": "bytes"}]}],
"outputs": [{"name": "amountOut", "type": "uint256"},
{"name": "gasEstimate", "type": "uint256"}]}]
quoter = w3.eth.contract(address=V4_QUOTER, abi=QUOTER_ABI)
def quote_pool(pool_key, zero_for_one, amount_in):
"""Read-only simulation. Never submit this call."""
out, _gas = quoter.functions.quoteExactInputSingle(
(pool_key, zero_for_one, int(amount_in), b"")).call()
return outOne warning on hooks. A v4 pool can attach a hook contract that changes pricing at swap time, including just-in-time liquidity designs that fill from baskets rather than from standing depth. Local maths will not reproduce those pools. Filter hookless pools into the fast path and quote hooked pools on-chain, or skip them.
Step 3: scan for profitable spreads
The scanner is where the real-time price monitoring bot earns its name. It does not poll. It reacts to the feed, marks the pools a block touched, and recomputes only the cycles that pass through them.
from dataclasses import dataclass
FEE_BPS = 10 # 0.05% per leg, two legs
GAS_UNITS = 240_000 # measured, not guessed
MIN_NET = 2 * 10 ** 6 # 2 USDG, in token decimals
@dataclass
class Hit:
cycle: tuple # (pool_a, pool_b) or a triangle
size: int
gross: int
net: int
def gas_cost_wei(gas_price_wei):
return GAS_UNITS * gas_price_wei
def scan(touched_cycles, probe_size, gas_price_wei):
hits = []
for cycle in touched_cycles:
out = probe_size
for pool, zero_for_one in cycle:
out = local_quote(pool, zero_for_one, out) # in-memory curve
gross = out - probe_size
if gross <= 0:
continue
net = gross - to_token(gas_cost_wei(gas_price_wei))
if net < MIN_NET:
continue
hits.append(Hit(cycle, probe_size, gross, net))
return sorted(hits, key=lambda h: -h.net)Note what the threshold does. MIN_NET is not there to make you greedy, it is there to stop the executor firing on cycles whose profit is inside the error bar of your own local model. Set it at roughly four times the gas cost of a cycle and raise it if your revert rate climbs.
Steps 4 and 5: size the route and execute
Step 4: optimise the route and size the trade
Finding a spread is the easy half. Choosing how much to send through it is where most automated arbitrage strategy code quietly loses money, because profit is not monotonic in size. Impact grows faster than the spread it is chasing, so there is a maximum somewhere in the middle and the largest trade the pool will accept is almost never it.

Search for that maximum against your local curve, never against the node. A ternary search converges in forty iterations, and forty iterations at two on-chain calls each would be eighty round trips inside a 100 millisecond block. Run the search in memory, then spend one call confirming the winner.
def net_for(cycle, size, gas_token):
out = size
for pool, zero_for_one in cycle:
out = local_quote(pool, zero_for_one, out) # in-memory, microseconds
return out - size - gas_token
def best_size(cycle, lo, hi, gas_token, iters=40):
"""Ternary search: net(size) is unimodal, so this is safe."""
for _ in range(iters):
m1 = lo + (hi - lo) // 3
m2 = hi - (hi - lo) // 3
if net_for(cycle, m1, gas_token) < net_for(cycle, m2, gas_token):
lo = m1
else:
hi = m2
size = (lo + hi) // 2
return size, net_for(cycle, size, gas_token)
size, modelled = best_size(hit.cycle, lo=50 * 10**6, hi=50_000 * 10**6,
gas_token=gas_in_token)Then confirm. Transaction simulation is how you optimise away the losing fires: one eth_call against the current head, using the same calldata you are about to sign, tells you whether the modelled number survives contact with real state. A failed simulation costs microseconds. A failed transaction costs gas and a block.
def simulate(router, calldata, value, sender):
"""Dry-run the exact call. Returns False on revert."""
try:
w3.eth.call({"from": sender, "to": router,
"data": calldata, "value": value})
return True
except Exception as exc:
log.debug("sim revert: %s", exc)
return False
confirmed = quote_pool_chain(hit.cycle, size) # one on-chain read
if confirmed - size - gas_in_token < MIN_NET:
return # model drifted, skipSlippage handling automation belongs in the same step, and the right place for the guard is on-chain rather than in Python. The executor contract takes a minimum output and reverts below it, so a pool that moves between your simulation and your inclusion costs you gas instead of principal. Set the minimum from the confirmed quote with a small tolerance, typically ten to twenty basis points, rather than from a fixed percentage that ignores the depth you just measured.
Step 5: execute the transaction
Two details on this chain change how the executor is written. Priority fees do not buy position, so setting a tip is spending money for nothing. And deadlines belong on timestamps rather than block numbers, because 100 millisecond blocks make a block-count deadline far shorter than anyone intends.
def fire(router, calldata, value, gas_limit, nonce):
tx = {
"chainId": CHAIN_ID,
"to": router,
"data": calldata,
"value": value,
"gas": gas_limit, # measured, with 15% headroom
"maxFeePerGas": w3.eth.gas_price * 2,
"maxPriorityFeePerGas": 0, # FCFS: a tip buys nothing
"nonce": nonce,
}
signed = acct.sign_transaction(tx)
return w3.eth.send_raw_transaction(signed.raw_transaction)
# Nonce is managed locally. One in-flight transaction at a time per key,
# or a second key per concurrent cycle. Never let two cycles race a nonce.
nonce = w3.eth.get_transaction_count(acct.address, "pending")Order execution optimization on an EVM chain usually means bidding into a private relay. There is no equivalent here, and this is the point where the mental model has to change. Flashbots-style arbitrage execution relies on a builder auction and a private order flow channel, neither of which exists on a chain with one sequencer and no public mempool. What carries over is the atomic bundle, and you reproduce it in a single contract call: both legs plus an on-chain profit assertion, so an unprofitable outcome reverts rather than settles.
// Executor.sol, the part that matters
function run(bytes calldata path, uint256 minOut) external onlyOwner {
uint256 before = IERC20(USDG).balanceOf(address(this));
_swap(path); // both legs, one call
uint256 gained = IERC20(USDG).balanceOf(address(this)) - before;
require(gained >= minOut, "unprofitable"); // atomic revert
}The main loop and monitoring
The loop is driven by the sequencer feed rather than by a timer. The feed at wss://feed.mainnet.chain.robinhood.com broadcasts each block's ordering before any RPC node has re-executed it, which is the earliest signal available to anyone on the chain.
import asyncio, orjson, websockets
async def main():
book = PoolBook.build(w3, WATCHED_POOLS) # factory logs, once
book.hydrate(w3, MULTICALL) # one batched read
nonce = w3.eth.get_transaction_count(acct.address, "pending")
async with websockets.connect(FEED_WS, ping_interval=15,
max_queue=256) as ws:
async for raw in ws:
block = orjson.loads(raw)
touched = book.apply(block) # local state update
if not touched:
continue
gas_price = book.gas_price # cached per block
for hit in scan(book.cycles_through(touched),
PROBE_SIZE, gas_price):
size, modelled = best_size(hit.cycle, LO, HI, gas_in_token)
if modelled < MIN_NET:
continue
router, data, value = build_calldata(hit.cycle, size)
if not simulate(router, data, value, acct.address):
metrics.inc("sim_revert")
continue
tx_hash = fire(router, data, value, GAS_LIMIT, nonce)
nonce += 1
metrics.observe("fired", hit, size, modelled, tx_hash)
break # one cycle per block
asyncio.run(main())Two lines in that loop are what separate automated arbitrage strategy code that lands from code that merely runs. The break at the end is the first, and it is deliberate. Firing two cycles from one block means two transactions racing the same nonce and the same pool state, and the second one almost always reverts. One cycle per block, then let the next block tell you what changed.
What you log decides whether the bot ever improves. The minimum set below answers the only question that matters after a loss: did we lose on the signal or on the wire?
Two of those lines are the whole monitoring story. If feed-to-decision is comfortable and sign-to-acknowledge is not, no amount of code work will help. If modelled and realised diverge, your local curve is wrong and the fix is in the maths, not the network.
Optimisation and deployment
Quick optimisations
- Pre-sign templates. Build and sign the transaction shape at startup and mutate only the volatile fields at fire time. Signing in the hot path costs milliseconds you do not have.
- One HTTP connection, kept warm. An HTTP/2 client with keep-alive avoids a TLS handshake per quote. A fresh connection per call can add more latency than the whole scan.
- Batch every read. Multicall3 turns several hundred pool reads into one request. Hydration at startup and after a feed gap should never be a loop of single calls.
- Cache gas price per block. Calling for gas price inside the candidate loop adds a round trip to every evaluation for a number that changes once a block.
- Split read and write connections. State reconstruction is read-heavy and bursty. It must not be able to delay a submission by occupying the same socket.
- Filter hooked pools out of the fast path. Local maths cannot reproduce a hook that prices at swap time, and a wrong local quote is worse than a missing one.
Deployment checklist before mainnet
.jpg)
Before anything is submitted, replay. Record the sequencer feed for a volatile hour, then backtest your arbitrage strategy against that capture with the executor disabled. A single busy hour of real ordering is worth more than a week of synthetic data, because it contains the exact pattern you are trading: a large swap, a dislocated pool, and several other bots reacting to the same block you did.
Scaling path
Scale in the order that the constraint actually binds. First widen the pool graph, because more cycles cost nothing but memory. Then add the second and third leg, which turns a single-pair DEX arbitrage bot into a multi-DEX routing algorithm and opens pairs with no direct market. Then move the hot path from Python to Rust, but only once the logs show the scanner rather than the wire is the limit. Most teams reach for the rewrite two steps too early.
Capital scales differently. Doubling the bankroll does not double the profit, because the optimum size is set by pool depth rather than by what you hold. Extra capital buys an arbitrage bot more simultaneous cycles on separate keys, not larger ones on the same pool. The ceiling on Robinhood Chain is pool depth rather than balance, and the way past it is more pairs, not more size.
Risk management
Essential rules
Bot risk management automation is not a feature you add to a DEX arbitrage bot later. An unattended process with a signing key and a network connection will eventually meet a state you did not model, and the only question is whether it stops by itself. On Robinhood Chain that moment arrives sooner than on a slower network, because a 100 ms block lets a broken loop fire several hundred times before anyone looks at a dashboard.
- Atomic or nothing. Both legs and the profit assertion live in one call. A DEX arbitrage bot that sends two separate swaps is not arbitraging, it is taking directional risk with extra steps.
- Hard position cap. A per-cycle notional ceiling enforced in the contract, not only in Python, so a bug in the sizer cannot send the whole balance.
- Daily loss limit with a kill switch. Cumulative gas burn plus realised losses against a fixed number, checked before every fire, with a stop a human can reach from a phone.
- Consecutive failure breaker. Three reverts in a row halts the loop. It is almost always a stale local curve or a changed pool, and both get worse with repetition.
- Feed gap detection. A missed sequence number means your arbitrage bot is pricing against state that no longer matches the chain. Stop, rehydrate, resume. Never trade through a gap.
- Keys separated by function. The trading key holds working capital only. Treasury sits elsewhere and never signs from the bot process.
None of these rules costs throughput. An arbitrage bot on Robinhood Chain spends most of its life idle between opportunities, so every check above runs in the gap rather than in the hot path.
Example position sizing
Concrete numbers, built around the atomic revert property. Because a failed cycle costs gas rather than principal, the right way to size is to cap the notional at what pool depth can absorb and cap the daily bleed at what failed attempts can burn.
The gas figure is not invented. After the chain's subsidy ended, the median swap through the main router cost about $0.48 in gas on a median trade of $73.49, with gas moving from 0.020 gwei in late August to 0.511 gwei in early September, a 25-fold rise. Any token arbitrage bot setup modelled on subsidised gas is modelling a chain that no longer exists.
Common mistakes to avoid
Seven failures account for most of what goes wrong with an arbitrage bot on Robinhood Chain in its first month. None of them is subtle once you have seen it, and every one of them is cheaper to read about than to meet at full size.
- Sizing to the pool instead of to the curve. The largest trade a pool accepts is past the optimum almost every time. Search for the maximum of net, not of gross.
- Paying a priority fee. Ordering is by arrival time. A tip is a donation.
- Deadlines in block numbers. At 100 ms per block, a deadline of 20 blocks is two seconds. Use timestamps.
- Quoting from the node inside the loop. One round trip per candidate and the block is gone. A DEX arbitrage bot quotes locally and confirms once.
- Trusting a local quote on a hooked pool. A hook can price from a basket rather than from standing liquidity, and your curve will not see it.
- Ignoring the revert allowance. A strategy that is profitable per landed cycle and unprofitable per attempt is an unprofitable strategy.
- Running two cycles against one nonce. The second reverts, and you paid for the privilege. One in flight per key.
What actually decides whether this is profitable
Six hours is an honest estimate for the build described in this DEX arbitrage bot tutorial. Connect and probe the endpoint, wire the feed and the pool graph, write the scanner and the sizer, add simulation and the executor contract, then spend the rest on logging. None of it is hard, and all of it is available in open source if you would rather read than type.
What no account of how to build a trading bot on Robinhood Chain can hand you is the last term in the profit equation. On a chain where the sequencer orders by arrival time and refuses tips, two bots with identical logic produce different P&L entirely because of the milliseconds between signing and acknowledgement. That is the honest conclusion of any Robinhood Chain bot profitability guide: the strategy is public, the maths is public, the code is public, and the latency profile underneath it is not.
So build the loop, instrument it, and measure the wire before you optimise the code. If feed-to-decision is 50 milliseconds and sign-to-acknowledge is 90, the next rewrite will not help and the next endpoint will. An arbitrage bot on Robinhood Chain is a latency product with a trading strategy attached, and the order of those two words is the whole point.

.jpg)
.jpg)