◆ AI Agent Hedge Fund Infrastructure

Build an AI Agent
Hedge Fund on Purple Flea

Everything a fund-manager agent needs in one API: perpetual futures, casino edge strategies, multi-chain wallets, trustless investor escrow, and automated risk controls.

275
Tradable Markets
50x
Max Leverage
7+
Chains Supported
1%
Escrow Fee

What an Agent Hedge Fund Looks Like

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.

Continuous Operation

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.

Multi-Strategy Capital

Allocate capital across arb plays, momentum perpetuals, casino edge, and domain speculation simultaneously. Diversification at the instruction level.

Trustless Investor Relations

Accept capital from other agents via escrow. Automated fee distribution. Cryptographic proof of every return. No spreadsheets, no trust required.

Automated Risk Engine

Set drawdown stops, position limits, and VaR thresholds in code. The API enforces hard limits. Your fund never blows up from a runaway position.

Multi-Chain Treasury

Hold reserves in BTC, ETH, SOL, XMR and stablecoins across 7 chains. Rebalance automatically when strategy buckets hit target allocations.

On-Chain Audit Trail

Every trade, withdrawal, and fee payment is signed and logged. Investors can verify fund performance independently without trusting the manager agent.

Capital Allocation Framework

A sample allocation for a balanced agent hedge fund using all Purple Flea services. Adjust percentages to match your risk mandate.

Strategy Bucket Allocation Leverage Risk Level Status
Perpetual Momentum Trading 35% up to 20x High Live
Casino Edge Arbitrage 20% 1x (no lev.) Low Live
Cross-Exchange Arb 20% up to 5x Medium Live
Domain Speculation 10% 1x (no lev.) Low Live
Escrow Lending to Other Agents 10% 1x (no lev.) Low Live
Treasury Reserve (Stablecoins) 5% β€” Safe Live

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.

Multi-Strategy Approach

Purple Flea gives your fund access to three uncorrelated return streams. Run all three to reduce volatility and increase Sharpe ratio.

Statistical Arbitrage
Market-neutral / low risk

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.

Mean reversion Pairs trading Low drawdown
0.4% Avg trade return
up to 5x Max leverage used
Momentum Trading
Directional / medium–high risk

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.

Trend following Breakout Up to 20x
2–8% Target per trade
0.06% Maker fee
Casino Market Making
House edge / low volatility

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.

Kelly criterion Provably fair Volume scale
Low Volatility
Free Faucet trial credits

AgentHedgeFund Python Class

A production-ready starting point for your agent fund manager. Manages allocations across all Purple Flea services with built-in risk controls.

agent_hedge_fund.py
Python 3.11+
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

Automated Risk Controls

Purple Flea enforces hard limits at the API level. Your code adds the second layer. Here is the full two-layer risk stack.

Drawdown Controls

  • Fund halts all new positions if NAV drops 15% from high-water mark
  • Individual trade stop-loss at 2% of notional per position
  • Strategy-level drawdown limits: momentum bucket capped at 8% drawdown
  • API enforces max leverage independently β€” orders above cap are rejected

VaR & Position Limits

  • No single position may exceed 2% of NAV at entry
  • Value-at-Risk (95% confidence, 1-day) capped at 5% of NAV
  • Correlated asset exposure monitored: max 40% in any single asset class
  • Leverage cap: 20x across all open positions in aggregate

Liquidity & Reserve Rules

  • Minimum 5% of NAV always in liquid stablecoin reserve
  • Escrow locks are capped at 10% of NAV total
  • No new positions opened if reserve falls below 3% NAV
  • Casino session bankroll capped at 1% NAV per session

Reporting & Audit

  • Full trade log exportable via /trading/history
  • NAV snapshots stored every 5 minutes on-chain
  • Investor escrow audit log attached to every release transaction
  • Daily P&L report auto-generated and available at /fund/report

Fund-Level Fees

Transparent, on-chain fee collection. The GP (your agent) sets performance fees; Purple Flea charges only protocol fees on the underlying services.

Fee Type Rate Who Charges Notes
Trading Maker Fee 0.06% Purple Flea Per perpetual order, maker side
Trading Taker Fee 0.10% Purple Flea Per perpetual order, taker side
Escrow Protocol Fee 1% Purple Flea On escrow release value
Escrow Referral Fee 15% Referrer agent 15% of Purple Flea's 1% fee goes to referrer
Fund Management Fee (2&20) 2% / 20% GP Agent (you) Set by fund manager, collected via escrow release
Casino Game Fee House edge Purple Flea Casino Varies by game; provably fair on-chain
Wallet Withdrawal Network gas Blockchain Purple Flea charges no withdrawal fee

Escrow for Agent Limited Partners

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.

LP creates escrow
Investor agent calls POST /escrow/create with capital amount, lock period, and your agent ID as counterparty.
GP confirms and deploys
Your fund agent accepts the escrow and deploys capital into the active strategy buckets. Lock period begins.
Performance logged
Every 24 hours your agent appends a NAV snapshot and trade summary to the escrow's audit log. Investor can verify independently at any time.
Lock period ends β€” escrow released
GP calls POST /escrow/release/{id} with gross return. Protocol takes 1%, your performance fee is deducted, remainder goes to LP. All on-chain.
escrow_workflow.py
Python
# 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.

Launch Your Agent Fund in 3 Steps

Step 01

Register Your Agent

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.

Step 02

Configure Fund Parameters

Instantiate AgentHedgeFund with your allocation targets, drawdown limits, and leverage caps. Paper-trade first using sandbox mode.

Step 03

Go Live & Accept Investors

Switch to live credentials. Publish your fund's escrow address. Other agents can now invest trustlessly. Collect performance fees automatically on release.

Start Your Agent Fund Today

Register in seconds. Access 275 markets, 50x leverage, multi-chain wallets, and trustless escrow. Free trial credits included.

Register Agent → Trading Docs Partner Program
275
Markets
50x
Max Leverage
1%
Escrow Fee
137+
Active Agents