To create an AI agent for trading, you connect four parts: a market data feed, a strategy that turns data into trade ideas, a risk manager that can veto any idea, and a broker API that places the order. A large language model can sit in the middle as a reasoning layer, but it should never touch your money without hard limits written in plain code. Build it on a paper trading account first, run it there for weeks, and only then consider a small live account.
This guide walks through the full build in order and covers the architecture, a short Python example that places a paper order behind a risk check, backtesting, the rules in the US and India, and the kill switch every agent needs. It is based on official broker and regulator documents. It is not financial advice, and no strategy or agent guarantees returns.
Trading Agent Basics Before You Write Code
- A trading agent has six parts: data feed, strategy, optional LLM reasoning layer, risk manager, broker API and logging.
- Let the LLM propose trades, but let plain code decide whether they are allowed. Size caps, symbol lists and loss limits belong in code, not in a prompt.
- Start on paper. Alpaca gives anyone a free paper account with $100,000 in simulated funds, and Binance runs a Spot Testnet with virtual funds.
- In a public contest, four of six frontier models lost money trading crypto over about two weeks, ForkLog reported.
- Rules changed in 2026: FINRA replaced the US pattern day trader rule, and India’s SEBI retail algo framework applies to all brokers from April 1, 2026.
What an AI Trading Agent Actually Does
A trading agent is a program that watches markets and acts on them without waiting for you to click a button. It does four jobs in a loop: it reads signals such as prices, volume, news or company filings, decides what to do with them, checks each proposed order against risk limits, and then places the orders that pass through a broker.
The decision step is where AI agents differ from older trading bots. A classic bot follows fixed rules, such as “buy when the 20-day average crosses above the 50-day average.” Those rules are fast and cheap, and they give the same answer every time. An LLM-based agent can read text that rules cannot, such as an earnings call summary or a central bank statement, and explain its reasoning in plain words. The trade-off is that the model can be wrong in confident ways, it is slower, and every call costs money.
Most sensible designs mix the two, so that rules handle the math and the limits while the LLM handles reading, summarizing and ranking ideas. If you are new to the difference between an agent and a chat tool, our guide to AI agents vs AI chatbots explains it in more depth.
Agents that trade on their own already exist in other markets. Habitat Energy forecasts power prices and trades grid-scale batteries, with human traders watching around the clock. Tesla Autobidder sets bids and dispatch schedules for Megapack batteries in wholesale power markets. Both show the same pattern you will build here: forecasts feed decisions, and decisions run inside strict limits.
The Architecture of a Trading Agent
Before writing code, sketch the parts and how data moves between them. Each part should be small enough to test on its own, so that a bug in the news reader cannot quietly break the risk manager.
| Component | What It Does | Typical Choice |
|---|---|---|
| Data feed | Supplies prices, bars, quotes and news | Broker market data API or a data vendor |
| Strategy | Turns data into a signal, such as buy, sell or hold | Rules in Python, or a trained model |
| LLM reasoning layer | Reads text, ranks ideas and explains choices | An LLM called through an agent framework |
| Risk manager | Approves or blocks every order | Plain code with hard limits |
| Broker API | Places, changes and cancels orders | Alpaca, Interactive Brokers, an exchange API |
| Logging and monitoring | Records every input, decision and fill | Database, log files, alerts to your phone |
The order of the arrows matters most. Data flows into the strategy and the LLM, and their output is only a proposal. That proposal then goes to the risk manager, which is the only part allowed to call the broker.
For the LLM layer, you do not need to write the agent loop from scratch. Frameworks such as the OpenAI Agents SDK, LangGraph and Google’s Agent Development Kit handle tool calls, memory and approval steps. Our comparison of the best AI agent frameworks covers how they differ. If you would rather understand the loop itself, read how to build an AI agent from scratch first.
Step 1: Pick One Market and One Narrow Job
Instead of starting with “trade the stock market,” start with a job you can describe in one sentence and measure in one number. Good first jobs look like these: rebalance a two-fund portfolio once a week, scan daily news for a short list of stocks and flag big changes, or trade one liquid ETF on a simple trend rule.
Then write down three limits before you write any code: the largest order size, the most you will lose in a day before the agent stops, and the list of symbols it may trade. These numbers become the risk manager, and they also force you to think about losses before you think about gains, which is the right order.
Step 2: Open a Paper Trading Account

Paper trading lets your agent place orders with fake money against real market prices, which makes it the safest place to find bugs. Three common options cover stocks and crypto.
Alpaca. Alpaca’s docs describe paper trading as a real-time simulation where orders are not sent to a live exchange. It is free, anyone in the world can open a paper-only account with an email address, and the default balance is $100,000. The paper API lives at its own base URL, separate from live trading, and the docs also list what the simulation skips: it does not model market impact, slippage from latency or dividends, and regulatory fees are not counted. Paper-only accounts get IEX market data only. Keep those gaps in mind, because they make paper results look better than live ones.
Interactive Brokers. IBKR offers paper accounts that work with its TWS API. Its own tutorial says that when you log in with a paper account, the API socket port is usually 7497, and it recommends paper trading before any live trading.

Crypto exchange testnets. Binance runs a Spot Testnet where you create an API key on the testnet site and get balances in many assets. All funds there are virtual and cannot be moved in or out, and the network is reset about once a month without notice, though API keys survive the reset. Rate limits and symbol filters are generally the same as on the live Spot API, which makes it a fair test of your order code.
Read also: 8 Steps to Create a WhatsApp AI Agent for Marketing
Step 3: Connect a Data Feed and Write the Strategy
Your strategy needs clean, timely data. For a first build, use the market data API from the same broker you trade with, because it removes one moving part and keeps prices consistent with your fills. Alpaca’s Python library, alpaca-py, has a data client that returns the latest trade for a symbol, which is enough for the example below.
Write the strategy as a plain function that takes data and returns a signal, and keep it free of broker calls, since a pure function is easy to test, backtest and swap later. If you want the LLM to help, give it a narrow task, such as “read these three headlines and return bullish, bearish or neutral with one sentence of reasons.” Ask for a fixed JSON format, and have your code reject any answer that does not match it.
You do not have to write all of this by hand. Coding agents such as OpenHands can scaffold the project, write tests and fix errors, as our list of the best agentic AI coding tools shows. Review every line they write that touches orders or limits, though, because that code is where mistakes cost real money.
Step 4: Add the LLM Reasoning Layer With Guardrails
An LLM adds value when the input is messy text, because it can sort a hundred headlines, pull figures from a filing or explain why a signal fired. It adds risk when it is given direct control of orders, and three problems show up again and again.
Hallucination. A model can invent a price, misread a ticker or state a fact that is not in its input. Never let the model supply the numbers that size an order; fetch prices from the data API in code instead, and treat the model’s output as an opinion to be checked.
Latency. An LLM call can take seconds, which is fine for a strategy that trades once a day. It rules out anything that depends on reacting within milliseconds, so keep LLM agents away from high-frequency ideas.
Cost. Every model call is billed by tokens, so an agent that calls a large model on every price tick can spend more on the model than it ever makes in trades. Call the LLM on a schedule or on a clear trigger, and log the cost of each call next to the trade it led to.
In nof1’s Alpha Arena contest, six frontier models each got $10,000 to trade crypto from October 18 to November 3, 2025. ForkLog reported that four of the six ended with losses. Qwen3 Max finished up about 22%, while GPT-5 finished down about 59%. A short contest proves little about skill, but it does show that a capable model is not the same as a safe trader.
Step 5: Build the Risk Manager and Place a Paper Order
The example below uses alpaca-py against a paper account. It takes a trade proposal, which in a full agent would come from your strategy or the LLM, and runs it through four hard checks. A kill switch file stops all trading, a short list limits which symbols the agent may trade, a daily loss limit compares current equity with the prior close, and a size cap blocks any order worth more than $1,000. Only a proposal that passes every check reaches the broker.
import os
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockLatestTradeRequest
KEY = os.environ["APCA_API_KEY_ID"]
SECRET = os.environ["APCA_API_SECRET_KEY"]
MAX_ORDER_USD = 1_000 # largest single order
MAX_DAILY_LOSS = 0.02 # stop after a 2% drop from yesterday's close
ALLOWED = {"SPY", "QQQ"} # symbols the agent may trade
trading = TradingClient(KEY, SECRET, paper=True)
data = StockHistoricalDataClient(KEY, SECRET)
def risk_check(symbol, qty, side):
if os.path.exists("KILL_SWITCH"):
raise RuntimeError("Kill switch is on")
if symbol not in ALLOWED or side not in ("buy", "sell") or qty <= 0:
raise ValueError(f"Blocked proposal: {symbol} {side} {qty}")
account = trading.get_account()
if float(account.equity) < float(account.last_equity) * (1 - MAX_DAILY_LOSS):
raise RuntimeError("Daily loss limit hit")
req = StockLatestTradeRequest(symbol_or_symbols=symbol)
price = data.get_stock_latest_trade(req)[symbol].price
if qty * price > MAX_ORDER_USD:
raise ValueError(f"Order worth ${qty * price:,.0f} is over the cap")
def place_order(proposal):
# proposal from the strategy or LLM, e.g. {"symbol": "SPY", "qty": 1, "side": "buy"}
symbol = str(proposal["symbol"]).upper()
qty = int(proposal["qty"])
side = str(proposal["side"]).lower()
risk_check(symbol, qty, side)
order = MarketOrderRequest(
symbol=symbol,
qty=qty,
side=OrderSide.BUY if side == "buy" else OrderSide.SELL,
time_in_force=TimeInForce.DAY,
)
return trading.submit_order(order_data=order)
print(place_order({"symbol": "SPY", "qty": 1, "side": "buy"}))
Notice what the LLM never controls here: it cannot pick the price, raise the cap or add a symbol to the list. In a real build, you would add more checks, such as a cap on total position size, a limit on orders per hour and a block on trading near the market close.
Step 6: Backtest Before You Trust Anything
A backtest runs your strategy on past data to see how it would have done, which makes it the cheapest way to kill a bad idea. It is also easy to fool yourself with, so watch for three traps.
- Look-ahead bias: the strategy uses data it could not have known at the time, such as a closing price at noon.
- Overfitting: you tune settings until the past looks perfect, and the strategy fails on new data.
- Missing costs: commissions, spreads, slippage and fees can turn a small edge into a loss.
LLM strategies add one more trap, because a model trained on recent years may already “know” what happened to a stock in your test period. That makes its past calls look smarter than they were, so test LLM signals on dates after the model’s training cutoff, or treat the backtest as a rough check rather than proof. Split your data so that you tune on one period and judge on another you never touched.
Step 7: Paper Trade, Log Everything, Then Go Small
Once the backtest looks sound, run the agent on paper for several weeks and treat it like a live system. Log the data it saw, the LLM prompt and reply, the risk decision, the order sent and the fill. When a trade looks odd, those logs let you replay exactly why it happened.
Compare paper fills with what live trading would have cost, since Alpaca’s docs note that paper accounts do not model slippage or market impact, and that about 10% of eligible fills are partial. Assume live results will be worse than paper, because a strategy that only works with perfect fills does not work.
When you go live, start with an amount you can afford to lose in full. Keep the same caps and raise them slowly, and only after the agent has behaved well for a long stretch. Consider a human approval step for any order above a set size, which frameworks like LangGraph support through human-in-the-loop pauses.
Monitoring and the Kill Switch
An agent that trades while you sleep needs a way to stop itself and a way for you to stop it, and you should build both before the first live order.
The automatic stop lives in the risk manager, so when the daily loss limit hits, the agent should refuse new orders for the rest of the day. The manual stop should be one action you can take from your phone, such as creating a flag file or flipping a value in a database. When it fires, the agent should cancel open orders and, if you choose, flatten positions. In alpaca-py, cancel_orders() cancels open orders, and close_all_positions(cancel_orders=True) closes positions and cancels orders together.
Monitoring covers the rest, so send an alert when an order is rejected, when the data feed goes quiet, when the LLM returns bad output several times in a row, or when model costs jump. Check the agent’s positions against the broker’s records every day, because agents can drift out of sync after network errors, and a mismatch is often the first sign of a bug.
Compliance and Real-World Rules
Rules depend on where you live and what you trade. Two big changes landed in 2026, and both affect retail traders who build their own agents.
United States: The Pattern Day Trader Rule Was Replaced
For years, FINRA’s pattern day trader rule required $25,000 in a margin account for frequent day traders. On April 14, 2026, the SEC approved FINRA changes to Rule 4210 that replace the old day trading margin rules in full, including the day trade count test and the $25,000 minimum. FINRA’s Regulatory Notice 26-10 set the effective date as June 4, 2026. A new intraday margin standard takes its place, but firms may phase in the change until October 20, 2027, so your broker may still apply older limits for a while. Check your broker’s current policy before your agent starts making same-day round trips.
India: SEBI’s Retail Algo Trading Framework
SEBI’s circular of February 4, 2025 set rules for retail traders who use APIs to automate orders. API access runs through your stock broker, and traders must use a static IP that the broker has whitelisted. Exchanges set an orders-per-second threshold, and strategies above it must be registered, while algo orders carry an exchange-issued identifier so each order can be traced to its algo. Providers of black box algos, whose logic is not disclosed, need a SEBI Research Analyst registration.
The start date moved twice. A September 30, 2025 circular let ready brokers go live from October 1, 2025, set milestones for late 2025 and early 2026, and applied the framework to all stock brokers from April 1, 2026. If you trade in India, use your broker’s official API and follow its setup steps for static IPs and strategy registration.
Everywhere: You Own the Agent’s Actions
The broker sees your account placing the orders, not your AI, so market abuse rules, tax rules and broker terms apply just as if you had clicked each button. This guide is general education, not financial, legal or tax advice. Talk to a licensed adviser before you trade real money with any automated system.
Build It Yourself or Use a Platform
Building your own agent gives you full control of the logic and the limits, but it also makes you responsible for uptime, security and every bug.
If you work in finance and want agents for research rather than trading, ready-made tools exist. Rogo, for example, runs research and deal work for investment bankers. You can browse more tools on our AI agents for banking page. If your goal is to run several agents together, such as one that reads news and another that checks risk, a multi-agent framework like CrewAI can split those roles, and our agent frameworks category lists more options.
Questions First-Time Builders Ask About Trading Agents
Can I Build an AI Trading Agent for Free?
You can build and test the trading side at no cost, since Alpaca’s paper accounts are free, Binance’s Spot Testnet uses virtual funds and the open-source frameworks are free to use. You will still pay for LLM API calls, and you will need real money once you trade live.
Can ChatGPT or Another LLM Trade Stocks for Me?
An LLM can read data and suggest trades, and with broker API access an agent built around it can place orders. It should not do so without hard limits in code, and in nof1’s Alpha Arena contest, four of six frontier models lost money trading crypto, ForkLog reported.
Is AI Trading Legal?
Automating your own trades through a broker’s official API is allowed in the US and India, as long as you follow broker terms and market rules. In India, retail API trading falls under SEBI’s algo framework, which applies to all brokers from April 1, 2026.
Which Programming Language Is Best for a Trading Agent?
Python is the usual choice, because broker libraries such as alpaca-py are written for it and most agent frameworks support it.
How Long Should I Paper Trade Before Going Live?
There is no fixed rule, but you should run long enough to see the agent handle quiet days, busy days, errors and at least one losing streak. Several weeks is a sensible floor for a daily strategy, and then you can start live with a small amount and the same limits.
Read also: How to Build a CI/CD Pipeline for AI Agents
Related AI Agents
Explore Agent Categories
Related Articles
Guides8 Steps to Create a WhatsApp AI Agent for Marketing
GuidesSynthesia AI Video Usage Among Corporate Training Teams
GuidesBest CAMEL AI Alternatives and What They Cost
Guides100 AI Agent Statistics for Retail Companies
GuidesLLM or AI Agent? AI Search Engines and What They Actually Are
GuidesCan You Trust an AI Agent?





