DEV Community

AaronTrng
AaronTrng

Posted on

Complete Guide: Using AlpacaTradingAgent Web UI for Automated Trading

Multi Trading Agents on Alpaca

⚠️ Important: This system is designed for research and educational purposes. Always start with paper trading mode before risking real money.

Table of Contents

  1. 🆕 What’s New — AlpacaTradingAgent
  2. 🔑 Getting Started: API Keys Setup
  3. ⚙️ Environment Setup
  4. 🌐 Launching the Web UI
  5. 📈 Picking Symbols to Analyze
  6. 🧠 Select Analysts
  7. 🔍 Research Depth
  8. 📈 Understanding Investment vs Trading Modes
  9. ⏰ Scheduling Analysis and Trading
  10. ⚙️ Automated Trading
  11. 🧠 Choosing Your LLMs — Quick vs Deep Thinker
  12. 👀 Monitoring Your Operations
  13. 💼 Managing Positions and Orders
  14. 📊 Reading Reports and Results
  15. 🧩 How the Multi-Agent Brain Works
  16. 🆘 Troubleshooting Common Issues
  17. 🎉 Wrap-Up

🆕 What’s New — AlpacaTradingAgent

Use huygiatrng/AlpacaTradingAgent which was inspired by TauricResearch/TradingAgents and re-engineered **specifically for Alpaca* with an End-of-Day (EOD) focus and a five-agent architecture.*

🚀 Upgrade Why it matters
Dash-powered Web UI Modern, reactive dashboard built with Plotly Dash – live charts, tabbed agent reports, manual order buttons, no CLI needed.
Five-agent brain (was four) Market (technicals)
News (headline sentiment)
Social (Reddit/Twitter pulse)
Fundamentals (financials & comps)
Macro (FRED data: Fed speeches, CPI, GDP, rates)
EOD-tuned prompts LLM prompts rewritten around End-of-Day decision-making – less noise from intraday whipsaws, tighter alignment with closing prices.
Debate & 3-layer Risk Gate Bull vs Bear researchers debate, then three independent Risk-Manager agents vet position size, stop, and exposure before any order routes to Alpaca.
Stocks and Crypto Analyse and trade NVDA, AAPL, plus BTC/USD, ETH/USD, etc. in one batch (crypto data via CoinDesk & DeFi Llama).
Multi-symbol parallel runs Just type NVDA, TSLA, ETH/USD – the stack spins up all agents for each symbol concurrently.
Smart Scheduler • Continuous loop every N hours (ideal for 24/7 crypto)
• Market-hour triggers for equities (e.g. run at 10 AM & 3 PM ET).
Alpaca auto-trade Full support for paper or live accounts, fractional shares, and margin long/short.
Account dashboard Real-time buying power, cash, open P/L, and one-click LIQUIDATE for any position.

🔑 Getting Started: API Keys Setup

Before you can use AlpacaTradingAgent's web UI for automated trading, you'll need to obtain API keys from several financial data providers. This section will guide you through each provider step-by-step.

1. 🏦 Alpaca API Keys (Required for Trading and fetching stock chart)

Alpaca API Key and API Secret

Alpaca is your primary trading broker and the most critical API for this system.

Steps to get Alpaca API Keys:

  1. Visit Alpaca Markets and create an account
  2. Complete the account verification process (this may take 1-3 business days)
  3. Once verified, log into your Alpaca dashboard
  4. Navigate to "API Keys" section in your account settings
  5. Click "Create New Key" and give it a descriptive name like TradingAgent
  6. Copy both the API Key and Secret Key - you'll need both
  7. If you want the agent to be able to perform shorting. You should turn on "Shorting Enabled" in the Alpaca Account's Configuration.

💡 Pro Tip: Keep your API keys secure and never share them publicly!

Important Configuration Notes:

Setting ALPACA_USE_PAPER Recommendation ALPACA_ENDPOINT
Paper Trading ALPACA_USE_PAPER=True Start here for risk-free testing https://paper-api.alpaca.markets/v2
Live Trading ALPACA_USE_PAPER=False ⚠️ Only when ready to trade real money https://api.alpaca.markets

2. 🤖 OpenAI API Key (Required for AI Analysis)

OpenAI powers the multi-agent analysis system that makes trading decisions.

Steps to get OpenAI API Key:

  1. Go to OpenAI Platform
  2. Create an account or log in to your existing account
  3. Create a project and name it
  4. Navigate to "API Keys" section in "Setting"
  5. Click "Create new secret key"
  6. Give it a name like AlpacaTradingAgent
  7. Copy the generated key immediately (it won't be shown again)

API keys in OpenAI API

💰 Cost Considerations:

  • We recommend using gpt-4.1-nano for both quick and deep thinking models during testing, it has the websearch feature and still minimizes costs
  • The system makes numerous API calls across 5 different agents
  • Monitor your OpenAI usage dashboard regularly

3. 📰 Finnhub API Key (Required for Stock News)

Finnhub provides real-time financial news and market data.

Steps to get Finnhub API Key:

  1. Visit Finnhub
  2. Create a free account
  3. Verify your email address
  4. Log in and navigate to your dashboard
  5. Your API key will be displayed on the main dashboard page
  6. Copy the key for later use

Finnhub API Key

4. 🏛️ FRED API Key (Required for Macro Analysis)

FRED (Federal Reserve Economic Data) provides macroeconomic indicators.

Steps to get FRED API Key:

  1. Visit FRED API Registration
  2. Click "Request API Key"
  3. Fill out the registration form (it's completely free)
  4. Check your "API Keys" section for the "API Key"
  5. Save the key for configuration

FREDAPI API Keys

5. ₿ CoinDesk API Key (Required for Crypto Analysis)

For cryptocurrency news and data analysis.

Steps to get CoinDesk API Key:

  1. Visit CryptoCompare
  2. Create an account
  3. Navigate to API Keys section
  4. Generate a new API key
  5. Copy the key for your configuration

API Keys in Coindesk


⚙️ Environment Setup

1️⃣ Clone the Repository

# Pick a folder and grab the code
git clone https://github.com/huygiatrng/AlpacaTradingAgent.git
cd AlpacaTradingAgent
Enter fullscreen mode Exit fullscreen mode

Tip: Keep the project inside its own folder so the relative paths in the web UI (logs, checkpoints, screenshots) work out-of-the-box.


2️⃣ Create & Activate a Python Environment

# Create a fresh Conda env (recommended)
conda create -n alpacatradingagent python=3.13
conda activate alpacatradingagent
Enter fullscreen mode Exit fullscreen mode

If you prefer venv/virtualenv, that works too—just make sure it’s isolated.


3️⃣ Install Dependencies

# Inside the repo root
pip install -r requirements.txt

# Optional: keep pip itself current
pip install --upgrade pip
Enter fullscreen mode Exit fullscreen mode

You should see all packages install without errors; the heavy ones are dash, plotly, ta, and the OpenAI client.


4️⃣ Configure Your Secrets

  1. Copy the template:
   cp env.sample .env
Enter fullscreen mode Exit fullscreen mode
  1. Edit .env and drop in your keys:

Keep this file private—never commit it to GitHub.


.env file

🔒 Security Note: Never commit your .env file to version control or share it publicly!


🌐 Launching the Web UI

🚀 Starting the Application

Launch the web interface using:

python run_webui_dash.py
Enter fullscreen mode Exit fullscreen mode

WebUI is running

🖥️ Accessing the Interface

  1. Open your browser
  2. Navigate to http://localhost:7860
  3. You'll see the top with 2 panels which show your current positions and recent orders, which are fetched from your Alpaca account

Current position and recent order panels

  1. Below are the config, chart, status, and decision panels, which are set at their default settings.

Default config at left side and chart, status, decision panels at right side

  1. And the bottom is the reports panel, where we can navigate analysts' reports, debates, and managers' reports of our agent on multiple symbols.

Reports panel


📈 Picking Symbols to Analyze

In AlpacaTradingAgent, you can analyze both stocks and cryptocurrencies using a simple input format. The system will run a full AI-driven analysis on each symbol you specify.

🔤 Symbol Input Format

  • ✅ For stocks: just use the ticker (e.g., NVDA, AAPL, TSLA)
  • ✅ For cryptocurrencies: use the format COIN/USD (e.g., BTC/USD, ETH/USD)

🧠 Tip: Always include /USD for crypto symbols so the agent recognizes them correctly.

💬 Examples:

Input What It Analyzes
NVDA, AMD Nvidia and AMD (stocks)
BTC/USD, TSLA Bitcoin (crypto) and Tesla (stock)
ETH/USD, AAPL, SOL/USD Ethereum (crypto), Apple (stock), and Solana (crypto)

Symbol Input Screenshot

⚠️ Reminder: Stick to supported formats. Don't use $TSLA or BTCUSD – always enter TSLA, BTC/USD, etc.

🧩 Multi-Asset Support

The system can handle mixed symbol types in a single run:

NVDA, ETH/USD, GOOGL, BTC/USD
Enter fullscreen mode Exit fullscreen mode

Will analyze:

  • Nvidia (stock)
  • Ethereum (crypto)
  • Google (stock)
  • Bitcoin (crypto)

Once entered, the agents will begin processing each symbol in parallel and deliver tabbed reports with deep insights per asset.


🧠 Select Analysts

Before starting the analysis, you can choose which AI analysts you want to include in the decision-making process. This allows you to tailor the depth and focus of each run based on your strategy.

Select Analysts UI

✅ Analyst Options:

Analyst Description
Market Analyst Performs technical analysis on charts, price patterns, and volume indicators
News Analyst Extracts and evaluates sentiment and impact of recent financial news
Macro Analyst Analyzes economic indicators (GDP, interest rates, inflation, etc.) from FRED
Social Media Analyst Tracks sentiment trends on Reddit, Twitter, and other platforms
Fundamentals Analyst Reviews company financials, balance sheets, P/E ratio, and earnings reports

💡 Customization Tips:

  • Turn all analysts ON for full-spectrum analysis
  • Use Market + Fundamentals for traditional investing
  • Use News + Social Media for short-term sentiment-based trades
  • Use Macro Analyst for positions affected by economic cycles

🧪 Experiment Freely: You can rerun the analysis with different combinations to compare perspectives.

Once selected, these analysts will generate their individual reports, and the system will automatically synthesize their insights into a final recommendation.


🔍 Research Depth

You can customize how deeply the AI agents debate, analyze, and deliberate before making a recommendation. This affects how long the analysis takes and how thorough the results are.

Research Depth Options

🧠 Depth Levels:

Mode Description Settings Best For
Shallow Quick research with minimal discussion max_debate_rounds = 1
max_risk_discuss_rounds = 1
Fast results without deep debate
Medium Balanced analysis and agent debate max_debate_rounds = 3
max_risk_discuss_rounds = 3
General use cases and regular trading
Deep Full in-depth research with extensive deliberation max_debate_rounds = 5
max_risk_discuss_rounds = 5
High-stakes decisions and deep dives

⏱️ Trade-off: More depth = more time + more OpenAI usage. Use Shallow for quick checks and Deep when precision matters.

✅ How to Use

  • Select the Research Depth in the sidebar before clicking Start Analysis
  • The number of debate and risk discussion rounds will follow your selected depth
  • Each agent will use the depth to determine how much reasoning to perform before making conclusions

📈 Understanding Investment vs Trading Modes

The AlpacaTradingAgent supports two distinct approaches to market participation:

💎 Investment Mode (Buy/Hold/Sell)

Characteristics:

  • ⏰ Time Horizon: Long-term focus (days to months)
  • 📊 Strategy: Buy and hold approach
  • 🏦 Account Type: Suitable for retirement accounts and cash accounts
  • 🎯 Decisions: BUY, HOLD, or SELL existing positions

Investing Mode

💡 Use Cases:

  • Building long-term wealth
  • Retirement portfolio management
  • Low-frequency trading
  • Risk-averse investors

⚡ Trading Mode (Short/Neutral/Long)

Characteristics:

  • ⏰ Time Horizon: Short-term focus (minutes to days)
  • 📊 Strategy: Active position management
  • 🏦 Account Type: Requires margin account for short selling
  • 🎯 Decisions: SHORT (sell/bet against), NEUTRAL (no position), LONG (buy/bet for)

Trading Mode

💡 Use Cases:

  • Day trading and swing trading
  • Market timing strategies
  • Hedging existing positions
  • Active portfolio management

⚠️ Important: Trading mode requires a margin account and involves higher risk

🏦Turn on margin for Alpaca Paper account:

  • You can adjust the Max Margin Multiplier inside the Alpaca Paper account Configuration.

Alpaca paper account configuration


⏰ Scheduling Analysis and Trading

The web UI provides two powerful scheduling options for automated analysis and trading that you can turn on if you want:

🔄 Loop Scheduling (Continuous Analysis)

Turned on Loop Mode and set Loop Interval

🛠️ Configuration Steps:

  1. Input your symbols (e.g., "NVDA, ETH/USD, AAPL")
  2. Navigate to the "Scheduling Configuration " section in the web UI
  3. Select "Enable Loop Mode"
  4. Set the "Loop Interval" (e.g., 60 for 60 minutes after finished previous analysis)
  5. Enable/disable auto-execution of trades (switch "Trade After Analyze" in "Automated Trading " section)
  6. Click "Start Analaysis"

✨ Features:

  • ✅ Runs continuously (suited best for cryptocurrency trading)

📝 Best Practices:

  • Start with longer intervals (4-6 hours) for testing
  • Use paper trading mode initially
  • Monitor API usage costs with frequent analysis

🕐 Scheduled Analysis (Specific Time during Market hours)

Turned on Trade and Market Hour and set Trading Hours


Absolutely! Here's the completed section for ⚙️ Automated Trading, incorporating the two image states you provided:


⚙️ Automated Trading

You can decide whether to manually review analysis results or let the AI automatically place trades based on the final decision.


🖐️ Manual Trading Mode (Default)

Manual Mode Screenshot

When "Trade After Analyze" is turned OFF, the system enters Manual Trading Mode.

📝 Description:

Analysis results will be shown for your review. No trades will be executed automatically.

⚙️ Behavior:

  • ❌ No automatic orders will be placed
  • 👁️ Review analysis results manually
  • 🧑‍💻 Execute trades manually through your broker (e.g., Alpaca dashboard)

💡 Use This Mode If you're testing, learning, or want full control over execution.


🤖 Automated Trading Mode

Automated Mode Screenshot

Turn ON the "Trade After Analyze" toggle to let the agent auto-execute trades based on its final decision.

📝 Description:

The system will execute trades using the specified Order Amount (\$) per symbol.

⚙️ Behavior:

  • ✅ Automatically places trades after analysis finishes
  • 📏 Uses fractional or integer shares (depending on your Alpaca settings)
  • 📈 Executes trades based on strategy and risk assessment
  • 💸 Each symbol will be allocated the full amount you set (e.g., \$4500 per symbol)

📊 Example:

If Order Amount = 200 and NVDA is trading at $150, the system will purchase 1 share (not fractional unless enabled in Alpaca).


💵 Order Amount (\$)

Specify the amount of capital to use per trade. This is applied individually to each symbol being analyzed.

Setting Example Input Outcome
Order Amount = 500 Symbol = TSLA ($250) Buys 2 shares
Order Amount = 200 Symbol = NVDA ($150) Buys 1 share
Order Amount = 80 Symbol = AAPL ($190) No trade (unless fractional trading is on)

🧠 Choosing Your LLMs — Quick vs Deep Thinker

Slot Purpose What to look for Recommended Models
Quick Thinker Fast, surface-level reasoning, headline scraping, fact-gathering. Runs dozens of short calls per analysis. ⚡ Low latency • 🕸️ Built-in web-search gpt-4.1-nano ⭐ (cheapest)
gpt-4.1-mini
gpt-4.1
Deep Thinker Long-form synthesis, weighing evidence, writing structured reports. Runs only a handful of heavier calls. 🧠 High reasoning depth • 🕸️ Web-search optional OpenAI o3 🏆 (best accuracy)
gpt-4.1 family if cost-sensitive

Web-search support: Only the 4.1 family (4.1-nano, 4.1-mini, 4.1) can call the built-in browser tool. That makes them ideal for the Quick Thinker, which needs fresh headlines, Reddit threads, etc.

Practical tips

  • Budget testing: Set both slots to gpt-4.1-nano. You keep web-search capability at the lowest token price while you shake down the pipeline.
  • Production blend: Use gpt-4.1-nano (Quick) + o3 (Deep). You’ll pay a bit more per run but gain noticeably tighter reasoning in Researcher debates and Risk reviews.
  • You can switch models any time in the dropdowns shown above—changes take effect on the very next analysis cycle.

Keep an eye on your OpenAI usage dashboard; the Quick Thinker makes many more calls, so its model choice has the biggest impact on cost.


👀 Monitoring Your Operations

📊 Real-Time Progress Tracking

The web UI provides comprehensive monitoring capabilities:

Stock chart, status and decision summary when analyzing

🎛️ Analysis Report Panel Overview

Social Analysis report in Report panel

📺 Simulate Debate of Researchers and Risk Managers

Debate of Bullish and Bearish Researchers

🔄 Real-Time Updates Include:

  • 🤖 Agent decisions and reasoning
  • 📊 Market data updates
  • 📰 News events affecting analyzed symbols
  • ⚠️ Risk management alerts
  • ✅ Trade execution confirmations

💡 Pro Tip: Keep the live feed open to monitor agent decision-making in real-time


💼 Managing Positions and Orders

📈 Current Positions Dashboard

Manage Current Position, Recent Orders and Buying Power

Panel What you see What you can do
Open Positions Symbol, quantity, market value, unrealised P/L Click LIQUIDATE to close immediately, or open the symbol to adjust protective stops
Recent Orders Every submission, fill and cancel (status-coloured) Cancel or duplicate pending orders; click an order row to view the full JSON sent to Alpaca
Buying Power & Cash Real-time equity, cash and margin headroom

The panels refresh automatically every few seconds; no manual reload needed.


📊 Reading Reports and Results

The web UI organizes analysis results into digestible, tabbed reports:

Final Report

  1. Executive Summary – one-glance recommendation (BUY / HOLD / SELL or LONG / SHORT / NEUTRAL), conviction score and risk rating.
  2. Market Analysis – annotated 1-year candlestick chart with volume, key moving averages and break-out levels.
  3. News & Social – latest headlines with sentiment scores plus Reddit/Twitter mention heat-maps.
  4. Fundamentals – valuation multiples, growth metrics and peer comparison for equities; on-chain and macro drivers for crypto.
  5. Risk Assessment – suggested position size, stop distance and scenario analysis.

🧩 How the Multi-Agent Brain Works

Workflow of Agents

Below is a step-by-step walk-through of the five-layer “think → debate → trade → vet → commit” pipeline illustrated in your schema. Use it as the “how it works” section in your docs.

Stage Role(s) What happens
1. Analysts (5 specialists) Market Analyst – price/volume via Alpaca + Stockstats
News Analyst – headlines & sentiment (Google News, Finnhub, CoinDesk)
Social-Media Analyst – Reddit pulse + WebSearch
Fundamentals Analyst – earnings, comps (Finnhub, SimFin, DeFi Llama)
Macro Analyst – FRED macro series
Each analyst ingests its data silo, extracts features, and produces a JSON “evidence packet” (metrics, charts, sentiment scores, etc.).
2. Researcher Team Bullish Researcher
Bearish Researcher
Both researchers read every evidence packet and argue in an internal Discussion loop (⁠_N_ rounds set by “Research Depth”⁠).
- Bull builds the pro case (why to buy/long)
- Bear builds the con case (why to sell/short)
All arguments cite the analyst evidence, so nothing is “hand-waved.”
3. Research Manager Single agent Acts as the referee/critic. Scores each argument for quality, flags missing data, and produces an Executive Research Report summarising:
• strongest buy points
• strongest sell points
• open questions / confidence level
4. Trader (Plan Builder) Single agent Converts the Research Report into a Transaction Proposal:
• direction (BUY / SELL / LONG / SHORT / NEUTRAL)
• tentative size (shares or USD)
• stop-loss & take-profit levels
• time horizon
5. Risk-Management Team Aggressive
Neutral
Conservative
Three independent risk profiles stress-test the proposal (position sizing, VaR, liquidity, correlation). They debate and may scale size up/down or veto trades that breach their limits.
6. Portfolio Manager Single agent Reviews the three risk opinions, the trader’s rationale, and current portfolio exposures. Chooses the Final Decision: approve, modify, or cancel.
7. Execution Engine If approved, submits orders to Alpaca, watches fills, and feeds real-time status back to the dashboard.

🆘 Troubleshooting Common Issues

Symptom Likely cause Fix
Agents stuck at “PENDING” OpenAI quota exhausted Downgrade research depth or raise quota
Orders “REJECTED” by broker Trade After Analyze on but insufficient buying power Reduce Order Amount (\$) or deposit funds
Loop never stops Both Loop Mode and Trade at Market Hour unticked Click Stop or refresh browser – default is infinite loop when neither scheduler is active

🎉 Wrap-Up

The AlpacaTradingAgent UI gives you an end-to-end command centre for research-grade analysis and one-click execution. After working through this guide you can:

✅ What you can do Why it matters
Wire up every required API key (Alpaca, OpenAI, Finnhub, FRED, CoinDesk) Live data, AI brains and broker access all in one place
Lock down the environment with a clean .env and an isolated Conda env Keeps secrets safe and dependencies conflict-free
Flip between Investment ↔ Trading modes Match the agent’s tactics to your time-horizon and risk profile
Schedule runs — continuous loops, clock-based slots or both Automate everything from hourly crypto scans to 10 AM & 2 PM equity check-ins
Track progress in real time with colour-coded status, live fills and P/L No need to refresh — the dashboard streams updates as they happen
Manage positions and orders directly from the UI Liquidate, scale in/out or tweak stops without leaving the page
Drill into multi-agent reports to see exactly how each specialist reached the call Transparency beats black-box signals every time

🚀 First flight: start in paper-trading mode with small order sizes. Prove the loop, study the reports, then graduate to live capital when you’re satisfied.

The agent stack is powerful, but it’s still a tool — final responsibility rests with your risk limits and investment plan.


⚠️ Research & Education only. Markets carry risk and past results are not predictive. Do your own due diligence or consult a licensed professional before committing real funds.

Happy trading & clear skies! 🚀📈

Top comments (1)

Collapse
 
koxx3 profile image
Koxx3

seems awesome. any performance feedback ?