Guide

CDP Strategies for AI Agents: MakerDAO, Liquity, and Collateralized Debt Positions

March 6, 2026 Purple Flea Research Team 22 min read

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.

Purple Flea Wallet

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.

150%
MakerDAO min ratio
110%
Liquity min ratio
145%
Reflexer min ratio
0%
Liquity stability fee

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.

CDP Profitability Formula
net_yield = stablecoin_yield - stability_fee - liquidation_premium * liquidation_probability

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.

DSR Arbitrage

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-A150%6.25%13%15B DAI
ETH-B130%7.5%15%1B DAI
ETH-C175%5.5%13%100B DAI
WBTC-A150%6.75%13%2B DAI
stETH-B185%5.0%15%500M DAI
RWA-001100%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:

  1. A keeper calls the bark() function, placing the vault into liquidation.
  2. The Dutch auction starts at a price above market and decreases over time.
  3. Arbitrageurs buy collateral with DAI when the auction price is attractive.
  4. 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:

Leveraged stETH Strategy Return
return = stETH_APY + (DAI_deployed_yield - stability_fee) * LTV_ratio = 4.2% + (8% - 5.0%) * 0.54 = 4.2% + 1.62% = 5.82% net APY

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.
Redemption Risk

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:

PeriodETH Liquidation YieldLQTY RewardsTotal APY
High volatility (crash)15-40%3-8%18-48%
Low volatility (bull)0.5-2%1-3%1.5-5%
Typical market3-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.

RAI PID Controller
rate_change = Kp * (market_price - redemption_price) + Ki * integral(market_price - redemption_price, dt) new_redemption_rate = current_rate + rate_change

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

FeatureDAI (MakerDAO)RAI (Reflexer)
Peg target$1.00 fixedFloating (~$3.02 currently)
CollateralMulti-asset + RWAETH only
Stability feeFixed by governancePID-controlled, can go negative
Min CR150% (ETH-A)145%
GovernanceMKR tokenFLX token (minimal governance)
Best for agentsLarge-scale DAI strategiesNegative-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:

CollateralMin CRConservative TargetAggressive TargetEmergency Action CR
ETH (MakerDAO)150%200%165%155%
ETH (Liquity)110%150%120%115%
WBTC150%210%175%160%
stETH185%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):

5-Minute VaR Buffer
daily_vol = annual_vol / sqrt(365) = 75% / 19.1 = 3.93% 5min_vol = daily_vol / sqrt(288) = 3.93% / 16.97 = 0.23% 3-sigma_5min = 3 * 0.23% = 0.69% # For safety, add buffer above liquidation threshold: min_safe_CR = liquidation_CR * (1 + 3-sigma_5min * safety_multiplier) = 150% * (1 + 0.69% * 3) = 153.1%

Emergency Actions

An agent CDP manager should have a hierarchy of emergency responses as CR approaches the liquidation threshold:

  1. Alert: CR drops below Conservative Target → send notification, increase monitoring frequency to 1 minute.
  2. Partial repay: CR drops below Aggressive Target → withdraw some DAI from yield strategy and repay debt.
  3. Emergency repay: CR drops below Emergency Action CR → flash-loan repay entire debt, close yield position.
  4. 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:

Migration Break-Even Calculation
migration_cost = gas_fees + slippage + exit_penalties annual_saving = (old_rate - new_rate) * debt_outstanding break_even_days = (migration_cost / annual_saving) * 365 # Migrate only if break_even_days < 30 (recover in <1 month)

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

VenueAssetTypical APYRisk LevelLiquidity
MakerDAO DSRDAI5-15%LowInstant
Aave v3DAI/USDC/USDT3-12%LowInstant
Compound v3USDC4-10%LowInstant
Liquity Stability PoolLUSD5-48%MediumInstant
Curve 3pool LPDAI/USDC/USDT2-8%LowInstant
Convex FinanceVarious6-18%Medium1-7 days
Yearn DAI VaultDAI5-15%MediumInstant
Pendle PT-DAIDAIFixed 6-10%LowVia 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.

Liquidity Mismatch Risk

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.
Purple Flea Wallet: CDP Collateral Check
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.

Python: Complete CDP Manager Agent
"""
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:

  1. Flash borrow X ETH from Aave.
  2. Deposit all ETH (original + flash) into CDP vault.
  3. Borrow DAI at target CR against full collateral.
  4. Swap DAI to ETH on DEX.
  5. Repay flash loan with ETH proceeds.
  6. Net result: leveraged ETH position with CDP debt.
Leverage Risk Warning

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

RiskMitigationAgent Action
ETH price crashConservative CR targetAuto top-up or partial repay
Gas spikeKeep ETH reserve for gasPre-fund gas wallet via Purple Flea
Stablecoin depegDiversify stablecoin venuesMonitor peg deviation alerts
Smart contract bugUse battle-tested protocols onlyOnly MakerDAO / Liquity v1
Oracle manipulationUse protocols with multiple oracle sourcesPause CDP if oracle deviation >2%
Redemption (Liquity)Maintain CR above 150%Monitor Trove position in queue
Stablecoin illiquidity50% instantly withdrawableSplit 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.
Faucet for New Agents

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.