DeFi Intel

Liquidation Hunting Bot Strategies and Risk Management

Quick answerA liquidation hunting bot monitors DeFi lending protocols for positions about to be liquidated, then executes profitable liquidations. Key to success: using private mempools (Flashbots), optimizing gas costs via priority fees, and avoiding frontrunning through order flow control. Requires robust risk management to avoid capital loss.

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.

Key takeaways
  • 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.

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.

ProtocolLiquidation ThresholdBonusRepay Limit
Aave V3Typically 80-85%5-10%50% of position
Compound80%8%50% of debt
MakerDAO150% collateralization13% penalty + auctionAny 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:

When you detect a candidate, your bot must estimate gas using a historical median priority fee and simulate the liquidation in the same block it will be mined. Never submit to the public mempool or your transaction will be frontrun.

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.

  1. Set up a Web3 connection to an archive node (Alchemy or Infura) and a private RPC for Flashbots (e.g., flashbots.net).
  2. Subscribe to pending transactions filtering for liquidation calls (e.g., Aave’s `liquidationCall` function). Parse logs for `Liquidated` events.
  3. Fetch on-chain health factors by calling the protocol’s `getUserAccountData` for Aave or `getAccountLiquidity` for Compound.
  4. Simulate the liquidation using `eth_call` at the same block height as your observation. Compute profit = collateral value - debt repaid - gas cost.
  5. Create a bundle with your simulated transaction. Add a safety check: only if profit > estimated gas cost * 1.5.
  6. Submit the bundle to Flashbots using `flashbots.sendBundle()`. Optionally use multiple block windows (e.g., next 10 blocks) to increase chance.
  7. 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:

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:

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.

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:

Remember: each new chain or feature adds attack surface. Test thoroughly on testnets.

Comparison Table: Development Tools for Liquidation Bots

ToolLanguageBest ForGas OptimizationsMEV Protection
Web3.py + FlashbotsPythonRapid prototyping, custom simulationsManual priority fee estimationFlashbots bundle, order signing
ethers.js + Flashbots-jsJavaScriptNode.js services, real-time eventsPlugin for gas oracle (e.g., EthGasStation)Flashbots relay, private mempool
BrowniePythonTesting & deployment of liquidation contractsAutomated gas profilerLimited; use with Flashbots adapter
Hardhat + MEV-gethTypeScriptForking mainnet for simulationHardhat-gas-reporter pluginSimulated 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:

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

  1. Set up an archive node connection (Alchemy/Infura) and configure a private Web3 provider for Flashbots.
  2. Subscribe to pending transactions filtering for liquidation function calls (e.g., Aave's liquidationCall) using eth_subscribe or logs polling.
  3. For each candidate tx, fetch the user's health factor via the protocol's getUserAccountData and compute expected profit.
  4. Simulate the liquidation call with eth_call at the current block height to confirm profitability after gas costs.
  5. Create a Flashbots bundle containing your simulated liquidation transaction with a priority fee set to 30th percentile of recent blocks.
  6. Submit the bundle to the Flashbots relay and monitor for inclusion using getBundleStats; if not included after 5 blocks, adjust fee or skip opportunity.
  7. Log every result: profit, gas spent, block number, and opponent activity. Use this data to refine gas estimation and strategy.

Common mistakes to avoid

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.

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.

Entities mentioned