275+ Perpetual Markets — Hyperliquid + DEX Spot

DeFi Arbitrage
API for AI Agents

Profit from price differences across 275+ markets. Instantly.
Purple Flea gives your agent the trading infrastructure, wallet layer, and cross-chain tools to execute arbitrage strategies at machine speed with sub-50ms latency.


275+
Perp markets
<50ms
P50 API latency
20%
Referral fee share
6
Chains supported

What is DeFi Arbitrage?

Arbitrage is the practice of exploiting price differences for the same asset across different markets. In traditional finance, these gaps close in microseconds because institutional desks have co-located servers at exchanges. In DeFi, the landscape is more fragmented — dozens of DEXes, perpetual exchanges, and chains each quote slightly different prices for the same token. Those gaps are profit opportunities.

The mechanics are simple: if ETH-PERP is trading at $3,520 on Hyperliquid and spot ETH is available for $3,500 on Uniswap, you can buy spot, short the perp, and lock in a $20 margin — risk-free, assuming execution is fast enough. If BTC costs $0.02 more on Arbitrum than on Polygon, bridge and sell. If the funding rate on a perp is +0.1% per 8 hours, going delta-neutral earns that rate as pure yield.

Purple Flea gives your AI agent all three layers it needs to execute these strategies: a Trading API for Hyperliquid perp positions, a Wallet API for spot token swaps, and a Cross-Chain Swap API for bridging assets between networks. Your agent can scan, evaluate, and execute an arbitrage opportunity entirely via REST calls — no blockchain SDK integration required.


Purple Flea's Arbitrage Toolkit

Three complementary APIs that together cover every arbitrage strategy in DeFi.

Endpoint What it does Used for
POST/v1/trading/order Open and close perpetual futures positions on Hyperliquid across 275+ markets Short perp leg of basis trade; directional funding arb
POST/v1/wallet/swap Spot token swap via Wagyu aggregator (routes through best DEX on any chain) Long spot leg of basis trade; DEX price arbitrage
POST/v1/cross-chain/swap Swap tokens across chains in a single call (bridges + swaps automatically) Cross-chain price arbitrage; asset rebalancing
GET/v1/market/orderbook/{symbol} Fetch real-time orderbook depth for any Hyperliquid perp market Identify bid/ask spread; size positions correctly
GET/v1/funding-history/{symbol} Historical funding rate data per 8-hour epoch for any perp market Backtest funding strategies; identify high-rate markets
GET/v1/trading/positions List all open perpetual positions with current PnL and liquidation price Monitor exposure; trigger stop-loss rebalances

Arbitrage Strategies for AI Agents

Four proven strategies your agent can implement using Purple Flea's APIs. Each targets a different type of market inefficiency.

1

Perp / Spot Basis Trade

When a perpetual futures contract trades at a premium to spot price, you can capture the gap by buying spot and simultaneously shorting the perp. The positions are delta-neutral — you profit as the premium converges, plus you earn positive funding if the perp is in contango.

Execution: Use /v1/wallet/swap to buy spot tokens, then /v1/trading/order to short the same asset on Hyperliquid. Close both legs when the basis tightens.

Delta Neutral
2

Cross-Exchange Perp Arbitrage

The same perpetual contract can trade at different prices on different venues. If BTC-PERP is $50 cheaper on one exchange than Hyperliquid, buy the cheaper leg and short the more expensive one. Lock in the spread as both prices converge under market pressure.

Execution: Monitor Hyperliquid prices via /v1/market/orderbook/{symbol} and compare against external price feeds. When the spread exceeds your threshold plus fees, open both legs simultaneously.

Cross-Venue
3

Funding Rate Farming

Perpetual contracts pay or receive a funding rate every 8 hours to keep the perp price anchored to spot. When funding is highly positive (longs pay shorts), go short on the perp and long on spot to create a delta-neutral position that earns the funding payment.

Execution: Use /v1/funding-history/{symbol} to identify markets with consistently high positive funding. Open a delta-neutral position and hold through the funding epoch. Unwind when funding normalizes.

Yield Strategy
4

Cross-Chain Price Arbitrage

The same token can trade at different prices on different chains due to bridge latency, liquidity fragmentation, and different DEX depths. If USDC/ETH is 0.3% cheaper on Polygon than on Arbitrum, bridge ETH to Polygon, buy, bridge back, and sell.

Execution: Compare spot prices across chains using /v1/market/price?chain=polygon vs chain=arbitrum. When net of bridge fees a gap exists, execute via /v1/cross-chain/swap.

Cross-Chain

Triangular Arbitrage Scanner

A complete Python agent that scans price relationships across three assets and executes when a profitable cycle is detected.

triangular_arb_scanner.py
import requests, os, time, itertools from decimal import Decimal API_KEY = os.environ["PURPLEFLEA_API_KEY"] BASE = "https://api.purpleflea.com/v1" H = {"X-API-Key": API_KEY, "Content-Type": "application/json"} # Triangular set: USDC -> ETH -> BTC -> USDC TRIANGLE = ["USDC", "ETH", "BTC"] FEE_BPS = 30 # 0.3% per swap MIN_PROFIT = 0.002 # Execute if net profit > 0.2% CAPITAL = "500" # USDC starting capital per cycle def get_quote(from_asset: str, to_asset: str, amount: str) -> dict: """Get a swap quote without executing.""" r = requests.get(f"{BASE}/wallet/quote", params={ "chain": "polygon", # Low-fee chain for triangular arb "from_asset": from_asset, "to_asset": to_asset, "amount": amount, }, headers=H) return r.json() def execute_swap(from_asset: str, to_asset: str, amount: str) -> dict: """Execute an actual swap.""" r = requests.post(f"{BASE}/wallet/swap", json={ "chain": "polygon", "from_asset": from_asset, "to_asset": to_asset, "amount": amount, "slippage_bps": 20, }, headers=H) return r.json() def scan_triangle() -> float: """ Simulate USDC -> ETH -> BTC -> USDC path. Return net profit as a fraction (e.g., 0.003 = 0.3%). """ q1 = get_quote("USDC", "ETH", CAPITAL) q2 = get_quote("ETH", "BTC", q1["to_amount"]) q3 = get_quote("BTC", "USDC", q2["to_amount"]) final_usdc = Decimal(q3["to_amount"]) start_usdc = Decimal(CAPITAL) net_profit = (final_usdc - start_usdc) / start_usdc return float(net_profit) def run_scanner(): print("Triangular arb scanner running (Polygon, USDC/ETH/BTC)...") cycles = 0 profits = 0.0 while True: profit_pct = scan_triangle() cycles += 1 print(f"[Cycle {cycles}] Spread: {profit_pct*100:.3f}%", end=" ") if profit_pct > MIN_PROFIT: print("-- EXECUTING") r1 = execute_swap("USDC", "ETH", CAPITAL) r2 = execute_swap("ETH", "BTC", r1["to_amount"]) r3 = execute_swap("BTC", "USDC", r2["to_amount"]) pnl = float(r3["to_amount"]) - float(CAPITAL) profits += pnl print(f" PnL this cycle: +${pnl:.4f} | Total: +${profits:.4f}") else: print("-- skip") time.sleep(2) # Poll every 2 seconds (Polygon block time) if __name__ == "__main__": run_scanner()

Latency Considerations

In arbitrage, latency is alpha. The faster your agent receives market data and submits orders, the narrower the spreads it can exploit — and the less likely another bot beats it to the same opportunity. Purple Flea's infrastructure is co-located with Hyperliquid's order matching engine to minimize round-trip time.

Our P50 API latency for order submission is under 50ms from any major cloud region. P95 remains below 120ms. For context, Hyperliquid's matching engine processes orders in under 1ms — the bottleneck for most agents is the API call, not the exchange itself.

For latency-sensitive strategies, deploy your agent in AWS us-east-1 or GCP us-east4 — the same regions where Purple Flea's API infrastructure is hosted. This shaves another 5–15ms off typical round-trips versus running from other geographies.

API Latency Profile

P10
18ms
P50
48ms
P90
92ms
P95
118ms
P99
155ms

Measured from AWS us-east-1. Order submission endpoint. 30-day rolling average.


Built-In Risk Controls

Arbitrage is not risk-free. Slippage, latency, and correlation risk can turn profitable-looking opportunities into losses. Purple Flea provides the primitives to manage these risks programmatically.

Manageable

Position Sizing

Set a maximum capital allocation per arbitrage cycle. Never put more than a fixed percentage of the wallet into a single arb to limit downside on bad executions.

Active

Max Concurrent Arbs

Limit how many simultaneous arbitrage positions your agent holds. High concurrency magnifies both profit and loss — cap it at a level that keeps total exposure bounded.

Automated

Stop-Loss Triggers

Poll /v1/trading/positions for unrealized PnL. If any position hits your stop-loss threshold, close it immediately via /v1/trading/order with reduce_only: true.

risk_monitor.py
import requests, os API_KEY = os.environ["PURPLEFLEA_API_KEY"] BASE = "https://api.purpleflea.com/v1" H = {"X-API-Key": API_KEY, "Content-Type": "application/json"} MAX_POSITIONS = 5 # Never hold more than 5 open arb positions STOP_LOSS_PCT = -0.015 # Close position if PnL < -1.5% MAX_CAPITAL_PER_ARB = 500 # Maximum USDC per arb cycle def monitor_and_hedge(): positions = requests.get(f"{BASE}/trading/positions", headers=H).json() # Enforce max concurrent positions if len(positions) >= MAX_POSITIONS: print(f"Position cap reached ({len(positions)}). Skipping new arbs.") return False # Check each position for stop-loss breach for pos in positions: pnl_pct = float(pos["unrealized_pnl_pct"]) if pnl_pct < STOP_LOSS_PCT: print(f"Stop-loss triggered on {pos['symbol']}: {pnl_pct*100:.2f}%") requests.post(f"{BASE}/trading/order", json={ "symbol": pos["symbol"], "side": "buy" if pos["side"] == "short" else "sell", "size": pos["size"], "reduce_only": True, "order_type": "market", }, headers=H) return True # OK to proceed with new arbs

Backtest with Historical Funding Data

Before running a funding rate strategy live, validate it against historical data. Purple Flea's /v1/funding-history/{symbol} endpoint returns per-epoch (8-hour) funding rates for any Hyperliquid perpetual market, going back to the market's inception.

Pull the full rate history, filter for periods where funding was consistently positive and above your minimum threshold, and simulate the PnL of a long-spot short-perp delta-neutral position through those periods. Subtract estimated slippage (0.05% per entry/exit) and borrow costs to get realistic net returns.

Markets to examine first: ETH, BTC, SOL, and DOGE have the longest histories and most stable patterns. Smaller-cap perps occasionally show extreme funding spikes (5%+ per 8 hours) but carry higher liquidation risk from volatility.

backtest_funding.py
import requests, os import pandas as pd API_KEY = os.environ["PURPLEFLEA_API_KEY"] BASE = "https://api.purpleflea.com/v1" H = {"X-API-Key": API_KEY} def backtest_funding_arb(symbol: str, min_rate: float = 0.01): """ Backtest delta-neutral funding rate strategy. Enter when funding > min_rate, exit when funding drops below. """ # Fetch full funding history r = requests.get(f"{BASE}/funding-history/{symbol}", headers=H) history = r.json()["epochs"] # List of {timestamp, rate} dicts df = pd.DataFrame(history) df["rate"] = df["rate"].astype(float) df["in_trade"] = df["rate"] > min_rate # Calculate gross PnL: earn funding when in trade (short perp) df["gross_pnl"] = df["rate"].where(df["in_trade"], 0) # Subtract round-trip slippage on entry/exit (0.1% total) transitions = df["in_trade"].diff().abs().sum() slippage = transitions * 0.001 net_pnl = df["gross_pnl"].sum() - slippage epochs_in_trade = df["in_trade"].sum() print(f"Symbol: {symbol}") print(f"Epochs in trade: {epochs_in_trade} of {len(df)}") print(f"Gross funding earned: {df['gross_pnl'].sum()*100:.2f}%") print(f"Slippage cost: {slippage*100:.2f}%") print(f"Net PnL: {net_pnl*100:.2f}%") return net_pnl backtest_funding_arb("BTC", min_rate=0.005) backtest_funding_arb("ETH", min_rate=0.005)

Earn 20% of Other Agents' Trading Fees

When your agent registers other arbitrage bots through its referral link, it earns 20% of all trading fees those agents generate — forever. An active arbitrage bot can execute hundreds of trades per day. If you refer ten such agents, you are earning a significant passive revenue stream with zero additional work from your agent.

Referral earnings are accrued in USDC and paid on-chain to your agent's wallet. Use /v1/referral/earnings to check the current balance and /v1/referral/withdraw to sweep earnings into your trading wallet. Your agent can then redeploy those earnings as additional capital in arbitrage strategies — a fully compounding autonomous flywheel.

referral_earnings.py
import requests, os API_KEY = os.environ["PURPLEFLEA_API_KEY"] BASE = "https://api.purpleflea.com/v1" H = {"X-API-Key": API_KEY, "Content-Type": "application/json"} # Get your referral link to share with other agents ref = requests.get(f"{BASE}/referral/link", headers=H).json() print(f"Referral URL: {ref['url']}") # Check referral program stats earnings = requests.get(f"{BASE}/referral/earnings", headers=H).json() print(f"Referred agents: {earnings['referred_agents']}") print(f"Pending USDC: {earnings['pending_usdc']}") print(f"Total earned: {earnings['total_earned_usdc']} USDC") print(f"30-day volume (referred): ${earnings['referred_volume_30d']:,}") # Auto-withdraw and redeploy as trading capital pending = float(earnings["pending_usdc"]) if pending >= 10.0: requests.post(f"{BASE}/referral/withdraw", json={ "asset": "USDC", "chain": "arbitrum", # Withdraw to Arbitrum for trading }, headers=H) print(f"Swept ${pending:.2f} USDC into trading wallet")

Explore more APIs.

Your agent, exploiting
every market inefficiency.

275+ markets. Sub-50ms latency. Full arbitrage toolkit. Free to start — no KYC.