Welcome to AutoTrader Bot, a Python-based automated stock trading bot designed for real-time trading with customizable buy/sell strategies. This bot is optimized for Indian stocks and integrates with Zerodha Kite for seamless execution. It's built to be efficient, customizable, and easy to deploy.
- 🔄 Custom Trading Strategies: Leverage MACD, RSI, EMA, and Volume-based strategies to make buy/sell decisions.
- 📈 Real-Time Data: Fetches live price and volume data using Zerodha’s KiteTicker.
- 🤖 Automated Orders: Executes buy, sell, and hold signals based on predefined conditions.
- 🚀 Performance Optimization: Efficient order placement adhering to rate limits, with caching and multiprocessing capabilities.
- 💰 Funds Management: Allocates ₹20,000 per stock for trading.
- 🛡️ Error Handling: Logging module coming soon.
- Installation
- Configuration
- Usage
- Strategies
- Performance Optimization
- Deployment
- Running the Bot as a Service with Systemd
- Using Systemd Timers to Refresh Session Token
- Future Enhancements
- Contributing
- License
-
Clone the repository:
git clone https://github.com/The-Great-One/Auto_Trader.git cd autotrader-bot
-
Install the dependencies:
pip install -r requirements.txt
-
Create a file called
my_secrets.py
in theAuto_Trader
directory with your API credentials:API_KEY = 'your_api_key' API_SECRET = 'your_api_secret' TOTP_KEY = 'your_totp_key' USER_NAME = 'your_username' PASS = 'your_password' TG_TOKEN = 'your_telegram_token' CHANNEL = '@your_channel' GITHUB_PAT = 'your_github_personal_access_token'
- You can get your TOTP_KEY by scanning the QR code shown during the 2FA setup on the Zerodha website.
Steps:
- Log in to Zerodha.
- Set up 2-factor authentication.
- Use an app like Google Authenticator or Authy to scan the QR code.
- Retrieve the TOTP key from the authenticator app and add it to
my_secrets.py
.
- Rate Limits: The bot complies with Zerodha's API rate limits (10 requests/second, 200 orders/minute).
- Funds Management: By default, the bot allocates ₹20,000 per stock from a total fund pool for trading.
- Order Handling: Sell orders are prioritized to free up funds for new buy orders.
Create a file called RULE_SET_*.py
and define a function called buy_or_sell(df, row, holdings)
.
df
: This is the entire DataFrame with calculated indicators.row
: This contains the latest raw values from the ticker, providing real-time data.holdings
: A list of symbols currently held by the bot.
If you want to add more indicators, you can modify them here or in the utils.py
file, inside the indicators function.
def buy_or_sell(df, row, holdings):
# Example logic based on RSI and MACD
if row['rsi'] > 60 and row['macd_hist'] > 5 and row['symbol'] not in holdings:
# Place Buy Order
return 'BUY'
elif row['rsi'] < 40 and row['symbol'] in holdings:
# Place Sell Order
return 'SELL'
else:
return 'HOLD'
To start the bot, run:
python wednesday.py
This will launch the bot, connect it to the Zerodha Kite API, fetch live stock data, and execute trades based on the defined strategy.
The following indicators are used in default strategies:
- MACD: Signal line and histogram-based decisions.
- RSI: Buy when RSI crosses above 60, sell below 40.
- EMA: Crossover-based strategies using EMA 10 and EMA 20.
- Volume: Volume spikes for trend confirmation.
You can modify these strategies by editing their respective RULE_SET
files.
- Caching: Data is fetched once per day and stored in memory for fast access.
- Multiprocessing: Tasks are parallelized to avoid WebSocket blocking and ensure smooth data processing.
- Non-blocking WebSocket: The bot uses asynchronous I/O to keep WebSocket connections stable while processing data.
You can deploy this bot on Vultr or any cloud platform to keep it running continuously.
To make the bot run continuously in the background as a service using systemd
, follow these steps:
-
Create a new service file:
sudo nano /etc/systemd/system/autotrader.service
-
Add the following content to the service file:
[Unit] Description=AutoTrader Bot Service After=network.target [Service] User=your_username WorkingDirectory=/path/to/AutoTrader ExecStart=/usr/bin/python3 /path/to/AutoTrader/wednesday.py Restart=on-failure [Install] WantedBy=multi-user.target
-
Reload
systemd
to recognize the new service:sudo systemctl daemon-reload
-
Start the service:
sudo systemctl start autotrader.service
-
Enable the service to start on boot:
sudo systemctl enable autotrader.service
-
Check the status of the service:
sudo systemctl status autotrader.service
Now, the bot will automatically run as a service in the background and restart on failure.
I wasn't able to refresh the session token in Python, so I'm using systemd
to handle it. The bot will restart daily at 8:30 AM to refresh the session token.
-
Create a timer file:
sudo nano /etc/systemd/system/autotrader.timer
-
Add the following content to the timer file:
[Unit] Description=Run AutoTrader Bot at 8:30 AM daily to refresh the session token [Timer] OnCalendar=*-*-* 08:30:00 Persistent=true [Install] WantedBy=timers.target
-
Enable and start the timer:
sudo systemctl enable autotrader.timer sudo systemctl start autotrader.timer
-
Check the status of the timer to ensure it’s working:
sudo systemctl status autotrader.timer
The bot will now refresh the session token daily at 8:30 AM.
- Additional Indicators: Add support for Bollinger Bands, Stochastic Oscillator, etc.
- More Exchanges: Support for BSE, international exchanges.
- Advanced Risk Management: Stop-loss, trailing stops, and better fund management.
- Analytics Dashboard: A real-time performance monitoring dashboard with profit/loss trends.
We welcome contributions! Please read our Contributing Guide for details on our code of conduct, and the process for submitting pull requests.
This project is licensed under the MIT License – see the LICENSE file for details.
Happy Trading! 🚀📈