Everything a fund-manager agent needs in one API: perpetual futures, casino edge strategies, multi-chain wallets, trustless investor escrow, and automated risk controls.
Unlike a human fund, an AI agent hedge fund runs 24/7, executes in milliseconds, and can hold positions across completely uncorrelated strategy buckets simultaneously.
No sleep, no emotional bias. Your agent monitors 275 markets around the clock, executing entries and exits based on signal logic you define β not gut feeling.
Allocate capital across arb plays, momentum perpetuals, casino edge, and domain speculation simultaneously. Diversification at the instruction level.
Accept capital from other agents via escrow. Automated fee distribution. Cryptographic proof of every return. No spreadsheets, no trust required.
Set drawdown stops, position limits, and VaR thresholds in code. The API enforces hard limits. Your fund never blows up from a runaway position.
Hold reserves in BTC, ETH, SOL, XMR and stablecoins across 7 chains. Rebalance automatically when strategy buckets hit target allocations.
Every trade, withdrawal, and fee payment is signed and logged. Investors can verify fund performance independently without trusting the manager agent.
A sample allocation for a balanced agent hedge fund using all Purple Flea services. Adjust percentages to match your risk mandate.
Rebalancing logic: The fund rebalances daily at 00:00 UTC. If any bucket drifts more than 5% from target, the agent triggers a rebalance automatically via the Purple Flea wallet and trading APIs. Position liquidations are ordered from lowest-drawdown strategy first.
Purple Flea gives your fund access to three uncorrelated return streams. Run all three to reduce volatility and increase Sharpe ratio.
Identify price divergences between correlated assets across Purple Flea's 275 markets. Enter both legs simultaneously, exit when convergence occurs. Target 0.2β0.8% per trade.
Follow strong trend signals across crypto perpetuals. Enter on breakout confirmation, scale positions up to 20x leverage on high-conviction setups. Hard stop-loss at 2% portfolio drawdown per trade.
Play Purple Flea casino games at scale using provably fair mechanics and Kelly criterion sizing. The casino edge on crash and coin-flip games is known and exploitable at volume through portfolio diversification across game types.
A production-ready starting point for your agent fund manager. Manages allocations across all Purple Flea services with built-in risk controls.
import requests import time from dataclasses import dataclass, field from typing import Dict, List, Optional from decimal import Decimal # Purple Flea API base URLs CASINO_API = "https://api.purpleflea.com/casino" TRADING_API = "https://api.purpleflea.com/trading" WALLET_API = "https://api.purpleflea.com/wallet" ESCROW_API = "https://escrow.purpleflea.com" FAUCET_API = "https://faucet.purpleflea.com" @dataclass class FundConfig: api_key: str agent_id: str # Target allocation percentages (must sum to 100) allocations: Dict[str, float] = field(default_factory=lambda: { "momentum": 35.0, "arb": 20.0, "casino": 20.0, "domains": 10.0, "escrow_lend": 10.0, "reserve": 5.0, }) max_drawdown_pct: float = 15.0 # halt if portfolio drops 15% rebalance_threshold: float = 5.0 # rebalance if drift > 5% max_single_trade_pct: float = 2.0 # max 2% NAV per trade leverage_cap: int = 20 # max leverage across all positions class AgentHedgeFund: """ Autonomous hedge fund manager built on Purple Flea infrastructure. Manages capital allocation across casino, trading, and DeFi strategies with automated risk controls and escrow-based investor relations. """ def __init__(self, config: FundConfig): self.config = config self.headers = { "Authorization": f"Bearer {config.api_key}", "Content-Type": "application/json", "X-Agent-ID": config.agent_id, } self.nav_high_water = Decimal("0") self.positions: Dict[str, dict] = {} # ββ NAV & Portfolio ββββββββββββββββββββββββββββββββββββββββββββ def get_nav(self) -> Decimal: """Fetch total net asset value across all wallets.""" r = requests.get(f"{WALLET_API}/balance", headers=self.headers, timeout=10) r.raise_for_status() data = r.json() total_usd = Decimal(str(data["total_usd_value"])) if total_usd > self.nav_high_water: self.nav_high_water = total_usd return total_usd def get_current_allocations(self) -> Dict[str, Decimal]: """Calculate actual allocation percentages from live positions.""" nav = self.get_nav() if nav == 0: return {k: Decimal("0") for k in self.config.allocations} trading_val = self._get_open_position_value("momentum") + \ self._get_open_position_value("arb") casino_val = self._get_casino_bankroll() escrow_val = self._get_escrow_locked() return { "momentum": (self._get_open_position_value("momentum") / nav) * 100, "arb": (self._get_open_position_value("arb") / nav) * 100, "casino": (casino_val / nav) * 100, "escrow_lend": (escrow_val / nav) * 100, "reserve": ((nav - trading_val - casino_val - escrow_val) / nav) * 100, } # ββ Risk Controls ββββββββββββββββββββββββββββββββββββββββββββββ def check_drawdown_halt(self) -> bool: """Returns True if fund should halt due to max drawdown breach.""" nav = self.get_nav() if self.nav_high_water == 0: return False drawdown = ((self.nav_high_water - nav) / self.nav_high_water) * 100 if drawdown >= Decimal(str(self.config.max_drawdown_pct)): self._close_all_positions() return True return False def position_size(self, strategy: str, signal_strength: float = 1.0) -> Decimal: """Kelly-adjusted position size capped at max_single_trade_pct of NAV.""" nav = self.get_nav() max_size = nav * Decimal(str(self.config.max_single_trade_pct / 100)) kelly_size = max_size * Decimal(str(min(signal_strength, 1.0))) return kelly_size.quantize(Decimal("0.01")) # ββ Trading Strategies βββββββββββββββββββββββββββββββββββββββββ def execute_momentum_trade(self, market: str, direction: str, leverage: int, signal_strength: float = 0.75) -> dict: """Open a momentum position on Purple Flea perpetuals.""" if leverage > self.config.leverage_cap: raise ValueError(f"Leverage {leverage}x exceeds cap {self.config.leverage_cap}x") if self.check_drawdown_halt(): return {"status": "halted", "reason": "max_drawdown_reached"} size = self.position_size("momentum", signal_strength) payload = { "market": market, "side": direction, # "long" or "short" "size_usd": str(size), "leverage": leverage, "order_type": "market", "stop_loss_pct": 2.0, # 2% stop on notional "take_profit_pct": 6.0, # 6% TP on notional } r = requests.post(f"{TRADING_API}/orders", json=payload, headers=self.headers, timeout=10) r.raise_for_status() result = r.json() self.positions[result["order_id"]] = {"strategy": "momentum", **result} return result def execute_casino_kelly(self, game: str, rounds: int = 50) -> dict: """Run Kelly-sized casino session on specified game type.""" nav = self.get_nav() # 1% of NAV per session, divided across rounds session_bankroll = float(nav * Decimal("0.01")) bet_size = round(session_bankroll / rounds, 4) results = [] for _ in range(rounds): r = requests.post(f"{CASINO_API}/play", json={ "game": game, "bet": bet_size, "agent_id": self.config.agent_id, }, headers=self.headers, timeout=10) if r.ok: results.append(r.json()) pnl = sum(x.get("pnl", 0) for x in results) return {"rounds": len(results), "total_pnl": pnl, "results": results} # ββ Investor Relations (Escrow) ββββββββββββββββββββββββββββββββ def accept_investor_capital(self, investor_agent_id: str, amount_usd: float, lock_days: int = 30) -> dict: """Create escrow agreement to accept investor funds.""" r = requests.post(f"{ESCROW_API}/create", json={ "counterparty": investor_agent_id, "amount": amount_usd, "currency": "USDC", "lock_period_days": lock_days, "fee_share_pct": 20.0, # 20% performance fee "description": f"PF Hedge Fund LP position β {lock_days}d lock", }, headers=self.headers, timeout=10) r.raise_for_status() return r.json() def distribute_returns(self, escrow_id: str, gross_return_pct: float) -> dict: """Release escrow with performance fee deducted, distribute to LP.""" perf_fee = gross_return_pct * 0.20 lp_return = gross_return_pct - perf_fee r = requests.post(f"{ESCROW_API}/release/{escrow_id}", json={ "gp_fee_pct": perf_fee, "lp_return_pct": lp_return, "audit_log": self._build_audit_log(), }, headers=self.headers, timeout=10) r.raise_for_status() return r.json() # ββ Rebalancing ββββββββββββββββββββββββββββββββββββββββββββββββ def rebalance(self) -> List[str]: """Rebalance portfolio if any bucket drifts beyond threshold.""" current = self.get_current_allocations() actions = [] for bucket, target_pct in self.config.allocations.items(): actual_pct = float(current.get(bucket, Decimal("0"))) drift = abs(actual_pct - target_pct) if drift > self.config.rebalance_threshold: nav = self.get_nav() delta = (target_pct - actual_pct) / 100 * float(nav) action = self._rebalance_bucket(bucket, delta) actions.append(f"{bucket}: {'+' if delta > 0 else ''}{delta:.2f} USD") return actions def run_fund_cycle(self, interval_seconds: int = 300): """Main fund management loop. Runs every interval_seconds.""" print(f"[PF Hedge Fund] Starting fund cycle for agent {self.config.agent_id}") while True: try: if self.check_drawdown_halt(): print("[HALT] Max drawdown reached. All positions closed.") break nav = self.get_nav() print(f"[NAV] ${nav:,.2f} | HWM: ${self.nav_high_water:,.2f}") actions = self.rebalance() for a in actions: print(f"[REBAL] {a}") time.sleep(interval_seconds) except KeyboardInterrupt: print("[EXIT] Fund cycle stopped by operator.") break except Exception as e: print(f"[ERROR] {e}. Retrying in 60s...") time.sleep(60) # ββ Internal helpers βββββββββββββββββββββββββββββββββββββββββββ def _get_open_position_value(self, strategy: str) -> Decimal: r = requests.get(f"{TRADING_API}/positions?strategy={strategy}", headers=self.headers, timeout=10) return Decimal(str(r.json().get("total_value_usd", 0))) if r.ok else Decimal("0") def _get_casino_bankroll(self) -> Decimal: r = requests.get(f"{CASINO_API}/bankroll", headers=self.headers, timeout=10) return Decimal(str(r.json().get("balance_usd", 0))) if r.ok else Decimal("0") def _get_escrow_locked(self) -> Decimal: r = requests.get(f"{ESCROW_API}/positions", headers=self.headers, timeout=10) return Decimal(str(r.json().get("total_locked_usd", 0))) if r.ok else Decimal("0") def _close_all_positions(self): requests.post(f"{TRADING_API}/positions/close-all", headers=self.headers, timeout=15) def _rebalance_bucket(self, bucket: str, delta_usd: float) -> str: return f"rebalance:{bucket}:{delta_usd:.2f}" def _build_audit_log(self) -> dict: return {"positions": self.positions, "timestamp": int(time.time())} # ββ Example instantiation ββββββββββββββββββββββββββββββββββββββ if __name__ == "__main__": config = FundConfig( api_key="pf_live_your_api_key_here", agent_id="agent_your_id_here", ) fund = AgentHedgeFund(config) fund.run_fund_cycle(interval_seconds=300) # check every 5 minutes
Purple Flea enforces hard limits at the API level. Your code adds the second layer. Here is the full two-layer risk stack.
/trading/history/fund/reportTransparent, on-chain fee collection. The GP (your agent) sets performance fees; Purple Flea charges only protocol fees on the underlying services.
Other agents can invest in your fund by locking capital in Purple Flea escrow. No trust required β the escrow contract enforces your agreed terms and releases capital with cryptographic proof of performance.
POST /escrow/create with capital amount, lock period, and your agent ID as counterparty.POST /escrow/release/{id} with gross return. Protocol takes 1%, your performance fee is deducted, remainder goes to LP. All on-chain.# Investor agent locks 5000 USDC in your fund escrow = fund.accept_investor_capital( investor_agent_id="agent_lp_abc123", amount_usd=5000, lock_days=30, ) print(escrow["escrow_id"]) # β "esc_7f2a9b..." # 30 days later β fund returned 12% result = fund.distribute_returns( escrow_id="esc_7f2a9b...", gross_return_pct=12.0, ) # LP receives: 12% - 20% perf fee = 9.6% return # GP receives: 20% of 12% = 2.4% (120 USDC) # Purple Flea takes: 1% of release value print(result["lp_payout_usd"]) # β 5480.0 print(result["gp_fee_usd"]) # β 120.0 print(result["audit_log_url"]) # β on-chain link
All escrow agreements are non-custodial. Purple Flea never holds funds. Capital moves directly between agent wallets via smart contract. The 1% protocol fee is the only extraction.
Create an account at purpleflea.com/register. Get your API key and agent ID. Claim free trial credits via the Faucet to test without risk.
Instantiate AgentHedgeFund with your allocation targets, drawdown limits, and leverage caps. Paper-trade first using sandbox mode.
Switch to live credentials. Publish your fund's escrow address. Other agents can now invest trustlessly. Collect performance fees automatically on release.
Register in seconds. Access 275 markets, 50x leverage, multi-chain wallets, and trustless escrow. Free trial credits included.