Building an Autonomous AI Quantitative Trading System for Indian Equities (NSE & Groww)
Most algorithmic trading tutorials online stop at simple moving average crossovers backtested on cherry-picked data. When you transition from Jupyter notebooks to the real Indian equity market, you hit immediate roadblocks: daily broker token resets at 6:00 AM, SEBI regulations, non-trivial execution slippage, statutory transaction costs (STT, GST, stamp duty, SEBI turnover fees), and the psychological challenge of letting software place live orders.
This weekend, we built and deployed an end-to-end, production-grade Autonomous Quantitative Trading System designed specifically for the National Stock Exchange of India (NSE). It combines disciplined quantitative momentum screening, a multi-provider LLM brain (Claude 3.5 Sonnet, DeepSeek Reasoner, OpenAI, Gemini) for macro thesis formulation, autonomous daily TOTP broker authentication on Groww, strict Cash & Carry (CNC) delivery execution, and a live web terminal with an instantaneous circuit breaker.
In this guide, we outline the complete architectural blueprint, link to the open-source GitHub repository with the complete sanitized codebase, walk through the core engines, and explain how to adapt or remove the built-in ethical/Shariah screening module for general stock universes.
System Architecture Overview
The system is designed with a strict separation of concerns across four sequential layers to guarantee capital preservation and prevent model hallucination from triggering unintended trades:
- Stage 1: Algorithmic Pre-Screening: Filters the raw 500-stock universe down to candidates exhibiting strong balance sheets, breakout price action (20-day high breakouts above the 50-day SMA), healthy RSI momentum, and volume expansion before consuming any AI tokens.
- Stage 2: Synthetic Intelligence (The AI Brain): A multi-LLM evaluation engine that synthesizes technical charts, quarterly earnings momentum (QoQ/YoY profit growth), and corporate news into a structured thesis with a conviction score (1.0 to 10.0 scale). Trades execute only when confidence exceeds 8.0/10.
- Stage 3: Autonomous Live Broker Execution: An official Groww API client featuring automatic daily 6:00 AM IST TOTP token generation (via
pyotp) to bypass manual morning logins, strictly forcing delivery-only orders (no margin, no intraday, no shorting). - Stage 4: Real-Time Risk & Web Terminal: A dedicated FastAPI/ASGI dark-mode dashboard displaying live P&L, position heatmaps, trade logs, and an unconditional Emergency Kill Switch.

Core Engine 1: Multi-LLM Reasoning & Conviction Scoring
Rather than relying solely on lagging technical indicators, the trading engine uses an LLM-powered synthetic brain. It converts quantitative stock data, quarterly financials, and market regime metrics into a strict JSON contract:
{
"scan_timestamp": "2026-11-08 12:20 IST",
"provider": "claude",
"model": "claude-3-5-sonnet-latest",
"market_regime": "bullish",
"verdict": "EXECUTE",
"selected_trade": {
"symbol": "SHYAMMETL",
"action": "BUY",
"current_price": 1300.6,
"target_price": 1404.65,
"target_pct": 0.08,
"stop_loss": 1248.58,
"stop_pct": 0.04,
"max_hold_days": 10,
"confidence_score": 8.8,
"thesis": "Multi-week consolidation breakout above 50 SMA with positive momentum and clean debt-free balance sheet.",
"catalysts": ["Metals sector tailwinds", "Q2 margin expansion"],
"risks": ["General market gap-down risk"]
}
}
The system supports plug-and-play providers (Anthropic Claude, DeepSeek, OpenAI, Google Gemini) controlled entirely via environment variables, requiring zero core code modifications.
Core Engine 2: Autonomous Morning 6:00 AM TOTP Broker Refresh
Under SEBI regulations, Indian brokers invalidate API access tokens daily around 06:00 AM IST. Most retail trading bots require the user to wake up before 9:00 AM, log into a portal, solve a CAPTCHA, and paste a bearer token into a config file.
Our Groww adapter solves this autonomously using programmatic Time-based One-Time Passwords (TOTP):
import pyotp
import requests
def get_valid_groww_token(api_key: str, totp_secret: str, cached_token_data: dict) -> str:
"""Refreshes Groww token automatically if older than today's 6:00 AM IST reset window."""
if is_token_fresh(cached_token_data):
return cached_token_data["access_token"]
# Generate fresh 6-digit TOTP
totp = pyotp.TOTP(totp_secret)
current_otp = totp.now()
# Request fresh 24-hour token from Groww authentication endpoint
response = requests.post(
"https://api.groww.in/v1/auth/token",
headers={"X-API-KEY": api_key},
json={"totp": current_otp}
)
response.raise_for_status()
token = response.json()["access_token"]
save_token_cache(token)
return token
Whenever the scheduler triggers before market open, the client checks the token age. If expired, it silently derives the current TOTP token, negotiates a new session, and continues execution seamlessly.
Core Engine 3: Emergency Circuit Breaker (Kill Switch)
In automated trading, the ability to stop is more critical than the ability to execute. The system incorporates an independent, stateful Kill Switch layer:
- Instant Web Toggle: Clicking the red “Emergency Kill Switch” button on the dashboard immediately writes a hardware-level lock to
data/kill_switch.json. - Order Veto: Every order route (whether paper rebalance or live broker buy) reads the lock file milliseconds before transmission. If active, execution is blocked and logged.
- CLI Override: Can be triggered or reset from any terminal session via
agent kill-switch --triggeroragent kill-switch --reset.
How to Remove or Customize the Shariah Screening Module
By default, our system runs an AAOIFI-compliant Shariah screening engine that filters out non-compliant business sectors (conventional banking, alcohol, gambling, tobacco, defence) and enforces financial ratio thresholds (Debt/Market Cap < 33%, Cash & Interest Securities/Market Cap < 33%, Interest Income/Total Income < 5%).
If you are a conventional quantitative trader who wants to trade the entire Nifty 500, S&P 500, or any custom equity list without these ethical constraints, you can disable or bypass the filter in three simple steps:
1. Disable the Screening Guard in shariah.py
In src/agent/shariah.py, locate the screen_universe function and simply mark all stocks as compliant:
def screen_universe(fundamentals: pd.DataFrame, thresholds: Thresholds, excluded_symbols: Iterable[str] = ()) -> pd.DataFrame:
"""Bypassed mode: Passes all stocks in the universe directly to the strategy."""
df = fundamentals.copy()
df["compliant"] = True
df["reasons"] = ""
df["impure_ratio"] = 0.0
return df
2. Point config.yaml to a Standard Index List
In config.yaml, update your universe source to point to a plain Nifty 500 or market-cap CSV instead of the screened subset:
universe:
nse_list_csv: data/nifty500.csv # All 500 constituents
fundamentals_csv: data/fundamentals.csv # Yahoo Finance fundamentals cache
screen_report_csv: data/screen_report.csv
prices_cache_csv: data/prices_cache.csv
excluded_symbols: [] # Optional: add any tickers you want to skip
3. Relax the AI Brain Veto in ai_brain.py
In src/agent/ai_brain.py, locate the validate_ai_decision function and remove the compliance veto check:
# Comment out or remove this block:
# if not is_shariah_compliant(symbol, screen_report):
# decision["verdict"] = "VETO"
# decision["decision_summary"] = f"VETOED: {symbol} is not certified compliant."
Once these three adjustments are made, your system will rank, analyze, and trade across the entire universe purely based on quantitative momentum, volume profile, quarterly earnings, and AI conviction score.
Open-Source GitHub Repository
The entire production-ready codebase—including all 23 Python modules, Docker setup, sample seed data, and CLI tools—is open-source and available on GitHub, completely sanitized with all personal identification data and private API keys removed:
⭐ View & Fork on GitHub: alvikashif/autonomous-trading-agent
Quickstart: Cloning & Running Locally
- Clone the repository and create a Python virtual environment:
git clone https://github.com/alvikashif/autonomous-trading-agent.git cd autonomous-trading-agent python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate pip install -e ".[dev]" - Copy
.env.exampleto.envand configure your preferred AI provider:AI_PROVIDER=claude ANTHROPIC_API_KEY=your_key_here AI_MIN_CONFIDENCE=8.0 - Launch the web dashboard:
agent dashboard --port 8765 - Run a paper simulation test:
agent paper-run --dry-run
Summary
Building this system proved that institutional-grade quantitative workflows—from automated morning broker handshakes to LLM-assisted multi-factor reasoning—are now completely accessible for individual developers running low-cost cloud servers or local homelabs. Start in paper mode, test your risk parameters thoroughly, and let the software handle the discipline.