Skip to content

credencewall/Trading-Algorithm

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CredenceWall Trading Algorithm

A Python-based algorithmic trading system for the Indian stock market (NSE). It focuses on NIFTY and BANKNIFTY options/futures trading with real-time data processing and strategy execution.

📋 Table of Contents

✨ Features

  • Real-time Market Data: WebSocket-based live data streaming from GDFL
  • Multiple Timeframes: 30s, 60s, 180s, 300s data resampling
  • Options Trading Strategies: NIFTY and BANKNIFTY options strategies
  • IV Calculation: Uses Black-Scholes model for implied volatility
  • Risk Management: Stop-loss, trailing stops, expiry-based exits
  • Telegram Notifications: Real-time alerts for trades and system status
  • Scheduled Execution: Time-based triggers using APScheduler

🔧 Prerequisites

  • Python 3.7 or higher
  • MongoDB (installed and running)
  • Access to GDFL market data API
  • Zerodha API credentials (optional, for alternative data source)
  • Telegram Bot Token and Channels (for notifications)

📦 Installation

1. Clone the Repository

git clone <repository-url>
cd Trading-Algorithm

2. Create Virtual Environment (Recommended)

# Windows
python -m venv venv
venv\Scripts\activate

# Linux/Mac
python3 -m venv venv
source venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

Note: If requirements.txt is not available, install the following packages:

pip install motor pandas numpy asyncio websocket-client mibian APScheduler python-telegram-bot python-dotenv schedule dateutil

⚙️ Configuration

1. Install python-dotenv

pip install python-dotenv

2. Create Configuration File

Copy the example configuration file:

copy appConfig.example.py appConfig.py

Linux/Mac:

cp appConfig.example.py appConfig.py

3. Create .env File

Create a .env file in the project root directory with your credentials:

# MongoDB Configuration
MONGODB_USER=your_mongodb_username
MONGODB_PASSWORD=your_mongodb_password
MONGODB_HOST=127.0.0.1
MONGODB_PORT=27016
MONGODB_DATABASE=credencewall

# Telegram Configuration
TELEGRAM_BOT_TOKEN=your_telegram_bot_token
TELEGRAM_CHANNEL_MONITOR=@your_monitor_channel
TELEGRAM_CHANNEL_SE=@your_se_channel
TELEGRAM_CHANNEL_CP=@your_cp_channel
TELEGRAM_CHANNEL_ID=@your_id_channel

# GDFL API Configuration
GDFL_API_KEY=your_gdfl_api_key
GDFL_WEBSOCKET_ENDPOINT=ws://your-gdfl-endpoint:port

# Zerodha API Configuration (Optional)
ZERODHA_USER_ID=your_zerodha_user_id
ZERODHA_API_KEY=your_zerodha_api_key
ZERODHA_API_SECRET=your_zerodha_api_secret
ZERODHA_PASSWORD=your_zerodha_password
ZERODHA_PIN=your_zerodha_pin

# MySQL Configuration (If used)
MYSQL_HOST=your_mysql_host
MYSQL_PORT=3306
MYSQL_USER=your_mysql_user
MYSQL_PASSWORD=your_mysql_password
MYSQL_DATABASE=your_mysql_database

4. Update appConfig.py (if needed)

Edit appConfig.py and ensure it's configured to load environment variables. The file should already be set up to use python-dotenv if available.

🚀 Running the System

The system consists of multiple scripts that need to be run in a specific order or as separate processes.

Daily Initialization

Run this first to update exchange data and instruments:

python main_001_GDailyInit.py

Alternative (Zerodha):

python main_001_ZDailyInit.py

Live Data Collection

Start collecting real-time market data:

python main_002_GDailyLiveTicks.py

Alternative (Zerodha):

python main_002_ZDailyLiveTicks.py

Data Resampling

Convert raw ticks into OHLCV candles:

30-second resampling:

python main_003_GDataResample_30Sec_v5.py

60-second resampling:

python main_004_GDataResample_60Sec_v2.py

Strategy Execution

Run trading strategies:

Short Expiry Strategy (300-second intervals):

python main_005_GSolverSE_300Sec_v2.py

Call/Put Strategy (180-second intervals):

python main_006_GSolverCP_180Sec_v2.py

Intraday ID Strategy:

python main_007_QStrategy_ID_v1.py

Production Deployment (Linux)

For production, use systemd services (if configured):

# Start services
sudo systemctl start qchGDFL-Live.service
sudo systemctl start qchGDFL-LiveResample30Sec.service
sudo systemctl start qchGDFL-LiveResample60Sec.service
sudo systemctl start qchGDFL-LiveStrategySE300Sec.service
sudo systemctl start qchGDFL-LiveStrategyCP180Sec.service

# Enable auto-start on boot
sudo systemctl enable qchGDFL-Live.service

📁 Project Structure

Trading-Algorithm/
├── main_001_GDailyInit.py          # Daily initialization
├── main_002_GDailyLiveTicks.py     # Live data collection
├── main_003_GDataResample_30Sec_v5.py  # 30s resampling
├── main_004_GDataResample_60Sec_v2.py  # 60s resampling
├── main_005_GSolverSE_300Sec_v2.py     # SE strategy execution
├── main_006_GSolverCP_180Sec_v2.py     # CP strategy execution
├── main_007_QStrategy_ID_v1.py         # ID strategy execution
├── appConfig.py                     # Configuration (use .env)
├── appConfig.example.py             # Configuration template
├── .env                             # Environment variables (create this)
├── .gitignore                       # Git ignore rules
├── Sources/                         # Data source implementations
│   ├── GDFL/                       # GDFL data source
│   └── ZERO/                       # Zerodha data source
├── SolverStrategies/               # Strategy framework
│   ├── BaseStrategy.py            # Base strategy engine
│   ├── Strategies.py              # Strategy implementations
│   ├── Rules.py                   # Trade rule definitions
│   └── Enums.py                   # Trading enums
├── Channels/                       # Notification channels
│   └── TelegramChannel.py         # Telegram integration
├── Utils/                          # Utility modules
│   └── BrokerUtils/               # Broker utilities
└── Linux/                          # Systemd service files

🏗️ Architecture

The system follows a multi-stage pipeline:

  1. Daily Initialization: Updates exchange data and instruments from GDFL
  2. Live Tick Collection: Subscribes to real-time market data via WebSocket
  3. Data Resampling: Converts raw ticks into OHLCV candles (30s, 60s intervals)
  4. Strategy Execution: Implements entry/exit rules, stop-loss, trailing stops
  5. Notifications: Sends alerts via Telegram

Data Flow

Market Data (GDFL/Zerodha)
    ↓
Raw Ticks (MongoDB)
    ↓
Resampled Candles (30s, 60s)
    ↓
Strategy Evaluation
    ↓
Trade Signals → Telegram Notifications

🔒 Security Notes

⚠️ Important Security Reminders

  1. Never commit .env file: The .env file contains sensitive credentials and is excluded via .gitignore

  2. Rotate exposed credentials: If any credentials were previously committed to version control, rotate them immediately

  3. Use environment variables: All credentials should be stored in the .env file, never hardcoded in the code

  4. Review git history: If this code was previously committed with credentials, clean the git history

  5. Production deployment: For production, consider using:

    • AWS Secrets Manager
    • HashiCorp Vault
    • Azure Key Vault
    • Or similar secrets management solutions

Environment Variables Required

See the Configuration section above for the complete list of required environment variables.

🐛 Troubleshooting

MongoDB Connection Issues

Problem: Cannot connect to MongoDB

Solution:

  • Ensure MongoDB is running: mongod --version
  • Check MongoDB connection settings in .env
  • Verify network connectivity to MongoDB host
  • Check MongoDB logs for authentication errors

Telegram Bot Issues

Problem: Telegram notifications not working

Solution:

  • Verify bot token is correct
  • Ensure bot is added as administrator to channels
  • Check bot has "Post Messages" permission
  • Verify channel usernames are correct (include @ symbol)

GDFL API Connection Issues

Problem: Cannot connect to GDFL WebSocket

Solution:

  • Verify GDFL API key is correct
  • Check WebSocket endpoint URL
  • Ensure network connectivity to GDFL servers
  • Verify API key permissions

Module Import Errors

Problem: ModuleNotFoundError when running scripts

Solution:

  • Ensure virtual environment is activated
  • Install all requirements: pip install -r requirements.txt
  • Check Python path is correct
  • Verify all dependencies are installed

Database Name Errors

Problem: Database name errors or collection not found

Solution:

  • Check MONGODB_DATABASE in .env file
  • Verify database exists in MongoDB
  • Run initialization script first: python main_001_GDailyInit.py
  • Check database collections are created

📝 Additional Resources

📄 License

[Add your license information here]

🤝 Contributing

[Add contributing guidelines if applicable]

📧 Support

[Add support contact information if applicable]


Note: This is a production trading system. Always test thoroughly in a paper trading environment before using with real funds. Use at your own risk.

About

Live Trading Algorithm

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages