- Real-time data fetching from Polygon.io
- Advanced trading strategy with multiple indicators
- IBKR integration for live trading
- Terminal monitoring with 60-second updates
- macOS compatibility
- 5-minute TSLA data processing
- Comprehensive error handling
- Risk management systems
| File | Purpose |
|---|---|
tsla_trading_bot.py |
Main bot application |
live_data_fetcher.py |
Polygon.io data integration |
live_strategy_engine.py |
Trading strategy logic |
ibkr_interface.py |
Interactive Brokers API |
terminal_monitor.py |
Real-time terminal display |
requirements.txt |
Python dependencies |
setup.py |
Package installation |
test_setup.py |
Setup validation |
quick_start.sh |
Automated setup script |
.env.example |
Environment variables template |
README.md |
Complete documentation |
# Clone the repository
git clone <your-repo-url>
cd tsla-trading-bot
# Run automated setup
./quick_start.sh# Edit environment file
nano .env
# Add your Polygon API key
POLYGON_API_KEY=JlAQap9qJ8F8VrfChiPmYpticVo6SMPO# Activate environment
source venv/bin/activate
# Run the bot
python tsla_trading_bot.py# Create virtual environment
python3 -m venv venv
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt# Copy template
cp .env.example .env
# Edit with your values
nano .env# Validate configuration
python test_setup.py
# Test terminal display
python terminal_monitor.pyThe bot displays real-time information every 60 seconds:
================================================================================
TSLA TRADING BOT - LIVE MONITOR
================================================================================
Last Update: 2024-01-15 14:30:15 EST
BOT STATUS
--------------------
Status: RUNNING
Update Interval: 60 seconds
Next Update: 14:31:15
MARKET CONDITIONS
------------------------------
TSLA Price: $215.50
Market: OPEN
Trend: Strong
Volatility: Normal
Momentum: Bullish
RSI: 65.5
ADX: 28.3
POSITION STATUS
-------------------------
Position: LONG
Quantity: 3 shares
Entry Price: $210.00
Current Price: $215.50
Unrealized P&L: $16.50
Stop Loss: $205.00
Take Profit: $220.00
PERFORMANCE STATISTICS
-----------------------------------
Total Trades: 5
Win Rate: 60.0%
Total P&L: $125.50
Current Streak: 2
- Position Size: 3 shares per trade (configurable)
- Risk Management: ATR-based stops and targets
- Daily Limits: Max trades and loss limits
- Strategy: Multi-indicator confirmation system
- Paper Trading Mode: Test without real money
- Emergency Stops: Global account protection
- Real-time Monitoring: Continuous status updates
- Comprehensive Logging: Full audit trail
- Position Limits: Maximum 3 shares per trade
- Daily Limits: Configurable trade and loss limits
- Stop Losses: Automatic risk management
- Emergency Stops: Account-level protection
- Paper Trading: Safe testing environment
ENABLE_TRADING=true # Live trading always enabled
MAX_POSITION_SIZE=3 # Small position size
MAX_DAILY_TRADES=3 # Conservative trade limit
MAX_DAILY_LOSS=200.0 # Reasonable loss limit-
"Connection refused" to IBKR
# Check TWS is running ps aux | grep tws # Verify API settings in TWS # File β Global Configuration β API β Settings
-
"Invalid API key" for Polygon
# Test API key curl "https://api.polygon.io/v2/last/trade/TSLA?apikey=YOUR_KEY"
-
Import errors
# Reinstall dependencies pip install -r requirements.txt --force-reinstall -
macOS permission issues
# Fix Python permissions sudo xcode-select --install
- Win Rate: Percentage of profitable trades
- Average P&L: Per-trade performance
- Maximum Drawdown: Risk assessment
- Sharpe Ratio: Risk-adjusted returns
- Trade Frequency: Activity level
tsla_bot.log: Main application logsession_data_*.json: Trading session data- Terminal output: Real-time status
- Start with paper trading to test the system
- Never risk more than you can afford to lose
- Monitor the bot actively during market hours
- Understand the strategy before using real money
- Requires stable internet connection
- Dependent on Polygon.io and IBKR uptime
- Strategy performance varies with market conditions
- Past performance doesn't guarantee future results
- Setup Issues: Run
python test_setup.py - Strategy Questions: Review
live_strategy_engine.py - IBKR Problems: Check TWS/Gateway status
- Data Issues: Verify Polygon.io subscription
- IBKR API Documentation: interactivebrokers.github.io
- Polygon.io Docs: polygon.io/docs
- Python Trading: python-trading.com
A sophisticated real-time trading bot for Tesla (TSLA) stock using Interactive Brokers (IBKR) with live data from Polygon.io. Features advanced technical analysis, risk management, and real-time terminal monitoring.
- Real-time Data: Live 5-minute OHLCV data from Polygon.io
- Advanced Strategy: Multi-timeframe technical analysis with UT Bot, ADX, RSI, MACD, and Bollinger Bands
- IBKR Integration: Direct trading through Interactive Brokers API
- Terminal Monitoring: Real-time status updates every 60 seconds with colored output
- Risk Management: Stop losses, take profits, position sizing, and daily limits
- macOS Compatible: Optimized for macOS development environment
- Paper Trading: Built-in simulation mode for testing
-
Polygon.io Account: For real-time market data
- Sign up at polygon.io
- Get your API key from the dashboard
-
Interactive Brokers Account: For trade execution
- Open account at Interactive Brokers
- Download and install TWS (Trader Workstation) or IB Gateway
- Enable API trading in TWS settings
-
Python 3.8+: Required for running the bot
- Install from python.org or use Homebrew on macOS
# Install Python via Homebrew (recommended)
brew install python
# Install Git if not already installed
brew install gitgit clone https://github.com/yourusername/tsla-trading-bot.git
cd tsla-trading-bot# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate # macOS/Linux# Install required packages
pip install -r requirements.txt
# Install IBKR API (if not included in requirements)
pip install ibapiCreate a .env file in the project root:
# Copy the example environment file
cp .env.example .env
# Edit with your actual values
nano .envAdd your API keys and settings:
# Polygon.io API Key (Required)
POLYGON_API_KEY=JlAQap9qJ8F8VrfChiPmYpticVo6SMPO
# IBKR Settings
IBKR_HOST=127.0.0.1
IBKR_PORT=7496 # 7496 for live trading, 7497 for paper trading
IBKR_CLIENT_ID=1
# Trading Settings
ENABLE_TRADING=true # Live trading cannot be disabled
MAX_POSITION_SIZE=3
MAX_DAILY_TRADES=5
MAX_DAILY_LOSS=500.0
# Monitoring
UPDATE_INTERVAL=60
LOG_LEVEL=INFO
# CSV logging
LOG_DIR=./logs
LOG_PREFIX=tsla_bot
SESSION_ID=-
Start TWS or IB Gateway:
# TWS is usually installed in Applications on macOS open "/Applications/Trader Workstation.app"
-
Configure API Settings:
- In TWS: File β Global Configuration β API β Settings
- Enable "Enable ActiveX and Socket Clients"
- Add "127.0.0.1" to trusted IPs
- Set Socket port to 7496 (live) or 7497 (paper)
-
Login to Paper Trading Account (recommended for testing)
# Test data connection
python test_data_connection.py
# Test IBKR connection
python test_ibkr_connection.py
# Test terminal monitor
python test_terminal_monitor.py# Start the trading bot
python tsla_trading_bot.pyThe bot will display a real-time terminal interface with:
- Current market conditions
- Position status
- Performance statistics
- Recent signals and trades
- Alerts and warnings
The bot provides a comprehensive terminal interface that updates every 60 seconds:
================================================================================
TSLA TRADING BOT - LIVE MONITOR
================================================================================
Last Update: 2024-01-15 14:30:15 EST
BOT STATUS
--------------------
Status: RUNNING
Update Interval: 60 seconds
Next Update: 14:31:15
MARKET CONDITIONS
------------------------------
TSLA Price: $215.50
Market: OPEN
Trend: Strong
Volatility: Normal
Momentum: Bullish
RSI: 65.5
ADX: 28.3
POSITION STATUS
-------------------------
Position: LONG
Quantity: 3 shares
Entry Price: $210.00
Current Price: $215.50
Unrealized P&L: $16.50
Stop Loss: $205.00
Take Profit: $220.00
Time in Trade: 15 bars
PERFORMANCE STATISTICS
-----------------------------------
Total Trades: 5
Win Rate: 60.0%
Winning Trades: 3
Losing Trades: 2
Total P&L: $125.50
Avg Win: $75.25
Avg Loss: $-37.50
Current Streak: 2
Max Win Streak: 3
Max Loss Streak: 1
RECENT ACTIVITY
-------------------------
Recent Signals:
14:25:30 - BUY: Pullback + UT Bot signal
13:45:15 - SELL: Stop Loss
12:30:45 - BUY: Breakout signal
Recent Trades:
14:25:30 - BUY 10 @ $210.00 | P&L: $0.00
13:45:15 - SELL 10 @ $208.50 | P&L: $-15.00
12:30:45 - BUY 10 @ $207.00 | P&L: $0.00
================================================================================
Controls: Ctrl+C to stop | Bot will update every 60 seconds
================================================================================
The bot uses a sophisticated multi-indicator strategy. Key parameters can be adjusted in live_strategy_engine.py:
@dataclass
class StrategyParams:
# Position sizing
shares_per_trade: int = 3
max_position_size: int = 3
# Risk management
stop_atr: float = 1.0 # Stop loss in ATR multiples
tp1_atr: float = 1.5 # Take profit in ATR multiples
tp1_qty_pct: int = 50 # Partial profit percentage
# Entry filters
adx_min: float = 15.0 # Minimum trend strength
atr_min_pct: float = 0.0005 # Minimum volatility
rsi_threshold: float = 30 # RSI threshold for entries
# Indicator periods
atr_len: int = 14
adx_len: int = 14
rsi_len: int = 14Built-in risk management features:
- Position Sizing: Fixed 3 shares per trade (configurable)
- Stop Losses: ATR-based dynamic stops
- Take Profits: Partial profit taking with trailing stops
- Daily Limits: Maximum trades and loss limits per day
- Emergency Stop: Global stop loss for account protection
The bot now always runs in live trading mode and forces ENABLE_TRADING=true:
python tsla_trading_bot.py# Run all tests
python -m pytest tests/
# Run specific test
python test_strategy_engine.py
# Test with coverage
python -m pytest --cov=. tests/Enable debug logging:
# Set in .env file
LOG_LEVEL=DEBUG
# Or run with debug flag
python tsla_trading_bot.py --debugtsla-trading-bot/
βββ README.md # This file
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
βββ .gitignore # Git ignore file
βββ setup.py # Package setup
βββ tsla_trading_bot.py # Main bot application
βββ live_data_fetcher.py # Polygon.io data integration
βββ live_strategy_engine.py # Trading strategy logic
βββ ibkr_interface.py # Interactive Brokers API
βββ terminal_monitor.py # Real-time terminal display
βββ tests/ # Test files
β βββ test_data_fetcher.py
β βββ test_strategy.py
β βββ test_ibkr.py
βββ docs/ # Documentation
β βββ strategy_guide.md
β βββ api_reference.md
β βββ troubleshooting.md
βββ logs/ # Log files (created at runtime)
-
"Connection refused" to IBKR:
- Ensure TWS/Gateway is running
- Check API settings are enabled
- Verify port number (7496 for live, 7497 for paper)
-
"Invalid API key" for Polygon:
- Verify your API key is correct
- Check your Polygon.io subscription status
- Ensure you have real-time data access
-
"No data available":
- Check market hours (9:30 AM - 4:00 PM ET)
- Verify internet connection
- Check Polygon.io API status
-
macOS Permission Issues:
# Fix Python permissions sudo xcode-select --install # Reinstall Python packages pip uninstall -r requirements.txt pip install -r requirements.txt
Check log files for detailed error information:
# View recent logs
tail -f tsla_bot.log
# Search for errors
grep ERROR tsla_bot.log
# View specific date
grep "2024-01-15" tsla_bot.log- Start with paper trading to test the system
- Never risk more than you can afford to lose
- Understand the strategy before using real money
- Monitor the bot actively during trading hours
- Have a backup plan for system failures
- Interactive Brokers for their comprehensive API
- Polygon.io for reliable market data
- The Python trading community for inspiration and tools