Testing crypto arbitrage and funding carry
TradeFlow started with a simple idea. The same asset often trades at slightly different prices on different exchanges: Hyperliquid's perpetual future against spot on Kraken, Coinbase or Binance US, or the same stock perp on two venues. Short the rich side, buy the cheap side, and close both when the gap collapses.
Big gaps often mean something broke, like a hack, frozen withdrawals or a delisting. So every trade first passes a danger sentinel: a language model, running locally, that reads crypto news and exchange announcements every ten minutes, backed by hard rules for delistings and stablecoin depegs.
This post is about the research more than the bot: how I tested that idea, why it failed, and how I found and validated the strategy that replaced it. The original idea didn't survive realistic testing, but something much less exciting did.
TradeFlow now runs in production with small amounts of real money. The results below come from backtests and order-book replays, not that live trading, and none of this is financial advice.
How I tested
The same rules applied to every idea, because the easiest way to fool yourself in a backtest is to give each idea its own:
- Settings are chosen on one window and scored on the next unseen one: walk-forward on bars, first-half versus second-half on the daily replays, and cross-fitting over five time blocks where a rule picks from many candidates.
- Every trade pays real costs: taker or maker fees by venue tier, half the spread, slippage, funding and borrow. Crypto signals execute eight hours after they fire, so a stale price can't flatter them.
- Strategies are compared on the capital they actually tie up, with idle money earning T-bills, so a strategy that sits out earns the risk-free rate, not zero.
- Where bars could mislead, I replayed recorded order books instead: block-by-block books for latency, recorded quotes for spreads.
- A change ships only if it improves the out-of-sample result. Several reasonable-sounding ones didn't, and stayed off.
1. The "premium" was mostly the bid-ask spread
On hourly bars the strategy looked profitable, even in walk-forward tests across 43 pairs. But nearly all the profit came from pairs with a thin order book on one side, and it shrank as the bars got finer:
| Bars | Pairs with a thin leg | Pairs where both legs trade |
|---|---|---|
| 1-hour, 205 days | +$2,045 | +$320 |
| 15-minute, 51 days | +$1,157 | +$43 |
| 5-minute, 17 days | +$520 | +$20 |
| 1-minute, 3.4 days | +$99 | +$7 |
A bar's closing price is the last trade, which happened at either the bid or the ask. On a thin book those are 5 to 65 basis points apart, so the "premium" jumps by that much and appears to collapse. On real recorded quotes, the gap's standard deviation is just 1 to 3 basis points.
The same artifact had earlier fooled a carry optimizer. Backtested entering at the signal's own price, it made +46.6% over the test year. With realistic entry it made about 3%, half as much as simply holding a fixed BTC and ETH carry position.
2. I tried to make it faster
Some gaps were real. The cleanest was the same stock perp on two Hyperliquid exchanges, such as NVDA on
xyz and io, which drift a few basis points apart and snap back within about a
second. Reacting instantly earned +2.7 basis points per trade; reacting a second late lost 2.4. The
first version of the bot, in Python, took 3 to 6 seconds to notice a price change, so I went after the
latency next.
Stop polling
The original bot polled each exchange over REST. It now keeps one websocket subscription to Hyperliquid's best bid and offer per leg, updated about every 170 ms, once per block. REST is reserved for slow data like funding, and paced, since REST and the websocket share one rate limit per IP. Decisions became event-driven: each book update immediately re-evaluates the pairs that use that market, instead of waiting for the one-second loop.
Rewrite the hot path in Rust
The path from new price to signed order moved into a Rust gateway: one persistent websocket, a local top of book, and Hyperliquid's order signing reimplemented from scratch. Signing is unforgiving, so the tests reproduce 33 signatures byte for byte against Hyperliquid's official Python SDK. Measured on an M-series Mac:
| Step | Time |
|---|---|
| Parse a book update | 0.4 µs |
| Check 20 resting-order guards | 2.8 µs |
| Build, sign and serialize a 10-order cancel | 36 µs |
| Whole update, micro-benchmark | ~40 µs (p99 63 µs) |
| Book update to signed order, live data | 155 µs median (p90 301 µs) |
The gateway began as a separate process the Python bot called over a Unix socket. Once it proved itself, I rewrote the whole engine in Rust and dropped Python from trading entirely, so there's no socket hop. The decision pass also never reads the database or takes a blocking lock: orders go to a worker pool, writes are batched on their own thread, and a price change wakes the loop immediately.
Resting orders instead of taking them
Taking liquidity means racing everyone who saw the same gap. The alternative is to rest an order on the thin venue and hedge on the deep one when it fills. Hyperliquid processes cancels and post-only orders before taker orders in each block, so a quote that's pulled the moment its reference price moves can't be picked off by a taker reacting at the same time.
Each resting order gets a guard, checked on every book update inside the websocket reader. It cancels the order when the reference price moves against it, the other side of the book comes too close, or the quote gets too old, and the engine re-posts at the new price.
Measuring fills
Every fill logs the quote's age at decision time, time spent in the bot's code and in transit, slippage, and where the market went 1, 5, 30 and 60 seconds later. Consistently negative short-term markouts mean someone faster is picking you off. Paper fills follow the same rules: an order only fills against a quote that arrived after it could have reached the exchange.
I then recorded 90 minutes of block-by-block order books during US market hours (20 stock pairs, 674,000 updates) and replayed the trade at every reaction time from 0 to 2,000 ms. If only one leg fills, it's unwound one delay later at whatever the price is then.
- Take both legs (IOC), best setting
- Rest an order on io, hedge on xyz
| Reaction time | Take both legs | Rest a quote, hedge the fill |
|---|---|---|
| 0 ms (same block) | +1.6 bps/trade | — |
| 100 ms (Tokyo server, optimistic) | −1.0 | −5.3 per fill |
| 200 ms (Tokyo server, typical) | −1.9 | −5.7 |
| 500 ms (US desktop, new code) | −2.9 | −6.6 |
| 1–2 s | −2.9 to −3.6 | −8.0 |
Network and block time set the limit
Between the websocket feed and the Rust rewrite, the time from a price change to a signed order went from seconds to about 0.15 ms, and it didn't matter. What's left is the network and the chain:
- Hyperliquid's API is served from Tokyo, about 175 ms of ping from the US.
- Blocks come every ~160 ms, and the gaps close within one.
- A server in Tokyo (AWS
ap-northeast-1) gets to about 100 ms and still loses a basis point per trade. - Arriving a block late leaves one leg unfilled a third to two thirds of the time.
- Resting quotes mostly fill just before the price moves against them; making them pay would take total costs under about 2 bps.
- The books hold only $150 to $1,000 at the best price, so even a winning version would be small.
That doesn't rule the trade out, but it changes what it takes. Two things could make it pay, and I haven't tested either: maker rebates at a high volume tier, which would cut the cost of the resting quotes below that 2 bps line, and getting orders into the same block as the price change, by reading blocks from my own node or using how Hyperliquid orders transactions inside a block. Both are the territory of professional market makers. Larger dislocations don't help either: scanning 135 Hyperliquid perps for 14 days found only 7 gaps over 2%, all on small coins worth tens of dollars of profit.
3. Funding carry
Perpetual futures have no expiry, so exchanges keep them near spot with funding: a fee longs pay shorts when the perp trades rich. The trade that held up in every test is funding carry. Short a perp whose longs are paying, hold the same asset long elsewhere so price moves cancel, and collect the funding.
The cleanest version comes from how two venues set funding. Hyperliquid's formula includes a fixed interest term worth 10.95% a year, so in calm markets its longs keep paying. Kalshi, a US-regulated exchange that started offering perps in June 2026, has no such term. Short ETH on Hyperliquid, long ETH on Kalshi, and the book collects the difference.
The gap closed or reversed for a few weeks in late June, mid-October and early November, so the engine only holds a pair while its trailing 72-hour funding pays: it enters above about 4% a year and exits only when funding turns negative. The wide gap between entry and exit is deliberate, because every exit costs a round trip of fees.
The carry is also shrinking. Hyperliquid's ETH funding gap averaged 16 to 17% a year in 2023 and 2024, and 6 to 8% in 2025 and 2026. It's real, but not guaranteed to stay well above T-bills.
4. Combining five strategies
The same idea works wherever a perp pays funding and the asset can be held cheaply elsewhere. I ended up with five versions:
| Strategy | Short | Long | Return/yr | Sharpe |
|---|---|---|---|---|
| CME basis | Gold, silver, EUR perps | CME micro futures | 11.1% | 3.1 |
| Perp spread | Hyperliquid perps | Kalshi perps | 9.5% | 2.0 |
| Crypto basis | Hyperliquid perps | Spot on Binance US | 8.7% | 2.5 |
| Stock basis | Stock perps | Shares at a broker | 6.3% | 3.6 |
| Looped lending | Borrow stablecoins against a savings token, about 6x | 6.1% | 4.2 | |
| T-bills | The hurdle | 4.0% | — | |
None of them is remarkable alone. Together they work because they barely move with each other: weekly correlations sit between −0.3 and +0.3.
Before trusting a strategy, I checked that its result didn't depend on one lucky setting. The parameter maps below show return across the main settings of two books. The crypto map is the out-of-sample year, and it stays positive across most of the grid, with a broad plateau rather than one sharp peak.
I replayed the whole system day by day over 800 days, deciding each day on earlier data only and paying every rebalance's costs. It returned about 9 to 9.5% a year against 4% for T-bills, with a Sharpe ratio of 2.7 to 3.1 depending on the weighting rule and a worst drop of half a percent. Out of sample it was 6 to 7% a year, which is the number to believe.
5. Risk
A hedged book has small daily swings and a few large hidden risks, so I measured both. Day to day, the book on $10,000 moves a few dollars, almost all of it the two venues' prices drifting apart and back. The daily P&L has fat tails, so I fit a Student-t rather than a normal distribution and estimated the expected loss in the worst 1% of periods (CVaR) with a block bootstrap.
The larger risks are leverage and outages. Each leg is margined on its own venue, so the engine closes both legs when either has moved halfway to liquidation. Every forced close costs a round trip, and above about 2x leverage those closes eat the carry. The worst case is one leg left unhedged while a venue is down: two hours unhedged in a bad hour cost $236 at 1-in-100 odds and $1,887 in the worst move since 2017. That's why the engine alerts on a naked leg within a minute.
6. Moving money toward the highest yield
The obvious improvement is to move money toward whatever pays most right now. Every version of that did worse out of sample: 0.3 to 0.7 points a year less, with a deeper worst drop. Current yields overstate what the strategies go on to earn by 1 to 3 points a year, and switching costs eat the rest. So the allocator estimates from what each strategy actually earned, and only moves money when it's measurably worth the cost.
Picking the best of many backtests has its own bias. When the allocator chose among 70 configurations (leverage rule, loop buffer, yield dial), the configurations chosen on the first half all fell short of the second half's frontier, and returns fell about 5 points between the halves. Volatility rankings persisted between halves (rank correlation 0.89); return rankings barely did (0.13).
To estimate the bias directly, I cross-fit the selection rule: choose on four of five time blocks, score on the fifth, and average. At the highest targets the in-sample pick overstates its return by 0.6 to 0.9 points, the winner's curse of choosing the best of 70 noisy backtests. Two refinements that looked sensible, smoothing the frontier and Ledoit–Wolf shrinkage of the covariance matrix, didn't improve the out-of-sample result, so both ship turned off.
7. How the allocator and router work
Running five strategies across seven venues means answering three questions at different speeds: which listings are worth holding, how much capital each strategy gets, and which orders that implies. TradeFlow gives each its own layer:
Scroll sideways to see the whole diagram.
- Every pass, ~1 s Strategies Gate their own listings and split capital across the ones that are on.
- Every 15 min Allocator Sets each strategy's share of capital, rebalancing only when it pays.
- Every pass, ~1 s Router Turns weights into target sizes: entries, closes and resizes.
- End of each pass Netting & executor Offsets opposite trades between strategies, then sends the rest.
Strategies
A strategy is a kind of trade, like "short a stock perp, hold the shares", not a single coin. Each owns a list of listings with their own gates; a crypto listing turns on when its expected return over T-bills clears +2% a year and off below −1%. Capital is split across the listings that are on by edge over T-bills divided by variance, with caps, and the split only changes when a listing turns on or off.
Leverage is set per listing by a rule:
leverage = min(venue max,
cap,
1 / (maintenance + k·σ·√3))
With k = 6 and σ the asset's 60-day daily volatility, each leg survives a six-sigma move over three days, since money can't move between venues over a weekend. In replay the rule added about 3 points a year on the CME book and a few tenths elsewhere.
The allocator
Every 15 minutes the allocator estimates each strategy's return over T-bills from the last 180 days, shrunk toward the group average by n/(n+365), so a strategy with three months of history is mostly assumed to be average. It proposes mean-variance weights on those estimates, a rule picked on the first half of the history:
| Weighting rule | In-sample Sharpe | Worst drop | 2nd-half Sharpe, $3k / $50k |
|---|---|---|---|
| Shrunk mean-variance (live) | 3.64 | −0.42% | 2.5 / 2.3 |
| Inverse volatility | 3.58 | −0.45% | 2.3 / 2.5 |
| Equal risk contribution | 3.58 | −0.45% | 2.4 / 2.5 |
| Equal weights | 3.40 | −0.53% | 1.8 / 2.6 |
The differences between them are small, and when to trade matters more. A rebalance only goes ahead when its expected gain beats its cost by more than the uncertainty in the estimates:
U(w) = w·μ - (λ/2) wᵀΣw
gain = [U(target) - U(now)] × 120/365
noise = 1 standard error of the gain
cost = Σ |Δwᵢ| × ½ round tripᵢ
trade if gain - noise > cost
and 3+ days since the last move
Forced exits skip the wait, and a short history's large standard error keeps it from trading on noise. This replaced a fixed "rebalance weekly on 20% drift" band, scoring a second-half Sharpe of 2.44 against 2.38: close, but it trades on a measured reason rather than a tuned threshold.
An optional target-yield mode finds the least-volatile portfolio expected to earn a chosen yield. It's a small convex quadratic program over each strategy's weight and leverage, with a branch-and-bound for minimum capital; the whole efficient frontier takes 20 to 30 ms and runs once a minute in the background. Two choices made it usable in practice. First, it estimates from trailing realised returns rather than today's funding, which overstated returns (8.3% a year signalled against 5.5% realised for the perp spread); that took its Sharpe from about 1 to 2.7. Second, it only switches portfolios when the new one has at least 5% less volatility, which cut switching costs from about 1% a year to 0.2%.
The router
Every pass, the router multiplies each strategy's weight by capital and by each listing's split to get a target size for every pair. Moving money between venues takes hours to days (a Kalshi withdrawal is a 1–3 day bank transfer), so targets are scaled to the capital that can actually reach each venue, and a separate planner moves funds over automatable routes without touching margin open positions need.
Pairs are resized only when they're more than 25% or $50 off target, the target has held for five minutes, and they haven't been resized in the last hour. Both legs always hold the same quantity, so the hedge never drifts. Orders from a pass are netted before they're sent: when one strategy needs to buy what another needs to sell, the overlap moves between them inside the account at the mid price, with no fee. Weights, splits and every decision are saved, so a restart doesn't resize the book.
The slow decisions, the frontier and the allocator, run in the background on minutes. The fast path from quote to order never waits on them.
What I ruled out
- Trading the premium collapse: an artifact on bars, and a loss on real order books at any realistic speed.
- Trend following on BTC and ETH: 28% a year, but with a 34% worst drop, which makes it a bet on the market rather than an edge.
- Funding long-short, long the coins paying least and short those paying most: −22% a year.
- Forecast models and directional books: none survived costs and out-of-sample tests.
Where TradeFlow stands
TradeFlow is in production, trading the carry strategies with small amounts of real money. It reconciles live results against the backtest piece by piece (funding, fees, margin interest and price drift), and size only goes up once the two keep agreeing. The danger sentinel still screens every entry.