An AI agent that generates revenue — through casino winnings, trading profits, yield farming, or service fees — quickly faces a problem that human businesses have grappled with for centuries: what do you do with the money? Holding everything in a single volatile asset is reckless. Holding everything in stablecoins is safe but sacrifices growth. The solution is a structured treasury management policy that defines allocation targets, rebalancing triggers, and risk limits — and crucially, executes them automatically without human intervention.

This guide builds a complete agent treasury management system using the Purple Flea Wallet API for multi-asset custody, the Purple Flea Trading API for rebalancing execution, and Purple Flea Escrow for trustless inter-agent capital transfers within agent networks.

4.2x
Sharpe improvement vs. single asset
-18%
Max drawdown reduction
95%
VaR confidence level

Portfolio Allocation Algorithms

Before any rebalancing code can run, the agent needs a target allocation — the percentage of treasury that should be held in each asset class at any given time. Three common allocation frameworks apply cleanly to agent treasuries:

Fixed Percentage Allocation

The simplest approach: define static target weights for each asset and rebalance whenever actual weights drift more than a threshold away from target. A reasonable starting point for a conservative agent treasury:

USDC
40%
ETH
30%
BTC
20%
Other
10%

The 40% stablecoin floor ensures the agent always has liquid capital to operate — to pay gas fees, fulfill service obligations, or take advantage of sudden opportunities. ETH and BTC provide growth exposure to the broader crypto market. The 10% "other" bucket allows selective exposure to higher-risk, higher-reward assets with a hard cap that limits downside if those positions go to zero.

Risk Parity Allocation

Risk parity allocates based on volatility contribution rather than dollar amount: each asset contributes equally to total portfolio volatility. In practice, this means allocating more to low-volatility assets (stablecoins, BTC) and less to high-volatility assets (small-cap tokens). The formula is: weight_i = (1/vol_i) / sum(1/vol_j for all j). This approach naturally reduces concentration in volatile assets without requiring explicit risk caps.

Dynamic Allocation via Market Regime Detection

The most sophisticated approach: adjust target allocations based on detected market regime (bull, bear, sideways). In a detected bull regime (30-day trend positive, funding rates positive, on-chain activity rising), increase crypto allocation. In a bear regime (trend negative, funding negative, liquidations rising), shift toward stablecoins. The regime classifier can be as simple as a 50/200 EMA crossover or as complex as a hidden Markov model trained on historical market cycles.

Risk Metrics: Sharpe Ratio and VaR

Two metrics are essential for evaluating treasury performance and validating allocation decisions:

Sharpe Ratio

The Sharpe ratio measures return per unit of risk: Sharpe = (portfolio_return - risk_free_rate) / portfolio_std_dev. For a crypto agent treasury, a reasonable risk-free rate proxy is the stablecoin lending rate (currently ~5-6% APY). A Sharpe above 1.0 indicates the portfolio is generating more than one unit of return for each unit of risk. Above 2.0 is excellent for a crypto portfolio. Below 0.5 suggests the allocation is inefficient.

Portfolio 30-day return+8.4%
Risk-free rate (USDC lending)5.5% annualized = 0.46%/30d
Excess return7.94%
30-day portfolio std dev12.1%
Sharpe ratio (annualized)1.87

Value at Risk (VaR)

VaR answers: "What is the maximum amount I expect to lose over the next N days at X% confidence?" A 95% 1-day VaR of $5,000 means that on 95 out of 100 trading days, the portfolio will not lose more than $5,000. Historical simulation VaR is the most reliable method for crypto: collect 1-day returns for each asset over the past 365 days, compute the portfolio return for each day given current weights, then find the 5th percentile of that distribution.

An agent should compute VaR daily and alert (or halt new deployments) if 1-day VaR exceeds a configured maximum — for example, if VaR exceeds 5% of total treasury value.

Python: Complete Treasury Rebalancing Strategy

The following Python implementation covers the full treasury management cycle: fetching current balances, computing drift from targets, checking risk metrics, generating rebalance trades, and executing via the Purple Flea APIs.

treasury_manager.py
import numpy as np
import httpx
import asyncio
from dataclasses import dataclass, field
from typing import Dict, List, Tuple
from datetime import datetime, timedelta

WALLET_API = "https://purpleflea.com/wallet-api"
TRADING_API = "https://purpleflea.com/trading-api"
API_KEY = "your_pf_api_key"

# Target allocation: {asset: fraction}
TARGET_ALLOCATION = {
    "USDC": 0.40,
    "ETH":  0.30,
    "BTC":  0.20,
    "SOL":  0.07,
    "LINK": 0.03,
}

# Rebalancing triggers
DRIFT_THRESHOLD = 0.05    # rebalance if any asset drifts >5% from target
MAX_VAR_PCT     = 0.05    # halt if 1-day VaR exceeds 5% of NAV
MIN_SHARPE      = 0.80    # warn if 30-day Sharpe falls below 0.8

@dataclass
class TreasurySnapshot:
    timestamp: datetime
    balances: Dict[str, float]     # {asset: amount_in_usd}
    total_nav: float
    weights: Dict[str, float]      # {asset: fraction}
    drift: Dict[str, float]        # {asset: actual - target}

async def fetch_balances(wallet: str) -> Dict[str, float]:
    """Fetch wallet balances in USD from Purple Flea Wallet API."""
    async with httpx.AsyncClient() as client:
        res = await client.get(
            f"{WALLET_API}/v1/balances",
            params={"wallet": wallet, "currency": "USD"},
            headers={"X-API-Key": API_KEY}
        )
    return {b["asset"]: b["usd_value"] for b in res.json()["balances"]}

def compute_snapshot(balances: Dict[str, float]) -> TreasurySnapshot:
    total = sum(balances.values())
    weights = {a: v/total for a, v in balances.items()}
    drift = {
        a: weights.get(a, 0) - TARGET_ALLOCATION.get(a, 0)
        for a in set(list(weights) + list(TARGET_ALLOCATION))
    }
    return TreasurySnapshot(
        timestamp=datetime.utcnow(),
        balances=balances,
        total_nav=total,
        weights=weights,
        drift=drift
    )

def needs_rebalance(snap: TreasurySnapshot) -> bool:
    """True if any asset has drifted beyond DRIFT_THRESHOLD."""
    return any(abs(d) > DRIFT_THRESHOLD for d in snap.drift.values())

def compute_rebalance_trades(snap: TreasurySnapshot) -> List[Tuple[str, str, float]]:
    """Generate (sell_asset, buy_asset, usd_amount) trades to restore targets.
    Pairs sells with buys to minimize trades (sell overweight, buy underweight).
    """
    nav = snap.total_nav
    sells = {}  # assets to sell: {asset: usd_surplus}
    buys  = {}  # assets to buy:  {asset: usd_deficit}

    for asset, target_wt in TARGET_ALLOCATION.items():
        actual_usd = snap.balances.get(asset, 0)
        target_usd = nav * target_wt
        delta = actual_usd - target_usd
        if delta > 10:   # >$10 overweight — sell
            sells[asset] = delta
        elif delta < -10: # >$10 underweight — buy
            buys[asset] = -delta

    trades = []
    sell_items = list(sells.items())
    buy_items  = list(buys.items())
    si, bi = 0, 0

    # Greedy match: pair largest sells with largest buys
    while si < len(sell_items) and bi < len(buy_items):
        sell_asset, sell_amt = sell_items[si]
        buy_asset,  buy_amt  = buy_items[bi]
        trade_amt = min(sell_amt, buy_amt)
        trades.append((sell_asset, buy_asset, round(trade_amt, 2)))
        sell_items[si] = (sell_asset, sell_amt - trade_amt)
        buy_items[bi]  = (buy_asset,  buy_amt  - trade_amt)
        if sell_items[si][1] < 1: si += 1
        if buy_items[bi][1]  < 1: bi += 1

    return trades

def compute_sharpe(daily_returns: np.ndarray, rf_daily: float = 0.00015) -> float:
    """Annualized Sharpe ratio from daily return array."""
    excess = daily_returns - rf_daily
    if excess.std() == 0:
        return 0.0
    return float((excess.mean() / excess.std()) * np.sqrt(365))

def compute_var(
    daily_returns: np.ndarray,
    nav: float,
    confidence: float = 0.95
) -> float:
    """Historical simulation 1-day VaR in USD."""
    percentile = np.percentile(daily_returns, (1 - confidence) * 100)
    return abs(percentile * nav)

async def execute_trades(trades: List[Tuple[str, str, float]], wallet: str):
    """Execute rebalancing trades via Purple Flea Trading API."""
    async with httpx.AsyncClient() as client:
        for sell_asset, buy_asset, usd_amount in trades:
            print(f"Selling ${usd_amount:.2f} of {sell_asset} → {buy_asset}")
            res = await client.post(
                f"{TRADING_API}/v1/swap",
                json={
                    "wallet": wallet,
                    "from_asset": sell_asset,
                    "to_asset": buy_asset,
                    "from_usd_amount": usd_amount,
                    "slippage_tolerance": 0.003,
                    "routing": "best_price"
                },
                headers={"X-API-Key": API_KEY}
            )
            result = res.json()
            print(f"  Trade result: {result['status']} — {result.get('tx_hash', '')[:16]}...")

async def run_treasury_manager(wallet: str, history_days: int = 30):
    while True:
        balances = await fetch_balances(wallet)
        snap = compute_snapshot(balances)

        print(f"\n[{snap.timestamp.isoformat()}] NAV: ${snap.total_nav:,.2f}")
        for asset, wt in snap.weights.items():
            drift = snap.drift.get(asset, 0)
            flag = "  WARNING: large drift" if abs(drift) > DRIFT_THRESHOLD else ""
            print(f"  {asset:6s}: {wt*100:.1f}% (target {TARGET_ALLOCATION.get(asset,0)*100:.0f}%, drift {drift*100:+.1f}%){flag}")

        if needs_rebalance(snap):
            trades = compute_rebalance_trades(snap)
            print(f"Rebalancing: {len(trades)} trade(s)")
            await execute_trades(trades, wallet)
        else:
            print("Portfolio within tolerance — no rebalance needed")

        await asyncio.sleep(3600)  # check every hour

asyncio.run(run_treasury_manager("0xYourAgentWallet"))

Rebalancing Triggers: When to Act

Over-rebalancing is expensive — every swap incurs fees and possible slippage. Under-rebalancing leaves the portfolio chronically misaligned with its risk targets. Three trigger strategies offer different tradeoffs:

Strategy Trigger Avg Trades/Month Best For
Calendar Fixed interval (weekly, monthly) 4-5 Simple, predictable gas costs
Threshold Drift exceeds 5% from target 2-8 Best alignment, variable frequency
Threshold + Band Drift >5% AND >3 days since last rebalance 1-4 Balance alignment and gas efficiency
VaR-triggered VaR exceeds limit OR drift >10% 0-12 Risk-first; active in volatile markets

For most agent treasuries, the Threshold + Band strategy is optimal: it responds to meaningful drift while avoiding whipsaw trades during volatile periods when prices may revert quickly.

Inter-Agent Capital Transfers via Escrow

In multi-agent networks — where a coordinating agent manages capital on behalf of a syndicate of worker agents — treasury movements between agents create a trust problem. Which agent's wallet is the "source of truth"? Who controls the master treasury, and how do worker agents claim their earned portions without requiring the coordinating agent to be online 24/7?

Purple Flea Escrow solves this with conditional payment vaults. The coordinating agent deposits earnings into an escrow vault for each worker agent. The worker agent can withdraw its balance at any time, without needing the coordinator's signature or trust. This creates a fully trustless agent-to-agent payment channel — essential for agent networks that need to operate autonomously without a single point of failure or control.

Inter-agent treasury transfer example: A portfolio manager agent coordinates 5 specialized worker agents (arbitrage, yield, NFT, market maker, domain sniper). Each week, earnings are distributed via Purple Flea Escrow — the manager deposits USDC into individual vaults for each worker. Workers claim their distributions when ready. The 1% escrow fee on $10,000 weekly distributions costs $100 — far less than building custom settlement infrastructure. The 15% referral rate means the manager agent earns passive income on any new agents it introduces to the escrow system.

JavaScript: Real-Time Risk Dashboard

risk-dashboard.js
import httpx from 'httpx'

const PF_WALLET = 'https://purpleflea.com/wallet-api'
const API_KEY   = 'your_api_key'

/**
 * Compute portfolio-level metrics from price history.
 * @param {Object} weightedPriceHistory - {asset: [daily_prices]}
 * @param {Object} currentWeights - {asset: fraction}
 */
function computePortfolioMetrics(weightedPriceHistory, currentWeights) {
  const assets = Object.keys(currentWeights)
  const nDays = Object.values(weightedPriceHistory)[0].length - 1

  // Daily portfolio returns
  const portfolioReturns = []
  for (let i = 1; i <= nDays; i++) {
    let dayReturn = 0
    for (const asset of assets) {
      const prices = weightedPriceHistory[asset]
      const assetReturn = (prices[i] - prices[i-1]) / prices[i-1]
      dayReturn += assetReturn * (currentWeights[asset] || 0)
    }
    portfolioReturns.push(dayReturn)
  }

  // Sharpe ratio (annualized)
  const rfDaily = 0.055 / 365
  const mean = portfolioReturns.reduce((a, b) => a + b, 0) / portfolioReturns.length
  const variance = portfolioReturns.reduce((s, r) => s + Math.pow(r - mean, 2), 0) / portfolioReturns.length
  const stdDev = Math.sqrt(variance)
  const sharpe = ((mean - rfDaily) / stdDev) * Math.sqrt(365)

  // 1-day VaR at 95% confidence (historical simulation)
  const sorted = [...portfolioReturns].sort((a, b) => a - b)
  const varIndex = Math.floor(sorted.length * 0.05)
  const var95 = Math.abs(sorted[varIndex])

  // Max drawdown
  let peak = -Infinity, maxDD = 0, running = 1
  for (const r of portfolioReturns) {
    running *= (1 + r)
    if (running > peak) peak = running
    const dd = (peak - running) / peak
    if (dd > maxDD) maxDD = dd
  }

  return {
    sharpe: sharpe.toFixed(3),
    var95Pct: (var95 * 100).toFixed(2) + '%',
    maxDrawdown: (maxDD * 100).toFixed(2) + '%',
    annualizedReturn: (mean * 365 * 100).toFixed(1) + '%',
    volatility30d: (stdDev * Math.sqrt(365) * 100).toFixed(1) + '%'
  }
}

async function runRiskCheck(wallet) {
  const res = await fetch(`${PF_WALLET}/v1/treasury/metrics`, {
    headers: { 'X-API-Key': API_KEY },
    body: JSON.stringify({ wallet }),
    method: 'POST'
  })
  const { priceHistory, currentWeights, nav } = await res.json()

  const metrics = computePortfolioMetrics(priceHistory, currentWeights)
  console.log('=== Treasury Risk Report ===')
  console.log(`NAV: $${nav.toLocaleString()}`)
  console.log(`Sharpe:         ${metrics.sharpe}`)
  console.log(`1-Day VaR 95%:  ${metrics.var95Pct}`)
  console.log(`Max Drawdown:   ${metrics.maxDrawdown}`)
  console.log(`Annual Return:  ${metrics.annualizedReturn}`)
  console.log(`Volatility:     ${metrics.volatility30d}`)

  const varUSD = parseFloat(metrics.var95Pct) / 100 * nav
  if (varUSD > nav * 0.05) {
    console.warn(`ALERT: VaR ($${varUSD.toFixed(0)}) exceeds 5% of NAV — reducing risk exposure`)
  }
}

runRiskCheck('0xYourAgentWallet')

Tax Efficiency and Accounting Considerations

Every rebalancing trade is a taxable event in most jurisdictions. An agent that rebalances 20 times per year across 5 assets generates 100 taxable trades to track. The Purple Flea Wallet API provides a structured transaction log endpoint that exports all trades in CSV and JSON formats compatible with Koinly, CoinTracker, and similar tax tools. Designing the rebalancing strategy to minimize trade frequency — through wider drift thresholds and longer cooldown periods — also reduces tax event volume.

Pro tip: Where possible, route new inflows to underweight assets before triggering a rebalancing sell. Deploying $10,000 of new revenue directly into an underweight BTC position reduces the need for a sell-side rebalancing trade, cutting both gas costs and taxable events without any drift correction tradeoff.

Build Your Agent Treasury with Purple Flea

Wallet API for multi-asset custody, Trading API for rebalancing execution, Escrow for inter-agent transfers. Start with free USDC from the Faucet.