Automate your Robinhood trades with custom and pre-built algorithmic strategies, removing emotion from your investment decisions.
- 🚀 Overview
- ✨ Feature Highlights
- 🏗️ Architecture & Technology Stack
- 🏁 Getting Started
- 💡 Usage & Workflows
⚠️ Limitations, Known Issues & Future Roadmap- 🤝 Contributing & Development Guidelines
- ©️ License, Credits & Contact
- 📚 Appendix
The Robinhood Trading Bot is a robust Python application designed to execute automated market orders on the Robinhood platform based on predefined or custom trading algorithms. Its primary goal is to empower users to implement systematic trading strategies, thereby eliminating emotional bias and ensuring consistent execution.
This bot provides a framework for developing and deploying various algorithmic trading strategies, from simple moving average crossovers to more advanced sentiment analysis. It aims to simplify the process of connecting to Robinhood, fetching real-time data, and placing trades programmatically.
- Removes Emotional Bias: Trading decisions are made strictly by logic, not fear or greed.
- Enables Systematic Trading: Facilitates the execution of rule-based strategies without constant manual intervention.
- Simplifies API Interaction: Abstracts away the complexities of interacting with the Robinhood API.
- Extensible Design: Allows for easy integration of new trading algorithms and strategies.
- Developers & Programmers: Who want to leverage Python for algorithmic trading.
- Algorithmic Traders: Seeking a customizable platform to test and deploy their strategies.
- Quantitative Analysts: Interested in automating data-driven investment approaches.
- Curious Investors: Who wish to explore the world of automated stock trading with a hands-on approach.
This Robinhood Trading Bot comes packed with features to get you started and provide a flexible framework for your trading needs.
- ✅ Seamless Robinhood Integration: Connects securely to your Robinhood account to fetch data and execute trades.
- 🚀 Multiple Built-in Trading Strategies:
- Simple Moving Average (SMA): Analyzes 50-day and 200-day moving averages for buy/sell signals.
- Volume-Weighted Average Price (VWAP): Compares current price against VWAP for short-term entry/exit.
- Twitter Sentiment Analysis: Leverages real-time tweet sentiment to inform trading decisions.
- 🛠️ Configurable Bot Framework: Easily create your own unique trading algorithms by adding new strategy functions.
- 🔐 Secure Configuration: Utilizes environment variables (
.env) for sensitive API keys and credentials, keeping them out of source control. - ⚙️ Automated Setup: A simple
initialize.shscript handles virtual environment creation, dependency installation, and.envfile generation. - 📏 Code Quality & Consistency: Integrated
black,isort, andpre-commithooks ensure a clean and maintainable codebase. - 📖 Comprehensive Documentation: Clear examples and explanations for both using existing strategies and developing new ones.
The Robinhood Trading Bot is designed with modularity in mind, allowing for easy expansion and maintenance.
The system follows a client-server interaction pattern where your bot acts as a client interacting with the Robinhood API (and optionally Twitter API) through a Python wrapper.
graph TD
A[User Script] --> B(TradeBot Instance)
B --> C{TradeBot Logic}
C --> D[src/bots/trading_strategies.py]
D -- Robinhood API Wrapper --> E(Robinhood API)
D -- Twitter API Library --> F(Twitter API)
E -- Market Data & Order Execution --> G[Robinhood Platform]
F -- Tweet Data --> H[Twitter Platform]
C -- Order Recommendation --> B
B -- Executes Trade --> D
src/bots/base_trade_bot.py:- 🔍 TradeBot: The core trading bot class. It handles configuration, authentication, strategy execution, and order placement.
src/bots/trading_strategies.py:- 🚀 Strategy Functions: A collection of functions, each implementing a distinct trading strategy (e.g.,
calculate_sma_signal,calculate_sentiment_signal).
- 🚀 Strategy Functions: A collection of functions, each implementing a distinct trading strategy (e.g.,
src/utilities.py:- 💡 Utility Functions: Contains helper classes for managing credentials.
src/bots/config.py:- ⚙️ Configuration Management: Defines dataclasses for configuring all aspects of the bot, from strategies to risk management.
initialize.sh:- 🛠️ Setup Script: A shell script to automate the initial setup process: virtual environment creation, dependency installation, pre-commit hook setup, and
.envfile generation.
- 🛠️ Setup Script: A shell script to automate the initial setup process: virtual environment creation, dependency installation, pre-commit hook setup, and
.env.example:- 🔐 Environment Variables Template: A template for the required environment variables.
- Python: The core language for the application. (Recommended: Python 3.8+)
- robin_stocks: A comprehensive Python wrapper for the Robinhood API, used for authentication, fetching market data, and placing orders.
- tweepy: A user-friendly Python library for accessing the Twitter API, primarily used in the sentiment analysis strategy.
- pandas: Utilized for data manipulation and analysis, especially for handling historical stock data and moving average calculations.
- numpy: Provides fundamental support for numerical operations.
- python-dotenv: For loading environment variables from a
.envfile. - black: An uncompromising Python code formatter.
- isort: A Python utility to sort imports alphabetically and automatically separate them into sections and types.
- pytest: A mature full-featured Python testing framework.
Follow these steps to get your Robinhood Trading Bot up and running.
Before you begin, ensure you have the following:
- Python 3.8+: Download and install from python.org.
- Robinhood Account: You will need an active Robinhood brokerage account.
- Twitter API Keys (Optional): If you plan to use the sentiment analysis strategy, you'll need a Twitter Developer Account to obtain API keys (
Consumer KeyandConsumer Secret). - Multi-Factor Authentication (MFA) Setup for Robinhood:
- Log into your Robinhood account.
- Navigate to
Menu>Security and privacy>Two-Factor Authentication. - Choose "Authenticator App" (e.g., Duo Mobile, Google Authenticator).
- Copy the secret key provided by Robinhood. This key is your
ROBINHOOD_MFA_CODE. You will use this key in your authenticator app to generate TOTP codes.
-
Clone the repository:
git clone https://github.com/ElysiumOSS/robinhood-bot.git cd robinhood-bot -
Run the Initialization Script: The
initialize.shscript will set up your Python virtual environment, install all necessary dependencies, and create a.envfile for your credentials.sh initialize.sh
💡 What
The script performs the following actions: 1. Checks if a virtual environment named `env` exists. If not, it creates one. 2. Activates the virtual environment. 3. Upgrades `pip` to the latest version. 4. Installs all Python dependencies listed in `requirements.txt`. 5. Installs `pre-commit` hooks for automatic code formatting and linting. 6. Creates a `.env` file from the `.env.example` template if it doesn't exist.initialize.shdoes:
After running initialize.sh, you must update the .env file with your actual credentials.
-
Open the
.envfile:nano .env # or use your preferred text editor -
Populate your credentials: Replace the placeholder values with your actual Robinhood and (optional) Twitter API credentials.
# .env.example # This file is a template for the required environment variables. # Copy this file to .env and fill in your actual credentials. # Do NOT commit the .env file to version control. # Twitter API Credentials (Optional - only for sentiment analysis bot) TWITTER_CONSUMER_KEY="YOUR_TWITTER_CONSUMER_KEY" TWITTER_CONSUMER_SECRET="YOUR_TWITTER_CONSUMER_SECRET" # Robinhood Credentials ROBINHOOD_USER="YOUR_ROBINHOOD_EMAIL" ROBINHOOD_PASS="YOUR_ROBINHOOD_PASSWORD" ROBINHOOD_MFA_CODE="YOUR_ROBINHOOD_MFA_SECRET_KEY" # Optional: MFA secret key for automated authentication
-
Activate your virtual environment: Always ensure your virtual environment is active when running the bot or installing packages.
source env/bin/activate
The bot now supports multiple authentication methods with automatic retry and verification timer:
Method 1: Environment Variable MFA (Recommended for Automation)
- Set
ROBINHOOD_MFA_CODEin your.envfile with your authenticator app's secret key - The bot will automatically use this for authentication
- Best for scheduled/automated runs
Method 2: Interactive Device Approval (For "Yes, it's me" prompts)
- If Robinhood asks you to approve the login on your device:
python approve_login.py
- This script gives you 3 minutes to approve the login on your mobile app
- Look for the "Yes, it's me" prompt in your Robinhood app
- The script will wait and verify the approval automatically
- Use this if you keep seeing "Approve this login" notifications
Method 3: Interactive MFA (SMS/Code Entry)
- Leave
ROBINHOOD_MFA_CODEempty or unset - The bot will attempt SMS verification
- If MFA is required, it will wait 45 seconds for SMS delivery
- You'll be prompted to enter the verification code interactively
- Ideal for manual runs and initial setup
Method 4: Automatic Retry with Timer
- The bot implements a 3-attempt retry mechanism with exponential backoff (10s, 20s, 40s)
- Each attempt tries multiple authentication methods
- Provides detailed error messages and troubleshooting steps
- Gracefully handles various authentication errors (missing 'detail' key, locked accounts, etc.)
Once configured, you can start using the existing strategies or create your own.
To use the pre-built trading algorithms, create a new Python script in the project's root directory.
-
Import and Configure the
TradeBot:# my_trade.py from src.bots.base_trade_bot import TradeBot from src.bots.config import TradingConfig, StrategyType # 1. Configure the strategies you want to use my_config = TradingConfig( enabled_strategies=[ StrategyType.SMA_CROSSOVER, StrategyType.SENTIMENT, ], strategy_weights={ StrategyType.SMA_CROSSOVER: 0.6, StrategyType.SENTIMENT: 0.4, } ) # 2. Initialize the TradeBot with your configuration trade_bot = TradeBot(config=my_config) # 3. Execute a trade decision for a specific ticker trade_bot.execute_trade_decision(ticker="AAPL")
-
Run your script: Make sure your virtual environment is active.
python my_trade.py
The
execute_trade_decision()function will connect to Robinhood, fetch necessary data, apply the configured strategies, and execute a trade if the combined signal meets the configured thresholds.
The framework is designed for easy extension. You can create your own custom trading logic by adding a new strategy function.
-
Create a new function in
trading_strategies.py: Insrc/bots/trading_strategies.py, create a new Python function that takes a ticker and a configuration object as input and returns a float between -1.0 (strong sell) and 1.0 (strong buy).# src/bots/trading_strategies.py def calculate_my_custom_signal(df: pd.DataFrame, config: MyCustomConfig) -> float: """ Implement your custom trading algorithm here. """ # Your logic here return 0.0
-
Add your strategy to
StrategyType: Insrc/bots/config.py, add your new strategy to theStrategyTypeenum.# src/bots/config.py class StrategyType(Enum): # ... existing strategies MY_CUSTOM_STRATEGY = "my_custom_strategy"
-
Integrate your strategy into
TradeBot: Insrc/bots/base_trade_bot.py, update thecalculate_strategy_signalsmethod to include your new strategy.# src/bots/base_trade_bot.py # ... inside calculate_strategy_signals elif strategy == StrategyType.MY_CUSTOM_STRATEGY: signals[strategy] = calculate_my_custom_signal( df, self.config.my_custom_config )
Here's a brief overview of the algorithms implemented in the existing strategies:
This algorithm calculates two Simple Moving Averages (SMAs): a 50-day SMA and a 200-day SMA. These are derived from historical stock prices. * **Buy Recommendation**: Made when the 50-day moving average is strictly greater than the 200-day moving average (a "golden cross" signal, often considered bullish). * **Sell Recommendation**: Made when the 50-day moving average is strictly less than the 200-day moving average (a "death cross" signal, often considered bearish). * **No Recommendation**: If the two moving averages are equal.
The Volume-Weighted Average Price (VWAP) is a trading benchmark that represents the average price a security has traded at throughout the day, based on both volume and price. It's calculated by summing the dollar value of all shares traded and dividing by the total shares traded over a specific period. * **Buy Recommendation**: Made when the current price of a security is below its VWAP (suggesting the stock is undervalued or trading at a discount for the day). * **Sell Recommendation**: Made when the current price of a security is above its VWAP (suggesting the stock is overvalued or trading at a premium for the day). * **No Recommendation**: If neither of the above conditions are met.
This algorithm harnesses the power of social media by sourcing tweets mentioning a specific company via the Twitter API. * A sentiment analysis is performed on each collected tweet, assigning a score (negative, neutral, or positive). * The average sentiment score for all relevant tweets is calculated. * **Buy Recommendation**: Made if the average sentiment is positive. * **Sell Recommendation**: Made if the average sentiment is negative. * **No Recommendation**: If the average sentiment is neutral.
Understanding the current state and future direction of the project is crucial.
- No True Backtesting: The current framework does not include a dedicated backtesting module to evaluate strategy performance on historical data.
- Basic Risk Management: Lacks advanced risk management features like stop-loss, take-profit orders, or portfolio-level risk assessment.
- Robinhood API Constraints: Dependent on
robin_stockslibrary and Robinhood's public API limitations, which may include rate limits, available order types, and data refresh rates. - Single Ticker Focus: The bot is designed to trade one ticker at a time per execution; no multi-asset portfolio management.
- No Persistent State: Bot state (e.g., open positions, historical trades for analysis) is not persistently stored by the bot itself across runs.
- MFA Code Generation: Users sometimes struggle with correctly obtaining and using the
ROBINHOOD_MFA_CODE(secret key) rather than a time-based OTP. Ensure you copy the secret key given by Robinhood for authenticator app setup. - Rate Limiting: Frequent calls to Robinhood or Twitter APIs might lead to temporary rate limiting. Implement delays between calls if experiencing issues.
The following enhancements are planned or under consideration:
- 📈 Dedicated Backtesting Module: Allow users to test their algorithms against historical market data before live deployment.
- 🛡️ Advanced Risk Management: Integrate features like configurable stop-loss/take-profit, position sizing, and diversified portfolio management.
- 🐳 Dockerization: Provide Docker images and Docker Compose configurations for easier deployment and environment consistency.
- 🌐 Web User Interface (UI): Develop a simple web interface for monitoring bot activity, configuring strategies, and viewing performance.
- 📊 Performance Tracking & Reporting: Implement logging and reporting tools to track bot performance over time.
- 🔄 Recurring Trades: Add functionality to schedule trades at specific intervals (e.g., daily, weekly) using a scheduler like
APSchedulerorCelery. - 📨 Notification System: Integrate with messaging services (e.g., email, Discord, Telegram) for trade alerts and status updates.
We welcome contributions from the community! Whether it's bug fixes, new features, or improved documentation, your help is appreciated.
- Fork the Repository: Start by forking the
ElysiumOSS/robinhood-botrepository to your GitHub account. - Clone Your Fork: Clone your forked repository to your local machine.
git clone https://github.com/YOUR_USERNAME/robinhood-bot.git cd robinhood-bot - Create a New Branch: Always work on a new branch, giving it a descriptive name.
git checkout -b feature/your-awesome-feature # or git checkout -b fix/issue-description - Make Your Changes: Implement your feature or bug fix.
- Test Your Changes: Ensure your code works as expected and doesn't introduce regressions. Add new tests if applicable.
- Commit Your Changes: Write clear and concise commit messages.
git commit -m "feat: Add new awesome trading strategy" - Push to Your Fork: Push your new branch to your GitHub fork.
git push origin feature/your-awesome-feature
- Open a Pull Request (PR): Go to the original
ElysiumOSS/robinhood-botrepository on GitHub and open a new Pull Request from your forked branch to themainbranch. Provide a detailed description of your changes.
- Branch Naming: Use prefixes like
feature/,fix/,docs/,refactor/.feature/add-new-indicatorfix/mfa-auth-bugdocs/update-installation-guide
- Commit Messages: Follow Conventional Commits style (e.g.,
feat: Add new bot,fix: Correct date parsing). - Pull Request Description: Clearly describe the problem your PR solves, how you solved it, and any potential side effects. Link to relevant issues if applicable.
This project enforces consistent code style and quality standards using black, isort, and pre-commit hooks.
- Automatic Formatting:
blackautomatically formats your code, andisortorganizes imports. These are configured to run viapre-commithooks. - Pre-commit Hooks: When you run
sh initialize.sh,pre-commit installis executed, setting up hooks that runblackandisortautomatically before each commit. This ensures your code is formatted correctly every time. - Manual Check: If for any reason pre-commit hooks don't run, you can manually check and fix formatting:
black . isort .
- Test Framework:
pytestis used for unit and integration testing. - Running Tests: Ensure your virtual environment is active, then run tests from the project root:
pytest
- Adding Tests: When submitting new features or bug fixes, please include relevant tests to cover your changes.
This project is licensed under the MIT License. See the LICENSE file for details.
MIT License
Copyright (c) 2022 Andrew B. Ghorbani
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This project gratefully acknowledges the following open-source projects and their contributors:
- robin_stocks - A Python wrapper for the Robinhood API.
- tweepy - An easy-to-use Python library for accessing the Twitter API.
- pandas - For data manipulation and analysis.
- numpy - For numerical operations.
- python-dotenv - For managing environment variables.
- black - The uncompromising Python code formatter.
- isort - A Python utility / library to sort imports.
- pytest - A testing framework.
Special thanks to Andrew B. Ghorbani for initiating and maintaining this project.
For questions, suggestions, or collaborations, please feel free to:
- Open an issue on the GitHub Issue Tracker.
- Reach out via the GitHub profile of the primary maintainer: Andrew B. Ghorbani.
You need to apply for a Twitter Developer Account. 1. Go to the [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard). 2. Sign up for a developer account and create a new project/app. 3. Generate your API Key (`Consumer Key`) and API Secret (`Consumer Secret`). These will be used for `TWITTER_CONSUMER_KEY` and `TWITTER_CONSUMER_SECRET` in your `.env` file.
Yes, you can. For continuous operation, you might consider setting up a cron job on a Linux system or a scheduled task on Windows to run your trading script at desired intervals. However, remember the limitations (e.g., rate limits) and ensure proper error handling and logging for long-running processes. For production, consider using containerization (Docker) and dedicated server environments.
The `ROBINHOOD_MFA_CODE` is the *secret key* you get when initially setting up an authenticator app, not the time-based OTP. This secret key generally does not expire unless you explicitly disable and re-enable MFA for your Robinhood account. If you do, you'll need to update the `ROBINHOOD_MFA_CODE` in your `.env` file with the new secret key.
If you keep getting prompted to approve the login on your Robinhood mobile app:
This is a device challenge - Robinhood wants to verify it's really you logging in.
Solution: Use the approval script
python approve_login.pyThis specialized script:
- Waits 3 minutes for you to approve the login
- Shows countdown timer so you know how much time you have
- Automatically verifies once you click "Yes, it's me"
- Provides clear instructions at each step
Steps:
- Run
python approve_login.py - Open your Robinhood mobile app
- Look for the "Approve this login" notification
- Tap "Yes, it's me" or "Approve"
- Wait for the script to confirm success
Why this happens:
- New device or IP address
- Long time since last login
- Suspicious activity detection
- Security measure by Robinhood
If it still fails:
- Make sure you're approving within the 3-minute window
- Check that notifications are enabled in the Robinhood app
- Try logging into Robinhood app/website directly first
- Wait 30 minutes and try again if you've had many failed attempts
This error typically occurs when Robinhood's API returns a 403 response without the expected error details. This can happen for several reasons:
Common Causes:
- MFA/2FA Required: Your account requires two-factor authentication
- Device Approval Required: Robinhood wants you to approve the login (see above)
- Account Verification Needed: Robinhood may need you to verify your account through their app/website
- Suspicious Activity: Account temporarily locked due to unusual login patterns
- Invalid Credentials: Username or password is incorrect
- Rate Limiting: Too many login attempts in a short period
Solutions:
-
Try Device Approval Script (if you see "Yes, it's me" prompts):
python approve_login.py
-
Enable Interactive MFA:
- Leave
ROBINHOOD_MFA_CODEempty in.env - Run the bot - it will wait 45 seconds for SMS and prompt for code
- Leave
-
Set Up MFA in Environment:
- Add your MFA secret key to
ROBINHOOD_MFA_CODEin.env - Bot will automatically authenticate using this key
- Add your MFA secret key to
-
Verify Account Manually:
- Log into Robinhood app/website directly
- Complete any pending verification steps
- Try running the bot again
-
Wait and Retry:
- The bot automatically retries 3 times with exponential backoff (10s, 20s, 40s)
- If rate-limited, wait 15-30 minutes before trying again
-
Check Credentials:
- Verify
ROBINHOOD_USERandROBINHOOD_PASSare correct - Ensure no extra spaces or quotes in
.envfile
- Verify
This error usually means the `ROBINHOOD_MFA_CODE` in your `.env` file is incorrect or not the correct type of code. * **Ensure it's the Secret Key**: The `ROBINHOOD_MFA_CODE` should be the **long alphanumeric secret key** that Robinhood provides when you *first set up* an authenticator app (e.g., "JBSWY3DPEHPK3PXP"). It is *not* the 6-digit number generated by your authenticator app. * **Check for Typos**: Double-check for any typos or missing characters in the key. * **Re-setup MFA (if necessary)**: If unsure, you might need to disable and re-enable Authenticator App MFA in Robinhood to get a fresh secret key.
This indicates an issue with your `TWITTER_CONSUMER_KEY` or `TWITTER_CONSUMER_SECRET`. * **Check `.env`**: Verify that `TWITTER_CONSUMER_KEY` and `TWITTER_CONSUMER_SECRET` in your `.env` file are correct and complete. * **Twitter Developer Portal**: Log in to your Twitter Developer Portal and ensure your app's API keys are still valid and that your project has the necessary permissions (e.g., "Elevated" access) to perform searches. * **Environment Activation**: Ensure your virtual environment is active before running the script.
This typically means a required package wasn't installed correctly or your virtual environment isn't active. * **Activate Virtual Environment**: Always run `source env/bin/activate` before trying to run the bot. * **Re-install Dependencies**: If the issue persists, try reinstalling all dependencies: ```bash source env/bin/activate pip install -r requirements.txt ```
v1.1.0 - Refactoring and Unification (2025-11-01)
- Refactored the bot architecture to use a single, configuration-driven
TradeBot. - Removed the standalone
TradeBotTwitterSentimentsand integrated it as a configurable strategy. - Improved security by using a
.env.examplefile and updating theinitialize.shscript. - Removed obsolete
sample.pyfile.
v1.0.0 - Initial Release (2022-XX-XX)
- Core framework for Robinhood bot with
BaseTradeBot. - Implemented Simple Moving Average (SMA) strategy.
- Implemented Volume-Weighted Average Price (VWAP) strategy.
- Implemented Twitter Sentiment Analysis strategy.
- Initial
initialize.shfor easy setup. - Basic
.envconfiguration for credentials. black,isort,pre-commitfor code quality.- MIT License.
Future Releases
- (Planned) v1.2.0: Backtesting module and enhanced logging.
- (Planned) v1.3.0: Dockerization for easier deployment.