Skip to content

A robust, modular, and scalable Python-based automatic intraday trading application using the Fyers API for Indian stock markets.

License

Notifications You must be signed in to change notification settings

alwin48/fyers-trading-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Fyers Trading Bot

A robust, modular, and scalable Python-based automatic intraday trading application using the Fyers API for Indian stock markets.

🎯 Features

  • 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

πŸ“¦ Installation

Prerequisites

  • Python 3.9+
  • Fyers API credentials
  • pip package manager

Setup

  1. Clone the repository

    git clone <repository-url>
    cd fyers-trading-bot
  2. Install dependencies

    pip install -r requirements.txt
  3. Configure environment variables

    cp env_template.txt .env

    Edit .env file 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
  4. Configure settings

    Edit trading_app/config/settings.yaml to customize:

    • Trading parameters (capital, risk limits)
    • Strategy configurations
    • Risk management settings
    • Logging preferences

πŸ”§ Configuration

Fyers API Setup

  1. Create Fyers App

  2. Generate Access Token

    • Use the Fyers API to generate an access token
    • Add the token to your .env file

Strategy Configuration

The application includes three pre-built strategies:

1. Moving Average Crossover

  • Parameters: short_window, long_window, ma_type (SMA/EMA)
  • Logic: Buy when short MA crosses above long MA, sell on reverse

2. VWAP Bounce

  • Parameters: vwap_period, bounce_threshold, rsi_period
  • Logic: Buy when price bounces from below VWAP with RSI confirmation

3. RSI Price Action

  • Parameters: rsi_period, rsi_oversold, rsi_overbought
  • Logic: Buy on RSI oversold with price action confirmation

πŸš€ Usage

Command Line Interface

1. Test Connection

python -m trading_app.main --mode test

2. View Available Strategies

python -m trading_app.main --mode strategies

3. View Configured Symbols

python -m trading_app.main --mode symbols

4. Run Backtest

python -m trading_app.main --mode backtest \
    --symbol NIFTY \
    --strategy ma_crossover \
    --start-date 2024-01-01 \
    --end-date 2024-01-31 \
    --timeframe 5min

5. Live Trading

python -m trading_app.main --mode live \
    --symbols NIFTY BANKNIFTY \
    --strategies ma_crossover vwap_bounce

6. View Performance

python -m trading_app.main --mode performance

Python API

from 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"]
)

πŸ“Š Backtesting Results

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

Sample Backtest Report

==================================================
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
==================================================

πŸ—οΈ Architecture

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

πŸ”’ Risk Management

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

πŸ“ Logging

The application provides detailed logging in multiple files:

  • trading_app.log: General application logs
  • errors.log: Error and exception logs
  • trades.log: Trade-specific logs
  • backtest_results_*.json: Backtest results

πŸ§ͺ Testing

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

πŸ“ˆ Performance Monitoring

Real-time Monitoring

  • Live trade execution status
  • Current positions and P&L
  • Strategy performance metrics
  • Risk limit monitoring

Performance Metrics

  • Total return and Sharpe ratio
  • Win rate and profit factor
  • Maximum drawdown analysis
  • Trade-by-trade breakdown

πŸ”§ Customization

Adding New Strategies

  1. Create a new strategy class inheriting from BaseStrategy
  2. Implement required methods: generate_signals(), should_buy(), should_sell()
  3. Add strategy to the factory in strategies/__init__.py
  4. Configure parameters in settings.yaml

Example Custom Strategy

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 condition

⚠️ Disclaimer

This 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.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

πŸ“ž Support

For issues and questions:

  • Create an issue on GitHub
  • Check the documentation
  • Review the logs for error details

πŸ”„ Updates

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! πŸ“ˆ

About

A robust, modular, and scalable Python-based automatic intraday trading application using the Fyers API for Indian stock markets.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages