DEV Community

Byaigo
Byaigo

Posted on

Building a DeFi Lending Position Health Monitor: Track Collateral Ratios and Liquidation Risks with Python

DeFi lending protocols like Aave and Compound hold billions in locked value — but every depositor lives with one fear: liquidation. If your collateral drops below the threshold, bots eat your position. Let's build a Python script that monitors your lending health in real time.

The Problem

When you deposit ETH as collateral and borrow USDC on Aave, your position's health factor fluctuates with ETH's price. If it drops below 1.0, you're liquidated. Most people only check when prices crash — by then it's too late.

The Solution: A Health Factor Monitor

We'll use Web3.py to read on-chain data from Aave's LendingPool contract and calculate health factors for any address. The script watches for positions approaching liquidation and sends alerts.

from web3 import Web3
import json
import time
import os

RPC_URL = os.getenv("ETH_RPC_URL", "https://mainnet.infura.io/v3/YOUR_KEY")
w3 = Web3(Web3.HTTPProvider(RPC_URL))

LENDING_POOL = "0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9"

POOL_ABI = json.loads('''[
  {
    "inputs": [{"internalType": "address", "name": "user", "type": "address"}],
    "name": "getUserAccountData",
    "outputs": [
      {"internalType": "uint256", "name": "totalCollateralETH"},
      {"internalType": "uint256", "name": "totalDebtETH"},
      {"internalType": "uint256", "name": "availableBorrowsETH"},
      {"internalType": "uint256", "name": "currentLiquidationThreshold"},
      {"internalType": "uint256", "name": "ltv"},
      {"internalType": "uint256", "name": "healthFactor"}
    ],
    "stateMutability": "view",
    "type": "function"
  }
]''')

pool = w3.eth.contract(address=LENDING_POOL, abi=POOL_ABI)

def check_health(user_address, min_health=1.5):
    data = pool.functions.getUserAccountData(user_address).call()
    health = data[5] / 1e18
    status = "SAFE" if health > min_health else "AT RISK" if health <= 1.1 else "WARNING"
    print(f"{status} | Health Factor: {health:.4f} | Collateral: {data[0]/1e18:.2f} ETH")
    return health

WATCH_ADDRESS = os.getenv("WATCH_ADDRESS", "0xYourAddressHere")
while True:
    try:
        check_health(WATCH_ADDRESS)
    except Exception as e:
        print(f"Error: {e}")
    time.sleep(300)
Enter fullscreen mode Exit fullscreen mode

How It Works

  • getUserAccountData() returns six values from Aave's LendingPool: total collateral, total debt, available borrows, liquidation threshold, LTV, and the all-important health factor.
  • Health factor is a uint256 scaled by 1e18 — divide to get the real number.
  • Below 1.0 = liquidation. We set alerts at 1.5 (warning) and 1.1 (danger).

Going Further

  • Add Telegram/Discord alerts when health drops below your threshold
  • Extend to Compound and MakerDAO vaults for multi-protocol coverage
  • Track multiple wallets — ideal for fund managers and DeFi power users
  • Use web3.eth.filter to watch for liquidation events in real time

Open Source & Contributions

All code is available on GitHub: github.com/Byaigo

If you find this useful, consider supporting:

ETH: 0x18da907cb9d981bc798acb87ac27b03a2dc3cbb7

Stay safe out there. Market swings are brutal — code your way to peace of mind.

Top comments (0)