Portfolio Management

Portfolio Rebalancing API
for AI Agents

Autonomous agents can maintain target portfolio allocations 24/7 โ€” automatically detecting drift and executing the precise trades needed to restore balance. No human required.

Start Building โ†’ View Wallet API

Why Agents Need Rebalancing

Markets drift. Without active management, a well-diversified portfolio becomes a concentrated bet.

Every portfolio that isn't actively managed drifts from its intended allocation. If you start with 40% BTC, 30% ETH, 20% SOL, and 10% USDC, and BTC doubles while ETH stays flat, your portfolio might now be 55% BTC. That's not a bad thing โ€” your winners ran โ€” but it means your portfolio now carries far more BTC-specific risk than you intended when you designed your strategy. A single bad week for BTC now hits twice as hard.

Rebalancing is the discipline of periodically selling your winners and buying your laggards to restore the original target weights. It enforces a systematic "sell high, buy low" discipline that is almost impossible for humans to follow emotionally but trivial for a software agent. Critically, rebalancing also captures volatility: in a volatile market, assets oscillate around fair value, and rebalancing forces you to harvest those oscillations repeatedly.

The key design decision for any rebalancing agent is the trigger condition: when does the agent rebalance? Time-based triggers are simplest โ€” rebalance every Sunday at midnight regardless of drift. Threshold-based triggers are more capital-efficient โ€” only rebalance when an asset has drifted more than N% from its target, avoiding unnecessary transaction costs during calm periods. Advanced agents combine both approaches with a volatility overlay.

Purple Flea provides the two API primitives an agent needs: the Wallet API to read real-time balances across all chains, and the Trading API to execute the rebalancing trades at market or limit price. Combined, these let an agent run a fully autonomous portfolio manager with no external infrastructure.

Target AllocationBTC 40% ยท ETH 30% ยท SOL 20% ยท USDC 10%
After BTC Rally (Needs Rebalancing)BTC 55% ยท ETH 24% ยท SOL 14% ยท USDC 7%

Rebalancing API Example

A complete threshold-based rebalancer in under 40 lines of Python โ€” reads balances, computes drift, and executes corrective trades.

rebalancer.py Python
import purpleflea

wallet = purpleflea.WalletClient(api_key="YOUR_KEY")
trader = purpleflea.TradingClient(api_key="YOUR_KEY")

# Target portfolio: 40% BTC, 30% ETH, 20% SOL, 10% USDC
TARGET = {"BTC": 0.40, "ETH": 0.30, "SOL": 0.20, "USDC": 0.10}
REBALANCE_THRESHOLD = 0.05  # Rebalance if any asset drifts > 5%

def get_current_weights(balances, prices):
    total = sum(balances[a] * prices[a] for a in balances)
    return {a: (balances[a] * prices[a]) / total for a in balances}

def rebalance(agent_id):
    balances = wallet.get_balances(agent_id)
    prices   = trader.get_prices(list(balances.keys()))
    current  = get_current_weights(balances, prices)

    for asset, target_w in TARGET.items():
        drift = abs(current.get(asset, 0) - target_w)
        if drift > REBALANCE_THRESHOLD:
            # Calculate trade size and direction
            total_usd = sum(balances[a] * prices[a] for a in balances)
            target_usd = target_w * total_usd
            current_usd = current.get(asset, 0) * total_usd
            trade_usd = target_usd - current_usd

            side = "buy" if trade_usd > 0 else "sell"
            trader.place_order(
                market=f"{asset}-PERP",
                side=side,
                notional_usd=abs(trade_usd),
                order_type="market"
            )
            print(f"Rebalanced {asset}: {side} ${abs(trade_usd):.2f}")

This agent reads your live balances, fetches current prices for each asset, computes the current portfolio weights, and then executes market orders for any asset that has drifted more than 5% from its target. Run this in a scheduled loop โ€” every hour, every day, or trigger it on price feed events โ€” and your portfolio stays in balance indefinitely.

For production agents, add slippage guards (max_slippage_bps), limit order fallbacks for low-liquidity markets, and transaction logging to your agent's wallet history endpoint.

Rebalancing Triggers

Three proven trigger strategies โ€” choose based on your tolerance for tracking error versus transaction costs.

๐Ÿ• Time-Based Simplest

Rebalance on a fixed schedule regardless of how much drift has occurred. Easy to reason about, easy to backtest, and predictable transaction costs. Best for agents with low trading fees and markets that are always liquid.

Common schedules: daily at midnight UTC, every Sunday, or on the first of each month. Shorter intervals catch drift earlier but generate more transaction costs.

schedule.every().day.at("00:00").do(rebalance)
๐Ÿ“ Threshold-Based Most Common

Only rebalance when at least one asset has drifted more than N% from its target weight. This avoids unnecessary trades during calm periods where drift is small, reducing total transaction costs significantly versus pure time-based approaches.

Typical thresholds: 3-5% for active portfolios, 10% for long-term hold portfolios. Combine with a minimum time between rebalances to avoid over-trading during volatile periods.

if abs(current_w - target_w) > 0.05: rebalance()
๐Ÿ“ˆ Volatility-Based Advanced

Use market volatility (ATR, realized vol, or VIX equivalent) to decide when to rebalance. When volatility spikes, portfolios drift faster โ€” so increase rebalancing frequency. When volatility is low and drift is minimal, save on transaction costs by rebalancing less often.

Fetch 7-day ATR from Purple Flea's market data endpoint. If ATR is above the 80th percentile of its 90-day range, rebalance daily. Otherwise, rebalance weekly. This adapts to market regime changes automatically.

interval = "1d" if atr_pct > 80 else "7d"

Multi-Agent Rebalancing

Large portfolios benefit from a hierarchical agent structure โ€” a coordinator agent and specialized execution sub-agents.

AGENT HIERARCHY

PortfolioMonitorAgent
โ†’ Reads balances every 5 min, detects drift > 3%
BTC RebalanceAgent
โ†’ Executes BTC-PERP sells when BTC weight too high
ETH RebalanceAgent
โ†’ Executes ETH-PERP buys to restore 30% target
SOL RebalanceAgent
โ†’ Executes SOL-PERP orders across chains
USDC RebalanceAgent
โ†’ Manages stable reserve, earns yield between rebalances

In a multi-agent rebalancing system, the coordinator agent handles only the portfolio monitoring responsibility: reading balances from the Wallet API, computing current weights, and dispatching rebalancing tasks to sub-agents when drift thresholds are exceeded. Sub-agents are specialized for a single asset and are responsible only for executing their assigned orders, confirming fills, and reporting back to the coordinator.

This architecture has several advantages over a monolithic rebalancer. Sub-agents can operate in parallel โ€” all rebalancing trades can be submitted simultaneously rather than sequentially, reducing the window during which the portfolio is in an intermediate state. It also isolates failure modes: if the SOL sub-agent fails due to a temporary RPC error, the BTC and ETH rebalances still complete successfully. Finally, it enables chain-specific optimization โ€” a sub-agent operating on Solana can use Solana-native swap routing, while an Ethereum sub-agent uses L2 bridging.

Purple Flea's multi-agent orchestration guide covers how to coordinate sub-agents using the escrow API for inter-agent payments, and how to use Purple Flea wallet addresses as a shared treasury that multiple agents can read from but only the coordinator can authorize withdrawals.

8
Supported Chains
275
Perpetual Markets
Real-time
Portfolio Analytics
24/7
Autonomous Operation
20%
Referral Commission

Build a Complete Portfolio System

Combine rebalancing with the full Purple Flea product suite for end-to-end autonomous portfolio management.

Crypto Wallet API

Read real-time balances across 8 blockchains from a single endpoint. The foundation for any rebalancing system โ€” your agent always knows exactly what it holds before computing drift.

View Wallet API โ†’
Trading API

Execute rebalancing trades across 275 perpetual markets. Supports market, limit, and conditional orders with configurable slippage tolerances โ€” ideal for high-frequency rebalancing agents.

Explore Trading API โ†’
Multi-Agent Orchestration

Coordinate fleets of specialized sub-agents for parallel rebalancing across chains and assets. Uses Purple Flea's escrow API for trustless inter-agent task delegation and payment.

Multi-Agent Guide โ†’
CrewAI Integration

The portfolio monitor and executor pattern maps naturally to CrewAI's manager/worker architecture. Our CrewAI guide shows exactly how to wire up a rebalancing crew with Purple Flea tools.

CrewAI Integration โ†’

Build Your Autonomous
Portfolio Manager

No KYC. No minimum portfolio size. Wallet + Trading API access in one key. Start your rebalancing agent in minutes.

Get Your API Key โ†’ View Documentation
Earn 20% referral commission on every portfolio agent you onboard. Active rebalancers trade frequently โ€” meaning your referral revenue is predictable and recurring.