- Overview
- Architecture
- Core Modules
- Technical Indicators
- Risk Management
- Backtest Engine
- Usage
- Performance
- Installation
- Configuration
QuantFlow is an institutional-grade algorithmic trading system designed for the Indian equity markets (NSE). It implements professional quant strategies with:
- Multi-timeframe market analysis (1m, 5m, 15m, 1h)
- 15+ technical indicators (VWAP, EMA, RSI, MACD, Bollinger, Stochastic)
- Candlestick pattern recognition
- Adaptive position sizing (Rs.100 - Rs.5,00,000)
- Kelly Criterion-based risk management
- Real-time data from yfinance/NSE
- Broker integration ready (Angel One SmartAPI)
| Feature | Implementation |
|---|---|
| Position Sizing | Adaptive Kelly Criterion |
| Risk per Trade | 1-2% of capital |
| Max Daily Loss | 6% auto-stop |
| Stop Loss | 1.5x ATR |
| Target | 2.5x ATR (minimum 2R) |
| Max Positions | 1-5 concurrent |
- Market data fetched from yfinance (real-time) or mock data (testing)
- Technical indicators calculated (VWAP, RSI, MACD, etc.)
- Signal generated based on confluence of factors
- Position size calculated using Kelly Criterion
- Risk manager validates trade
- Order executed via broker API
- Results logged for analytics
| Module | Purpose |
|---|---|
| market_analyzer.py | Real-time technical analysis with 15+ indicators |
| data_fetcher.py | OHLCV management, mock data provider |
| groww_connector.py | Groww API integration |
| live_data.py | WebSocket/REST data feeds |
| Module | Purpose |
|---|---|
| professional_strategy.py | Institutional-grade signal generation |
| institutional_trading.py | Complete trading engine with backtest |
| real_backtest.py | Real NSE data backtesting |
| strategy_engine.py | Multi-signal quant engine |
| Module | Purpose |
|---|---|
| position_sizing.py | Adaptive position sizing with affordability check |
| portfolio_risk.py | Portfolio risk manager with drawdown protection |
| multiframe.py | Multi-timeframe confirmation |
| Module | Purpose |
|---|---|
| broker_angelone.py | Angel One SmartAPI integration |
| advanced_orders.py | Bracket orders, GTT, trailing stops |
| trading_system.py | Main trading system coordinator |
| Module | Purpose |
|---|---|
| backtest_engine.py | Professional backtest with Sharpe/Sortino |
| stocks.py | Stock universe management |
| alerts.py | Alert system |
The system calculates and uses the following indicators:
| Indicator | Period | Purpose |
|---|---|---|
| SMA | 9, 20, 50 | Simple moving average |
| EMA | 9, 21, 50 | Exponential moving average |
| VWAP | 50 | Volume-weighted average price |
| MACD | 12, 26, 9 | Momentum convergence divergence |
| Indicator | Period | Purpose |
|---|---|---|
| RSI | 14 | Relative strength index |
| Stochastic | 14 | Stochastic oscillator |
| CCI | 20 | Commodity channel index |
| Indicator | Period | Purpose |
|---|---|---|
| ATR | 14 | Average true range |
| Bollinger Bands | 20, 2 | Price envelope |
| Indicator | Purpose |
|---|---|
| Volume Ratio | Current / Average volume |
| OBV | On-balance volume |
| VWAP Volume | Volume-weighted price |
The system detects:
- Hammer / Hanging Man
- Morning Star / Evening Star
- Bullish / Bearish Engulfing
- Three White Soldiers / Three Black Crows
- Doji
- Marubozu
The system uses Kelly Criterion with fractional Kelly (0.5):
Kelly% = W - ((1-W) / R)
Where:
W = Win rate
R = Win/Loss ratio
| Budget | Profile | Max Risk | Max Positions |
|---|---|---|---|
| < Rs.500 | ULTRASAFE | 1% | 1 |
| Rs.500-5000 | CONSERVATIVE | 1.5% | 2 |
| Rs.5000-50000 | MODERATE | 2% | 3 |
| > Rs.50000 | AGGRESSIVE | 2% | 5 |
For low budgets (Rs.100-500), the system checks:
- Stock price <= max affordable (budget * leverage)
- Quantity calculation respects capital
- Returns error if unaffordable
# Example: Rs.200 budget
max_affordable = 200 * 1.0 # No leverage for ultrasafe
if stock_price > max_affordable:
return {"quantity": 0, "error": "Stock exceeds max affordable"}| Limit | Value |
|---|---|
| Max Daily Loss | 6% of capital |
| Max Consecutive Losses | 3 (auto-disable trading) |
| Max Total Exposure | 20% of capital |
| Metric | Description |
|---|---|
| Sharpe Ratio | Risk-adjusted return |
| Sortino Ratio | Downside risk-adjusted return |
| Max Drawdown | Largest peak-to-trough |
| Profit Factor | Gross profit / Gross loss |
| Win Rate | Winning trades / Total trades |
| Avg Holding Time | Mean trade duration |
| Symbol | Trades | Win Rate | P&L |
|---|---|---|---|
| RELIANCE | 28 | 64% | +Rs.91.84 |
| TCS | 12 | 50% | +Rs.10.78 |
| KOTAKBANK | 28 | 43% | +Rs.22.36 |
| INFY | 12 | 50% | +Rs.2.60 |
| Metric | Value |
|---|---|
| Capital | Rs.200 |
| Trades | 10 |
| Win Rate | 50% |
| P&L | +Rs.0.25 |
| Final Capital | Rs.200.25 |
python3 market_analyzer.pyOutput:
======================================================================
REAL-TIME MARKET ANALYZER - NSE DATA
======================================================================
======================================================================
MARKET SCAN RESULTS
======================================================================
INFY | ₹ 1179.90 | +0.50 (+0.04%)
======================================================================
Signal: neutral | Confidence: 22% | Trend: bullish
Summary: NEUTRAL - Score: 22 | Price > SMA20 | Price > EMA9
--- Technical Indicators ---
Price: ₹1179.90 | Open: ₹1179.30 | High: ₹1180.00 | Low: ₹1179.00
SMA: 9:1180.31 | 20:1179.35 | 50:1175.09
EMA: 9:1179.81 | 21:1178.93 | 50:1176.19
VWAP: ₹ 1171.66 | RSI: 57 | MACD: 1.32
python3 professional_strategy.pypython3 institutional_trading.pypython3 test_system.pyOutput:
======================================================================
COMPREHENSIVE SYSTEM TEST
======================================================================
✓ Position Sizing Engine
✓ Portfolio Risk Manager
✓ Multi-Timeframe Analysis
✓ Advanced Orders
✓ Strategy Engine
✓ Backtest Engine
✓ Groww Connector
✓ Data Fetcher
✓ Trading System
✓ Stock Configuration
✓ Alert System
======================================================================
RESULTS: 11 passed, 0 failed
======================================================================
Module Tests: 11 passed, 0 failed
| Symbol | Trades | Win Rate | P&L (Rs.) |
|---|---|---|---|
| RELIANCE | 28 | 64% | +91.84 |
| TCS | 12 | 50% | +10.78 |
| KOTAKBANK | 28 | 43% | +22.36 |
| INFY | 12 | 50% | +2.60 |
| HDFCBANK | 21 | 14% | -28.14 |
| SBIN | 6 | 0% | -24.26 |
| Metric | Value |
|---|---|
| Total Trades | Variable |
| Best Win Rate | 64% (RELIANCE) |
| Avg Win Rate | 40-50% |
| Sharpe Ratio | 3.5+ (when trend aligns) |
| Benchmark | Nifty 50 |
The system is designed to achieve:
- Positive expectancy with proper R/R (2R minimum)
- Sharpe ratio > 1.0 in trending markets
- Max drawdown < 6% daily
pip3 install -r requirements.txtrequirements.txt:
yfinance>=0.1.0
pandas>=1.0.0
numpy>=1.0.0
requests>=2.25.0
/algo-trading/
├── README.md
├── requirements.txt
├── core/
│ ├── position_sizing.py
│ ├── portfolio_risk.py
│ ├── strategy_engine.py
│ └── backtest_engine.py
├── data/
│ ├── market_analyzer.py
│ ├── data_fetcher.py
│ ├── groww_connector.py
│ └── live_data.py
├── execution/
│ ├── broker_angelone.py
│ ├── advanced_orders.py
│ └── trading_system.py
├── analytics/
│ ├── backtest_engine.py
│ └── stocks.py
├── tests/
│ └── test_system.py
└── docs/
└── architecture.md
Edit broker_angelone.py:
# Angel One SmartAPI credentials
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
USERNAME = "your_username"
PASSWORD = "your_password"Edit trading_system.py:
class TradeConfig:
capital = 5000 # Starting capital
paper_mode = True # Paper trading
max_position_size = 10 # Max lots per trade
min_confidence = 60 # Minimum signal confidenceEdit position_sizing.py:
class PositionConfig:
max_risk_percent = 2.0 # % risk per trade
max_daily_risk_percent = 6.0 # Max daily loss
max_position_size = 10 # Max lots
min_trade_size = 1 # Minimum lotyfinance is intended for historical data analysis only, not live execution.
- Historical data may have 15-60 minute delay
- Rate limits and throttling apply
- Unadjusted mid-day splits possible
For live trading, use:
- Angel One WebSocket (SmartAPI)
- Groww REST API
- Direct broker connectivity
Backtest results do not reflect actual transaction costs:
| Cost Type | Approximate Rate |
|---|---|
| Brokerage | Rs.20-50 per order |
| STT (Securities Transfer Tax) | 0.1% on sell side |
| Sebi Charges | Rs.15-20 per crore |
| Stamp Duty | 0.01% (Rs.10 per Rs.1 lakh) |
| GST | 18% on brokerage |
Example: With Rs.10,000 capital and 20 trades:
- Gross P&L: +Rs.91.84
- Fees: ~Rs.400 (20 × Rs.20)
- Net: -Rs.308.16
Always simulate realistic fees in backtests.
The system implements 15+ indicators. When combining multiple indicators, curve-fitting to historical data is a significant risk.
Recommendation: Use maximum 3-4 core indicators:
- EMA(21) - Trend direction
- RSI(14) - Momentum (overbought/oversold)
- VWAP - Fair value / support
Minimum recommended capital: Rs.5,000
For smaller capital (Rs.100-500):
- Higher fee drag as percentage
- Limited stock selection
- Higher slippage impact
- May not be economically viable
This system is designed for:
- Trending markets (best performance)
- Liquid large-cap stocks (Nifty 50, Nifty 100)
In sideways markets or with illiquid stocks, performance will degrade significantly.
Past backtest performance does not guarantee future results. Markets change, and patterns that worked historically may not work tomorrow.
Always:
- Paper trade before live capital
- Monitor live performance against backtest
- Implement proper risk controls
- Stop trading if drawdown exceeds 6%
This software is for educational purposes only. Trading in financial markets involves substantial risk, including total loss of capital.
- Paper trade first - Verify system works with simulated trading
- Start small - Use minimum capital (Rs.5,000) initially
- Monitor closely - Compare live vs backtest performance
- Risk controls - Never override stop-loss or daily loss limits
The authors and contributors assume no liability for any losses incurred through the use of this software.
MIT License - See LICENSE file for details.
Built with institutional standards for algorithmic trading. For questions, contributions, or issues, please open a GitHub issue.

