How to Build an "AI" That Trades Nifty Options - A Technical Guide
A practical breakdown of running an LLM-driven Nifty options trader — costs, architecture, edge cases, and where the "autonomous" part actually breaks.
In this blog we will see what are the technical requirements of setting up a system that trades autonomously on the Indian stock market. It does not cover the emotional actions or any human-driven behavior that will affect the system.
The Stack
| Component | Monthly Cost |
|---|---|
| Zerodha Kite Connect API | ₹500 (~$5) |
| Bare metal cloud instance with India region (optional) | ~$6 (Hetzner / Vultr) |
| LLM — DeepSeek, Claude, or GPT-4 | $5–$20 depending on usage |
| Total | ~₹2,500–₹3,000 |
The cloud instance is optional as the system runs fine from a laptop. It matters only for cron-based execution when the machine is asleep. The LLM cost is the variable: it scales with how many strategy sessions you run and how large the context windows get.
Architecture: Two Files, One Loop
strategy.md — roughly 1000 lines of trading rules, written as a system prompt for the AI.
It defines the tradable universe (Nifty 50 F&O stocks + index options, tiered by liquidity and budget), entry gates, exit logic, and a growing list of edge-case rules surfaced from live trading. Every instruction is a call to a Kite MCP tool.
strategy_runner.py — roughly 1,000 lines of Python. The coded version of the same rules. Written and maintained by the AI alongside every strategy change. Can be invoked directly via python3 strategy_runner.py or by the AI itself. Single-shot execution as completes its entire scan-and-decide loop in under a second.
The AI is invoked every 5 minutes (via cron on cloud, or manually from a terminal). Each invocation is stateless. It polls positions, checks margins, scans the market, and acts. No in-memory state between runs.
The MCP Gap: Read vs Execute
Kite offers a free MCP server that exposes market data — positions, orders, quotes, LTP, OHLC, instrument metadata. But it deliberately does not expose execution endpoints. You can read everything. You cannot place, modify, or cancel orders through the standard Kite MCP.
This is by design. Zerodha does not want an off-the-shelf MCP server to be a one-click gateway for autonomous order placement. It is a safety boundary.
To close the loop, you have two options:
Option A: Separate execution layer. The AI reads everything through the Kite MCP (following strategy.md), then hands off to strategy_runner.py for order placement. The Python script uses kiteconnect directly which has full read/write access including the feature to place buys, set limit sells, ratchet, and force-close. The AI instructs, Python executes. This is the setup described here.
Option B: Custom MCP with both baked in. Build your own MCP server that wraps kiteconnect and exposes both read and execute tools (place_order, cancel_order, modify_order) alongside the standard read tools. The AI can then call everything through a single interface without switching contexts. More work upfront, but a cleaner single-agent loop.
Either way, the AI is the decision engine. The execution path is just a transport concern.

What the AI Does — Step by Step
When the AI runs :
- Auth check — reads
access_token.txt, verifies the date matches today, initializes the Kite session. - Position audit — polls open MIS positions and pending orders. For each open position: checks whether the limit-sell exit has filled, runs technical-exit checks (MTF reversal + broader market confirmation), applies the ratchet rule if LTP has crossed +5%.
- Capital gate — reads available margin, subtracts deployed capital across all open positions. If less than X amount remains of the Y budget, skip new entries.
- Universe pre-filter — drops underlyings where one lot cannot fit the remaining budget at realistic ATM premiums, before wasting API calls on OHLC or option chains.
- OHLC scan — batched call across the filtered universe. Pulls last price, open, high, low, close for every candidate.
- Signal gates (sequential, each candidate eliminated on first failure):
- Momentum thresholds and direction bias
- Multi-timeframe alignment across multiple intervals with exhaustion and wick-rejection checks
- Reversal-pattern filters (e.g. false breakout detection)
- Time-of-day gate (no late-session entries)
- Contract selection — resolves the correct weekly/monthly expiry for the series, finds the ATM strike, walks OTM up to 20 strikes until a contract fits the budget. Filters out options with LTP < ₹5 (wide spreads) and those near upper circuit (no sellers).
- Execute buy — LIMIT order at current LTP (rounded to tick). Confirms fill within 1 second.
- Place exit — immediately after fill confirmation, places a LIMIT SELL at entry × 1.10 (rounded to tick). This resting order is the primary exit path.
- Ratchet — when the position reaches a partial-profit threshold, the limit sell is adjusted to lock in a minimum gain. This ensures a winning trade doesn't reverse into a loss while still leaving room for the original target.
- Technical exit (triggered on subsequent runs) — if MTF signals flip against the position (≥2/3 timeframes adverse + ≥3 of 7 broader-market stocks confirming), cancel the limit sell and market-exit immediately.
- 3 PM force-close — cancel all pending sell orders, market-close every open MIS position. No overnight holds.
The exit hierarchy is: technical exit > ratchet > limit sell at +10% > 3 PM force-close. A position is never held without a plan to close it.
Where Autonomy Breaks
Daily Manual Auth
Kite Connect does not support persistent OAuth. Access tokens expire daily. Every morning, you must manually log in through a browser, authorize the app, and save a fresh token. The AI checks the token date and refuses to start with a stale one.
This cannot be automated under SEBI regulations. It is a hard constraint.
Manual Intervention
Every automated strategy has exit rules: profit targets, stop losses, time-based force-closes. The AI follows these rules rigorously. But markets produce conditions that no pre-written rule anticipates, for example; a sudden macro event, an unusual order book imbalance, a regime shift mid-session. When that happens, the human operator steps in and exits manually.
That intervention then gets formalized into a new rule. The next time those conditions appear, the AI handles them. The strategy gets sharper.
Strategy Evolution: Edge Cases Discovered in Production
The current strategy.md is not the first version. It is the result of iterating through failures that the initial specification did not address. Examples:
- BANKNIFTY weekly series disappeared. SEBI discontinued weekly BANKNIFTY options. The AI was attempting to trade a series with no liquidity. Rule added: check series availability dynamically, skip if no active weekly contract.
- FINNIFTY ATM premiums routinely exceed the Y budget. The monthly ATM contract costs 2Y. Rule added: pre-filter FINNIFTY out unless the budget gate passes it explicitly.
- Upper circuit locks. On volatile days, option contracts hit the upper circuit with no sellers. Buy orders sit unfilled indefinitely. Rule added: check
upper_circuit_limitfrom instrument metadata before every buy — skip if LTP ≥ 95% of circuit. - Dead-cat bounce entries. A sharp reversal candle followed by a partial recovery was being read as a new trend. Positions entered, then the prior trend resumed — losses. Rule added: cumulative recovery filter across subsequent candles — if recovery exceeds 50% of the reversal body, skip the signal.
- SEBI lot-size revisions. Lot sizes changed for AXISBANK (1200 → 625) and others. Hardcoded lot sizes broke the budget calculation. Rule added: read
lot_sizefrom live instrument metadata, never hardcode it. - Proximity exhaustion. Entries near intraday highs (for calls) or lows (for puts) had poor risk/reward. Rule added: skip signals where LTP is within 0.5% of the session extreme in the trade direction.
Each rule was added because the AI lost money without it. The LLM does not predict these — the trade log reveals them, and the LLM helps formalize the fix into strategy.md and the corresponding Python.
The LLM Has Two Roles
The same LLM serves both execution and refinement:
1. Execution — it is the trader. During the trading session, the AI receives strategy.md as its system prompt and follows it step by step: log in, poll positions, scan OHLC, evaluate signals, select contracts, place buy orders, set exit orders, ratchet, force-close. The AI opens positions. The AI closes them. The human is not placing orders — the AI is.
2. Refinement — it improves the strategy. After the session, the trade log is reviewed. Patterns are identified — entries that should not have fired, exits that fired too late, contracts that should have been skipped. The LLM receives the current strategy.md, the day's log, and a prompt: "Here's what happened. Find the gaps. Propose rule changes." Once the change is agreed, the LLM translates it into a Python diff against strategy_runner.py. The diff is reviewed, tested with --dry-run, and deployed.
Both roles use the same model. The same AI that trades during the day also reviews the log at night and rewrites the rules. The strategy gets sharper with every session.
Disclaimer: This article is for informational and educational purposes only. It does not constitute financial advice, investment advice, trading advice, or any other type of advice. Trading in options involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. You should consult with a qualified financial advisor before making any trading decisions. The author is not a registered investment advisor and bears no responsibility for any trading losses incurred based on the information provided.