Agentic tradingPortfolio managementDevelopersSelf-custody

How to rebalance a portfolio with an AI agent without giving up custody

Developers can automate portfolio rebalancing with an AI agent while keeping funds in a wallet they control. Non-custodial APIs and scoped keys make this possible.

By the Felix team9 min read
Key takeaways
  • 01Non-custodial rebalancing lets an AI agent trade across multiple market types while your funds remain in a wallet or account that only you control.
  • 02Scoped API keys enforce strict limits on what the agent can do, removing withdrawal permissions and capping both spend and position size.
  • 03Dollar-based order sizing abstracts away venue-specific contract math, allowing the agent to reason in simple percentages and US dollar amounts.
  • 04Paper trading provides a safe environment to validate rebalancing logic before you explicitly authorize a live key and real capital.
  • 05A kill switch, budget caps, and position limits are essential safety controls, but they cannot eliminate the risk of losing money entirely.

You can automate portfolio rebalancing with an AI agent without ever transferring funds to a third party. The agent receives a scoped key that can place orders within dollar limits you set, but it cannot withdraw funds or change your withdrawal addresses. Your capital stays in a wallet or account that you control, and you can revoke the agent's access at any time.

What does non-custodial rebalancing actually mean?

Many developers assume that automating a portfolio requires depositing funds into a centralized exchange or a managed account where you no longer hold the keys. Non-custodial rebalancing rejects that assumption. Your funds stay in your own wallet or brokerage account, and you issue a scoped API key that grants the agent strictly limited trading rights. The key cannot move funds to an external address, change account settings, or view personal information beyond the balances and positions needed for allocation math. If the agent is compromised, the attacker is trapped inside the permissions you defined ahead of time. This architecture works across stocks, crypto, perpetual futures, options, and prediction markets. The API normalizes access so that the agent can treat a stock broker, a perps venue, an options venue, and a prediction market as a single portfolio layer. You remain the ultimate custodian, and the agent is a temporary operator with a restricted set of keys. The distinction is important: delegation means the agent can act on your behalf, but custody means the agent controls the assets. Felix is designed for delegation without custody. Because the key is scoped, you can rotate it or revoke it without moving funds or closing accounts. If you decide to stop using the agent, you simply delete the key and the access is gone. There is no offboarding process or withdrawal queue. For a deeper look at the mechanics, see How an AI agent executes orders while you keep full custody.

How do you scope an agent's permissions for rebalancing?

The principle of least privilege should guide every key you create. Start by listing exactly what the agent needs to do: read balances, read market data, and place orders that rebalance toward your target allocation. It does not need the ability to withdraw, transfer, or change withdrawal addresses. It also does not need access to markets you do not intend to trade. You can restrict the key to a whitelist of symbols or asset classes so that a hallucinated or errant order is rejected at the API level before it reaches a venue. Budget caps add another layer of defense. Suppose you set a target allocation of fifty percent stocks, thirty percent crypto, and twenty percent prediction markets. The agent calculates the deviation between current weights and targets, then generates buy or sell orders. A daily budget cap of one thousand dollars ensures that even if the agent misinterprets a signal, it cannot spend more than that amount in a twenty-four hour period. Position limits prevent any single asset from exceeding a maximum notional size. You can also set a maximum rebalance frequency, such as once per day, to prevent the agent from overtrading during volatile periods. It is also useful to separate read-only keys from trading keys during development. A read-only key lets you build and test the allocation logic without any risk of accidental execution. Once the logic is stable, you swap in the scoped trading key with its specific limits. These guardrails are covered in more detail in How to build guardrails for a trading agent and How to control the risks of LLM-powered trading without giving up custody.

Why does dollar-based sizing simplify cross-market rebalancing?

Rebalancing across multiple market types introduces a unit problem that complicates both portfolio math and risk management. Stocks trade in whole shares, crypto perpetual futures trade in contracts with notional exposure, options trade in lots of one hundred shares, and prediction markets trade in outcome shares with binary payoffs. If the agent had to reason in native units, it would need venue-specific logic for every market, increasing the chance of a sizing bug that blows through a budget cap. Imagine an agent that confuses contract notional value with margin required and sends an order ten times larger than intended. Felix avoids this by accepting orders denominated in plain US dollars. The developer writes allocation logic in percentages of total portfolio value, and the agent converts those percentages into dollar amounts. The API then translates each dollar amount into the correct native unit for the specific venue. This means the core rebalancing algorithm stays market-agnostic and you can test it in isolation. It also makes risk management easier because a budget cap or position limit is expressed in a single currency that you intuitively understand. The agent never needs to calculate margin ratios, tick sizes, or contract multipliers, so there are fewer places for an arithmetic error to hide. Dollar sizing also simplifies reporting. When you review the agent's activity, you see a uniform ledger of dollar amounts rather than a mixture of shares, contracts, and lots. This makes it easier to audit whether the agent stayed within its mandate and whether the rebalancing actually brought the portfolio closer to the target weights.

Which safety controls prevent unintended losses?

No automation can eliminate trading risk. Markets gap, liquidity disappears, and models fail. The goal of safety controls is to limit the speed and magnitude of losses, not to guarantee profits. Before you authorize a live key, you should walk through a failure mode analysis. Ask what happens if the agent receives a stale price, if the API returns an error, or if a market drops fifty percent overnight. The safety controls are your answers to those questions. You should configure at least the following protections before the agent touches live capital.

  • ·Budget caps set a hard ceiling on how much the agent can spend in a given period, such as a day or a week. Once the cap is reached, the API rejects further orders until the period resets.
  • ·Position limits restrict the maximum notional exposure for any single asset or market type, preventing a single bad trade from dominating the portfolio.
  • ·An exit plan flattens positions or pauses trading if the portfolio drawdown exceeds a threshold you define, such as five or ten percent.
  • ·A panic kill switch revokes the API key immediately and cancels open orders, returning full control to you within seconds.
  • ·Market whitelists prevent the agent from trading assets outside your intended universe, which limits the blast radius of a misinterpreted signal or prompt injection.

These controls act as independent checks. Even if the agent's logic drifts or an external signal is misinterpreted, the API enforces the boundaries. For more on structuring these protections, read How to control risks in autonomous trading systems that use MCP. Remember that trading can lose money, including everything you allocate to the agent. The controls slow down the damage but do not make the strategy safe.

How do you test a rebalancing strategy before live trading?

Paper trading lets you run the agent against live market data with simulated execution. The agent follows the exact same code path it would use in production, but orders are not sent to live markets with real money. This is useful for catching bugs in allocation math, unexpected API errors, and slippage assumptions. You should observe the agent through multiple rebalancing cycles, ideally across different market conditions, before considering a live deployment. Pay attention to how the agent handles drift when prices move quickly, whether it respects the whitelist, and if it stops correctly when a budget cap is hit. During paper trading, simulate edge cases manually. Suppose a market in your whitelist suddenly has zero volume. Does the agent skip it or does it retry indefinitely? Suppose the total portfolio value drops below the minimum order size for one asset. Does the agent handle the rounding error gracefully? These are the scenarios that expose weak logic. When you are ready to trade real capital, you must explicitly authorize a live key. This authorization is a manual step, not an automatic upgrade from paper mode. Start with a small budget cap and increase it only after the agent behaves predictably for an extended period. Resist the temptation to scale quickly after a short winning streak. Your First Automated Multi-Market Portfolio: A Step-by-Step Walkthrough offers a practical starting point for this process.

What does the integration look like for developers?

Agents can connect through MCP tools for LLM clients such as Claude or Cursor, or through the REST API for scheduled services and custom applications. MCP is convenient for conversational agents that interpret natural language instructions, while the REST API is better for deterministic services that run on a cron job or event loop. For MCP-based agents, the tool definitions themselves act as a form of guardrail. The LLM can only invoke the functions you expose, so you should not expose a generic raw order endpoint. Instead, expose a high-level rebalance function that takes target percentages and a budget cap. This constrains the LLM to your intended interface. The exact request schema is in the docs; the shape looks like this.

curl -X POST \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{\n    "intent": "rebalance",\n    "targets": {\n      "stocks": 60,\n      "crypto": 40\n    },\n    "budget_cap_usd": 1000\n  }' \
  https://api.example.com/v1/orders

The response includes an order identifier and status, which your agent should log and monitor. You should build a health check that alerts you if the agent stops reporting or if order rejections spike. Rejected orders are often a sign of boundary conditions, such as a budget cap being hit or a market leaving the whitelist. In those cases, the agent should pause and wait for developer review rather than retrying aggressively. Good logging and alerting are essential because the agent is unsupervised most of the time. You want to know within minutes, not days, if the automation has stalled or is behaving erratically.

Frequently asked questions

Can the agent withdraw my funds to its own wallet?

No. The scoped key is created without withdrawal permissions. Even if the agent is compromised, it can only place trades within the limits you set. Withdrawal addresses are owner-approved and cannot be changed by the API key.

What happens if the agent makes a mistake during rebalancing?

Safety controls such as budget caps, position limits, and a kill switch limit the scope of any error. You can revoke the key instantly to stop all activity. Trading can still lose money, including the full budget allocated to the agent.

Do I need to deposit funds on a centralized exchange?

No. Non-custodial rebalancing means your funds stay in a wallet or brokerage account that you control. The agent uses a scoped API key to trade on your behalf without taking custody of the assets.

Can I test the rebalancing logic before risking real money?

Yes. Paper trading lets you run the agent against live market data with simulated execution. You should observe multiple rebalancing cycles and verify behavior before authorizing a live key.

Which markets can the agent rebalance across?

The Felix API supports stocks, crypto, perpetual futures, options, and prediction markets. You can define target allocations across any combination of these, and the API normalizes order sizing to plain US dollars.

How do I connect my agent to the API?

Agents can connect through MCP tools for LLM clients like Claude or Cursor, or through the REST API for custom services. The docs at [docs](/docs) cover authentication and request formats.

Give your agent a key.

One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.

Keep reading

Not a brokerage, exchange, or investment adviser. Not investment advice. Trading involves risk, including total loss.