Developing a Cash-and-Carry Arbitrage Algorithm
The basis between spot and perpetual futures on liquid crypto pairs consistently yields 10–20% annually — provided you precisely manage funding rate, fees, and liquidation risks. The strategy sounds simple: buy spot, short futures, collect the spread. But in practice, hidden costs and liquidity anomalies kill profitability if not built into the algorithm. We specialize in precisely such algorithms — with detailed consideration of expiry, margin buffer, and cross-exchange collateral.
How the Basis Works and Where Yield Comes From
Cash-and-carry exploits the divergence between the spot price of an asset and the futures or perpetual price. For dated futures, the basis is defined by the cost of carry formula:
F = S × e^(r-q)×T
where S is the spot price, r is the risk-free rate, q is the asset yield, and T is time to expiry. In crypto, the risk-free rate is historically higher than in traditional assets, so futures trade in contango (F > S) most of the time.
For perpetual futures, the basis is maintained through the funding rate: when the perpetual trades above spot, longs pay shorts every 8 hours (on Binance). The funding rate amount is a direct source of yield for the trader holding a long spot + short perp position. More on the cost of carry model can be found in the Wikipedia article.
Non-Obvious Risks in Cash-and-Carry Arbitrage
Funding rate reversal. The funding rate can turn negative. In a bear market or during a sharp increase in short open interest, shorts start paying longs. The strategy turns from profitable to losing. The algorithm must track funding rate dynamics and close the position when it falls below a threshold (accounting for fees and slippage on close).
Liquidation asymmetry. A short on futures theoretically has unlimited loss, a long spot is limited to zero. During a sharp price increase (30% in an hour, as in some altcoin events), margin on the short futures may be insufficient, even if the long spot is in profit. The strategy is technically delta-neutral but requires a sufficient margin buffer. Rule: margin on short ≥ 2× the maximum historical daily move of the asset.
Exchange counterparty risk. Holding both spot and futures on the same exchange carries the risk of a freeze (FTX case). This can be neutralized via a cross-exchange strategy: spot on one exchange (or DeFi), futures on another. However, this adds complexity to collateral management.
Basis divergence at expiry. For dated futures, theory says F → S at expiry. In practice, 1–2 days before expiry the basis can widen due to demand imbalances — especially in altcoins with low liquidity. The algorithm must account for the optimal exit time.
Why the Algorithm Must Track Funding Rate
The funding rate is the main driver of yield. Even with stable contango, a negative rate over several periods can wipe out all profit. The algorithm monitors the predicted funding rate in real time (available 8 hours ahead) and compares it to a threshold, accounting for opening/closing fees. If the expected net yield falls below the minimum — the system automatically exits the position.
Algorithm Architecture
System Components
Data aggregator. Collects in real time:
- Spot prices from multiple sources (Binance spot, Coinbase, Kraken) to avoid manipulation
- Futures/perp prices and open interest
- Current and predicted funding rate (Binance publishes predicted funding rate 8 hours ahead)
- Historical funding rate data for rolling annualized yield calculation
Basis calculator. Normalizes data and calculates:
- Current basis in % and annualized form
- Estimated yield accounting for entry/exit fees, funding payments
- Break-even holding period
Position manager. Opens and closes positions based on signals from the basis calculator. Ensures delta-neutrality: size of long spot = notional value of short futures.
Risk monitor. Continuously tracks margin ratio on futures position, funding rate trend, basis anomalies. If conditions are violated — automated exit.
Net Yield Calculation
Real strategy profit after all costs:
Net APY = Funding Rate (annualized)
- Trading fees (entry + exit, both legs)
- Slippage (bid-ask spread × 2)
- Borrowing cost (if using margin)
- Opportunity cost on margin collateral
| Parameter | Example for BTC | DeFi version |
|---|---|---|
| Funding rate (APY) | 10.95% | 8.4% (average) |
| Trading fees | 0.16% | 0.5–1% (gas) |
| Slippage | 0.06% | 0.1–0.3% |
| Net yield | ≈10.7% APY | ≈7–8% APY |
Example calculation for BTC cash-and-carry on Binance (real data):
- Funding rate: 0.01% every 8h = 10.95% APY
- Taker fees: 0.04% × 4 operations = 0.16% round trip
- Slippage: ~0.03% × 2 = 0.06%
- Net yield ≈ 10.73% APY before tax
When funding rate is 0.03% (common in a bullish market), net yield rises to 30%+ APY.
Rollover of Dated Futures
When working with quarterly/monthly futures, a rollover algorithm is needed: close the expiring contract and open the next one. Optimal rollover time is 3–5 days before expiry, when the basis of the next contract has normalized but liquidity of the current one is still sufficient.
Automatic rollover accounts for:
- Basis difference between current and next contract (if the next is in greater contango — rollover is profitable, if less — it's a cost)
- Current liquidity of both contracts
- Spread on both contracts simultaneously (risk: basis may shift while closing the first contract)
To minimize the latter risk, we use TWAP execution: close current and open new contract in parallel with small orders.
On-Chain Implementation: DeFi Version of the Strategy
In DeFi markets, cash-and-carry can be implemented via:
- Pendle Finance. The protocol splits yield-bearing tokens into Principal Token (PT) and Yield Token (YT). Buying PT at a discount to par plus hedging through Pendle AMM is analogous to cash-and-carry with fixed yield to maturity.
- Perp on dYdX / GMX v2 / Synthetix Perps. Long spot via Aave/Compound (staked ETH or cbETH) + short ETH perp on dYdX. The spot position earns staking yield (~4% APY), short collects funding rate.
The on-chain version adds gas costs and oracle risk but removes exchange counterparty risk. The exchange version is 10× faster in execution than DeFi but requires trust in a centralized platform.
Comparison of CEX and DEX versions
| Characteristic | CEX (Binance) | DEX (dYdX) |
|---|---|---|
| Execution | Instant | Delayed due to gas |
| Fees | 0.04% taker | 0.1-0.5% + gas |
| Counterparty risk | Present | None (non-custodial) |
| Available pairs | 200+ | 20-30 |
Development Process
- Analytics (3–5 days). Backtesting on historical data: Binance historical funding rates available via API for 2+ years. Model strategy under different market conditions, determine entry/exit thresholds.
- Core development (1–2 weeks). Data aggregator, basis calculator, position manager. Connect to exchange APIs (CCXT as universal library or direct WebSocket connections for latency).
- Risk management and monitoring (1 week). Automated exit when funding rate < threshold, margin call protection, Telegram alerts.
- Paper trading (3–5 days). Run without real money on production data. Verify calculations, latency, edge cases.
- Deploy. Test with small amounts, gradually increase positions.
What's Included
- Data collection and basis calculation algorithm
- Position management module with delta-neutrality
- Risk monitor with automatic exit on condition violations
- Documentation and architectural diagram
- Deployment on your server or cloud
- 1 month of post-deployment support
Time Estimates
An algorithm for one pair on one exchange with basic risk management — 2–3 weeks. Multi-asset, multi-exchange strategy with automatic rollover — 4–8 weeks. DeFi version via on-chain protocols — additional 2–3 weeks. Cost is calculated individually.
We have developed over 15 algorithms for crypto arbitrage, 5 years on the market. Experience with Ethereum since 2017. To discuss your strategy, leave a request — we will select the optimal architecture. Get a consultation on choosing a solution for your project.







