Autonomous Yield Strategies for AI Agents

DeFi Yield Agent
Powered by Purple Flea

Your agent can earn yield around the clock without relying on traditional DeFi protocols. Purple Flea's Trading API unlocks Hyperliquid perpetuals funding rates — the highest on-chain yield available today — while the Wallet API handles cross-chain capital movement for basis trading and position management.

0.05–0.3% Funding rate / day
18–110% Annualised yield
8h Funding interval
3 Yield strategies

Three Ways Your Agent Earns

Purple Flea exposes two APIs that together cover every layer of a DeFi yield stack. The Trading API connects to Hyperliquid perpetuals; the Wallet API moves tokens cross-chain. Combined, your agent can run all three strategies simultaneously.

Highest yield

Funding Rate Farming

Open a short perpetual on Hyperliquid and collect funding payments every 8 hours when the rate is positive. BTC, ETH, and SOL perps routinely pay 0.05–0.3%/day during bull markets — that's 18–110% annualised on a market-neutral basis. Purple Flea's Trading API handles position entry, monitoring, and exit in a single authenticated REST call.

0.05–0.3%
Per day
3× leverage
Typical size
Market-neutral
Direction risk
Market-neutral

Basis Trading

Hold spot (via Wallet API) and short the perp (via Trading API) in equal notional size. The spread between spot and perpetual — the "basis" — converges at delivery, and funding accrues on the short leg. The position is fully delta-neutral: spot gains offset perp losses, and funding is pure profit. Ideal for agents that hold crypto inventory already.

Delta-zero
Price exposure
Wallet + Trading
APIs used
Low
Liquidation risk
Passive

Referral Yield

Agents that bring other agents onto Hyperliquid through Purple Flea's referral system earn 10–20% of the fees those agents pay — indefinitely. If you're building a multi-agent system or an agent marketplace, every agent you register under your referral code generates passive yield that requires zero ongoing capital.

10–20%
Fee share
Zero
Capital required
Perpetual
Duration

Funding Rates vs Traditional DeFi

Hyperliquid funding rates compare favourably to every yield source in DeFi, and they carry fundamentally different risk characteristics — no smart contract exposure, no impermanent loss, and instant liquidity.

Strategy Source Typical APY Direction risk Liquidity Risk level
Funding rate farming Hyperliquid (via Purple Flea) 18–110% None (short + hedged) Instant Medium
Basis trading Spot + Hyperliquid perp 12–60% Delta-neutral Instant Low
Referral yield Purple Flea program Unbounded None Daily Very low
Aave USDC lending Ethereum / Polygon 3–12% None Instant Low
Uniswap v3 LP (volatile) Ethereum 8–40% Impermanent loss Instant High
ETH liquid staking Lido / Rocket Pool 3–4% None Seconds Low
SOL staking Solana validators 6–8% None ~2 days Low
Kamino USDC Solana 5–20% None Instant Medium

Funding Rate Farming Bot

A complete Python agent that registers with Purple Flea's Trading API, polls BTC, ETH, and SOL funding rates every 8 hours, opens a 3x short when the rate exceeds 0.05%, closes when it drops below 0.01%, and tracks cumulative yield.

funding_rate_bot.py
import time, requests, logging from datetime import datetime, timezone from dataclasses import dataclass, field from typing import Optional logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) # ── Configuration ───────────────────────────────────────────────────────────── PURPLE_FLEA_BASE = "https://api.purpleflea.com" MARKETS = ["BTC-PERP", "ETH-PERP", "SOL-PERP"] LEVERAGE = 3 # 3x short POSITION_USD = 5_000 # notional per market OPEN_THRESHOLD = 0.0005 # open short when funding > 0.05 % CLOSE_THRESHOLD = 0.0001 # close short when funding < 0.01 % POLL_INTERVAL_SEC = 8 * 3600 # every 8 hours (one funding epoch) # ── Data structures ──────────────────────────────────────────────────────────── @dataclass class Position: market: str side: str # "short" size_usd: float entry_price: float opened_at: datetime funding_collected: float = 0.0 @dataclass class YieldLedger: total_funding_usd: float = 0.0 epochs_collected: int = 0 positions_opened: int = 0 positions_closed: int = 0 log: list = field(default_factory=list) def record(self, market, rate, payout_usd): self.total_funding_usd += payout_usd self.epochs_collected += 1 self.log.append({ "ts": datetime.now(timezone.utc).isoformat(), "market": market, "rate": rate, "payout_usd": payout_usd, }) # ── API client ───────────────────────────────────────────────────────────────── class PurpleFleaTrading: def __init__(self, api_key: str): self.session = requests.Session() self.session.headers.update({ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", }) self.base = PURPLE_FLEA_BASE def register(self) -> dict: """Register this agent instance with Purple Flea Trading API.""" r = self.session.post(f"{self.base}/trading/register", json={ "agent_name": "funding-rate-farmer", "description": "Autonomous funding rate harvesting bot", "markets": MARKETS, }) r.raise_for_status() return r.json() def funding_rate(self, market: str) -> float: """Return current 8-hour funding rate for a perp market.""" r = self.session.get(f"{self.base}/trading/funding", params={"market": market}) r.raise_for_status() return float(r.json()["funding_rate"]) # e.g. 0.00063 def open_short(self, market: str, size_usd: float, leverage: int) -> dict: r = self.session.post(f"{self.base}/trading/order", json={ "market": market, "side": "sell", "type": "market", "size_usd": size_usd, "leverage": leverage, "reduce_only": False, }) r.raise_for_status() return r.json() def close_position(self, market: str) -> dict: r = self.session.post(f"{self.base}/trading/close", json={"market": market}) r.raise_for_status() return r.json() # ── Main agent loop ──────────────────────────────────────────────────────────── class FundingRateAgent: def __init__(self, api_key: str): self.api = PurpleFleaTrading(api_key) self.ledger = YieldLedger() self.open_positions: dict[str, Position] = {} def start(self): logging.info("Registering agent with Purple Flea Trading API...") reg = self.api.register() logging.info(f"Registered. Agent ID: {reg.get('agent_id')}") while True: self._tick() logging.info( f"Cycle complete. Cumulative yield: " f"${self.ledger.total_funding_usd:,.2f} USD " f"across {self.ledger.epochs_collected} epochs." ) time.sleep(POLL_INTERVAL_SEC) def _tick(self): for market in MARKETS: try: rate = self.api.funding_rate(market) logging.info(f" {market:12s} funding={rate:.4%}") if market in self.open_positions: pos = self.open_positions[market] payout = pos.size_usd * rate self.ledger.record(market, rate, payout) pos.funding_collected += payout logging.info(f" Collected ${payout:.2f} total=${pos.funding_collected:.2f}") if rate < CLOSE_THRESHOLD: logging.info(f" Rate below close threshold — closing {market}") self.api.close_position(market) del self.open_positions[market] self.ledger.positions_closed += 1 elif rate >= OPEN_THRESHOLD: logging.info(f" Rate above open threshold — opening {LEVERAGE}x short on {market}") resp = self.api.open_short(market, POSITION_USD, LEVERAGE) self.open_positions[market] = Position( market=market, side="short", size_usd=POSITION_USD, entry_price=float(resp["fill_price"]), opened_at=datetime.now(timezone.utc), ) self.ledger.positions_opened += 1 except Exception as e: logging.error(f"Error processing {market}: {e}") if __name__ == "__main__": agent = FundingRateAgent(api_key="pf_sk_YOUR_KEY_HERE") agent.start()

Basis Trading: Both Legs

Basis trading requires two simultaneous positions: a spot long (funded via the Wallet API) and a perpetual short (via the Trading API). Both legs must be equal notional size to achieve true delta-neutrality.

basis_trade.py
import requests, logging from dataclasses import dataclass log = logging.getLogger("basis_trade") # ── Wallet API: buy and hold spot ────────────────────────────────────────────── class WalletAPI: """Purple Flea Wallet API — cross-chain token movements and spot swaps.""" def __init__(self, api_key: str): self.s = requests.Session() self.s.headers["Authorization"] = f"Bearer {api_key}" self.base = "https://api.purpleflea.com/wallet" def buy_spot(self, token: str, amount_usd: float, chain: str = "ethereum") -> dict: """Buy {token} worth {amount_usd} USD on {chain} via Purple Flea.""" r = self.s.post(f"{self.base}/swap", json={ "from_token": "USDC", "to_token": token, "amount_usd": amount_usd, "chain": chain, "slippage": 0.005, }) r.raise_for_status() return r.json() def sell_spot(self, token: str, amount_usd: float, chain: str = "ethereum") -> dict: """Sell {token} back to USDC to close the spot leg.""" r = self.s.post(f"{self.base}/swap", json={ "from_token": token, "to_token": "USDC", "amount_usd": amount_usd, "chain": chain, "slippage": 0.005, }) r.raise_for_status() return r.json() def balance(self, token: str, chain: str = "ethereum") -> float: r = self.s.get(f"{self.base}/balance", params={"token": token, "chain": chain}) r.raise_for_status() return float(r.json()["balance_usd"]) # ── Trading API: short the perp ──────────────────────────────────────────────── class TradingAPI: """Purple Flea Trading API — Hyperliquid perpetuals.""" def __init__(self, api_key: str): self.s = requests.Session() self.s.headers["Authorization"] = f"Bearer {api_key}" self.base = "https://api.purpleflea.com/trading" def open_short(self, market: str, size_usd: float) -> dict: """Open 1x short perp — no leverage for basis, delta-neutral.""" r = self.s.post(f"{self.base}/order", json={ "market": market, "side": "sell", "type": "market", "size_usd": size_usd, "leverage": 1, }) r.raise_for_status() return r.json() def close_short(self, market: str) -> dict: r = self.s.post(f"{self.base}/close", json={"market": market}) r.raise_for_status() return r.json() def funding_rate(self, market: str) -> float: r = self.s.get(f"{self.base}/funding", params={"market": market}) r.raise_for_status() return float(r.json()["funding_rate"]) # ── Basis trade: open both legs ──────────────────────────────────────────────── @dataclass class BasisPosition: token: str notional_usd: float spot_tx: dict perp_tx: dict funding_collected: float = 0.0 def open_basis_trade( wallet: WalletAPI, trading: TradingAPI, token: str, # "BTC", "ETH", "SOL" notional_usd: float, # equal size on both legs chain: str = "ethereum", ) -> BasisPosition: market = f"{token}-PERP" log.info(f"Opening basis trade on {token}: ${notional_usd:,.0f} each leg") # Leg 1: buy spot via Wallet API spot = wallet.buy_spot(token, notional_usd, chain) log.info(f" Spot leg opened: tx={spot.get('tx_hash')}") # Leg 2: short perp via Trading API (1x = delta-neutral with spot) perp = trading.open_short(market, notional_usd) log.info(f" Perp leg opened: fill_price={perp.get('fill_price')}") return BasisPosition(token=token, notional_usd=notional_usd, spot_tx=spot, perp_tx=perp) def close_basis_trade( wallet: WalletAPI, trading: TradingAPI, pos: BasisPosition, chain: str = "ethereum", ): market = f"{pos.token}-PERP" log.info(f"Closing basis trade on {pos.token}. Funding collected: ${pos.funding_collected:.2f}") # Close perp first to avoid naked exposure during liquidation window trading.close_short(market) wallet.sell_spot(pos.token, pos.notional_usd, chain) # ── Example usage ────────────────────────────────────────────────────────────── if __name__ == "__main__": KEY = "pf_sk_YOUR_KEY_HERE" wallet = WalletAPI(KEY) trading = TradingAPI(KEY) # Open a $10k ETH basis trade pos = open_basis_trade(wallet, trading, token="ETH", notional_usd=10_000) print(f"Basis position open: {pos}")

Strategy Risk Analysis

Each strategy has a distinct risk / reward profile. Understanding the tail risks before your agent allocates capital is essential — especially for leveraged funding rate farming where rapid funding rate reversals can trigger liquidations.

Funding Rate Farming

3x short perp
Expected daily yield0.05–0.3%
Annual (mid estimate)~65% APY
Price direction riskYes (short)
Liquidation riskYes at 3x
Funding reversalPays instead of earns
Smart contract riskNone (CEX)
MitigationAuto-close at <0.01%

Basis Trading

Long spot + short perp
Expected daily yield0.03–0.2%
Annual (mid estimate)~40% APY
Price direction riskDelta-neutral
Liquidation riskLow (1x perp)
Spot custody riskIf Wallet API fails
Leg mismatch riskPartial fill slippage
MitigationOpen perp first, hedge after

Referral Yield

Passive fee share
Expected yield10–20% of sub-fees
Capital at riskZero
Direction riskNone
Downside scenarioSub-agents go inactive
Platform riskProgram terms change
Upside scenarioScales with sub count
MitigationDiversify sub-agent activity

Tracking Yield for Tax Purposes

Funding payments received on perpetual positions are typically treated as ordinary income in most jurisdictions — similar to interest income — and should be recorded at the USD value at the time each 8-hour settlement occurs. Your agent should log every funding payment with a UTC timestamp, the market, the rate, and the USD equivalent.

Basis trades introduce two separate cost-basis events: the spot purchase and the perp position. When you close the spot leg, the gain or loss is calculated against the original purchase price. Funding collected on the perp short is separate income. These are not netted against each other for tax purposes in most regulatory frameworks.

What to log per epoch

  • Timestamp (UTC ISO-8601)
  • Market (e.g. BTC-PERP)
  • Funding rate (8-hour, as a decimal)
  • Notional position size (USD)
  • Funding payment received (USD)
  • Cumulative funding to date (USD)
  • Open / close events with fill prices

The YieldLedger dataclass in the funding bot above captures all of this. Export ledger.log as a CSV at the end of each quarter and pass it to your accountant or tax software.

Disclaimer: This is not tax advice. Tax treatment of DeFi yield varies significantly by jurisdiction. Consult a qualified tax professional familiar with crypto assets before filing. Your agent should keep immutable logs — blockchain records are auditable evidence.


Auto-Reinvesting Yield

Funding payments settle in USDC every 8 hours. Once accumulated yield exceeds a minimum threshold, your agent can auto-reinvest by increasing position size — compounding the yield back into the strategy.

compound_yield.py
# ── Compound: reinvest funding into larger positions ─────────────────────────── COMPOUND_THRESHOLD_USD = 50 # only reinvest once $50 has accumulated COMPOUND_FRACTION = 0.8 # keep 20% as buffer; reinvest 80% def maybe_compound(agent: FundingRateAgent): """ Called after each funding epoch. If accumulated yield exceeds the threshold, resize open positions upward to compound the returns. """ undeployed = agent.ledger.total_funding_usd # simplified: track undeployed cash if undeployed < COMPOUND_THRESHOLD_USD: return # not enough to compound yet reinvest = undeployed * COMPOUND_FRACTION per_market = reinvest / len(agent.open_positions) if agent.open_positions else 0 log.info(f"Compounding ${reinvest:.2f} across {len(agent.open_positions)} open positions") for market, pos in agent.open_positions.items(): if per_market > 10: # min order size resp = agent.api.open_short(market, per_market, LEVERAGE) pos.size_usd += per_market log.info(f" Increased {market} position by ${per_market:.2f} → total ${pos.size_usd:.2f}") # Reset the undeployed counter (in a real system, track cash balance separately) agent.ledger.total_funding_usd *= (1 - COMPOUND_FRACTION) # ── Effect of compounding on annual returns ──────────────────────────────────── def compound_projection(daily_rate: float, principal: float, days: int) -> None: """Print balance over time with and without compounding.""" simple = principal * (1 + daily_rate * days) compound = principal * ((1 + daily_rate) ** days) print(f"Principal: ${principal:,.0f} | Daily rate: {daily_rate:.3%} | Days: {days}") print(f" Simple → ${simple:,.2f} (gain: ${simple-principal:,.2f})") print(f" Compound → ${compound:,.2f} (gain: ${compound-principal:,.2f})") print(f" Compounding edge: ${compound-simple:,.2f}") # $10,000 at 0.1%/day for 365 days compound_projection(0.001, 10_000, 365) # Simple → $13,650.00 (gain: $3,650.00) # Compound → $14,430.77 (gain: $4,430.77) # Compounding edge: $780.77

Suggested Strategy Mix

No single strategy is optimal in all market conditions. The suggested allocation below balances yield maximisation during high-funding environments with resilience when rates collapse.

Funding Rate Farming (BTC/ETH/SOL) 50%
Basis Trading (delta-neutral) 30%
Cash / USDC (dry powder) 15%
Referral yield compounding 5%

Allocation logic

Funding rate farming gets the largest share because it has the highest risk-adjusted yield when markets are trending. But it carries short-side price risk: if BTC pumps 10% in an hour, the unrealised loss on the 3x short exceeds the weeks of funding collected. The 15% cash reserve exists to top up margin and avoid liquidation.

Basis trading (30%) provides a lower-volatility floor. Since both legs move together, the PnL is smoother and survives bear markets where funding rates collapse. It earns less in bull markets but does not blow up.

In practice, your agent should shift allocation dynamically: increase funding farming when rates exceed 0.1%/day; increase basis trading when rates are below 0.05%/day; increase cash when volatility spikes above 5% daily range.


Related Guides

Build an agent that
earns while it thinks.

Register once. Earn funding every 8 hours. No KYC. No minimums.