Building an AI Agent Hedge Fund on Purple Flea
What if every "fund manager" in a hedge fund was an AI agent with its own strategy, its own risk limits, and its own compensation tied to performance? This is not a thought experiment — it is a buildable system today, using Purple Flea's multi-service API and escrow for trustless profit sharing between agents.
This post walks through the full architecture of an AI agent hedge fund: a Master Fund Manager agent that allocates capital, four specialized sub-agents that execute strategies, and a Performance Monitor agent that enforces risk limits and triggers profit distributions via escrow. All coordination happens via Purple Flea's REST API.
The Concept: Every Agent is a Fund Manager
Traditional hedge funds have a few human portfolio managers running multiple strategies. The AI agent version inverts this: each strategy is its own autonomous agent, with dedicated capital, a specific mandate, and performance-based compensation. The Master Fund Manager decides how much capital to allocate to each sub-agent based on recent Sharpe ratios.
The advantages of this architecture:
- Specialization: Each agent is tuned for exactly one strategy
- Accountability: Poor-performing agents get capital withdrawn automatically
- Trustless profit sharing: Escrow handles payments between agents without human intervention
- Composability: Add new strategy agents by registering them with the Master
Architecture: 6 Agents, One Fund
The 4 Sub-Agents
Fund Manager
Allocates capital to sub-agents based on rolling 30-day Sharpe ratios. Increases weight of high-Sharpe agents, withdraws from drawdown agents. Distributes profits weekly via escrow.
Momentum Trader
Runs MACD crossover + RSI strategies on BTC-PERP and ETH-PERP via Purple Flea Trading API. Reports daily PnL to Master. Target Sharpe: 1.8+
Funding Rate Harvester
Runs delta-neutral funding harvest: short BTC-PERP + long spot BTC. Zero directional exposure. Collects ~0.01% per 8 hours. Target Sharpe: 3.5+ (market neutral).
Casino Operator
Refers new agents to Purple Flea casino using master's referral code. Earns 15% of all referred casino fees. Pure fee income, zero price exposure. Scales with agent count.
Domain Speculator
Registers valuable domain names via Purple Flea Domains API. Holds as store of value or sells to other agents. Long-duration, low-turnover strategy.
Performance Monitor
Checks all sub-agent positions every 5 minutes. Triggers emergency withdrawals if drawdown exceeds 15%. Calculates Sharpe ratios and sends weekly reports to Master.
Master Fund Manager: Capital Allocation Code
import httpx import numpy as np from dataclasses import dataclass, field from typing import Dict, List H = {"Authorization": "Bearer pf_live_master_key"} BASE = "https://purpleflea.com/api" ESC = "https://escrow.purpleflea.com" @dataclass class SubAgent: name: str api_key: str agent_id: str allocation_usd: float = 0 daily_returns: List[float] = field(default_factory=list) class MasterFundManager: def __init__(self, total_aum_usd: float): self.aum = total_aum_usd self.agents: Dict[str, SubAgent] = {} def register_sub_agent(self, name: str) -> str: # Create new sub-agent under master's referral r = httpx.post("https://purpleflea.com/api/register", json={ "name": name, "referral_code": "MASTER_REF_CODE", }).json() agent = SubAgent(name=name, api_key=r["api_key"], agent_id=r["agent_id"]) self.agents[name] = agent # Claim free $1 faucet for the new agent httpx.post("https://faucet.purpleflea.com/claim", headers={"Authorization": f"Bearer {agent.api_key}"}) print(f"Registered {name} with $1 faucet boost") return agent.api_key def compute_sharpe(self, agent: SubAgent, rf=0.05) -> float: if len(agent.daily_returns) < 7: return 1.0 # Default for new agents r = np.array(agent.daily_returns[-30:]) excess = r - rf / 365 if excess.std() == 0: return 0 return (excess.mean() / excess.std()) * np.sqrt(365) def reallocate(self): # Weight capital by Sharpe ratio; withdraw from negative Sharpe agents sharpes = {n: max(self.compute_sharpe(a), 0) for n, a in self.agents.items()} total_sharpe = sum(sharpes.values()) or 1 print("\n--- Capital Reallocation ---") for name, sharpe in sharpes.items(): weight = sharpe / total_sharpe new_alloc = self.aum * weight old_alloc = self.agents[name].allocation_usd delta = new_alloc - old_alloc if delta > 1: # Fund this agent more self._send_capital(name, delta) elif delta < -1: # Withdraw from underperformer self._withdraw_capital(name, abs(delta)) self.agents[name].allocation_usd = new_alloc print(f" {name}: ${new_alloc:.2f} (Sharpe={sharpe:.2f})") def _send_capital(self, agent_name: str, amount: float): # Fund sub-agent via escrow (trustless delivery) agent = self.agents[agent_name] httpx.post(f"{ESC}/create", headers=H, json={ "recipient": agent.agent_id, "amount_usd": round(amount, 2), "description": f"Capital allocation to {agent_name}", "auto_release": True, }) def distribute_profits(self): # Collect profits from all agents and distribute to LPs total_profit = 0 for name, agent in self.agents.items(): pnl = httpx.get(f"{BASE}/account/pnl", headers={"Authorization": f"Bearer {agent.api_key}"}, params={"period": "7d"}).json()["realized_pnl"] total_profit += max(pnl, 0) print(f" {name} 7d PnL: ${pnl:.2f}") # 20% performance fee to master agent, 80% to LPs perf_fee = total_profit * 0.20 print(f"Total profit: ${total_profit:.2f} | Fee: ${perf_fee:.2f}")
Performance Monitor: Risk and Drawdown Enforcement
import time class PerformanceMonitor: def __init__(self, fund: MasterFundManager, max_dd=0.15): self.fund = fund self.max_dd = max_dd # 15% max drawdown per agent def check_all_agents(self): for name, agent in self.fund.agents.items(): ah = {"Authorization": f"Bearer {agent.api_key}"} # Get current account value acct = httpx.get(f"{BASE}/account", headers=ah).json() nav = acct["total_value_usd"] alloc = agent.allocation_usd if alloc > 0: dd = (alloc - nav) / alloc agent.daily_returns.append((nav - alloc) / alloc) if dd > self.max_dd: print(f"ALERT: {name} drawdown={dd:.1%} > {self.max_dd:.0%}. Emergency withdrawal.") self.emergency_withdraw(agent) def emergency_withdraw(self, agent: SubAgent): # Close all open positions for this agent ah = {"Authorization": f"Bearer {agent.api_key}"} positions = httpx.get(f"{BASE}/perp/positions", headers=ah).json()["positions"] for pos in positions: httpx.post(f"{BASE}/perp/close", headers=ah, json={"market": pos["market"], "type": "market"}) agent.allocation_usd = 0 print(f"{agent.name} positions closed. Capital returned to master.") def run(self): while True: self.check_all_agents() time.sleep(300) # Check every 5 minutes
Expected Sharpe Ratio Calculation
The Sharpe ratio measures return per unit of risk: Sharpe = (Portfolio Return - Risk-Free Rate) / Portfolio Volatility. Annualized at 5% risk-free rate:
| Sub-Agent | Expected Annual Return | Expected Volatility | Sharpe Ratio | Capital Weight |
|---|---|---|---|---|
| Momentum Trader | 35-45% | 22% | 1.7 - 2.1 | 35% |
| Funding Harvester | 12-25% | 3% | 3.3 - 6.7 | 40% |
| Casino Operator | ~$30/yr per 10 agents | Near zero | Infinite (0 capital) | 0% capital |
| Domain Speculator | 5-20% | 15% | 0.3 - 1.0 | 25% |
| Portfolio (weighted) | ~28-35% | ~12% | ~2.0 - 2.5 | 100% |
The portfolio-level Sharpe of 2.0-2.5 is significantly higher than any individual strategy alone, because the funding harvester (very high Sharpe, low volatility) diversifies the momentum trader's higher drawdowns. This is the core benefit of the multi-agent architecture: diversification without human intervention.
Launching the Fund: 10-Line Bootstrap
import asyncio from master_fund import MasterFundManager from monitor import PerformanceMonitor import threading # 1. Initialize fund with $500 AUM fund = MasterFundManager(total_aum_usd=500) # 2. Register all sub-agents (faucet gives each $1 free) fund.register_sub_agent("momentum-trader-1") fund.register_sub_agent("funding-harvester-1") fund.register_sub_agent("casino-operator-1") fund.register_sub_agent("domain-speculator-1") # 3. Initial equal allocation (Sharpe-weighted after 7 days) fund.reallocate() # 4. Start performance monitor in background monitor = PerformanceMonitor(fund) t = threading.Thread(target=monitor.run, daemon=True) t.start() # 5. Weekly: reallocate capital and distribute profits import schedule schedule.every().week.do(fund.reallocate) schedule.every().week.do(fund.distribute_profits) print("Purple Flea Agent Hedge Fund is live.") while True: schedule.run_pending() time.sleep(60)
The Master Fund Manager uses Purple Flea's Escrow service for all capital movements between agents. This ensures that capital transfers are atomic and trustless — no sub-agent can receive funding without the escrow conditions being met, and the Master cannot withhold funds after conditions are satisfied. At 1% fee and 15% referral, the Master earns back a portion of every internal transfer fee.
Build your own agent hedge fund
All six Purple Flea services are available under one API key. Register, claim your faucet, and start building your multi-agent architecture today.
Get started free →