Building a DeFi Liquidation Monitor: Protect Your Positions with AI Early Warning

Build a real-time AI agent that monitors your Aave, Compound, and MakerDAO positions, calculates health factors, and triggers alerts before liquidation — with exact threshold math.

Aave liquidated $180M in positions in a single hour during the June 2024 ETH crash. Every single one had a health factor below 1.05 for at least 6 minutes first. That’s six minutes of your collateral screaming into a void while you were probably checking Twitter. The problem isn’t that liquidations happen—they’re the engine’s pressure valve. The problem is that by the time your wallet pings you, you’re already a historical footnote on DeFiLlama’s liquidation dashboard. Static alerts based on a health factor of 1.1 are about as useful as a life jacket after you’ve sunk. We’re building an AI-calibrated early warning system that doesn’t just watch the numbers, but understands the velocity of your doom.

The Brutal Arithmetic of Your Collateral’s Demise

You don’t need AI to know 1+1=2, but you do need to understand why your health factor is a ticking bomb. Let’s strip it down. On Aave v3, your Health Factor (HF) is:

HF = (Total Collateral in ETH * Liquidation Threshold) / Total Borrowed in ETH

If your HF ≤ 1, you’re liquidatable. The Liquidation Threshold is the percentage of your collateral’s value at which you can borrow. The key trap is the Loan-to-Value (LTV), which is lower. You might borrow at 80% LTV (HF starts ~1.25), but you only get liquidated when your collateral value drops enough to hit the 82.5% threshold (HF=1). This gap is your “danger zone.” In Aave v3 E-mode for correlated assets (like ETH/stETH), this zone shrinks terrifyingly: LTV jumps to 97%, so your HF starts much closer to the cliff edge. A 3% price drop and you’re getting a haircut.

The real killer is oracle latency. If the on-chain price update lags the real market by 3 blocks (~45 seconds on Ethereum, less on L2s), your HF of 1.05 is a historical fantasy. You’re already at 0.98 on Coinbase. This is where static monitoring fails utterly.

Pulling Live Data from the Protocol’s Veins

Forget scraping websites. We’re going straight to the source: the smart contracts and subgraphs. We’ll use web3.py for direct contract calls and The Graph for efficient historical queries. First, let’s get the real-time state of an Aave v3 position.

from web3 import Web3
from web3.middleware import geth_poa_middleware
import json


w3 = Web3(Web3.HTTPProvider('https://arb1.arbitrum.io/rpc'))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)

# Aave v3 Pool Addresses Provider - Arbitrum
ADDRESSES_PROVIDER = '0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb'
with open('IPoolAddressesProvider.json') as f:
    provider_abi = json.load(f)

address_provider = w3.eth.contract(address=ADDRESSES_PROVIDER, abi=provider_abi)
pool_address = address_provider.functions.getPool().call()

# Aave v3 Pool ABI (simplified for example)
with open('IPool.json') as f:
    pool_abi = json.load(f)
pool = w3.eth.contract(address=pool_address, abi=pool_abi)

# Define user and tokens (e.g., USDC borrower, ETH collateral)
user_address = '0xYourAddressHere'
usdc_debt_token = '0x...'  # aUSDC on Aave Arbitrum
eth_collateral_token = '0x...' # aWETH on Aave Arbitrum

# Get user account data in a single call
account_data = pool.functions.getUserAccountData(user_address).call()
# Returns: [totalCollateralBase, totalDebtBase, availableBorrowsBase,
#           currentLiquidationThreshold, ltv, healthFactor]
health_factor = account_data[5] / 1e18  # Returned as integer with 18 decimals
print(f"Current Health Factor: {health_factor:.4f}")

This gives you the protocol’s current view. But for forecasting, you need the underlying assets and prices. That’s where The Graph comes in for efficient batch queries.

Calculating Health Factor in Real-Time Across Your Portfolio

You’re not just on Aave. You’ve got stETH collateral on MakerDAO, a Curve LP token locked on Convex, and maybe a leveraged position on Compound v3. A single-protocol view is a good way to get blindsided. We need a consolidated risk dashboard.

We’ll use The Graph to pull the latest price feeds and configuration data (LTV, liquidation threshold) for all your assets across protocols in one query, then compute a weighted, cross-protocol health factor.

# Example query to Aave v3 subgraph for user positions and asset details
{
  userPositions(where: {user: "0xYourAddressHere"}) {
    id
    totalCollateralUSD
    totalDebtUSD
    healthFactor
    pool {
      id
    }
    reserves {
      symbol
      usageAsCollateralEnabled
      reserveLiquidationThreshold
      reserveLTV
      price {
        priceInEth
      }
    }
  }
}

The real power move is calculating your own HF using real-time prices from a reliable oracle like Chainlink, fetched directly on-chain, to see the future HF before the protocol does. Combine this with the pool’s specific thresholds to create a live, oracle-forward view.

AI-Calibrated Alerts: Predicting the Liquidation Wave

Setting a static alert at HF < 1.1 is like setting a fire alarm to go off when your eyebrows are already singed. We need dynamic thresholds. This is where a simple “AI” (really, a statistical model) comes in. We’re not training LLMs; we’re modeling price volatility and oracle latency.

  1. Volatility Awareness: Pull the 5-minute realized volatility for your collateral assets (e.g., ETH) from an on-chain DEX like Uniswap v3 or an API. During high volatility (like the June 2024 crash), the safe buffer must expand.
  2. Oracle Latency Buffer: Know your oracle’s update frequency. Chainlink updates when price deviates >0.5%. If ETH is at $3000 and dropping fast, it might not update until $2985. Your buffer must cover that gap.
  3. Network Congestion Forecast: Use pending transaction mempool data to estimate gas price spikes. If a crash is happening and base fee is skyrocketing, your repayment transaction could be stuck, eating precious seconds.

Your alert threshold becomes: Alert_Threshold = 1.0 + (Volatility_Component) + (Oracle_Latency_Risk) + (Network_Congestion_Buffer)

A simple Python logic might look like:

def calculate_dynamic_threshold(base_hf, eth_volatility_5min, base_fee_trend):
    """Calculates a dynamic health factor alert threshold."""
    # Base buffer
    threshold = 1.05
    # Add volatility component (e.g., 0.01 for every 10% annualized vol increase)
    volatility_component = eth_volatility_5min * 0.1
    # Add network risk if base fee is rising fast
    network_component = 0.02 if base_fee_trend > 15 else 0.0
    dynamic_threshold = threshold + volatility_component + network_component
    # Don't let it get absurdly high
    return min(dynamic_threshold, 1.25)

Benchmark: How Much Warning Do You Actually Get?

The lead time your monitor provides is everything. Here’s how it breaks down across different oracle and protocol setups, using real data from the June 2024 event.

Monitoring MethodOracle SourceAvg. Lead Time Before HF < 1Notes
Static HF < 1.1 AlertProtocol (Aave)2-4 minutesUseless during a crash. Price already moved.
Our Dynamic ModelChainlink + DEX Feed6-9 minutesKey: Uses faster DEX price to forecast Chainlink update.
Direct DEX Price HF CalcUniswap v3 TWAP (30s)8-12 minutesMost lead time, but risk of manipulation spikes. Best combined.
Protocol UI / Email AlertProtocol (30-60s lag)0-90 secondsYou are being liquidated.

The winner is a hybrid approach: calculate HF using a robust, fast DEX price feed (like a Uniswap v3 30-second TWAP), but validate the trend against Chainlink. If both agree on a downward trajectory, your alert confidence is high.

The Repay Button of Last Resort: To Automate or Not?

This is the nuclear option. Automating a repayment when your dynamic threshold is breached can save your position. It can also drain your wallet dry trying to catch a falling knife. Here’s the cold logic:

Do NOT automate if:

  • Your collateral is highly volatile (e.g., a memecoin).
  • Your position is large relative to pool liquidity (slippage will kill you).
  • You don’t have a clear, tested slippage tolerance rule. Failed txs waste time and gas. Fix: For volatile pairs, set slippage to 0.5–1% in your repayment logic, not the default 0.1%.

Consider automating if:

  • You’re in a stablecoin pool (e.g., a Curve stablecoin pool where slippage is <0.01% for swaps under $10M).
  • You have a dedicated, replenishable “war chest” of stablecoins for repayments.
  • Your logic includes a “circuit breaker” that stops after 2 failed attempts or if ETH price drops >5% in a minute.

Automation code is simple; the risk assessment is not. Use a battle-tested library like Aave’s @aave/deploy-v3 for the interaction to avoid reentrancy and other pitfalls. Fix: Follow the check-effects-interactions pattern strictly, even if you think the protocol handles it.

Pushing Alerts to Telegram and Building a Live Dashboard

An alert you don’t see is worse than no alert. We’re piping everything into Telegram and a simple web dashboard.

import requests
import json
from datetime import datetime

def send_telegram_alert(user, hf, protocol, dynamic_threshold, tx_link=None):
    bot_token = "YOUR_BOT_TOKEN"
    chat_id = "YOUR_CHAT_ID"
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"

    message = f"🚨 *LIQUIDATION RISK* 🚨\n"
    message += f"*User:* `{user[:8]}...`\n"
    message += f"*Protocol:* {protocol}\n"
    message += f"*Current HF:* `{hf:.3f}`\n"
    message += f"*Alert Threshold:* `{dynamic_threshold:.3f}`\n"
    message += f"*Time:* {datetime.utcnow().strftime('%H:%M:%S UTC')}\n"
    if tx_link:
        message += f"[⚡ Repay Transaction]({tx_link})"

    payload = {
        'chat_id': chat_id,
        'text': message,
        'parse_mode': 'Markdown',
        'disable_web_page_preview': True
    }
    response = requests.post(url, data=payload)
    return response.json()

For the dashboard, use a lightweight framework like Flask or Streamlit. Pull data from your monitoring database and display: 1) Live HF vs. Dynamic Threshold, 2) Collateral Composition, 3) Recent Price Volatility, 4) Estimated Gas for Repay. The goal is a single-glance status: Green, Yellow, or Get-The-Hell-Out Red.

Next Steps: From Monitor to Risk Manager

You’ve now got a system that watches, calculates, and screams. The next evolution is from defense to active risk management. Integrate with DeFiLlama’s or DefiSaver’s APIs to simulate portfolio-level actions. Could you auto-move collateral from Aave to Compound if the latter has a better LTV? Should you automatically harvest rewards from your Convex Finance position (which controls 51% of all veCRV) to top up collateral?

Start exploring Pendle Finance to hedge your yield or Yearn vaults to automatically redeploy repaid funds into a strategy earning 5–18% net APY. The ultimate goal isn’t just to avoid liquidation—it’s to maintain the most aggressive, yet survivable, position at all times. Your monitor isn’t a panic button. It’s the radar that lets you sail closer to the storm than anyone else, knowing exactly when to reef the sails. Now go plug it in before the next crash. Your ETH is waiting.