DeFi

DeFi Arbitrage: CEX vs DEX Strategies Explained (2025)

DeFi has opened entirely new arbitrage opportunities that didn't exist before. Learn the key differences between CEX and DEX arbitrage, the risks, and which strategies bots can exploit automatically.

A
AI Agents Hubยท2025-03-13ยท4 min readยท646 words

Builder of AI agents, crypto trading bots, and open-source automation tools. Sharing practical guides on how to build, deploy, and profit from AI and DeFi technology.

CEX vs DEX: The Core Difference

Centralized Exchanges (CEX) โ€” Binance, Coinbase, Kraken. Traditional order books, fast execution, custody risk.

Decentralized Exchanges (DEX) โ€” Uniswap, Curve, dYdX. On-chain, permissionless, self-custody, but slower and with gas costs.

Both create arbitrage opportunities, but the mechanics โ€” and the bots you need โ€” are completely different.

CEX Arbitrage

How It Works

Monitor the same trading pair across multiple CEXs. When the price diverges, buy on the cheaper exchange and sell on the more expensive one.

Pros

  • Fast execution (milliseconds)
  • No gas fees
  • Familiar order book mechanics

Cons

  • Requires capital locked on multiple exchanges
  • Withdrawal limits can trap profits
  • Highly competitive โ€” major firms run co-located servers

Sample Bot Logic

import ccxt
import asyncio

async def cex_arb_monitor():
    binance = ccxt.binance({'apiKey': '...', 'secret': '...'})
    kraken = ccxt.kraken({'apiKey': '...', 'secret': '...'})
    
    while True:
        # Fetch simultaneously
        tasks = [
            asyncio.create_task(fetch_price(binance, 'ETH/USDT')),
            asyncio.create_task(fetch_price(kraken, 'ETH/USDT'))
        ]
        prices = await asyncio.gather(*tasks)
        
        spread = abs(prices[0] - prices[1]) / min(prices[0], prices[1]) * 100
        
        if spread > 0.3:  # 0.3% minimum spread
            print(f"Arbitrage opportunity: {spread:.2f}% spread")
            # Execute trades
        
        await asyncio.sleep(0.5)

async def fetch_price(exchange, symbol):
    ticker = await exchange.fetch_ticker(symbol)
    return ticker['last']

DEX Arbitrage

How It Works

DEXs use Automated Market Makers (AMMs). Price is determined by a formula (x * y = k for Uniswap V2). When large trades move the pool price, it creates temporary discrepancies vs. other pools.

Pros

  • No custody risk (self-custodial)
  • Flash loans enable capital-free arbitrage
  • More opportunities due to market inefficiency

Cons

  • Gas fees can eliminate profit
  • MEV bots (sandwich attacks) compete aggressively
  • Transaction may fail if price moves before confirmation

The Uniswap V2 Arbitrage Flow

const { ethers } = require('ethers')

const ROUTER_ABI = ['function getAmountsOut(uint, address[]) returns (uint[])']
const router = new ethers.Contract(UNISWAP_ROUTER, ROUTER_ABI, provider)

async function checkArbitrage(tokenIn, tokenOut, amount) {
  // Route 1: tokenIn -> WETH -> tokenOut
  const route1 = await router.getAmountsOut(amount, [tokenIn, WETH, tokenOut])
  
  // Route 2: tokenIn -> USDC -> tokenOut  
  const route2 = await router.getAmountsOut(amount, [tokenIn, USDC, tokenOut])
  
  const profit1 = route1[route1.length - 1]
  const profit2 = route2[route2.length - 1]
  
  if (profit1 > profit2 && profit1 > amount) {
    console.log(`Profitable route 1: ${ethers.formatEther(profit1 - amount)} ETH profit`)
    return { route: route1, profit: profit1 - amount }
  }
  
  return null
}

Flash Loan Arbitrage

Flash loans are the holy grail of DeFi arbitrage: borrow millions with zero collateral, execute your arbitrage, repay the loan โ€” all in one transaction.

// FlashArb.sol (simplified)
contract FlashArb is IFlashLoanReceiver {
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external returns (bool) {
        // 1. Received flash loan
        // 2. Execute arbitrage (buy on DEX A, sell on DEX B)
        // 3. Repay loan + premium
        
        uint256 repayAmount = amount + premium;
        IERC20(asset).approve(address(POOL), repayAmount);
        return true;
    }
}

The beauty: if there's no profit, the transaction reverts and you lose only gas. No principal at risk.

MEV: The Dark Side of DEX Arbitrage

Maximal Extractable Value (MEV) bots constantly scan the mempool for profitable transactions and either:

  • Front-run them (execute just before)
  • Sandwich them (buy before + sell after)

To avoid MEV attacks on your own trades, use Flashbots or private RPC endpoints.

Which Strategy Is Right for You?

| Strategy | Capital Required | Technical Level | Competition | Expected Return | |----------|-----------------|-----------------|-------------|-----------------| | CEX-CEX | $1,000+ | Low | Very High | 1โ€“5%/month | | DEX-DEX | $500+ | Medium | High | 2โ€“8%/month | | Flash Loans | ~0 (+ gas) | Very High | Extreme | Variable |

Get the Code

All our arbitrage bot code is available on the Tools page. The DEX bot includes Uniswap V2/V3 support, gas optimization, and MEV protection.

Related Articles