MEV
Trading Bots
14 min read
MEV Bot Strategy for AI Agents: Sandwich, Arbitrage, and Liquidation
Maximal Extractable Value (MEV) is the profit a block producer — or a sophisticated bot — can capture by reordering, inserting, or censoring transactions within a block. For AI agents with fast execution capabilities and access to on-chain data, MEV represents a systematic alpha source. This guide covers the four main MEV strategies, their profitability mechanics, and how to implement them.
What Is MEV and Why Should Agents Care?
MEV was originally called "miner extractable value" but is now called "maximal extractable value" since the Ethereum Merge. It refers to value extracted by including, excluding, or reordering transactions in a block beyond standard block rewards.
The MEV opportunity is enormous — over $1.4 billion was extracted on Ethereum in 2023 alone, according to Flashbots data. Most of this was captured by specialized bots: automated programs that scan the mempool for profitable opportunities and submit transactions with precise gas pricing to capture value before or after target transactions.
AI agents are uniquely positioned for MEV because:
- Speed: Agents can react to mempool events in milliseconds, faster than any human
- Reasoning: LLM-powered agents can evaluate complex multi-hop arbitrage routes in real time
- Autonomy: Agents run 24/7 without fatigue or distraction
- Composability: Agents can combine flash loans, swaps, and liquidations atomically via APIs like Purple Flea
MEV Strategy Overview
Low difficulty
DEX Arbitrage
Buy low on one DEX, sell high on another. Pure price discovery play with no user harm.
Medium difficulty
Liquidation
Liquidate undercollateralized loans on Aave/Compound before the position deteriorates further.
High difficulty
Sandwich Attack
Front-run large swaps to capture slippage. Ethically contentious — harms users directly.
High difficulty
JIT Liquidity
Provide concentrated liquidity just-in-time for a known large swap, earn fees, withdraw immediately.
Ethical Note: Sandwich attacks extract value directly from retail traders by worsening their execution price. DEX arbitrage and liquidations are generally considered "good MEV" — they improve price efficiency and reduce systemic risk. This guide focuses primarily on arbitrage and liquidation strategies. We document sandwich mechanics for educational understanding only.
Strategy 1: DEX Arbitrage
DEX arbitrage is the most common and least controversial MEV strategy. Price discrepancies between Uniswap, Curve, Balancer, and other DEXes create atomic profit opportunities. An agent that detects a 0.5% price gap on a $1M pool can execute a flash loan arbitrage for roughly $5,000 gross profit — minus fees and gas.
Anatomy of a DEX Arbitrage
- Monitor ETH/USDC price on Uniswap V3 vs Curve 3pool
- Detect >0.2% price difference (after accounting for swap fees)
- Flash borrow USDC (no collateral needed)
- Buy ETH on cheaper DEX
- Sell ETH on more expensive DEX
- Repay flash loan + 0.09% fee
- Keep the spread
# dex_arb_agent.py — real-time DEX price monitoring + flash arb
import asyncio, requests
from decimal import Decimal
PURPLE_FLEA = "https://api.purpleflea.com/v1"
HEADERS = {"X-API-Key": "pf_your_key"}
async def find_arb_opportunities():
# Query on-chain prices from multiple DEXes simultaneously
dex_prices = requests.get(
f"{PURPLE_FLEA}/market/dex-prices",
params={"pair": "ETH/USDC", "dexes": "uniswap_v3,curve,balancer,sushi"},
headers=HEADERS
).json()["prices"]
best_buy = min(dex_prices, key=lambda x: x["price"])
best_sell = max(dex_prices, key=lambda x: x["price"])
spread_pct = (best_sell["price"] - best_buy["price"]) / best_buy["price"]
if spread_pct > 0.002: # 0.2% minimum after fees
print(f"Arb opportunity: buy on {best_buy['dex']} at ${best_buy['price']:.2f}")
print(f"Sell on {best_sell['dex']} at ${best_sell['price']:.2f} ({spread_pct:.2%} spread)")
# Simulate first
sim = requests.post(f"{PURPLE_FLEA}/flash-loans/simulate", json={
"strategy": "dex_arbitrage",
"buy_dex": best_buy["dex"], "sell_dex": best_sell["dex"],
"loan_amount_usd": 100000
}, headers=HEADERS).json()
if sim["profitable"] and sim["net_profit_usd"] > 50:
# Execute — atomic, no-loss if reverts
result = requests.post(f"{PURPLE_FLEA}/flash-loans/execute", json={
"strategy": "dex_arbitrage",
"route": sim["optimal_route"]
}, headers=HEADERS).json()
print(f"Profit: ${result.get('actual_profit_usd', 0):.2f}")
asyncio.run(find_arb_opportunities())
Profitability Considerations
| Factor | Impact on Profitability |
| Gas cost | High — arb txs are complex, $30–$150 on Ethereum mainnet |
| Flash loan fee | 0.09% of loan amount (Purple Flea / Aave rates) |
| DEX fees | 0.05–0.3% per swap (Uniswap V3: 0.05% for major pairs) |
| Slippage | Reduces profit — simulate optimal loan size for each opportunity |
| Competition | Hundreds of bots scan the same opportunities — speed is critical |
| Layer 2 advantage | Arbitrum/Polygon: 10–100x lower gas, more viable at smaller sizes |
Strategy 2: Liquidation Bots
Lending protocols like Aave, Compound, and Euler maintain collateral ratios. When a borrower's collateral falls below the liquidation threshold (due to price drops), their loan becomes undercollateralized. Liquidation bots repay the debt and seize a portion of the collateral at a discount — the "liquidation bonus" (typically 5–15%).
This is considered "good MEV" because it prevents bad debt from accumulating in the protocol and protects depositors. AI agents make excellent liquidation bots because they can monitor positions across multiple protocols simultaneously and execute faster than manual liquidators.
# liquidation_agent.py — monitor and execute DeFi liquidations
import requests, time
PURPLE_FLEA = "https://api.purpleflea.com/v1"
HEADERS = {"X-API-Key": "pf_your_key"}
class LiquidationAgent:
PROTOCOLS = ["aave_v3", "compound_v3", "euler"]
def scan_liquidatable_positions(self) -> list:
# Purple Flea aggregates health factors across protocols
r = requests.get(
f"{PURPLE_FLEA}/defi/liquidatable-positions",
params={"protocols": ",".join(self.PROTOCOLS), "max_health_factor": 1.0},
headers=HEADERS
)
r.raise_for_status()
return sorted(r.json()["positions"], key=lambda x: -x["liquidation_profit_usd"])
def execute_liquidation(self, position: dict, wallet_id: str):
# Use flash loan to fund liquidation if needed
payload = {
"wallet_id": wallet_id,
"strategy": "liquidation",
"protocol": position["protocol"],
"borrower": position["borrower_address"],
"debt_asset": position["debt_asset"],
"collateral_asset": position["collateral_asset"],
"use_flash_loan": True # borrow repayment capital atomically
}
r = requests.post(f"{PURPLE_FLEA}/flash-loans/execute", json=payload, headers=HEADERS)
result = r.json()
print(f"Liquidated {position['borrower_address'][:8]}... profit: ${result.get('actual_profit_usd', 0):.2f}")
return result
def run(self, wallet_id: str):
while True:
positions = self.scan_liquidatable_positions()
if positions:
print(f"{len(positions)} liquidatable positions found")
best = positions[0] # take highest-profit first
if best["liquidation_profit_usd"] > 100:
self.execute_liquidation(best, wallet_id)
time.sleep(3)
LiquidationAgent().run("wallet_abc123")
Strategy 3: JIT Liquidity
Just-in-time (JIT) liquidity is a sophisticated MEV strategy specific to Uniswap V3 concentrated liquidity. When a bot detects a large pending swap in the mempool, it provides highly concentrated liquidity in the swap's exact price range just before the swap executes — earning a disproportionate share of the swap fees. After the swap, the bot withdraws its liquidity immediately.
JIT is technically complex but highly capital-efficient. The bot earns fees that would normally go to passive LPs who hold positions for days or weeks — by being present for only a single block.
JIT Liquidity Reality Check: JIT bots are running against the Flashbots MEV-Boost relay and require precise mempool monitoring. For most agent builders, DEX arbitrage and liquidation bots offer better risk-adjusted returns with lower infrastructure complexity. JIT is a strategy for specialized MEV teams with dedicated relay connections.
Competitive Landscape and What Agents Can Win
The MEV space is extremely competitive. The top MEV bots are built by specialized teams with:
- Dedicated full nodes for private mempool access
- Co-located servers running next to Ethereum validators
- Direct private order flow from DEX aggregators
- Custom Solidity contracts for gas optimization
That said, AI agents have competitive advantages in specific niches:
- Long-tail liquidations: Small positions ($500–$5,000) that top bots ignore due to high gas cost ratios are viable on Layer 2 where gas is cheap
- Cross-chain arbitrage: Price gaps between Ethereum and Arbitrum/Polygon that require reasoning about bridge mechanics — areas where LLM reasoning adds value
- Multi-protocol strategies: Complex liquidation routes that span multiple lending protocols require reasoning that pure rule-based bots lack
- Novel protocol opportunities: New DeFi protocols launching daily create opportunities before specialized bots are deployed
Building MEV Bots with Purple Flea
Purple Flea provides several APIs that MEV bots can leverage:
- Flash Loan API: Borrow uncollateralized capital for arbitrage and liquidation, 0.09% fee
- Trading API: Execute perpetual futures trades as part of hedging strategies
- Wallet API: Manage MEV proceeds across 6 chains, convert profits to stable assets
- Faucet: Bootstrap new agent wallets with seed capital for gas fees
The MCP interface allows LLM-powered agents to reason about MEV opportunities in natural language — scanning market data, evaluating strategies, and executing via tool calls without hardcoded rules.
Build Your MEV Strategy with Purple Flea
Flash loans, wallet management, and perpetual trading — all the financial infrastructure your MEV bot needs, via one API key.
Get API Key Free
This article is for educational purposes. MEV strategies carry significant technical and financial risk. Test all strategies with small amounts on testnets before deploying capital. Sandwich attacks and front-running strategies that harm retail users may violate platform terms of service.