Autonomous stock trading with a safety-first architecture — scan, rank, plan, and execute trades automatically.
TWS Robot is an autonomous trading system that scans the S&P 500 universe, ranks candidates using technical analysis, builds trade plans, and executes them — all with multiple layers of safety gates. By default it runs in recommend-only mode so you can review every decision before any order is placed. Graduate to paper execution once you're confident in the pipeline.
TWS Robot is experimental open-source software for use with Interactive Brokers TWS / IB Gateway. It is provided as-is, without warranties. Trading involves substantial risk, including loss of capital. Use paper trading first. You are solely responsible for all trading decisions, orders, and losses. See DISCLAIMER.md.
TWS Robot's primary capability is its autonomous trading pipeline — a fully automated system that finds, evaluates, and executes trades without manual intervention.
┌──────────┬──────────┬──────────┬─────────────┬────────────────┐
│ Scanner │ Ranker │ Planner │ Engine │ Adapter │
│ │ │ │ (Gating) │ (Execution) │
│ S&P 500 │ Hard │ BUY_ │ Cash check │ Paper adapter │
│ universe │ filters │ SHARES │ Risk check │ Live adapter │
│ + │ Scoring │ or │ Daily limit │ (disabled by │
│ Signal │ Ranking │ SELL_ │ Emergency │ default) │
│ provider │ │ CSP │ stop gate │ │
└──────────┴──────────┴──────────┴─────────────┴────────────────┘
| Stage | What It Does |
|---|---|
| Scanner | Scans the S&P 500 universe using the TechnicalAnalysisSignalProvider to identify candidates with actionable signals. |
| Ranker | Applies hard filters (signal strength, volume, trend, earnings proximity, concentration limits), then scores and sorts survivors. |
| Planner | Builds a TradePlan — BUY_SHARES (limit order) by default. SELL_CASH_SECURED_PUT is supported but requires an option-chain hint provider and support-price data wired into the engine (not configured by default). |
| Engine | Validates against safety gates: emergency stop, daily trade limit, deployable cash, equity checks, and the optional RiskManager. |
| Adapter | In Paper Execute mode, sends the order to your IBKR paper account. In Recommend-Only mode, returns the plan without executing. |
| Mode | Orders Placed? | Description |
|---|---|---|
| Recommend Only (default) | ❌ Never | Runs the full pipeline and returns a trade plan for your review. Safe to run anytime. |
| Paper Execute | ✅ Paper only | Executes trades on your IBKR paper account. Requires active paper connection. |
| Assisted Live | ✅ Live (opt-in) | Live execution requires explicit config flag + caller confirmation. HTTP endpoints exist (/api/autonomous/live/*) but are disabled by default and not surfaced in the main dashboard UI. |
Multiple independent layers must all pass before any order is placed:
- Emergency Stop — A single
EMERGENCY_STOPfile halts the system instantly - Runner Gates — Connection verified, paper adapter ready, trade limits enforced
- Engine Validation — Deployable cash sufficient, position sizing within limits, risk manager approval
- Mode Gate — Recommend-Only never executes; Paper requires paper connection; Live requires explicit opt-in + confirmation
- Audit Trail — Every decision (including rejections) written to append-only JSONL log
The web dashboard provides a dedicated Autonomous Trading page where you can:
- Scan Universe — Run a full recommend-only pass and see ranked candidates with rejection reasons
- Propose Trade — Run the full pipeline and review the trade plan before execution
- Execute Paper Trade — Submit the proposed trade to your paper account
- Paper Robot Runner — Continuous autonomous trading loop (configurable interval)
- Exit Manager — Monitors open positions for take-profit, stop-loss, and max holding duration
- 🌐 Point-and-click interface for managing everything from your browser
- 📊 Real-time positions and P&L tracking
- 🧪 Backtesting — Test strategies on historical data before risking money
- 🛡️ Risk monitoring with emergency stop button always visible
- 📈 Performance tracking — Sharpe ratio, win rate, drawdown metrics
- 📊 Moving Average, Mean Reversion, and Momentum strategy templates
- ⚡ Paper trading validation with real-time data
- 🔧 Risk profiles: Conservative, Balanced, Aggressive
- 🏢 Company name display (supports international stocks: HK, JP, UK, AU, etc.)
- 📰 AI Market Outlook with session recap and actionable recommendations
- 🎯 AI Portfolio Intelligence — auto-detect strategies from positions (covered calls, spreads, iron condors)
- 🧠 Account Intelligence modules — health scoring, cash management, risk analysis, performance benchmarking
- 🏗️ Event-driven architecture with modular components
- 🧬 Extensible framework — build custom signal providers and strategies
- 📊 Comprehensive backtesting with realistic market simulation
- 🔧 Full control over risk profiles, position sizing, and execution logic
Prerequisites: For paper or live trading, you need Interactive Brokers TWS (or IB Gateway) running with API access enabled. Backtesting works without TWS. See the TWS Connection Guide for complete setup instructions.
# Clone and set up
git clone https://github.com/evanlow/tws_robot.git
cd tws_robot
# Create virtual environment
python -m venv venv
# Activate it (choose your platform)
.\venv\Scripts\Activate.ps1 # Windows PowerShell
source venv/bin/activate # Mac/Linux
# Install dependencies
pip install -r requirements.txtThe easiest way to use TWS Robot is through the web dashboard — no terminal expertise needed:
# Start the web dashboard
python scripts/run_web.py
# Then open your browser to: http://127.0.0.1:5000From the dashboard you can:
- 🤖 Autonomous Trading - Scan, propose, and execute trades automatically
- 📊 View positions and P&L on the Dashboard page
- 🧪 Run backtests from the Backtest page
- 🛡️ Monitor risk on the Risk page
- ⚙️ Configure settings on the Settings page
- 🚨 Emergency stop with one click from the top bar
🔐 Authentication: The dashboard requires login. Default credentials are
admin/changeme. See Authentication below to configure.
If you prefer working in a terminal:
New to algo trading? Start here:
# Interactive guide to choose a strategy for your stock
python scripts/strategy_selector.pyWant to see if a strategy works? Try this:
# Test Moving Average strategy on historical data
python scripts/quick_start.py💡 Note: Quick start examples use backtest strategies (Moving Average, Mean Reversion, Momentum) for historical testing. For live/paper trading, see the Bollinger Bands strategy in
strategies/folder.
Ready to explore? Check these out:
# Compare Conservative vs. Aggressive risk profiles
python examples/example_profile_comparison.py
# Test all three strategies (MA, Mean Reversion, Momentum)
python examples/example_strategy_templates.pygraph LR
A[🤖 Autonomous Scan] --> B[📊 Review Recommendations]
B --> C{Confident?}
C -->|No| D[🔧 Adjust Config]
D --> A
C -->|Yes| E[📄 Paper Execute]
E --> F{Proven Results?}
F -->|No| D
F -->|Yes| G[💰 Assisted Live]
style A fill:#e1f5ff
style B fill:#fff3cd
style E fill:#d4edda
style G fill:#f8d7da
Start in recommend-only mode. Review several cycles of recommendations before enabling paper execution.
📖 Read the User Guide - Everything you need to know to use TWS Robot effectively
- Understand what each strategy does and when to use it
- Learn about risk management and position sizing
- Get a realistic weekly trading routine
- Know when to stop trading a strategy
Understanding the codebase:
tws_robot/
├── autonomous/ # ⭐ Autonomous trading engine (core feature)
│ ├── autonomous_engine.py # Top-level orchestrator
│ ├── candidate_scanner.py # S&P 500 universe scanning
│ ├── candidate_ranker.py # Signal filtering and scoring
│ ├── trade_planner.py # Trade plan generation (shares/puts)
│ ├── signal_provider.py # Signal provider interface
│ ├── exit_manager.py # Automated exit management
│ ├── autonomous_runner.py # Paper trading runner loop
│ └── audit.py # JSONL audit logging
├── web/ # Web dashboard (user interface)
│ ├── routes/ # One Blueprint per menu section
│ ├── templates/ # Jinja2 HTML templates
│ └── static/ # CSS, JavaScript assets
├── backtest/ # Historical testing engine
│ ├── strategy_templates.py # Pre-built strategies (MA, MeanReversion, Momentum)
│ ├── engine.py # Backtesting engine
│ └── profiles.py # Risk profiles (Conservative, Moderate, Aggressive)
├── strategies/ # Live trading strategies
├── risk/ # Risk management system
│ ├── risk_manager.py # Position sizing, drawdown control
│ └── position_sizer.py # Calculate position sizes
├── core/ # Infrastructure
│ ├── event_bus.py # Event-driven architecture
│ └── ... # Other core components
├── execution/ # Order execution and TWS integration
├── monitoring/ # Performance tracking
├── scripts/ # Command-line utilities (run_web.py, quick_start.py, etc.)
├── examples/ # Self-contained demonstration scripts
└── docs/ # Documentation
🎯 Quick Navigation:
- Autonomous trading? →
autonomous/autonomous_engine.pyor web dashboard Autonomous Trading page - Want to use the dashboard? →
python scripts/run_web.pythen open http://127.0.0.1:5000 - Want to backtest? →
backtest/strategy_templates.py - Need risk controls? →
risk/risk_manager.py - Building custom signal provider? →
autonomous/signal_provider.py
The autonomous trading engine supports paper execution out of the box — it will scan, rank, plan, and execute trades on your IBKR paper account. Live execution (assisted_live mode) has HTTP endpoints (/api/autonomous/live/*) and a live runner, but is intentionally disabled by default and not surfaced in the main dashboard UI. Start with recommend-only mode, graduate to paper, and paper trade for at least 30 days before considering live.
- Autonomous trading? Open the web dashboard → Autonomous Trading page → click "Scan Universe" to see what the system recommends
- Manual backtesting? Run
python scripts/strategy_selector.pyfor guided selection - Want to compare? Backtest all strategies:
python examples/example_strategy_templates.py
- For backtesting: No, works offline with historical data
- For paper trading: Yes, need TWS Paper Trading mode (port 7497)
- For live trading: Yes, need TWS with live account (port 7496)
- Setup guide: See the TWS Connection Guide for step-by-step instructions
- Backtesting: $0 (simulated)
- Paper trading: $0 (simulated TWS account)
- Live trading: Minimum $10,000 recommended for proper diversification
Absolutely! TWS Robot includes a web dashboard that you can access in your browser — no terminal experience required.
Backtesting: Yes! The web dashboard lets you run backtests with a few clicks
Live trading: Intermediate+ (requires understanding of trading, risk management, TWS setup)
- Check you're in the project directory and venv is activated
- Verify dependencies installed:
pip install -r requirements.txt - For TWS connection issues, see Troubleshooting below
- See Debugging Guide for detailed help
# Ensure you're in the project directory
cd tws_robot
# Activate virtual environment
.\venv\Scripts\Activate.ps1 # Windows
source venv/bin/activate # Mac/Linux
# Install dependencies
pip install -r requirements.txt- Ensure TWS or IB Gateway is running
- Check TWS API settings enabled: Edit → Global Configuration → API → Settings
- Enable ActiveX and Socket Clients
- Trusted IP addresses: 127.0.0.1
- Paper trading uses port 7497, live uses port 7496
# Download historical data first
python scripts/download_real_data.py AAPL MSFT GOOGL# Clear test cache and rerun
pytest --cache-clear
# Run specific test file
pytest test_backtest_engine.py -vMore help:
Getting Started:
- ⭐ Your First 30 Minutes - Complete beginner tutorial
- README - Quick start and overview (you are here)
- User Guide - Learn strategies and workflows
- Autonomous Trading (USER_GUIDE §11) - Full autonomous pipeline documentation
- Examples Guide - Working code examples
- Quick Reference - Commands and configs cheat sheet
Development:
- API Reference - Complete developer API documentation
- Web API Reference - REST API for web dashboard
- Contributing Guide - How to contribute
- Technical Specs - Architecture details
- Architecture Docs - System design
- Adding New Strategy - Development guide
- Prime Directive - Development philosophy
Operations:
- Deployment Guide - Production setup
- Local Deployment - Local development setup
- Emergency Procedures - Crisis management
- Debugging Guide - Troubleshooting
Test Environment: Windows 11, Python 3.12.10, 2500+ tests passing
| Strategy | Symbol | Total Return | Sharpe Ratio | Max Drawdown | Win Rate |
|---|---|---|---|---|---|
| Moving Average | AAPL | +18.7% | 1.52 | -8.1% | 56.7% |
| Mean Reversion | KO | +12.3% | 1.38 | -6.5% | 62.1% |
| Momentum | NVDA | +31.2% | 1.71 | -12.3% | 51.3% |
Benchmark: S&P 500 buy-and-hold returned +15.2% over same period.
- Backtest Speed: 2 years of daily data processed in ~8 seconds
- Data Processing: 500+ bars/second
- Test Suite: All 2500+ tests complete in ~140 seconds
- Memory Usage: ~500MB for typical backtest
- Order Execution: < 100ms latency to TWS (paper/live)
- Position Sizing: Dynamic based on volatility and account equity
- Risk Per Trade: 1-2% of account by default
- Correlation Analysis: Multi-asset portfolio risk checking
- Emergency Stop: Automatic portfolio halt at -5% daily loss
Note: Past performance does not guarantee future results. All figures are from backtests on historical data.
- Understand the scan → rank → plan → execute pipeline
- Run in recommend-only mode and review trade proposals
- Read the audit log to understand why candidates were selected or rejected
- Connect to Interactive Brokers paper account
- Enable paper execute mode and run autonomous cycles
- Use the Paper Robot Runner for continuous operation
- Monitor the Exit Manager handling take-profit and stop-loss
- Set position sizes based on account size
- Configure daily trade limits and max open positions
- Use the emergency stop mechanism
- Understand the multi-layer safety architecture
- Build custom signal providers
- Configure symbol whitelists/blacklists
- Tune ranker scoring parameters
- Review and adjust trade planner settings
Full learning path in USER_GUIDE.md
Primary: Autonomous Trading Pipeline — The autonomous engine uses the TechnicalAnalysisSignalProvider to scan the S&P 500 and automatically identify, rank, and execute trades. This is the recommended way to trade with TWS Robot.
Backtesting strategies (for historical analysis only):
| Strategy | Best For | When to Use | Example Stocks |
|---|---|---|---|
| Moving Average Crossover | Trending markets | Stock has clear up/down movements | AAPL, MSFT, NVDA |
| Mean Reversion | Range-bound markets | Stock bounces around stable average | KO, PG, JNJ |
| Momentum | High-growth stocks | Stock shows strong trends | TSLA, growth stocks |
Note: The backtest strategies above are for historical testing and learning. For automated trading, use the Autonomous Trading pipeline.
- ✅ Paper trading first - Test with fake money before risking real capital
- ✅ Position limits - Never risk more than configured percentage per trade
- ✅ Circuit breakers - Auto-shutdown on excessive losses (2% daily, 15% total)
- ✅ Market hours checks - Warns about after-hours trading
- ✅ Confirmation prompts - Extra confirmation for live trading
Choose your comfort level:
- Conservative - 2-3% per trade, tight stops, retirement accounts
- Balanced - 5% per trade, moderate stops, active traders
- Aggressive - 10% per trade, wide stops, experienced traders
Autonomous trading pipeline:
- S&P 500 universe scanning with technical analysis signals
- Multi-factor candidate ranking with hard filters
- Automatic trade plan generation (shares or cash-secured puts)
- Paper Robot Runner for continuous autonomous execution
- Exit Manager with take-profit, stop-loss, and max holding duration
- Full audit trail of every decision in JSONL format
Professional-grade backtesting:
- Realistic market simulation with slippage and commissions
- Performance analytics (Sharpe, Sortino, Calmar ratios)
- Trade-by-trade analysis and visualization
Web dashboard (built-in):
- Autonomous Trading page with scan, propose, and execute controls
- Real-time position and P&L tracking
- Backtest execution from the browser
- Risk monitoring and emergency stop
Start Here: Your complete guide to TWS Robot documentation.
| Guide | When to Use | What You'll Learn |
|---|---|---|
| Web Dashboard | Right now! | Launch python scripts/run_web.py and open http://127.0.0.1:5000 |
| USER_GUIDE.md | Your first 30 minutes | Complete walkthrough: strategies, risk management, weekly routine, realistic expectations |
| QUICK_REFERENCE.md | Daily commands | Cheat sheet: common commands, quick metrics guide, emergency procedures |
| Quick Start Script | From the terminal | Run your first backtest in 5 minutes |
| Guide | When to Use | What You'll Learn |
|---|---|---|
| EXAMPLES_GUIDE.md | Before running any example | What each example script does, expected output, common issues |
| PROJECT_PLAN.md | Understanding architecture | System design, component overview, development guidelines |
| Guide | When to Use | What You'll Learn |
|---|---|---|
| Autonomous Trading (USER_GUIDE §11) | Using autonomous mode | Pipeline, safety gates, operating modes, dashboard controls |
| Web Dashboard | Every trading session | Real-time positions, P&L, strategy status, risk monitoring |
| check_account.py | Terminal account check | Current account status, positions, P&L, margin health |
| market_status.py | Before placing trades | Is the market open? Safe to trade? |
| Guide | When to Use | What You'll Learn |
|---|---|---|
| prime_directive.md | Before coding anything | Development standards, testing requirements, code quality rules |
| TECHNICAL_SPECS.md | Building features | API references, class structures, integration patterns |
| docs/ | Deep dives | Architecture details, runbooks, troubleshooting guides |
| Guide | When to Use | What You'll Learn |
|---|---|---|
| Metrics in USER_GUIDE | After every backtest | What Sharpe ratio, drawdown, win rate mean |
| Risk Management in USER_GUIDE | Setting up strategies | Position sizing, stop losses, circuit breakers |
| Guide | When to Use | What You'll Find |
|---|---|---|
| QUICK_REFERENCE.md | Quick fixes | Common errors and fast solutions |
| Emergency Procedures | System acting weird | How to stop everything NOW |
| docs/runbooks/debugging-strategies.md | Strategy not working | Step-by-step debugging process |
If you're brand new:
- This README (you are here!) → Get the big picture
- USER_GUIDE.md → Learn strategies and risk management
- QUICK_REFERENCE.md → Bookmark for daily use
- EXAMPLES_GUIDE.md → Before running examples
If you want to trade today:
- Web Dashboard → Run
python scripts/run_web.pyand open http://127.0.0.1:5000 - Autonomous Trading page → Click "Scan Universe" to see recommendations
- USER_GUIDE §11 → Full autonomous trading documentation
- QUICK_REFERENCE.md → Commands you need
If you're a developer:
- prime_directive.md → MUST READ before coding
- PROJECT_PLAN.md → Understand architecture
- TECHNICAL_SPECS.md → API references
- docs/ → Deep technical docs
- ✅ Good strategy: 10-20% annual return
- ✅ Great strategy: 20-30% annual return
- ❌ Claiming 50%+: Probably too risky or unrealistic
Remember: S&P 500 averages ~10% per year. Beating that consistently is success!
- ALWAYS backtest first - If it didn't work historically, it won't work now
- ALWAYS paper trade 30+ days - Prove it works in real-time
- NEVER risk more than 1-2% per trade - Survive being wrong 20+ times
- NEVER set-and-forget - Check your system daily
- STOP if strategy fails - 5+ consecutive losses or 10% drawdown = stop and reassess
Web dashboard for easy management:
- Launch with
python scripts/run_web.pyand access at http://127.0.0.1:5000 - Manage strategies, run backtests, and monitor risk from your browser
- Connect/disconnect from TWS directly via the Settings page
- Emergency stop button always visible in the top bar
Supports both paper and live trading:
- Configuration via
.envfiles for security - Easy switching between environments
- Separate settings for paper/live accounts
Market Status Integration:
- Real-time US stock market status checking
- Automatic warnings for after-hours trading
- Safety prompts for live trading during market closures
TWS Integration:
- Real-time market data streaming
- Historical data collection
- Account balance and portfolio monitoring
- Order execution capabilities
- Interactive Brokers Account - Paper or live trading account (only needed for paper/live trading, not for backtesting)
- TWS or IB Gateway - Download from Interactive Brokers website (only needed for paper/live trading)
- Python 3.8+ - With pip package manager
1. Clone the repository:
git clone https://github.com/evanlow/tws_robot.git
cd tws_robot2. Create virtual environment:
python -m venv venv3. Activate virtual environment:
# Windows PowerShell
.\venv\Scripts\Activate.ps1
# macOS/Linux
source venv/bin/activate4. Install dependencies:
pip install -r requirements.txt5. Configure your account:
cp .env.example .env
# Edit .env with your Interactive Brokers detailsEnable API Access in TWS:
- Open TWS or IB Gateway
- Go to: File → Global Configuration → API → Settings
- Enable "Enable ActiveX and Socket Clients"
- Set Socket Port:
- Paper trading:
7497 - Live trading:
7496
- Paper trading:
- Add
127.0.0.1to trusted IPs if prompted
# Start the web dashboard
python scripts/run_web.py
# Open in your browser: http://127.0.0.1:5000
# Optional: specify host/port
python scripts/run_web.py --host 0.0.0.0 --port 8080 --debugFrom the web dashboard you can manage everything visually:
- Autonomous Trading — Scan universe, propose trades, execute on paper, run continuous robot
- Dashboard — Connection status, equity, P&L at a glance
- Backtest — Run backtests and review results
- Positions — View open positions and trade history
- Risk — Monitor risk levels and circuit breaker status
- Logs — Browse application logs in real time
- Settings — Configure TWS connection and trading parameters
# Interactive guide for first-time users
python scripts/quick_start.py
# Find the right strategy for your stock
python scripts/strategy_selector.py
# Compare risk profiles (Conservative vs. Aggressive)
python examples/example_profile_comparison.py
# Test all three strategies on historical data
python examples/example_strategy_templates.py# Start paper trading with default settings
python tws_client.py --env paper --timeout 30
# Show current configuration
python tws_client.py --show-config
# Skip market status check (for after-hours testing)
python tws_client.py --env paper --skip-market-check# Live trading requires explicit confirmation
python tws_client.py --env live --timeout 60
# Check market status before trading
python scripts/market_status.py| Option | Description |
|---|---|
--env, -e |
Trading environment: paper or live |
--timeout, -t |
Set timeout in seconds (default: no timeout) |
--show-config |
Display current configuration and exit |
--skip-market-check |
Skip market status verification |
--no-timeout |
Run without timeout |
--help, -h |
Show help message |
Total Return
- Your profit/loss percentage over the test period
- Compare to S&P 500 (~10% annually) as benchmark
Sharpe Ratio (Risk-adjusted return)
> 2.0= Excellent> 1.0= Good> 0.5= Fair< 0.5= Poor (too much risk)
Max Drawdown (Worst loss from peak)
< 10%= Low risk10-20%= Moderate risk> 20%= High risk (be careful!)
Win Rate (Percentage of winning trades)
> 60%= Great> 50%= Good (more wins than losses)< 40%= Concerning (review strategy)
tws_robot/
├── autonomous/ # ⭐ Autonomous trading engine (core feature)
│ ├── autonomous_engine.py # Top-level pipeline orchestrator
│ ├── candidate_scanner.py # S&P 500 universe scanning
│ ├── candidate_ranker.py # Hard filters + scoring
│ ├── trade_planner.py # BUY_SHARES / SELL_CSP planning
│ ├── signal_provider.py # Signal provider interface
│ ├── exit_manager.py # TP/SL/duration exit logic
│ ├── autonomous_runner.py # Paper runner loop
│ └── audit.py # JSONL decision audit log
├── web/ # Flask web UI (user interface)
│ ├── app.py # Application entry point
│ ├── routes/ # One Blueprint per menu section
│ ├── templates/ # Jinja2 HTML templates
│ └── static/ # CSS, JavaScript assets
├── backtest/ # Backtesting engine, data manager, analytics, profiles
├── config/ # Environment & broker configuration
│ ├── env_config.py # Loads & validates .env at runtime
│ ├── paper.py # Paper trading defaults (port 7497)
│ └── live.py # Live trading defaults (port 7496)
├── core/ # Event bus, TWS connection, order management
├── data/ # SQLite databases, data models, real-time pipeline
├── deployment_scripts/ # Startup / backup scripts
├── docs/ # All project documentation
│ ├── architecture/ # System design overviews
│ ├── decisions/ # Architectural decision records (ADRs)
│ ├── runbooks/ # Operational runbooks
│ └── sprints/ # Sprint & week-by-week progress logs
├── examples/ # Self-contained demonstration scripts
├── execution/ # Order executor, market data feed, paper adapter
├── ibapi/ # Interactive Brokers Python API (vendored)
├── monitoring/ # Paper trading monitor, validation monitor
├── reports/ # Generated backtest chart images
├── risk/ # Risk manager, position sizer, drawdown control
├── scripts/ # Command-line utilities and entry points
│ ├── run_web.py # Start the Flask web UI
│ ├── quick_start.py # Your first backtest (5 min)
│ ├── run_live.py # Launch paper / live trading session
│ ├── check_account.py # Account balance, positions, P&L
│ ├── market_status.py # Is the US market open?
│ └── ...
├── strategies/ # Live-trading strategies, configs
├── strategy/ # Strategy lifecycle, metrics, promotion, validation
├── tests/ # Full test suite (mirrors source structure)
├── .env.example # Configuration template
├── prime_directive.md # Development standards & safety rules
├── pytest.ini # Test discovery & coverage config
├── requirements.txt # Python dependencies
├── README.md # This file
└── tws_robot_spec.md # Full application specification
- Never commit
.envfile - Contains sensitive account information - Use paper trading first - Test strategies before going live
- Monitor live trades - Always supervise automated trading
- Market hours awareness - System warns about after-hours trading
The web dashboard is protected by login authentication. All routes (pages and APIs) require a valid session. CSRF protection is enabled for all state-changing requests, including cookie-authenticated API calls.
| Setting | Default |
|---|---|
| Username | admin |
| Password | must be configured |
TWS_ADMIN_PASSWORD or TWS_ADMIN_PASSWORD_HASH. The insecure changeme fallback is only allowed when TESTING, DEBUG, or ALLOW_DEFAULT_PASSWORD=true is enabled.
Set credentials in your .env file:
TWS_ADMIN_USERNAME=admin
TWS_ADMIN_PASSWORD=your-secure-passwordFor local-only development on 127.0.0.1, you can disable authentication:
LOGIN_DISABLED=true- Session-based auth using Flask-Login with secure cookies.
- CSRF protection via Flask-WTF on all POST/PUT/DELETE requests, including
/api/*; the web client sends the token in anX-CSRFTokenheader for JavaScript requests. - API routes return
401 JSONresponses when unauthenticated. - Page routes redirect to the login page when the session is missing or expired.
- Start TWS or IB Gateway
- Enable API connections:
- File → Global Configuration → API → Settings
- Enable "Enable ActiveX and Socket Clients"
- Set Socket Port: 7497 (paper) or 7496 (live)
- Add trusted IPs: Add
127.0.0.1if needed
Common TWS error codes you might see:
- 2104: Market data farm connection OK (informational)
- 2106: HMDS data farm connection OK (informational)
- 2158: Security definition data farm connection OK (informational)
- 2108: Unable to subscribe to market data (normal during off-hours)
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is for educational purposes only. Please ensure you understand the risks of automated trading and comply with all applicable regulations.
- Automated trading involves substantial risk of loss
- Past performance does not guarantee future results
- Only trade with money you can afford to lose
- Always test strategies in paper trading first
- Monitor your automated systems at all times
The authors are not responsible for any financial losses incurred through the use of this software.
"How much money can I make?"
- Realistic: 10-30% annually with good strategies
- Anything claiming 50%+ is likely too risky
- Goal: Beat S&P 500's ~10% average consistently
"Which strategy should I use?"
- Start with Moving Average Crossover (simplest)
- Run
python scripts/strategy_selector.pyfor personalized recommendations - Test multiple strategies to find what works for you
"How much money do I need?"
- Paper trading: $0 (fake money)
- Live trading: $5,000-$10,000 minimum recommended
- Need enough to diversify and cover commissions
"What if my strategy stops working?"
- Normal! Markets change and strategies fail
- Stop trading if: 2 months of losses, 10% drawdown, or 5+ consecutive losses
- Re-test on recent data and adjust or switch strategies
📖 Read First:
- USER_GUIDE.md - Complete trader's guide
- Technical Docs - Architecture and API reference
- Runbooks - Common tasks and troubleshooting
🐛 Found a Bug?
- Check existing Issues
- Create new issue with:
- What you were trying to do
- What happened vs. what you expected
- Error messages and logs
- Your configuration (hide sensitive data!)
💡 Have a Suggestion? We love feature requests! Open an issue with the "enhancement" label.
- Launch the web dashboard:
python scripts/run_web.py - Run
python scripts/quick_start.pyfor your first backtest - Test strategies with
python examples/example_strategy_templates.py - Use
python scripts/strategy_selector.pyto find your strategy - Read USER_GUIDE.md completely
- Connect to IB paper account
- Run chosen strategy for 30 days minimum
- Track daily performance
- Verify risk controls work correctly
- Did you beat buy-and-hold?
- Is Sharpe ratio > 1.0?
- Is max drawdown acceptable?
- Ready to go live? Start small!
- Start with 25% of intended capital
- Use 1% position sizes initially
- Monitor daily for first month
- Scale up gradually if successful
Remember: Most traders fail. Go slow, test thoroughly, and never risk money you can't afford to lose.
Happy Trading! 📈