backtrader
Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers,…
MEV exposure assessment, sandwich attack detection, and protection strategies for Solana DEX trading
$ npx -y skills add agiprolabs/claude-trading-skills --skill mev-analysis --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
/mev-analysisContext preview
The summary Claude sees to decide when to auto-load this skill.
MEV exposure assessment, sandwich attack detection, and protection strategies for Solana DEX trading
name: mev-analysis description: MEV exposure assessment, sandwich attack detection, and protection strategies for Solana DEX trading
Maximal Extractable Value (MEV) is the profit that validators and searchers can extract by reordering, inserting, or censoring transactions within a block. On Solana DEXes, MEV primarily manifests as sandwich attacks against swaps, cross-DEX arbitrage, and liquidation extraction. This skill covers detection, estimation, and protection strategies.
MEV occurs when someone with transaction ordering power profits at other traders' expense. On Solana, the MEV supply chain works as follows:
1. **You submit a swap** through an RPC endpoint 2. **Searchers observe** your transaction (via RPC forwarding, block engine access, or leader TPU sniffing) 3. **Searcher constructs a profitable bundle** (e.g., sandwich your swap) 4. **Bundle submitted to Jito block engine** with a tip to the validator 5. **Validator includes the bundle** in the block, earning the tip 6. **You receive worse execution**; the searcher profits the difference
| Aspect | Ethereum | Solana | |--------|----------|--------| | Block time | 12 seconds | ~400ms slots | | Mempool | Public mempool | No mempool (but tx visible in transit) | | Ordering | Proposer-builder separation (PBS) | Jito block engine (~85%+ validators) | | Bundle system | Flashbots bundles | Jito bundles with tips | | MEV cost | Gas priority fees | Jito tips (SOL) | | Latency pressure | Moderate | Extreme (sub-100ms decisions) |
Key Solana-specific factors:
The most common MEV attack against retail traders.
**Mechanics:**
1. Attacker sees your pending swap: Buy 10 SOL worth of TOKEN_X 2. Front-run: Attacker buys TOKEN_X first → price rises 3. Your swap: You buy TOKEN_X at higher price → worse execution 4. Back-run: Attacker sells TOKEN_X → profits the difference
**Your loss** = price impact from front-run + attacker's profit margin **Attacker profit** = your_loss - jito_tip - transaction_fees
**Risk factors:**
Searchers capture price discrepancies between DEXes.
Pool A: TOKEN_X = 1.00 USDC Pool B: TOKEN_X = 1.02 USDC → Buy on A, sell on B, profit 0.02 USDC per token (minus fees)
This is generally **beneficial** to the market — it equalizes prices across venues. However, your trade may trigger the arbitrage opportunity that the searcher captures.
When DeFi positions (Solend, Marginfi, Kamino) become undercollateralized, searchers race to liquidate them and claim the liquidation bonus (typically 5-10%).
Searchers add concentrated liquidity to a CLMM pool just before a large swap and remove it immediately after, earning swap fees without sustained impermanent loss exposure. This is a sophisticated MEV form that can actually **improve** execution for the swapper.
Trading immediately after a large swap that moved the price, capturing the reversion. Less harmful than sandwiching because it does not worsen your execution — it profits from the market response to your trade.
Estimate your MEV risk before executing a trade:
import httpx
def estimate_mev_risk(
trade_size_sol: float,
pool_liquidity_usd: float,
slippage_bps: int,
token_daily_volume_usd: float,
) -> dict:
"""Estimate sandwich attack profitability for a given trade.
Returns risk assessment with estimated cost and recommendations.
"""
# Trade as percentage of pool liquidity
sol_price = 150.0 # approximate; fetch live price in production
trade_usd = trade_size_sol * sol_price
trade_pct_of_pool = (trade_usd / pool_liquidity_usd) * 100
# Estimated price impact from constant-product AMM
# price_impact ≈ trade_size / pool_liquidity (simplified)
price_impact_bps = int(trade_pct_of_pool * 100)
# Sandwich profitability: attacker captures portion of slippage headroom
# Rough model: sandwich_profit ≈ 0.5 * slippage_headroom * trade_size
slippage_headroom_bps = slippage_bps - price_impact_bps
if slippage_headroom_bps < 0:
slippage_headroom_bps = 0
sandwich_profit_usd = (slippage_headroom_bps / 10000) * trade_usd * 0.5
jito_tip_cost = 0.001 * sol_price # ~0.001 SOL typical tip
tx_fees = 0.000015 * sol_price * 2 # two transactions for sandwich
net_mev_profit = sandwich_profit_usd - jito_tip_cost - tx_fees
is_profitable_to_sandwich = net_mev_profit > 0.10 # $0.10 minimum
# Volume ratio indicates MEV bot attention level
volume_ratio = trade_usd / max(token_daily_volume_usd, 1)
risk_level = "LOW"
if is_profitable_to_sandwich and trade_pct_of_pool > 1.0:
risk_level = "HIGH"
elif is_profitable_to_sandwich or trade_pct_of_pool > 0.5:
risk_level = "MEDIUM"
return {
"risk_level": risk_level,
"trade_pct_of_pool": round(trade_pct_of_pool, 2),
"estimated_price_impact_bps": price_impact_bps,
"slippage_headroom_bps": slipA comprehensive collection of 68 ready-to-use trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools.
Repo: agiprolabs/claude-trading-skills
Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers,…
Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security…
Broad crypto market data from CoinGecko covering 13,000+ tokens. Global market stats,…
Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability…
Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading
Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail…