Recursive borrowing (looping) on Aave, Compound, Morpho, and Spark lets AI agents amplify DeFi yields by 2x to 5x. Real-time health factor monitoring, automatic deleveraging, and protocol-optimized routing — all via a single API.
The looping strategy multiplies your yield by borrowing against your deposit, reinvesting, and repeating — up to the protocol's max LTV. Each loop adds incremental yield with diminishing capital efficiency.
Deposit your ETH into Aave v3. It earns the base supply APY (currently ~3.5%). Your ETH is now collateral that you can borrow against up to 80% LTV.
Borrow USDC against your ETH. The borrow rate is 4.8%. You now have $2,400 USDC while your ETH earns 3.5% supply APY simultaneously.
Swap USDC → ETH → stETH. Deposit stETH back as additional collateral. It earns Lido staking yield (~4.2%) on top of the Aave supply APY. Health factor resets at a higher effective capital base.
Each additional loop adds ~80% of the previous loop's capital. After 5 loops, your effective exposure is ~4.8x. Net yield after borrow costs: 8–15% vs the base 3.5% — a 2.5–4x amplification.
Higher leverage amplifies both yield and liquidation risk. The Purple Flea API enforces minimum health factors and auto-unwinds before liquidation can occur.
| Leverage | Loops | Effective Capital | Net APY (stETH loop) | Net APY (USDC loop) | Min Health Factor | Liquidation Buffer | Risk Level |
|---|---|---|---|---|---|---|---|
| 1x | 0 (base) | $1,000 | 4.2% | 5.1% | — | — | None |
| 1.5x | 1 | $1,500 | 6.8% | 8.2% | 2.5 | ~38% | Very Low |
| 2x | 2 | $2,000 | 9.1% | 11.4% | 2.0 | ~28% | Low |
| 3x | 3 | $3,000 | 13.8% | 17.2% | 1.6 | ~18% | Moderate |
| 4x | 4 | $4,000 | 18.4% | 22.9% | 1.35 | ~11% | High |
| 5x | 5+ | $5,000 | 22.1% | 27.6% | 1.15 | ~6% | Very High |
* Net APY = (staked yield + supply APY) x leverage minus borrow costs. Liquidation buffer = the % price drop that would trigger liquidation. Auto-unwind triggers at 1.15 health factor minimum.
The classic: deposit ETH, mint stETH via Lido, supply to Aave, borrow ETH, swap to stETH, repeat. Earns staking yield (~4.2%) + Aave supply rewards on 3–5x capital. Net APY: 13–22% at 3–5x leverage.
Supply USDC to Morpho Blue, borrow against it, reinvest in higher-yield USDC strategies (e.g., Spark DSR at 6%), and repeat. Delta-neutral — no ETH price exposure. Net APY: 11–18% at 3x leverage.
Deposit WBTC into Compound v3, borrow USDC, route USDC into stablecoin yield (Spark, AAVE savings), and loop. Your BTC gains supply APY while USDC earns 5–8% separately. Net APY: 8–14% at 2x leverage.
Bridge SOL to Ethereum as stSOL or mSOL, supply to Spark, borrow ETH, convert to stETH, and loop. Cross-chain yield stack: SOL staking + ETH staking + Spark supply. High complexity, highest potential yield.
All endpoints authenticate with X-API-Key: pf_live_... header. All amounts in USDC equivalent unless specified.
The LoopingAgent monitors health factor continuously and unwinds before liquidation. The Purple Flea API streams health factor updates via webhook and triggers automatic deleveraging.
Configure a webhook URL in your agent settings. Purple Flea posts health factor updates every 10 minutes and immediately on rapid drops. Your agent can override auto-unwind if it detects a flash-crash false positive.
When ETH price drops more than 15% in a 4-hour window, the circuit breaker pauses new loops and alerts your agent. Existing positions are maintained but no additional leverage is added until the circuit resets.
Complete Python implementation for recursive borrowing with health factor monitoring and automatic deleveraging.
import requests
import time
import logging
from typing import Optional
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("looping-agent")
BASE = "https://purpleflea.com/api/v1"
API_KEY = "pf_live_your_key_here"
HDR = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
class LoopingAgent:
"""
Recursive borrowing agent with health factor monitoring.
Automatically adjusts leverage and unwinds on risk events.
"""
SAFE_HEALTH = 2.0
WATCH_HEALTH = 1.5
WARN_HEALTH = 1.25
DANGER_HEALTH = 1.15
def __init__(
self,
strategy: str = "steth-loop",
capital_usdc: float = 5000,
target_leverage: float = 3.0,
protocol: str = "aave",
):
self.strategy = strategy
self.capital_usdc = capital_usdc
self.target_leverage = target_leverage
self.protocol = protocol
self.position_id = None
def get_rates(self) -> dict:
"""Fetch current rates for our strategy."""
r = requests.get(f"{BASE}/leverage/rates", headers=HDR, params={
"strategy": self.strategy,
"protocol": self.protocol
})
return r.json()
def open_position(self) -> str:
"""Open the leveraged position and return position_id."""
rates = self.get_rates()
log.info(f"Opening {self.strategy} at {self.target_leverage}x | "
f"projected APY={rates['net_apy_at_leverage'][str(self.target_leverage)]:.1f}%")
r = requests.post(f"{BASE}/leverage/open", headers=HDR, json={
"strategy": self.strategy,
"initial_capital_usdc": self.capital_usdc,
"target_leverage": self.target_leverage,
"protocol": self.protocol,
"auto_unwind_enabled": True
})
data = r.json()
self.position_id = data["position_id"]
log.info(f"Position opened: {self.position_id} | HF={data['health_factor']:.2f} | "
f"liq_price=${data['liquidation_price']:,.0f}")
return self.position_id
def check_health(self) -> dict:
"""Fetch live health factor data."""
r = requests.get(f"{BASE}/leverage/health", headers=HDR,
params={"position_id": self.position_id})
return r.json()
def handle_health(self, hf: float):
"""Take action based on current health factor."""
if hf >= self.SAFE_HEALTH:
log.info(f"HF={hf:.2f} — SAFE, no action")
elif hf >= self.WATCH_HEALTH:
log.warning(f"HF={hf:.2f} — WATCH, monitoring closely")
elif hf >= self.WARN_HEALTH:
log.warning(f"HF={hf:.2f} — WARN, unwind 50%")
requests.post(f"{BASE}/leverage/unwind", headers=HDR, json={
"position_id": self.position_id,
"partial_unwind_pct": 50
})
else:
log.error(f"HF={hf:.2f} — DANGER, emergency full unwind!")
requests.post(f"{BASE}/leverage/unwind", headers=HDR, json={
"position_id": self.position_id,
"partial_unwind_pct": 100
})
self.position_id = None # position closed
def run(self, poll_interval: int = 600):
"""Main monitoring loop. Checks health every 10 minutes."""
self.open_position()
while True:
if not self.position_id:
log.info("Position closed. Waiting 1h before reopening...")
time.sleep(3600)
self.open_position()
continue
health = self.check_health()
hf = health["health_factor"]
dist = health["distance_to_liquidation_pct"]
log.info(f"HF={hf:.3f} | dist_to_liq={dist:.1f}% | "
f"collateral=${health['collateral_value_usd']:,.0f} | "
f"debt=${health['debt_value_usd']:,.0f}")
self.handle_health(hf)
time.sleep(poll_interval)
if __name__ == "__main__":
agent = LoopingAgent(
strategy = "steth-loop",
capital_usdc = 10000,
target_leverage = 3.0,
protocol = "aave"
)
agent.run()
Layer covered call vaults on top of your leveraged positions. Earn 15–35% APY from vault premiums while your loop compounds underneath.
Delta-hedge your leveraged ETH position with a short perpetual on Hyperliquid. Earn yield without directional ETH risk.
Manage collateral across ETH, SOL, BTC, MATIC, BNB, and XMR. Move assets between chains to optimize cross-protocol leverage strategies.
Pay out leveraged yield profits to other agents trustlessly. 1% fee, 15% referral commission. Build multi-agent yield distribution networks.
Register your agent and claim free USDC from the faucet to open your first leveraged position risk-free.