How to build an LLM-powered trading agent with one API
A developer's guide to connecting LLM agents to stocks, crypto, perps, options, and prediction markets through a single, non-custodial API with built-in safety controls.
- 01A single API can normalize stocks, crypto, perps, options, and prediction markets into one interface where orders are sized in plain US dollars.
- 02LLM agents connect through MCP tools or a REST API, but the connection is only as safe as the scoped keys and budget caps you configure before it starts.
- 03Non-custodial architecture means the agent can trade within limits but can never withdraw funds to itself or override owner-approved withdrawal addresses.
- 04Paper trading lets you test logic against live market data without risking capital, and live trading requires explicit owner authorization of a scoped key.
- 05Trading can lose money, including the entire balance, so position limits, exit plans, and a panic switch are essential infrastructure, not optional extras.
You can connect an LLM agent to stocks, crypto, perpetual futures, options, and prediction markets through a single API and a single key. The API normalizes venue-specific contract math and denominates orders in plain US dollars, so the agent does not need to handle per-market sizing logic, margin formulas, or tick size conversions. Safety is enforced outside the model through scoped keys, budget caps, and a non-custodial wallet structure that prevents the agent from ever withdrawing funds to itself or an unapproved address.
What does a single API actually abstract?
Building a multi-market trading bot traditionally means integrating separate libraries for each asset class. A stock broker speaks in shares and fractional quantities. A perps venue speaks in contracts, notional value, and leverage tiers. An options venue uses strike prices, expiries, and multipliers. A prediction market may use binary contracts or continuous outcome pools. Each has its own authentication flow, rate limits, error codes, and order formats. For an LLM agent, this fragmentation is dangerous because the model must hold more context about plumbing than about strategy. When a venue rejects an order for insufficient margin or a price band violation, the unified API surfaces that error in a normalized format. The agent does not need custom parsing logic for each exchange's error schema.
A unified API collapses these five market types into one interface. You send an order with a dollar amount, a side, and a market identifier. The infrastructure translates that into the native contract size, checks margin requirements, and routes it to the correct venue. The agent receives position updates and portfolio summaries in the same normalized format, regardless of whether the underlying exposure is a stock, a crypto perpetual, or a prediction market contract. This uniformity means your prompt engineering and tool definitions stay constant even as you add new markets. The model reasons about allocation in dollars, and the API handles the rest.
How does an LLM connect to the API?
Agents connect through MCP tools or the REST API. The MCP path is designed for AI editors and assistants that already speak the Model Context Protocol. You define a tool schema that describes available actions, such as placing a market order or checking a portfolio balance. The description should be explicit about the required parameters and the consequences of the call. A well-written tool description is part of the safety layer because it shapes the model's understanding of what it is allowed to do. When the LLM decides to trade, it emits a function call with parameters in JSON. The MCP client validates those parameters against your guardrails, adds the scoped key, and forwards the request. The model never sees the key, the base URL, or any secrets.
The REST path is for developers who want full control over the stack. You run your own inference endpoint or call a remote LLM from a backend service, parse the output, and construct the HTTP request yourself. This lets you insert custom pre-trade checks, logging, and retry logic that the MCP layer might not expose. Both paths use the same normalized data model and the same key format. The exact request schema is in the docs; the shape looks like this:
curl -X POST https://api.host/v1/orders \
-H "Authorization: Bearer YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"market": "BTC-USD",
"side": "buy",
"dollar_amount": 500,
"type": "market"
}'In either setup, the critical detail is that the LLM does not hold the key. The key lives in the client or the server, and the API permissions are scoped to trading only. If you are configuring an MCP client, make sure the tool definition does not expose endpoints that could leak secrets or change key permissions. For a detailed setup guide, see our practical checklist for non-custodial MCP.
Why is non-custodial architecture important for agents?
In a custodial model, you deposit funds into a wallet or account that the agent controls. If the agent's key is leaked, or if the LLM is jailbroken into issuing a malicious command, the attacker can withdraw everything. Non-custodial design removes this risk by construction. Funds remain in a wallet the owner controls. The agent operates with a scoped key that can place trades, manage positions, and read balances, but it lacks the permission to withdraw funds. Withdrawal addresses are whitelisted by the owner during setup, and the agent cannot add, remove, or modify them. The owner approves withdrawal addresses through a separate interface that requires a higher privilege level than the trading key. Even if the agent's key is compromised, the attacker cannot simply change the withdrawal destination to their own wallet. The separation of trading and withdrawal privileges is fundamental to the architecture.
This is not a matter of trust or code review. It is a cryptographic and permissions boundary. Even if the agent's server is fully compromised, the scoped key simply cannot construct a valid withdrawal transaction. The worst case is that the attacker trades within the remaining budget cap until the owner hits the panic switch. That is still a real loss, but it is bounded. To understand the mechanics of these permissions, read how scoped API keys work without custody.
Many developers treat key rotation as their primary security mechanism, but rotation does not limit blast radius. A master key that can trade and withdraw is dangerous no matter how often you rotate it. Scoped keys fix the blast radius at creation time. When you provision the key, you attach a maximum budget, a whitelist of tradable markets, and a maximum position size. The API rejects any request that violates these constraints, even if the signature is valid and the payload is well-formed. Misconfiguring these scopes is a common source of incidents. We have cataloged the typical errors in common mistakes with scoped API keys for trading agents.
How do you keep an agent from exceeding its mandate?
An LLM should generate intent, not exercise authority. Final authority must rest in infrastructure that the model cannot reason around or persuade. Hard limits live in the API layer, outside the context window, and they are enforced before any order reaches a market. You configure them when you create the scoped key, and they persist independently of the agent's prompt or memory.
- ·Budget caps: a hard ceiling on the dollars the agent can deploy in a day, week, or month.
- ·Position limits: a maximum dollar value for any single position, preventing concentration risk.
- ·Exit plans: pre-defined orders or triggers that close positions when conditions are met, so the agent does not need to decide in real time during a crash.
- ·Panic switch: a manual or automated kill switch that flattens all positions and revokes the key instantly.
Exit plans deserve special attention. They can be static, such as a stop-loss order attached at entry, or dynamic, such as a rule that reduces position size when portfolio volatility exceeds a threshold. The key is that the plan is registered with the API and executes independently of the LLM's next inference cycle. If the model is slow to respond or hallucinates a reason to hold, the exit plan still fires. When the agent hits a limit, the API returns an error. The model can incorporate that error into its reasoning and propose a smaller trade, but it cannot override the boundary. If the owner triggers the panic switch, the system sends flattening orders across all markets and disables the key within seconds. Trading can lose money, including the entire balance, and these guardrails only bound the speed and scale of that loss. They do not guarantee profits, prevent all losses, or predict market behavior. They simply ensure that a bug or a bad day cannot escalate beyond the parameters you set.
How should you think about order sizing and risk?
LLMs reason well in natural language and absolute values, but poorly in venue-specific units like contract sizes, lot multipliers, or leveraged notional. A unified API lets the agent think in dollars. If the strategy calls for five hundred dollars of exposure to a given asset, the agent sends exactly that number. The infrastructure calculates the equivalent shares, contracts, or units, accounts for leverage and margin, and submits the native order. This removes an entire category of conversion errors from the agent's loop. Because the agent sees a unified portfolio, it can reason about total exposure across asset classes. A human might think separately about a stock position and a crypto position, but the agent can receive a single number for total long exposure. This holistic view supports better risk management, provided the dollar sizing translations are accurate.
Suppose the agent decides to reduce its exposure by two hundred dollars. It does not need to know the current price, the contract size, or whether the venue supports fractional shares. It sends the dollar reduction, and the API translates it. This simplifies prompt engineering because you can describe risk in plain terms. However, dollar-based sizing is not perfect. Minimum order sizes, rounding behavior, and margin requirements can cause the executed exposure to differ slightly from the requested dollar amount. An agent that assumes perfect dollar equivalence may miscalculate its total portfolio risk. You should test these translations in paper trading and understand how each venue handles fractional or minimum-quantity orders. For a starting guide, see how to start trading with dollar-based order sizing in 2026.
What is the safest way to go from paper to live trading?
Paper trading uses live market data and simulated fills to let you test the full loop from prompt to order without risking capital. You should treat paper trading as a proving ground for the safety layer, not just for the strategy. Observe how the agent behaves when orders are rejected, when markets gap, and when it approaches its budget cap. Check that the panic switch works as expected and that the scoped key cannot perform unauthorized actions. Verify that the API's normalization matches your expectations by comparing the reported dollar exposure against the underlying venue's native position reports during paper trading.
Only after you have validated the guardrails should you authorize a live key. The authorization is an explicit owner action, not an automatic graduation. It typically requires the owner to sign a message or confirm through a second factor that the key is permitted to trade real money. This creates an audit trail and prevents accidental live deployment. Once authorized, the key is bound to the live budget cap, which can be lower than the paper trading limit. You can maintain separate paper and live keys for the same strategy, which makes it easy to compare behavior under identical market conditions. Start the live key with a budget that is a small fraction of your intended allocation. Run it for a defined period, review the logs, and verify that the agent respects the limits under real fill conditions. Once you are confident, you can raise the cap gradually. Never increase the budget in response to a short winning streak. The goal of early live trading is to confirm that the non-custodial controls and guardrails function in production, not to maximize returns. Trading can lose money, including everything, and a small initial live budget limits the cost of discovering an edge case that paper trading did not reveal.
Frequently asked questions
No. The scoped key cannot initiate withdrawals, and withdrawal addresses are owner-approved only. This is enforced by the non-custodial architecture, not by the LLM's instructions.
No. One key and one API cover stocks, crypto, perps, options, and prediction markets. The infrastructure handles the normalization across venues.
The API rejects the order before it reaches the market. The agent receives an error and can adjust its plan, but it cannot override the cap.
Yes. You can call the REST API directly from any service that hosts its own inference. The MCP path is optional and provided for convenience.
No. Paper trading validates logic and guardrails, but slippage, liquidity, and fill behavior differ in live markets. Always start with a small live budget and strict limits.
Use the panic switch. It flattens positions and revokes the key immediately. You can then review logs and adjust prompts or guardrails before reactivating.
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.