How to secure an AI trading agent step by step
An AI trading agent needs non-custodial keys, scoped permissions, budget caps, and a kill switch before real money. Here is a security guide for developers.
- 01Non-custodial architecture means the agent can trade within limits but can never withdraw funds to an address the owner has not explicitly approved.
- 02Scoped API keys should restrict each agent to specific markets, order types, and maximum position sizes so a bug cannot wander across the entire portfolio.
- 03Budget caps and position limits act as independent guardrails that enforce maximum loss before the agent reaches a venue.
- 04A kill switch must flatten all positions and revoke the agent's key in a single automated step, because manual intervention during a flash event is usually too slow.
- 05Paper trading proves the plumbing works, but it does not prove the agent is secure; only explicit owner authorization of a live key should enable real money.
An AI trading agent should never hold custody of the funds it trades. Before any code sends an order, the developer must set up non-custodial wallet permissions, scoped API keys, strict budget caps, and a kill switch that can flatten positions and revoke access instantly. These layers are the baseline infrastructure that keeps an autonomous system from moving faster than its owner can react, and this guide walks through each layer in order, starting with wallet architecture and ending with the explicit authorization step that separates paper testing from real money.
What does non-custodial mean for an AI agent?
In a custodial setup, the agent or the service behind it holds the private keys to the trading account. If the agent is compromised, the attacker can withdraw everything to an external wallet with no recourse. A non-custodial design removes that risk by construction. The owner controls the wallet and pre-approves withdrawal addresses. The agent receives a scoped key that can place orders, manage positions, and sometimes transfer funds between pre-approved internal accounts, but it cannot unilaterally send money to itself or to a new address. This architecture changes how developers think about failure. A bug in the agent's logic might still cause bad trades, but it cannot result in total theft. The damage is bounded by the trading budget and position limits, not by the entire account balance. When you build on infrastructure that is non-custodial by construction, you do not need to trust the agent's reasoning. You only need to trust the permission layer underneath it. That distinction is critical because LLM agents are probabilistic. They can hallucinate strategies, misread prompts, or loop under edge conditions. A deterministic permission layer should override any probabilistic output. The agent proposes, the wallet disposes. Developers sometimes confuse partial access with full custody. Giving an agent an API key to a centralized account is not non-custodial if that same key can withdraw to any address. True non-custodial infrastructure requires that withdrawal addresses are owner-approved only, and that the agent's key is physically incapable of changing that list. Before you integrate any trading API, verify the permission matrix. If the agent key has withdrawal rights, assume breach is total loss and redesign the key scope.
How should you scope an API key for a trading agent?
Scoped keys are the first line of defense against a logic error. A single API key that can trade stocks, crypto, perps, options, and prediction markets sounds convenient, but it multiplies the blast radius of a single bug. The correct approach is to issue one key per agent or per strategy, and to restrict each key to the specific markets and instruments it actually needs. Start with market type. If the agent is designed for prediction markets, the key should not have permissions for options or perps. Then restrict order types. Many agents only need market orders and limit orders. There is rarely a reason to grant cancel-all, mass modify, or advanced execution types unless the strategy explicitly requires them. Next, set a maximum order size in plain US dollars. This prevents the agent from accidentally sizing an order in native units and sending a thousand times the intended notional value. The API should normalize venue-specific contract math so the developer thinks in dollars, not in ticks or lot sizes. Time restrictions also matter. A key that is valid only during trading hours, or only for a specific session, reduces the window for unattended behavior. IP allowlisting adds another layer, though it is less practical for cloud-hosted agents that may shift addresses. The principle is least privilege. Every permission that is not strictly necessary should be removed. If the agent later needs a new capability, you can issue a new scoped key rather than weakening the existing one. This practice is tedious but it pays for itself the first time a prompt injection or loop sends an unexpected command. You can see how these protections fail when they are skipped in How guardrails for trading agents break in practice. You should also separate read keys from write keys where possible. A monitoring agent that checks positions and calculates signals does not need the same key as the execution agent. If the monitoring layer is compromised, the attacker gains information, not control. This separation limits the number of surfaces that can reach the market. When you design the key hierarchy, imagine the worst possible prompt the agent could receive, and then confirm that the key would block it.
What are the right budget and position limits?
Budget caps and position limits are independent guardrails that sit below the agent's strategy. They exist because an agent does not know when it is wrong. A model might double down on a losing position because its training data favored persistence, or it might misread a news headline and allocate far more capital than intended. Hard limits stop these behaviors before they reach a venue. A budget cap should be defined in US dollars and should represent the maximum capital the agent can deploy at any moment. This is not the same as account equity. The owner might hold fifty thousand dollars in the wallet but only authorize the agent to trade five thousand. The cap should also specify the maximum loss per day or per trade, because a budget that allows full redeployment after every loss is effectively a larger cap than it appears. Position limits are equally important. They prevent the agent from concentrating the entire budget in a single instrument. A sensible starting point is to limit any single position to a fraction of the total budget, such as ten or twenty percent, depending on volatility. For options, the limit should also account for maximum risk at expiration, not just entry premium. The Greeks can shift quickly, and an agent that does not understand gamma risk can still be stopped by a hard notional limit at the API level. How hard limits keep AI agents safe when trading options covers this in more detail. These limits must be enforced by the infrastructure, not by the agent's own code. An agent that checks its own budget is like a driver relying on the speedometer to regulate the engine. The limit belongs in the API or the wallet layer, where it cannot be overridden by a prompt, a code change, or a jailbreak attempt. If the agent requests a trade that violates the limit, the API should return a clear rejection and log the event. Those logs become part of the audit trail that tells you whether the agent is misbehaving or simply misinformed.
Why does a kill switch matter more than a stop loss?
A stop loss is a trading instruction that tells the agent to exit a position when a price level is hit. A kill switch is an infrastructure command that tells the system to flatten everything, revoke the key, and disconnect the agent from the account. The difference is control. A stop loss can fail if the market gaps, if liquidity disappears, or if the agent's logic prevents it from executing. A kill switch is external and unconditional. Developers often build elaborate stop rules but neglect the kill switch because it feels like an admission of failure. In practice, it is the most important safety tool. Markets can move faster than any API can respond, and an agent that is looping or hallucinating will not respect a gentle stop request. The kill switch should be a single authenticated call that triggers a sequence: cancel all open orders, close all open positions at market where possible, and disable the API key so the agent cannot reconnect. The trigger can be manual, but it should also be automated. If the daily loss cap is breached, if the agent sends more than a threshold number of orders per minute, or if a health-check heartbeat stops, the switch should fire. Testing the kill switch is as important as testing the strategy. You should trigger it during paper trading at least once to measure how long the flattening takes and whether any positions remain open in illiquid markets. If the agent trades across multiple venues, the switch must reach every venue simultaneously. A partial kill is not a kill. One subtle risk is that the kill switch itself can be triggered by the agent if the agent has access to the same authentication context as the owner. Keep the switch credentials separate from the trading key. The owner or a separate monitoring service should hold the revocation capability. If the agent is running inside an MCP client or an AI code editor, make sure the kill command is not in the same project context that the agent can read or modify.
How do you test security before going live?
Paper trading is the standard first step, but it tests connectivity and logic, not security. In a paper environment, the API key often has broader permissions than it will in production, and the emotional pressure of real money is absent. Use paper trading to verify that the agent reads data correctly, sizes orders in dollars, and respects the basic strategy parameters. Then run a security audit on the key permissions before you authorize live trading. Review the scoped key configuration in a separate session from strategy development. Read every permission aloud and justify it. If the key can access a market the agent does not currently trade, remove it. Check the withdrawal whitelist to confirm that only the owner's addresses are present. Verify that the budget cap is set at the infrastructure level and not passed as a variable the agent can override. You should also simulate failure modes. Introduce a bad prompt and watch what the agent tries to do. If the scoped key is correct, the bad prompt will result in a permission error, not a bad trade. Test the kill switch under load. Send a burst of paper orders and then trigger the switch. Measure the time to flat. If the agent is trading across multiple markets, confirm that the switch reaches every venue. For a practical checklist, see How to run a trading agent from an AI code editor. Finally, inspect the audit trail. Every rejected order, every cap breach, and every kill switch trigger should be logged with a timestamp and a reason. If the logs are incomplete, the security layer is incomplete. Developers sometimes focus on trade execution logs and forget permission logs. Both are necessary for post-incident review. A clean paper trading record means nothing if the security logs show that the agent could have bypassed a limit had it tried.
How do you authorize real money without losing custody?
Live trading requires an explicit owner authorization step. The system should not default to real money after paper trading succeeds. The owner must approve a specific key for live use, usually through a signed transaction or a separate authentication flow that the agent cannot perform. This step ensures that the transition from simulation to real capital is intentional and auditable. After authorization, the owner should still maintain the same non-custodial controls. The wallet remains under the owner's private key. The agent's API key is still scoped, capped, and revocable. The owner can review the authorized key at any time and remove it without asking the agent for permission. This is the final check in the security chain: the owner, not the agent, decides when trading begins and ends. How a news-driven LLM agent trades real money without taking custody shows what this looks like in practice. Developers should document this authorization flow in their runbooks. If the agent is deployed from an AI code editor or an MCP client, the documentation should state exactly which key is live, which markets it touches, and who can trigger the kill switch. Clarity here prevents the common mistake of leaving a test key active in a production environment, or worse, assuming that a live key is somehow safer because it has been used before. Security is a process, not a product. Every deployment of an AI trading agent should start with the assumption that something will go wrong, and the permission layer should be built to survive that assumption. Trading can lose money, including everything. No permission layer can prevent a poorly designed strategy from losing the budget it is allowed to trade. The goal of security is not to guarantee profit. It is to guarantee that the agent cannot take more than the owner explicitly allowed.
Frequently asked questions
No. Non-custodial architecture means the agent cannot withdraw funds to an address that the owner has not pre-approved. It can trade within scoped limits, but it cannot move capital outside the owner's control.
No. Issue one scoped key per agent or strategy, and restrict each key to the specific markets and order types it needs. This limits the damage if one agent malfunctions or is compromised.
A stop loss is a trading rule that the agent may fail to execute. A kill switch is an infrastructure command that flattens all positions and revokes the key unconditionally, regardless of market conditions or agent logic.
No. Paper trading tests logic and connectivity. Security requires a separate audit of key permissions, budget caps, position limits, and kill switch behavior before you authorize live trading.
The owner must explicitly authorize a specific key for live use through a separate authentication flow. The system should never default to real money automatically after paper trading succeeds.
Hard limits prevent the agent from losing more than the owner allows, but they cannot prevent losses within that budget. Trading can lose money, including the entire allocated amount.
Give your agent a key.
One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.
Perpetual futures look simple through a unified API, but most builders underestimate funding rates, margin math, and the speed at which leverage amplifies errors. Here is what actually matters.
A webhook pushes market events to your agent instantly, removing the delay and waste of polling. Here is how to build a safe handler and test it before going live.