QuantLab is a professional-grade quantitative trading platform built for Indian equity markets. It connects to Angel One SmartAPI for real historical data, runs sandboxed Python strategies, simulates real Indian market charges (STT, GST, SEBI, Stamp Duty), and visualizes everything through a premium Next.js dashboard with TradingView Lightweight Charts, ECharts, and the Monaco Editor.
Scope: equities only. QuantLab trades cash equities (NSE/BSE delivery and intraday). Options, futures, and the Dhan HQ pipeline have been removed β there is no options strategy builder, no F&O bhavcopy import, and no Dhan integration. Every feature below operates on equity candles.
| Feature | Description |
|---|---|
| Dashboard | System health, connection status, quick backtest launch, and live notifications |
| Datasets | Download real historical equity candles from SmartAPI with From/To date range filtering, async background jobs with progress tracking, universal data aggregator (chunking, merge, dedup, forward-fill), preview with interactive charts, file export (CSV/Excel/Parquet), and symbol group / basket management |
| Strategy Workspace | Monaco Editor with Python templates, dual runtime support (legacy_on_bar / prosperity_trader), symbol/interval/capital configuration, auto max-position sizing from volatility, risk settings, and parameter JSON |
| Backtests & Replay | Event-driven engine with Indian charge simulation, equity/drawdown charts, per-symbol analytics, auto max-position sizing, data coverage validation, and frame-by-frame replay studio with speed controls |
| Live Trading (Mock) | Dedicated /live trading page with real-time market data, manual order placement, live PnL tracking, full charge breakdown, SSE event streaming, pause/resume deployments, reset capital, and deployment event logs |
| Deployments | Paper and live deployment management with status monitoring, pause/resume, capital reset, PnL snapshots, event history, and service-oriented orchestration |
| Research Lab | Deep statistical analysis β returns, volatility, regime detection (HMM), seasonality, strategy-suitability scoring, mean-reversion diagnostics (Hurst, half-life), gap analysis, intraday behavior, volatility structure, tail risk, order-flow proxies, multi-timeframe analysis, factor exposure, walk-forward stability, feature-importance engine, and AI strategy generator |
| Multi-Asset Research | Correlation matrices, pair discovery, cointegration, spread analysis, lead-lag, sector breadth, rolling correlation, and cross-sectional factor ranking with From/To date range filtering |
| Portfolio Risk | Monte Carlo simulation, stress testing, risk-of-ruin, drawdown projections, confidence intervals, and daily PnL heatmaps |
| Optimization Lab | Grid/random search with Sharpe/Sortino/Calmar objectives, walk-forward validation, sensitivity analysis, and 3D surface plots |
| Strategy Registry | Backend market-analysis pipeline that auto-ranks strategies by suitability, runs walk-forward optimization with robustness scoring, overfit detection, and grading profiles |
| System Cleanup | Log and dataset cleanup, database vacuum, and disk usage analytics |
Real Data Only. The platform enforces real downloaded candles for all production backtests. No simulated or mock data is injected into the backtest engine.
QuantLab supports two strategy execution models side by side. You pick one per strategy:
| Runtime | Signature | Returns | Best For |
|---|---|---|---|
| legacy_on_bar | def on_bar(self, state) |
list[dict] |
Quick backtests, single/multi-symbol, candle-based signals |
| prosperity_trader | def run(self, state) |
(orders, conversions, trader_data) |
Order-book-aware strategies, live trading, state persistence |
Both runtimes are sandboxed, charge-aware, and replay-compatible. The engine auto-detects your runtime from the strategy class and selects the correct adapter. See the sample files for a working EMA crossover in each style.
Backtests and live trades support two equity trade modes:
- INTRADAY β squared off within the session; uses a 5Γ intraday margin multiplier and intraday brokerage.
- DELIVERY β carried overnight; full capital margin and delivery brokerage.
Options and futures are not supported.
All symbols are automatically normalized to the canonical NSE:SYMBOL-EQ format across the entire stack:
- Frontend β type
SBIN, it becomesNSE:SBIN-EQbefore sending - Backend β stored as
NSE:SBIN-EQin the database - Engine β catalog lookups, backtests, and live data all use the canonical form
You never need to think about it. Just type the symbol name and everything resolves correctly.
All screenshots were captured live from the running application on localhost:3000.
Datasets β Real Historical Data Catalog

Strategy Workspace β Monaco Editor & Configuration

Optimizer β Grid Search Parameter Sweeps

Deployments β Paper / Live Management

Live Mock Trading (Paper Mode)

System Cleanup β Disk & Database Maintenance

Research Lab β Statistical Diagnostics

Multi-Asset Research β Correlation & Pair Analysis

Portfolio Risk β Monte Carlo Simulation

graph TD
A[Next.js Frontend: Port 3000] -->|REST API / WebSockets / SSE| B[FastAPI Backend: Port 8000]
B -->|Metadata & Run Catalog| C[(SQLite Database: quantlab.db)]
B -->|SmartAPI Client| D[Angel One SmartAPI Gateway]
B -->|Historical Data Download| E[Parquet/CSV/Excel Storage: /datasets]
B -->|Task Trigger| F[Backtest Engine]
F -->|Executes Code| G[Sandboxed Runtime]
G -->|Runs| H[User Strategy: trader.py]
F -->|Transaction Details| I[Execution Simulator]
I -->|Calculates Fees| J[Indian Charges: STT/GST/Stamp Duty]
F -->|Writes Logs| K[Replay Log Generator: /logs]
B -->|Reads Logs| K
B -->|Event Bus| N[EventBus / PersistenceService]
B -->|Market Data| O[MarketDataService: Redis-backed tick/candle cache]
B -->|Deployments| P[DeploymentEngine: Orchestrator per deployment]
| Layer | Technology |
|---|---|
| Frontend | Next.js 16, React 19, Tailwind CSS v4, TypeScript, Monaco Editor, TradingView Lightweight Charts, ECharts, Lucide Icons |
| Backend | FastAPI, Uvicorn, SQLAlchemy, SQLite (WAL mode), Pydantic, WebSockets, SSE, async background jobs, APScheduler |
| Engine | Python 3.10+, NumPy, Pandas, Parquet, sandboxed exec, event-driven loop, universal data aggregator |
| Data | Angel One SmartAPI, TOTP 2FA, CSV/Parquet/Excel storage, Redis-backed tick/candle cache |
| AI/LLM | Ollama integration for strategy assistance, research summarization, and AI strategy generation |
quantp/
βββ backend/ # FastAPI application
β βββ main.py # App entrypoint, lifespan management, router inclusion
β βββ database.py # SQLAlchemy models: StrategyDB, DeploymentDB, BacktestResultDB, DownloadJobDB, etc.
β βββ smartapi.py # SmartAPI client wrapper with TOTP 2FA
β βββ data_loader.py # Data loading utilities
β βββ cleanup_api.py # Cleanup router (logs, datasets, DB vacuum)
β βββ routers/ # API endpoint modules
β β βββ __init__.py # Router aggregation for clean imports
β β βββ auth.py # SmartAPI authentication, TOTP
β β βββ data.py # Dataset download, catalog, search, preview
β β βββ strategies.py # Strategy CRUD
β β βββ backtest.py # Backtest execution, results, replay logs
β β βββ research.py # Research lab, regime, capital analysis, optimization
β β βββ deployments.py # Deployment lifecycle management
β β βββ live_trading.py # Live mock trading, SSE streaming, manual orders
β β βββ groups.py # Symbol group / basket management
β βββ services/ # Core backend services
β βββ data_aggregator.py # Universal data aggregator (chunk, merge, dedup, fill)
β βββ data_service.py # Data service layer
β βββ download_job_service.py # Async download job tracking
β βββ market_data_service.py # Redis-backed tick/candle cache
β βββ market_feed.py # Market feed handler
β βββ smartapi_manager.py # SmartAPI connection manager
β βββ redis_client.py # Redis connection wrapper
β βββ shared_cache.py # In-memory shared cache
β βββ event_bus.py # Pub/sub event bus for deployments
β βββ persistence_service.py # Periodic state persistence
β βββ deployment_engine.py # Central deployment orchestrator manager
β βββ deployment_orchestrator.py # Per-deployment orchestrator
β βββ mock_deployment_engine.py # Legacy mock engine (backwards compat)
β βββ sizing_service.py # Auto position sizing from volatility
β βββ ollama_manager.py # Ollama LLM integration
β βββ pnl_snapshot_scheduler.py # PnL snapshot scheduling
β
βββ engine/ # Core backtest, execution, analytics, and optimization modules
β βββ backtester.py # Event-driven backtesting loop
β βββ execution.py # Order matching and charge calculation (INTRADAY / DELIVERY)
β βββ execution_engine.py # Order execution engine
β βββ analytics.py # Risk metrics and performance attribution
β βββ portfolio.py # Portfolio tracking and sizing
β βββ sizing.py # Position sizing logic
β βββ capital.py # Capital requirements analysis
β βββ order_manager.py # Order lifecycle management
β βββ datamodels.py # Core data models
β βββ market.py # Market data interface and regime detection
β βββ market_interface.py # Unified market data interface
β βββ regime.py # Market regime classification
β βββ quant_analysis.py # Full quantitative analysis engine
β βββ data_analyzer.py # Deep independent dataset statistical analysis
β βββ research.py # Statistical research tools
β βββ research_extras.py # Seasonality, volume profile, S/R detection
β βββ research_multiasset.py # Multi-asset correlation and cointegration
β βββ monte_carlo.py # Portfolio simulation
β βββ optimization.py # Parameter search and walk-forward analysis
β βββ walk_forward.py # Walk-forward optimization
β βββ replay_logger.py # Replay log generation
β βββ runtime/ # Sandboxed strategy execution
β β βββ __init__.py
β β βββ sandbox.py # Sandboxed exec environment
β β βββ adapters.py # Runtime adapters (legacy / prosperity)
β β βββ runtimes.py # Runtime implementations
β β βββ datamodels.py # Runtime data models (Order, State, etc.)
β β βββ strategies.py # Strategy base classes
β β βββ multi_asset_strategy.py # Multi-asset strategy support
β βββ strategy_executor.py # Strategy execution wrapper
β
βββ frontend/ # Next.js 16 client app
β βββ src/app/
β β βββ page.tsx # Main layout with tab router, top nav, sidebar
β β βββ layout.tsx # Root layout
β β βββ globals.css # Global styles + Tailwind v4
β β βββ live/page.tsx # Dedicated live trading page
β β βββ hooks/
β β β βββ useAxon.ts # Central state management hook
β β βββ components/
β β β βββ DailyPnLHeatmap.tsx # Daily PnL heatmap visualization
β β β βββ shared/
β β β β βββ AxonSidebar.tsx # Main sidebar navigation (single-section mapping)
β β β βββ ResearchLab.tsx # Deep statistical research panel
β β β βββ MultiAssetResearch.tsx # Correlation / pair analysis
β β β βββ PortfolioAnalytics.tsx # Monte Carlo / risk analytics
β β β βββ LightweightChart.tsx # TradingView chart wrapper
β β β βββ PnLChart.tsx # PnL visualization
β β β βββ PositionChart.tsx # Position tracking chart
β β β βββ tabs/
β β β βββ DashboardTab.tsx # Dashboard + TOTP modal + error banners
β β β βββ DatasetsTab.tsx # Dataset management, download, preview
β β β βββ StrategiesTab.tsx # Strategy workspace with Monaco
β β β βββ BacktestsTab.tsx # Backtest config, results, replay
β β β βββ DeploymentsTab.tsx # Deployment list and controls
β β β βββ OptimizerTab.tsx # Grid/random search UI
β β β βββ LiveTradingTab.tsx # Live mock trading UI
β β β βββ CleanupTab.tsx # Disk / DB cleanup
β β βββ lib/
β β β βββ api-client.ts # Frontend API client
β β βββ public/ # Static assets
β
βββ datasets/ # Historical candle storage
β βββ csv/ # Symbol-named CSV files
β βββ parquet/ # Efficient columnar storage
β βββ excel/ # Excel exports
β βββ catalog.json # Dataset metadata index
β βββ groups.yaml # Symbol grouping definitions
β βββ symbol_tokens.json # SmartAPI token mapping
β
βββ docs/ # Documentation and extra samples
β βββ screenshots/ # UI screenshots (live captures)
β βββ sample_strategy_legacy.py # EMA crossover sample
β βββ sample_strategy_prosperity.py # Prosperity-style sample
β βββ test_live_trading.py # Live trading test script
β
βββ logs/ # Backtest replay logs (JSONL)
β
βββ strategies/ # Saved strategy configs
β
βββ sample_strategy_legacy.py # EMA crossover β legacy_on_bar runtime
βββ sample_strategy_prosperity.py # EMA crossover β prosperity_trader runtime
βββ test_aggregator.py # Data aggregator unit test
βββ test_live_trading.py # Live trading integration test
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variable template
βββ .env # Local secrets (ignored by Git)
βββ quantlab.db # SQLite database (auto-created, WAL mode)
βββ README.md # This file
- Python 3.10+
- Node.js v18.0.0+
- NPM (packaged with Node.js)
- Git (optional)
- Redis (optional β falls back to in-memory caching)
Create a copy of .env.example and rename it to .env:
copy .env.example .env # Windows
cp .env.example .env # Linux / macOSFill in your Angel One SmartAPI credentials:
SMARTAPI_CLIENT_CODE="YOUR_CLIENT_CODE"
SMARTAPI_PASSWORD="YOUR_PASSWORD"
SMARTAPI_API_KEY="YOUR_API_KEY"
# Optional: network identifiers for SmartAPI headers
# SMARTAPI_CLIENT_LOCAL_IP=127.0.0.1
# SMARTAPI_CLIENT_PUBLIC_IP=127.0.0.1
# SMARTAPI_MAC_ADDRESS=00:00:00:00:00:00
# Optional: Redis
# REDIS_URL=redis://localhost:6379/0
# Optional: custom database
# DATABASE_URL=sqlite:///./quantlab.dbNote: Without credentials, the platform still boots in a basic mode. You can still write and edit strategies, but live data download and mock trading require SmartAPI authentication.
Virtual environment (Windows):
python -m venv .venv
.venv\Scripts\Activate.ps1Virtual environment (Linux / macOS):
python3 -m venv .venv
source .venv/bin/activateInstall dependencies:
python -m pip install --upgrade pip
pip install -r requirements.txtRun the server:
.venv\Scripts\python -m backend.mainThe server starts on http://0.0.0.0:8000 and auto-creates quantlab.db with WAL mode enabled.
Important: Always run with
python -m backend.main, notpython backend/main.py. The module path matters for imports.
cd frontend
npm install
npm run devOpen http://localhost:3000.
pytest tests/Or run a core test directly:
python tests/test_backtest.pyStandalone root-level test scripts:
python test_aggregator.py
python test_live_trading.py- Go to the Datasets tab in the sidebar
- Enter a symbol like
SBINand intervalFIVE_MINUTE - Use the From and To date pickers to select your exact range
- Click Download
- The backend runs the universal data aggregator β it chunks large requests into SmartAPI-safe ranges, merges results, deduplicates, validates coverage, and forward-fills any gaps
- Track progress in real-time; large jobs run in the background and can be cancelled at any time
Symbols are auto-normalized. Type
SBINand it resolves toNSE:SBIN-EQeverywhere.
- Go to Datasets β Groups
- Create a named basket like
BankNiftywith symbolsSBIN,ICICIBANK,HDFCBANK - Use the group in multi-symbol backtests or multi-asset research
- Go to Strategy Workspace
- Copy one of the included samples into the Monaco editor:
sample_strategy_legacy.pyβlegacy_on_barruntimesample_strategy_prosperity.pyβprosperity_traderruntime
- Configure symbols, interval, capital, and max position size
- Enable Auto Max Position to let the engine calculate size from recent volatility
- Click Save
- Go to the Backtests tab
- Select your strategy, use the From/To date range, and configure slippage
- Choose INTRADAY or DELIVERY trade type
- The engine validates data coverage before running β if gaps exist, you get a clear warning
- Click Run
The engine parses your strategy in a sandbox, steps through every candle, executes orders, applies real Indian market charges, and writes a replay log.
- Replay Studio β frame-by-frame playback with speed controls
- Research Lab β regime attribution, performance maps, mean-reversion diagnostics, and AI strategy generation
- Portfolio Risk β Monte Carlo simulations and stress tests
- Go to the Live Trading page (
/live) or the Deployments tab - Create a paper deployment with your strategy
- Pause, resume, or reset capital at any time without restarting
- View the full deployment event log and periodic PnL snapshots for audit trails
The download engine automatically handles large date ranges by:
- Chunking requests into SmartAPI-safe intervals
- Merging and deduplicating overlapping candles
- Validating coverage and warning about gaps before backtests
- Forward-filling missing candles so the engine never sees null data
Real Data Only. The platform enforces real downloaded candles for all production backtests. No simulated or mock data is injected into the backtest engine.
Large downloads run as cancellable background jobs. The UI shows real-time progress, and you can cancel pending jobs without restarting the server.
Create named groups (e.g., BankNifty, ITPack) in datasets/groups.yaml via the Groups API. Use them for multi-symbol backtests, multi-asset correlation studies, and sector-breadth analysis.
When enabled, the engine calculates a suggested max position from recent price volatility and your configured capital. You can override it manually or let the system size every backtest and deployment automatically.
A full market-analysis pipeline that:
- Analyzes current market conditions across all datasets
- Ranks every registered strategy by suitability score
- Runs walk-forward optimization with train/validation/test splits
- Detects overfitting via robustness scoring and sensitivity analysis
- Applies dynamic grading profiles (Balanced, Conservative, Aggressive)
- Enables one-click deployment of the best configuration
Deployments support a full lifecycle via the service-oriented architecture:
- Pause / Resume β freeze a running paper deployment without losing state
- Reset Capital β adjust starting cash/equity mid-run
- PnL Snapshots β periodic portfolio snapshots with position breakdowns
- Event Log β full audit trail of fills, errors, margin calls, and state transitions
- Market Data Service β centralized Redis-backed tick and candle cache shared across all deployments
- Event Bus β pub/sub architecture for real-time deployment events
The Research Lab can auto-generate a complete strategy from quantitative analysis: entry/exit rules, position sizing, holding period, and expected win rate. Generated strategies can be saved to the StrategyDB and backtested in one click.
| File | Description |
|---|---|
sample_strategy_legacy.py |
EMA crossover β legacy_on_bar runtime |
sample_strategy_prosperity.py |
EMA crossover β prosperity_trader runtime |
requirements.txt |
Python dependencies |
.env.example |
SmartAPI, Redis, and database credentials template |
datasets/groups.yaml |
Symbol basket definitions |
datasets/catalog.json |
Dataset metadata index |
PowerShell execution policy error
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUserBackend offline on frontend
Ensure python -m backend.main is running on http://127.0.0.1:8000. If you run the frontend dev server on a port other than 3000, CORS allows localhost / 127.0.0.1 on port 3000β3009. For a custom port, update backend/main.py.
Dataset not found
Download the symbol first in the Datasets tab. Bare symbols like SBIN are auto-resolved to NSE:SBIN-EQ β old records in the database are also canonicalized on read.
Data coverage warning before backtest The engine validates that the requested date range has sufficient downloaded candles. If gaps exist, download the missing range in the Datasets tab, or the backtest will error out rather than use mock data.
Async download job stuck Check the download status in the Datasets tab. Jobs can be cancelled and restarted. Large ranges may take a few minutes due to SmartAPI rate limits.
Strategy sandbox error Check your Python syntax. Ensure your class matches the selected runtime:
- Legacy:
class Strategywithdef on_bar(self, state):returninglist[dict] - Prosperity:
class Traderwithdef run(self, state):returning(orders, conversions, trader_data)
Redis not available
Redis is optional. Without it, the market data service falls back to in-memory caching. For production live-trading loads, start Redis and set REDIS_URL in .env.
Contributions are welcome. Good starting points:
- New strategy templates for the built-in gallery
- Additional chart types or visualizations
- New research and analytics modules
- Bug fixes and performance improvements
- Documentation improvements
This project is open-source and available for personal and research use. Check the repository for the full license text.
Built for Indian equity markets. Powered by real data. No shortcuts.

