Skip to content

ghimirebibek/Stock

Repository files navigation

NEPSE Trading Bot

A comprehensive automated trading system for the Nepal Stock Exchange (NEPSE) that provides real-time technical analysis, trading signals, and portfolio management.

πŸš€ Features

Core Functionality

  • Real-time Data Fetching: Connects to NEPSE API for live market data
  • Technical Analysis: Comprehensive indicator analysis (RSI, MACD, Bollinger Bands, EMA, SMA)
  • Candlestick Pattern Recognition: Detects hammer, engulfing, morning star, evening star patterns
  • Signal Generation: BUY/SELL/HOLD signals with confidence scores
  • Position Sizing: Calculates optimal quantity based on capital and confidence

Advanced Features

  • Portfolio Management: Track positions, P&L, and performance
  • Discord Notifications: Real-time alerts for trading signals via Discord webhooks
  • Chart Generation: Professional technical analysis charts
  • Database Storage: SQLite database for historical data and signals
  • Automated Scheduling: Configurable analysis intervals

Risk Management

  • Stop Loss: Configurable stop loss percentages
  • Position Limits: Maximum position size per trade
  • Volume Filters: Minimum volume thresholds
  • Confidence Scoring: Only trade high-confidence signals

πŸ“‹ Requirements

  • Python 3.8+
  • NEPSE API access
  • Discord webhook (optional, for notifications)

πŸ› οΈ Installation

  1. Clone the repository

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

    pip install -r requirements.txt
  3. Configure environment variables Create a .env file:

    DISCORD_WEBHOOK_URL=your_discord_webhook_url
    DISCORD_USERNAME=NEPSE Trading Bot
    DISCORD_AVATAR_URL=your_avatar_url  # Optional
  4. Initialize the system

    python main.py --once

βš™οΈ Configuration

Edit config.py to customize:

  • Trading Parameters: Capital, position sizes, stop losses
  • Technical Indicators: RSI, MACD, Bollinger Bands settings
  • Analysis Settings: History days, symbol limits, intervals
  • Risk Management: Volume thresholds, confidence requirements

πŸš€ Usage

Run Once

python main.py --once

Run Scheduled

python main.py

Manual Analysis

from main import NepseTradingBot
import asyncio

async def analyze_symbol():
    bot = NepseTradingBot()
    result = await bot.analyze_symbol("NABIL")
    print(result)

asyncio.run(analyze_symbol())

πŸ“Š Signal Types

BUY Signals

  • RSI oversold (< 30)
  • MACD bullish crossover
  • Price below Bollinger lower band
  • Bullish candlestick patterns
  • High volume confirmation

SELL Signals

  • RSI overbought (> 70)
  • MACD bearish crossover
  • Price above Bollinger upper band
  • Bearish candlestick patterns
  • High volume confirmation

HOLD Signals

  • Mixed or neutral indicators
  • Low confidence scores
  • No clear pattern direction

πŸ“ˆ Technical Indicators

  • EMA (20): Exponential Moving Average
  • SMA (50, 200): Simple Moving Averages
  • RSI (14): Relative Strength Index
  • MACD: Moving Average Convergence Divergence
  • Bollinger Bands (20, 2): Volatility bands
  • Volume Analysis: Volume SMA and ratios
  • ATR (14): Average True Range

πŸ•―οΈ Candlestick Patterns

  • Hammer: Bullish reversal pattern
  • Shooting Star: Bearish reversal pattern
  • Doji: Indecision pattern
  • Bullish/Bearish Engulfing: Strong reversal signals
  • Morning/Evening Star: Three-candle reversal patterns

πŸ’° Portfolio Management

The system automatically:

  • Tracks all positions
  • Calculates P&L
  • Manages position sizes
  • Prevents duplicate positions
  • Records trade history

πŸ“± Telegram Notifications

Receive real-time alerts for:

  • Trading signals with details
  • Portfolio updates
  • Market summaries
  • Error notifications
  • System status

πŸ—„οΈ Database Schema

Tables

  • StockData: Historical price data
  • TradingSignal: Generated signals
  • Portfolio: Active positions
  • MarketSummary: Market statistics

πŸ“ Project Structure

nepse-trading-bot/
β”œβ”€β”€ main.py                 # Main application
β”œβ”€β”€ config.py              # Configuration settings
β”œβ”€β”€ requirements.txt       # Dependencies
β”œβ”€β”€ README.md             # This file
β”œβ”€β”€ data/
β”‚   └── nepse_api.py      # API client
β”œβ”€β”€ analysis/
β”‚   └── technical_indicators.py  # Technical analysis
β”œβ”€β”€ notifications/
β”‚   β”œβ”€β”€ discord_bot.py    # Discord notifications
β”‚   └── telegram_bot.py   # Telegram notifications (legacy)
β”œβ”€β”€ visualization/
β”‚   └── chart_generator.py # Chart generation
β”œβ”€β”€ database/
β”‚   └── models.py         # Database models
β”œβ”€β”€ charts/               # Generated charts
└── logs/                 # Log files

πŸ”§ Customization

Adding New Indicators

# In technical_indicators.py
def compute_indicators(self, df):
    # Add your custom indicator
    df['custom_indicator'] = your_calculation(df)
    return df

Custom Signal Logic

# In technical_indicators.py
def _generate_signal_for_row(self, df, index):
    # Add your custom signal logic
    if your_condition:
        return "BUY", confidence

New Notification Channels

# Create new notification class
class CustomNotifier:
    async def send_signal(self, signal_data):
        # Your notification logic
        pass

πŸ“Š Performance Metrics

The system tracks:

  • Total return
  • Win rate
  • Average P&L
  • Maximum drawdown
  • Sharpe ratio
  • Position duration

🚨 Risk Disclaimer

This software is for educational and research purposes only. Trading involves substantial risk of loss. Always:

  • Test thoroughly before live trading
  • Start with small positions
  • Monitor system performance
  • Have proper risk management
  • Consult financial advisors

🀝 Contributing

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

πŸ“„ License

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

πŸ†˜ Support

For issues and questions:

  1. Check the logs in logs/trading_bot.log
  2. Review configuration settings
  3. Test with --once flag first
  4. Create an issue with detailed error information

Discord Setup

For detailed Discord notification setup instructions, see DISCORD_SETUP.md.

πŸ”„ Updates

  • v1.0: Initial release with core functionality
  • v1.1: Added candlestick patterns
  • v1.2: Enhanced portfolio management
  • v1.3: Improved chart generation
  • v1.4: Added backtesting capabilities

Happy Trading! πŸ“ˆ

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors