How one API routes orders across five market types for AI agents
A single API and key can route orders to stocks, crypto, perpetuals, options, and prediction markets while keeping funds non-custodial and enforcing scoped limits.
- 01A single API normalizes stocks, crypto, perpetual futures, options, and prediction markets into plain US dollars so the agent can reason in one currency.
- 02The architecture separates the agent tier, the API policy tier, and the wallet tier so the agent can trade within scoped limits but never withdraw funds.
- 03Scoped keys carry budget caps, position limits, and kill switches that the API enforces before any order reaches a market.
- 04Developers should start with paper trading, use a small live budget, and define an exit plan because trading can lose money, including everything.
- 05Dollar-based order sizing pushes contract math and venue-specific formatting down to the routing layer, reducing unit errors in the agent's reasoning loop.
An AI agent trading API is a thin, stateful routing layer that sits between a model's intent and the execution logic of a broker or venue. It translates natural language or structured intent into dollar-denominated orders, enforces owner-defined guardrails before any request reaches a market, and keeps funds in a wallet the owner controls rather than a pooled account. The agent can spend within scoped limits but can never withdraw funds to itself or change owner-approved withdrawal addresses. This design means the architecture must handle normalization, authorization, and risk enforcement in a single request path before any capital is exposed to market volatility.
How does a single API normalize five different market types?
Each market type speaks a different dialect. A stock broker thinks in whole shares and notional value. A perps venue thinks in contract sizes, margin ratios, and funding rates. An options venue thinks in contract multipliers, strike granularity, delta, and expiration dates. A crypto exchange might think in base and quote increments with varying lot sizes across trading pairs. A prediction market thinks in binary shares, limit prices, and conditional settlement logic. If an agent had to reason in all of these native formats, the prompt context would balloon, the error surface would widen, and the likelihood of a rounding or unit error would increase with every new market.
The API solves this by accepting orders in plain US dollars. When a developer sends an intent, the routing layer inspects the market type, maps the dollar value to the venue-specific contract math, and constructs the native order. The agent does not need to know that a particular perpetual futures contract has a specific margin requirement, or that an options contract controls a specific number of underlying shares. The API computes the correct size, checks the venue's minimums and tick increments, and returns a unified response shape that describes the filled notional value in dollars.
This normalization also applies to market data flowing back to the agent. Rather than forcing the agent to parse five different websocket formats with five different field names for the same concept, the API presents a single schema for positions, balances, and order status. The agent can query its total exposure across a stock position, a perpetual futures position, and an options position in one call and receive numbers it can compare directly. The routing layer handles the currency conversion, contract multiplier division, and notional translation so the agent sees a consistent balance sheet.
The normalization layer also handles idempotency and tracking. Because the agent may retry a request if it suspects a network failure, the API assigns a unique intent identifier to each order. The API deduplicates retries so that a single intent does not result in multiple executions. This is especially important for agents that operate on loops or event triggers, where a stuck process might resubmit the same intent dozens of times. The API's stateful layer acts as a circuit breaker between the agent's reasoning loop and the venue's execution engine.
Developers should still be aware that normalization does not erase market-specific risk. A dollar of exposure in a perpetual future carries funding rate risk and liquidation risk that a dollar of exposure in a stock does not. A dollar of exposure in an option has theta and gamma that a dollar in a prediction market lacks. Even though the API presents both as a dollar value, the agent must still understand the instrument it is trading. The API handles the wire format, but the agent must handle the economics. Common mistakes when using one API for every market usually stem from assuming that unified formatting implies unified risk mechanics.
Where does the non-custodial layer sit in the stack?
Non-custodial design is not a feature added at the end of the development cycle. It is a constraint baked into the key hierarchy from the first request. When an owner creates an API key, the system generates a scoped key pair. The private key material lives in the owner-controlled wallet, which may be hardware-backed or software-backed depending on the owner's preference. The public key is used to derive an agent key that can sign orders but cannot sign withdrawals or change wallet configuration.
The API layer sits between the agent and the wallet as a policy enforcement point. When the agent requests a trade, the API checks the request against the owner-defined policy. If the request passes the policy, the API asks the wallet to sign the order with the scoped key. If the request violates the policy, the API rejects it before the wallet ever sees it. The agent never holds the owner's main key. It never sees a mnemonic or seed phrase. It cannot change withdrawal addresses because those are owner-approved and stored in a separate policy layer that the agent key cannot read.
This means the architecture has three distinct tiers that are separated by network boundaries. The top tier is the agent, which holds reasoning and intent. The middle tier is the API, which holds policy, routing logic, and normalization. The bottom tier is the wallet, which holds the funds and the signing keys. The API can route an order from the agent to the wallet for signature, but it cannot route a withdrawal from the wallet to an agent-controlled address. The policy engine enforces this at the API layer so that even a compromised agent key cannot reconfigure the boundaries or exfiltrate funds.
The wallet itself may be offline for signing, requiring the API to queue requests until the owner approves them. This is useful for high-value accounts where the owner wants to review every order. The API supports both automatic signing within policy and manual signing for extra sensitive thresholds. The owner chooses the mode when creating the scoped key.
The separation between wallet and API also simplifies key rotation. If an owner suspects the agent key has been leaked, they can revoke the agent key without rotating the wallet's main key. The wallet remains untouched. The API simply stops accepting requests from the old agent key and the owner can generate a new scoped key with the same or different policy limits. This rotation takes seconds and does not require moving funds or updating withdrawal addresses. The architecture treats the agent key as disposable and the wallet key as permanent. How scoped API keys let an agent trade without taking custody of your funds explains this key hierarchy in more detail.
How do scoped keys prevent an agent from exceeding its authority?
Scoped keys are policy objects, not just authentication tokens. Each key carries a budget cap, a list of allowed markets, position limits, an exit plan, and a kill switch configuration. The API evaluates every incoming request against this policy object before it reaches the routing layer that speaks to external venues.
Suppose an agent has a daily budget cap of one thousand dollars. If the agent sends an order that would exceed the remaining budget for that calendar window, the API rejects the request with a clear error that the agent can parse. The agent can retry with a smaller size, or it can wait for the budget window to reset. The owner does not need to monitor every request in real time because the API enforces the cap at the boundary. The cap is spend-only. If the agent closes a position for a profit, the realized gain still counts against the daily budget because the architecture treats budget as a flow limit, not a net PnL limit. This prevents an agent from cycling capital rapidly to evade controls.
The API also tracks the time dimension of the budget. A daily cap resets on a calendar boundary, not a rolling window. This prevents an agent from gaming a rolling average by concentrating trades at the boundary. The owner can also set a lifetime cap on a key, which is useful for experimental agents that should be retired after a fixed amount of capital consumption.
Position limits work the same way. If the owner configures a maximum position size of five thousand dollars for a particular market, the API checks the current exposure before accepting a new order. If the agent is already at the limit, any additive order is blocked even if the order direction is technically a hedge. The owner must explicitly configure hedging exemptions if the strategy requires them. The panic switch, or kill switch, is the most aggressive limit. When triggered by the owner or by an automated rule, the API flattens all open positions and revokes the agent key. The agent cannot override this because the kill switch is wired to the owner-controlled policy layer, not to the agent's session. The revocation is immediate and does not wait for the agent to acknowledge. How to add a kill switch to a trading agent with real money walks through the configuration.
What does the MCP layer look like for developers?
Developers can connect agents through Model Context Protocol tools or through the REST API directly. The MCP path is useful when the agent is running inside an MCP client such as Claude or Cursor. The REST path is useful when the agent is a standalone service that polls or streams data without an editor context. Developers who choose the REST path can integrate from any language. The API uses standard HTTP methods and returns JSON. The MCP path exposes the same underlying functionality as tool definitions that the model invokes. Both paths require the same scoped key and both are subject to the same policy checks. The choice is primarily about where the agent runs, not about what it can do.
In either case, the interaction follows the same three-phase pattern. The agent constructs an intent in plain language or structured JSON. The API validates the intent against the scoped policy. If the intent is valid, the API routes the order to the relevant venue and returns a normalized execution report. The exact request schema is in the docs; the shape looks like this:
{
"key": "YOUR_KEY",
"intent": "reduce exposure by fifty dollars",
"market": "perpetual futures",
"symbol": "EXAMPLE-PERP"
}The API returns a normalized execution report that includes the filled notional amount in dollars, the remaining budget for the scoped key, and the current position size across all connected venues. The developer does not need to parse venue-specific error codes or handle decimal precision quirks. The API maps venue errors to a standard set of retryable and fatal errors so the agent can decide whether to try again, wait, or escalate to the owner. The MCP layer exposes these as tools with descriptions that the model can read, so the agent discovers the available actions rather than hardcoding endpoints.
How should developers think about risk when wiring an agent to real money?
Trading can lose money, including everything. This is not a corner case or a theoretical possibility. It is the base case that the architecture must withstand. The API provides guardrails, but guardrails do not eliminate risk. They limit the speed and scope at which losses can accumulate. A kill switch can stop a runaway agent, but it cannot guarantee that the agent has not already lost the budget cap before the switch fires.
Developers should start with paper trading. The API supports a paper mode where orders are routed to simulated execution. The agent experiences the same latency, the same error shapes, the same budget enforcement, and the same market data delays, but no real capital moves. Paper trading is not a guarantee of live success, but it is a necessary filter for logic errors. Only after the owner explicitly authorizes a live key does the API begin routing to real venues. This authorization step is a deliberate friction point in the architecture. It exists so that an agent cannot accidentally promote itself from simulation to live trading through a configuration drift or a prompt injection.
When moving to live trading, the developer should set a small initial budget. A scoped key with a hundred dollar cap teaches the agent the same execution logic as a key with a hundred thousand dollar cap, but the cost of a bug is bounded. The developer should also define an exit plan. An exit plan is a policy rule that tells the API how to close positions if the agent stops sending heartbeats or if the position drift exceeds a threshold. The API can monitor these conditions and trigger the exit plan automatically without waiting for the agent to respond.
Developers should also consider observability. The API emits structured audit logs that show every intent, every policy decision, and every dollar moved. These logs are owner-readable and agent-readable, but they are append-only from the agent's perspective. An agent cannot delete or modify its history to hide a mistake. This logging layer lives outside the agent's control and gives the owner a complete trail for debugging and for understanding how the agent's reasoning translated into capital exposure.
Why do dollar-based orders simplify agent logic?
When an agent reasons in shares, contracts, or lots, it must track multipliers, margin ratios, minimum order sizes, and tick sizes. This is error-prone, especially for perpetual futures and options where the relationship between the contract unit and the dollar exposure is non-linear and varies by underlying asset. The API accepts orders sized in plain US dollars so the agent can think in the same currency it uses for budgeting and risk management.
The API handles the conversion internally. If an agent wants to buy one hundred dollars of a particular stock, the API computes the correct share count, rounds to the venue's lot size, and handles any residual cash. If the agent wants to short one hundred dollars of a perpetual future, the API computes the correct contract size, estimates the margin allocation, and checks the liquidation buffer. The agent does not need to know the contract specifications. It only needs to know its desired dollar exposure and whether it wants to increase or decrease that exposure.
This simplifies prompt engineering and reduces the surface area for unit errors. The developer can tell the agent, "maintain a portfolio with no more than one thousand dollars in tech exposure," and the agent can generate orders in dollars. The API translates those dollars into the correct native units for each venue. The risk of mishandling contract math is pushed down to the routing layer, where it is tested and deterministic. The agent still needs to understand that leverage changes the risk profile, but it does not need to compute the leverage itself.
The simplification also makes backtesting and forward-testing easier. Because the agent's reasoning is in dollars, a developer can replay historical data and compare the agent's intended dollar exposure against actual market prices without translating historical contract sizes. The API's routing layer handles the live conversion, but the strategy logic remains currency-agnostic. This separation of strategy from execution mechanics is the core architectural benefit. How AI agents mishandle perpetual futures and how to prevent it discusses the specific errors that dollar sizing avoids.
Frequently asked questions
No. The agent key can only sign orders. Withdrawal addresses are owner-approved and stored in a separate policy layer that the agent key cannot read or modify. Even if the agent key is compromised, the API will reject any withdrawal request to an unapproved address.
The API rejects the request before it reaches any market. The agent receives an error indicating the budget violation and can retry with a smaller size. The owner does not need to monitor every request because the cap is enforced automatically at the API boundary.
No. Trading can lose money, including everything. The API provides guardrails such as budget caps and kill switches, but these only limit the speed and scope of losses. They do not eliminate market risk or prevent a losing strategy from consuming its entire budget.
No. Live trading requires explicit owner authorization of a specific key. The API treats paper and live routing as separate paths, and the agent cannot promote itself from simulation to real money without the owner generating and approving a live scoped key.
The API assigns a unique intent identifier to each order and deduplicates retries. If an agent resubmits the same intent because of a suspected network failure, the API recognizes the duplicate and returns the original execution report rather than placing a second order.
No. The API normalizes orders into plain US dollars and handles the venue-specific contract math internally. Developers must still understand the economic risks of each instrument, but they do not need to implement tick sizes, multipliers, or margin formulas in the agent logic.
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.