Market-Specific Crypto, DeFi

MEV & Arbitrage

Paste into Claude, ChatGPT, or any coding agent

This skill covers arbitrage identification and execution across centralized and decentralized exchanges, as well as awareness of the MEV (Maximal Extractable Value) landscape on blockchains. It teaches how to find and evaluate price discrepancies, funding rate mismatches, and cyclic swap opportunities — and critically, how to assess whether an apparent opportunity is actually profitable after accounting for all costs and risks.

IMPORTANT DISCLAIMER: Most retail arbitrage attempts lose money. Professional arbitrageurs operate with co-located infrastructure, proprietary algorithms, and millisecond latency advantages. The opportunities visible to retail participants are typically either (a) already captured by faster actors, (b) illusions created by fees and slippage, or (c) traps (e.g., honeypot tokens). This skill focuses on realistic strategies with honest profitability assessment, not get-rich-quick arb fantasies.

ETHICS NOTE: Some MEV extraction methods (sandwich attacks, frontrunning) are adversarial — they profit by harming other users. This skill covers these topics for awareness and defense only, NOT as recommended strategies. Understanding these attacks helps you protect your own transactions.

When to Use This Skill

  • When evaluating a potential price difference between exchanges
  • When analyzing funding rate differentials for basis trading
  • When exploring DEX arbitrage or cyclic swap opportunities
  • When assessing whether an arbitrage opportunity is real or illusory
  • When understanding MEV risks to your own transactions
  • When designing infrastructure for arbitrage execution
  • When evaluating the profitability of an arb strategy after all costs

What This Skill Does

  1. Cross-Exchange Arb Analysis: Evaluates CEX-CEX, DEX-DEX, and CEX-DEX price differences
  2. Funding Rate Arbitrage: Designs cash-and-carry and reverse cash-and-carry strategies
  3. DEX Cyclic Arbitrage: Identifies triangular and multi-hop swap opportunities
  4. MEV Landscape Awareness: Explains frontrunning, backrunning, sandwich attacks, and JIT liquidity
  5. Profitability Analysis: Calculates true profit after fees, gas, slippage, capital costs, and infrastructure
  6. Risk Assessment: Evaluates execution risk, inventory risk, smart contract risk, and gas spike risk
  7. Infrastructure Requirements: Details what you need to compete in different arb categories
  8. Reality Check: Honestly assesses whether an opportunity is viable for a given participant

How to Use

Cross-Exchange Arbitrage

Is there an arb opportunity between Binance and KuCoin for ETH?
Compare BTC prices across major CEXs -- any tradeable spread?

Funding Rate Arbitrage

Analyze BTC funding rate for a basis trade opportunity
What pairs have the highest funding rate differential right now?

DEX Arbitrage

Find cyclic arb paths for ETH/USDC across Uniswap, SushiSwap, and Curve

MEV Protection

How do I protect my large swap from sandwich attacks?

Data Sources

With MCP/CLI tools connected:

  • Binance MCP / Bybit MCP / OKX MCP — Real-time prices, order books, funding rates, futures data
  • DexScreener — DEX pair prices, volume, and liquidity across chains
  • Jupiter Talk MCP — Solana DEX aggregation, routing, and price quotes
  • Uniswap MCP (yurenju) — Ethereum DEX pool data, tick liquidity, swap simulation
  • CoinGecko MCP — Cross-exchange price comparison, historical funding rates
  • DeFiLlama — DEX TVL, volume comparisons, bridge data
  • Flashbots Protect (via web) — MEV protection for Ethereum transactions

Without tool access: Ask the user to provide:

  1. Exchanges they have accounts on (with fee tier information)
  2. Current prices for the asset on each exchange
  3. Order book depth (at least top 5 levels) on each exchange
  4. Funding rates for perpetual contracts (if applicable)
  5. DEX pool addresses and liquidity data (if applicable)
  6. Gas price on the relevant blockchain
  7. Available capital and current positions

Methodology

Step 1: Classify the Arbitrage Type

ARBITRAGE CLASSIFICATION

Type 1: CROSS-EXCHANGE (CEX-CEX)
  Buy on exchange A, sell on exchange B
  Requirements: Accounts on both, capital pre-positioned, fast execution
  Typical spread: 0.01% - 0.5% (large-cap), 0.5% - 5% (small-cap)
  Main costs: Trading fees (2x), withdrawal fees, transfer time

Type 2: CROSS-VENUE (CEX-DEX)
  Buy on DEX, sell on CEX (or vice versa)
  Requirements: CEX account + on-chain wallet, bridging capability
  Typical spread: 0.1% - 2% (major pairs)
  Main costs: Gas, trading fees, bridge fees, transfer time

Type 3: DEX-DEX (SAME CHAIN)
  Swap on DEX A, reverse swap on DEX B
  Requirements: Wallet, gas, can use flash loans for capital-free arb
  Typical spread: 0.05% - 1% (standard pairs)
  Main costs: Gas (single transaction possible with flash loans)

Type 4: CYCLIC / TRIANGULAR
  A → B → C → A through 3+ pools/pairs
  Requirements: Path calculation, simulation, gas optimization
  Typical spread: 0.01% - 0.5% (highly competitive)
  Main costs: Gas, complex execution risk

Type 5: FUNDING RATE / BASIS
  Long spot + short perp (when funding positive) or vice versa
  Requirements: Spot and futures accounts, margin
  Typical yield: 5% - 30% annualized
  Main costs: Capital lockup, margin requirements, liquidation risk

Type 6: STATISTICAL / CONVERGENCE
  Correlated assets temporarily diverge, bet on convergence
  Requirements: Historical correlation data, patience
  Typical yield: Variable, can hold for days/weeks
  Main costs: Capital lockup, divergence risk (may not converge)

Step 2: Cross-Exchange Arbitrage

The simplest form of arbitrage — buying on one exchange and selling on another.

Spot-Spot CEX Arbitrage

PROFITABILITY CALCULATION

Gross spread = (Price_B - Price_A) / Price_A × 100%

Net profit = Gross spread - costs

Costs:
  Trading fees (buy):     fee_A × trade_size
  Trading fees (sell):    fee_B × trade_size
  Slippage (buy):         estimate from order book depth
  Slippage (sell):        estimate from order book depth
  Transfer fee:           withdrawal fee from exchange A
  Transfer time risk:     price change during transfer (biggest risk!)
  Capital cost:           opportunity cost of capital on both exchanges

Example: BTC on Binance ($67,000) vs. KuCoin ($67,150)

  Gross spread: ($67,150 - $67,000) / $67,000 = 0.224%

  Costs:
    Binance maker fee: 0.10%
    KuCoin taker fee:  0.10%
    Slippage (est):    0.02% each side
    BTC withdrawal:    0.0002 BTC ($13.40)
    Transfer time:     ~20 minutes (price risk!)

  Net on $10,000 trade:
    Gross: $22.40
    Fees:  $10 + $10 = $20
    Slip:  $2 + $2 = $4
    Withdrawal: $13.40
    Net:   $22.40 - $20 - $4 - $13.40 = -$15 (LOSS!)

  THIS ARB IS NOT PROFITABLE at this size.
  Need: $50K+ trade OR wider spread OR pre-positioned capital on both exchanges.

Pre-Positioned Capital Model

The viable CEX-CEX model uses pre-positioned capital:

Setup: Hold $50K USDT on Exchange A, $50K USDT on Exchange B

When spread appears:
  1. Buy on cheap exchange (use existing USDT)
  2. Sell on expensive exchange (use existing asset or short)
  3. NO TRANSFER NEEDED (eliminate transfer time risk)
  4. Rebalance between exchanges periodically when capital becomes imbalanced

Rebalancing cost: One-time transfer fee per rebalancing cycle
Capital requirement: 2x trade size (split across exchanges)
Capital efficiency: Low (half your capital is idle at any time)

Net profit per trade = Gross spread - (2 × trading fees) - (2 × slippage)
No withdrawal fee per trade (only during periodic rebalancing)

Step 3: Funding Rate Arbitrage (Basis Trade)

This is the most accessible arb strategy for retail. It captures the funding rate differential between spot and perpetual futures.

FUNDING RATE MECHANICS

Perpetual futures use funding rates to stay close to spot price:
  - When funding is POSITIVE: longs pay shorts (market is bullish)
  - When funding is NEGATIVE: shorts pay longs (market is bearish)
  - Funding is paid every 8 hours on most exchanges

BASIS TRADE (Cash-and-Carry):
  When funding is positive:
    Long spot (buy BTC)
    Short perp (sell BTC-PERP)
    Net market exposure: ZERO (delta neutral)
    Income: Funding rate × position size × 3 per day

  When funding is negative:
    Short spot (sell BTC or borrow and sell)
    Long perp (buy BTC-PERP)
    Income: |Funding rate| × position size × 3 per day

PROFITABILITY ANALYSIS:

  Annualized yield = Average funding rate × 3 × 365

  Example:
    BTC funding rate: 0.01% per 8 hours (average over 30 days)
    Annualized: 0.01% × 3 × 365 = 10.95%
    On $50,000 position: ~$5,475/year

  Costs to deduct:
    Trading fees to enter (spot + perp):     ~0.10% = $50
    Trading fees to exit:                     ~0.10% = $50
    Margin requirement (perp):                20-50% of position
    Basis risk (spot-perp price divergence):  variable
    Liquidation risk (if leveraged perp):     must maintain margin

  VIABLE THRESHOLDS:
    Annualized yield > 15% → Attractive
    Annualized yield 8-15% → Moderate (consider capital efficiency)
    Annualized yield < 8%  → Not worth the complexity and risk

FUNDING RATE SIGNALS:
  Funding consistently > 0.03% / 8h → Market overleveraged long (crowded trade)
  Funding consistently < -0.01% / 8h → Market overleveraged short (contrarian signal)
  Funding volatile (swinging ±0.05%) → Avoid basis trade (high basis risk)

Step 4: DEX Arbitrage

On-chain arbitrage between decentralized exchanges.

Simple Two-Pool Arbitrage

SCENARIO: ETH/USDC price differs between Uniswap and SushiSwap

Uniswap pool: 1 ETH = $3,500 USDC
SushiSwap pool: 1 ETH = $3,520 USDC
Spread: $20 (0.57%)

Execution:
  1. Swap USDC → ETH on Uniswap (cheaper)
  2. Swap ETH → USDC on SushiSwap (more expensive)

Profit calculation (on $10,000):
  Step 1: $10,000 → 2.857 ETH (Uniswap, 0.30% fee = $30)
  Step 2: 2.857 ETH → $10,056 USDC (SushiSwap, 0.30% fee = $30)
  Gross: $56
  Fees: $60
  Gas: ~$15 (Ethereum mainnet, 2 swaps)
  Net: $56 - $60 - $15 = -$19 (LOSS!)

  To profit: Need spread > 0.75% (2 × 0.30% fee + gas)
  OR: Use flash loan to do both swaps in single transaction

Flash Loan Arbitrage

Flash loans allow capital-free arbitrage within a single transaction:

Flow:
  1. Borrow $X from Aave/dYdX flash loan (0% interest, same-tx repayment)
  2. Buy asset on cheap DEX
  3. Sell asset on expensive DEX
  4. Repay flash loan + fee
  5. Keep profit

Flash loan fees:
  Aave: 0.05% (v3), 0.09% (v2)
  dYdX: 0 (but uses their specific system)
  Uniswap v3: 0.01-1% (depends on pool)

Advantage: No capital required
Disadvantage: Entire arb must execute in single transaction
Risk: Transaction reverts if profit < costs (only gas is lost)

REALITY CHECK:
  Flash loan arb is EXTREMELY competitive.
  Professional bots monitor the mempool and backrun profitable paths.
  By the time you see an opportunity, it's likely already captured.
  Building competitive flash loan bots requires:
    - Custom smart contracts
    - Mempool monitoring infrastructure
    - Sub-second execution
    - MEV-aware transaction submission (Flashbots)

Triangular / Cyclic Arbitrage

TRIANGULAR ARB: A → B → C → A

Example: USDC → ETH → LINK → USDC
  Pool 1: USDC → ETH (Uniswap, 0.30% fee)
  Pool 2: ETH → LINK (Uniswap, 0.30% fee)
  Pool 3: LINK → USDC (SushiSwap, 0.30% fee)

  If: Amount_out > Amount_in + (3 × swap fees) + gas → PROFITABLE

Detection algorithm:
  1. Build graph of all DEX pools (nodes = tokens, edges = pools)
  2. For each cycle of length 3-5:
     Simulate swap amounts through each pool
     Calculate net output vs. input
  3. If output > input + costs → execute

Costs:
  3+ swap fees (0.30% × 3 = 0.90% minimum)
  Gas for multi-hop swap (~$20-50 on Ethereum, ~$0.50 on L2)
  Price impact on each pool (dependent on liquidity and trade size)

REALISTIC ASSESSMENT:
  Triangular arb profits are typically 0.01-0.1% per cycle.
  At $10,000 per cycle: $1-10 profit.
  At $100,000 per cycle: $10-100 profit.
  Frequency: Opportunities appear and disappear in seconds.
  You are competing against specialized bots running 24/7.

Step 5: MEV Landscape (Awareness Section)

MEV (Maximal Extractable Value) refers to value that block producers or searchers can extract by reordering, inserting, or censoring transactions.

MEV TYPES (for awareness and defense)

FRONTRUNNING
  What: Observing a pending large buy, placing a buy before it, selling after
  Impact: Victim gets worse price
  Defense: Use private mempools (Flashbots Protect), set tight slippage

BACKRUNNING
  What: Placing a transaction immediately after a price-moving event
  Impact: Captures the arb created by the event (less adversarial)
  Example: Backrunning an oracle update to arb DEX vs. new price
  This is the most "legitimate" MEV strategy

SANDWICH ATTACK
  What: Frontrun AND backrun a victim's swap
  Impact: Victim pays inflated price, attacker profits the difference
  Defense: Use MEV-protected RPCs, lower slippage tolerance, split large swaps

  WARNING: Sandwich attacks extract value from other users.
  This skill does NOT recommend implementing sandwich attacks.

JIT (Just-In-Time) LIQUIDITY
  What: Adding concentrated liquidity just before a large swap, removing after
  Impact: Captures fees from the swap without persistent LP exposure
  Defense: No direct harm to swappers, but reduces fees for existing LPs

LIQUIDATION MEV
  What: Monitoring lending protocols for undercollateralized positions, liquidating them
  Impact: Necessary for protocol health, but competitive
  Profitability: Liquidation bonus (5-15%) minus gas cost

Step 6: Infrastructure Requirements

Different arb strategies require different infrastructure levels:

INFRASTRUCTURE TIERS

TIER 1: Manual / Semi-Automated (Retail Accessible)
  Strategy: Funding rate arb, slow CEX-CEX spot arb
  Requirements:
    - CEX accounts with API access
    - Basic scripting (Python) for monitoring
    - Alert system for opportunities
    - Manual execution (minutes-level latency OK)
  Capital: $10K+
  Expected: 5-15% annualized (funding rate arb)

TIER 2: Automated Bot (Semi-Professional)
  Strategy: CEX-CEX pre-positioned, simple DEX arb
  Requirements:
    - Hummingbot or custom trading bot
    - VPS near exchange servers
    - Dedicated RPC node access
    - Automated execution (seconds-level latency)
  Capital: $50K+
  Expected: 10-30% annualized (if competitive edge exists)

TIER 3: Low-Latency MEV (Professional)
  Strategy: DEX cyclic arb, backrunning, liquidations
  Requirements:
    - Custom smart contracts (Solidity/Rust)
    - Private mempool access (Flashbots, Jito)
    - Co-located nodes (same datacenter as validators)
    - Transaction simulation infrastructure
    - Sub-100ms execution
  Capital: $100K+ (plus $5-20K/month infrastructure)
  Expected: Variable, highly competitive

TIER 4: HFT / Market Making (Institutional)
  Strategy: All of above + cross-venue, stat arb
  Requirements:
    - Co-location at exchange datacenters
    - Custom FPGA/networking hardware
    - Team of engineers
    - Exchange market maker agreements
  Capital: $1M+
  This tier is NOT realistic for retail participants.

Step 7: Profitability Analysis Framework

For every arb opportunity, run this honest assessment:

ARB PROFITABILITY CHECKLIST

1. GROSS SPREAD
   Observed price difference: ____%
   On position size $____: $____ gross

2. EXPLICIT COSTS
   Trading fees (all legs): $____
   Gas costs (all transactions): $____
   Withdrawal/bridge fees: $____
   Flash loan fee (if applicable): $____
   Slippage estimate (per leg): $____
   Total explicit costs: $____

3. IMPLICIT COSTS
   Capital cost (opportunity cost of locked capital): $____/day
   Transfer time risk (price can move during transfer): $____
   Infrastructure cost (amortized VPS, RPC, etc.): $____/trade
   Total implicit costs: $____

4. TOTAL COST: $____ (explicit + implicit)

5. NET PROFIT: $____ (gross - total cost)

6. RISK-ADJUSTED RETURN
   Probability of successful execution: ____%
   Worst case loss (if execution fails): $____
   Expected value = (prob × net_profit) - ((1-prob) × worst_case)
   Expected value: $____

7. ANNUALIZED RETURN (for recurring strategies)
   Trades per day × Net profit per trade × 365
   Annualized return on capital: ____%

DECISION THRESHOLDS:
  Expected value positive with >90% confidence → PROCEED
  Expected value positive with 70-90% confidence → PROCEED WITH CAUTION
  Expected value positive with <70% confidence → DO NOT PROCEED
  Expected value negative → DEFINITELY DO NOT PROCEED

REALITY CHECK QUESTIONS:
  □ Why does this opportunity exist? (If no good answer → it's a trap)
  □ Who is on the other side? (If institutions → you probably don't have edge)
  □ How long has this spread persisted? (If >5 min → something is wrong)
  □ Can you execute before the spread closes? (If not → not your arb)

Step 8: Risk Management for Arbitrage

ARBITRAGE-SPECIFIC RISKS

1. EXECUTION RISK (highest priority)
   One leg executes, other fails → left with directional position
   Mitigation: Atomic execution (flash loans), tight timeouts, pre-positioned capital
   Sizing: Never commit >10% of capital to a single arb cycle

2. INVENTORY RISK
   Capital stuck on wrong exchange after arb
   Mitigation: Rebalancing schedule, multiple exchange accounts
   Track: Net inventory imbalance across all venues

3. SMART CONTRACT RISK (DEX arb)
   Pool exploit, token contract rug, oracle manipulation
   Mitigation: Only arb well-known tokens on audited DEXs
   Never: Arb unknown tokens (honeypot risk is extreme)

4. GAS SPIKE RISK (on-chain arb)
   Gas price surges between transaction submission and inclusion
   Mitigation: Set max gas price, use priority fee estimation
   Budget: Always assume 2x current gas price

5. COUNTERPARTY RISK (CEX arb)
   Exchange freezes withdrawals, halts trading, or becomes insolvent
   Mitigation: Limit capital per exchange, use reputable exchanges
   Max per exchange: 25% of total arb capital

6. MARKET REGIME RISK
   Arb strategies perform differently in different regimes
   High volatility: More opportunities but more execution risk
   Low volatility: Fewer opportunities, tighter spreads
   Flash crashes: Extreme opportunity but extreme risk

HARD LIMITS (pass to risk-management):
  Max capital per arb cycle: 10% of total portfolio
  Max capital per exchange: 25% of arb allocation
  Max daily loss from arb: 2% of arb allocation
  Stop trading if: 3 consecutive failed executions

Anti-Patterns

DO NOT do these — they are the most common arbitrage mistakes:

  1. Ignoring fees in spread calculation: A 0.5% spread between exchanges means nothing if your round-trip fees are 0.6%. Always calculate NET profit, never gross.

  2. Arbing honeypot tokens: Unknown tokens with massive DEX price discrepancies are almost always scams. The token’s sell function may be disabled, or there is a transfer tax that makes selling impossible. Only arb well-known, verified tokens.

  3. Ignoring transfer time: CEX-CEX arb with 20-minute blockchain confirmation means 20 minutes of unhedged directional exposure. In crypto, a 5% move in 20 minutes is not uncommon.

  4. Assuming flash loan arb is free money: Flash loan arb has zero capital risk but still costs gas. More importantly, professional searchers with sub-second infrastructure capture nearly all flash loan arb opportunities before you can.

  5. Overleveraging funding rate arb: Funding rate arb is delta-neutral in theory but the perp side has liquidation risk. If you use high leverage on the perp, a price spike can liquidate you before funding pays out.

  6. Treating backtest profitability as live profitability: Historical arb opportunities are visible in hindsight. In real-time, execution latency, slippage, and competition reduce actual capture rate dramatically. Assume 20-40% capture rate vs. backtest.

  7. Ignoring MEV on your own transactions: When you submit a large DEX swap, you are the one being arbitraged. Always use MEV protection (Flashbots Protect, private RPCs, slippage limits).

  8. Building sandwich bots: Sandwich attacks extract value from other users and are increasingly detected and penalized. Some chains and protocols are implementing protections that make sandwiching unprofitable or traceable. This is adversarial and not recommended.

Validation Checkpoints

Input Validation

  • Arb type classified (cross-exchange, funding rate, DEX, cyclic)
  • Prices verified on all relevant venues (not stale data)
  • Order book depth checked (sufficient liquidity for intended size)
  • Fee structure confirmed for all exchanges/protocols involved
  • Gas price current and realistic (not using stale gas estimates)
  • Capital allocation defined and within risk limits
  • Transfer times and routes identified (for cross-exchange)

Output Validation

  • Net profit calculated after ALL costs (explicit and implicit)
  • Slippage estimated from order book depth, not assumed to be zero
  • Execution risk assessed (what happens if one leg fails?)
  • Risk/reward ratio acceptable (expected value clearly positive)
  • Infrastructure requirements honest (do you actually have the speed needed?)
  • Reality check passed (why does this opportunity exist? who else sees it?)
  • Risk management limits applied (max size, max loss, exchange limits)
  • Risk validation gate from Risk Management passed

Example

User: “BTC funding rate on Binance is 0.05% per 8 hours. Should I do a basis trade?”

Analysis:

## Arbitrage Analysis: BTC Funding Rate Basis Trade

### Opportunity Assessment
- Current BTC funding rate: 0.05% per 8 hours (Binance)
- 30-day average funding rate: 0.03% per 8 hours
- Annualized yield (current): 0.05% × 3 × 365 = 54.75%
- Annualized yield (30d avg): 0.03% × 3 × 365 = 32.85%

### Strategy Design
- Long: Buy 0.5 BTC spot at $67,000 = $33,500
- Short: Sell 0.5 BTC perpetual at $67,100 = $33,550
- Net exposure: ~0 BTC (delta neutral)
- Funding income: 0.05% × $33,550 × 3 = $50.33/day (at current rate)

### Cost Analysis
- Entry fees (spot buy + perp sell): 0.10% × 2 × $33,500 = $67
- Exit fees (spot sell + perp buy): 0.10% × 2 × $33,500 = $67
- Total entry/exit cost: $134
- Breakeven: $134 / $50.33 = 2.7 days

### Risk Assessment
- Liquidation risk (perp short at 5x): BTC would need to reach ~$80,400
  Distance from current: +20% (>2x ATR -- acceptable)
- Funding rate reversal risk: If funding goes negative, you PAY
  Historical: BTC funding negative ~15% of days in past year
- Basis risk: Spot-perp basis can widen, creating temporary unrealized loss
- Capital efficiency: $33,500 spot + $6,700 margin = $40,200 total capital
  Yield on total capital (at current rate): 54.75% × ($33,550/$40,200) = 45.7%

### Profitability Scenarios

| Scenario | Avg Funding | Daily Income | Monthly | Annualized |
|----------|-------------|-------------|---------|------------|
| Bull case | 0.05%/8h | $50 | $1,510 | 45.7% |
| Base case | 0.03%/8h | $30 | $906 | 27.4% |
| Bear case | 0.01%/8h | $10 | $302 | 9.1% |
| Worst case | -0.01%/8h | -$10 | -$302 | -9.1% |

### Verdict: PROCEED WITH CAUTION
- Current funding is elevated (0.05% > 30d avg of 0.03%)
- This suggests the market is overleveraged long -- funding may normalize
- Base case yield (27.4%) is attractive for delta-neutral strategy
- Set exit trigger: close trade if 7-day average funding drops below 0.01%

### Risk Management
- Max capital: 20% of portfolio in basis trade
- Perp leverage: Max 5x (maintain >50% buffer to liquidation)
- Monitor: Funding rate daily, close if consistently negative for 3+ days
- Hedge: None needed (strategy is inherently delta-neutral)

### Recommendation
Enter at current levels with plan to hold for 2-4 weeks.
Expected net income: $600-1,200 (base case, 1 month)
Entry cost: $134 (recovered in ~3 days)

--> Pass to risk-management for portfolio allocation check
--> Use order-execution for simultaneous spot buy + perp sell