A sophisticated Python trading bot for 0 DTE (Days to Expiration) SPX options trading. The bot analyzes market conditions at 7 AM PST daily and executes high-probability trades based on technical analysis.
- Real-time SPX data using Yahoo Finance
- Technical Indicators: RSI, MACD, Moving Averages, Bollinger Bands, Stochastic
- VIX analysis for volatility assessment
- Volume analysis and market breadth indicators
- Pre-market sentiment evaluation
-
Put Credit Spreads (Bullish Markets)
- $10 wide spreads
- High probability of profit (>70%)
- Target delta around 0.15
- Automatic strike selection based on support levels
-
Call Diagonal Spreads (Sideways Markets)
- Front-month 0DTE short calls
- Back-month long calls for protection
- Favorable volatility skew optimization
- Time decay advantage
- Position sizing based on account value (2% risk per trade)
- Daily loss limits and trade count restrictions
- Greeks validation (Delta, Theta, Vega limits)
- Market condition filters (VIX, RSI thresholds)
- Concentration risk controls
- Interactive Brokers API support
- Paper trading mode for testing
- Real-time market data and order execution
- Position monitoring and management
- Email notifications (Gmail, custom SMTP)
- Telegram alerts with formatted messages
- Slack integration for team notifications
- Daily summaries and trade confirmations
- Scheduled execution at 7 AM PST
- Market hours validation
- Weekend/holiday detection
- Automatic error handling and recovery
- Python 3.8+
- Interactive Brokers account (for live trading)
- TWS or IB Gateway running (for live trading)
- Clone the repository
git clone <repository-url>
cd spx-0dte-trading-bot
- Install dependencies
pip install -r requirements.txt
- Create environment configuration
python main_trading_bot.py --create-env
cp .env.template .env
- Configure your settings in
.env
:
# Interactive Brokers Settings
IB_HOST=127.0.0.1
IB_PORT=7497
IB_CLIENT_ID=1
# Email Notifications
EMAIL_USER=[email protected]
EMAIL_PASSWORD=your-app-password
NOTIFICATION_EMAIL=[email protected]
# Telegram Notifications (optional)
TELEGRAM_BOT_TOKEN=your-bot-token
TELEGRAM_CHAT_ID=your-chat-id
# Slack Notifications (optional)
SLACK_WEBHOOK_URL=your-webhook-url
# Run a single analysis in paper trading mode
python main_trading_bot.py --mode manual
# Test with notifications disabled
python main_trading_bot.py --mode manual --no-notifications
# Start the bot with daily 7 AM PST execution (paper trading)
python main_trading_bot.py --mode scheduled
# Run with live trading (CAUTION: Real money!)
python main_trading_bot.py --mode scheduled --live
# Run immediate market analysis and trading
python main_trading_bot.py --mode manual
spx-0dte-trading-bot/
├── main_trading_bot.py # Main entry point
├── config.py # Configuration settings
├── market_analyzer.py # Market analysis and indicators
├── strategy_engine.py # Trading strategy logic
├── options_calculator.py # Options pricing and Greeks
├── trading_interface.py # Broker API integration
├── risk_management.py # Risk controls and validation
├── scheduler.py # Automated scheduling
├── notifications.py # Alert system
├── requirements.txt # Python dependencies
├── .env.template # Environment template
└── logs/ # Trading logs
Edit config.py
to customize:
# Trading Parameters
SPREAD_WIDTH = 10 # $10 width for credit spreads
MIN_CREDIT = 2.0 # Minimum credit to collect
MAX_RISK_PER_TRADE = 1000 # Maximum risk per trade
TARGET_DELTA = 0.15 # Target delta for short strikes
MIN_PROBABILITY = 0.70 # Minimum probability of profit
# Technical Indicator Parameters
RSI_PERIOD = 14
MACD_FAST = 12
MACD_SLOW = 26
BB_PERIOD = 20
# Strategy Thresholds
BULLISH_RSI_MIN = 40
BULLISH_RSI_MAX = 70
# Risk Parameters (in risk_management.py)
max_daily_loss = 5000 # Maximum daily loss
max_position_size = 10 # Maximum contracts per position
max_trades_per_day = 5 # Daily trade limit
- RSI between 40-70
- MACD above signal line
- Price above 20 & 50 SMA
- VIX < 20
- Strong volume confirmation
- RSI between 30-70
- Price within Bollinger Bands
- Low volatility environment
- Conflicting indicators
- RSI < 30 or > 70
- MACD below signal line
- Price below moving averages
- VIX > 30
- High volatility
When: Bullish market conditions Structure:
- Sell higher strike put (short)
- Buy lower strike put (long)
- Collect net credit upfront
Example:
- SPX at 4500
- Sell 4450 Put, Buy 4440 Put
- Collect $3.50 credit
- Max profit: $3.50
- Max loss: $6.50
- Breakeven: 4446.50
When: Sideways/neutral market conditions Structure:
- Sell near-term call (0DTE)
- Buy longer-term call (1 week)
- Benefit from time decay
Example:
- SPX at 4500
- Sell 4520 Call (0DTE)
- Buy 4540 Call (7DTE)
- Collect time decay while protected
The bot logs all activities and provides:
- Daily P&L tracking
- Win/loss ratios
- Risk metrics
- Trade performance analytics
- Market condition correlation
Logs are stored in logs/trading_bot_YYYYMMDD.log
- Enable 2-factor authentication
- Generate app password
- Use app password in
.env
file
- Create bot with @BotFather
- Get bot token
- Find your chat ID
- Configure in
.env
- Create incoming webhook
- Configure webhook URL
- Add to
.env
IMPORTANT: This bot trades real money when in live mode. Please:
- Start with paper trading to test the system
- Use small position sizes initially
- Monitor the bot regularly
- Understand the strategies before deploying
- Have stop-loss procedures in place
- Keep adequate account funding
- 0DTE options are highly volatile and can expire worthless
- Market gaps can cause significant losses
- System failures could prevent trade management
- Broker connectivity issues may affect execution
# Run on your computer
python main_trading_bot.py --mode scheduled
- Set up virtual machine
- Install dependencies
- Configure cron job for 7 AM PST
- Set up monitoring and alerts
FROM python:3.9
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "main_trading_bot.py", "--mode", "scheduled"]
-
Market data errors
- Check internet connection
- Verify Yahoo Finance access
- Try different data sources
-
Broker connection issues
- Ensure TWS/IB Gateway is running
- Check port and client ID
- Verify account permissions
-
Notification failures
- Check API keys and tokens
- Verify network connectivity
- Test notification services separately
# Enable verbose logging
python main_trading_bot.py --mode manual --debug
# Custom backtesting module (future enhancement)
from backtester import BacktestEngine
backtester = BacktestEngine()
results = backtester.run(start_date, end_date)
Extend the StrategyEngine
class to add new strategies:
def find_iron_condor(self, market_analysis):
# Custom iron condor implementation
pass
Add new data sources by extending MarketAnalyzer
:
def get_alternative_data(self):
# Integration with other data providers
pass
- Fork the repository
- Create feature branch
- Add tests for new functionality
- Submit pull request
This project is for educational purposes. Use at your own risk.
For questions or issues:
- Check the logs first
- Review configuration settings
- Test in paper trading mode
- Create GitHub issue with details
- Additional strategy types (Iron Condors, Strangles)
- Machine learning market prediction
- Advanced backtesting framework
- Web dashboard for monitoring
- Mobile app notifications
- Multi-timeframe analysis
- Earnings calendar integration
- Social sentiment analysis
Disclaimer: This software is for educational and research purposes only. Trading options involves substantial risk and is not suitable for all investors. Past performance does not guarantee future results. Always consult with a qualified financial advisor before making investment decisions.