How to build an AI portfolio rebalancing agent step by step
A developer guide to building an AI agent that rebalances portfolios across markets using scoped, non-custodial permissions and strict safety controls.
- 01AI portfolio rebalancing automates the mechanical process of returning allocations to preset target weights when drift exceeds a threshold.
- 02Developers should define target weights, drift thresholds, and dollar-based order logic before giving the agent any trading permissions.
- 03Safety controls like scoped keys, budget caps, position limits, and a kill switch are essential because the agent operates without human click-through on every trade.
- 04Paper trading and historical simulations reveal logic errors and fee churn, but they do not predict future performance or guarantee profits.
- 05Live evaluation requires monitoring drift reduction, fill quality, and fee impact, starting with a small capital allocation and an accessible panic switch.
AI portfolio rebalancing uses an autonomous agent to buy and sell assets when actual allocations drift from preset target weights. A developer implements this by defining the target portfolio, setting a drift threshold, and giving the agent scoped permission to submit trades within strict budget and position limits. The agent checks current weights, calculates the required trades to return to target, and executes them through a non-custodial API that prevents the agent from ever withdrawing funds.
What is AI portfolio rebalancing and why automate it?
Portfolio rebalancing is a mechanical discipline, not a market prediction strategy. Over time, price movements cause some assets to become overweight and others underweight relative to a target allocation, which changes the portfolio's risk profile. An AI agent automates the arithmetic and execution: it measures drift, computes the necessary trades, and submits orders without requiring a human to log into multiple venues or calculate share counts manually. Because Felix exposes stocks, crypto, perpetual futures, options, and prediction markets through a single API that normalizes contract math into plain dollars, the agent can treat a stock position and a crypto position identically when calculating weight drift. How trading APIs let AI agents trade across markets explains this abstraction in more detail. Without automation, investors often delay rebalancing because selling winners feels uncomfortable and buying losers feels counterintuitive. The agent removes that emotional friction by following rules. However, automation does not remove risk. Trading can lose money, including everything, and an agent that rebalances too frequently can lose capital to fees and slippage. A developer must treat the rebalancer as a control system, not an alpha generator.
Developers typically choose between calendar-based rebalancing and threshold-based rebalancing. A calendar approach runs the agent every day or week regardless of drift, which is simple but may trade unnecessarily. A threshold approach lets the agent sleep until drift exceeds a limit, which reduces fees but requires continuous or frequent polling. Most production systems use a hybrid: check drift every hour, but trade only when the threshold is breached. This minimizes both computational load and transaction costs.
How do you model the portfolio and set target weights?
Start with the total investable capital in dollars. Define each asset's target weight as a percentage of that total, ensuring the weights sum to exactly one hundred percent. Then choose a drift threshold, which is the tolerance band around each target before the agent acts. An absolute threshold of five percentage points means an asset with a twenty percent target can drift between fifteen and twenty-five percent without triggering a trade. A relative threshold of twenty percent means the same asset would trade only if it drifted below sixteen percent or above twenty-four percent. Absolute thresholds are usually easier to reason about for multi-asset portfolios, while relative thresholds work better when target weights vary widely across assets. You must also decide whether cash is an asset class with its own target weight or a residual buffer. If cash has a zero percent target, the agent will attempt to deploy all available cash into underweight positions. If cash has a ten percent target, the agent will raise cash by selling overweight assets when needed. Consider correlation and liquidity. Rebalancing between two highly correlated assets may not reduce risk enough to justify the transaction costs. An agent cannot rebalance into an illiquid options contract or a thin perps market without accepting slippage. You should also consider whether the account is taxable, because the agent does not know about tax lots or harvesting logic unless you explicitly code for it. How to size positions for an AI trading agent step by step covers the underlying logic for converting weight deltas into precise dollar orders, which the rebalancer uses for every trade.
- ·Define the investable capital base in dollars.
- ·Assign target weights to each asset or asset class.
- ·Choose an absolute or relative drift threshold.
- ·Decide whether cash is a target allocation or a residual.
- ·Verify that each asset is tradable on an authorized venue.
How does the agent calculate and execute trades?
The agent begins by fetching current positions and mark prices through the API. It converts every position into a notional dollar value, sums them into a total portfolio value, and computes the current weight of each asset. The drift for each asset is simply the current weight minus the target weight. If the absolute value of that drift exceeds the threshold, the agent flags the asset for rebalancing. The dollar value of the required trade is the drift multiplied by the total portfolio value. A negative drift means the asset is underweight, so the agent generates a buy order. A positive drift means the asset is overweight, so the agent generates a sell order. The agent then checks constraints. It cannot sell more of an asset than it currently holds unless short selling is explicitly enabled. It cannot submit orders below minimum size thresholds. If the sell orders generate insufficient cash to fund all buy orders, the agent should scale down the buy orders proportionally rather than exceed its budget. Some developers prefer to fund buys only from sells, while others allow the agent to hold a small cash reserve. Once the trade list is finalized, the agent submits orders. The exact request schema is in the docs; the shape looks like this:
POST /api/rebalance
Authorization: Bearer YOUR_KEY
Content-Type: application/json
{
"strategy": "portfolio_rebalance",
"drift_threshold_percent": 5,
"target_weights": {
"asset_a": 0.50,
"asset_b": 0.30,
"asset_c": 0.20
},
"max_order_value_usd": 5000,
"allow_partial": true
}This example is illustrative. The actual endpoint and field names may differ, so refer to the documentation for the current schema. The key point is that the agent sends dollar amounts, not share counts or contract sizes, and the API handles normalization across venues. After submission, the agent should log fills and wait for settlement. If an order receives a partial fill, the agent should record the remaining desired quantity and either wait for the next rebalance cycle or resubmit according to a policy you define in advance. The agent should also verify that the post-trade portfolio actually reduced drift before considering the job complete.
What safety controls keep the agent within bounds?
An autonomous rebalancer must have hard guardrails because it operates without per-trade human approval. Felix provides several layers of safety. First, scoped API keys mean the key you give the agent can place orders but cannot withdraw funds or change account settings. The funds sit in a wallet you control, and withdrawal addresses are owner-approved only. Second, budget caps limit how much notional value the agent can trade in a given period, which prevents a logic error from generating unlimited orders. Third, position limits prevent any single asset from exceeding a maximum weight, even if the target weight is higher and the agent is trying to buy a dip. This acts as a circuit breaker against runaway behavior. Fourth, drawdown limits can pause the agent if the total portfolio value falls by a preset percentage, preventing the agent from rebalancing deeper into a crisis without human review. Fifth, an exit plan defines what happens if the agent loses connectivity: orders can be set to cancel after a timeout rather than remain open indefinitely. Finally, a panic or kill switch flattens positions and revokes the agent's key instantly. How a Claude trading agent trades without taking custody of your funds describes the non-custodial architecture that makes these controls possible. You should also add a cooldown period, such as six hours after a rebalance, to prevent the agent from churning the portfolio if prices oscillate near the threshold. Without these controls, a simple bug in drift calculation could cause repeated wash trading and rapid capital erosion.
How do you test and evaluate before live capital?
Paper trading is the first step. Felix supports paper trading so you can run the agent against live market data without risking capital. Run the agent for several days and inspect the order log. Look for tiny orders that indicate rounding errors, or excessive order counts that indicate a threshold set too tight. Feed the agent historical portfolio snapshots to see how it would have behaved during past volatility. This is a backtest of logic, not a prediction of profit. Test edge cases deliberately. Suppose an asset price drops to zero or the asset is delisted; the agent should skip it and alert, not block indefinitely. Suppose the API returns a stale price with an old timestamp; the agent should verify data freshness before trading. Imagine a scenario where two assets cross the threshold simultaneously but the agent has buying power for only one; your logic should handle priority gracefully. Latency is another consideration. If the agent checks prices and submits orders slowly, the market may move between calculation and execution, leaving the portfolio still out of balance. Never assume that profitable backtests guarantee future results. Trading can lose money, and backtests often assume perfect fills and stable liquidity that do not occur in live markets. Use paper trading to validate the integration, and use historical simulations only to validate the arithmetic.
What does monitoring look like after launch?
When you move to live trading, start with a small fraction of your total capital and authorize the key explicitly. The first live rebalances should be watched closely. Compare the portfolio state before and after execution to confirm that drift actually decreased. Review fees as a percentage of portfolio value; if the cost of rebalancing exceeds the risk reduction benefit, your threshold is too tight. Check for partial fills and rejected orders, which can leave the portfolio in a half-rebalanced state. Measure tracking error by recording the standard deviation of weight drift over time; a well-tuned agent should keep this low without excessive trading. Monitor slippage by comparing the intended notional trade value against the actual filled notional value. If slippage is consistently high, the agent may be trading during illiquid periods or using market orders when limit orders are more appropriate. Keep the kill switch accessible and test it once during the first week to ensure it flattens and revokes as expected. How to evaluate AI portfolio rebalancing with real money offers a longer framework for ongoing assessment. Increase capital allocation only after you have observed stable, predictable behavior across multiple market conditions. Even then, remember that all trading carries the risk of loss, and automation does not change that.
Frequently asked questions
Yes. The Felix API abstracts venue-specific contract sizes so the agent can treat all positions as dollar values. A single rebalance job can sell an overweight stock position and buy an underweight crypto position, provided the owner has authorized both market types on the key.
The developer should code a fallback, such as scaling down all buy orders proportionally or skipping the smallest adjustments. The agent should never exceed the scoped budget cap or attempt to trade on margin unless explicitly configured to do so.
That depends on the asset volatility and transaction costs. A common starting point is every four hours or once per day. Checking continuously can lead to churn and excessive fees, so most developers add a cooldown period after each successful rebalance.
The agent can incorporate new cash by treating it as an increase in total portfolio value and applying target weights to the new total. Withdrawals are owner-approved only; the agent cannot initiate a withdrawal, so the owner must manually remove funds and then update the target base capital.
The most common error is setting the drift threshold too tight, which causes the agent to trade constantly and lose money to fees. Another frequent mistake is failing to account for minimum order sizes, which can leave the agent generating orders that venues reject.
No. Rebalancing is a risk-management discipline, not a profit guarantee. It can reduce concentration risk, but all trading can lose money, and poor thresholds or bad market conditions can lead to losses.
Give your agent a key.
One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.
Newcomers often treat scoped API keys like strong passwords. In practice, they are programmable contracts that limit what an agent can do, regardless of whether the agent is buggy, compromised, or hallucinating.
Running a trading agent from Claude means connecting an LLM to real markets through MCP tools and scoped API keys. This guide walks through the architecture, safety setup, and first steps without assuming prior automation experience.