Liquidation Hunting Bot Strategies and Risk Management
A liquidation hunting bot is a specialized trading algorithm that scans decentralized lending protocols for undercollateralized positions—loans where the collateral value has fallen below the required threshold—and quickly submits liquidation transactions to earn a reward, typically the liquidator gets a bonus plus the collateral at a discount. For advanced DeFi traders and bot developers, building a profitable liquidation monitoring bot means balancing speed, gas efficiency, and protection against manipulation by MEV searchers.
This definitive guide walks you through the mechanics of liquidations on Aave and Compound, then dives into the architecture of a real-world bot: how to monitor events, simulate liquidations, bid for gas, and route transactions through private order flows like Flashbots. You’ll also learn common pitfalls—such as underestimating MEV traps and failing to manage risk—plus concrete strategies for staying ahead of the competition. Whether you are building with Web3.py, ethers.js, or Hardhat, these principles apply across EVM-compatible chains.
- Always use private mempools (Flashbots) to submit liquidation transactions and avoid MEV extraction.
- Gas optimization requires dynamic priority fee estimation and exact gas limit through off-chain simulation.
- A liquidation bot must monitor multiple protocols and chains simultaneously to capture opportunities.
- Risk management is critical: pre-allocate safe capital, use flash loans to reduce lockup, and set strict profit thresholds.
- Test on testnets (Sepolia, Holesky) before deploying real capital; record all metrics to iteratively improve.
- Advanced bots can combine flash loans, cross-chain arbitrage, and synthetic positions to increase returns.
What Is a Liquidation Hunting Bot and How Does It Capture Value?
A liquidation hunting bot is an automated program that watches blockchain mempools and on-chain events for liquidation opportunities. When a borrower’s health factor drops below 1 (on Aave) or the liquidation threshold is crossed (on Compound), the bot competes to repay the debt and seize the collateral, netting a fee—typically 5-10% of the position plus a liquidation bonus paid in the reserve asset.
The core value capture comes from the discount on collateral: you repay the debt (say, $1000 DAI) and receive collateral worth more (e.g., $1100 ETH), earning $100 minus gas. Competition is fierce; hundreds of bots may target the same position. Successful bots combine low-latency monitoring, accurate gas estimation, and MEV-aware submission to avoid being frontrun. Real protocols like Aave V2/V3 and Compound III reward liquidators with a fixed bonus, while MakerDAO and Liquity offer different liquidation mechanics.
- Monitor liquidation events via subgraphs (The Graph) or directly via RPC logs.
- Simulate the liquidation off-chain to ensure profitability after gas.
- Submit through a private mempool (Flashbots, BloxRoute) to avoid MEV extraction.
Understanding Liquidation Mechanics on Aave and Compound
Lending protocols define a loan-to-value (LTV) ratio and a liquidation threshold. When the LTV exceeds the threshold (e.g., 80% on Compound), anyone can liquidate the position. The liquidator repays a portion of the debt and receives the borrower’s collateral, often with an extra bonus. For example, on Aave V3, the liquidation bonus is 5% on most assets.
| Protocol | Liquidation Threshold | Bonus | Repay Limit |
|---|---|---|---|
| Aave V3 | Typically 80-85% | 5-10% | 50% of position |
| Compound | 80% | 8% | 50% of debt |
| MakerDAO | 150% collateralization | 13% penalty + auction | Any amount |
Your bot must compute the exact health factor in real-time. Use the protocol’s price oracle (Chainlink) or a flash loan to simulate the trade. Knowing the precise liquidation penalty helps you set a maximum gas price that still yields profit.
Core Components of a Profitable Liquidation Bot
A production-grade bot consists of three interconnected modules: monitoring, simulation, and execution. The monitoring layer listens to mempool transactions and logs health factor changes. Many advanced bots use subgraphs on The Graph for queries on liquidation events. The simulation layer runs a smart contract call locally—using eth_call—to verify the liquidation is still profitable at current gas prices. Finally, execution submits the transaction through a private order flow, such as Flashbots, to prevent MEV attacks.
Key tools:
- Web3.py (Python) or ethers.js (JS) for blockchain interaction.
- FastAPI to serve an HTTP endpoint for trigger events.
- Redis to cache recent blocks and avoid redundant computations.
- Flashbots-js or mev-geth for bundle submissions.
Building Your Liquidation Monitoring Bot – Step-by-Step
Follow these concrete steps to construct a functional prototype on Ethereum mainnet (tested on a testnet like Sepolia first). The example uses Web3.py and Flashbots.
- Set up a Web3 connection to an archive node (Alchemy or Infura) and a private RPC for Flashbots (e.g., flashbots.net).
- Subscribe to pending transactions filtering for liquidation calls (e.g., Aave’s `liquidationCall` function). Parse logs for `Liquidated` events.
- Fetch on-chain health factors by calling the protocol’s `getUserAccountData` for Aave or `getAccountLiquidity` for Compound.
- Simulate the liquidation using `eth_call` at the same block height as your observation. Compute profit = collateral value - debt repaid - gas cost.
- Create a bundle with your simulated transaction. Add a safety check: only if profit > estimated gas cost * 1.5.
- Submit the bundle to Flashbots using `flashbots.sendBundle()`. Optionally use multiple block windows (e.g., next 10 blocks) to increase chance.
- Monitor results via bundle status: if included, update your profit log; if not, adjust gas price or try other protocols.
Gas Optimization Strategies for Liquidation Bots
Gas is the single largest cost after capital. A naively submitted transaction with a high priority fee will be outbid by MEV bots. Instead, optimize using these techniques:
- Priority fee estimation: Use a percentile (e.g., 30th) of recent priority fees from the mempool to avoid overpaying. Update every block.
- Gas limit: Exactly simulate the liquidation to get a tight gas limit (~150k for Aave V3). Overestimating wastes ETH; underestimating causes revert.
- Bundle ordering: Place your liquidation transaction after a likely user transaction that triggers the liquidation (e.g., a swap that moves price). This reduces competition.
- Private mempool relayers: Flashbots and BloxRoute allow you to submit bundles that only your searcher can land, preventing frontrunning.
- Cross-chain arbitrage: Some bots monitor multiple L2s (Polygon, Arbitrum) where gas is cheaper, but liquidation size may be smaller.
A common mistake: setting a fixed gas price. Always use dynamic fee estimation based on recent inclusion rates.
Avoiding MEV Traps: Frontrunning, Sandwich Attacks, and Order Flow Hijacking
When your liquidation hunting bot submits a transaction, you are vulnerable to MEV extraction. The three main traps are:
- Frontrunning: A malicious searcher sees your pending tx and submits their own with a higher gas price, stealing the liquidation.
- Sandwich attack: If you buy collateral immediately after liquidation, an attacker can sandwich your trade, causing slippage.
- Order flow leakage: Public mempool transactions are visible to all; using Flashbots solves most of this, but you must also protect the block builder from seeing your intent.
To defend: Always submit through private mempools. For Flashbots, use the `flashbots_getBundleStats` to verify your bundle is not being tampered. Additionally, design your smart contract to atomically repay debt and withdraw collateral in one function call, so no intermediate steps are exposed. Use gas-abstraction patterns to hide the actual liquidation function selector.
Real-world pattern: bots that broadcast liquidation transactions through the public mempool are routinely frontrun or sandwiched, so a competitor captures the liquidation bonus while the exposed bot pays gas for a reverted or losing transaction.
Risk Management for Liquidation Bots
Running a liquidation hunting bot is capital-intensive and risky. Managing risk properly separates professionals from amateurs.
- Capital lockup: You must pre-deposit tokens (e.g., DAI, USDC) into your liquidation contract to have funds ready. If you are outbid, your capital sits idle. Allocate only a fraction of total capital to active strategies.
- Bad debt risk: In rare volatility events, the collateral may drop further before you can sell it. Use only highly liquid collaterals (ETH, WBTC) and set a maximum position size.
- Slippage on sale: After liquidating, you often hold the collateral. Selling it on DEXes incurs slippage. Include a buffer of 2-3% in profit calculations.
- Network congestion: When the market dumps, many liquidations happen simultaneously, gas prices spike, and your transaction may fail. Have a fallback of submitting to multiple private mempools.
- Smart contract risk: Protocol upgrades or bugs can break your bot. Monitor governance and test on testnets after upgrades.
Rule of thumb: only liquidate positions where profit margin is at least 20% above estimated gas cost. That gives room for slippage and network spikes.
Advanced Strategies: Multi-Chain, Flash Loans, and Synthetic Liquidations
Once your bot is profitable on a single chain, consider these advanced techniques:
- Multi-chain monitoring: Use a centralized control plane to watch Aave V3 on Polygon, Arbitrum, and Optimism. Execute flash loans to move capital between chains quickly. Tools like Chainlink CCIP or LayerZero can automate cross-chain messaging.
- Flash loan powered liquidations: Instead of pre-depositing capital, borrow a flash loan to repay debt, receive collateral, then swap and repay the flash loan—all in one block, earning the bonus. This reduces capital lockup but increases gas and execution risk.
- Synthetic liquidations: Use protocols like Synthetix or Perpetual Protocol where liquidations are triggered by price feeds. Your bot can arbitrage the difference between on-chain price and centralized exchange price before liquidating on a DEX.
- MEV-share agreements: Partner with block builders to get a cut of the MEV in exchange for allowing them to order your transactions. This is emerging through MEV-sharing arrangements such as Flashbots’ MEV-Share.
Remember: each new chain or feature adds attack surface. Test thoroughly on testnets.
Comparison Table: Development Tools for Liquidation Bots
| Tool | Language | Best For | Gas Optimizations | MEV Protection |
|---|---|---|---|---|
| Web3.py + Flashbots | Python | Rapid prototyping, custom simulations | Manual priority fee estimation | Flashbots bundle, order signing |
| ethers.js + Flashbots-js | JavaScript | Node.js services, real-time events | Plugin for gas oracle (e.g., EthGasStation) | Flashbots relay, private mempool |
| Brownie | Python | Testing & deployment of liquidation contracts | Automated gas profiler | Limited; use with Flashbots adapter |
| Hardhat + MEV-geth | TypeScript | Forking mainnet for simulation | Hardhat-gas-reporter plugin | Simulated MEV environment |
Choose Web3.py if you need maximum control over nonce management and bundle composition. Use ethers.js if your stack is already Node-based. For testing, Brownie or Hardhat are indispensable.
Summary and Key Takeaways
Building a liquidation hunting bot is a challenging but rewarding DeFi strategy for advanced developers. The key success factors are:
- Real-time monitoring of health factors across multiple lending protocols.
- Accurate off-chain simulation of liquidation profitability.
- Submission through private mempools (Flashbots) to avoid frontrunning.
- Dynamic gas pricing based on recent block conditions.
- Prudent risk management to prevent capital loss during volatility.
Start small on testnet, scale gradually, and never use the public mempool. With these strategies, you can consistently capture liquidation bonuses and earn alpha in the DeFi ecosystem.
Step-by-step
- Set up an archive node connection (Alchemy/Infura) and configure a private Web3 provider for Flashbots.
- Subscribe to pending transactions filtering for liquidation function calls (e.g., Aave's liquidationCall) using eth_subscribe or logs polling.
- For each candidate tx, fetch the user's health factor via the protocol's getUserAccountData and compute expected profit.
- Simulate the liquidation call with eth_call at the current block height to confirm profitability after gas costs.
- Create a Flashbots bundle containing your simulated liquidation transaction with a priority fee set to 30th percentile of recent blocks.
- Submit the bundle to the Flashbots relay and monitor for inclusion using getBundleStats; if not included after 5 blocks, adjust fee or skip opportunity.
- Log every result: profit, gas spent, block number, and opponent activity. Use this data to refine gas estimation and strategy.
Common mistakes to avoid
- Submitting transactions to the public mempool, leading to frontrunning or sandwich attacks.
- Using a static gas price instead of dynamic estimation based on current network conditions.
- Failing to simulate the liquidation in the exact same block it will be executed, causing inaccurate profit calculations.
- Overlooking slippage when selling the seized collateral, especially for illiquid assets.
- Not monitoring protocol governance changes (e.g., bonus percentage adjustments) that affect profitability.
- Allocating too much capital to a single bot without fallback mechanisms during network congestion.
Frequently asked questions
What is the best blockchain for running a liquidation hunting bot?
Ethereum mainnet still offers the largest liquidation opportunities due to high TVL on Aave and Compound, but competition is fierce. Polygon and Arbitrum have lower gas costs and less competition, making them good starting points for smaller capital bots.
Do I need to write a custom smart contract for liquidation bots?
Yes, most advanced bots use a smart contract to atomically repay debt, receive collateral, and swap it in one transaction. This reduces frontrunning risk and allows flash loan integration. You can adapt open-source liquidation contract examples published by the community as a starting point.
How much capital do I need to start a liquidation bot?
You need at least enough to cover one full liquidation plus gas reserves. On Ethereum, a typical liquidation might require $5k-$20k. Start with $10k on Polygon for lower gas costs. Use flash loans to reduce capital needs but increase complexity.
Can I run a liquidation bot without using Flashbots?
Technically yes, but you will likely lose all opportunities to frontrunners. Flashbots is the standard for private order flow. Alternative private mempools and relays include bloXroute's private transaction service.
What programming languages are most commonly used for these bots?
Python (Web3.py) and JavaScript/TypeScript (ethers.js) are most popular. Python is preferred for data analysis and rapid prototyping; JS for real-time event handling. Some use Rust with ethers-rs for extreme performance.
Related reading
Track the entities behind the concepts
DeFi Intel maps 11,000+ protocols, tokens and companies to a typed knowledge graph — with live data, incidents and regulation.