Keep Your AI Agent Solvent: Health Factor Monitoring for DeFi Lending
When DeFi lending protocols liquidate positions at 1.05x health factor, your AI trading bot can lose thousands in seconds. If you're building automated yield strategies or DeFi bots, you need real-time health factor monitoring across multiple protocols — but each one has different APIs, calculation methods, and liquidation thresholds.
Why Health Factor Monitoring Is Critical
In DeFi lending, your health factor is the difference between profit and liquidation. Aave liquidates at 1.0, Kamino at 1.1, and each protocol calculates it differently. Your AI agent might be managing positions across multiple protocols simultaneously — a profitable arbitrage strategy on one platform could trigger a liquidation cascade on another if you're not monitoring cross-protocol risk.
Manual monitoring doesn't scale. By the time you check each protocol's dashboard, volatile markets have already moved. You need programmatic access to health factors, collateral ratios, and liquidation thresholds — ideally through a single API that normalizes data across protocols.
Unified Health Factor Monitoring with WAIaaS
WAIaaS provides real-time DeFi position monitoring across 15 protocols through a single REST API. Your AI agent gets normalized health factor data from Aave V3, Kamino, Drift, and other major protocols without managing multiple SDKs or RPC connections.
Here's how to check your health factor across all protocols:
curl http://127.0.0.1:3100/v1/wallet/defi-positions \
-H "Authorization: Bearer wai_sess_eyJhbGciOiJIUzI1NiJ9..."
The response includes health factors, liquidation thresholds, and collateral values in USD:
{
"positions": [
{
"protocol": "aave-v3",
"network": "ethereum-mainnet",
"healthFactor": 1.85,
"liquidationThreshold": 1.0,
"totalCollateralUsd": 5420.30,
"totalBorrowedUsd": 2930.15,
"assets": [
{
"asset": "WETH",
"type": "collateral",
"amount": "2.1",
"valueUsd": 4200.30,
"apy": 0.0245
}
]
},
{
"protocol": "kamino",
"network": "solana-mainnet",
"healthFactor": 2.34,
"liquidationThreshold": 1.1,
"totalCollateralUsd": 8750.25,
"totalBorrowedUsd": 3740.10
}
],
"summary": {
"totalCollateralUsd": 14170.55,
"totalBorrowedUsd": 6670.25,
"aggregateHealthFactor": 2.12,
"lowestHealthFactor": 1.85,
"protocolsAtRisk": 0
}
}
Setting Up Health Factor Alerts
WAIaaS includes policy-based monitoring that can trigger notifications when health factors drop below thresholds. Create a lending policy with health factor limits:
curl -X POST http://127.0.0.1:3100/v1/policies \
-H "Content-Type: application/json" \
-H "X-Master-Password: my-secret-password" \
-d '{
"walletId": "<wallet-uuid>",
"type": "LENDING_LTV_LIMIT",
"rules": {
"max_ltv_ratio": 0.75,
"health_factor_warning": 1.5,
"health_factor_critical": 1.2,
"auto_deleverage_threshold": 1.1,
"notification_channels": ["telegram", "webhook"]
}
}'
When your health factor drops below 1.5, WAIaaS sends a warning notification. At 1.2, it triggers a critical alert. Below 1.1, it can automatically trigger deleveraging actions to prevent liquidation.
Automated Position Management
Beyond monitoring, WAIaaS lets your AI agent automatically manage positions based on health factor changes. Here's how to set up an automated deleveraging strategy:
import { WAIaaSClient } from '@waiaas/sdk';
const client = new WAIaaSClient({
baseUrl: 'http://127.0.0.1:3100',
sessionToken: process.env.WAIAAS_SESSION_TOKEN,
});
async function monitorAndDeleverage() {
const positions = await client.getDeFiPositions();
for (const position of positions.positions) {
if (position.healthFactor < 1.3) {
console.log(`⚠️ Health factor ${position.healthFactor} on ${position.protocol}`);
// Calculate repayment needed to reach safe health factor (>2.0)
const targetHealthFactor = 2.0;
const repaymentNeeded = calculateRepayment(position, targetHealthFactor);
// Execute repayment through WAIaaS
const tx = await client.executeAction('aave-v3', 'repay', {
asset: position.borrowedAsset,
amount: repaymentNeeded.toString(),
walletAddress: position.walletAddress
});
console.log(`🔧 Deleveraging tx: ${tx.id}`);
}
}
}
function calculateRepayment(position, targetHF) {
// Simplified calculation - real implementation should account for
// liquidation thresholds, price impact, and protocol-specific factors
const currentLTV = position.totalBorrowedUsd / position.totalCollateralUsd;
const targetLTV = currentLTV / targetHF;
const repaymentUsd = position.totalBorrowedUsd * (currentLTV - targetLTV);
return repaymentUsd / position.borrowAssetPrice;
}
// Run monitoring every 30 seconds
setInterval(monitorAndDeleverage, 30000);
Cross-Protocol Risk Assessment
WAIaaS aggregates positions across all protocols to give you portfolio-wide risk metrics. This prevents situations where closing a position on one protocol inadvertently triggers liquidation on another due to collateral interdependencies.
The aggregateHealthFactor in the API response considers cross-protocol correlations and shared collateral assets. If you're using the same WETH as collateral on both Aave and Compound, WAIaaS factors this into the risk calculation.
You can also set protocol-specific limits through policies:
curl -X POST http://127.0.0.1:3100/v1/policies \
-H "Content-Type: application/json" \
-H "X-Master-Password: my-secret-password" \
-d '{
"walletId": "<wallet-uuid>",
"type": "LENDING_ASSET_WHITELIST",
"rules": {
"allowed_collateral": [
{"asset": "WETH", "max_ltv": 0.8},
{"asset": "WBTC", "max_ltv": 0.75},
{"asset": "USDC", "max_ltv": 0.9}
],
"allowed_borrow": ["USDC", "DAI", "USDT"],
"protocol_limits": {
"aave-v3": {"max_position_usd": 50000},
"kamino": {"max_position_usd": 25000}
}
}
}'
Integration with Trading Strategies
Health factor monitoring becomes powerful when integrated with your existing trading logic. WAIaaS provides WebSocket subscriptions for real-time position updates:
// Subscribe to position updates
const ws = new WebSocket('ws://127.0.0.1:3100/v1/subscriptions/defi-positions');
ws.on('message', (data) => {
const update = JSON.parse(data);
if (update.type === 'health_factor_change') {
const { protocol, oldHealthFactor, newHealthFactor, change } = update;
if (newHealthFactor < 1.5 && change < -0.1) {
// Health factor dropped significantly - pause new borrows
pauseBorrowingStrategy(protocol);
// Consider taking profits on related positions
await reduceExposure(protocol, 0.2); // Reduce by 20%
}
}
});
Quick Start: Set Up Health Factor Monitoring
Here's how to get health factor monitoring running in under 5 minutes:
- Start WAIaaS daemon:
npm install -g @waiaas/cli
waiaas init
waiaas start
- Create a wallet and session:
waiaas quickset --mode mainnet
# Copy the session token from output
- Check your current DeFi positions:
curl http://127.0.0.1:3100/v1/wallet/defi-positions \
-H "Authorization: Bearer wai_sess_<your-token>"
- Set up health factor alerts:
curl -X POST http://127.0.0.1:3100/v1/policies \
-H "Content-Type: application/json" \
-H "X-Master-Password: <your-password>" \
-d '{
"walletId": "<wallet-id>",
"type": "LENDING_LTV_LIMIT",
"rules": {"health_factor_warning": 1.5}
}'
- Monitor programmatically:
import { WAIaaSClient } from '@waiaas/sdk';
const client = new WAIaaSClient({
sessionToken: 'wai_sess_<your-token>'
});
const positions = await client.getDeFiPositions();
console.log(`Lowest health factor: ${positions.summary.lowestHealthFactor}`);
Advanced: Multi-Wallet Portfolio Monitoring
For institutional strategies managing multiple wallets, WAIaaS supports portfolio-wide risk monitoring. Each wallet can have different risk profiles and health factor thresholds:
# Conservative wallet - early warnings
curl -X POST http://127.0.0.1:3100/v1/policies \
-d '{"walletId": "conservative-wallet", "type": "LENDING_LTV_LIMIT",
"rules": {"health_factor_warning": 2.0, "max_ltv_ratio": 0.6}}'
# Aggressive wallet - higher risk tolerance
curl -X POST http://127.0.0.1:3100/v1/policies \
-d '{"walletId": "aggressive-wallet", "type": "LENDING_LTV_LIMIT",
"rules": {"health_factor_warning": 1.3, "max_ltv_ratio": 0.85}}'
WAIaaS aggregates risk metrics across all wallets, giving you portfolio-wide health factors and correlation analysis between positions.
What's Next
Health factor monitoring is just one piece of comprehensive DeFi risk management. WAIaaS also provides cross-chain bridging, automated rebalancing, and integration with 15 DeFi protocols through a single API.
Ready to protect your DeFi positions from liquidation? Get started at GitHub or learn more at waiaas.ai. Your trading bot's survival depends on staying ahead of health factor drops — don't wait for the next market crash to find out your monitoring isn't fast enough.