Skip to content

haj8110/hd_trade

Repository files navigation

HD Trade Paper Trading Bot

A modular paper-trading bot for BankNifty/Nifty using Angel One SmartAPI with deterministic mock data fallback.

πŸš€ Features

  • Paper Trading Only: Safe trading simulation with no real money at risk
  • Angel One SmartAPI Integration: Real-time data feed with WebSocket support
  • Mock Data Fallback: Deterministic seeded RNG for testing and development
  • Breakout Strategy: EMA20 + Volume Spike + Price Breakout strategy
  • Risk Management: Position sizing, stop losses, and capital protection
  • IST Market Hours: Respects Indian market timing (09:30-14:30)
  • Comprehensive Logging: JSON trade logs and daily summaries
  • Unit Tests: Full test coverage for indicators and strategy logic

πŸ“‹ Prerequisites

  • Node.js 16+
  • Angel One SmartAPI credentials (optional, for live data)
  • npm or yarn

πŸ› οΈ Installation

  1. Clone the repository:
git clone <repository-url>
cd hd_trade
  1. Install dependencies:
npm install
  1. Copy environment file:
cp env.sample .env
  1. Configure your environment variables in .env:
# Angel One SmartAPI Configuration (optional)
ANGEL_ONE_API_KEY=your_api_key_here
ANGEL_ONE_CLIENT_ID=your_client_id_here
ANGEL_ONE_PASSWORD=your_password_here
ANGEL_ONE_TOTP_SECRET=your_totp_secret_here

# Trading Configuration
PAPER_TRADING=true
STARTING_CAPITAL=1000
MAX_LOSS_PER_TRADE=100
MAX_CONSECUTIVE_SL=3
MIN_CAPITAL=500

# Strategy Configuration
EMA_PERIOD=20
ATR_PERIOD=14
ATR_SL_MULTIPLIER=1.5
ATR_TARGET_MULTIPLIER=3.0
VOLUME_SPIKE_THRESHOLD=1.5

# Mock Data (for testing)
MOCK_DATA_ENABLED=true
MOCK_DATA_SEED=12345

🎯 Usage

Development Mode

npm run dev

Paper Trading Mode

npm run paper

Run Simulation

npm run simulate

Run Tests

npm test

Lint Code

npm run lint

Format Code

npm run format

πŸ“Š Strategy

The bot implements a breakout strategy with the following conditions:

Entry Conditions

  • Price Breakout: Current price breaks above previous 5-minute high
  • EMA Filter: Price must be above EMA20
  • Volume Spike: Current volume must be 1.5x above recent average

Exit Conditions

  • Stop Loss: 1.5 Γ— ATR(14) below entry price
  • Target: 3.0 Γ— ATR(14) above entry price
  • Time Exit: Force exit at 14:30 IST

Risk Management

  • Position Sizing: Based on max loss per trade (default β‚Ή100)
  • Capital Protection: Minimum capital threshold (default β‚Ή500)
  • Consecutive SL Limit: Stop trading after 3 consecutive stop losses
  • One Position: Maximum one position at a time

πŸ—οΈ Architecture

β”œβ”€β”€ index.js                 # Main application entry point
β”œβ”€β”€ config.js               # Configuration loader
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ priceFeed.js        # Price data feed (SmartAPI/Mock)
β”‚   β”œβ”€β”€ smartApiClient.js   # Angel One SmartAPI wrapper
β”‚   β”œβ”€β”€ strategyEngine.js   # Trading strategy logic
β”‚   β”œβ”€β”€ tradeEngine.js      # Position management
β”‚   β”œβ”€β”€ capitalManager.js   # Risk and capital management
β”‚   └── logger.js           # Trade logging and summaries
β”œβ”€β”€ utils/
β”‚   └── indicators.js       # Technical indicators (EMA, ATR, etc.)
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ trades.json         # Trade history log
β”‚   └── daily-summary-*.json # Daily performance summaries
β”œβ”€β”€ tests/                  # Unit tests
└── scripts/
    └── simulate.js         # Simulation runner

πŸ“ˆ Technical Indicators

  • EMA (Exponential Moving Average): Smooth price trend indicator
  • ATR (Average True Range): Volatility-based stop loss and target calculation
  • Average Volume: Volume spike detection for entry confirmation

πŸ”’ Safety Features

  • Paper Trading Default: All order execution is stubbed unless explicitly enabled
  • Live Trading Lock: Requires PAPER_TRADING=false AND LIVE_TRADING_UNLOCK="I-know-what-I-am-doing"
  • Market Hours: Respects IST trading windows
  • Capital Limits: Multiple safety checks prevent over-trading

πŸ“ Logging

Trade Logs

All trades are logged to data/trades.json with:

  • Entry/exit timestamps and prices
  • Stop loss and target levels
  • Trade result (TARGET HIT, SL HIT, TIME EXIT)
  • P&L and capital updates

Daily Summaries

Optional daily summaries include:

  • Win rate and total P&L
  • Trade breakdown and statistics
  • Drawdown analysis
  • Consecutive loss tracking

πŸ§ͺ Testing

Run the full test suite:

npm test

Run specific test files:

npm test -- tests/indicators.test.js
npm test -- tests/strategyEngine.test.js
npm test -- tests/capitalManager.test.js

Run simulation:

npm run simulate

πŸ“Š Simulation Results

The simulation script generates:

  • Mock trading day with 100+ candles
  • Real-time strategy signal generation
  • Position entry/exit simulation
  • Capital tracking and P&L calculation
  • JSON results file for analysis

⚠️ Important Notes

  1. Paper Trading Only: This bot is designed for paper trading and learning purposes
  2. No Financial Advice: This software is not financial advice
  3. Risk Warning: Trading involves risk of loss
  4. IST Timezone: All times are in Indian Standard Time
  5. Market Hours: Bot only trades during market hours (09:30-14:30 IST)

🀝 Contributing

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

πŸ“„ License

MIT License - see LICENSE file for details

πŸ†˜ Support

For issues and questions:

  1. Check the existing issues
  2. Create a new issue with detailed description
  3. Include logs and configuration details

Disclaimer: This software is for educational and paper trading purposes only. Trading involves risk of loss. Use at your own risk.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors