A self-contained Python monorepo for algorithmic trading, shipping two platforms over three shared installable packages (ba2_common / ba2_providers / ba2_experts):
- ba2-trade (repo root) — the live trader: NiceGUI web app running the expert fleet against a real/paper broker (Alpaca, TastyTrade, IBKR), with ruleset-driven trade actions (equity and options), risk management, order execution and performance analytics.
- ba2-test (
testplatform/, aka BA2ML) — the backtest & ML platform: FastAPI + React app for dataset building, genetic-algorithm strategy optimization, deep-learning forecasting (12 PyTorch architectures) and point-in-time screening.
Both apps run the same expert/provider code, which is what makes a backtest predictive of live behaviour.
Main dashboard showing account summary and position overview
Multi-agent AI analysis with detailed recommendations and technical indicators
AI-generated trading recommendations with confidence levels and action items
Historical view of all generated recommendations and their performance
- 🧪 Experimental Release: This is pre-beta software with active development and breaking changes
- 🔄 Frequent Updates: APIs, database schema, and core functionality may change without notice
- 🐛 Expect Bugs: Known and unknown issues exist throughout the platform
- 📝 Incomplete Features: Some functionality may be partially implemented or missing
- 🔧 Developer Focused: Currently intended for developers and advanced users willing to troubleshoot
- 💾 No Migration Guarantees: Database schema changes may require fresh installations
- 📋 Documentation Gaps: Some features may lack complete documentation
USE ONLY FOR TESTING AND DEVELOPMENT - NOT SUITABLE FOR PRODUCTION TRADING
THIS SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY OF ANY KIND.
- 🚨 Trading involves substantial risk of loss and is not suitable for all investors
- 🧪 This software is experimental and should be thoroughly tested in paper trading mode before considering live trading
- 💰 You can lose money - possibly all of your investment capital
- 🤖 AI-driven decisions are not infallible - algorithms can make mistakes, markets are unpredictable
- 📉 Past performance does not guarantee future results - backtesting and historical analysis may not reflect real trading conditions
- ⚙️ Software bugs may exist - thoroughly review all code and test extensively before use
- 🔒 Use at your own risk and discretion - you are solely responsible for any trading decisions and their outcomes
- 💼 Not financial advice - this platform is a tool for educational and research purposes
RECOMMENDED PRACTICES:
- ✅ Start with paper trading to familiarize yourself with the platform
- ✅ Set strict risk limits and position sizing rules
- ✅ Monitor all automated trades closely
- ✅ Never invest more than you can afford to lose
- ✅ Understand the underlying strategies and code before enabling automation
- ✅ Keep detailed logs and review trading decisions regularly
- ✅ Test thoroughly in various market conditions before live deployment
By using this software, you acknowledge that you understand and accept these risks.
- Plugin Architecture: Extensible system for trading accounts and market experts
- Shared package split (see the intro):
ba2_commonholds models/DB/interfaces/types/position sizing,ba2_providersthe market-data providers, screener and caches,ba2_expertsthe expert implementations — so an expert is written once and runs identically live and in backtest. - SQLModel ORM: Modern database layer with SQLite backend, Alembic migrations
- NiceGUI Web Interface: Clean, responsive web UI for configuration and monitoring
- Extensible Settings: Flexible configuration system for all plugins
- Centralized Logging: Comprehensive logging with file rotation and colored output
- Event-driven backtest engine: daily and 5-minute bars, point-in-time data only, hermetic runs (never fetches mid-run) so results are reproducible
- Genetic optimization (DEAP): searches entry/exit rulesets, expert settings and risk-manager parameters together; per-generation checkpoints mean an interrupted multi-day run resumes rather than restarts
- Distributed evaluation: master + local process pool + version-matched remote workers, with a per-box memory governor that sheds concurrency instead of OOMing
- Robustness-adjusted fitness: a genome's raw score is discounted by concentration (does the book survive without its top trades?), Monte Carlo resampling, and a bid-ask spread stress test — both the raw and adjusted values are stored so a discounted result is explainable
- Realistic cost modelling: per-fill commission and measured per-cap-band bid-ask spreads (Alpaca SIP quotes), with an optional widening stress applied on top
- Screener metric store: precomputed cap-band/factor metrics so a genome's universe is selected point-in-time, per day, without re-scanning the market
- Multiple Expert Support: Extensible plugin architecture supporting multiple expert types (see EXPERTS.md for complete list)
- Parallel Market Analysis: Simultaneous analysis across multiple symbols for efficient processing
- Multi-Agent Analysis: Market, news, fundamentals, social media, and macro-economic analysts
- TradingAgents Integration: Advanced multi-agent LLM framework for financial trading
- Government Trading Data: FMP Senate/House trading analysis with both weighted algorithms and simple copy trading
- Analyst Consensus: Finnhub and FMP analyst rating aggregation and price target analysis
- FRED API Integration: Real-time macroeconomic data analysis
- Debate-Based Decision Making: Bull vs bear researcher debates with research manager oversight
- Risk Management: Multi-layered risk analysis and management
- Semi-Automatic Trading: Human approval required for trade execution
- Full Automatic Trading: Autonomous trading based on AI recommendations
- Virtual Equity Management: Split account balance across multiple experts to limit individual risk
- Expert-Level Risk Controls: Configurable risk limits per expert instance
- Portfolio Diversification: Automatic allocation management across different strategies
- Multiple Data Sources: Alpaca, Finnhub, SimFin, Yahoo Finance, FRED
- Real-Time & Historical Data: Comprehensive market data coverage
- Economic Indicators: Inflation, employment, treasury yields, economic calendar
- Social Sentiment: Reddit and social media sentiment analysis
- Multi-Expert Support: Run multiple AI experts simultaneously with individual risk management
- Parallel Symbol Analysis: Analyze multiple instruments concurrently for faster decision-making
- Automated Trade Execution: Semi-automatic (manual approval) or fully automatic trading modes
- Virtual Account Splitting: Allocate portions of your account to different experts to limit exposure
- Risk-Based Position Sizing: Dynamic position sizing based on expert confidence and risk assessment
- Expert Performance Tracking: Monitor and compare performance across different expert strategies
- Options Strategies: equity actions plus an entry-option path (rulesets can fire an option action with no equity leg) — long calls/puts, covered calls, credit/debit spreads, short straddle/strangle, iron condor, jade lizard, call butterfly, put ratio spread; GA-optimizable (
option_wing_widthgene + per-strategy grids), validated against real Alpaca options cache data
- Alpaca: Paper and live trading, equities + options (the primary, most exercised broker)
- TastyTrade: Options-oriented broker integration
- Interactive Brokers (IBKR): Broker integration
- Extensible Architecture: Easy addition of new brokers via
AccountInterface
The platform includes multiple AI trading experts with different strategies and capabilities:
| Expert | Description | Data Sources | Special Features |
|---|---|---|---|
| TradingAgents | Multi-agent AI system with debate-based analysis | Market data, news, fundamentals | Complex AI analysis, agent debates |
| FinnHubRating | Analyst consensus tracker | Finnhub analyst ratings | Weighted consensus scoring |
| FMPRating | Price target analyzer | FMP analyst data | Profit potential calculation |
| FMPSenateTraderWeight | Government trading tracker (sophisticated) | FMP Senate/House data | Portfolio allocation analysis |
| FMPSenateTraderCopy | Government trading tracker (simple copy) | FMP Senate/House data | 100% confidence copy trading, can recommend instruments |
| FMPInsiderClusterBuy | Insider cluster-buy detector — BUY when several insiders bought recently | FMP insider transactions | Cluster/recency windows, min distinct insiders (no large-cap data: small/mid only) |
| FMPEarningsDrift | Post-earnings-announcement drift — BUY fresh EPS beats, time-boxed hold | FMP earnings surprises | Surprise threshold, freshness window, forced time exit (small/mid only) |
| PennyMomentumTrader | Live intraday penny-stock momentum trader | Market data, screener, social/news catalysts | Self-executing live expert, screener universe, staged exits |
| FactorRanker | Cross-sectional multi-factor equity ranker | FMP fundamentals & prices, StockScreener | momentum / value / quality / PEAD factors, static or screener universe, self-rebalancing top-N (no recommendations) |
| DeterministicScorer | LLM-free multi-section scorer — reproduces a TradingAgents-style verdict with pure local math, zero LLM calls | FMP/FinnHub fundamentals, prices, ratings, FRED macro | Technical + fundamental + analyst + macro sections, tanh-bounded composite score, Altman-Z hard veto, fully deterministic and free to run |
PremiumSeller (systematic short-premium options income) was removed 2026-08-31 — its rails and exit lifecycle were promoted into shared code, so ANY expert can now be switched to risk_manager_mode: classic_options and have its option ENTRIES gated by them, with the drawdown circuit breaker transitioning identically in live and in the backtest. The exit/servicing pass is live-only by design; see EXPERTS.md §8 for what is and is not wired.
📖 For detailed documentation on all experts, their settings, and configuration options, see EXPERTS.md — and the dedicated FactorRanker guide.
- Python 3.11+, SQLModel/SQLAlchemy ORM on SQLite (Alembic migrations)
- ba2-trade UI: NiceGUI (dashboard, analysis, recommendations, rulesets, settings)
- ba2-test: FastAPI + Uvicorn backend; React 19 + TypeScript + Vite + Tailwind CSS frontend (lightweight-charts, recharts)
- ML: PyTorch — 12 forecasting architectures (LSTM, GRU, TCN, InceptionTime, ResNet, XceptionTime, OmniScale CNN, MiniRocket, PatchTST, TST, LSTM-FCN, N-BEATS), GA-tuned
- Optimization: DEAP genetic algorithms (strategy rails S1–S7, distributed workers, robustness-adjusted fitness)
- Data providers: Alpaca (prices/options), FMP (fundamentals, earnings, insider, Senate/House, screener), Finnhub, FRED (point-in-time macro), Yahoo Finance, ThetaData (option chains)
- Shared state:
BA2_HOMEcache tree (parquet OHLCV, options history, screener metric store) + shared app-settings/API-keys DB read by both platforms
- Python 3.11+
- SQLite (included)
- OpenAI API Key (or compatible LLM provider)
- Optional: Alpaca API Key, Finnhub API Key, FRED API Key, FMP API Key
The platform requires certain API keys to function properly. Configure all API keys through the Settings page at http://localhost:8080/settings.
LLM Configuration (Required - Choose One or Both)
The platform supports both OpenAI and NagaAI for AI-driven market analysis. You must configure at least one LLM provider.
- Purpose: Powers all AI trading experts and analysis
- Used by: TradingAgents multi-agent framework, market analysis, recommendation generation
- Get it: OpenAI API Platform
- Configure: Settings → Application Settings → OpenAI API Key
- Purpose: Cost-effective alternative to OpenAI with competitive models
- Used by: TradingAgents multi-agent framework, market analysis, recommendation generation
- Get it: NagaAI Platform - Sign up and create API key
- Configure: Settings → Application Settings → NagaAI API Key
- Backend URL:
https://api.nagaai.com/v1(automatically configured)
In Web Interface (Recommended):
- Navigate to Settings → Application Settings
- Choose your LLM provider:
- Enter OpenAI API Key if using OpenAI
- Enter NagaAI API Key if using NagaAI
- Select your preferred model from the dropdown
- Click Save - the platform automatically uses the configured provider
| Feature | OpenAI | NagaAI |
|---|---|---|
| Cost | Higher | Lower (often 50-70% cheaper) |
| Latency | Very fast | Fast |
| Rate Limits | Per-plan | Per-plan |
| Setup Time | Immediate | Immediate |
| Best For | Premium features | Budget-conscious users |
- Production Trading: Use OpenAI for reliability and latest models
- Testing/Development: Use NagaAI for cost savings
- Hybrid Approach: Configure both and switch based on market conditions
- Model and provider selection for AI experts is managed per-expert in the "Expert Settings" section of the web UI (Settings → Experts or the specific expert configuration page).
- Model names include a provider prefix so the platform can route requests to the correct backend:
- OpenAI models appear with the prefix
OpenAI/(for exampleOpenAI/gpt-4-turbo) - NagaAI models appear with the prefix
NagaAI/(for exampleNagaAI/claude-3-sonnet)
- OpenAI models appear with the prefix
- You can also choose which provider an expert uses in the same Expert Settings UI. This is a per-expert selection — different experts may use different providers concurrently.
- Important: It is the user's responsibility to add and configure valid API keys for any provider you select before enabling or running an expert. If an expert is configured to use a provider but no valid API key is present, the expert may receive empty responses or fail during execution.
Alpaca API Keys (Required if using Alpaca account provider)
Alpaca API keys are used at two levels:
-
Application Level (Optional - for market data/news):
- Purpose: Used by platform for real-time market prices and news data
- Configure: Settings → Application Settings → Alpaca API Key
- Used by: Market data retrieval, price feeds for analysis
-
Per-Account Level (Required for trading):
- Purpose: Live or paper trading account credentials
- Configure: Settings → Accounts → Add Alpaca Account
- Keys needed: API Key + Secret Key for each trading account
- Used by: Order execution, position tracking, account management
- Without account-level keys: Cannot trade through Alpaca (but can still use other trading providers or paper trading accounts)
- Without app-level keys: Platform uses alternative data sources for market data; reduced real-time market data accuracy
Finnhub API Key (Optional - enhances market data)
- Purpose: Additional market data, news, and fundamental analysis
- Used by: TradingAgents news analyst, fundamental analysis
- Get it: Finnhub API
- Configure: Settings → Application Settings → Finnhub API Key
- Without this: Uses alternative data sources, reduced analysis depth
FRED API Key (Optional - enhances macro analysis)
- Purpose: Federal Reserve economic data for macro analysis
- Used by: TradingAgents macro analyst for economic indicators
- Get it: FRED API
- Configure: Settings → Application Settings → FRED API Key
- Without this: Macro analysis uses limited economic data
FMP API Key (Optional - enhances fundamental data)
- Purpose: Financial Modeling Prep API for company fundamentals
- Used by: TradingAgents fundamental analyst for detailed financial metrics
- Get it: Financial Modeling Prep
- Configure: Settings → Application Settings → FMP API Key
- Without this: Limited fundamental analysis capabilities
All API keys should be configured through the Web Interface (Recommended):
- Navigate to
http://localhost:8080/settings - Enter API keys in respective sections (OpenAI or NagaAI)
- Select your preferred LLM model
- Keys are stored in local database
- API keys are stored in the local SQLite database - keep the database file secure
- Keys are never transmitted except to their respective API endpoints
- Use paper trading accounts for testing (Alpaca provides free paper trading)
- Keep your API keys secure and never share them publicly
- Regularly rotate API keys as a security best practice
- Python 3.11 or higher
- Git
- Windows/Linux/macOS
-
Clone the repository:
git clone https://github.com/bmigette/BA2TradePlatform.git cd BA2TradePlatformThis is a self-contained monorepo — the shared packages (
packages/common,packages/providers,packages/experts), the live trade app (repo root →ba2-trade), and the backtest/optimization platform (testplatform/→ba2-test) all live here. No external or sibling repositories are required. -
Recommended — install script (builds both venvs from this repo):
The install script creates two isolated venvs under
~/ba2-venvs/{trade,test}from the in-repopackages/chain + each app'srequirements.txt, and registers theba2-trade/ba2-testconsole commands. Everything is installed from this repo — no other git is referenced.Windows:
.\install.ps1 -Editable # -e in-repo packages for development
Linux/macOS:
./install.sh --editable
Useful flags:
-TradeOnly/-TestOnly(--trade-only/--test-only) to build just one venv,-Ui(--ui) for the NiceGUI extra,-Upgrade(--upgrade) to re-resolve deps. -
Alternative — manual single-venv setup (trade app only):
uvis a blazingly fast Python package installer and resolver, written in Rust. It's 10-100x faster than pip for installing packages.Install uv (if not already installed):
# Windows (PowerShell) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # Linux/macOS curl -LsSf https://astral.sh/uv/install.sh | sh
Create virtual environment and install dependencies:
# Create venv and install dependencies in one command uv venv uv pip install -r requirements.txtActivate the virtual environment:
# Windows .venv\Scripts\Activate.ps1 # Linux/macOS source .venv/bin/activate
Create and activate virtual environment:
Windows:
python -m venv .venv .venv\Scripts\Activate.ps1Linux/macOS:
python -m venv .venv source .venv/bin/activateInstall dependencies:
# Windows .venv\Scripts\python.exe -m pip install -r requirements.txt # Linux/macOS .venv/bin/python -m pip install -r requirements.txt
-
Run the application:
Windows:
.venv\Scripts\python.exe main.pyLinux/macOS:
.venv/bin/python main.py
The application supports command-line arguments to customize data folders and HTTP port:
python main.py [options]Available Options:
| Option | Description | Default |
|---|---|---|
--db-file |
Path to the SQLite database file | ~/Documents/ba2_trade_platform/db.sqlite |
--cache-folder |
Path to the cache folder for temporary data | ~/Documents/ba2_trade_platform/cache |
--log-folder |
Path to the log folder | ./logs |
--port |
HTTP port for the web interface | 8080 |
Examples:
# View help
python main.py --help
# Use custom database path
python main.py --db-file /data/trading/database.sqlite
# Use custom port
python main.py --port 9090
# Combine multiple options
python main.py --db-file /data/trading.db --cache-folder /tmp/cache --log-folder /var/log/ba2 --port 3000
# Development setup (separate database)
python main.py --db-file ./dev_database.sqlite --port 8081
# Production setup
python main.py --db-file /opt/ba2/production.db --cache-folder /opt/ba2/cache --log-folder /var/log/ba2 --port 80Notes:
- All folder paths are created automatically if they don't exist
- The database file's parent directory is also created automatically
- Arguments are parsed before any system initialization occurs
- The
--helpoption shows all available options without starting the application
-
Access the web interface:
Open your browser and navigate to:
http://localhost:8080
After starting the application:
- Navigate to Settings (http://localhost:8080/settings)
- Configure API Keys: Enter your OpenAI, Finnhub, and other API keys
- Add Trading Account: Configure your Alpaca or other broker credentials
- Create Expert Instance: Set up your first AI trading expert
- Configure Rulesets: Define your trading rules and risk parameters
The SQLite database is automatically created at:
~/Documents/ba2_trade_platform/db.sqlite
Logs are stored in:
ba2_trade_platform/logs/
Cache (ChromaDB, price data) is stored in:
~/Documents/ba2_trade_platform/cache/
BA2 Trade Platform can be easily run in Docker with persistent data storage. The Docker setup uses separate volumes for database and cache, allowing you to persist only what you need.
- Docker 20.10+
- Docker Compose 1.29+ (optional but recommended)
1. Clone the repository:
git clone https://github.com/bmigette/BA2TradePlatform.git
cd BA2TradePlatform2. Start the platform:
docker-compose up -dThis will:
- Build the Docker image from Dockerfile
- Create three named volumes (
ba2_db_volume,ba2_cache_volume,ba2_logs_volume) - Start the container with web interface on port 8000
- Automatically restart if the container stops
3. Access the web interface:
http://localhost:8000
4. View logs:
docker-compose logs -f5. Stop the platform:
docker-compose downThe docker-compose.yml file defines three independent volumes:
| Volume | Purpose | Path in Container |
|---|---|---|
ba2_db_volume |
Database persistence | /opt/ba2_trade_platform/db |
ba2_cache_volume |
Cache persistence | /opt/ba2_trade_platform/cache |
ba2_logs_volume |
Logs persistence | /opt/ba2_trade_platform/logs |
Persist Only Database (best for development):
volumes:
- ba2_db_volume:/opt/ba2_trade_platform/db
# Don't mount cache or logs - they'll be ephemeralPersist Only Cache (for stateless deployments):
volumes:
- ba2_cache_volume:/opt/ba2_trade_platform/cachePersist Everything (default in docker-compose.yml):
volumes:
- ba2_db_volume:/opt/ba2_trade_platform/db
- ba2_cache_volume:/opt/ba2_trade_platform/cache
- ba2_logs_volume:/opt/ba2_trade_platform/logs1. Build the image:
docker build -t ba2-trade-platform:latest .2. Create volumes (optional but recommended):
docker volume create ba2_db_volume
docker volume create ba2_cache_volume
docker volume create ba2_logs_volume3. Run the container:
docker run -d \
--name ba2-trade-platform \
-p 8000:8000 \
-v ba2_db_volume:/opt/ba2_trade_platform/db \
-v ba2_cache_volume:/opt/ba2_trade_platform/cache \
-v ba2_logs_volume:/opt/ba2_trade_platform/logs \
ba2-trade-platform:latest4. Access the web interface:
http://localhost:8000
Development Setup (persist only database):
docker run -d \
--name ba2-dev \
-p 8001:8000 \
-v ba2_dev_db:/opt/ba2_trade_platform/db \
ba2-trade-platform:latestProduction Setup (persist everything, custom port):
docker run -d \
--name ba2-prod \
-p 80:8000 \
--restart unless-stopped \
-v ba2_prod_db:/opt/ba2_trade_platform/db \
-v ba2_prod_cache:/opt/ba2_trade_platform/cache \
-v ba2_prod_logs:/opt/ba2_trade_platform/logs \
ba2-trade-platform:latestCustom Database Location (use host folder instead of volume):
mkdir -p /data/ba2-trade/db /data/ba2-trade/cache
chmod 755 /data/ba2-trade/*
docker run -d \
--name ba2-custom \
-p 8000:8000 \
-v /data/ba2-trade/db:/opt/ba2_trade_platform/db \
-v /data/ba2-trade/cache:/opt/ba2_trade_platform/cache \
ba2-trade-platform:latestList volumes:
docker volume ls | grep ba2Inspect a volume:
docker volume inspect ba2_db_volumeView volume data (Linux/macOS):
# Find where Docker stores volumes (Docker Desktop on macOS stores at ~/Library/Docker/volumes)
ls -la /var/lib/docker/volumes/ba2_db_volume/_data/Backup database:
docker cp ba2-trade-platform:/opt/ba2_trade_platform/db/db.sqlite ~/backup/db.sqliteBackup everything:
docker run --rm \
-v ba2_db_volume:/data/db \
-v ba2_cache_volume:/data/cache \
-v ba2_logs_volume:/data/logs \
-v ~/backup:/backup \
ubuntu tar czf /backup/ba2-backup-$(date +%Y%m%d).tar.gz /dataStop and remove container:
docker-compose down
# or
docker stop ba2-trade-platform
docker rm ba2-trade-platformRemove volumes (CAUTION - deletes data):
docker-compose down -v
# or
docker volume rm ba2_db_volume ba2_cache_volume ba2_logs_volumeRemove image:
docker rmi ba2-trade-platform:latestThe Dockerfile:
- Base Image:
python:3.11-slim(minimal footprint) - Multi-stage Build: Reduces final image size
- Non-root User: Runs as
traderuser for security - Working Directory:
/app - Exposed Port:
8000(web interface) - Entry Point: Automatically starts with proper volume paths
Default Paths in Container:
- Database:
/opt/ba2_trade_platform/db/db.sqlite - Cache:
/opt/ba2_trade_platform/cache - Logs:
/opt/ba2_trade_platform/logs
Port Already in Use:
# Change port in docker-compose.yml or use different port
docker run -p 9000:8000 ba2-trade-platform:latest
# Check what's using port 8000
lsof -i :8000 # Linux/macOS
netstat -ano | findstr :8000 # WindowsContainer Won't Start:
# View detailed logs
docker logs ba2-trade-platform
# Or with compose
docker-compose logs -f ba2-trade-platform
# Check container status
docker ps -a | grep ba2Data Persistence Issues:
# Verify volumes exist
docker volume ls | grep ba2
# Check volume data
docker volume inspect ba2_db_volume
# View volume contents
docker run --rm -v ba2_db_volume:/data ubuntu ls -la /dataPermission Denied Errors:
- Docker container runs as non-root user
trader(UID 1000) - If using host directories, ensure they have proper permissions:
mkdir -p /data/ba2-trade/{db,cache}
chmod 755 /data/ba2-trade
chown -R 1000:1000 /data/ba2-tradeOut of Disk Space:
# Clean up unused volumes and images
docker system prune -a --volumes
# View disk usage
docker system dfDatabase Corruption:
- Delete the database volume and start fresh:
docker-compose down -v # Removes all volumes
docker-compose up -d # Creates new volumes with fresh databaseVirtual Environment Issues:
- Always use the virtual environment Python executable (
.venv\Scripts\python.exeor.venv/bin/python) - Avoid using global
pythonorpipcommands
Dependency Installation Errors:
# With uv (recommended - much faster)
uv pip install -r requirements.txt
# Or with pip (upgrade first)
.venv\Scripts\python.exe -m pip install --upgrade pip
.venv\Scripts\python.exe -m pip install -r requirements.txtPort Already in Use:
- NiceGUI runs on port 8080 by default
- Check for other applications using this port
- Stop conflicting services or use
--portargument:
python main.py --port 9090Permission Errors:
- Ensure you have write permissions in
~/Documents/ - Run terminal/PowerShell with appropriate permissions
Abstract base class for trading account implementations:
class AccountInterface(ExtendableSettingsInterface):
def get_account_info(self) -> dict
def submit_order(self, order_data: dict) -> dict
def get_positions(self) -> List[dict]
def get_orders(self) -> List[dict]Abstract base class for AI trading experts:
class MarketExpertInterface(ExtendableSettingsInterface):
def get_prediction_for_instrument(self, symbol: str) -> dict
def get_analysis_for_instruments(self, symbols: List[str]) -> dictBase class providing flexible configuration:
@classmethod
def get_settings_definitions(cls) -> Dict[str, Any]:
return {
"setting_name": {
"type": "str",
"required": True,
"description": "Setting description"
}
}Core Models (in ba2_trade_platform/core/models.py):
AppSetting: Application-wide configuration (API keys, settings)AccountDefinition: Trading account provider configurationsAccountSetting: Account-specific settings (key-value storage)ExpertInstance: AI expert configurations with virtual equity allocation and rulesetsExpertSetting: Expert-specific settings (key-value storage)ExpertRecommendation: Trading recommendations with risk level, time horizon, and confidenceMarketAnalysis: Analysis sessions with status tracking and expert linkingAnalysisOutput: Detailed analysis outputs from individual agentsTradingOrder: Order lifecycle tracking (PENDING → OPEN → FILLED/CLOSED)Transaction: Transaction history for orders (fills, partial fills)Position: Current positions with P&L trackingInstrument: Instrument metadata (symbols, exchanges, asset classes)Ruleset: Rule-based trading logic containersEventAction: Conditional actions within rulesetsRulesetEventActionLink: Many-to-many relationship for rulesets and actionsTradeActionResult: Results from executed trade actions (BUY, SELL, CLOSE, etc.)
ba2_trade_platform/
├── core/ # Core interfaces and models
│ ├── AccountInterface.py # Account provider interface
│ ├── MarketExpertInterface.py # Expert interface
│ ├── ExtendableSettingsInterface.py # Settings management
│ ├── models.py # SQLModel database models
│ ├── types.py # Enums (OrderStatus, OrderDirection, RiskLevel, etc.)
│ ├── db.py # Database utilities (CRUD operations)
│ ├── utils.py # Helper functions
│ ├── actions.py # Trade action helpers
│ ├── TradeManager.py # Order processing and recommendation handling
│ ├── TradeActionEvaluator.py # Ruleset evaluation engine
│ ├── TradeActions.py # Trade action implementations (BUY, SELL, CLOSE)
│ ├── TradeConditions.py # Condition evaluation for rulesets
│ ├── TradeRiskManagement.py # Risk management and position sizing
│ ├── JobManager.py # Background job scheduling
│ ├── WorkerQueue.py # Task queue for parallel processing
│ ├── MarketAnalysisPDFExport.py # Export analysis to PDF reports
│ ├── rules_documentation.py # Ruleset documentation generator
│ └── rules_export_import.py # Import/export rulesets
├── modules/
│ ├── accounts/ # Account implementations
│ │ ├── __init__.py # Account registry
│ │ └── AlpacaAccount.py # Alpaca integration
│ ├── experts/ # Expert implementations
│ │ ├── __init__.py # Expert registry
│ │ └── TradingAgents.py # Multi-agent LLM expert
│ └── marketinfo/ # Market information providers
├── thirdparties/
│ └── TradingAgents/ # TradingAgents multi-agent framework
├── ui/ # NiceGUI web interface
│ ├── main.py # Route definitions and app initialization
│ ├── layout.py # Page layout components
│ ├── menus.py # Navigation menus
│ ├── svg.py # SVG icon utilities
│ ├── pages/ # Page components
│ │ ├── overview.py # Dashboard and account overview
│ │ ├── marketanalysis.py # Market analysis management
│ │ └── settings.py # Configuration interface
│ ├── components/ # Reusable UI components
│ │ └── InstrumentSelector.py # Instrument selection widget
│ └── static/ # Static assets (favicons, etc.)
├── logs/ # Application logs
├── config.py # Global configuration
└── logger.py # Centralized logging
The platform integrates the TradingAgents multi-agent framework for sophisticated market analysis:
- Market Analyst: Technical analysis and price patterns
- News Analyst: News sentiment and impact analysis
- Fundamentals Analyst: Company financials and metrics
- Social Media Analyst: Social sentiment analysis
- Macro Analyst: Economic indicators and macro trends
- Bull/Bear Researchers: Debate-based analysis
- Research Manager: Synthesis and final recommendations
- Data Collection: Multi-source data gathering
- Agent Analysis: Parallel analysis by specialized agents
- Debate Phase: Bull vs bear researcher arguments
- Synthesis: Research manager consolidation
- Risk Assessment: Multi-perspective risk analysis
- Final Recommendation: Trading decision with confidence levels
Access the settings page at http://localhost:8080/settings to configure:
- API Keys (OpenAI, Finnhub, FRED)
- Account Providers (Alpaca credentials)
- Expert Settings (TradingAgents parameters)
Modify ba2_trade_platform/config.py:
STDOUT_LOGGING = True # Console output
FILE_LOGGING = True # File logging with rotation📖 For detailed information about existing experts and their implementation patterns, see EXPERTS.md
- Create provider class:
from ba2_trade_platform.core.AccountInterface import AccountInterface
class MyBrokerAccount(AccountInterface):
@classmethod
def get_settings_definitions(cls):
return {
"api_key": {"type": "str", "required": True},
"paper_trading": {"type": "bool", "required": True}
}
def get_account_info(self):
# Implementation here
pass- Register in UI: The provider will automatically appear in the web interface
- Create expert class:
from ba2_trade_platform.core.MarketExpertInterface import MarketExpertInterface
class MyExpert(MarketExpertInterface):
@classmethod
def get_settings_definitions(cls):
return {
"model_type": {"type": "str", "required": True},
"confidence_threshold": {"type": "float", "required": True}
}
def get_prediction_for_instrument(self, symbol: str):
# Implementation here
passThe platform uses SQLModel for ORM with automatic SQLite database creation:
Key Tables:
appsetting: Application-wide configuration and API keysaccountdefinition: Trading account provider configurationsaccountsetting: Account-specific settings (key-value)expertinstance: AI expert configurations with rulesets and virtual equityexpertsetting: Expert-specific settings (key-value)expertrecommendation: Trading recommendations with risk/confidence metricsmarketanalysis: Analysis job tracking with status and timinganalysisoutput: Detailed outputs from individual analysis agentstradingorder: Order lifecycle and execution trackingtransaction: Transaction history for order fillsposition: Current positions with unrealized P&Linstrument: Instrument metadata and specificationsruleset: Rule-based trading logic containerseventaction: Conditional actions (triggers and actions)ruleseteventactionlink: Many-to-many relationship for rulesetstradeactionresult: Results from executed trade actions
Database Features:
- Automatic schema creation and migrations via Alembic
- SQLite backend with full ACID compliance
- Foreign key constraints for data integrity
- Indexed fields for query performance
Database auto-initializes at: ~/Documents/ba2_trade_platform/db.sqlite
Run all unit tests (pytest):
.venv\Scripts\python.exe -m pytest # Run all tests
.venv\Scripts\python.exe -m pytest -x # Stop on first failure
.venv\Scripts\python.exe -m pytest -k "test_name" # Run specific testTest configuration is in pytest.ini. Tests are located in the tests/ directory.
Legacy test scripts:
python test_trade_agents.py
python test.pyFile Locations:
- Main logs:
ba2_trade_platform/logs/app.log - Debug logs:
ba2_trade_platform/logs/app.debug.log - TradingAgents logs:
./tradeagents-exp{id}.log
Log Features:
- Automatic rotation (10MB max, 5 backups)
- Colored console output with icons
- Expert-specific log files
- Configurable log levels
Project Structure:
- Core interfaces in
ba2_trade_platform/core/ - Implementations in
ba2_trade_platform/modules/ - Web UI in
ba2_trade_platform/ui/ - Third-party integrations in
ba2_trade_platform/thirdparties/
Adding Dependencies:
# With uv (recommended)
uv pip install new_package
uv pip freeze > requirements.txt
# Or with pip
pip install new_package
pip freeze > requirements.txt- Configure API keys via Settings page at
/settings - Enable file logging: Set
FILE_LOGGING = Truein config.py - Run with production WSGI server (if needed)
- Set up proper database backup strategy
Common Issues:
-
Import Errors: Ensure all dependencies installed with
.venv\Scripts\python.exe -m pip install -r requirements.txt -
Database Issues: Database auto-creates on first run. Check permissions in
~/Documents/ -
API Key Issues: Configure keys via web interface at
/settings -
Unicode Console Errors: Logger automatically falls back to ASCII on Windows
-
ChromaDB Instance Conflicts: Fixed in latest version - each expert/symbol combination now gets isolated ChromaDB storage
-
AttributeError on TradingOrder: Ensure database schema is up-to-date. The
filled_avg_pricefield was removed in favor ofopen_price -
PyTorch DLL Error on Windows (
OSError: [WinError 1114]): The default PyTorch build may fail to load CUDA DLLs. Install the CPU-only build instead:pip install torch --index-url https://download.pytorch.org/whl/cpu
Do not blindly upgrade torch to the latest version (e.g. 2.10+) — pin to a known working version such as
torch==2.6.0+cpu.
Debug Mode:
ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG)- Fixed ChromaDB Instance Conflicts: ChromaDB path now includes symbol to prevent conflicts when same expert analyzes multiple symbols
- Database Schema Improvements: Added CASCADE foreign key constraints for proper cleanup when deleting accounts/experts
- Removed Redundant Fields: Cleaned up
TradingOrdermodel by removingfilled_avg_price(now usesopen_price) - Trade Action Fixes:
- Fixed Take Profit/Stop Loss calculation to use correct order direction (from recommendation vs. existing order)
- Fixed increase/decrease instrument share actions to properly extract target percentage
- Rule Evaluation Traceability: Added detailed tracking of trade action results linked to expert recommendations
- UI Enhancements: Added magnifying glass icons for viewing detailed rule evaluation results
- Async Price Loading: Overview widgets load price information asynchronously to prevent UI blocking
- Performance Analytics: New trade performance tab with comprehensive metrics:
- Average transaction time per expert
- Total and monthly profit analysis
- Sharpe ratio calculations
- Win/loss ratio tracking
- Average profit per transaction
- Reusable Chart Components: Modular chart components for consistent visualization across the platform
- Core Interfaces: See docstrings in
ba2_trade_platform/core/ - API Reference: Auto-generated from type hints
- Examples: Check
test_trade_agents.pyandtest.py
- Fork the repository
- Create feature branch:
git checkout -b feature-name - Make changes with proper tests
- Submit pull request
[Add your license information here]
Project that uses TradingAgents https://github.com/TauricResearch/TradingAgents
@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},
}
The live trader shares its core packages (editable installs) with the rest of the BA2 stack:
# from the live venv (.venv)
.venv/bin/pip install -e ../BA2TradeCommon -e ../BA2TradeProviders -e ../BA2TradeExperts
.venv/bin/pip install -r requirements.txt
.venv/bin/python main.py # serves the NiceGUI UI on :8080API keys (FMP, Finnhub, ...) live in the shared app-settings DB and are read by both the live trader and the backtester (BA2TestPlatform).
Nothing is cached inside the code repos. Shared cache/data lives under a single
root, BA2_HOME (env-overridable, default ~/Documents/ba2):
BA2_HOME (default ~/Documents/ba2)
├── common/ # SHARED with the backtester
│ ├── cache/ # raw provider cache: OHLCV parquet, as_of cache, fmp_history (CACHE_FOLDER)
│ ├── db.sqlite # shared app-settings / API-keys DB (FMP, Finnhub, ...) (DB_FILE)
│ └── options/ # options-history cache
└── trade/ # screener caches + your live trade instance DBs
└── screener/ # metric_store/ (parquet) + screener_history.sqlite
- The shared app-settings/keys DB (
ba2_common.config.DB_FILE, default~/Documents/ba2/common/db.sqlite) is read by both test + live. - A live trade instance DB is separate per run: point
--db-fileat a file undertrade/(e.g.python main.py --db-file ~/Documents/ba2/trade/dev.db).
Defined in ba2_common/config.py. BA2_HOME relocates the whole tree;
CACHE_FOLDER / DB_FILE still win when set explicitly (backward-compatible).
The old layout used ~/Documents/ba2_trade_platform. Migrate the shared
cache/DB with the script in BA2TestPlatform, then restart the live app so it
reads the relocated common/db.sqlite:
../BA2TestPlatform/backend/venv/bin/python ../BA2TestPlatform/scripts/migrate_cache_layout.py [--apply]