Understanding the mechanisms that underpin automated debt repayment is essential for analyzing bot competition in derivatives markets.
How Liquidation Bots Compete in DeFi Derivatives Markets
Core Concepts of DeFi Liquidations
Health Factor & Collateralization Ratio
The Health Factor is a risk metric determining a position's safety. A value below 1 triggers liquidation.
- Calculated as (Collateral Value * Liquidation Threshold) / Borrowed Value.
- Protocols like Aave and Compound use this model.
- For users, monitoring this ratio is critical to avoid unexpected position closure and loss of collateral.
Liquidation Threshold & Bonus
The Liquidation Threshold is the maximum loan-to-value ratio before liquidation. The Liquidation Bonus is the discount liquidators receive on seized collateral.
- A 10% bonus means liquidators buy collateral at 90% of market value.
- This bonus creates the profit incentive for competing bots.
- For users, a higher bonus means greater potential loss during a liquidation event.
Liquidation Queue & Priority Gas Auction (PGA)
A Priority Gas Auction occurs when multiple bots compete to be first in the transaction queue for a profitable liquidation.
- Bots programmatically outbid each other on transaction fees (gas).
- This competition can temporarily spike network gas prices.
- For the market, PGAs ensure liquidations are executed swiftly, maintaining protocol solvency.
Keeper Networks & MEV
Keepers are automated agents that monitor and execute liquidations. Their activity is a major source of Maximal Extractable Value (MEV).
- Bots scan mempools for undercollateralized positions.
- Successful liquidation bundles are profitable MEV transactions.
- This creates a competitive, latency-sensitive environment where sophisticated infrastructure is key to capturing value.
Cross-Margin & Isolated Margin
Cross-margin uses a unified collateral pool for all positions, while isolated margin confines risk to specific assets.
- Cross-margin, used in protocols like dYdX, increases capital efficiency but risks cascade liquidations.
- Isolated margin, common in perpetual swaps, limits contagion.
- The choice directly impacts a user's liquidation risk profile and a bot's strategy for scanning.
Oracle Price Feeds
Oracles provide the external price data that determines collateral value and triggers liquidations.
- Decentralized oracles like Chainlink are commonly used.
- Price latency or manipulation can lead to incorrect liquidations.
- For bots, accessing fast, accurate price data is a competitive advantage in identifying opportunities first.
Liquidation Bot Strategies and Tactics
Understanding the Liquidation Game
Liquidation is the forced closure of an undercollateralized position to repay its debt. In DeFi derivatives markets like dYdX, GMX, or Synthetix, users can open leveraged positions. If the value of their collateral falls too close to their loan value, the position becomes eligible for liquidation. Bots compete to be the first to execute this transaction, earning a liquidation fee as a reward.
Key Mechanics
- Health Factor/CR: A position's health is measured by its Collateral Ratio. When this ratio drops below a protocol's liquidation threshold, the position is flagged.
- Liquidation Fee: The bot executor receives a percentage of the position's size or collateral as a reward, typically 5-15%.
- Gas Auction: Bots often engage in a Priority Gas Auction (PGA), bidding up transaction fees to have their liquidation transaction processed first on-chain.
Example Scenario
On a perpetual futures platform like GMX, a trader opens a 10x long ETH position. If the price of ETH drops 9%, their position becomes undercollateralized. A liquidation bot monitoring the blockchain state will detect this, submit a transaction to close the position, and claim the liquidation reward from the remaining collateral.
Anatomy of a Liquidation Execution
Process overview
Monitor Positions and Price Feeds
Continuously track user positions and oracle prices to identify candidates.
Detailed Instructions
A liquidation bot's core function is real-time monitoring. It subscribes to events from the Perpetual Protocol's clearing house or similar contracts to track all open positions. Concurrently, it polls multiple price feed oracles (e.g., Chainlink, Pyth Network) for the underlying asset. The bot calculates the health factor or margin ratio for each position by comparing the collateral value to the position's notional size and required maintenance margin. Positions are flagged when this ratio falls below the protocol's defined liquidation threshold, such as 6.25% for GMX or a 1.1 health factor for Aave. The bot must account for price feed latency and potential oracle manipulation when making this assessment.
- Sub-step 1: Subscribe to
PositionOpened,PositionIncreased, andPositionDecreasedevents. - Sub-step 2: Fetch the latest price from the designated oracle adapter contract.
- Sub-step 3: Calculate
marginRatio = (collateralValue / positionSize) * 100. - Sub-step 4: Compare the calculated ratio against the protocol's
liquidationThreshold.
javascript// Example: Checking a position's health on a hypothetical perp DEX const position = await clearingHouse.getPosition(userAddress, marketId); const oraclePrice = await priceFeed.getPrice(marketId); const collateralValue = position.collateral * oraclePrice; const positionNotional = position.size * oraclePrice; const marginRatio = (collateralValue / Math.abs(positionNotional)) * 100; const isLiquidatable = marginRatio < LIQUIDATION_THRESHOLD;
Tip: Implement a confidence check by comparing prices across multiple oracles to guard against stale or manipulated data.
Assess Profitability and Gas Costs
Calculate potential profit from the liquidation fee after accounting for network fees.
Detailed Instructions
Before initiating a transaction, the bot must perform a profitability check. The protocol defines a liquidation fee (e.g., 10% of the position size on dYdX, a dynamic fee based on slippage on Perpetual Protocol), which is the gross reward. From this, the bot must subtract the expected gas cost for the liquidation transaction, which can be highly volatile. The bot estimates gas by simulating the liquidatePosition call using eth_call or by checking recent base fees and priority fees for similar transactions. It also must account for potential slippage if the liquidation involves closing a large position on an AMM, which could reduce the realized fee. The final calculation must exceed the bot operator's minimum profit threshold to proceed.
- Sub-step 1: Query the protocol contract for the
liquidationFeefor the specific position. - Sub-step 2: Estimate current gas cost:
gasUnits * (baseFee + priorityFee)in ETH. - Sub-step 3: Convert the gas cost to the fee token (e.g., USDC) using a spot price.
- Sub-step 4: Calculate net profit:
liquidationFee - estimatedGasCost.
solidity// Solidity view function example for fee calculation (simplified) function getLiquidationBonus(address user, uint256 marketId) public view returns (uint256) { Position memory pos = positions[user][marketId]; // Bonus is often a percentage of the position size or collateral return (pos.size * LIQUIDATION_PENALTY) / BASIS_POINTS; }
Tip: Use EIP-1559 fee estimation tools and set a dynamic minimum profit threshold based on a percentage of your capital at risk.
Construct and Simulate the Transaction
Build the liquidation tx and simulate it to ensure success and validate profit.
Detailed Instructions
Transaction construction is critical for success and cost management. The bot builds a transaction calling the protocol's liquidate function (e.g., PerpV2ClearingHouse.liquidate()), encoding the target user's address and market ID. It must set an appropriate gas limit to cover the execution, which includes potential AMM swaps. Before broadcasting, the transaction is simulated via eth_call on a forked network or a local node. This simulation checks for failures due to race conditions (another bot liquidating first), slippage protection, or unexpected state changes. The simulation also returns the exact amount of fee tokens received, allowing for a final, precise profit validation against the current gas estimate.
- Sub-step 1: Encode the function call data for
liquidate(address account, uint256 marketId). - Sub-step 2: Set a competitive
maxPriorityFeePerGasbased on current mempool conditions. - Sub-step 3: Execute a static call (
eth_call) with the sender's address to simulate. - Sub-step 4: Parse the simulation result to confirm success and output token amounts.
javascript// Example using ethers.js to build and simulate tconst liquidateTx = await clearingHouse.populateTransaction.liquidate(targetUser, marketId); const simulationResult = await provider.call({ to: liquidateTx.to, data: liquidateTx.data, from: botAddress }); // Decode the result to get the liquidation fee amount in USDC const [feeAmount] = ethers.utils.defaultAbiCoder.decode(['uint256'], simulationResult);
Tip: Use a dedicated RPC endpoint with low latency for simulations to reduce the time between simulation and broadcast.
Broadcast with Competitive Gas and Monitor
Send the transaction with optimized gas and confirm its inclusion in a block.
Detailed Instructions
The final step is broadcasting the signed transaction to the network. To outcompete other bots, gas optimization is key. The bot must use a competitive gas price, often employing a strategy like gas auctioning where it sets a maxPriorityFeePerGas slightly above the estimated market rate. It sends the transaction via a direct connection to a block builder or multiple public RPC endpoints to minimize propagation delay. After broadcasting, the bot monitors the transaction's status. If it's pending too long, it may issue a replacement transaction (same nonce) with a higher gas price. Upon successful inclusion, it parses the transaction receipt to log the profit, gas used, and verify the state change in the protocol.
- Sub-step 1: Sign the constructed transaction with the bot's private key.
- Sub-step 2: Broadcast the signed tx simultaneously to several Ethereum node endpoints.
- Sub-step 3: Monitor mempool for competing transactions targeting the same position.
- Sub-step 4: If needed, replace the tx with a higher gas price before confirmation.
- Sub-step 5: On confirmation, parse logs for
PositionLiquidatedevent to confirm.
bash# Example curl to send a raw transaction to a node curl -X POST \ -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0","method":"eth_sendRawTransaction","params":["0xSignedTxData"],"id":1}' \ http://your-node:8545
Tip: Implement a transaction manager that tracks nonces locally and can quickly bump gas for stale pending transactions to avoid getting stuck.
Liquidation Mechanisms Across Major Protocols
Comparison of key parameters and incentives for liquidators.
| Mechanism / Parameter | dYdX (v3) | GMX (v1) | Perpetual Protocol (v2) | Synthetix (Perps V2) |
|---|---|---|---|---|
Liquidation Fee (Incentive) | 1.5% of position size | Up to 10% of position size (scales with price impact) | 1.5% of position size | Liquidator's reward + keeper fee from a global pool |
Health Check | Maintenance Margin Ratio | Liquidation Threshold based on Max. Drawdown | Maintenance Margin | Skew-adjusted Margin Ratio |
Liquidation Execution | Permissionless, on-chain auction | Permissionless, keeper-executed | Permissionless, keeper-executed via Gelato | Permissionless, keeper-executed via Pyth network |
Gas Cost Coverage | Not provided by protocol | Gas cost reimbursed from liquidation fee | Gas cost reimbursed via Gelato's gas tank | Keeper fee from pool covers gas + profit |
Max. Liquidation Size | Up to entire position | Limited by available liquidity in pool | Up to entire position | Limited by skew and available liquidity |
Price Oracle | dYdX Oracle (Pyth, Chainlink) | Chainlink Fast Price Feed + GMX Oracle | Uniswap V3 TWAP + Pyth | Pyth Network |
Time Priority | First-come, first-served (FCFS) | FCFS, but gas bidding influences priority | FCFS via Gelato's task queue | FCFS, influenced by keeper's stake and gas bid |
Partial Liquidation | No, full position only | Yes, based on max. allowable drawdown | No, full position only | Yes, liquidates to a safe margin level |
Technical Infrastructure for Bots
The hardware and software stack that enables low-latency execution and reliable operation in competitive DeFi environments.
Node Infrastructure
Dedicated RPC nodes are critical for speed and reliability. Running private nodes or using premium services reduces latency and provides direct access to transaction pools.
- Deploying nodes in the same geographic region as the target blockchain's validators.
- Using archival nodes for historical state queries during strategy backtesting.
- Why this matters: Minimizes the time between seeing a liquidation opportunity and submitting a transaction.
Transaction Management
Transaction simulation and gas optimization are used to ensure success and cost-effectiveness. Bots simulate transactions locally before broadcasting and employ dynamic gas strategies.
- Using
eth_callto pre-check for failure conditions like insufficient collateral. - Implementing gas auctions with tools like Flashbots to avoid frontrunning and failed transactions.
- Why this matters: Prevents capital loss from reverted transactions and optimizes profit margins.
Monitoring & Alerting
Real-time mempool and state monitoring systems watch for specific on-chain conditions. This involves subscribing to WebSocket streams and parsing event logs.
- Setting up alerts for specific function calls like
liquidatePosition()on a protocol. - Monitoring health metrics like gas prices and network congestion to adjust strategy.
- Why this matters: Provides the initial signal for a potential liquidation opportunity before it's widely visible.
Execution Strategies
Precise execution logic determines how a bot capitalizes on an opportunity. This includes logic for bidding in gas auctions and handling partial liquidations.
- Implementing a competitive gas price algorithm based on real-time mempool data.
- Designing fallback logic for when a target position is liquidated by another bot mid-process.
- Why this matters: Directly impacts the bot's success rate and profitability in a crowded field.
Risk Management Systems
Automated risk parameters protect the bot's capital from adverse market moves or system failures. This includes circuit breakers and position size limits.
- Setting maximum gas price caps to avoid unprofitable liquidations.
- Implementing cooldown periods after failed attempts to prevent fee waste.
- Why this matters: Ensures long-term operational viability by preventing catastrophic losses from single events.
Backtesting & Simulation
Historical data analysis is used to validate strategies before deploying capital. This involves replaying past blockchain state to test logic.
- Using forked mainnet environments with tools like Ganache or Hardhat to simulate execution.
- Analyzing metrics like win rate, average profit, and gas costs across historical events.
- Why this matters: Provides confidence in the strategy's edge and helps optimize parameters without real financial risk.
Economics and Incentive Structures
Understanding the Profit Motive
Liquidation bots are automated programs that compete to be the first to liquidate undercollateralized positions. In DeFi derivatives, users borrow assets or open leveraged positions by locking up collateral. If the value of this collateral falls too close to the borrowed value, the position becomes eligible for liquidation to protect the protocol from losses. The first bot to successfully execute this transaction earns a liquidation bonus or fee, typically 5-15% of the position's value, paid from the user's remaining collateral.
Key Economic Drivers
- Arbitrage Opportunity: The liquidation bonus creates a direct financial reward, turning risk management into a competitive race.
- Gas Price Auctions: Bots compete by paying higher transaction fees (gas) to miners/validators to get their transaction processed first in the next block. This creates a dynamic where profit must exceed gas costs.
- Monitoring Costs: Running these bots requires constant, low-latency monitoring of blockchain state and oracle prices, which is an ongoing operational expense.
Real-World Example
On a protocol like dYdX or GMX, if a trader's leveraged long ETH position drops in value, their health factor falls. A network of bots will detect this, each trying to submit the liquidation transaction with the highest priority fee to win the reward, often within the same block.
Risks and Operational Challenges
The main technical risks involve smart contract vulnerabilities and infrastructure reliability. Bots interact directly with protocol contracts, exposing them to potential bugs or exploits in the underlying code. A single failure in your node provider, RPC endpoint, or internet connection can cause missed opportunities or failed transactions. Gas price volatility is another critical factor; sudden network congestion can make profitable liquidations unprofitable. For example, during an Ethereum gas spike to 200+ gwei, a bot's transaction cost could exceed the liquidation reward, resulting in a net loss despite correct execution.