Skip to main content

A high-performance algorithmic trading platform for Indian stock markets

Project description

ZebuBot - Advanced Algorithmic Trading Platform

Python Version License MyntAPI PyPI

ZebuBot is a high-performance algorithmic trading platform designed specifically for Indian stock markets via MyntAPI (Noren). It provides a flexible framework for creating custom trading strategies with real-time data processing, technical indicators, and automated order execution.

๐ŸŽฏ Quick Installation

pip install zebubot

๐Ÿš€ CLI Commands

ZebuBot comes with a powerful command-line interface:

# Create and run a trading strategy
zebubot create option_trading_strategy

# List available strategies
zebubot strategy list

# Create new strategies
zebubot strategy create my_strategy --type rsi

# Show help
zebubot --help

๐Ÿš€ Key Features

  • ๐Ÿš€ CLI Interface: Easy-to-use command-line tools for strategy management
  • โšก Auto-Configuration: Automatic config file creation with smart templates
  • ๐Ÿ” Credentials Management: Support for JSON credentials files and interactive setup
  • ๐Ÿ“Š Real-time Data: WebSocket + Polling fallback for reliable data feeds
  • โšก Cython Optimization: High-performance technical indicator calculations
  • ๐Ÿ“ˆ Historical Data: Automatic loading of 30 days historical data for accurate indicators
  • ๐ŸŽฏ Multi-Symbol Trading: Trade multiple symbols simultaneously
  • ๐Ÿ›ก๏ธ Risk Management: Built-in position sizing and risk controls
  • โš™๏ธ Flexible Configuration: YAML-based strategy configuration
  • ๐Ÿ‡ฎ๐Ÿ‡ณ MyntAPI Integration: Seamless integration with Indian stock markets
  • ๐Ÿ“ Script Priority System: Intelligent script discovery with package priority

๐Ÿ“Š Performance

  • Cython Optimized: Up to 10x faster indicator calculations
  • Real-time Processing: Sub-millisecond tick processing
  • Memory Efficient: Automatic data management with deque buffers
  • Scalable: Handle multiple symbols and strategies simultaneously

๐Ÿ› ๏ธ Quick Start

Installation

Option 1: Install from PyPI (Recommended)

pip install zebubot

Option 2: Install from source

git clone https://github.com/your-username/zebubot.git
cd zebubot
pip install -e .

Your First Strategy

1. Create a strategy using CLI:

# Create an RSI strategy
zebubot strategy create my_rsi_strategy --type rsi

# Or create an option trading strategy
zebubot strategy create my_option_strategy --type option_trading

2. Run your strategy:

# Run with interactive credential setup
zebubot create my_rsi_strategy

# Or run with credentials file
zebubot create my_rsi_strategy --credentials=my_credentials.json

3. List available strategies:

zebubot strategy list

Configuration Management

Automatic Configuration:

  • Config files are created automatically when missing
  • Option trading strategies get specialized config templates
  • Other strategies get default RSI/SMA/MACD configs

Manual Configuration:

# configs/my_strategy.yaml
symbols:
  - NSE:RELIANCE-EQ
exchange: myntapi
strategy:
  rsi_period: 14
  sma_fast: 20
  sma_slow: 50
risk:
  min_position_inr: 1000
  max_position_pct: 0.02

Credentials Setup:

// credentials.json
{
  "api_secret": "your_api_secret",
  "password": "your_password",
  "twoFA": "your_2fa_code",
  "userid": "your_user_id",
  "vendor_code": "your_vendor_code"
}

๐Ÿ“š CLI Commands Reference

Main Commands

# Create and run a trading strategy
zebubot create <script_name> [OPTIONS]

# Strategy management
zebubot strategy list                    # List available strategies
zebubot strategy create <name> [OPTIONS] # Create new strategy
zebubot strategy option <name>           # Create option trading strategy

# Configuration management
zebubot config init                      # Initialize configuration
zebubot config validate                  # Validate configuration

Create Command Options

zebubot create <script_name> [OPTIONS]

Options:
  -t, --template TEXT      Template to use for the script
  -o, --output-dir TEXT    Output directory for scripts (default: scripts)
  -c, --config TEXT        Configuration file path (default: zebubot_config.yaml)
  --credentials TEXT       JSON file containing MyntAPI credentials
  --help-strategies        Show available strategies and exit

Strategy Types

# Available strategy types
zebubot strategy create <name> --type basic           # Basic strategy template
zebubot strategy create <name> --type rsi             # RSI-based strategy
zebubot strategy create <name> --type moving_average  # Moving average strategy
zebubot strategy create <name> --type option_trading  # Option trading strategy
zebubot strategy create <name> --type custom          # Custom strategy template

๐Ÿ“š Documentation

๐Ÿ—๏ธ Architecture

ZebuBot Core
โ”œโ”€โ”€ ๐Ÿš€ CLI Interface (Command-line tools)
โ”œโ”€โ”€ โš™๏ธ Configuration Manager (Auto-config creation)
โ”œโ”€โ”€ ๐Ÿ” Credentials Manager (JSON & interactive setup)
โ”œโ”€โ”€ ๐Ÿ“Š MyntAPI Integration (Real-time data & orders)
โ”œโ”€โ”€ ๐ŸŽฏ Symbol Manager (Symbol lookup & conversion)
โ”œโ”€โ”€ โšก Performance Engine (Cython-optimized calculations)
โ”œโ”€โ”€ ๐Ÿ“ Script Manager (Priority-based script discovery)
โ”œโ”€โ”€ ๐ŸŽฎ Strategy Executor (Your custom strategy)
โ””โ”€โ”€ ๐Ÿ›ก๏ธ Risk Manager (Position sizing & controls)

๐Ÿ“ˆ Available Indicators

  • RSI (Relative Strength Index)
  • SMA (Simple Moving Average)
  • EMA (Exponential Moving Average)
  • Bollinger Bands
  • MACD (Moving Average Convergence Divergence)
  • Custom Indicators (Easy to add)

๐Ÿ”ง Configuration

Automatic Configuration

ZebuBot automatically creates configuration files when missing:

Option Trading Strategies:

# Auto-created for option_trading_strategy.py
exchange: myntapi
strategy:
  start_time: "18:21:00"
  end_time: "22:45:10"
  square_off_time: "22:03:30"
  overall_target: 1000
  overall_stop_loss: 1000
  idx_pair: "NSE:NIFTY 50"
  legs:
    1:
      exch: "NFO"
      symbol: "NIFTY"
      expiry: "16-09-2025"
      option_type: "CE"
      lot_size: 10
      # ... more legs

Default Strategies:

# Auto-created for other strategies
symbols:
  - NSE:SBIN-EQ
exchange: myntapi
strategy:
  rsi_period: 14
  sma_fast: 20
  sma_slow: 50
  bb_period: 20
  bb_stddev: 2.0
  macd_fast: 12
  macd_slow: 26
  macd_signal: 9
risk:
  min_position_inr: 1000
  max_position_pct: 0.04

Manual Configuration

symbols:
  - NSE:RELIANCE-EQ
  - NSE:TCS-EQ
exchange: myntapi
strategy:
  rsi_period: 14
  sma_fast: 20
  sma_slow: 50
  bb_period: 20
  bb_stddev: 2.0
  macd_fast: 12
  macd_slow: 26
  macd_signal: 9
  additional_symbols:
    - NSE:INFY-EQ
    - NSE:HINDUNILVR-EQ
risk:
  min_position_inr: 1000
  max_position_pct: 0.04
  additional_symbol_position_pct: 0.005
  stop_loss_pct: 0.02
  take_profit_pct: 0.04

๐ŸŽฏ Example Strategies

1. Create and Run RSI Strategy

# Create RSI strategy
zebubot strategy create my_rsi --type rsi

# Run with credentials
zebubot create my_rsi --credentials=my_creds.json

2. Option Trading Strategy

# Create option trading strategy
zebubot strategy create my_options --type option_trading

# Run the strategy
zebubot create my_options

3. Custom Strategy Development

# scripts/my_custom_strategy.py
from collections import deque
import pandas as pd

price_history = deque(maxlen=1000)
rsi_period = 14
last_signal = None

def calculate_rsi(prices, period=14):
    if len(prices) < period + 1:
        return None
    delta = pd.Series(prices).diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi.iloc[-1]

def on_tick(symbol, ticker_data):
    global last_signal
    
    current_price = ticker_data.get('price', 0)
    price_history.append(current_price)
    
    if len(price_history) >= rsi_period + 1:
        prices = list(price_history)
        rsi = calculate_rsi(prices, rsi_period)
        
        if rsi is not None:
            if rsi < 30 and last_signal != 'BUY':
                print(f"๐ŸŸข BUY Signal! RSI: {rsi:.2f}")
                last_signal = 'BUY'
                place_order(symbol, 'buy', 10, current_price, 'limit', 'myntapi')
            elif rsi > 70 and last_signal != 'SELL':
                print(f"๐Ÿ”ด SELL Signal! RSI: {rsi:.2f}")
                last_signal = 'SELL'
                place_order(symbol, 'sell', 10, current_price, 'limit', 'myntapi')

def main():
    on_tick(current_symbol, ticker_data)

4. Multi-Indicator Strategy

def on_tick(symbol, ticker_data):
    current_price = ticker_data.get('price', 0)
    price_history.append(current_price)
    
    if len(price_history) >= 50:
        prices = list(price_history)
        
        # Calculate multiple indicators
        rsi = calculate_rsi(prices, 14)
        sma_20 = calculate_sma(prices, 20)
        bb_upper, bb_middle, bb_lower = calculate_bollinger_bands(prices, 20, 2.0)
        macd, macd_signal, macd_hist = calculate_macd(prices, 12, 26, 9)
        
        # Count signals
        bullish_signals = 0
        if rsi and rsi < 30:
            bullish_signals += 1
        if sma_20 and current_price > sma_20:
            bullish_signals += 1
        if bb_lower and current_price < bb_lower:
            bullish_signals += 1
        if macd and macd_signal and macd > macd_signal:
            bullish_signals += 1
        
        # Generate signal based on confirmation
        if bullish_signals >= 3 and last_signal != 'BUY':
            print(f"๐ŸŸข Strong BUY Signal! ({bullish_signals}/4 confirmations)")
            last_signal = 'BUY'
            place_order(symbol, 'buy', 10, current_price, 'limit', 'myntapi')

๐Ÿš€ Performance Optimization

Cython Integration

ZebuBot includes Cython-optimized functions for maximum performance:

try:
    from zebubot.performance import (
        calculate_rsi_fast,
        calculate_sma_fast,
        calculate_ema_fast,
        calculate_bollinger_bands_fast,
        calculate_macd_fast,
        process_ticker_data_fast
    )
    CYTHON_AVAILABLE = True
except ImportError:
    CYTHON_AVAILABLE = False

Memory Management

from collections import deque
import numpy as np

# Use deque for efficient price history
price_history = deque(maxlen=1000)  # Automatically removes old data

# Use numpy arrays for calculations
prices_array = np.array(price_list, dtype=np.float64)

๐Ÿ”’ Risk Management

Built-in Risk Controls

  • Position Sizing: Dynamic position sizing based on signal strength
  • Margin Management: Automatic margin calculation and monitoring
  • Stop Loss: Configurable stop loss percentages
  • Take Profit: Configurable take profit percentages
  • Maximum Position: Limits on maximum position size

Risk Management Example

def calculate_position_size(signal_strength, available_margin):
    base_size = available_margin * 0.01  # 1% base
    signal_multiplier = min(signal_strength / 4.0, 1.0)  # Max 4x
    position_size = base_size * signal_multiplier
    
    # Apply risk limits
    max_size = available_margin * risk.get('max_position_pct', 0.04)
    min_size = risk.get('min_position_inr', 1000)
    
    return max(min_size, min(position_size, max_size))

๐Ÿ“Š Real-time Data

Data Sources

  • Primary: MyntAPI WebSocket feed
  • Fallback: MyntAPI REST API polling
  • Historical: MyntAPI tpseries endpoint

Data Format

ticker_data = {
    'symbol': 'NSE:RELIANCE-EQ',
    'price': 2450.50,
    'volume': 1500000,
    'timestamp': 1699123456789,
    'high': 2460.00,
    'low': 2440.00,
    'open': 2445.00,
    'close': 2450.50
}

๐Ÿ› ๏ธ Development

Project Structure

zebubot/
โ”œโ”€โ”€ zebubot/                 # Core library
โ”‚   โ”œโ”€โ”€ cli.py              # Command-line interface
โ”‚   โ”œโ”€โ”€ myntapi_integration.py
โ”‚   โ”œโ”€โ”€ symbol_manager.py
โ”‚   โ”œโ”€โ”€ performance.pyx      # Cython optimizations
โ”‚   โ””โ”€โ”€ scripts/            # Built-in strategy scripts
โ”‚       โ”œโ”€โ”€ option_trading_strategy.py
โ”‚       โ””โ”€โ”€ myntapi_rsi_optimized.py
โ”œโ”€โ”€ scripts/                 # User strategy scripts
โ”‚   โ”œโ”€โ”€ myntapi_rsi_optimized.py
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ configs/                 # Configuration files
โ”‚   โ”œโ”€โ”€ option_trading_strategy.yaml
โ”‚   โ”œโ”€โ”€ myntapi_rsi_optimized.yaml
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ docs/                    # Documentation
โ”‚   โ”œโ”€โ”€ QUICK_START_GUIDE.md
โ”‚   โ”œโ”€โ”€ STRATEGY_DEVELOPMENT_GUIDE.md
โ”‚   โ””โ”€โ”€ API_REFERENCE.md
โ”œโ”€โ”€ templates/               # Strategy templates
โ”‚   โ”œโ”€โ”€ option_trading_strategy_template.yaml
โ”‚   โ”œโ”€โ”€ option_trading_strategy_template.py
โ”‚   โ””โ”€โ”€ generate_strategy.py
โ””โ”€โ”€ tests/                   # Test files

Script Priority System

ZebuBot uses an intelligent script discovery system:

  1. First Priority: zebubot/scripts/ (built-in package scripts)
  2. Second Priority: scripts/ (user scripts directory)
  3. Third Priority: Specified output directory
  4. Fallback: Current directory and parent directories

This ensures built-in strategies are always available while allowing user customization.

Building Cython Extensions

# Build Cython extensions
python setup_cython.py build_ext --inplace

# Or use the build script
python build_cython.py

Running Tests

python -m pytest tests/

๐ŸŽฏ Advanced Features

Auto-Configuration System

  • Smart Detection: Automatically detects script type and creates appropriate config
  • Option Trading: Full option trading config with legs, expiry, and premium settings
  • Default Strategies: RSI, SMA, Bollinger Bands, MACD configurations
  • Template System: Pre-built templates for common strategy types

Credentials Management

  • JSON Support: Load credentials from JSON files
  • Interactive Setup: Prompt-based credential entry
  • Security: Password hiding and secure storage
  • Validation: Automatic validation of required fields

CLI Features

  • Strategy Creation: Create strategies with different types
  • Script Discovery: Intelligent script finding with priority system
  • Configuration Management: Auto-create and validate configs
  • Help System: Comprehensive help and documentation

๐Ÿ“„ License

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

โš ๏ธ 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 is not indicative of future results. Always do your own research and consider consulting with a financial advisor before making investment decisions.

๐Ÿ“ž Support

  • Documentation: Check the docs/ directory
  • CLI Help: Use zebubot --help for command reference
  • Issues: Report bugs and request features on GitHub
  • Community: Join our Discord/Telegram group

๐Ÿ™ Acknowledgments

  • MyntAPI (Noren) for providing the trading API
  • The Python community for excellent libraries
  • Contributors and users who help improve ZebuBot

Happy Trading! ๐Ÿš€๐Ÿ“ˆ

Built with โค๏ธ for the Indian trading community

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zebubot-0.0.1b8.tar.gz (79.1 kB view details)

Uploaded Source

File details

Details for the file zebubot-0.0.1b8.tar.gz.

File metadata

  • Download URL: zebubot-0.0.1b8.tar.gz
  • Upload date:
  • Size: 79.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for zebubot-0.0.1b8.tar.gz
Algorithm Hash digest
SHA256 cebdc8a904e488db93982b7e3e7d0c249304efc572ff0cbd9540d79ff9d344e1
MD5 49e7f1d4fda7e6ef4a8aaf635866bd78
BLAKE2b-256 681f90fe7ebddca3ea746c9441723c1f243ebf3a90911440ce940fbcccbaf3e5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page