An LLM trading agent in Python is a program that collects prices and indicators, sends news and context to a large language model, turns the model’s answer into a Buy, Sell or Hold decision and, after a rule-based risk check, places the order through a broker API. This first part explains the building blocks, the multi-agent idea and the frameworks you can use; the next part gets into code.
Imagine having a smart assistant that helps you trade. This assistant can:
- Read market prices and charts (like you do)
- Read news articles and social media (faster than you can)
- Make trading decisions 24/7 without getting tired or emotional
It’s like having a team of experienced traders working for you around the clock, but automated.
- An LLM-based trading agent combines technical indicators (numbers) with LLM reading of news and filings (text).
- Split the job into specialist agents: market watcher, news analyser and risk manager, with an optional supervisor.
- Keep position sizing and stop-losses in plain code; let the LLM suggest, not size, trades.
- Framework landscape has moved: Swarm is replaced by the OpenAI Agents SDK, AutoGen is archived, phidata is now Agno.
- Indian retail algo rules apply to agents too: registered API apps, static IPs and order-rate limits.
What is an Agent?
An agent is a computer program that acts on its own to perform tasks, make decisions, or solve problems, often on behalf of a human user. When an agent uses a Large Language Model (LLM) (like ChatGPT, Deepseek, Claude Sonnet, Google Gemini etc), it leverages the model’s ability to understand, generate, and process natural language to help it make more informed decisions.

What Is a Trading Agent?
A Trading Agent is an automated software system that acts as your personal market assistant, combining real-time market analysis with precise execution capabilities. Think of it as a sophisticated digital trader that operates 24/7, simultaneously monitoring multiple data streams – from price movements and technical indicators to breaking news and social media sentiment.
Unlike traditional trading systems that rely solely on technical analysis, modern Trading Agents leverage artificial intelligence and Large Language Models (LLMs) to comprehend and act upon complex market information, including earnings reports, economic data, and market sentiment.
When specified conditions are met, the agent executes trades automatically based on predefined rules and risk parameters, eliminating emotional bias and human error from the trading process. For instance, if you’re trading Reliance at ₹1200, the agent continuously analyzes price patterns, volume data, news about the company, and broader market conditions, making split-second decisions based on your strategic guidelines while maintaining strict risk management protocols – all without requiring constant human supervision.

Introducing LLM-Based Trading Agents
An LLM-based trading agent enhances this traditional approach by integrating Large Language Models (LLMs) into the decision-making process. While technical indicators provide numerical insights, LLMs enable the agent to “read” and understand text-based information, such as financial news, reports, and social media updates. Here’s how it works:
- Data Collection: The agent collects real-time market data (prices, volumes) alongside textual data from news feeds and reports.
- Indicator Calculation: It computes technical indicators (e.g., moving averages, RSI) from the numerical data to identify trends and potential trading opportunities.
- LLM Analysis: The agent sends relevant text, such as breaking news headlines, to an LLM. The model processes this text to extract sentiment and key insights (e.g., positive or negative market outlook).
- Signal Combination and Decision Making: The insights from both the technical indicators and the LLM are combined. For example, if the technical analysis shows an upward trend and the LLM indicates positive news, the agent may generate a “Buy” signal. Conflicting signals might result in a “Sell” or “Hold” decision.
- Order Execution: The final decision is sent to a trading platform via an API, executing the order automatically.
- Continuous Feedback: The agent continuously monitors market responses and updates its decision-making process, creating a dynamic feedback loop.
How Does It Work? A Simple Example
The Three Expert System
Think of it as having three experienced professionals working for you around the clock:
- The Market Watcher
- Monitors Reliance’s price movements (currently ₹1200)
- Tracks support levels (₹1150) and resistance (₹1250)
- Alerts you about significant price movements
- Identifies trading patterns
- The News Analyzer
- Reads financial news 24/7
- Processes Reliance’s corporate announcements
- Monitors Mukesh Ambani’s interviews
- Tracks competitor news
- Analyzes market sentiment
- The Risk Manager
- Controls position sizes
- Sets stop losses and targets
- Manages your overall portfolio risk
- Prevents emotional trading decisions
Real-World Example: A Day in the Life
Let’s see how this works on a typical trading day:
Morning Session (9:15 AM)
- Reliance opens at ₹1200
- News breaks about Jio’s 5G expansion
- Nifty is trending upward
- Trading volume is above average
The System’s Analysis
- Technical Check:
- Price above 20-day average (₹1180)
- Volume confirms strength
- Upward trend intact
- News Impact:
- 5G expansion is positive
- No negative news from competitors
- Overall market sentiment is bullish
- Risk Assessment:
- Portfolio has room for position
- Stop loss level clear at ₹1176
- Target potential: ₹1260
The Decision Process
Based on a ₹10 lakh portfolio:
- Maximum Reliance exposure: ₹50,000 (5%)
- Number of shares: 41 (₹50,000 ÷ ₹1200)
- Stop loss: 2% below entry
- Target: 5% above entry
Notice that the share count is pure arithmetic from the risk rules. That is the pattern I recommend: the LLM gives a view and a reason, and deterministic code decides how much to buy.
Practical Benefits for Regular Investors
1. Time Management
- No need to watch markets constantly
- Automated monitoring of critical levels
- Instant notification of important events
2. Emotional Control
- Rules-based trading decisions
- No panic selling during volatility
- Consistent trade management
3. Risk Protection
- Predetermined position sizes
- Automatic stop losses
- Portfolio diversification control
What Is a Multi-Agent Framework?
Multi-agent systems let you break down the complex process of trading into smaller, specialized tasks. Instead of having one “super-agent” that does everything, you create several independent agents that each handle a part of the trading process. For example, one agent might analyze technical indicators (like moving averages), another might scan for relevant news and social sentiment, while yet another focuses on risk management and execution of orders.

A Simple Multi-Agent Setup You Can Understand: High-Level Example
Think of it like a trading company with different departments:
- Research Department (Agent A): Watches technical indicators. Example: “The RSI just crossed above 70, suggesting overbought conditions”
- News Desk (Agent B): Monitors news and social media. Example: “Breaking: Fed announces interest rate decision”
- Risk Manager (Agent C): Makes final trading decisions. Example: “Despite positive news, we’re at position limit – hold current positions”
A supervisor agent can be added to manage which agent should act next or to resolve conflicting signals. This multi-agent workflow not only makes the system more modular and easier to scale but also enables each agent to excel in its specific task.
I built a working example of this pattern in a stock market assistant using Swarm multi-agent systems.
Ten Leading Agentic Frameworks in Trading and AI
Here are ten prominent frameworks that help build autonomous multi-agent systems. Each comes with unique characteristics that can be particularly useful in autonomous trading decisions:
1. Crew AI
- Link: Crew AI
- Unique Aspects: Emphasizes team-based collaboration where agents take on specialized roles (e.g., analysis, execution, risk management). Its design is particularly friendly for users looking to quickly set up coordinated agent systems.
2. Pydantic AI
- Link: Pydantic AI (or see related GitHub projects)
- Unique Aspects: Leverages the Pydantic library’s strong data validation and schema enforcement, ensuring that all agent inputs and outputs are robust and consistent, a critical factor in automated trading environments.
3. Smol Agents
- Link: Smol Agents
- Unique Aspects: Provides a lightweight and minimalistic approach, making it ideal for rapid prototyping and for traders who want to experiment without the overhead of larger frameworks.
4. OpenAI Swarm Agents
- Link: OpenAI Swarm
- Unique Aspects: Focuses on the orchestration of multiple lightweight agents. Although experimental, its design is excellent for educational purposes and exploratory projects in autonomous decision-making.
Update (2026): Swarm was experimental and has been replaced by the OpenAI Agents SDK, which OpenAI describes as the production-ready evolution of Swarm (Swarm README).
5. Autogen
- Link: Autogen
- Unique Aspects: Specializes in creating autonomous conversational multi-agent systems that can self-correct and adapt dynamically, useful for developing trading systems that need to adjust strategies on the fly.
Update (2026): AutoGen is now archived and no longer maintained by Microsoft; new users are pointed to Microsoft Agent Framework (AutoGen README).
6. LangChain
- Link: LangChain
- Unique Aspects: Known for its versatility, LangChain seamlessly integrates large language models with external tools and APIs. This makes it powerful for building agents that require both sophisticated language understanding and direct action capabilities.
7. phi data
- Link: phi data
- Unique Aspects: Focuses on integrating robust data analytics into agent decision-making. Its strength lies in transforming raw data into actionable insights, which is essential for data-driven trading strategies.
Update (2026): phidata has been renamed Agno, and phidata.com now redirects to agno.com. I used it in a multi-agent financial news system with Agno and Agent UI.
8. MetaGPT
- Link: MetaGPT
- Unique Aspects: Enhances meta-reasoning, enabling agents not only to execute tasks but also to evaluate and refine their own strategies over time, ideal for evolving trading strategies in a dynamic market.
9. Botpress
- Link: Botpress
- Unique Aspects: Originally designed for conversational applications, Botpress can be adapted to handle interactive trading functions, such as customer support or trade confirmation, bridging the gap between automated execution and human interaction.
10. LlamaIndex
- Link: LlamaIndex
- Unique Aspects: Excels at context-aware data retrieval and indexing. LlamaIndex agents can sift through vast amounts of financial data to provide precise, informed insights, making them highly effective in the fast-paced trading domain.
LLM Trading Agent Python Skeleton
Before picking a framework, it helps to see the moving parts in plain Python. The skeleton below calculates a technical snapshot with pandas, asks an LLM for a JSON decision, rejects anything malformed, and lets a rule-based risk manager decide the quantity. Plug your own provider into ask_llm().
import json
import pandas as pd
def indicators(df: pd.DataFrame) -> dict:
"""Technical snapshot from a DataFrame with a 'close' column."""
close = df["close"]
delta = close.diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
rsi = 100 - 100 / (1 + gain / loss)
return {
"close": round(float(close.iloc[-1]), 2),
"sma20": round(float(close.rolling(20).mean().iloc[-1]), 2),
"rsi14": round(float(rsi.iloc[-1]), 2),
}
def ask_llm(prompt: str) -> str:
"""Replace with a call to your LLM provider (OpenAI, Claude, Gemini, Ollama...)."""
raise NotImplementedError
def decide(symbol: str, df: pd.DataFrame, headlines: list[str]) -> dict:
tech = indicators(df)
prompt = (
f"You are a cautious trading assistant for {symbol}.\n"
f"Technical data: {json.dumps(tech)}\n"
f"Recent headlines: {json.dumps(headlines)}\n"
'Reply only with JSON: {"action": "BUY|SELL|HOLD", "confidence": 0-1, "reason": "..."}'
)
try:
reply = json.loads(ask_llm(prompt))
except (ValueError, NotImplementedError):
return {"action": "HOLD", "reason": "no valid LLM reply"}
if reply.get("action") not in ("BUY", "SELL", "HOLD"):
return {"action": "HOLD", "reason": "invalid action"}
return reply
def risk_check(decision: dict, capital: float, price: float,
max_exposure: float = 0.05, min_conf: float = 0.6) -> int:
"""Rule-based risk manager: the LLM never sets the quantity."""
if decision["action"] == "HOLD" or decision.get("confidence", 0) < min_conf:
return 0
return int(capital * max_exposure // price)
With a ₹10 lakh portfolio, a 5% exposure cap and Reliance at ₹1200, risk_check() returns 41 shares, the same number as the worked example above. Data validation for the LLM reply is exactly where Pydantic helps; see Pydantic for traders.
Autonomous Trading Decisions with Multi-Agent Frameworks
When a multi-agent framework is applied to trading, each autonomous agent is responsible for a segment of the trading process. For instance, one agent might continuously monitor market data, another could generate trading signals based on technical analysis, while a third agent manages order execution and risk controls. This distributed decision-making process leads to a more responsive and resilient trading system that can operate with minimal human intervention.
Limitations and Guardrails for LLM Trading Agents
- Hallucination. An LLM can invent a headline or misread a number. Pass it the raw data and ask it to quote the source line for its reason.
- Latency and cost. Each LLM call takes time and money, so agents suit swing and positional decisions or slow intraday timeframes, not tick-by-tick scalping.
- Non-deterministic output. The same prompt can give different answers. Log every prompt and reply so you can audit decisions later.
- Look-ahead bias in testing. When backtesting, give the agent only news published before each bar; models may also “remember” what happened later.
- Regulation. In India, retail algo orders above 10 orders per second per exchange segment need exchange registration (NSE framework), and from 1 April 2026 API orders are accepted only from a registered app mapped to a whitelisted static IP (Fyers summary).
Required Skillset for Learning Agentic Frameworks
To effectively work with these frameworks, especially in an autonomous trading environment, practitioners typically need a mix of technical and domain-specific skills:
- Programming Proficiency: Strong skills in languages like Python, which is widely used in AI and trading automation.
- Understanding of Machine Learning and NLP: Familiarity with machine learning concepts and large language models (LLMs) is crucial for leveraging frameworks like LangChain and MetaGPT.
- Data Engineering and Analytics: Skills in processing, analyzing, and validating large volumes of financial data. Experience with data libraries (e.g., Pandas, NumPy) and data validation frameworks (like Pydantic) is highly beneficial.
- API Integration: Knowledge of RESTful APIs and experience in integrating various data sources and external tools are essential for connecting agents with real-time market feeds and trading platforms.
- Financial Market Acumen: A strong grasp of trading fundamentals, risk management, and market mechanics is necessary to translate technical capabilities into effective trading strategies.
- Asynchronous Programming and System Design: Understanding how to design scalable, multi-threaded, or asynchronous systems can help in managing the interactions between multiple agents.
- DevOps and Containerization: Familiarity with tools like Docker can assist in deploying multi-agent systems efficiently, ensuring they run reliably in production environments.
Wrapping Up Part 1 and What Comes Next
In this first part, we’ve explored how multi-agent systems can empower traders by breaking down complex trading processes into specialized tasks, from technical analysis to news sentiment interpretation and risk management. By leveraging these autonomous agents, traders can achieve faster, more accurate, and scalable decision-making.
In Part 2, we will take a hands-on approach and show you how to build a basic trading agent from scratch using Python and Pydantic AI. Stay tuned as we dive into coding, data integration, and real-time execution to bring your trading agent to life.
If you want a hands-on version you can run on your own machine today, start with building a trading agent locally using Ollama and Google Gemma 3.
Frequently Asked Questions
Can an LLM trade stocks on its own?
It can if you connect it to a broker API, but it should not have unchecked control. Keep risk limits, position sizing and kill switches in deterministic code outside the model.
Which Python framework is best for an LLM trading agent?
For a simple single agent, plain Python or Pydantic AI is enough. For multi-agent workflows, CrewAI, LangGraph, Agno or the OpenAI Agents SDK are common choices.
Do I need to know machine learning to build a trading agent?
Not deeply. You need solid Python, API integration, prompt design and trading knowledge. Machine learning knowledge helps when you start evaluating agent performance.
Are LLM trading agents allowed in India?
Automated trading through a broker API is allowed for retail traders under SEBI’s algo framework, with broker-registered API access, static IPs and order-rate limits. The decision logic, LLM or not, is your responsibility.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

