Collateralized Debt Positions (CDPs) are one of DeFi's most powerful primitives—and one of the most underutilized by autonomous AI agents. By locking collateral to mint stablecoins, an agent can deploy capital across multiple yield strategies simultaneously: the collateral earns staking rewards while the borrowed stablecoin earns lending yield. Done correctly, a CDP transforms idle ETH into a two-sided income stream.
This guide covers the three dominant CDP systems—MakerDAO (DAI), Liquity (LUSD), and Reflexer (RAI)—explaining how each works, how collateral ratios and liquidation risk differ, and how an AI agent can automate CDP management. We include a complete Python CDP manager agent at the end.
The Purple Flea Wallet API supports ETH, WBTC, and stablecoin management across all major chains—making it ideal for funding CDP collateral positions and routing borrowed stablecoins into yield strategies. Register your agent to get started.
What Is a CDP?
A Collateralized Debt Position is a smart contract vault where you deposit collateral (ETH, WBTC, staked assets) and borrow a protocol-native stablecoin against it. The key mechanics:
- Collateral ratio (CR): The ratio of collateral value to debt. If ETH is $3,000 and you owe 2,000 DAI, your CR is 150%.
- Liquidation threshold: If CR drops below the minimum, anyone can liquidate your vault—buying your collateral at a discount to cover the debt.
- Stability fee: An annual interest rate on borrowed stablecoins, paid in the protocol's token or the borrowed asset.
- Minting ceiling: Each collateral type has a debt ceiling limiting how much can be borrowed against it globally.
For an AI agent, the CDP loop looks like this: deposit ETH as collateral → borrow DAI → deploy DAI into a yield strategy (lending, LP, yield aggregator) → yield pays the stability fee with profit left over → monitor CR continuously to avoid liquidation.
MakerDAO: DAI and the DSR
MakerDAO is the original CDP protocol and still the largest by DAI supply. It supports dozens of collateral types—from ETH and WBTC to real-world assets (RWAs)—each with its own stability fee and liquidation parameters.
Dai Savings Rate (DSR)
The DSR is MakerDAO's native yield on DAI deposits. It's set by MKR governance and has ranged from 0% to 15% depending on monetary policy. The key insight for agents: you can borrow DAI from your own vault and deposit it into the DSR contract in a single transaction loop, netting the spread between DSR and your vault's stability fee.
When DSR > stability fee, borrowing DAI from your vault and depositing into DSR generates risk-free spread (ignoring liquidation risk). MakerDAO has run this configuration deliberately to bootstrap DAI demand.
MakerDAO Collateral Types
| Collateral | Min CR | Stability Fee | Liquidation Penalty | Debt Ceiling |
|---|---|---|---|---|
| ETH-A | 150% | 6.25% | 13% | 15B DAI |
| ETH-B | 130% | 7.5% | 15% | 1B DAI |
| ETH-C | 175% | 5.5% | 13% | 100B DAI |
| WBTC-A | 150% | 6.75% | 13% | 2B DAI |
| stETH-B | 185% | 5.0% | 15% | 500M DAI |
| RWA-001 | 100% | 4.5% | 0% | 400M DAI |
Liquidation Mechanics in MakerDAO v2
MakerDAO uses a Dutch auction (Liquidations 2.0) for collateral sales. When a vault becomes undercollateralized:
- A keeper calls the
bark()function, placing the vault into liquidation. - The Dutch auction starts at a price above market and decreases over time.
- Arbitrageurs buy collateral with DAI when the auction price is attractive.
- Any remaining DAI debt is covered by the MakerDAO surplus buffer or via MKR dilution.
The liquidation penalty is 13% for ETH-A. This means if you had $1,500 in ETH and $1,000 in DAI debt when liquidated, you lose 13% of the collateral on top of recovering your net equity.
Agent Strategy: Leveraged stETH CDP
One of the most capital-efficient MakerDAO strategies is using liquid staking tokens (stETH, rETH) as collateral. You earn staking yield on the collateral while borrowing against it:
Liquity: LUSD and Zero Stability Fee
Liquity v1 launched in 2021 with a radically different model: ETH-only collateral, no governance, no stability fee (only a one-time borrowing fee), and a minimum collateral ratio of just 110% under normal operation. This makes it the most capital-efficient CDP protocol available.
How Liquity Works
Instead of a stability fee, Liquity charges a one-time fee when you open a Trove (their term for a CDP). This fee is algorithmically set based on recent redemption volume—typically 0.5% to 5% of borrowed LUSD. After that, you pay nothing to hold the position indefinitely.
The protocol has two stability mechanisms:
- Stability Pool: LUSD depositors earn ETH from liquidations as a reward. This creates yield on idle LUSD without lending risk.
- Redemptions: Any LUSD holder can redeem against the lowest-CR Troves at face value, keeping LUSD pegged to $1.
If your Trove has the lowest CR in the system, LUSD holders can redeem against you—you keep the ETH equivalent but lose your position. Agents should maintain CR well above system minimum or sort their Trove position higher in the list.
Liquity Stability Pool Yield
Depositing LUSD in the Stability Pool earns ETH distributions from liquidations plus LQTY token rewards. Historical yields:
| Period | ETH Liquidation Yield | LQTY Rewards | Total APY |
|---|---|---|---|
| High volatility (crash) | 15-40% | 3-8% | 18-48% |
| Low volatility (bull) | 0.5-2% | 1-3% | 1.5-5% |
| Typical market | 3-8% | 2-4% | 5-12% |
For an agent, this creates a compelling loop: open a Trove (borrow LUSD cheaply) → deposit LUSD in Stability Pool → earn ETH and LQTY rewards → compound LUSD from earned ETH → monitor Trove CR continuously.
Liquity v2: Multi-Collateral
Liquity v2 introduced support for liquid staking tokens (stETH, rETH, wstETH) as collateral, expanding the strategy space dramatically. Agents can now use yield-bearing collateral in a zero-stability-fee environment—the highest capital efficiency in DeFi.
Reflexer: RAI and the Floating Peg
Reflexer Protocol introduced RAI—a stablecoin that intentionally does not target $1. Instead, RAI has a "redemption price" that floats based on a PID controller (Proportional-Integral-Derivative), similar to a central bank rate mechanism. This makes RAI the most algorithmically pure stablecoin in existence.
The RAI Redemption Rate
The redemption rate is RAI's equivalent of a stability fee, but it can go negative. If RAI trades above redemption price, the controller sets a negative rate to discourage borrowing. If RAI trades below, the rate goes positive to incentivize minting. This creates a reflexive system where the protocol continuously self-adjusts.
For agents, this means RAI borrowing costs are dynamic and can turn profitable (negative rate = you get paid to borrow). Monitoring the redemption rate and entering positions when it turns negative is an edge case strategy available only to agents—humans rarely track RAI's redemption rate closely enough.
RAI vs DAI: Key Differences
| Feature | DAI (MakerDAO) | RAI (Reflexer) |
|---|---|---|
| Peg target | $1.00 fixed | Floating (~$3.02 currently) |
| Collateral | Multi-asset + RWA | ETH only |
| Stability fee | Fixed by governance | PID-controlled, can go negative |
| Min CR | 150% (ETH-A) | 145% |
| Governance | MKR token | FLX token (minimal governance) |
| Best for agents | Large-scale DAI strategies | Negative-rate arbitrage |
Collateral Ratios and Liquidation Risk
Managing liquidation risk is the core challenge of CDP strategies for agents. Unlike humans who check positions daily, agents can monitor continuously—but they must be programmed with the right buffer zones and emergency actions.
Defining Safe CR Targets
A prudent agent should maintain CR well above the liquidation threshold, with the buffer sized to the volatility of the collateral asset:
| Collateral | Min CR | Conservative Target | Aggressive Target | Emergency Action CR |
|---|---|---|---|---|
| ETH (MakerDAO) | 150% | 200% | 165% | 155% |
| ETH (Liquity) | 110% | 150% | 120% | 115% |
| WBTC | 150% | 210% | 175% | 160% |
| stETH | 185% | 240% | 200% | 190% |
Volatility-Adjusted Buffer Sizing
The required CR buffer depends on how far prices can move before your next monitoring cycle. For an agent monitoring every 5 minutes on a 30-day rolling volatility of ETH (typically 60-80% annualized):
Emergency Actions
An agent CDP manager should have a hierarchy of emergency responses as CR approaches the liquidation threshold:
- Alert: CR drops below Conservative Target → send notification, increase monitoring frequency to 1 minute.
- Partial repay: CR drops below Aggressive Target → withdraw some DAI from yield strategy and repay debt.
- Emergency repay: CR drops below Emergency Action CR → flash-loan repay entire debt, close yield position.
- Self-liquidation: If CR approaches liquidation threshold and flash loan unavailable → accept self-liquidation to preserve equity.
Stability Fee Optimization
Stability fees change based on governance votes (MakerDAO), redemption activity (Liquity), or the PID controller (Reflexer). An agent can optimize across protocols to minimize borrowing costs.
Cross-Protocol Rate Monitoring
The agent should track stability fees across all CDP protocols and actively migrate positions when cheaper borrowing is available. Typical monitoring intervals:
- MakerDAO: Stability fee changes only via governance vote (days to weeks). Check weekly.
- Liquity: One-time fee only at open. Focus on redemption pressure instead. Check hourly.
- Reflexer: PID controller updates every few hours. Check every 30 minutes.
Migration Cost Analysis
Migrating a CDP position incurs gas costs, slippage, and sometimes exit fees. The agent should only migrate when the fee savings exceed migration costs over a reasonable time horizon:
Yield on Borrowed Stablecoins
The stablecoins borrowed from a CDP must be deployed productively to justify the borrowing cost. Here are the main yield venues and their risk profiles:
Stablecoin Yield Venues
| Venue | Asset | Typical APY | Risk Level | Liquidity |
|---|---|---|---|---|
| MakerDAO DSR | DAI | 5-15% | Low | Instant |
| Aave v3 | DAI/USDC/USDT | 3-12% | Low | Instant |
| Compound v3 | USDC | 4-10% | Low | Instant |
| Liquity Stability Pool | LUSD | 5-48% | Medium | Instant |
| Curve 3pool LP | DAI/USDC/USDT | 2-8% | Low | Instant |
| Convex Finance | Various | 6-18% | Medium | 1-7 days |
| Yearn DAI Vault | DAI | 5-15% | Medium | Instant |
| Pendle PT-DAI | DAI | Fixed 6-10% | Low | Via AMM |
Risk-Adjusted Yield Selection
An agent should prefer venues with instant liquidity to enable emergency CDP repayment. Locking stablecoins in illiquid strategies (Convex lock, Pendle PT before maturity) creates a dangerous mismatch: if ETH crashes, the agent cannot quickly repay the CDP without taking a loss on the stablecoin position.
Never lock borrowed stablecoins in illiquid strategies. CDP liquidations happen in minutes; illiquid stablecoin exits can take days. Always maintain at least 50% of borrowed stablecoins in instantly withdrawable venues.
Purple Flea Wallet for Collateral Management
The Purple Flea Wallet API provides multi-chain balance management with ETH, WBTC, BNB, and stablecoin support—exactly what CDP collateral strategies require. Key capabilities for CDP agents:
- ETH balance monitoring: Track available ETH for collateral top-ups in real time.
- Multi-chain USDC routing: Move stablecoins from Arbitrum lending back to Ethereum for CDP repayment.
- Transaction signing: Sign CDP vault interactions without manual private key management.
- Balance webhooks: Receive alerts when ETH balance drops below collateral top-up threshold.
import requests AGENT_TOKEN = "pf_live_your_token_here" BASE_URL = "https://purpleflea.com/api" def get_eth_balance(): r = requests.get( f"{BASE_URL}/wallet/balance", headers={"Authorization": f"Bearer {AGENT_TOKEN}"}, params={"asset": "ETH", "chain": "ethereum"} ) return r.json()["balance"] def check_cdp_safety(eth_price, collateral_eth, debt_dai, min_cr=1.65): current_cr = (collateral_eth * eth_price) / debt_dai if current_cr < min_cr: return {"action": "top_up", "cr": current_cr} return {"action": "none", "cr": current_cr}
Python CDP Manager Agent
The following is a complete Python CDP manager that monitors a MakerDAO ETH-A vault, manages collateral ratios, and routes borrowed DAI into the DSR. It uses web3.py for on-chain interaction and the Purple Flea Wallet API for balance management.
""" CDP Manager Agent for MakerDAO ETH-A Vault - Monitors collateral ratio continuously - Auto top-up collateral from Purple Flea wallet - Routes DAI to DSR for yield - Emergency repay if CR approaches liquidation """ import asyncio, time, logging from web3 import Web3 from web3.middleware import geth_poa_middleware import requests logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') log = logging.getLogger("cdp-agent") # --- Configuration --- RPC_URL = "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY" AGENT_PK = "0xYOUR_PRIVATE_KEY" PF_TOKEN = "pf_live_your_token_here" PF_BASE = "https://purpleflea.com/api" # MakerDAO contract addresses (mainnet) VAT_ADDR = "0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B" SPOT_ADDR = "0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3" JUG_ADDR = "0x19c0976f590D67707E62397C87829d896Dc0f1F" DAI_JOIN = "0x9759A6Ac90977b93B58547b4A71c78317f391A28" POT_ADDR = "0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7" # DSR ILK_ETH_A = b"ETH-A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" # Strategy parameters TARGET_CR = 2.00 # 200% target collateral ratio WARNING_CR = 1.70 # 170% trigger partial repay EMERGENCY_CR = 1.55 # 155% trigger emergency repay MONITOR_SECS = 300 # poll every 5 minutes w3 = Web3(Web3.HTTPProvider(RPC_URL)) account = w3.eth.account.from_key(AGENT_PK) class CDPAgent: def __init__(self, vault_id: int): self.vault_id = vault_id self.vat = self._load_contract(VAT_ADDR, "vat_abi.json") self.spot = self._load_contract(SPOT_ADDR, "spot_abi.json") self.pot = self._load_contract(POT_ADDR, "pot_abi.json") def _load_contract(self, addr, abi_file): import json with open(abi_file) as f: abi = json.load(f) return w3.eth.contract(address=addr, abi=abi) def get_vault_state(self): # Returns (collateral_wad, debt_wad, spot_price) urn = self.vat.functions.urns(ILK_ETH_A, account.address).call() ilk = self.vat.functions.ilks(ILK_ETH_A).call() ink, art = urn[0], urn[1] # collateral ink, normalized debt art rate = ilk[1] # accumulated rate (1e27) spot_data = self.spot.functions.ilks(ILK_ETH_A).call() spot_price = spot_data[1] / 1e27 # collateralization-adjusted ETH price collateral_eth = ink / 1e18 debt_dai = (art * rate) / (1e45) # convert rad to DAI eth_price = spot_price * 1.5 # spot = price / liq_ratio return collateral_eth, debt_dai, eth_price def get_current_cr(self): col, debt, price = self.get_vault_state() if debt == 0: return float('inf') return (col * price) / debt def get_dsr_rate(self): dsr = self.pot.functions.dsr().call() # ray (1e27) # Convert ray per-second to APY return (dsr / 1e27) ** (365 * 24 * 3600) - 1 def get_stability_fee(self): import json with open("jug_abi.json") as f: abi = json.load(f) jug = w3.eth.contract(address=JUG_ADDR, abi=abi) ilk_data = jug.functions.ilks(ILK_ETH_A).call() duty = ilk_data[0] # ray return (duty / 1e27) ** (365 * 24 * 3600) - 1 def pf_eth_balance(self): r = requests.get( f"{PF_BASE}/wallet/balance", headers={"Authorization": f"Bearer {PF_TOKEN}"}, params={"asset": "ETH"} ) return float(r.json().get("balance", 0)) def top_up_collateral(self, eth_amount: float): log.info(f"Topping up {eth_amount} ETH collateral") # Build ETH-Join call to add collateral # Implementation: call GemJoin.join() then Vat.frob() amount_wei = w3.to_wei(eth_amount, 'ether') # ... (contract interaction via web3) pass def partial_repay(self, dai_amount: float): log.info(f"Repaying {dai_amount} DAI to improve CR") # Withdraw DAI from DSR → repay vault # ... (contract interaction via web3) pass async def monitor_loop(self): while True: try: cr = self.get_current_cr() col, debt, price = self.get_vault_state() dsr = self.get_dsr_rate() fee = self.get_stability_fee() spread = dsr - fee log.info(f"CR={cr:.2%} collateral={col:.4f}ETH debt={debt:.2f}DAI " f"DSR={dsr:.2%} fee={fee:.2%} spread={spread:.2%}") if cr < EMERGENCY_CR: log.warning("EMERGENCY: CR near liquidation. Repaying all debt!") self.partial_repay(debt) elif cr < WARNING_CR: # Repay enough to restore TARGET_CR target_debt = (col * price) / TARGET_CR repay_amt = debt - target_debt log.warning(f"WARNING: CR low. Repaying {repay_amt:.2f} DAI") self.partial_repay(repay_amt) elif spread < 0: log.info("DSR < stability fee. Consider reducing DAI position.") except Exception as e: log.error(f"Monitor loop error: {e}") await asyncio.sleep(MONITOR_SECS) if __name__ == "__main__": agent = CDPAgent(vault_id=12345) asyncio.run(agent.monitor_loop())
Advanced CDP Strategies
Recursive Leverage (Looping)
Recursive CDP loops compound exposure by repeatedly borrowing stablecoins and converting them back to ETH as additional collateral. Each loop increases effective leverage. With flash loans, this can be done in a single transaction:
- Flash borrow X ETH from Aave.
- Deposit all ETH (original + flash) into CDP vault.
- Borrow DAI at target CR against full collateral.
- Swap DAI to ETH on DEX.
- Repay flash loan with ETH proceeds.
- Net result: leveraged ETH position with CDP debt.
Recursive loops amplify liquidation risk proportionally to leverage. A 3x leveraged ETH CDP can be liquidated by a ~20% ETH price drop. Only agents with robust monitoring and emergency repay mechanisms should use leverage above 1.5x.
Arbitraging Protocol Fee Differences
When MakerDAO stability fees differ significantly from Liquity's effective borrowing cost, an agent can profit by migrating debt between protocols. The migration trade:
- If MakerDAO ETH-A fee (6.25%) > Liquity effective cost (0.5% one-time / 12 months = ~0.5% annual): migrate DAI debt to Liquity Trove.
- Use a flash loan to close the MakerDAO vault and open the Liquity Trove atomically.
- Net saving: 5.75% APY on outstanding debt.
Negative RAI Rate Farming
When Reflexer's PID controller sets a negative redemption rate (meaning you get paid to borrow RAI), agents can open RAI vaults and earn the negative rate as income. The strategy:
- Monitor Reflexer's
oracleRelayer.redemptionRate(). - When it goes negative (< 1e27 in ray units), open an ETH vault and borrow maximum RAI.
- Deploy RAI into yield venues (Curve, lending protocols).
- Earn: RAI lending yield + negative rate income (you pay less back over time).
Risk Management Summary
| Risk | Mitigation | Agent Action |
|---|---|---|
| ETH price crash | Conservative CR target | Auto top-up or partial repay |
| Gas spike | Keep ETH reserve for gas | Pre-fund gas wallet via Purple Flea |
| Stablecoin depeg | Diversify stablecoin venues | Monitor peg deviation alerts |
| Smart contract bug | Use battle-tested protocols only | Only MakerDAO / Liquity v1 |
| Oracle manipulation | Use protocols with multiple oracle sources | Pause CDP if oracle deviation >2% |
| Redemption (Liquity) | Maintain CR above 150% | Monitor Trove position in queue |
| Stablecoin illiquidity | 50% instantly withdrawable | Split between DSR and Aave |
Getting Started with Purple Flea
CDP strategies require reliable multi-chain capital management. The Purple Flea Wallet API gives agents programmatic access to ETH and stablecoin balances for funding and managing CDP positions:
- Register your agent to get API credentials.
- Fund your Purple Flea wallet with ETH for CDP collateral.
- Use the Wallet API to monitor and move funds programmatically.
- Combine with the Trading API to hedge ETH collateral exposure with short perps.
New agents can claim free credits via the Purple Flea Faucet to test API calls before deploying real capital into CDP strategies.
Conclusion
CDPs are among the highest-leverage tools in an AI agent's DeFi arsenal—in the sense of capital efficiency, not just leverage. A well-managed CDP enables an agent to earn yield on two pools of capital simultaneously: the collateral (via staking) and the borrowed stablecoins (via lending or liquidity provision).
The key differentiators for agents vs. human CDP managers are: continuous monitoring (vs. daily checks), automated emergency response (vs. manual panic selling), and systematic rate optimization across protocols (vs. set-and-forget). MakerDAO suits large-scale DAI strategies with governance-mediated rate changes. Liquity offers zero ongoing fees for long-duration positions. Reflexer provides negative-rate arbitrage windows unique to its PID mechanism.
Use the Purple Flea Wallet API to keep your CDP collateral topped up automatically, and the Trading API to hedge your collateral's price risk. Together, they give autonomous agents the infrastructure to run CDP strategies that would be operationally impossible for human managers.