Market mechanics for code-first traders in India

Market mechanics for code-first traders in India

07 Aug 2026 13 mins read

Indian markets are not one continuous stream of prices. Cash equities, optional T+0 trades, opening and closing auctions, index futures and index options follow different clocks, contract rules and settlement processes. Trading code must understand sessions, order behaviour, lot metadata, expiries and official closing prices before it can interpret a signal or place an order safely.

That sounds abstract until a backtest makes a very ordinary mistake. It treats the 3:30 pm print as every stock’s close, uses today’s Nifty lot size for a trade from two years ago, or marks an order as filled the instant an API accepts it. The strategy may look fine in a notebook, but the market it simulated never existed.

This guide builds the practical layer between a trading idea and an exchange. It assumes you already understand the difference between algorithmic, systematic and automated trading; if not, start with Algorithmic Trading in India. The aim here is narrower: to show what a code-first trader must model about an NSE trading day, an order, a derivative contract and the eventual settlement of a trade.

Start with the clock: an NSE day has several market states

The shorthand 09:15 → 15:30 is useful for a quick glance at the cash market, but it is not a sufficient model for software. Before and after continuous trading, different rules determine which orders are accepted, how prices are discovered and which events count as a trade.

For a simplified view, think of the day as a state machine:

PRE-OPEN → CONTINUOUS (optional T+0 path) → CLOSE / AUCTION → POST-CLOSE

The state is part of the meaning of every tick. A price received during an auction is not interchangeable with a price received from the regular order book.

The opening is an auction, not simply the first tick

NSE’s regular pre-open session runs from 9:00 am to 9:15 am. During order collection, participants can enter, modify and cancel orders. The collection period closes at a system-driven random point between the seventh and eighth minute; matching and a transition period follow before normal trading begins. The opening price is therefore an auction result, not necessarily the first trade your broker’s WebSocket happens to deliver after 9:15 am (1).

That matters when a data feed reconnects just after the open. If your programme missed the auction message and only sees the first continuous-market trade, it should record the gap rather than quietly labelling that trade as the official open.

The closing auction changed what “market close” means

NSE’s general timetable places the normal cash-market close at 3:30 pm, the optional T+0 close at 1:30 pm and the equity-derivatives close at 3:40 pm. But from 3 August 2026, phase-one cash securities with listed derivative contracts have a Closing Auction Session (CAS). For those securities, continuous trading ends at 3:15 pm and the closing-auction process runs until 3:35 pm. Cash securities outside CAS continue in the normal continuous market until 3:30 pm (2, 3).

The CAS is not just an extra twenty minutes on the normal order book. NSE forms a reference price from the volume-weighted average of trades between 3:00 pm and 3:15 pm. The auction then moves through a reference-price and transition window, order collection, and matching and confirmation. The equilibrium price is chosen by executable quantity first, then by imbalance and proximity to the reference price. During the latter part of order collection, market-order entry, modification and cancellation are restricted; stop-loss and iceberg orders are not permitted in CAS.

After matching ends at 3:35 pm, NSE records a separate transition period from 3:35 pm to 3:50 pm and a post-close session from 3:50 pm to 4:00 pm. Neither window should be replayed as ordinary continuous-book trading.

NSE session states do not share one closing event. Timings checked 5 August 2026; this is a DailyBulls rendering of NSE-published timings.

For a backtest or execution service, the practical consequences are straightforward:

  • the last continuous-market trade may not be the official CAS closing price;
  • a 3:30 pm snapshot describes different states for CAS and non-CAS securities;
  • a CAS fill should not be simulated as an ordinary market-order fill;
  • daily bars need an explicit rule for which close they represent;
  • “five minutes before close” is incomplete unless the instrument and session are known.

Store a session_label beside each event. Labels such as PREOPEN, CONTINUOUS, T0, CAS_REFERENCE, CAS_ORDER_ENTRY, CAS_MATCH, CAS_TRANSITION, DERIVATIVES and POST_CLOSE are more useful than asking a timestamp to carry all that meaning by itself.

An order is an intention, not a fill

Suppose a strategy detects a breakout and sends a buy order. At that moment, the strategy has expressed an intention. It has not bought anything. The broker may accept the request, the exchange may acknowledge it, the order may wait behind earlier orders, and only part of the quantity may eventually execute.

In the regular continuous order book, NSE applies price-time priority. A more competitive price comes first; orders at the same price are ranked by the time the exchange received them. The best bid is the highest available buy price and the best offer is the lowest available sell price. One order can match against several resting orders and produce several fills (4).

A robust trade record therefore separates at least these events:

  1. the strategy signal;
  2. the broker instruction;
  3. exchange acknowledgement;
  4. the open quantity;
  5. each fill and its price;
  6. cancellation, rejection or expiry;
  7. the resulting position and settlement status.

The distinction is not academic. A limit order for 300 shares may fill 120 and leave 180 resting. An IOC order may fill 120 and cancel the remainder. A market order may sweep several price levels. If your ledger stores only order_sent = position_created, it will overstate fill quality and understate execution risk.

Price, time and quantity conditions answer different questions

“Order type” is often used as if it were one property, but an exchange instruction combines several conditions.

DAY keeps an unmatched quantity active for the trading day. Any remainder is cancelled when the exchange ends that day’s session; your code should rely on the confirmed exchange or broker status rather than a guessed local cron time.

IOC (Immediate or Cancel) attempts to execute as soon as it reaches the book. It can partially fill. IOC does not mean all-or-nothing.

A limit order sets the worst acceptable price: a buy limit is a maximum and a sell limit is a minimum. It gives price control, not execution certainty. A favourable-looking price can still have a long queue ahead of it.

A market order seeks the best available prices when it reaches the book. It does not promise the last traded price, the chart midpoint or the price visible before transmission. Thin depth, latency and intervening orders can move the average fill.

A stop-loss order remains inactive until its trigger condition is reached, after which it is released into the relevant book. A sell stop normally activates when LTP reaches or falls below its trigger; a buy stop activates when LTP reaches or rises above it. A stop-limit can trigger without filling if the market moves through the limit.

Disclosed quantity shows only part of a larger order. As the displayed portion trades, further quantity is released, subject to exchange conditions.

Time conditions such as DAY and IOC should not be confused with price conditions such as limit or market. NSE’s trading-system documentation also describes GTC and GTD, while noting that they are not currently available on the exchange system.

Broker features are not automatically NSE order types

An API may offer an after-market order, GTT instruction, iceberg interface, cover order or a product-specific stop-market label. That is a broker-layer facility, not necessarily an exchange-native order type. The broker might hold the instruction and release a different exchange order later.

Keep both values in your audit log:

broker_instruction_type
exchange_order_type

The same discipline applies to auctions. During CAS, an order valid in the continuous book can be invalid in the auction. Your simulator should branch on session_label before validating an order, not after it has pretended to fill one.

A lot is a unit of contract, not a measure of risk

Cash equities commonly trade in a one-share market lot. Index derivatives work differently: the exchange defines how many index units one contract contains. That means quantity = 1 is ambiguous. It might mean one lot, one index unit, or a broker quantity already expanded into units.

Prefer explicit fields such as:

Fields
exchange, segment, market_type, settlement_type
instrument_type, underlying_symbol, contract_symbol
event_timestamp_ist, trade_date, session_label
expiry_date, settlement_date, strike_price, option_type
lot_size, tick_size, quantity_freeze
best_bid, best_ask, last_traded_price, official_close
reference_file_date

number_of_lots, units_per_lot, exchange_quantity
index_level, notional_value, option_premium

NSE’s October 2025 revision established the following lots for contracts in the 2026 cycle:

UnderlyingSymbolUnits per lot
Nifty 50NIFTY65
Nifty BankBANKNIFTY30
Nifty Financial ServicesFINNIFTY60
Nifty Midcap SelectMIDCPNIFTY120
Nifty Next 50NIFTYNXT5025

These are a dated snapshot, not permission to hard-code constants forever. Load the current NSE FO contract master and attach its effective date to every backtest row and order. The applicable lot size and quantity-freeze limits can change (5, 6).

Notional value, premium and margin are different numbers

For an index future:

notional contract value = futures price × units per lot × number of lots

If Nifty futures were at 25,000 and one lot contained 65 units, the notional value would be ₹16,25,000. That is the exposure represented by the contract, not the cash margin a broker may require.

For an option purchase:

premium paid = option premium × units per lot × number of lots

Premium paid is not the same as underlying notional exposure. A risk model that calls either value “the position size” without qualification is mixing different concepts. Brokerage, taxes and exchange charges have their own bases; Indian trading-cost maths belongs in a separate calculation.

Tick size is another field, not a substitute for lot size. NSE currently specifies index-futures price steps of ₹0.05 below 15,000, ₹0.10 from above 15,000 to 30,000, and ₹0.20 above 30,000. Index options use a ₹0.05 price step. Quantity freeze answers a different question: how large an order may be before exchange-side freeze or confirmation treatment applies.

Nifty, Bank Nifty and FinNifty are different portfolios

These indices are often discussed as if they were simply three volatility settings. Their underlying portfolios and methodologies are different, so a signal tested on one should not be assumed to transfer to another.

Nifty 50 contains 50 companies and uses free-float market capitalisation. It is a broad large-company benchmark (7).

Nifty Bank is a concentrated basket of large and liquid banking stocks; its July 2026 factsheet lists a maximum of 14 constituents and a capped free-float methodology (8).

Nifty Financial Services (FinNifty) is broader than banking. Its 20-stock universe includes banks, financial institutions, housing-finance companies, insurers and other financial-services businesses (9).

When a backtest names an index, record the official symbol, the methodology, the constituent set effective on that date, the rebalancing date and whether the series is price return or total return. “Nifty” without that context is not a reproducible instrument definition.

Expiry calendars belong in reference data

NSE currently lists three consecutive monthly futures for Nifty 50, Nifty Bank and FinNifty. Option availability differs: Nifty 50 has weekly and monthly series under the current schedule, while Bank Nifty and FinNifty have their own monthly and quarterly or monthly arrangements. NSE uses Tuesday as the relevant expiry day; if Tuesday is a trading holiday, expiry moves to the previous trading day (6).

Do not recreate expiry with a generic function such as:

last_thursday(year, month)

That rule belongs to a different period. Lot sizes, weekly availability and expiry conventions have changed over time, so historical tests need the rules that applied on each historical date. Store an exact expiry_date, plus contract_version_date, rather than deriving an old contract from today’s calendar.

Settlement is part of the strategy clock

The timestamp of a fill tells you when a trade occurred. Settlement tells you when obligations and cash flows are completed. A strategy ledger needs both.

Normal cash-market trades follow a T+1 rolling settlement cycle. T+1 means the next applicable settlement day after weekends, bank holidays and exchange holidays are excluded; it does not always mean the next calendar date. Failed delivery can lead to a buy-in auction and a later settlement event (10).

An optional T+0 cycle operates alongside T+1 for eligible securities and participating members. T+0 closes at 1:30 pm and settles on trade day, but eligibility must be read from the current exchange and member lists rather than inferred from a stock symbol (11).

Index futures are marked to market daily. NSE Clearing calculates profit or loss against the daily settlement price and resets the open position to that price; the associated pay-in or pay-out normally occurs on T+1. At expiry, the final profit or loss is settled in cash.

Index options are European style and cash settled under current clearing rules. Individual-stock derivatives have different expiry and delivery implications, so do not apply index-option settlement logic to them (12).

India VIX measures expected magnitude, not direction

India VIX is derived from Nifty option prices and expresses the option market’s expected volatility over the next 30 calendar days as an annualised percentage. A higher value means a larger magnitude of movement is being priced; it does not say whether Nifty is expected to rise or fall (13).

NSE’s calculation uses bid and ask quotes from out-of-the-money near- and mid-month Nifty options, a forward Nifty level, a relevant-tenure MIBOR rate, time to expiry measured in minutes and interpolation to a constant 30-day maturity. The square root of the resulting variance, multiplied by 100, gives the index value (14).

So “India VIX is 20” is not a forecast that Nifty will fall 20 per cent. Nor does it guarantee a realised range. Converting an annualised implied-volatility number into a daily range requires an approximation and assumptions about the distribution of returns. Reconstructing an intraday value also requires contemporaneous quote-level data and the relevant futures and interest-rate inputs; an end-of-day option-chain screenshot is not enough.

The small metadata layer that keeps a backtest honest

You do not need a giant data warehouse to begin, but you do need enough context to prevent unlike events being joined together. A sensible minimum record might look like this:

Fields
exchange, segment, market_type, settlement_type
instrument_type, underlying_symbol, contract_symbol
event_timestamp_ist, trade_date, session_label
expiry_date, settlement_date, strike_price, option_type
lot_size, tick_size, quantity_freeze
best_bid, best_ask, last_traded_price, official_close
reference_file_date

The fields solve concrete errors: joining spot and futures under one symbol, using today’s lot size for a historical trade, treating LTP as an executable quote, mistaking a pre-open event for a continuous fill, or confusing trade date with settlement date. Keep the raw exchange or vendor reference date alongside the normalised field so a later audit can explain where each value came from.

A practical pre-flight check before coding a strategy

Before trusting a signal, ask:

  • Which exchange segment and instrument does this row represent?
  • Was the event pre-open, continuous, T+0, CAS, post-close or derivatives?
  • Does the contract master for that date give the same lot, tick and freeze values?
  • Is the quoted price LTP, bid, ask, auction equilibrium or an official close?
  • Does an order quantity mean units or lots, and what is the resulting notional?
  • Which order state confirms a fill, and how are partial fills represented?
  • What is the settlement date and settlement type?
  • If India VIX is included, are you using it as a magnitude measure rather than a direction signal?

These questions do not create a trading edge. They stop the code from claiming an edge that came from mismatched clocks, stale contract metadata or imaginary fills.

The market model comes before the strategy model

A moving-average crossover, breakout or mean-reversion rule is only the top layer. Underneath it sits a market-state model: the session that produced the price, the order book that could accept the instruction, the contract version that defines its units, and the settlement cycle that completes the trade.

Once those objects are explicit, the next question is mathematical rather than mechanical: how often does the strategy win, how large are its wins and losses, and does the expected value survive costs?

Source note: Exchange timings, CAS rules, contract values, index descriptions and settlement claims were checked against NSE, NSE Indices and NSE Clearing material on 5 August 2026. Recheck current exchange files before live use; this article is educational, not a live reference or trading recommendation.

Sources

1. NSE — Equity Market Pre-Open

2. NSE — Market Timings

3. NSE — Closing Auction Session

4. NSE — Equity Market Trading System

5. NSE — FAOP70616 lot-size circular

6. NSE — Equity Derivatives Contract Specifications

7. NSE Indices — Nifty 50 factsheet

8. NSE Indices — Nifty Bank factsheet

9. NSE Indices — Nifty Financial Services factsheet

10. NSE Clearing — Capital-market settlement cycle

11. NSE Clearing — T+0 settlement cycle

12. NSE Clearing — Equity-derivatives settlement mechanism

13. NSE — India VIX

14. NSE — India VIX computation methodology

About the author

Pranay

Senior Researcher and Editor

Pranay is the co-founder of DailyBulls.in, a trader-focused market research and learning platform, and OIHelper.com, a platform focused on open interest analysis. He has 5+ years of experience following Indian markets, with core interests in technical analysis, stock screeners, open interest analysis, and structured research workflows.He is also a coder and spends much of his time building custom stock screeners, research tools, and AI-assisted workflows that help organize market data, improve research efficiency, and make technical learning more practical for traders and market learners. Through DailyBulls.in, he shares educational content, research-driven articles, and workflow ideas built around technical analysis, market behavior, and data-backed learning.His work has also been referenced in academic publishing, including an MDPI-published paper in the Journal of Risk and Financial Management.

Share this insight

Spread the Alpha

If this analysis helped you, pass it along to your trading desk or community.

Leave a Comment