Imagine having an AI assistant that watches the stock market 24/7, analyzes multiple technical indicators, makes trading decisions, and executes trades automatically. This isn’t science fiction — it’s what we call an “agentic trader.” In this article, I’ll walk you through how to build one from scratch, even if you’re just starting out.

What is an Agentic Trader?
An agentic trader is an AI-powered autonomous system that can make and execute trading decisions without constant human intervention. Think of it as a robot trader that:
- Monitors market data in real-time
- Analyzes technical indicators (like RSI, MACD, Bollinger Bands)
- Makes BUY/SELL/HOLD decisions based on patterns
- Executes trades automatically through a broker API
- Learns from past trades to improve over time
The key word here is “agentic” — meaning it has agency. It can take actions on its own within the rules you set.
Understanding the Building Blocks
Before we dive into building, let’s understand the three key technologies that make this possible:
1. OpenAI Agents SDK: The Brain
The OpenAI Agents SDK is a framework that lets you build AI agents — programs that can think, plan, and take actions. Here’s what makes it special:
What it does:
- Gives your AI the ability to use tools (like checking stock prices, placing orders)
- Allows the AI to plan multi-step actions (“First check the price, then if it’s below $100, buy 10 shares”)
- Handles the back-and-forth conversation between the AI and your tools
- Manages memory so the agent remembers previous trades.
Why it’s powerful:
Think of it like giving your AI hands and feet. Without the SDK, an AI model like GPT-5 can only generate text. With the SDK, it can actually DO things — check your account balance, fetch stock prices, place orders, and more.
Example:
Without SDK: AI can only suggest
AI: “I think you should buy RELIANCE stock”
With SDK: AI can actually execute
AI: *checks price* “RELIANCE is at 1385”
AI: *checks your balance* “You have sufficient funds”
AI: *places order* “Bought 10 shares of RELIANCE at 1385”
2. LiteLLM: The Universal Translator
LiteLLM is like a universal adapter for AI models. Here’s why it matters:
The Problem:
Different AI providers (OpenAI, Google, Anthropic, Groq, Cerebras) all have different APIs. If you build your agent to work with OpenAI’s GPT-5, switching to a faster or cheaper model from another provider means rewriting your code.
The Solution:
LiteLLM translates between all these different APIs into one standard format. Write your code once, and it works with 100+ different AI models.
Why this matters for trading:
Different models have different strengths:
- OpenAI GPT-5: High quality reasoning, but slower and expensive
- Cerebras GPT OSS-120B: Ultra-fast (2000+ tokens/second), great for real-time trading
- Groq Llama 3.3: Fast and cheap ($0.59 per 1M tokens), perfect for testing
- Claude 4.5 Sonnet: Excellent at complex analysis, but pricey
With LiteLLM, you can switch between them by changing just ONE line in your config file:
# .env file
MODEL_PROVIDER=cerebras # Ultra-fast for production
MODEL_PROVIDER=groq # Cheap for testing
MODEL_PROVIDER=openai # High quality reasoning
No code changes needed. Just swap and go.
3. Why Build Model-Agnostic?
Being model-agnostic (able to work with any AI model) gives you superpowers:
Cost Optimization:
- Development: Use cheap Groq models ($0.59/million tokens)
- Production: Switch to fast Cerebras models ($0.60/million tokens)
- Analysis: Use powerful Claude models when you need deep reasoning
Speed Matters:
In trading, milliseconds count. With model-agnostic design:
- OpenAI GPT-5-mini: 3–5 seconds per trading decision
- Cerebras Llama 3.1: 0.5–1 second per decision (80% faster!)
Fallback Strategy:
If one provider has downtime, instantly switch to another. Your trading doesn’t stop.
Future-Proof:
New, better models come out every month. With LiteLLM, you can test them immediately without changing your code.
Token Efficiency: Why It Matters
Here’s something most beginners don’t realize: AI models charge you by the “token” (roughly a word or piece of a word). Every message you send and every response costs money.
The Token Efficiency Lesson
When I first built my agentic trader, I made a common mistake: using a multi-agent architecture (multiple specialized AI agents working together). Here’s what I learned:
Multi-Agent Architecture:
- Market Analysis Agent (analyzes charts)
- Risk Management Agent (checks if trade is safe)
- Execution Agent (places orders)
- Memory Agent (remembers past trades)
- Coordinator Agent (manages all the others)
Sounds smart, right? But here’s the cost:
Per Trading Cycle:
- Input tokens: 144,000
- Cost: $0.023
- Time: 12–20 seconds
- Daily cost (75 cycles): $1.73
- Monthly cost: ~$52
**Single Agent Architecture:**
One smart agent that does everything:
Per Trading Cycle:
- Input tokens: 30,000 (79% less!)
- Cost: $0.008 (65% cheaper!)
- Time: 3–6 seconds (70% faster!)
- Daily cost (75 cycles): $0.60
- Monthly cost: ~$18
The Lesson:
More agents ≠ Better results. In fact, simpler is often better. Each time agents talk to each other, you pay for tokens. A well-designed single agent is faster, cheaper, and easier to debug.
Building the Agentic Trader Prototype
Now let’s talk about what our prototype actually does. This is an educational system designed to teach you how agentic trading works — NOT for live trading.
What the Prototype Does
1. Market Analysis:
The agent analyzes 5 NSE stocks (ICICIBANK, RELIANCE, SBIN, WIPRO, ITC) using 7 professional technical indicators:
- RSI (Relative Strength Index): Is the stock overbought or oversold?
- MACD (Moving Average Convergence Divergence): What’s the momentum?
- Bollinger Bands: Is the price at an extreme?
- EMA (Exponential Moving Average): What’s the trend direction?
- Stochastic Oscillator: Are we at a reversal point?
- ADX (Average Directional Index): How strong is the trend?
- ATR (Average True Range): How volatile is the stock?
The agent fetches all this data in parallel (all 5 stocks at once) in just 2–3 seconds.
2. Decision Making:
The agent looks for alignment across indicators. It only trades when 3+ indicators agree:
Example Decision Process:
ICICIBANK:
- RSI: 28 (oversold) → BUY signal
- MACD: Bullish crossover → BUY signal
- Price: Near lower Bollinger Band → BUY signal
- EMA: Price above 20 EMA → BUY signal
- Stochastic: < 20 → BUY signal
Result: 5 aligned signals → STRONG BUY
Action: Place market order for 7 shares (Rs.10,000 investment)
3. Risk Management:
The agent has built-in safety features:
- Daily Stop-Loss: Stops trading if you lose more than Rs.10,000 in a day
- Trade Limits: Maximum 5 trades per stock per day
- Position Control: Won’t add to existing positions (no pyramiding)
- Market Hours: Only trades 9:15 AM — 3:15 PM IST
- Auto Square-Off: Closes all positions at 3:15 PM
4. Memory & Learning:
The agent remembers:
- Every trade it made
- Profit/loss per trade
- Which indicators worked best
- Market conditions during each trade
This helps it improve over time (though remember, this is a learning prototype, not a money-making guarantee).
5. Account Access:
Through OpenAlgo, the agent can:
- Check your account balance
- View open positions
- See profit/loss in real-time
- Place market orders
- Cancel pending orders
- Close positions
Setting Up: What You Need
To build and run this prototype, you need:
1. OpenAlgo Running on Your System
What is OpenAlgo?
OpenAlgo is an open-source bridge between your code and your stock broker. It translates your code commands into broker-specific API calls.
Setup Steps:
# Install OpenAlgo from
git clone https://github.com/marketcalls/openalgo
OpenAlgo by default runs on: http://127.0.0.1:5000
Connect Your Broker:
- Log into OpenAlgo dashboard
- Connect your broker account (Zerodha, Fyers, Dhan, Upstox, etc.)
- Generate an API key
- Save the API key for your trading agent
Why OpenAlgo?
Without it, you’d need to write broker-specific code for each broker. OpenAlgo gives you one universal API that works with 23+ Indian brokers.
2. Get an LLM API Key
You need an API key from at least one AI model provider. Here are your options:
For Beginners (Cheapest):
- **Groq**: Free tier available, very fast
- Get key at: https://console.groq.com/
- Model: llama-3.3–70b-versatile
- Cost: $0.59 per 1M tokens
For Production (Fastest):
- Cerebras: Ultra-fast inference
- Get key at: https://cloud.cerebras.ai/
- Model: llama3.1–8b
- Cost: $0.60 per 1M tokens
- Speed: 1800+ tokens/second
For Quality (Most Accurate):
- OpenAI: Industry standard
- Get key at: https://platform.openai.com/
- Model: gpt-5-mini
- Cost: $0.15 input / $0.60 output per 1M tokens
Recommendation for Learning:
Start with Groq. It’s fast, cheap, and perfect for testing. Once you understand how everything works, you can switch to Cerebras for speed or OpenAI for quality.
3. Install the Agentic Trader
# Clone the repository
git clone https://github.com/marketcalls/Agentic-Trader.git
cd Agentic-Trader
# Install uv package manager (fast Python installer)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install dependencies
uv sync
# Configure environment
cp .env.example .env
Edit the `.env` file:
# Choose your AI provider
MODEL_PROVIDER=groq
# Add your AI API key
GROQ_API_KEY=gsk-your-key-here
GROQ_MODEL=groq/llama-3.3–70b-versatile
# Add your OpenAlgo API key
OPENALGO_API_KEY=your-openalgo-key-here
OPENALGO_HOST=http://127.0.0.1:5000
4. Run the Agent
# Start the agent
uv run python agent.py
You’ll see output like:
================================================================================
[INIT] Initializing Trading State…
================================================================================
[INIT] Fetching account funds…
[INIT] ✓ Available Cash: Rs.10,500.00
[INIT] Fetching open positions…
[INIT] ✓ Open Positions: 0
[INIT] ✓ Daily P&L: Rs.0.00
[INIT] ✓ Stop-loss check: OK
================================================================================
Trading Cycle: 2025–01–15 10:30:00 IST
================================================================================
[BULK DATA] Fetching data for 5 symbols in parallel…
[BULK DATA] Completed in 2.3 seconds
ICICIBANK: BUY Order#123 (MACD bullish)
RELIANCE: HOLD (weak signals)
SBIN: HOLD (existing position)
WIPRO: SELL Order#124 (take profit)
ITC: HOLD (mixed signals)
[TOKEN USAGE]
Total Tokens: 31,085
Cost: $0.008
How It All Works Together
Let me walk you through a complete trading cycle:
Step 1: Initialization (Happens Once at Startup)
Agent starts → Connects to OpenAlgo → Checks account balance
→ Fetches open positions → Calculates current P&L
→ Verifies stop-loss status → Ready to trade
Step 2: Market Data Fetch (Every 5 Minutes)
Agent wakes up → Fetches data for all 5 stocks in parallel
→ Gets quotes, depth, historical data
→ Calculates 7 technical indicators for each stock
→ Completes in 2–3 seconds
Step 3: Analysis (For Each Stock)
Agent analyzes ICICIBANK:
→ RSI = 28 (oversold)
→ MACD = bullish crossover
→ Price near lower Bollinger Band
→ 3+ indicators aligned → BUY signal
Agent checks risk constraints:
→ Daily P&L = Rs.250 (OK, below stop-loss)
→ Trades today = 2 (OK, below limit of 5)
→ Existing position? No (OK to trade)
→ Risk check PASSED
Agent calculates position size:
→ LTP = Rs.1,346.40
→ Investment = Rs.10,000
→ Quantity = 7 shares
→ Actual cost = Rs.9,424.80
Step 4: Execution
Agent places market order:
→ Symbol: ICICIBANK
→ Action: BUY
→ Quantity: 7
→ Order Type: MARKET (instant execution)
→ Strategy: AI Agent
OpenAlgo sends order to broker
→ Broker executes immediately at market price
→ Order ID: #123
→ Status: COMPLETED
Step 5: Tracking
Agent updates state:
→ Records trade in history
→ Updates trade count (now 3 for ICICIBANK)
→ Calculates new P&L
→ Saves to memory for learning
**Step 6: Wait**
Agent sleeps for 5 minutes → Repeat from Step 2
**Step 7: Square-Off (3:15 PM)**
Market closing time → Agent checks all open positions
→ ICICIBANK: 7 shares long → Place SELL 7 shares
→ RELIANCE: 1 share short → Place BUY 1 share
→ All positions closed
→ Cancel any pending orders
→ Done for the day
## Understanding the Architecture
Here’s what makes this prototype token-efficient:
### Single Agent Flow
┌─────────────────────────────────────┐
│ AUTONOMOUS TRADING AGENT │
│ (One Smart Agent) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────┐
│ BULK DATA FETCH (Parallel) │
│ • All 5 stocks at once │
│ • 2–3 seconds total │
└─────────────┬───────────────────┘
│
▼
┌─────────────────────────────────┐
│ ANALYZE EACH STOCK │
│ • Check 7 indicators │
│ • Make BUY/SELL/HOLD decision │
└─────────────┬───────────────────┘
│
▼
┌─────────────────────────────────┐
│ VALIDATE & EXECUTE │
│ • Check risk constraints │
│ • Calculate position size │
│ • Place orders in bulk │
└─────────────┬───────────────────┘
│
▼
┌─────────────────────────────────┐
│ OPENALGO → BROKER │
│ • Orders executed │
└─────────────────────────────────┘
Why This is Efficient
Single Context:
Instead of passing data between multiple agents (which costs tokens), everything happens in one conversation. The agent gets all the data once, makes all decisions, and executes all orders in one go.
Bulk Operations:
- Fetches data for ALL stocks in parallel (not one by one)
- Places ALL orders at once (not sequentially)
- Checks ALL risk constraints in one batch
Minimal Prompts:
The agent’s instructions are just 30 lines of plain text, not 80+ lines of verbose explanations.
No Memory Bloat:
Each trading cycle is independent. The agent doesn’t carry forward massive conversation history.
Real-World Performance
Let me show you actual numbers from testing:
Speed
Total Cycle Time: 5-9 seconds
Breakdown:
- Data Fetch (5 stocks): 2–3s
- Analysis & Decisions: 2–4s
- Order Execution: <1s
Compare this to the multi-agent version: 12–20 seconds per cycle.
### Cost
Per Trading Cycle:
- Tokens Used: ~30,000
- Cost (Groq): $0.018
- Cost (Cerebras): $0.018
- Cost (OpenAI): $0.008
Daily (75 cycles):
- Groq: $1.35
- Cerebras: $1.35
- OpenAI: $0.60
Monthly:
- Groq: ~$40
- Cerebras: ~$40
- OpenAI: ~$18
Accuracy
The agent requires 3+ indicators to align before trading. In testing:
- Win Rate: ~55–60% (varies by market conditions)
- Risk-Adjusted: All trades limited to Rs.10,000
- Max Loss: Rs.10,000 per day (enforced by code)
Important: These are prototype testing results, not live trading performance. Past performance doesn’t guarantee future results.
What You Should Know
This is an Educational Prototype
Let me be very clear about what this is and isn’t:
What it IS:
- A learning tool to understand agentic AI
- A demonstration of token-efficient architecture
- A way to experiment with AI trading concepts
- Open source code you can study and modify
What it is NOT:
- A guarantee to make money
- A production-ready trading system
- Financial advice
- A get-rich-quick scheme
Important Safety Points
1. Paper Trade First:
Test with fake money before real money. OpenAlgo supports paper trading mode.
2. Start Small:
If you do test with real money, start with the minimum amount you can afford to lose completely.
3. Understand the Risks:
- Markets are unpredictable
- Technical indicators can give false signals
- AI can make mistakes
- Past performance ≠ future results
- You can lose all your capital
4. Legal Compliance:
Check if algorithmic trading is legal in your jurisdiction. In India, it’s allowed for retail traders, but always verify.
5. Monitor It:
Never leave an automated trading system running unattended for long periods. Check it regularly.
Learning Path: Where to Go From Here
If you want to build on this prototype, here’s a learning path:
Beginner Level
- Run the prototype in paper trading mode
- Understand how each function works
- Try changing the technical indicators
- Experiment with different risk limits
- Test with different AI models (switch between Groq, OpenAI, Cerebras)
Intermediate Level
- Add more stocks to analyze
- Implement new technical indicators (VWAP, Fibonacci, etc.)
- Build a dashboard to visualize trades
- Add backtesting (test strategies on historical data)
- Implement position sizing strategies (Kelly Criterion, etc.)
Advanced Level
- Add sentiment analysis (news, Twitter, Reddit)
- Implement machine learning for pattern recognition
- Build multi-timeframe analysis (5min, 15min, 1hour charts)
- Add options trading capabilities
- Implement portfolio management across multiple stocks
The Bigger Picture: Why Agentic AI Matters
Building this trading agent taught me lessons that apply far beyond trading:
1. Simplicity Wins:
A well-designed single agent beats a complex multi-agent system. This applies to business processes, software architecture, and life.
2. Token Efficiency = Cost Efficiency:
Every API call costs money. In AI systems, efficiency isn’t just about speed — it’s about economics.
3. Model Agnostic = Future Proof:
Technology changes fast. Building systems that can swap components (like AI models) keeps you flexible.
4. Autonomous Doesn’t Mean Unsupervised:
The agent is autonomous, but it needs rules, constraints, and monitoring. True AI safety comes from good design, not just hoping the AI does the right thing.
5. Real-World AI is Messy:
Building this taught me about API rate limits, network timeouts, broker API quirks, and a hundred other practical issues you don’t face with toy examples.
Resources & Next Steps
If you want to build this yourself or learn more:
GitHub Repository:
https://github.com/marketcalls/Agentic-Trader
Prerequisites:**
- Basic Python knowledge
- Understanding of REST APIs
- Stock market basics (what’s a BUY/SELL order?)
- Basic terminal/command line skills
Documentation:
- OpenAI Agents SDK: https://openai.github.io/openai-agents-python/
- LiteLLM: https://docs.litellm.ai/
- OpenAlgo: https://openalgo.in/
- TA-Lib: https://ta-lib.org/
Community:
Join discussions about agentic AI and algo trading in Discord community. Share your learnings, ask questions, and help others.
Final Thoughts
Building an agentic trader is an incredible learning experience. You’ll learn about:
- AI agent architecture
- Real-time data processing
- Risk management
- API integration
- System design
- Financial markets
But remember: this is about learning, not about making quick money. The real value is in understanding how these systems work, so you can build other agentic systems (customer service bots, research assistants, automation tools) with the same principles.
The future is agentic. AI won’t just answer questions — it will take actions, make decisions, and accomplish goals autonomously. Understanding how to build, constrain, and optimize these systems is a valuable skill, whether you’re building trading agents, business automation, or the next AI startup.
Start simple, learn deeply, and build responsibly.
Happy building!
About This Article:
This article describes an open-source educational prototype. All code is available under MIT License. The author and contributors are not responsible for any financial losses. Trading involves substantial risk. Always test in paper trading mode first.
Want to Contribute?
The project is open source. Submit issues, pull requests, or feedback on GitHub.
Connect:
If you build something cool with this or have questions, share your journey. The best way to learn is by teaching others.