🚀 AlpacaTradingAgent - An independent enhanced version built upon the original TradingAgents framework, specifically designed for Alpaca users who want to test or use AI agents to trade on their Alpaca accounts.
This project is an independent upgrade inspired by the original TradingAgents framework by Tauric Research, extending it with real-time Alpaca integration, crypto support, automated trading capabilities, and an enhanced web interface.
Disclaimer: This project is provided solely for educational and research purposes. It is not financial, investment, or trading advice. Trading involves risk, and users should conduct their own due diligence before making any trading decisions.
🚀 Enhanced Features | ⚡ Installation & Setup | 📦 Package Usage | 🌐 Web Interface | 📖 Complete Guide | 🤝 Contributing | 📄 Citation
AlpacaTradingAgent introduces powerful new capabilities specifically designed for Alpaca users:
- Live Trading: Direct integration with Alpaca API for real-time trading execution
- Paper & Live Trading: Support for both paper trading (testing) and live trading with real money
- Margin Trading: Full support for margin accounts, including short selling capabilities
- Portfolio Management: Real-time portfolio tracking, position monitoring, and order management
- Multi-Asset Analysis: Analyze both traditional stocks and cryptocurrencies in a single session
- Crypto Format: Use proper crypto format (e.g.,
BTC/USD,ETH/USD) for cryptocurrency analysis - Mixed Portfolios: Support for mixed symbol inputs like
"NVDA, ETH/USD, AAPL"for diversified analysis - Dedicated Data Sources: CoinDesk/CryptoCompare-compatible crypto news and DeFi Llama for fundamental crypto data
- Market Analyst: Evaluates overall market conditions and trends
- Social Sentiment Analyst: Analyzes social media sentiment and public opinion
- News Analyst: Monitors and interprets financial news and events
- Fundamental Analyst: Assesses company financials and intrinsic value
- Macro Analyst: Analyzes macroeconomic indicators and Federal Reserve data
- Parallel Execution: All 5 analysts run simultaneously for faster analysis with configurable delays to prevent API overload
- Default OpenAI GPT-5.4 Path: Uses
gpt-5.4-nanofor quick agents andgpt-5.4-minifor deeper manager/trader agents - Provider Choice: Supports OpenAI, local OpenAI-compatible endpoints, Google Gemini, Anthropic Claude, xAI, DeepSeek, Qwen, GLM, OpenRouter, Ollama, and Azure OpenAI
- Provider-Specific Controls: Preserves GPT reasoning controls, Gemini thinking level, Claude effort, custom model IDs, and Azure deployment names
- Local Compatibility:
OPENAI_USE_LOCALandOPENAI_BASE_URLcontinue to route core LLM calls to a local OpenAI-compatible backend
- Executable Final Action: Final decisions preserve
BUY/HOLD/SELLorLONG/NEUTRAL/SHORTfor Alpaca execution - Advisory Ratings: Upstream-style ratings are treated as metadata only and never directly trigger Alpaca orders
- Structured Output Fallback: Research Manager, Trader, and Risk Manager use structured schemas where supported and gracefully retry as free text otherwise
- Persistent Decision Log: Completed decisions are written to a markdown memory log and later resolved with realized returns and reflections
- Checkpoint Resume: Optional per-symbol SQLite checkpoints allow failed LangGraph runs to resume while successful runs clean up automatically
- Safe Paths: Report, cache, checkpoint, and log paths use safe ticker components, including crypto symbols like
BTC/USD -> BTC_USD
- Market Hours Trading: Automatic execution during market hours
- Scheduled Analysis: Configurable recurring analysis every N hours
- Auto-Execution: Optional automatic trade execution based on agent recommendations
- Smart Scheduling: Respects market hours for different asset classes
- Multi-Symbol Dashboard: Analyze and trade multiple symbols simultaneously
- Progress Tracking: Real-time progress table showing analysis status for each symbol
- Interactive Charts: Live Alpaca data integration with technical indicators
- Tabbed Reports: Organized analysis reports with easy navigation
- Chat-Style Debates: Visualize agent debates as conversation threads
- Position Management: View current positions, recent orders, and liquidate positions directly from UI
- Model Configuration: Choose provider, model, provider-specific parameters, output language, and checkpoint resume from the UI
For an in-depth, step-by-step walkthrough of using the AlpacaTradingAgent web UI for automated trading, check out the complete guide on Dev.to:
AlpacaTradingAgent is a multi-agent trading framework that mirrors the dynamics of real-world trading firms. By deploying specialized LLM-powered agents working collaboratively, the platform evaluates market conditions across multiple asset classes and executes informed trading decisions through the Alpaca API.
AlpacaTradingAgent framework is designed for research and educational purposes. Trading performance may vary based on many factors, including the chosen backbone language models, model temperature, trading periods, the quality of data, and other non-deterministic factors. It is not intended as financial, investment, or trading advice.
Our enhanced framework decomposes complex trading tasks into specialized roles while providing real-time market connectivity and execution capabilities.
- Market Analyst: Evaluates overall market conditions, sector trends, and market sentiment indicators
- Social Sentiment Analyst: Analyzes Reddit, OpenAI web-search sentiment, and public market narratives
- News Analyst: Monitors financial news, earnings announcements, and global events that impact markets
- Fundamental Analyst: Evaluates company financials, earnings reports, and intrinsic value calculations
- Macro Analyst: Analyzes Federal Reserve data, economic indicators, and macroeconomic trends using FRED API
- Comprises both bullish and bearish researchers who critically assess the insights provided by the Analyst Team. Through structured debates, they balance potential gains against inherent risks, now with enhanced support for both equity and crypto markets.
- Composes reports from analysts and researchers to make informed trading decisions. Determines timing, magnitude, and direction (long/short) of trades with direct execution through Alpaca API.
- Continuously evaluates portfolio risk across stocks and crypto assets. Monitors margin requirements, position sizes, and overall portfolio exposure. Provides real-time risk assessment and position management through the Alpaca integration.
Clone AlpacaTradingAgent:
git clone https://github.com/huygiatrng/AlpacaTradingAgent.git
cd AlpacaTradingAgentInstall dependencies:
pip install -r requirements.txtFor full functionality including real-time trading, you'll need to set up the following API keys:
-
Copy the sample environment file:
cp env.sample .env
-
Edit the
.envfile with your API keys:
-
Alpaca API Keys (Required for trading):
- Sign up at Alpaca Markets
- Get your API key and secret from the dashboard
- Set
ALPACA_USE_PAPER=Truefor paper trading (recommended for testing) - Set
ALPACA_USE_PAPER=Falsefor live trading with real money
-
OpenAI API Key (Default LLM provider and OpenAI web-search tools):
- Sign up at OpenAI Platform
- Default models are
gpt-5.4-nanoandgpt-5.4-mini
Set LLM_PROVIDER in .env, the CLI, or the WebUI. Supported providers include:
- OpenAI:
OPENAI_API_KEY - Local OpenAI-compatible:
OPENAI_USE_LOCAL=true,OPENAI_BASE_URL, optionalOPENAI_API_KEY - Google Gemini:
GOOGLE_API_KEY - Anthropic Claude:
ANTHROPIC_API_KEY - xAI Grok:
XAI_API_KEY - DeepSeek:
DEEPSEEK_API_KEY - Qwen/DashScope:
DASHSCOPE_API_KEY - GLM/Zhipu:
ZHIPU_API_KEY - OpenRouter:
OPENROUTER_API_KEY - Ollama: no API key by default; configure the backend URL
- Azure OpenAI:
AZURE_OPENAI_API_KEY,AZURE_OPENAI_ENDPOINT,AZURE_OPENAI_DEPLOYMENT_NAME,AZURE_OPENAI_API_VERSION
-
Finnhub API Key (Required for stock news and data):
- Sign up at Finnhub
-
FRED API Key (Required for macro analysis):
- Get your free key from FRED
- CoinDesk/CryptoCompare API Key (Required for crypto news):
- Sign up at CryptoCompare
- Alpha Vantage API Key (Optional fallback market data):
- Get from Alpha Vantage
- Fallback routing is optional and does not replace Alpaca as the primary market data path
env.sample also documents optional runtime paths:
TRADINGAGENTS_RESULTS_DIRfor report outputTRADINGAGENTS_CACHE_DIRfor cache and checkpoint filesTRADINGAGENTS_MEMORY_LOG_PATHfor persistent decision memory
- Restart the application after setting up your API keys.
Note: Without valid Alpaca API keys, the application will fall back to demo mode without trading capabilities.
You can try out the CLI by running:
python -m cli.mainThe CLI now supports multiple symbols and crypto assets:
- Single stock:
NVDA - Single crypto:
BTC/USD - Multiple mixed assets:
NVDA, ETH/USD, AAPL, BTC/USD - Provider/model selection, custom model IDs, checkpoint resume, and provider-specific settings are available from the CLI prompts.
Launch the enhanced Dash-based web interface:
python run_webui_dash.pyCommon options:
--port PORT: Specify a custom port (default: 7860)--share: Create a public link to share with others--server-name: Specify the server name/IP to bind to (default: 127.0.0.1)--debug: Run in debug mode with more logging--max-threads N: Set the maximum number of threads (default: 40)
or launch it with Docker:
cp env.sample .env
# Edit .env with your provider, market data, and Alpaca credentials first.
docker compose up -d --buildThis starts a local web server at http://localhost:7860. To use a different
host port, set HOST_PORT, for example HOST_PORT=7861 docker compose up -d --build.
Model-facing prompts live in tradingagents/prompts/templates. Edit those
Markdown templates to tune analyst, researcher, trader, risk, signal extraction,
and reflection behavior from one place. Templates are grouped by role:
analysts/, researchers/, managers/, trader/, risk/, trading_modes/,
graph/, and shared/.
To keep custom prompts outside the repo, copy selected templates to another
folder and set TRADINGAGENTS_PROMPT_DIR to that path. Keep the same group path
for overrides, for example analysts/market_system.md. Missing files fall back
to the bundled templates.
The web interface offers comprehensive trading and analysis capabilities:
Multi-Asset Analysis Dashboard
- Analyze multiple stocks and crypto assets simultaneously
- Real-time progress tracking for each symbol
- Support for mixed portfolios (e.g.,
"NVDA, ETH/USD, AAPL")
Live Trading Integration
- View current Alpaca positions and recent orders
- Execute trades directly from the interface
- Liquidate positions with one-click functionality
- Real-time portfolio value tracking
Interactive Charts & Data
- Live price charts powered by Alpaca API
- Technical indicators and analysis overlays
- Support for both stock and crypto price data
Enhanced Reporting Interface
- Tabbed navigation for different analysis reports
- Chat-style conversation view for agent debates
- Progress table showing analysis status for each symbol
- Downloadable reports and trade recommendations
Automated Trading Controls
- Schedule recurring analysis during market hours
- Configure auto-execution of trade recommendations
- Set custom analysis intervals (every N hours)
- Margin trading controls and risk management
LLM and Runtime Controls
- Select OpenAI, local OpenAI-compatible, Google, Anthropic, xAI, DeepSeek, Qwen, GLM, OpenRouter, Ollama, or Azure OpenAI
- Configure custom model IDs for compatible providers and Azure deployment names
- Tune GPT reasoning controls, Gemini thinking level, Claude effort, output language, and checkpoint resume
Built with LangGraph for flexibility and modularity. The enhanced version integrates with multiple financial APIs and supports both paper and live trading through Alpaca. We recommend gpt-5-nano for the cheapest testing runs or gpt-5.4-nano for a newer low-cost default, as the framework makes numerous API calls across all 5 agents.
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG
# Initialize with default config
ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())
# Analyze a single stock
_, decision = ta.propagate("NVDA", "2024-05-10")
print(decision)
# Analyze multiple assets including crypto
symbols = ["NVDA", "ETH/USD", "AAPL"]
for symbol in symbols:
_, decision = ta.propagate(symbol, "2024-05-10")
print(f"{symbol}: {decision}")from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG
# Create custom config for enhanced features
config = DEFAULT_CONFIG.copy()
config["deep_think_llm"] = "gpt-5.4-mini" # Balanced current default
config["quick_think_llm"] = "gpt-5.4-nano" # New low-cost quick model
config["quick_llm_params"] = {
"reasoning_effort": "low",
"text_verbosity": "low",
"reasoning_summary": "auto",
}
config["deep_llm_params"] = {
"reasoning_effort": "medium",
"text_verbosity": "medium",
"reasoning_summary": "auto",
}
config["max_debate_rounds"] = 2 # Increase debate rounds
config["online_tools"] = True # Use real-time data
config["allow_shorts"] = False # Investment mode: BUY/HOLD/SELL
config["checkpoint_enabled"] = False # Enable to resume failed graph runs
config["memory_log_path"] = "~/.tradingagents/memory/trading_memory.md"
config["news_global_openai_enabled"] = False # Macro handles broad global context by default
# Parallel execution settings (to avoid API overload)
config["parallel_analysts"] = True # Run analysts in parallel (default: True)
config["analyst_start_delay"] = 0.5 # Delay between starting each analyst (seconds)
config["analyst_call_delay"] = 0.1 # Delay before making analyst calls (seconds)
config["tool_result_delay"] = 0.2 # Delay between tool results and next call (seconds)
# Initialize with custom config
ta = TradingAgentsGraph(debug=True, config=config)
# Analyze with crypto support
_, decision = ta.propagate("BTC/USD", "2024-05-10")
print(decision)For non-OpenAI providers, switch the provider and model IDs:
config = DEFAULT_CONFIG.copy()
config["llm_provider"] = "google"
config["quick_think_llm"] = "gemini-2.5-flash"
config["deep_think_llm"] = "gemini-3.1-pro-preview"
config["google_thinking_level"] = "high"
ta = TradingAgentsGraph(debug=True, config=config)
_, decision = ta.propagate("NVDA", "2024-05-10")
print(decision)We welcome contributions from the community! AlpacaTradingAgent is an independent project that builds upon concepts from the original TradingAgents framework, continuously evolving with new features for Alpaca integration and multi-asset support.
This project is inspired by and builds upon concepts from the original TradingAgents framework by Tauric Research. We extend our gratitude to the original authors for their pioneering work in multi-agent financial trading systems.
AlpacaTradingAgent is an independent project that focuses specifically on providing Alpaca users with a production-ready trading interface, real-time market connectivity, and expanded asset class support while implementing an enhanced multi-agent architecture.
Please reference the original TradingAgents work that inspired this project:
@misc{xiao2025tradingagentsmultiagentsllmfinancial,
title={TradingAgents: Multi-Agents LLM Financial Trading Framework},
author={Yijia Xiao and Edward Sun and Di Luo and Wei Wang},
year={2025},
eprint={2412.20138},
archivePrefix={arXiv},
primaryClass={q-fin.TR},
url={https://arxiv.org/abs/2412.20138},
}



