Agentic tradingDevelopersSecurityRisk

How to build scoped API keys for a trading agent step by step

Scoped API keys limit what a trading agent can do and how much it can lose. This guide walks through designing, creating, and enforcing those limits step by step.

By the Felix team11 min read
Key takeaways
  • 01A scoped API key should expose the minimum permissions, markets, and budgets required for the agent's specific strategy, nothing more.
  • 02Non-custodial architecture means the agent can trade within owner-approved limits but cannot unilaterally withdraw funds or change those limits.
  • 03Every key needs a kill switch that flattens positions and revokes access without requiring manual intervention at the venue.
  • 04Paper trading with identical scoped keys lets you validate that the agent respects limits before it touches live capital.
  • 05Trading with real money can result in total loss, and scoped keys reduce but do not eliminate that risk.

A scoped API key for a trading agent restricts which markets the agent can access, what actions it can perform, and how much capital it can place at risk. Building one step by step means defining the agent's purpose, translating that purpose into hard numeric limits, encoding those limits into the key or the policy that governs it, and testing the boundary before the agent touches live funds. The goal is not to make the key convenient for the agent, but to make it impossible for the agent to act outside the owner's intent even if the model behaves unexpectedly or is prompted to do so.

What is a scoped API key in agentic trading?

A general API key is a master credential. If an agent holds one, a bug, a prompt injection, or a confused model output can turn into a market order, a withdrawal, or a leveraged position the owner never intended. A scoped API key is different. It is a credential bound to a policy that the infrastructure enforces, not a suggestion the model may ignore. The policy lives on the server side, which means the agent can ask for anything, but the API will only execute what the scope allows. This distinction is critical because large language models are probabilistic. They can drift, misinterpret context, or be jailbroken. A client-side check in the agent's code is insufficient because the agent itself controls the code execution path. A server-side scope is enforced by the trading infrastructure, so the request never reaches the market if it violates the policy. In the Felix model, the owner holds the funds in a self-custodial wallet. The agent receives a key that can trade across stocks, crypto, perpetual futures, options, and prediction markets through a single interface, but the owner decides which of those markets are actually reachable by that specific key. The agent cannot withdraw to an external address because withdrawal addresses are owner-approved and typically excluded from agent keys entirely. This is the difference between a trading agent and a traditional trading bot. A bot often runs with a broad key and relies on its own internal logic to stay safe. An agent relies on the infrastructure to keep it safe because the agent's reasoning is not deterministic and can drift. Scoped API Keys for Trading Agents: Roll Your Own or Use an Agent-Ready API covers the high-level trade-offs between building your own scoping layer and using an API that ships with one. This article assumes you are doing the latter and focuses on the practical steps of configuring that scope for a single agent.

How do you decide what an agent should be allowed to do?

Start with a one-sentence strategy description. If you cannot state the agent's job in one sentence, the scope is already too broad. Suppose the agent is meant to run a long-only momentum strategy in large-cap stocks. That statement tells you the market type, the direction, the style, and the universe. From there, you derive the permissions in four layers. First, choose the markets. If the agent trades stocks, disable crypto, perpetual futures, options, and prediction markets on the key. One API reaches all five, but the key should only see the one it needs. Second, choose the actions. The agent needs to read market data, create orders, and cancel its own open orders. It does not need to withdraw funds, change wallet settings, approve new withdrawal addresses, or modify the scope itself. Third, choose the instrument universe. A scoped key should list the allowed symbols or apply a tight filter. If the agent is only allowed to trade two specific large-cap names, the key should reject an order for a third symbol even if the model hallucinates a signal. Symbol whitelisting is far safer than blacklisting because new assets launch constantly and a blacklist cannot anticipate them. Fourth, choose the temporal bounds. Some strategies only trade during regular equity hours. A scoped key can enforce that window so the agent does not place orders at 3 AM because it misread a timestamp or because a scheduled task fired early. This is the principle of least privilege applied to finance. The agent receives the minimum surface area required to do its job and nothing else. A well-scoped key does not replace a good prompt, but a good prompt cannot replace a well-scoped key. The prompt is advice; the key is a wall. If the model is compromised or confused, the prompt fails, but the wall remains.

How do you translate strategy into numeric limits?

Once the qualitative boundaries are set, the next step is to turn them into numbers that the API can enforce. This is where most developer guides stop at abstract advice, but the limits are the actual protection. Begin with the per-order cap. This is the maximum notional value in US dollars that a single order can carry. If the agent is meant to trade in $500 increments, the cap should be $500. The API normalizes venue-specific contract math, so you state the cap in plain dollars and the system handles the conversion. This prevents a model error from turning a $500 order into a $50,000 order because it misplaced a decimal or misread a token count. A per-order cap is your first line of defense against individual order accidents. Next, set the daily or weekly budget cap. This is the total notional the agent can deploy over a time window. If the strategy is designed to hold five positions of $500 each, a daily budget cap of $5,000 gives the agent room to enter and rotate without letting it build a $50,000 book. The budget cap should be a fraction of the total wallet balance, not the whole balance. The agent should not be able to deploy the entire stack in one day. Suppose the wallet holds $50,000. A daily budget cap of $5,000 means the agent can only lose a tenth of the capital in a single day of runaway trading. Then, set position limits. A max position notional cap prevents the agent from pyramiding into a single name. A max concentration cap prevents the agent from putting 90% of the budget into one symbol. If the strategy uses derivatives, add a leverage cap. If the agent is authorized for 2x leverage on perpetual futures, the key should reject a 5x order. The API should enforce this before the order reaches the venue. For options, the same logic applies to contract quantity and max premium at risk. The scoped key should not assume the agent will size responsibly. Finally, add a drawdown trigger. This is a soft or hard pause that stops new order creation if the agent's realized and unrealized PnL drops below a threshold. A drawdown limit is not a stop loss on a single trade; it is a circuit breaker on the entire agent. If the strategy loses 5% of allocated capital in a day, the key disables new orders and notifies the owner. This prevents the agent from doubling down or switching strategies in an attempt to recover losses.

The exact request schema is in the docs; the shape looks like this:

{
  "tool": "create_scoped_key",
  "params": {
    "name": "momentum-stocks-agent",
    "markets": ["stocks"],
    "permissions": ["read", "create_order", "cancel"],
    "budget": {
      "max_order_usd": 500,
      "max_daily_usd": 5000
    },
    "position_limits": {
      "max_notional_usd": 10000,
      "max_concentration_percent": 20
    },
    "leverage_cap": 1,
    "drawdown_circuit_breaker_percent": 5,
    "allowed_symbols": ["SYM_A", "SYM_B"],
    "withdrawal_enabled": false
  }
}

Note that the field names above are illustrative. The exact structure and parameter names depend on the current version of the API, which you should verify in the documentation.

How do you build in a kill switch and exit plan?

A scoped key without a kill switch is only half a safety system. The kill switch is an owner-controlled command that flattens all positions and revokes the key immediately. It must not depend on the agent's reasoning or willingness to comply. If the owner triggers it, the infrastructure sends exit orders, cancels open orders, and disables the key before the agent can object. The agent might be in the middle of a reasoning loop, but the key is already dead. This is essential because an agent that has gone off course may not recognize that it has gone off course. It might argue that its positions are justified. The kill switch bypasses all of that. The exit plan is the automated inverse of the entry strategy. Every entry should have a planned exit. This can be a stop loss, a take profit level, a time-based exit, or a conditional exit based on a signal change. The key detail is that the exit plan should be encoded in the scoped policy or in a separate automation layer, not left as a prompt instruction that the model might forget after a long context window. How to build your first automated exit plan and take-profit strategy walks through the logic of setting these levels. When you combine that with a scoped key, the exit plan becomes enforceable infrastructure rather than a hope. The panic switch and the exit plan serve different purposes. The exit plan handles normal risk management within the strategy. The kill switch handles abnormal conditions: a market crash, a model hallucination, a detected compromise, or simply the owner's decision to stop. Both should be tested in paper mode before the agent goes live. The owner should know the latency of each. An exit plan might take seconds or minutes to fill depending on liquidity. A kill switch should revoke the key instantly even if the flattening orders are still in flight.

How do you test a scoped key before live trading?

Paper trading exists so you can validate the scope without paying for mistakes. The critical rule is that the paper key must have the exact same limits as the live key. If the paper key is broader, you are not testing the safety layer. Create the scoped key, attach it to the paper environment, and run the agent for a meaningful period. A few hours is rarely enough. You need to see how the agent behaves across different market conditions, schedule windows, and signal types. During testing, attempt to breach the scope. Prompt the agent to trade a symbol outside the allowed list, to size an order above the cap, or to request a withdrawal. Each request should be rejected by the API with a clear error. If the agent can talk its way around the limit in paper mode, it will do so in live mode. Next, test the drawdown circuit breaker. Simulate or wait for a scenario where the drawdown threshold is hit, and verify that new orders are blocked while exit orders are still allowed. Then test the kill switch. Trigger it manually and confirm that positions flatten and the key is revoked within seconds. Finally, test revocation without the kill switch. Disable the key and ensure the agent cannot reconnect, while confirming that the owner retains full manual access to the wallet and funds. Many developers skip the breach attempts. Common mistakes running Claude trading agents with self custody includes the assumption that a polite agent will stay inside its prompt boundaries. It will not. The scoped key is the boundary. When you are confident the scope holds, you can authorize live trading. How to take an AI trading agent live in 2026 covers the authorization steps and the final checks before the first real dollar is deployed.

How do you rotate or revoke a key without losing custody?

Non-custodial architecture means that revoking the agent's key does not freeze the owner's assets. The funds sit in a wallet the owner controls. The key is merely a permission to trade from that wallet within limits. If you revoke the key, the agent stops, but the owner can still withdraw, deposit, or trade manually. The wallet does not disappear when the key does. Key rotation should be routine. When you update the strategy, retire the old key and mint a new one with the new scope. Do not reuse keys across different agents or strategies. Each agent should have its own credential so that a compromise or a bug in one agent does not affect the others. Keep an audit log of every key created, revoked, and modified. The log should include not just the orders that succeeded, but the orders that were rejected. Rejections are proof that the scope is working. They show that the safety layer caught an out-of-bounds request. If you detect an anomaly, the sequence is simple. Trigger the kill switch to flatten positions. Revoke the key. Then investigate. The owner can always move funds to a new wallet and start over with a fresh key if the compromise is severe. Because withdrawal addresses are owner-approved only, the agent cannot send funds to itself during the window between detection and revocation. The owner remains in control at every step.

Frequently asked questions

Frequently asked questions

Can one API key safely control multiple agents?

No. You should create a separate scoped key for each agent and each strategy. Sharing a key across agents breaks audit trails and means a bug in one agent can consume the budget or hit the drawdown limit intended for another.

What happens if an agent reaches its daily budget cap?

The API rejects any new order creation until the budget window resets. Open positions remain open and exit plans still execute, but the agent cannot add new risk. The owner can manually adjust the cap if the strategy genuinely requires it.

Does a scoped key prevent the agent from losing money?

No. Scoped keys limit the speed and scale of losses, but markets move and trading carries the risk of total loss. The key is a containment tool, not a prediction tool.

How fast does a kill switch work?

The kill switch sends exit orders and revokes the key as soon as the owner triggers it. The exact time depends on market liquidity and the number of open positions, but the key is disabled immediately so the agent cannot open new trades while exits are in flight.

Should I test the scoped key in paper trading first?

Yes. The paper environment should mirror the live scope exactly. Test normal operations, breach attempts, and the kill switch before authorizing live trading. Paper trading with mismatched limits gives a false sense of safety.

Can I change the limits on an existing key?

It depends on the implementation. Some systems allow live policy updates; others require key rotation. Check the current docs for the recommended path. Rotation is often safer because it forces you to re-document the strategy and limits.

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.