← All posts

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:

BarsPairs with a thin legPairs 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
Scatter plot of backtest profit per trade against Binance US bid-ask spread. BTC and ETH sit near zero; coins with wide spreads such as AVAX, HYPE and LTC show 14 to 19 bps of apparent profit.
Backtest profit per trade grows with the bid-ask spread: the signature of a data artifact, not an edge.

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.

Line chart of cumulative return over the out-of-sample year. The optimizer as first backtested, entering at the signal price, reaches +46.6%. Plain BTC and ETH carry reaches +6.2%. The optimizer with realistic entry reaches +3.2% on all coins and +3.1% on liquid coins only.
Year two, with settings chosen on year one. The dashed line is the backtest artifact; the solid lines are what the strategies would really have done.

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:

StepTime
Parse a book update0.4 µs
Check 20 resting-order guards2.8 µs
Build, sign and serialize a 10-order cancel36 µs
Whole update, micro-benchmark~40 µs (p99 63 µs)
Book update to signed order, live data155 µ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.

Profit per trade after fees against reaction time, for 20 Hyperliquid stock perp pairs replayed on 90 minutes of block-by-block order books. Taking both legs with IOC orders earns +1.6 basis points at 0 ms, filling in the same block as the price change, then loses 1.0 at 100 ms, 1.9 at 200 ms, 2.5 at 300 ms, 2.9 at 500 ms and 1,000 ms, and 3.6 at 2,000 ms. Resting an order on io and hedging on xyz loses 5.3 at 100 ms, 5.7 at 200 ms, 6.1 at 300 ms, 6.6 at 500 ms and 8.0 at 1,000 ms. A Tokyo server reacts in about 100 to 200 ms, a home Mac with the new code in about 500 ms, and the old bot took 3 to 6 seconds. Tokyo server home Mac old bot: 3–6 s → +2 0 −2 −4 −6 −8 bps per trade, after fees Take both legs, 100 ms: -1.0 bps Take both legs, 200 ms: -1.9 bps Take both legs, 300 ms: -2.5 bps Take both legs, 500 ms: -2.9 bps Take both legs, 1,000 ms: -2.9 bps Take both legs, 2,000 ms: -3.6 bps Rest on io, hedge on xyz, 100 ms: -5.3 bps Rest on io, hedge on xyz, 200 ms: -5.7 bps Rest on io, hedge on xyz, 300 ms: -6.1 bps Rest on io, hedge on xyz, 500 ms: -6.6 bps Rest on io, hedge on xyz, 1,000 ms: -8.0 bps Take both legs, 0 ms: +1.6 bps +1.6 same block as the move take both legs rest on io, hedge on xyz // 0 100 200 500 1,000 2,000 reaction time, ms (log scale)
  • Take both legs (IOC), best setting
  • Rest an order on io, hedge on xyz
Profit per trade after fees, by reaction time: the time from a price change to our order being matched. At standard fees, only a 0 ms reaction, filling in the same block as the price change, makes money. Nothing between 0 and 100 ms was measured, so the two are not joined. The resting-order test has no 0 ms case.
Reaction timeTake both legsRest 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.

Line chart of funding paid by ETH longs on Hyperliquid and on Kalshi, June to November 2026. Hyperliquid mostly sits between 5 and 11% a year near its fixed baseline; Kalshi mostly sits near zero. The gap reverses briefly in late June, mid-October and early November.
Funding paid by ETH longs, 7-day average. The blue band is what the pair collects, about 7.5% a year on average; orange is where it briefly paid out.

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:

StrategyShortLongReturn/yrSharpe
CME basisGold, silver, EUR perpsCME micro futures11.1%3.1
Perp spreadHyperliquid perpsKalshi perps9.5%2.0
Crypto basisHyperliquid perpsSpot on Binance US8.7%2.5
Stock basisStock perpsShares at a broker6.3%3.6
Looped lendingBorrow stablecoins against a savings token, about 6x6.1%4.2
T-billsThe hurdle4.0%—
Scatter plot of return against volatility for the five strategies. CME basis returns 11.1% at about 2.4% volatility; perp spread 9.5% at 2.8%; crypto basis 8.7% at 1.9%; stock basis and looped lending about 6% at under 1%. T-bills are a line at 4%.
Return against volatility for each strategy on its own history, after costs.

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.

Two heatmaps of return on capital. Left, crypto rotation out of sample: funding window from 1 to 30 days against entry threshold from 4% to 15% a year; most cells between 4% and 7.5%. Right, stock carry in sample: funding window from 5 to 40 days against a minimum funding level; cells between 4.6% and 8.4%.
Return across settings. Left: crypto rotation in its out-of-sample year. Right: stock carry, in sample, since the stock perps only have one window of history.
Heatmap of weekly correlations between the five strategies, all between -0.32 and +0.31, beside a bar chart of each strategy's minimum capital: $1k, $1k, $2k, $10k and $0.5k.
Left: weekly correlations between strategies. Right: the capital each one needs.

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.

Two line charts of cumulative return from September 2024 to November 2026. Left: each strategy alone, all above the T-bill line. Right: the combined allocator reaching about 20% cumulative, against about 9% for T-bills; the yield-chasing variant trails it.
Left: each strategy alone. Right: the combined book against T-bills. Right of the dotted line is out of sample. Some lines start partway through because their data does: stock basis has about 350 days of history (real stock-perp prices from April 2026, a proxy before that), CME basis about 330 days and the lending loop about 135 days, since its current Morpho market is recent. Until a strategy's data begins, its capital is counted at the T-bill rate, so it follows the T-bill line. The two crypto books cover the full 800 days; the perp spread uses a proxy for Kalshi funding before Kalshi listed perps in June 2026.

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.

Left: histogram of daily P&L for the hedged ETH and SOL book from June 4 to November 19, 2026, with a fitted Student-t curve; one-day 95% VaR is $8 and 99% VaR is $17 on $10,000. Right: one-day and ten-day 99% CVaR for the premium jitter, the funding differential and the whole book, between $5 and $34.
Daily P&L of the hedged book on $10,000 with a Student-t fit (99% one-day VaR about $17), and CVaR by component.

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.

Left: ETH pair return on capital against leverage on each leg, for a backtest without guard closes and after guard closes at 2023 to 2026 and 2017 to 2026 volatility; returns fall sharply above about 2x. Right: loss on a $6,000 leg left open for 5, 30 and 120 minutes at 1-in-100, 1-in-1,000 and worst-since-2017 odds, up to $1,887.
Left: return against leverage once forced closes are counted. Right: what a leg left unhedged during an outage can lose.

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).

Scatter of 70 configurations by second-half volatility and return, with the second-half efficient frontier. Configurations picked on first-half figures, raw and smoothed, sit below and to the right of the frontier.
Configurations chosen on the first half, plotted in the second half against that half's efficient frontier.

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.

Left: return at each target yield from 4% to 9%, in-sample against cross-fitted with a one-standard-error band, for raw and smoothed selection. Right: in-sample minus cross-fitted return per target for 4, 5 and 6 blocks, near zero up to 7% and rising to about 0.9 points at 9%.
Cross-fitted return per target, and the selection bias: in-sample minus cross-fitted. The bias grows at the top of the range, where the rule is choosing among the noisiest backtests.

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:

TradeFlow system architecture Market data from Hyperliquid's websocket, the other venues and funding and rate polls feeds an in-memory quote book inside tfengine, a Rust process. A decision loop that wakes on every quote change applies gates, risk limits and the margin guard; the allocator and router set weights and sizes; execution workers send orders to the venues, with one lock per venue; a store writer batches rows into SQLite every 75 milliseconds; and a reconciler compares venue positions with what the engine expects. A separate tfsentinel process reads news and gets verdicts from a local language model through LLMGateway, which gate entries. Offline, tfrecorder records order books and Python research refits and backtests the strategies and writes the seed the allocator starts from. The dashboard and Discord alerts read the database. MARKET DATA Hyperliquid websocket, every block Other venues Kalshi, Kraken, Binance US, Coinbase, IBKR Funding & rates paced polls, DeFi rates RESEARCH, OFFLINE tfrecorder records order books Python research refits and backtests, writes the strategy seed TFENGINE · RUST In-memory quote book Decision loop gates, risk, margin guard; wakes on every quote change Allocator → router weights every 15 min, sizes Execution workers 6 threads, one lock per venue Store writer batched every 75 ms Reconciler venue positions vs expected ORDERS Venues Hyperliquid (signed in Rust) Kalshi · Kraken (FIX) Binance US · Coinbase IBKR · Morpho (paper) tfsentinel news + local LLM verdicts via LLMGateway SQLite (WAL) pairs, fills, history Dashboard · alerts web UI, Discord orders gates seed

Scroll sideways to see the whole diagram.

TradeFlow's architecture. Everything on the trading path is Rust and runs in memory; the database, the sentinel and the research job sit beside it, never in front of it. Dashed lines are slower paths.
  1. Every pass, ~1 s Strategies Gate their own listings and split capital across the ones that are on.
  2. Every 15 min Allocator Sets each strategy's share of capital, rebalancing only when it pays.
  3. Every pass, ~1 s Router Turns weights into target sizes: entries, closes and resizes.
  4. 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 ruleIn-sample SharpeWorst drop2nd-half Sharpe, $3k / $50k
Shrunk mean-variance (live)3.64−0.42%2.5 / 2.3
Inverse volatility3.58−0.45%2.3 / 2.5
Equal risk contribution3.58−0.45%2.4 / 2.5
Equal weights3.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.