A robust, modular, and scalable Python-based automatic intraday trading application using the Fyers API for Indian stock markets.
- Automated Trading: Place trades automatically based on technical strategies
- Backtesting Engine: Test strategies on historical data with comprehensive performance metrics
- Multiple Strategies: Moving Average Crossover, VWAP Bounce, RSI Price Action
- Risk Management: Stop-loss, take-profit, position sizing, and daily loss limits
- Real-time Monitoring: Live data streaming and trade execution
- Comprehensive Logging: Detailed logs for trades, errors, and performance
- Modular Architecture: Clean separation of concerns with configurable components
- Python 3.9+
- Fyers API credentials
- pip package manager
-
Clone the repository
git clone <repository-url> cd fyers-trading-bot
-
Install dependencies
pip install -r requirements.txt
-
Configure environment variables
cp env_template.txt .env
Edit
.envfile with your Fyers API credentials:FYERS_APP_ID=your_app_id_here FYERS_APP_SECRET=your_app_secret_here FYERS_ACCESS_TOKEN=your_access_token_here
-
Configure settings
Edit
trading_app/config/settings.yamlto customize:- Trading parameters (capital, risk limits)
- Strategy configurations
- Risk management settings
- Logging preferences
-
Create Fyers App
- Visit Fyers Developer Portal
- Create a new app and get your App ID and App Secret
-
Generate Access Token
- Use the Fyers API to generate an access token
- Add the token to your
.envfile
The application includes three pre-built strategies:
- Parameters:
short_window,long_window,ma_type(SMA/EMA) - Logic: Buy when short MA crosses above long MA, sell on reverse
- Parameters:
vwap_period,bounce_threshold,rsi_period - Logic: Buy when price bounces from below VWAP with RSI confirmation
- Parameters:
rsi_period,rsi_oversold,rsi_overbought - Logic: Buy on RSI oversold with price action confirmation
python -m trading_app.main --mode testpython -m trading_app.main --mode strategiespython -m trading_app.main --mode symbolspython -m trading_app.main --mode backtest \
--symbol NIFTY \
--strategy ma_crossover \
--start-date 2024-01-01 \
--end-date 2024-01-31 \
--timeframe 5minpython -m trading_app.main --mode live \
--symbols NIFTY BANKNIFTY \
--strategies ma_crossover vwap_bouncepython -m trading_app.main --mode performancefrom trading_app.main import TradingApp
# Initialize app
app = TradingApp()
# Run backtest
results = app.run_backtest(
symbol="NIFTY",
strategy_name="ma_crossover",
start_date="2024-01-01",
end_date="2024-01-31"
)
# Start live trading
app.run_live_trading(
symbols=["NIFTY", "BANKNIFTY"],
strategies=["ma_crossover", "vwap_bounce"]
)The backtesting engine provides comprehensive performance metrics:
- Total Return: Overall percentage gain/loss
- Sharpe Ratio: Risk-adjusted return measure
- Maximum Drawdown: Largest peak-to-trough decline
- Win Rate: Percentage of profitable trades
- Profit Factor: Ratio of gross profit to gross loss
- Trade Analysis: Entry/exit points, P&L, reasons
==================================================
BACKTEST REPORT
==================================================
Symbol: NIFTY
Strategy: ma_crossover
Period: 2024-01-01 to 2024-01-31
Timeframe: 5min
PERFORMANCE METRICS:
Initial Capital: βΉ50,000.00
Final Capital: βΉ52,450.00
Total Return: 4.90%
Sharpe Ratio: 1.25
Max Drawdown: -2.10%
Win Rate: 65.20%
Total Trades: 23
Average Trade: βΉ106.52
Profit Factor: 1.85
TRADE SUMMARY:
Winning Trades: 15
Losing Trades: 8
Best Trade: βΉ450.00
Worst Trade: βΉ-180.00
==================================================
trading_app/
βββ config/
β βββ settings.yaml # Configuration file
βββ data/
β βββ data_loader.py # Market data management
βββ fyers_api/
β βββ fyers_connector.py # Fyers API integration
βββ strategies/
β βββ base_strategy.py # Base strategy class
β βββ ma_crossover.py # MA Crossover strategy
β βββ vwap_bounce.py # VWAP Bounce strategy
β βββ rsi_price_action.py # RSI Price Action strategy
βββ backtest/
β βββ backtest_engine.py # Backtesting engine
βββ execution/
β βββ trade_manager.py # Live trading execution
βββ utils/
β βββ logger.py # Logging utilities
β βββ helpers.py # Helper functions
βββ logs/ # Log files
βββ main.py # Main application
The application includes comprehensive risk management features:
- Position Sizing: Dynamic calculation based on risk percentage
- Stop Loss: Automatic stop-loss placement
- Take Profit: Target-based profit taking
- Trailing Stop: Dynamic stop-loss adjustment
- Daily Loss Limits: Maximum daily loss protection
- Maximum Positions: Limit on concurrent positions
- Time-based Exits: Automatic exit at market close
The application provides detailed logging in multiple files:
trading_app.log: General application logserrors.log: Error and exception logstrades.log: Trade-specific logsbacktest_results_*.json: Backtest results
Run tests to verify functionality:
# Install test dependencies
pip install pytest pytest-cov
# Run tests
pytest trading_app/tests/ -v
# Run with coverage
pytest trading_app/tests/ --cov=trading_app --cov-report=html- Live trade execution status
- Current positions and P&L
- Strategy performance metrics
- Risk limit monitoring
- Total return and Sharpe ratio
- Win rate and profit factor
- Maximum drawdown analysis
- Trade-by-trade breakdown
- Create a new strategy class inheriting from
BaseStrategy - Implement required methods:
generate_signals(),should_buy(),should_sell() - Add strategy to the factory in
strategies/__init__.py - Configure parameters in
settings.yaml
from .base_strategy import BaseStrategy
class CustomStrategy(BaseStrategy):
def generate_signals(self, df):
# Your signal generation logic
return df
def should_buy(self, df, index):
# Your buy condition
return condition
def should_sell(self, df, index):
# Your sell condition
return conditionThis software is for educational and research purposes only. Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results.
This project is licensed under the MIT License - see the LICENSE file for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
For issues and questions:
- Create an issue on GitHub
- Check the documentation
- Review the logs for error details
Stay updated with the latest features:
- Monitor the repository for updates
- Review changelog for new features
- Test new versions in a safe environment
Happy Trading! π